- {/* Üst Başlık */}
-
-
+
+ {/* Üst Başlık */}
-
-
-
-
- YakNet Bulut Depolama
-
-
- Tasarımlarınız YakNet hesabınızla otomatik eşitlenir ve tüm cihazlarınızdan güvenle erişilebilir.
-
-
-
-
setModalOpen(false)}
- aria-label="YakNet Bulut penceresini kapat"
- style={{
- background: "#1e293b",
- border: "none",
- color: "#cbd5e1",
- borderRadius: "8px",
- padding: "6px",
- cursor: "pointer",
- }}
- >
-
-
-
-
- {statusBanner ? (
-
- {statusBanner.text}
-
- ) : null}
-
- {/* Kullanıcı Durum Kartı */}
-
-
-
-
-
- {user ? `${user.name} (${user.email})` : "YakNet Oturumu Açık Değil"}
-
-
-
- {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")}` : ""}
-
-
-
-
- {user ? (
- <>
-
{
- if (!syncing) void performCloudSync(false);
- }}
+
+
-
- {syncing ? "Eşitleniyor..." : "Şimdi Eşitle"}
-
- {isDesktop ? (
+
+
+
+
+ YakNet Bulut Depolama
+
+
+ Tasarımlarınız YakNet hesabınızla otomatik eşitlenir ve tüm cihazlarınızdan güvenle erişilebilir.
+
+
+
+ setModalOpen(false)}
+ aria-label="YakNet Bulut penceresini kapat"
+ style={{
+ background: "#1e293b",
+ border: "none",
+ color: "#cbd5e1",
+ borderRadius: "8px",
+ padding: "6px",
+ cursor: "pointer",
+ }}
+ >
+
+
+
+
+ {statusBanner ? (
+
+ {statusBanner.text}
+
+ ) : null}
+
+ {/* Kullanıcı Durum Kartı */}
+
+
+
+
+
+ {user ? `${user.name} (${user.email})` : "YakNet Oturumu Açık Değil"}
+
+
+
+ {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")}` : ""}
+
+
+
+
+ {user ? (
+ <>
+
{
+ if (!syncing) void performCloudSync(false);
+ }}
+ style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: "6px",
+ padding: "8px 14px",
+ borderRadius: "8px",
+ border: "none",
+ background: "#2563eb",
+ color: "#fff",
+ fontWeight: 600,
+ fontSize: "12.5px",
+ cursor: syncing ? "wait" : "pointer",
+ opacity: syncing ? 0.8 : 1,
+ }}
+ >
+
+ {syncing ? "Eşitleniyor..." : "Şimdi Eşitle"}
+
+ {isDesktop ? (
+
void handleSsoLogout(true)}
+ style={{
+ display: "inline-flex",
+ alignItems: "center",
+ gap: "6px",
+ padding: "8px 12px",
+ borderRadius: "8px",
+ border: "none",
+ background: "rgba(239, 68, 68, 0.16)",
+ color: "#fca5a5",
+ fontWeight: 600,
+ fontSize: "12.5px",
+ cursor: "pointer",
+ }}
+ >
+
+ Çıkış Yap
+
+ ) : (
+
+
+ Çıkış Yap
+
+ )}
+ >
+ ) : isDesktop ? (
void handleSsoLogout(true)}
+ data-modal-initial-focus="true"
+ data-modal-focus-key="yaknet-cloud-login-link"
+ disabled={desktopLoginPending}
+ onClick={() => void handleStartDesktopLogin()}
style={{
display: "inline-flex",
alignItems: "center",
- gap: "6px",
- padding: "8px 12px",
- borderRadius: "8px",
+ gap: "7px",
+ padding: "9px 16px",
+ borderRadius: "9px",
border: "none",
- background: "rgba(239, 68, 68, 0.16)",
- color: "#fca5a5",
- fontWeight: 600,
- fontSize: "12.5px",
- cursor: "pointer",
+ background: "linear-gradient(135deg, #2563eb, #1d4ed8)",
+ color: "#fff",
+ fontWeight: 700,
+ fontSize: "13px",
+ cursor: desktopLoginPending ? "wait" : "pointer",
+ opacity: desktopLoginPending ? 0.85 : 1,
}}
>
-
- Çıkış Yap
+ {desktopLoginPending ? : }
+ {desktopLoginPending ? "Tarayıcıda Giriş Bekleniyor..." : "YakNet ile Giriş Yap"}
) : (
-
- Çıkış Yap
+
+ YakNet ile Giriş Yap
)}
- >
- ) : isDesktop ? (
-
void handleStartDesktopLogin()}
+
+
+
+ {/* Buluttaki Tasarımlar Listesi */}
+
+ Buluttaki Tasarımlarım ({cloudProjectCount})
+
+
+ {cloudList.length === 0 ? (
+
- {desktopLoginPending ? : }
- {desktopLoginPending ? "Tarayıcıda Giriş Bekleniyor..." : "YakNet ile Giriş Yap"}
-
+ {user
+ ? "Henüz bulutta kayıtlı tasarımınız bulunmuyor. 'Şimdi Eşitle' butonuna tıklayarak mevcut çalışmalarınızı yedekleyebilirsiniz."
+ : "Tasarımlarınızı bulutta yedeklemek ve tüm cihazlarınızdan erişmek için YakNet hesabınızla giriş yapın."}
+
) : (
-
-
- YakNet ile Giriş Yap
-
+
+ {cloudList.map((proj) => {
+ const dateLabel = proj.cloudUpdatedAt
+ ? new Date(proj.cloudUpdatedAt).toLocaleString("tr-TR", {
+ day: "2-digit",
+ month: "short",
+ hour: "2-digit",
+ minute: "2-digit",
+ })
+ : "Eşitlendi";
+ return (
+
+
+
+
+
+ {proj.name}
+
+
+ {proj.shapes?.length ?? 0} nesne • {dateLabel}
+
+
+
+
void handleDeleteCloudProject(proj.id)}
+ title="Buluttan Kaldır"
+ aria-label={`${proj.name} tasarımını buluttan kaldır`}
+ style={{
+ padding: "6px 8px",
+ borderRadius: "7px",
+ border: "none",
+ background: "rgba(239, 68, 68, 0.16)",
+ color: "#fca5a5",
+ cursor: "pointer",
+ }}
+ >
+
+
+
+ );
+ })}
+
)}
-
-
- {/* Buluttaki Tasarımlar Listesi */}
-
- Buluttaki Tasarımlarım ({cloudProjectCount})
-
-
- {cloudList.length === 0 ? (
-
- {user
- ? "Henüz bulutta kayıtlı tasarımınız bulunmuyor. 'Şimdi Eşitle' butonuna tıklayarak mevcut çalışmalarınızı yedekleyebilirsiniz."
- : "Tasarımlarınızı bulutta yedeklemek ve tüm cihazlarınızdan erişmek için YakNet hesabınızla giriş yapın."}
-
- ) : (
-
- {cloudList.map((proj) => {
- const dateLabel = proj.cloudUpdatedAt
- ? new Date(proj.cloudUpdatedAt).toLocaleString("tr-TR", {
- day: "2-digit",
- month: "short",
- hour: "2-digit",
- minute: "2-digit",
- })
- : "Eşitlendi";
- return (
-
-
-
-
-
- {proj.name}
-
-
- {proj.shapes?.length ?? 0} nesne • {dateLabel}
+ {localOnlyProjects.length > 0 ? (
+
+
+ Yalnızca bu tarayıcıda saklanan projeler ({localOnlyProjects.length})
+
+
+ Bu projeler bulut boyut sınırını aştığı veya yerel şekilleri okunamadığı için buluta yedeklenemedi.
+ Yerel kopyaları korunuyor. Yedek almak için projeyi açıp "Dosyayı Dışa Aktar" ile .skf dosyası oluşturun.
+
+
+ {localOnlyProjects.map((project) => (
+
+
+
+
{project.name}
+
+ {project.shapeCount} nesne •{" "}
+ {project.reason === "too-large"
+ ? `buluta sığmıyor (${formatByteSize(project.bytes)})`
+ : "yerel şekiller okunamadı"}
+
-
-
void handleDeleteCloudProject(proj.id)}
- title="Buluttan Kaldır"
- aria-label={`${proj.name} tasarımını buluttan kaldır`}
- style={{
- padding: "6px 8px",
- borderRadius: "7px",
- border: "none",
- background: "rgba(239, 68, 68, 0.16)",
- color: "#fca5a5",
- cursor: "pointer",
- }}
- >
-
-
+ ))}
- );
- })}
+
+ ) : null}
- )}
-
- {localOnlyProjects.length > 0 ? (
-
-
- Yalnızca bu tarayıcıda saklanan projeler ({localOnlyProjects.length})
-
-
- Bu projeler bulut boyut sınırını aştığı veya yerel şekilleri okunamadığı için buluta yedeklenemedi.
- Yerel kopyaları korunuyor. Yedek almak için projeyi açıp "Dosyayı Dışa Aktar" ile .skf dosyası oluşturun.
-
-
- {localOnlyProjects.map((project) => (
-
-
-
-
{project.name}
-
- {project.shapeCount} nesne •{" "}
- {project.reason === "too-large"
- ? `buluta sığmıyor (${formatByteSize(project.bytes)})`
- : "yerel şekiller okunamadı"}
-
-
-
- ))}
-
-
- ) : null}
-
-
,
+
,
document.body,
)
: null}
diff --git a/apps/web/src/lib/architecturalBimEngine.ts b/apps/web/src/lib/architecturalBimEngine.ts
new file mode 100644
index 0000000..9dd0800
--- /dev/null
+++ b/apps/web/src/lib/architecturalBimEngine.ts
@@ -0,0 +1,1874 @@
+import { createNoise2D } from "simplex-noise";
+import Delaunator from "delaunator";
+import { jsPDF } from "jspdf";
+import { createLocalId } from "@/lib/localIds";
+import { classifyShapeForIfc, type IfcBimEntityClass } from "@/lib/ifcExport";
+import type { ArchitecturalTextureId, WorkplaneShape } from "@/types/sketchforge";
+
+// ============================================================================
+// 1. ARCHITECTURAL SCALE & MULTI-STOREY (KAT / KOT) MANAGER
+// ============================================================================
+
+export type ArchitecturalScaleMode = "auto" | "1:100" | "1:50" | "1:1";
+
+export interface BuildingStorey {
+ id: string;
+ code: string;
+ name: string;
+ elevation: number; // In scene units (default 1:100 maket = 32 units per 3.2m storey, or 3000 in 1:1 mm)
+ height: number; // Storey height in scene units
+ realElevationMeters: number;
+ realHeightMeters: number;
+ tag: string;
+}
+
+export const DEFAULT_BUILDING_STOREYS: BuildingStorey[] = [
+ {
+ id: "storey-b1",
+ code: "B1",
+ name: "Bodrum Kat (-3.20 m)",
+ elevation: -32,
+ height: 32,
+ realElevationMeters: -3.2,
+ realHeightMeters: 3.2,
+ tag: "Kat: Bodrum Kat",
+ },
+ {
+ id: "storey-z0",
+ code: "Z0",
+ name: "Zemin Kat (±0.00 m)",
+ elevation: 0,
+ height: 32,
+ realElevationMeters: 0,
+ realHeightMeters: 3.2,
+ tag: "Kat: Zemin Kat",
+ },
+ {
+ id: "storey-n1",
+ code: "1K",
+ name: "1. Normal Kat (+3.20 m)",
+ elevation: 32,
+ height: 32,
+ realElevationMeters: 3.2,
+ realHeightMeters: 3.2,
+ tag: "Kat: 1. Normal Kat",
+ },
+ {
+ id: "storey-n2",
+ code: "2K",
+ name: "2. Normal Kat (+6.40 m)",
+ elevation: 64,
+ height: 32,
+ realElevationMeters: 6.4,
+ realHeightMeters: 3.2,
+ tag: "Kat: 2. Normal Kat",
+ },
+ {
+ id: "storey-roof",
+ code: "ÇK",
+ name: "Çatı / Teras Katı (+9.60 m)",
+ elevation: 96,
+ height: 28,
+ realElevationMeters: 9.6,
+ realHeightMeters: 2.8,
+ tag: "Kat: Çatı Katı",
+ },
+];
+
+/**
+ * Resolves scene unit -> real-world meters conversion factor.
+ * - "1:100": 1 scene unit = 0.1 m (10 cm), so 100x80 villa = 10m x 8m (80 m²), height 32 = 3.2 m.
+ * - "1:50": 1 scene unit = 0.05 m (5 cm).
+ * - "1:1": 1 scene unit = 0.001 m (1 mm).
+ * - "auto": Inspects scene bounding dimensions; if max span < 600, treats as 1:100 architectural studio scale.
+ */
+export function resolveMetersPerSceneUnit(
+ shapes: WorkplaneShape[],
+ scaleMode: ArchitecturalScaleMode = "auto",
+): number {
+ if (scaleMode === "1:100") return 0.1;
+ if (scaleMode === "1:50") return 0.05;
+ if (scaleMode === "1:1") return 0.001;
+
+ const solids = shapes.filter((s) => !s.hole);
+ if (solids.length === 0) return 0.1;
+ const maxSpan = Math.max(...solids.map((s) => Math.max(s.width || 0, s.depth || 0, s.height || 0)));
+ if (maxSpan >= 600) {
+ return 0.001; // 1:1 millimeter BIM model
+ }
+ return 0.1; // 1:100 architectural studio scale (1 unit = 10 cm)
+}
+
+export function doesShapeBelongToStorey(
+ shape: WorkplaneShape,
+ storey: BuildingStorey,
+ allStoreys: BuildingStorey[] = DEFAULT_BUILDING_STOREYS,
+): boolean {
+ const trimmedTag = (shape.tag || "").trim();
+ if (trimmedTag) {
+ if (trimmedTag === storey.tag) return true;
+ if (trimmedTag.startsWith("Kat:") || allStoreys.some((s) => s.tag === trimmedTag)) {
+ return false;
+ }
+ }
+ const elev = shape.elevation || 0;
+ const sorted = [...allStoreys].sort((a, b) => a.elevation - b.elevation);
+ const idx = sorted.findIndex((s) => s.id === storey.id);
+ const minElev = storey.elevation - 0.1;
+ const maxElev =
+ idx >= 0 && idx + 1 < sorted.length
+ ? sorted[idx + 1].elevation - 0.1
+ : storey.elevation + storey.height + 20;
+ return elev >= minElev && elev <= maxElev;
+}
+
+/**
+ * Isolates a target storey by showing its shapes and hiding other storeys (or showing all when storey is null).
+ */
+export function isolateStoreyVisibility(
+ shapes: WorkplaneShape[],
+ targetStorey: BuildingStorey | null,
+ allStoreys: BuildingStorey[] = DEFAULT_BUILDING_STOREYS,
+): WorkplaneShape[] {
+ if (!targetStorey) {
+ return shapes.map((s) => ({ ...s, hidden: false }));
+ }
+ return shapes.map((shape) => {
+ const belongs = doesShapeBelongToStorey(shape, targetStorey, allStoreys);
+ return {
+ ...shape,
+ hidden: !belongs,
+ };
+ });
+}
+
+/**
+ * Duplicates all architectural shapes on `sourceStorey` to `targetStorey` ("Katı Üst Kata Kopyala").
+ */
+export function duplicateStoreyToLevel(
+ shapes: WorkplaneShape[],
+ sourceStorey: BuildingStorey,
+ targetStorey: BuildingStorey,
+ allStoreys: BuildingStorey[] = DEFAULT_BUILDING_STOREYS,
+): { nextShapes: WorkplaneShape[]; clonedShapes: WorkplaneShape[] } {
+ const deltaElevation = targetStorey.elevation - sourceStorey.elevation;
+ const sourceShapes = shapes.filter((shape) => {
+ if (shape.tag?.toLocaleLowerCase("tr-TR").includes("arazi")) return false;
+ return doesShapeBelongToStorey(shape, sourceStorey, allStoreys);
+ });
+
+ const clonedShapes: WorkplaneShape[] = sourceShapes.map((orig) => ({
+ ...orig,
+ id: createLocalId("storey-copy"),
+ name: `${orig.name.replace(/\s*\([^)]*Kat\)\s*$/i, "")} (${targetStorey.code})`,
+ elevation: Number(((orig.elevation || 0) + deltaElevation).toFixed(2)),
+ tag: targetStorey.tag,
+ hidden: false,
+ locked: false,
+ }));
+
+ return {
+ nextShapes: [...shapes, ...clonedShapes],
+ clonedShapes,
+ };
+}
+
+// ============================================================================
+// 2. AUTOMATIC QUANTITY TAKE-OFF / METRAJ, MAHAL ALANI & KEŞİF (BOQ) ENGINE
+// ============================================================================
+
+export interface BoqLineItem {
+ pozNo: string;
+ category: string;
+ description: string;
+ ifcClass: IfcBimEntityClass;
+ elementCount: number;
+ quantity: number;
+ unit: "m²" | "m³" | "Adet" | "mt";
+ unitPriceTry: number;
+ totalCostTry: number;
+}
+
+export interface StoreyBoqSummary {
+ storeyId: string;
+ storeyName: string;
+ realElevationMeters: number;
+ elementCount: number;
+ grossFloorAreaM2: number;
+ wallAreaM2: number;
+ concreteVolumeM3: number;
+}
+
+export interface ArchitecturalBoqReport {
+ projectName: string;
+ scaleMode: ArchitecturalScaleMode;
+ metersPerUnit: number;
+ totalElementCount: number;
+ grossFloorAreaM2: number;
+ netUsableFloorAreaM2: number;
+ totalWallAreaM2: number;
+ totalRoofAreaM2: number;
+ totalStructuralConcreteM3: number;
+ windowCount: number;
+ windowAreaM2: number;
+ doorCount: number;
+ doorAreaM2: number;
+ railingLengthM: number;
+ furnitureCount: number;
+ totalEstimatedCostTry: number;
+ items: BoqLineItem[];
+ storeyBreakdown: StoreyBoqSummary[];
+}
+
+export interface BoqCalculationOptions {
+ projectName?: string;
+ scaleMode?: ArchitecturalScaleMode;
+ storeys?: BuildingStorey[];
+}
+
+/**
+ * Calculates full Architectural Quantity Take-Off (Metraj), Space Areas (m²/m³), and Cost Estimate (Keşif).
+ */
+export function calculateArchitecturalBoq(
+ shapes: WorkplaneShape[],
+ options: BoqCalculationOptions = {},
+): ArchitecturalBoqReport {
+ const scaleMode = options.scaleMode ?? "auto";
+ const mPerUnit = resolveMetersPerSceneUnit(shapes, scaleMode);
+ const storeys = options.storeys ?? DEFAULT_BUILDING_STOREYS;
+
+ const solids = shapes.filter((s) => !s.hole);
+ const holes = shapes.filter((s) => s.hole);
+
+ let grossFloorAreaM2 = 0;
+ let wallFootprintM2 = 0;
+ let rawWallAreaM2 = 0;
+ let openingDeductionM2 = 0;
+ let totalRoofAreaM2 = 0;
+ let totalStructuralConcreteM3 = 0;
+ let windowCount = 0;
+ let windowAreaM2 = 0;
+ let doorCount = 0;
+ let doorAreaM2 = 0;
+ let railingLengthM = 0;
+ let stairCount = 0;
+ let stairConcreteM3 = 0;
+ let columnBeamCount = 0;
+ let slabCount = 0;
+ let wallCount = 0;
+ let roofCount = 0;
+ let furnitureCount = 0;
+
+ // Evaluate holes for door/window openings when punched as boolean holes
+ for (const hShape of holes) {
+ const hName = `${hShape.tag || ""} ${hShape.name || ""}`.toLocaleLowerCase("tr-TR");
+ const wM = Math.max(hShape.width, hShape.depth) * mPerUnit;
+ const hM = hShape.height * mPerUnit;
+ const areaM2 = wM * hM;
+ if (hName.includes("pencere") || hName.includes("cam") || hName.includes("window")) {
+ windowCount += 1;
+ windowAreaM2 += areaM2;
+ openingDeductionM2 += areaM2;
+ } else if (hName.includes("kapı") || hName.includes("kapi") || hName.includes("door") || hName.includes("kemer")) {
+ doorCount += 1;
+ doorAreaM2 += areaM2;
+ openingDeductionM2 += areaM2;
+ }
+ }
+
+ for (const shape of solids) {
+ const ifcClass = classifyShapeForIfc(shape);
+ const wM = Math.max(0.05, shape.width * mPerUnit);
+ const dM = Math.max(0.05, shape.depth * mPerUnit);
+ const hM = Math.max(0.05, shape.height * mPerUnit);
+ const footprintM2 = wM * dM;
+ const volumeM3 = wM * dM * hM;
+ const verticalSideAreaM2 = Math.max(wM, dM) * hM;
+
+ switch (ifcClass) {
+ case "IFCSLAB":
+ slabCount += 1;
+ grossFloorAreaM2 += footprintM2;
+ totalStructuralConcreteM3 += volumeM3;
+ break;
+ case "IFCWALL":
+ wallCount += 1;
+ wallFootprintM2 += footprintM2;
+ rawWallAreaM2 += verticalSideAreaM2;
+ break;
+ case "IFCCOLUMN":
+ case "IFCBEAM":
+ columnBeamCount += 1;
+ totalStructuralConcreteM3 += volumeM3;
+ break;
+ case "IFCROOF":
+ roofCount += 1;
+ // Account for roof pitch factor (~1.18x footprint)
+ totalRoofAreaM2 += footprintM2 * 1.18;
+ break;
+ case "IFCSTAIR":
+ stairCount += 1;
+ stairConcreteM3 += volumeM3;
+ totalStructuralConcreteM3 += volumeM3;
+ break;
+ case "IFCRAILING":
+ railingLengthM += Math.max(wM, dM);
+ break;
+ case "IFCWINDOW":
+ windowCount += 1;
+ windowAreaM2 += verticalSideAreaM2;
+ break;
+ case "IFCDOOR":
+ doorCount += 1;
+ doorAreaM2 += verticalSideAreaM2;
+ break;
+ case "IFCFURNISHINGELEMENT":
+ furnitureCount += 1;
+ break;
+ default:
+ break;
+ }
+ }
+
+ // Fallback floor area estimation if walls exist without an explicit slab
+ if (grossFloorAreaM2 < 0.5 && solids.length > 0) {
+ const xs = solids.map((s) => [(s.x - s.width / 2) * mPerUnit, (s.x + s.width / 2) * mPerUnit]);
+ const zs = solids.map((s) => [(s.z - s.depth / 2) * mPerUnit, (s.z + s.depth / 2) * mPerUnit]);
+ const minX = Math.min(...xs.map((p) => p[0]));
+ const maxX = Math.max(...xs.map((p) => p[1]));
+ const minZ = Math.min(...zs.map((p) => p[0]));
+ const maxZ = Math.max(...zs.map((p) => p[1]));
+ grossFloorAreaM2 = Math.max(1, (maxX - minX) * (maxZ - minZ));
+ }
+
+ const totalWallAreaM2 = Math.max(0, rawWallAreaM2 - openingDeductionM2 * 0.65);
+ const netUsableFloorAreaM2 = Math.max(
+ grossFloorAreaM2 * 0.78,
+ grossFloorAreaM2 - Math.min(grossFloorAreaM2 * 0.22, wallFootprintM2),
+ );
+
+ // Build Turkish ÇŞB / Yaklaşık Maliyet Poz Kalemleri
+ const items: BoqLineItem[] = [];
+
+ if (totalStructuralConcreteM3 > 0.01) {
+ const qty = Number(totalStructuralConcreteM3.toFixed(2));
+ const unitPrice = 4250;
+ items.push({
+ pozNo: "15.150.1005",
+ category: "Betonarme & Kaba Yapı",
+ description: "C30/37 Hazır Beton Dökümü (Temel, Döşeme, Kolon, Kiriş & Merdiven)",
+ ifcClass: "IFCSLAB",
+ elementCount: slabCount + columnBeamCount + stairCount,
+ quantity: qty,
+ unit: "m³",
+ unitPriceTry: unitPrice,
+ totalCostTry: Math.round(qty * unitPrice),
+ });
+ }
+
+ if (totalWallAreaM2 > 0.01) {
+ const qty = Number(totalWallAreaM2.toFixed(2));
+ const unitPrice = 980;
+ items.push({
+ pozNo: "15.220.1004",
+ category: "Duvar & Bölme İşleri",
+ description: "Gazbeton / İzolasyonlu Tuğla Duvar Örülmesi + İç/Dış Sıva & Boya",
+ ifcClass: "IFCWALL",
+ elementCount: wallCount,
+ quantity: qty,
+ unit: "m²",
+ unitPriceTry: unitPrice,
+ totalCostTry: Math.round(qty * unitPrice),
+ });
+ }
+
+ if (netUsableFloorAreaM2 > 0.01) {
+ const qty = Number(netUsableFloorAreaM2.toFixed(2));
+ const unitPrice = 1150;
+ items.push({
+ pozNo: "15.340.1002",
+ category: "İnce Yapı & Zemin Kaplama",
+ description: "Tesviye Şapı + 1. Sınıf Porselen Seramik / Laminat Parke Döşeme Kaplaması",
+ ifcClass: "IFCSLAB",
+ elementCount: Math.max(1, slabCount),
+ quantity: qty,
+ unit: "m²",
+ unitPriceTry: unitPrice,
+ totalCostTry: Math.round(qty * unitPrice),
+ });
+ }
+
+ if (totalRoofAreaM2 > 0.01) {
+ const qty = Number(totalRoofAreaM2.toFixed(2));
+ const unitPrice = 1650;
+ items.push({
+ pozNo: "15.270.1001",
+ category: "Çatı & Su/Isı Yalıtımı",
+ description: "Çatı Karkası, Taşyünü Isı Yalıtımı, Su Yalıtım Membranı ve Çatı Örtüsü",
+ ifcClass: "IFCROOF",
+ elementCount: roofCount,
+ quantity: qty,
+ unit: "m²",
+ unitPriceTry: unitPrice,
+ totalCostTry: Math.round(qty * unitPrice),
+ });
+ }
+
+ if (windowAreaM2 > 0.01 || windowCount > 0) {
+ const qty = Number(Math.max(windowAreaM2, windowCount * 2.1).toFixed(2));
+ const unitPrice = 5400;
+ items.push({
+ pozNo: "15.410.1003",
+ category: "Pencere & Cephe Doğrama",
+ description: "Isı Yalıtımlı Alüminyum/PVC Doğrama + Konfor Isıcam (Low-E)",
+ ifcClass: "IFCWINDOW",
+ elementCount: windowCount,
+ quantity: qty,
+ unit: "m²",
+ unitPriceTry: unitPrice,
+ totalCostTry: Math.round(qty * unitPrice),
+ });
+ }
+
+ if (doorCount > 0) {
+ const unitPrice = 9500;
+ items.push({
+ pozNo: "15.430.1001",
+ category: "Kapı Doğramaları",
+ description: "Çelik Giriş Kapısı / Lake İç Oda Kapısı (Kasa, Kanat ve Aksesuar Dahil)",
+ ifcClass: "IFCDOOR",
+ elementCount: doorCount,
+ quantity: doorCount,
+ unit: "Adet",
+ unitPriceTry: unitPrice,
+ totalCostTry: Math.round(doorCount * unitPrice),
+ });
+ }
+
+ if (railingLengthM > 0.05) {
+ const qty = Number(railingLengthM.toFixed(2));
+ const unitPrice = 3200;
+ items.push({
+ pozNo: "15.455.1002",
+ category: "Korkuluk & Küpeşte",
+ description: "Temperli Lamine Camlı / Paslanmaz Çelik Balkon ve Merdiven Korkuluğu",
+ ifcClass: "IFCRAILING",
+ elementCount: 1,
+ quantity: qty,
+ unit: "mt",
+ unitPriceTry: unitPrice,
+ totalCostTry: Math.round(qty * unitPrice),
+ });
+ }
+
+ if (furnitureCount > 0) {
+ const unitPrice = 14500;
+ items.push({
+ pozNo: "15.610.1001",
+ category: "Sabit Mobilya & Tefrişat",
+ description: "Mimari Sabit Mobilya, Mutfak/Banyo Dolabı ve Tefrişat Elemanları",
+ ifcClass: "IFCFURNISHINGELEMENT",
+ elementCount: furnitureCount,
+ quantity: furnitureCount,
+ unit: "Adet",
+ unitPriceTry: unitPrice,
+ totalCostTry: Math.round(furnitureCount * unitPrice),
+ });
+ }
+
+ const totalEstimatedCostTry = items.reduce((acc, item) => acc + item.totalCostTry, 0);
+
+ // Per-storey breakdown
+ const storeyBreakdown: StoreyBoqSummary[] = storeys
+ .map((st) => {
+ const stShapes = solids.filter((s) => doesShapeBelongToStorey(s, st, storeys));
+ let stFloor = 0;
+ let stWall = 0;
+ let stConcrete = 0;
+ for (const s of stShapes) {
+ const cls = classifyShapeForIfc(s);
+ const wM = Math.max(0.05, s.width * mPerUnit);
+ const dM = Math.max(0.05, s.depth * mPerUnit);
+ const hM = Math.max(0.05, s.height * mPerUnit);
+ if (cls === "IFCSLAB") {
+ stFloor += wM * dM;
+ stConcrete += wM * dM * hM;
+ } else if (cls === "IFCWALL") {
+ stWall += Math.max(wM, dM) * hM;
+ } else if (cls === "IFCCOLUMN" || cls === "IFCBEAM" || cls === "IFCSTAIR") {
+ stConcrete += wM * dM * hM;
+ }
+ }
+ return {
+ storeyId: st.id,
+ storeyName: st.name,
+ realElevationMeters: st.realElevationMeters,
+ elementCount: stShapes.length,
+ grossFloorAreaM2: Number(stFloor.toFixed(2)),
+ wallAreaM2: Number(stWall.toFixed(2)),
+ concreteVolumeM3: Number(stConcrete.toFixed(2)),
+ };
+ })
+ .filter((st) => st.elementCount > 0);
+
+ return {
+ projectName: options.projectName?.trim() || "SnapCAD Mimari Proje",
+ scaleMode,
+ metersPerUnit: mPerUnit,
+ totalElementCount: solids.length,
+ grossFloorAreaM2: Number(grossFloorAreaM2.toFixed(2)),
+ netUsableFloorAreaM2: Number(netUsableFloorAreaM2.toFixed(2)),
+ totalWallAreaM2: Number(totalWallAreaM2.toFixed(2)),
+ totalRoofAreaM2: Number(totalRoofAreaM2.toFixed(2)),
+ totalStructuralConcreteM3: Number(totalStructuralConcreteM3.toFixed(2)),
+ windowCount,
+ windowAreaM2: Number(windowAreaM2.toFixed(2)),
+ doorCount,
+ doorAreaM2: Number(doorAreaM2.toFixed(2)),
+ railingLengthM: Number(railingLengthM.toFixed(2)),
+ furnitureCount,
+ totalEstimatedCostTry,
+ items,
+ storeyBreakdown,
+ };
+}
+
+/**
+ * Exports the Architectural BOQ & Cost Report to an Excel-compatible UTF-8 BOM CSV string.
+ */
+export function exportBoqToCsv(report: ArchitecturalBoqReport): string {
+ const rows: string[][] = [
+ ["SNAPCAD STUDIO - MIMARI METRAJ, MAHAL ALANI VE YAKLASIK MALIYET (BOQ) RAPORU"],
+ ["Proje Adi", report.projectName],
+ ["Toplam Brut Insaat Alani (m2)", String(report.grossFloorAreaM2)],
+ ["Toplam Net Kullanim Alani (m2)", String(report.netUsableFloorAreaM2)],
+ ["Toplam Net Duvar Alani (m2)", String(report.totalWallAreaM2)],
+ ["Toplam Betonarme Hacmi (m3)", String(report.totalStructuralConcreteM3)],
+ ["Toplam Cati Alani (m2)", String(report.totalRoofAreaM2)],
+ ["Pencere Adedi / Alani (m2)", `${report.windowCount} Adet / ${report.windowAreaM2} m2`],
+ ["Kapi Adedi", `${report.doorCount} Adet`],
+ ["Toplam Yaklasik Maliyet (TL)", `${report.totalEstimatedCostTry} TL`],
+ [],
+ ["Poz No", "Kategori", "Imalat Aciklamasi", "BIM Sinifi", "Eleman Adedi", "Miktar", "Birim", "Birim Fiyat (TL)", "Toplam Tutar (TL)"],
+ ...report.items.map((item) => [
+ item.pozNo,
+ item.category,
+ item.description,
+ item.ifcClass,
+ String(item.elementCount),
+ String(item.quantity),
+ item.unit,
+ String(item.unitPriceTry),
+ String(item.totalCostTry),
+ ]),
+ ];
+
+ const escapeCsvCell = (cell: string) => `"${cell.replace(/"/g, '""')}"`;
+ const csvBody = rows.map((r) => r.map(escapeCsvCell).join(";")).join("\r\n");
+ return `\uFEFF${csvBody}\r\n`;
+}
+
+/**
+ * Exports the Architectural BOQ & Cost Report to a formatted PDF document (Uint8Array).
+ */
+export function exportBoqToPdfBytes(report: ArchitecturalBoqReport): Uint8Array {
+ const doc = new jsPDF({ orientation: "portrait", unit: "mm", format: "a4" });
+ const safeAscii = (text: string) =>
+ text
+ .replace(/ğ/g, "g")
+ .replace(/Ğ/g, "G")
+ .replace(/ü/g, "u")
+ .replace(/Ü/g, "U")
+ .replace(/ş/g, "s")
+ .replace(/Ş/g, "S")
+ .replace(/ı/g, "i")
+ .replace(/İ/g, "I")
+ .replace(/ö/g, "o")
+ .replace(/Ö/g, "O")
+ .replace(/ç/g, "c")
+ .replace(/Ç/g, "C")
+ .replace(/±/g, "+/-")
+ .replace(/²/g, "2")
+ .replace(/³/g, "3")
+ .replace(/₺/g, "TL");
+
+ doc.setFillColor(15, 23, 42);
+ doc.rect(0, 0, 210, 32, "F");
+ doc.setTextColor(248, 250, 252);
+ doc.setFontSize(15);
+ doc.text("SNAPCAD STUDIO - MIMARI METRAJ & KESIF RAPORU (BIM 5D)", 14, 15);
+ doc.setFontSize(10);
+ doc.text(
+ safeAscii(`Proje: ${report.projectName} | Tarih: ${new Date().toISOString().slice(0, 10)}`),
+ 14,
+ 24,
+ );
+
+ doc.setTextColor(15, 23, 42);
+ doc.setFontSize(11);
+ doc.text("1. MAHAL ALANI VE KABA YAPI OZETI", 14, 42);
+
+ doc.setFontSize(9.5);
+ const summaryLines = [
+ `Brut Insaat / Doseme Alani: ${report.grossFloorAreaM2} m2 | Net Kullanim Alani: ${report.netUsableFloorAreaM2} m2`,
+ `Net Duvar Yuzey Alani: ${report.totalWallAreaM2} m2 | Betonarme Hacmi: ${report.totalStructuralConcreteM3} m3`,
+ `Cati Yuzey Alani: ${report.totalRoofAreaM2} m2 | Pencere: ${report.windowCount} Adet (${report.windowAreaM2} m2) | Kapi: ${report.doorCount} Adet`,
+ `TOPLAM YAKLASIK MALIYET: ${report.totalEstimatedCostTry.toLocaleString("tr-TR")} TL`,
+ ];
+ let y = 50;
+ for (const line of summaryLines) {
+ doc.text(safeAscii(line), 14, y);
+ y += 7;
+ }
+
+ y += 6;
+ doc.setFontSize(11);
+ doc.text("2. POZ BAZLI METRAJ VE MALIYET CETVELI", 14, y);
+ y += 8;
+
+ doc.setFontSize(8.5);
+ doc.setFillColor(226, 232, 240);
+ doc.rect(14, y - 4, 182, 7, "F");
+ doc.text("Poz No", 16, y);
+ doc.text("Imalat Kalemi", 42, y);
+ doc.text("Miktar", 132, y);
+ doc.text("Birim Fiyat", 154, y);
+ doc.text("Tutar (TL)", 176, y);
+ y += 7;
+
+ for (const item of report.items) {
+ if (y > 270) {
+ doc.addPage();
+ y = 20;
+ }
+ doc.text(safeAscii(item.pozNo), 16, y);
+ doc.text(safeAscii(item.description.slice(0, 48)), 42, y);
+ doc.text(safeAscii(`${item.quantity} ${item.unit}`), 132, y);
+ doc.text(safeAscii(`${item.unitPriceTry.toLocaleString("tr-TR")}`), 154, y);
+ doc.text(safeAscii(`${item.totalCostTry.toLocaleString("tr-TR")}`), 176, y);
+ y += 6.5;
+ }
+
+ const arrayBuffer = doc.output("arraybuffer");
+ return new Uint8Array(arrayBuffer);
+}
+
+// ============================================================================
+// 3. TURKISH BUILDING CODE & TS 9111 ACCESSIBILITY AUDITOR
+// ============================================================================
+
+export type CodeComplianceStatus = "pass" | "warning" | "fail";
+
+export interface ArchitecturalCodeCheckItem {
+ id: string;
+ codeReference: string;
+ title: string;
+ status: CodeComplianceStatus;
+ measuredValue: string;
+ requiredStandard: string;
+ recommendation: string;
+}
+
+export interface ArchitecturalCodeAuditReport {
+ score: number; // 0..100
+ overallStatus: CodeComplianceStatus;
+ checks: ArchitecturalCodeCheckItem[];
+}
+
+/**
+ * Audits the 3D scene against Planlı Alanlar İmar Yönetmeliği, TS 9111 (Engelsiz Tasarım), and TBDY 2018 rules.
+ */
+export function auditArchitecturalCodeCompliance(
+ shapes: WorkplaneShape[],
+ scaleMode: ArchitecturalScaleMode = "auto",
+): ArchitecturalCodeAuditReport {
+ const mPerUnit = resolveMetersPerSceneUnit(shapes, scaleMode);
+ const solids = shapes.filter((s) => !s.hole);
+ const boq = calculateArchitecturalBoq(shapes, { scaleMode });
+
+ const checks: ArchitecturalCodeCheckItem[] = [];
+
+ // 1. Ceiling Height Check (Planlı Alanlar İmar Yönetmeliği Madde 28: Net >= 2.60 m)
+ const walls = solids.filter((s) => classifyShapeForIfc(s) === "IFCWALL");
+ const maxWallHeightM =
+ walls.length > 0 ? Math.max(...walls.map((w) => w.height * mPerUnit)) : 3.0;
+ const ceilingStatus: CodeComplianceStatus =
+ walls.length === 0 ? "warning" : maxWallHeightM >= 2.6 ? "pass" : "fail";
+ checks.push({
+ id: "ceiling-height",
+ codeReference: "İmar Yön. Madde 28",
+ title: "Mahal İç Tavan Yüksekliği Kontrolü",
+ status: ceilingStatus,
+ measuredValue: walls.length > 0 ? `${maxWallHeightM.toFixed(2)} m` : "Duvar tespit edilmedi",
+ requiredStandard: "Min. 2.60 m net (2.85 m brüt) kat yüksekliği",
+ recommendation:
+ ceilingStatus === "pass"
+ ? "Kat yüksekliği konut ve ofis mahalleri için yönetmeliğe uygundur."
+ : "Duvar yüksekliğini en az 2.60 m (1:100 ölçekte >= 26 birim) olacak şekilde artırın.",
+ });
+
+ // 2. Stair Riser / Blondel Formula Check (İmar Yönetmeliği Madde 31: R <= 17.5 cm, G >= 27 cm, 2R+G = 60..64 cm)
+ const stairs = solids.filter((s) => classifyShapeForIfc(s) === "IFCSTAIR");
+ if (stairs.length > 0) {
+ const stepHeightsCm = stairs
+ .map((s) => s.height * mPerUnit * 100)
+ .filter((h) => h >= 10 && h <= 30);
+ const avgRiserCm = stepHeightsCm.length > 0 ? stepHeightsCm.reduce((a, b) => a + b, 0) / stepHeightsCm.length : 17.0;
+ const avgTreadCm = 28.0;
+ const blondel = 2 * avgRiserCm + avgTreadCm;
+ const stairOk = avgRiserCm <= 18.0 && blondel >= 59 && blondel <= 65;
+ checks.push({
+ id: "stair-blondel",
+ codeReference: "İmar Yön. Madde 31",
+ title: "Merdiven Rıht & Blondel (2R + G) Formülü",
+ status: stairOk ? "pass" : "warning",
+ measuredValue: `R ≈ ${avgRiserCm.toFixed(1)} cm, G ≈ ${avgTreadCm.toFixed(0)} cm (2R+G = ${blondel.toFixed(1)} cm)`,
+ requiredStandard: "R ≤ 17.5 cm, G ≥ 27 cm, 2R + G = 60–64 cm",
+ recommendation: stairOk
+ ? "Merdiven basamak oranları ergonomik Blondel kuralına uygundur."
+ : "Parametrik Merdiven aracından rıht yüksekliğini 16.5-17.5 cm aralığına ayarlayın.",
+ });
+ } else {
+ checks.push({
+ id: "stair-blondel",
+ codeReference: "İmar Yön. Madde 31",
+ title: "Merdiven & Kat Erişimi Kontrolü",
+ status: boq.storeyBreakdown.length > 1 ? "warning" : "pass",
+ measuredValue: boq.storeyBreakdown.length > 1 ? "Çok katlı yapıda merdiven yok" : "Tek katlı yapı",
+ requiredStandard: "Çok katlı binalarda R ≤ 17.5 cm, genişlik ≥ 120 cm merdiven",
+ recommendation:
+ boq.storeyBreakdown.length > 1
+ ? "Üst katlara erişim için Parametrik Merdiven sekmesinden Düz, L veya U merdiven ekleyin."
+ : "Tek katlı yapıda düşey sirkülasyon zorunlu değildir.",
+ });
+ }
+
+ // 3. Door Clear Width Check (TS 9111 Engelsiz Binalar: >= 90 cm)
+ const doorShapes = shapes.filter(
+ (s) =>
+ classifyShapeForIfc(s) === "IFCDOOR" ||
+ (s.hole && `${s.tag || ""} ${s.name || ""}`.toLocaleLowerCase("tr-TR").includes("kapı")),
+ );
+ if (doorShapes.length > 0) {
+ const minDoorWidthCm = Math.min(
+ ...doorShapes.map((d) => Math.max(d.width, d.depth) * mPerUnit * 100),
+ );
+ const doorOk = minDoorWidthCm >= 90;
+ checks.push({
+ id: "ts9111-door-width",
+ codeReference: "TS 9111 Engelsiz Tasarım",
+ title: "Kapı Net Geçiş Genişliği (Tekerlekli Sandalye Erişimi)",
+ status: doorOk ? "pass" : "warning",
+ measuredValue: `${minDoorWidthCm.toFixed(0)} cm (${doorShapes.length} kapı)`,
+ requiredStandard: "İç kapılar ≥ 90 cm, bina giriş kapısı ≥ 100 cm",
+ recommendation: doorOk
+ ? "Tüm kapı açıklıkları TS 9111 engelsiz erişim standardını sağlıyor."
+ : "Engelsiz erişim için kapı genişliğini en az 90 cm (girişte 100 cm) yapın.",
+ });
+ } else {
+ checks.push({
+ id: "ts9111-door-width",
+ codeReference: "TS 9111 Engelsiz Tasarım",
+ title: "Kapı & Giriş Açıklığı Kontrolü",
+ status: walls.length > 0 ? "warning" : "pass",
+ measuredValue: "0 adet kapı",
+ requiredStandard: "En az 1 adet ≥ 90 cm engelsiz kapı açıklığı",
+ recommendation: "Doğrama Kütüphanesinden Çelik Giriş Kapısı veya İç Oda Kapısı ekleyin.",
+ });
+ }
+
+ // 4. Daylight Window-to-Floor Ratio (Pencere / Döşeme Alanı >= %10)
+ const daylightRatioPct =
+ boq.grossFloorAreaM2 > 0 ? (boq.windowAreaM2 / boq.grossFloorAreaM2) * 100 : 12;
+ const daylightStatus: CodeComplianceStatus =
+ walls.length === 0 ? "pass" : daylightRatioPct >= 10 ? "pass" : daylightRatioPct >= 5 ? "warning" : "fail";
+ checks.push({
+ id: "daylight-ratio",
+ codeReference: "İmar Yön. Madde 51",
+ title: "Doğal Günışığı (Pencere / Zemin Alanı) Oranı",
+ status: daylightStatus,
+ measuredValue: `%${daylightRatioPct.toFixed(1)} (${boq.windowAreaM2} m² cam / ${boq.grossFloorAreaM2} m² döşeme)`,
+ requiredStandard: "Yaşam mahallerinde Pencere Alanı / Taban Alanı ≥ %10",
+ recommendation:
+ daylightStatus === "pass"
+ ? "Doğal aydınlatma ve havalandırma oranı yönetmeliğe uygundur."
+ : "Mahal aydınlatması için cepheye ilave pencere veya sürme doğrama ekleyin.",
+ });
+
+ // 5. Structural Column/Wall Support (TBDY 2018 Ön Kontrol)
+ const structuralCount = solids.filter((s) => {
+ const c = classifyShapeForIfc(s);
+ return c === "IFCCOLUMN" || c === "IFCWALL" || c === "IFCBEAM";
+ }).length;
+ const structStatus: CodeComplianceStatus = structuralCount >= 2 ? "pass" : "warning";
+ checks.push({
+ id: "tbdy-structural-support",
+ codeReference: "TBDY 2018 Ön İlke",
+ title: "Düşey Taşıyıcı Sistem (Kolon / Perde / Duvar) Sürekliliği",
+ status: structStatus,
+ measuredValue: `${structuralCount} taşıyıcı eleman (${boq.totalStructuralConcreteM3} m³ betonarme)`,
+ requiredStandard: "Simetrik aks düzeninde yeterli düşey taşıyıcı eleman",
+ recommendation:
+ structStatus === "pass"
+ ? "Taşıyıcı elemanlar sahnede mevcuttur."
+ : "Strüktür sekmesinden Kolon-Kiriş-Döşeme Aks Sistemi ekleyerek taşıyıcı iskelet oluşturun.",
+ });
+
+ const passCount = checks.filter((c) => c.status === "pass").length;
+ const warnCount = checks.filter((c) => c.status === "warning").length;
+ const score = Math.round(((passCount + warnCount * 0.6) / checks.length) * 100);
+ const overallStatus: CodeComplianceStatus =
+ checks.some((c) => c.status === "fail")
+ ? "fail"
+ : checks.some((c) => c.status === "warning")
+ ? "warning"
+ : "pass";
+
+ return {
+ score,
+ overallStatus,
+ checks,
+ };
+}
+
+// ============================================================================
+// 4. PARAMETRIC ARCHITECTURAL BIM ELEMENT GENERATORS
+// ============================================================================
+
+export type ParametricStairKind = "straight" | "l-shaped" | "u-shaped" | "spiral";
+
+export interface ParametricStairParams {
+ kind: ParametricStairKind;
+ totalHeight?: number; // Default 32 (= 3.20 m in 1:100)
+ flightWidth?: number; // Default 12 (= 1.20 m in 1:100)
+ stepCount?: number; // Default 16 steps (riser = 2.0 units = 20 cm, or 18 steps = 17.7 cm)
+ treadDepth?: number; // Default 3.0 (= 30 cm in 1:100)
+ includeRailing?: boolean;
+ baseElevation?: number;
+ storeyTag?: string;
+}
+
+export function generateParametricStair(params: ParametricStairParams): WorkplaneShape[] {
+ const totalHeight = Math.max(8, params.totalHeight ?? 32);
+ const flightWidth = Math.max(6, params.flightWidth ?? 12);
+ const stepCount = Math.max(4, Math.min(36, Math.round(params.stepCount ?? 18)));
+ const treadDepth = Math.max(2, params.treadDepth ?? 2.8);
+ const riserHeight = totalHeight / stepCount;
+ const baseElevation = params.baseElevation ?? 0;
+ const tag = params.storeyTag || "Merdiven";
+ const shapes: WorkplaneShape[] = [];
+
+ if (params.kind === "spiral") {
+ shapes.push({
+ id: createLocalId("stair-core"),
+ name: "Döner Merdiven Merkez Kolonu",
+ kind: "cylinder",
+ color: "#475569",
+ texture: "concrete",
+ tag,
+ x: 0,
+ z: 0,
+ elevation: baseElevation,
+ size: 6,
+ width: 5,
+ depth: 5,
+ height: totalHeight + 10,
+ rotation: 0,
+ sides: 28,
+ });
+
+ for (let i = 0; i < stepCount; i++) {
+ const angleDeg = i * (270 / stepCount);
+ const rad = (angleDeg * Math.PI) / 180;
+ const radius = flightWidth * 0.65;
+ shapes.push({
+ id: createLocalId("stair-step"),
+ name: `Döner Merdiven Basamağı ${i + 1}`,
+ kind: "box",
+ color: "#cbd5e1",
+ texture: "wood",
+ tag,
+ x: Number((Math.cos(rad) * radius).toFixed(2)),
+ z: Number((Math.sin(rad) * radius).toFixed(2)),
+ elevation: Number((baseElevation + i * riserHeight).toFixed(2)),
+ size: flightWidth,
+ width: flightWidth,
+ depth: treadDepth * 1.35,
+ height: Math.max(1.2, riserHeight * 0.9),
+ rotation: Number((-angleDeg).toFixed(1)),
+ });
+ }
+ return shapes;
+ }
+
+ if (params.kind === "u-shaped") {
+ const halfSteps = Math.floor(stepCount / 2);
+ const runLen = halfSteps * treadDepth;
+ const gap = 2;
+
+ // First flight (+Z direction)
+ for (let i = 0; i < halfSteps; i++) {
+ shapes.push({
+ id: createLocalId("stair-u1"),
+ name: `U-Merdiven 1. Kol Basamak ${i + 1}`,
+ kind: "box",
+ color: "#e2e8f0",
+ texture: "concrete",
+ tag,
+ x: -(flightWidth / 2 + gap / 2),
+ z: -runLen / 2 + i * treadDepth,
+ elevation: Number((baseElevation + i * riserHeight).toFixed(2)),
+ size: flightWidth,
+ width: flightWidth,
+ depth: treadDepth,
+ height: Number((riserHeight * 1.05).toFixed(2)),
+ rotation: 0,
+ });
+ }
+
+ // Mid-landing (Ara Sahanlık)
+ const landingElev = baseElevation + halfSteps * riserHeight;
+ shapes.push({
+ id: createLocalId("stair-landing"),
+ name: "U-Merdiven Ara Sahanlığı",
+ kind: "box",
+ color: "#94a3b8",
+ texture: "concrete",
+ tag,
+ x: 0,
+ z: runLen / 2 + flightWidth / 2,
+ elevation: Number((landingElev - riserHeight).toFixed(2)),
+ size: flightWidth * 2 + gap,
+ width: flightWidth * 2 + gap,
+ depth: flightWidth,
+ height: Number((riserHeight * 1.2).toFixed(2)),
+ rotation: 0,
+ });
+
+ // Second flight (-Z direction)
+ const remSteps = stepCount - halfSteps;
+ for (let j = 0; j < remSteps; j++) {
+ shapes.push({
+ id: createLocalId("stair-u2"),
+ name: `U-Merdiven 2. Kol Basamak ${j + 1}`,
+ kind: "box",
+ color: "#e2e8f0",
+ texture: "concrete",
+ tag,
+ x: flightWidth / 2 + gap / 2,
+ z: runLen / 2 - (j + 1) * treadDepth,
+ elevation: Number((landingElev + j * riserHeight).toFixed(2)),
+ size: flightWidth,
+ width: flightWidth,
+ depth: treadDepth,
+ height: Number((riserHeight * 1.05).toFixed(2)),
+ rotation: 0,
+ });
+ }
+ return shapes;
+ }
+
+ if (params.kind === "l-shaped") {
+ const halfSteps = Math.floor(stepCount / 2);
+ const run1 = halfSteps * treadDepth;
+ for (let i = 0; i < halfSteps; i++) {
+ shapes.push({
+ id: createLocalId("stair-l1"),
+ name: `L-Merdiven 1. Kol Basamak ${i + 1}`,
+ kind: "box",
+ color: "#e2e8f0",
+ texture: "concrete",
+ tag,
+ x: -run1 / 2 + i * treadDepth,
+ z: -flightWidth / 2,
+ elevation: Number((baseElevation + i * riserHeight).toFixed(2)),
+ size: flightWidth,
+ width: treadDepth,
+ depth: flightWidth,
+ height: Number((riserHeight * 1.05).toFixed(2)),
+ rotation: 0,
+ });
+ }
+
+ const landingElev = baseElevation + halfSteps * riserHeight;
+ const cornerX = run1 / 2 + flightWidth / 2;
+ shapes.push({
+ id: createLocalId("stair-l-landing"),
+ name: "L-Merdiven Köşe Sahanlığı",
+ kind: "box",
+ color: "#94a3b8",
+ texture: "concrete",
+ tag,
+ x: cornerX,
+ z: -flightWidth / 2,
+ elevation: Number((landingElev - riserHeight).toFixed(2)),
+ size: flightWidth,
+ width: flightWidth,
+ depth: flightWidth,
+ height: Number((riserHeight * 1.2).toFixed(2)),
+ rotation: 0,
+ });
+
+ const remSteps = stepCount - halfSteps;
+ for (let j = 0; j < remSteps; j++) {
+ shapes.push({
+ id: createLocalId("stair-l2"),
+ name: `L-Merdiven 2. Kol Basamak ${j + 1}`,
+ kind: "box",
+ color: "#e2e8f0",
+ texture: "concrete",
+ tag,
+ x: cornerX,
+ z: (j + 0.5) * treadDepth,
+ elevation: Number((landingElev + j * riserHeight).toFixed(2)),
+ size: flightWidth,
+ width: flightWidth,
+ depth: treadDepth,
+ height: Number((riserHeight * 1.05).toFixed(2)),
+ rotation: 0,
+ });
+ }
+ return shapes;
+ }
+
+ // Straight flight (Düz Kollu Merdiven)
+ const totalRun = stepCount * treadDepth;
+ for (let i = 0; i < stepCount; i++) {
+ shapes.push({
+ id: createLocalId("stair-straight"),
+ name: `Düz Merdiven Basamağı ${i + 1}`,
+ kind: "box",
+ color: "#e2e8f0",
+ texture: "concrete",
+ tag,
+ x: 0,
+ z: Number((-totalRun / 2 + i * treadDepth).toFixed(2)),
+ elevation: Number((baseElevation + i * riserHeight).toFixed(2)),
+ size: flightWidth,
+ width: flightWidth,
+ depth: treadDepth,
+ height: Number((riserHeight * 1.05).toFixed(2)),
+ rotation: 0,
+ });
+ }
+
+ if (params.includeRailing !== false) {
+ shapes.push({
+ id: createLocalId("stair-railing-l"),
+ name: "Merdiven Sol Korkuluk Küpeştesi",
+ kind: "box",
+ color: "#38bdf8",
+ tag: "Korkuluk",
+ x: -flightWidth / 2 + 0.4,
+ z: 0,
+ elevation: Number((baseElevation + totalHeight / 2 + 9).toFixed(2)),
+ size: totalRun,
+ width: 0.8,
+ depth: totalRun,
+ height: 9,
+ rotation: 0,
+ });
+ shapes.push({
+ id: createLocalId("stair-railing-r"),
+ name: "Merdiven Sağ Korkuluk Küpeştesi",
+ kind: "box",
+ color: "#38bdf8",
+ tag: "Korkuluk",
+ x: flightWidth / 2 - 0.4,
+ z: 0,
+ elevation: Number((baseElevation + totalHeight / 2 + 9).toFixed(2)),
+ size: totalRun,
+ width: 0.8,
+ depth: totalRun,
+ height: 9,
+ rotation: 0,
+ });
+ }
+
+ return shapes;
+}
+
+export type ParametricRoofKind = "gable" | "hip" | "shed" | "flat-parapet" | "barrel-vault";
+
+export interface ParametricRoofParams {
+ kind: ParametricRoofKind;
+ width?: number;
+ depth?: number;
+ ridgeHeight?: number;
+ overhang?: number;
+ baseElevation?: number;
+ storeyTag?: string;
+}
+
+export function generateParametricRoof(params: ParametricRoofParams): WorkplaneShape[] {
+ const width = Math.max(20, params.width ?? 80);
+ const depth = Math.max(20, params.depth ?? 60);
+ const ridgeHeight = Math.max(4, params.ridgeHeight ?? 18);
+ const overhang = Math.max(0, params.overhang ?? 4);
+ const baseElevation = params.baseElevation ?? 32;
+ const tag = params.storeyTag || "Çatı";
+ const spanW = width + overhang * 2;
+ const spanD = depth + overhang * 2;
+
+ if (params.kind === "flat-parapet") {
+ const pThick = 2.5;
+ const pHeight = Math.max(6, ridgeHeight * 0.5);
+ return [
+ {
+ id: createLocalId("roof-slab"),
+ name: "Teras Çatı Su/Isı Yalıtım Döşemesi",
+ kind: "box",
+ color: "#64748b",
+ texture: "concrete",
+ tag,
+ x: 0,
+ z: 0,
+ elevation: baseElevation,
+ size: width,
+ width,
+ depth,
+ height: 3.5,
+ rotation: 0,
+ },
+ {
+ id: createLocalId("parapet-n"),
+ name: "Kuzey Çatı Parapet Duvarı",
+ kind: "box",
+ color: "#cbd5e1",
+ tag,
+ x: 0,
+ z: -depth / 2 + pThick / 2,
+ elevation: baseElevation + 3.5,
+ size: width,
+ width,
+ depth: pThick,
+ height: pHeight,
+ rotation: 0,
+ },
+ {
+ id: createLocalId("parapet-s"),
+ name: "Güney Çatı Parapet Duvarı",
+ kind: "box",
+ color: "#cbd5e1",
+ tag,
+ x: 0,
+ z: depth / 2 - pThick / 2,
+ elevation: baseElevation + 3.5,
+ size: width,
+ width,
+ depth: pThick,
+ height: pHeight,
+ rotation: 0,
+ },
+ {
+ id: createLocalId("parapet-w"),
+ name: "Batı Çatı Parapet Duvarı",
+ kind: "box",
+ color: "#cbd5e1",
+ tag,
+ x: -width / 2 + pThick / 2,
+ z: 0,
+ elevation: baseElevation + 3.5,
+ size: depth,
+ width: pThick,
+ depth: depth - pThick * 2,
+ height: pHeight,
+ rotation: 0,
+ },
+ {
+ id: createLocalId("parapet-e"),
+ name: "Doğu Çatı Parapet Duvarı",
+ kind: "box",
+ color: "#cbd5e1",
+ tag,
+ x: width / 2 - pThick / 2,
+ z: 0,
+ elevation: baseElevation + 3.5,
+ size: depth,
+ width: pThick,
+ depth: depth - pThick * 2,
+ height: pHeight,
+ rotation: 0,
+ },
+ ];
+ }
+
+ if (params.kind === "barrel-vault") {
+ return [
+ {
+ id: createLocalId("roof-vault"),
+ name: "Tonoz Kemer Çatı Örtüsü",
+ kind: "roundRoof",
+ color: "#b45309",
+ texture: "brick",
+ tag,
+ x: 0,
+ z: 0,
+ elevation: baseElevation,
+ size: Math.max(spanW, spanD),
+ width: spanW,
+ depth: spanD,
+ height: ridgeHeight,
+ rotation: 0,
+ },
+ ];
+ }
+
+ if (params.kind === "shed") {
+ return [
+ {
+ id: createLocalId("roof-shed"),
+ name: "Tek Yöne Eğimli Sundurma Çatı",
+ kind: "wedge",
+ color: "#991b1b",
+ texture: "brick",
+ tag,
+ x: 0,
+ z: 0,
+ elevation: baseElevation,
+ size: Math.max(spanW, spanD),
+ width: spanW,
+ depth: spanD,
+ height: ridgeHeight,
+ rotation: 0,
+ },
+ ];
+ }
+
+ if (params.kind === "hip") {
+ return [
+ {
+ id: createLocalId("roof-hip"),
+ name: "Kırma Çatı (4 Yöne Eğimli)",
+ kind: "pyramid",
+ color: "#b91c1c",
+ texture: "brick",
+ tag,
+ x: 0,
+ z: 0,
+ elevation: baseElevation,
+ size: Math.max(spanW, spanD),
+ width: spanW,
+ depth: spanD,
+ height: ridgeHeight,
+ rotation: 0,
+ },
+ ];
+ }
+
+ // Default: Gable Roof (Beşik Çatı — Left & Right pitched roof slopes)
+ return [
+ {
+ id: createLocalId("roof-gable-l"),
+ name: "Beşik Çatı Sol Eğimli Kanat",
+ kind: "wedge",
+ color: "#dc2626",
+ texture: "brick",
+ tag,
+ x: -spanW / 4,
+ z: 0,
+ elevation: baseElevation,
+ size: Math.max(spanW / 2, spanD),
+ width: spanW / 2,
+ depth: spanD,
+ height: ridgeHeight,
+ rotation: 0,
+ },
+ {
+ id: createLocalId("roof-gable-r"),
+ name: "Beşik Çatı Sağ Eğimli Kanat",
+ kind: "wedge",
+ color: "#dc2626",
+ texture: "brick",
+ tag,
+ x: spanW / 4,
+ z: 0,
+ elevation: baseElevation,
+ size: Math.max(spanW / 2, spanD),
+ width: spanW / 2,
+ depth: spanD,
+ height: ridgeHeight,
+ rotation: 180,
+ },
+ ];
+}
+
+export type ParametricOpeningKind =
+ | "double-window"
+ | "sliding-patio"
+ | "french-balcony"
+ | "steel-entrance-door"
+ | "interior-door"
+ | "brise-soleil";
+
+export interface ParametricOpeningParams {
+ kind: ParametricOpeningKind;
+ width?: number;
+ height?: number;
+ sillElevation?: number;
+ storeyTag?: string;
+}
+
+export function generateParametricOpeningUnit(params: ParametricOpeningParams): WorkplaneShape[] {
+ const kind = params.kind;
+ const sill = params.sillElevation ?? (kind.includes("door") || kind === "sliding-patio" ? 0 : 9);
+
+ if (kind === "steel-entrance-door" || kind === "interior-door") {
+ const w = params.width ?? (kind === "steel-entrance-door" ? 12 : 9.5);
+ const h = params.height ?? 21;
+ const tag = params.storeyTag || "Kapı & Boşluklar";
+ return [
+ {
+ id: createLocalId("door-frame"),
+ name: kind === "steel-entrance-door" ? "Çelik Kapı Kasası & Pervazı" : "Ahşap Oda Kapısı Kasası",
+ kind: "box",
+ color: kind === "steel-entrance-door" ? "#1e293b" : "#78350f",
+ texture: "wood",
+ tag,
+ x: 0,
+ z: 0,
+ elevation: sill,
+ size: Math.max(w, h),
+ width: w,
+ depth: 2.4,
+ height: h,
+ rotation: 0,
+ },
+ {
+ id: createLocalId("door-leaf"),
+ name: kind === "steel-entrance-door" ? "Çelik Kapı Zırhlı Kanadı" : "Lake Kapı Kanadı",
+ kind: "box",
+ color: kind === "steel-entrance-door" ? "#334155" : "#d97706",
+ texture: "wood",
+ tag,
+ x: 0,
+ z: 0.2,
+ elevation: sill + 0.5,
+ size: Math.max(w, h),
+ width: w - 1.2,
+ depth: 1.4,
+ height: h - 0.8,
+ rotation: 0,
+ },
+ {
+ id: createLocalId("door-handle"),
+ name: "Paslanmaz Kapı Kolu",
+ kind: "box",
+ color: "#f8fafc",
+ tag,
+ x: w * 0.32,
+ z: 1.3,
+ elevation: sill + h * 0.48,
+ size: 2,
+ width: 1.8,
+ depth: 0.8,
+ height: 0.8,
+ rotation: 0,
+ },
+ ];
+ }
+
+ if (kind === "brise-soleil") {
+ const w = params.width ?? 28;
+ const h = params.height ?? 22;
+ const tag = params.storeyTag || "Pencereler";
+ const louverCount = 6;
+ const shapes: WorkplaneShape[] = [];
+ for (let i = 0; i < louverCount; i++) {
+ shapes.push({
+ id: createLocalId("louver-blade"),
+ name: `Güneş Kırıcı Alüminyum Kanat ${i + 1}`,
+ kind: "box",
+ color: "#d97706",
+ texture: "wood",
+ tag,
+ x: 0,
+ z: 1.5,
+ elevation: Number((sill + (i / (louverCount - 1)) * h).toFixed(2)),
+ size: w,
+ width: w,
+ depth: 3.2,
+ height: 0.8,
+ rotation: 0,
+ });
+ }
+ return shapes;
+ }
+
+ // Windows / Sliding Patio / French Balcony
+ const w = params.width ?? (kind === "sliding-patio" ? 28 : 16);
+ const h = params.height ?? (kind === "double-window" ? 14 : 21);
+ const tag = params.storeyTag || "Pencereler";
+ const shapes: WorkplaneShape[] = [
+ {
+ id: createLocalId("win-frame"),
+ name: kind === "sliding-patio" ? "Sürme Doğrama Ana Kasa" : "Isıcamlı Pencere Doğrama Kasası",
+ kind: "box",
+ color: "#334155",
+ tag,
+ x: 0,
+ z: 0,
+ elevation: sill,
+ size: Math.max(w, h),
+ width: w,
+ depth: 2.2,
+ height: h,
+ rotation: 0,
+ },
+ {
+ id: createLocalId("win-glass-l"),
+ name: "Sol Low-E Isıcam Paneli",
+ kind: "box",
+ color: "#38bdf8",
+ texture: "glass",
+ tag,
+ x: -w / 4,
+ z: 0,
+ elevation: sill + 0.8,
+ size: w / 2,
+ width: w / 2 - 1.2,
+ depth: 1.0,
+ height: h - 1.6,
+ rotation: 0,
+ },
+ {
+ id: createLocalId("win-glass-r"),
+ name: "Sağ Low-E Isıcam Paneli",
+ kind: "box",
+ color: "#38bdf8",
+ texture: "glass",
+ tag,
+ x: w / 4,
+ z: 0,
+ elevation: sill + 0.8,
+ size: w / 2,
+ width: w / 2 - 1.2,
+ depth: 1.0,
+ height: h - 1.6,
+ rotation: 0,
+ },
+ {
+ id: createLocalId("win-sill"),
+ name: "Mermer Pencere Denizliği",
+ kind: "box",
+ color: "#e2e8f0",
+ texture: "marble",
+ tag,
+ x: 0,
+ z: 0.8,
+ elevation: Math.max(0, sill - 1.2),
+ size: w + 3,
+ width: w + 3,
+ depth: 3.6,
+ height: 1.2,
+ rotation: 0,
+ },
+ ];
+
+ if (kind === "french-balcony") {
+ shapes.push({
+ id: createLocalId("french-railing"),
+ name: "Fransız Balkon Cam Korkuluğu",
+ kind: "box",
+ color: "#0ea5e9",
+ texture: "glass",
+ tag: "Korkuluk",
+ x: 0,
+ z: 2.0,
+ elevation: sill + 0.5,
+ size: w,
+ width: w,
+ depth: 0.6,
+ height: Math.min(9.5, h * 0.45),
+ rotation: 0,
+ });
+ }
+
+ return shapes;
+}
+
+export interface StructuralFrameGridParams {
+ baysX?: number; // Number of spans in X (e.g. 2 -> 3 column axes)
+ baysZ?: number; // Number of spans in Z (e.g. 2 -> 3 column axes)
+ spanX?: number; // Distance between X axes (default 40 = 4.0m in 1:100)
+ spanZ?: number; // Distance between Z axes (default 40 = 4.0m in 1:100)
+ storeyHeight?: number; // Default 32 = 3.2m
+ columnSize?: number; // Default 4 = 40x40 cm
+ includeFoundationSlab?: boolean;
+ includeCeilingSlab?: boolean;
+ baseElevation?: number;
+ storeyTag?: string;
+}
+
+/**
+ * Generates a parametric reinforced-concrete Column + Beam + Slab Structural Axis Grid (Kolon-Kiriş-Döşeme Sistemi).
+ */
+export function generateStructuralFrameGrid(params: StructuralFrameGridParams): WorkplaneShape[] {
+ const baysX = Math.max(1, Math.min(6, Math.round(params.baysX ?? 2)));
+ const baysZ = Math.max(1, Math.min(6, Math.round(params.baysZ ?? 2)));
+ const spanX = Math.max(15, params.spanX ?? 42);
+ const spanZ = Math.max(15, params.spanZ ?? 38);
+ const storeyHeight = Math.max(18, params.storeyHeight ?? 32);
+ const colSize = Math.max(2.5, params.columnSize ?? 4);
+ const baseElevation = params.baseElevation ?? 0;
+ const tag = params.storeyTag || "Kat: Zemin Kat";
+
+ const totalW = baysX * spanX;
+ const totalD = baysZ * spanZ;
+ const slabThickness = 3.0;
+ const beamHeight = 4.5;
+ const shapes: WorkplaneShape[] = [];
+
+ if (params.includeFoundationSlab !== false) {
+ shapes.push({
+ id: createLocalId("struct-foundation"),
+ name: "Radye Temel / Kat Tabliye Döşemesi",
+ kind: "box",
+ color: "#94a3b8",
+ texture: "concrete",
+ tag: "Zemin",
+ x: 0,
+ z: 0,
+ elevation: baseElevation,
+ size: Math.max(totalW, totalD) + colSize * 2,
+ width: totalW + colSize * 2,
+ depth: totalD + colSize * 2,
+ height: slabThickness,
+ rotation: 0,
+ });
+ }
+
+ const colStartElev = params.includeFoundationSlab !== false ? baseElevation + slabThickness : baseElevation;
+
+ // Columns at grid intersections
+ for (let ix = 0; ix <= baysX; ix++) {
+ for (let iz = 0; iz <= baysZ; iz++) {
+ const cx = -totalW / 2 + ix * spanX;
+ const cz = -totalD / 2 + iz * spanZ;
+ const axisLabel = `${String.fromCharCode(65 + iz)}${ix + 1}`;
+ shapes.push({
+ id: createLocalId("struct-col"),
+ name: `Betonarme Kolon Aks ${axisLabel}`,
+ kind: "box",
+ color: "#64748b",
+ texture: "concrete",
+ tag,
+ x: Number(cx.toFixed(2)),
+ z: Number(cz.toFixed(2)),
+ elevation: colStartElev,
+ size: colSize,
+ width: colSize,
+ depth: colSize,
+ height: storeyHeight,
+ rotation: 0,
+ });
+ }
+ }
+
+ // X-direction Beams
+ const beamElev = colStartElev + storeyHeight - beamHeight;
+ for (let iz = 0; iz <= baysZ; iz++) {
+ const cz = -totalD / 2 + iz * spanZ;
+ shapes.push({
+ id: createLocalId("struct-beam-x"),
+ name: `Ana Taşıyıcı Kiriş X-${iz + 1}`,
+ kind: "box",
+ color: "#475569",
+ texture: "concrete",
+ tag,
+ x: 0,
+ z: Number(cz.toFixed(2)),
+ elevation: beamElev,
+ size: totalW,
+ width: totalW + colSize,
+ depth: colSize * 0.85,
+ height: beamHeight,
+ rotation: 0,
+ });
+ }
+
+ // Z-direction Beams
+ for (let ix = 0; ix <= baysX; ix++) {
+ const cx = -totalW / 2 + ix * spanX;
+ shapes.push({
+ id: createLocalId("struct-beam-z"),
+ name: `Ana Taşıyıcı Kiriş Z-${ix + 1}`,
+ kind: "box",
+ color: "#475569",
+ texture: "concrete",
+ tag,
+ x: Number(cx.toFixed(2)),
+ z: 0,
+ elevation: beamElev,
+ size: totalD,
+ width: colSize * 0.85,
+ depth: totalD + colSize,
+ height: beamHeight,
+ rotation: 0,
+ });
+ }
+
+ if (params.includeCeilingSlab) {
+ shapes.push({
+ id: createLocalId("struct-top-slab"),
+ name: "Üst Kat Tavan Döşeme Tabliyesi",
+ kind: "box",
+ color: "#cbd5e1",
+ texture: "concrete",
+ tag: "Zemin",
+ x: 0,
+ z: 0,
+ elevation: colStartElev + storeyHeight,
+ size: Math.max(totalW, totalD) + colSize * 2,
+ width: totalW + colSize * 2,
+ depth: totalD + colSize * 2,
+ height: slabThickness,
+ rotation: 0,
+ });
+ }
+
+ return shapes;
+}
+
+// ============================================================================
+// 5. OPEN-SOURCE SIMPLEX-NOISE + DELAUNATOR TOPOGRAPHY & EXCAVATION GENERATOR
+// ============================================================================
+
+export type TerrainTopographyPreset = "hills" | "slope" | "valley" | "terrace" | "coastal-ridge";
+
+export interface AdvancedTerrainParams {
+ preset: TerrainTopographyPreset;
+ width?: number;
+ depth?: number;
+ maxHeight?: number;
+ gridResolution?: number; // Default 18 (18x18 Delaunay survey points)
+ seed?: number;
+ texture?: ArchitecturalTextureId;
+ includeBuildingPad?: boolean;
+ padWidth?: number;
+ padDepth?: number;
+ padElevation?: number;
+ metersPerUnit?: number;
+}
+
+export interface GeneratedTerrainResult {
+ terrainShape: WorkplaneShape;
+ padShape: WorkplaneShape | null;
+ triangleCount: number;
+ vertexCount: number;
+ excavationCutVolumeM3: number;
+ embankmentFillVolumeM3: number;
+ netEarthworkVolumeM3: number;
+}
+
+function createSeededRandom(seed: number): () => number {
+ let state = Math.floor(seed) || 1337;
+ return () => {
+ state = (state * 1664525 + 1013904223) >>> 0;
+ return state / 0x100000000;
+ };
+}
+
+/**
+ * Generates a realistic 3D site topography mesh using `simplex-noise` + `delaunator`
+ * and calculates exact building pad excavation (Kazı / Hafriyat) & fill (Dolgu) volumes in m³.
+ */
+export function generateAdvancedTerrainWithPad(params: AdvancedTerrainParams): GeneratedTerrainResult {
+ const width = Math.max(60, params.width ?? 220);
+ const depth = Math.max(60, params.depth ?? 220);
+ const maxHeight = Math.max(4, params.maxHeight ?? 20);
+ const res = Math.max(8, Math.min(36, Math.round(params.gridResolution ?? 18)));
+ const seed = params.seed ?? 42;
+ const texture: ArchitecturalTextureId = params.texture ?? "grass";
+ const includePad = params.includeBuildingPad ?? true;
+ const padWidth = Math.min(width * 0.75, Math.max(20, params.padWidth ?? width * 0.45));
+ const padDepth = Math.min(depth * 0.75, Math.max(20, params.padDepth ?? depth * 0.4));
+ const padElevation = params.padElevation ?? maxHeight * 0.35;
+ const mPerUnit = params.metersPerUnit ?? 0.1;
+
+ const noise2D = createNoise2D(createSeededRandom(seed));
+
+ const sampleNaturalHeight = (u: number, v: number): number => {
+ const n1 = noise2D(u * 2.2, v * 2.2); // [-1, 1]
+ const n2 = noise2D(u * 4.5 + 7.1, v * 4.5 - 3.4) * 0.35;
+ const combinedNoise = (n1 + n2 + 1.35) / 2.7; // ~ [0, 1]
+
+ switch (params.preset) {
+ case "slope":
+ return Math.max(0.5, u * maxHeight * 0.85 + combinedNoise * maxHeight * 0.2);
+ case "valley": {
+ const distCenter = Math.abs(u - 0.5) * 2;
+ return Math.max(0.5, distCenter * distCenter * maxHeight * 0.85 + combinedNoise * maxHeight * 0.2);
+ }
+ case "terrace": {
+ const raw = u * 0.75 + combinedNoise * 0.25;
+ const steps = 5;
+ return Math.max(0.5, (Math.floor(raw * steps) / steps) * maxHeight);
+ }
+ case "coastal-ridge": {
+ const ridge = Math.sin(u * Math.PI) * Math.cos((v - 0.5) * Math.PI * 0.8);
+ return Math.max(0.5, ridge * maxHeight * 0.75 + combinedNoise * maxHeight * 0.3);
+ }
+ case "hills":
+ default:
+ return Math.max(0.5, combinedNoise * maxHeight);
+ }
+ };
+
+ const halfW = width / 2;
+ const halfD = depth / 2;
+ const halfPadW = padWidth / 2;
+ const halfPadD = padDepth / 2;
+
+ const points2D: Array<[number, number]> = [];
+ const heights: number[] = [];
+
+ let cutVolumeSceneUnits3 = 0;
+ let fillVolumeSceneUnits3 = 0;
+ const cellArea = (width / res) * (depth / res);
+
+ for (let i = 0; i <= res; i++) {
+ for (let j = 0; j <= res; j++) {
+ const u = i / res;
+ const v = j / res;
+ const x = -halfW + u * width;
+ const z = -halfD + v * depth;
+ const natY = sampleNaturalHeight(u, v);
+
+ let finalY = natY;
+ if (includePad) {
+ const dx = Math.max(0, Math.abs(x) - halfPadW);
+ const dz = Math.max(0, Math.abs(z) - halfPadD);
+ const distToPad = Math.hypot(dx, dz);
+ const blendMargin = Math.max(8, Math.min(width, depth) * 0.08);
+
+ if (distToPad <= 0.001) {
+ finalY = padElevation;
+ if (natY > padElevation) {
+ cutVolumeSceneUnits3 += (natY - padElevation) * cellArea;
+ } else {
+ fillVolumeSceneUnits3 += (padElevation - natY) * cellArea;
+ }
+ } else if (distToPad < blendMargin) {
+ const t = distToPad / blendMargin;
+ const smoothT = t * t * (3 - 2 * t);
+ finalY = padElevation * (1 - smoothT) + natY * smoothT;
+ }
+ }
+
+ points2D.push([x, z]);
+ heights.push(finalY);
+ }
+ }
+
+ // Triangulate 2D survey points with Delaunator
+ const delaunay = Delaunator.from(points2D);
+ const triangles = delaunay.triangles;
+
+ const positions: number[] = [];
+ const normals: number[] = [];
+
+ for (let t = 0; t < triangles.length; t += 3) {
+ // Flip winding so normal points +Y upward in Three.js (X, Y=up, Z)
+ const i0 = triangles[t];
+ const i1 = triangles[t + 2];
+ const i2 = triangles[t + 1];
+
+ const [x0, z0] = points2D[i0];
+ const y0 = heights[i0];
+ const [x1, z1] = points2D[i1];
+ const y1 = heights[i1];
+ const [x2, z2] = points2D[i2];
+ const y2 = heights[i2];
+
+ const ux = x1 - x0;
+ const uy = y1 - y0;
+ const uz = z1 - z0;
+ const vx = x2 - x0;
+ const vy = y2 - y0;
+ const vz = z2 - z0;
+
+ let nx = uy * vz - uz * vy;
+ let ny = uz * vx - ux * vz;
+ let nz = ux * vy - uy * vx;
+ if (ny < 0) {
+ nx = -nx;
+ ny = -ny;
+ nz = -nz;
+ }
+ const len = Math.hypot(nx, ny, nz) || 1;
+ nx /= len;
+ ny /= len;
+ nz /= len;
+
+ positions.push(x0, y0, z0, x1, y1, z1, x2, y2, z2);
+ normals.push(nx, ny, nz, nx, ny, nz, nx, ny, nz);
+ }
+
+ const presetLabelMap: Record
= {
+ hills: "Simplex Doğal Tepe Topoğrafyası",
+ slope: "Eğimli Yamaç Topoğrafyası",
+ valley: "Akarsu Vadisi Topoğrafyası",
+ terrace: "Eşyükselti Kademeli Teras Arazi",
+ "coastal-ridge": "Kıyı Sırtı Topoğrafyası",
+ };
+
+ const terrainShape: WorkplaneShape = {
+ id: createLocalId("terrain-delaunay"),
+ name: presetLabelMap[params.preset] || "Topoğrafik Arazi",
+ kind: "mesh",
+ color: texture === "grass" ? "#22c55e" : "#64748b",
+ texture,
+ tag: "Arazi / Topoğrafya",
+ x: 0,
+ z: 0,
+ elevation: 0,
+ size: Math.max(width, depth),
+ width,
+ depth,
+ height: Math.max(5, maxHeight),
+ rotation: 0,
+ importedMesh: {
+ positions,
+ normals,
+ baseWidth: width,
+ baseDepth: depth,
+ baseHeight: maxHeight,
+ triangleCount: positions.length / 9,
+ sourceFormat: "json",
+ },
+ };
+
+ const padShape: WorkplaneShape | null = includePad
+ ? {
+ id: createLocalId("terrain-pad"),
+ name: "Tesviye Edilmiş Bina Oturum Düzlüğü (Temel Kotu)",
+ kind: "box",
+ color: "#cbd5e1",
+ texture: "concrete",
+ tag: "Zemin",
+ x: 0,
+ z: 0,
+ elevation: Number(padElevation.toFixed(2)),
+ size: Math.max(padWidth, padDepth),
+ width: padWidth,
+ depth: padDepth,
+ height: 1.5,
+ rotation: 0,
+ }
+ : null;
+
+ const volScale = Math.pow(mPerUnit, 3);
+ const excavationCutVolumeM3 = Number((cutVolumeSceneUnits3 * volScale).toFixed(1));
+ const embankmentFillVolumeM3 = Number((fillVolumeSceneUnits3 * volScale).toFixed(1));
+
+ return {
+ terrainShape,
+ padShape,
+ triangleCount: positions.length / 9,
+ vertexCount: points2D.length,
+ excavationCutVolumeM3,
+ embankmentFillVolumeM3,
+ netEarthworkVolumeM3: Number((excavationCutVolumeM3 - embankmentFillVolumeM3).toFixed(1)),
+ };
+}
diff --git a/apps/web/src/lib/desktopBridge.ts b/apps/web/src/lib/desktopBridge.ts
index 1ab0001..bd5afab 100644
--- a/apps/web/src/lib/desktopBridge.ts
+++ b/apps/web/src/lib/desktopBridge.ts
@@ -9,12 +9,14 @@ const VALID_DESKTOP_MENU_ACTIONS = new Set([
"file:save",
"file:save-as",
"file:save-and-quit",
+ "file:save-and-update",
"file:import",
"file:export-panel",
"file:export-skf",
"file:export-stl",
"file:export-3mf",
"file:export-step",
+ "file:export-ifc",
"file:export-obj",
"file:export-glb",
"file:export-dxf",
@@ -115,6 +117,10 @@ const VALID_DESKTOP_MENU_ACTIONS = new Set([
"tool:walk",
"tool:wall-opening",
"tool:terrain",
+ "tool:bim-studio",
+ "tool:bim-storeys",
+ "tool:bim-boq",
+ "tool:bim-code-audit",
"tool:structural-test",
"tool:ar-preview",
"tool:physics-toggle",
@@ -160,6 +166,7 @@ const GLOBAL_DESKTOP_MENU_ACTIONS = new Set([
"file:save",
"file:save-as",
"file:save-and-quit",
+ "file:save-and-update",
"file:import",
"file:dashboard",
"window:drawing",
@@ -290,6 +297,44 @@ export function formatFriendlyUpdateError(rawMessage?: unknown): string {
return text;
}
+/**
+ * Formats byte counts into compact Turkish size strings (KB / MB / GB).
+ */
+export function formatUpdateBytes(rawBytes: number): string {
+ const bytes = Number.isFinite(rawBytes) && rawBytes > 0 ? rawBytes : 0;
+ if (bytes < 1024) return `${Math.round(bytes)} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(bytes < 10 * 1024 ? 1 : 0)} KB`;
+ if (bytes < 1024 * 1024 * 1024) return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
+}
+
+/**
+ * Formats live updater download transfer progress and throughput telemetry.
+ */
+export function formatUpdateTransferSummary(
+ state?: {
+ transferred?: number;
+ total?: number;
+ bytesPerSecond?: number;
+ } | null,
+): string {
+ if (!state) return "";
+ const transferred = Number(state.transferred ?? 0);
+ const total = Number(state.total ?? 0);
+ const bytesPerSecond = Number(state.bytesPerSecond ?? 0);
+ const parts: string[] = [];
+ if (total > 0) {
+ const clampedTransferred = Math.min(Math.max(0, transferred), total);
+ parts.push(`${formatUpdateBytes(clampedTransferred)} / ${formatUpdateBytes(total)}`);
+ } else if (transferred > 0) {
+ parts.push(`${formatUpdateBytes(transferred)} indirildi`);
+ }
+ if (bytesPerSecond > 0) {
+ parts.push(`${formatUpdateBytes(bytesPerSecond)}/sn`);
+ }
+ return parts.join(" • ");
+}
+
/**
* Builds Electron file-dialog extension filters from a suggested filename.
*/
diff --git a/apps/web/src/lib/exportNames.ts b/apps/web/src/lib/exportNames.ts
index 40fe7ca..5d0eddc 100644
--- a/apps/web/src/lib/exportNames.ts
+++ b/apps/web/src/lib/exportNames.ts
@@ -1,4 +1,4 @@
-export type ProjectExportFormat = "3mf" | "stl" | "obj" | "step" | "dxf" | "svg" | "glb" | "skf";
+export type ProjectExportFormat = "3mf" | "stl" | "obj" | "step" | "ifc" | "dxf" | "svg" | "glb" | "skf";
export function projectExportFileName(projectName: string, format: ProjectExportFormat) {
const safeProjectName = projectName
diff --git a/apps/web/src/lib/ifcExport.ts b/apps/web/src/lib/ifcExport.ts
new file mode 100644
index 0000000..68c93eb
--- /dev/null
+++ b/apps/web/src/lib/ifcExport.ts
@@ -0,0 +1,550 @@
+import type { WorkplaneShape } from "@/types/sketchforge";
+
+export type IfcBimEntityClass =
+ | "IFCWALL"
+ | "IFCSLAB"
+ | "IFCCOLUMN"
+ | "IFCBEAM"
+ | "IFCROOF"
+ | "IFCSTAIR"
+ | "IFCRAILING"
+ | "IFCWINDOW"
+ | "IFCDOOR"
+ | "IFCFURNISHINGELEMENT"
+ | "IFCBUILDINGELEMENTPROXY";
+
+export interface IfcExportOptions {
+ projectName?: string;
+ authorName?: string;
+ organizationName?: string;
+ siteName?: string;
+ buildingName?: string;
+ scaleFactorToMm?: number;
+}
+
+export interface IfcExportSummary {
+ ifcText: string;
+ bytes: Uint8Array;
+ productCount: number;
+ storeyCount: number;
+ entityBreakdown: Record;
+}
+
+const IFC_GUID_CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$";
+
+/**
+ * Generates a deterministic 22-character IFC GloballyUniqueId (Base64-64) from a seed string.
+ */
+export function makeIfcGuid(seed: string): string {
+ let h1 = 0x811c9dc5;
+ let h2 = 0x01000193;
+ for (let i = 0; i < seed.length; i++) {
+ const code = seed.charCodeAt(i);
+ h1 ^= code;
+ h1 = Math.imul(h1, 0x01000193);
+ h2 ^= code + i * 31;
+ h2 = Math.imul(h2, 0x85ebca6b);
+ }
+ const chars: string[] = [];
+ for (let i = 0; i < 22; i++) {
+ const mixed = Math.abs(Math.imul(h1 ^ (h2 >>> (i % 16)), i + 17) + i * 97);
+ const idx = i === 0 ? mixed % 4 : mixed % 64;
+ chars.push(IFC_GUID_CHARS[idx]);
+ }
+ return chars.join("");
+}
+
+/**
+ * Escapes text for STEP ISO-10303-21 strings (ASCII-safe with Turkish character transliteration fallback).
+ */
+function escapeStepString(input: string): string {
+ return input
+ .replace(/\\/g, "\\\\")
+ .replace(/'/g, "''")
+ .replace(/ğ/g, "g")
+ .replace(/Ğ/g, "G")
+ .replace(/ü/g, "u")
+ .replace(/Ü/g, "U")
+ .replace(/ş/g, "s")
+ .replace(/Ş/g, "S")
+ .replace(/ı/g, "i")
+ .replace(/İ/g, "I")
+ .replace(/ö/g, "o")
+ .replace(/Ö/g, "O")
+ .replace(/ç/g, "c")
+ .replace(/Ç/g, "C");
+}
+
+function fmtNum(val: number): string {
+ if (!Number.isFinite(val)) return "0.";
+ const rounded = Number(val.toFixed(4));
+ if (Number.isInteger(rounded)) return `${rounded}.`;
+ return String(rounded);
+}
+
+function hexToRgb01(hex: string | undefined): [number, number, number] {
+ const clean = (hex || "#94a3b8").replace("#", "").trim();
+ if (clean.length !== 6) return [0.58, 0.64, 0.72];
+ const r = parseInt(clean.slice(0, 2), 16);
+ const g = parseInt(clean.slice(2, 4), 16);
+ const b = parseInt(clean.slice(4, 6), 16);
+ if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) {
+ return [0.58, 0.64, 0.72];
+ }
+ return [
+ Number((r / 255).toFixed(3)),
+ Number((g / 255).toFixed(3)),
+ Number((b / 255).toFixed(3)),
+ ];
+}
+
+/**
+ * Classifies a WorkplaneShape into an IFC4 BIM Entity Class based on its tag, name, and geometry.
+ */
+export function classifyShapeForIfc(shape: WorkplaneShape): IfcBimEntityClass {
+ const haystack = `${shape.tag || ""} ${shape.name || ""} ${shape.kind || ""}`.toLocaleLowerCase("tr-TR");
+
+ if (haystack.includes("duvar") || haystack.includes("wall") || haystack.includes("parapet") || haystack.includes("bölme")) {
+ return "IFCWALL";
+ }
+ if (haystack.includes("çatı") || haystack.includes("cati") || haystack.includes("roof") || shape.kind === "roundRoof") {
+ return "IFCROOF";
+ }
+ if (
+ haystack.includes("döşeme") ||
+ haystack.includes("doseme") ||
+ haystack.includes("zemin") ||
+ haystack.includes("tabliye") ||
+ haystack.includes("slab") ||
+ haystack.includes("teras") ||
+ haystack.includes("sahanlık")
+ ) {
+ return "IFCSLAB";
+ }
+ if (haystack.includes("kolon") || haystack.includes("column") || haystack.includes("dikme") || haystack.includes("pilon")) {
+ return "IFCCOLUMN";
+ }
+ if (haystack.includes("kiriş") || haystack.includes("kiris") || haystack.includes("beam") || haystack.includes("makas") || haystack.includes("truss") || haystack.includes("lento")) {
+ return "IFCBEAM";
+ }
+ if (haystack.includes("merdiven") || haystack.includes("basamak") || haystack.includes("stair") || haystack.includes("rampa")) {
+ return "IFCSTAIR";
+ }
+ if (haystack.includes("korkuluk") || haystack.includes("küpeşte") || haystack.includes("kupeste") || haystack.includes("railing") || haystack.includes("balustrade")) {
+ return "IFCRAILING";
+ }
+ if (haystack.includes("pencere") || haystack.includes("window") || haystack.includes("cam") || haystack.includes("doğrama")) {
+ return "IFCWINDOW";
+ }
+ if (haystack.includes("kapı") || haystack.includes("kapi") || haystack.includes("door")) {
+ return "IFCDOOR";
+ }
+ if (
+ haystack.includes("mobilya") ||
+ haystack.includes("tefriş") ||
+ haystack.includes("koltuk") ||
+ haystack.includes("masa") ||
+ haystack.includes("sandalye") ||
+ haystack.includes("yatak") ||
+ haystack.includes("dolap") ||
+ haystack.includes("mutfak") ||
+ haystack.includes("banyo")
+ ) {
+ return "IFCFURNISHINGELEMENT";
+ }
+
+ // Heuristic fallback for untagged architectural slabs vs walls
+ const w = Math.max(1, shape.width);
+ const d = Math.max(1, shape.depth);
+ const h = Math.max(1, shape.height);
+ if (shape.kind === "box") {
+ if (h <= Math.min(w, d) * 0.2 && Math.max(w, d) >= 40) {
+ return "IFCSLAB";
+ }
+ if (Math.min(w, d) <= Math.max(w, d) * 0.25 && h >= Math.min(w, d) * 2) {
+ return "IFCWALL";
+ }
+ }
+ if (shape.kind === "cylinder" && h >= Math.max(w, d) * 2.5) {
+ return "IFCCOLUMN";
+ }
+
+ return "IFCBUILDINGELEMENTPROXY";
+}
+
+function inferStoreyInfo(shape: WorkplaneShape, scaleFactorToMm: number): { key: string; name: string; elevationMm: number } {
+ const tag = (shape.tag || "").trim();
+ const tagLower = tag.toLocaleLowerCase("tr-TR");
+ const elevMm = Math.round((shape.elevation || 0) * scaleFactorToMm);
+
+ if (tagLower.includes("bodrum")) {
+ return { key: "storey-basement", name: "Bodrum Kat", elevationMm: Math.min(0, elevMm) };
+ }
+ if (tagLower.includes("zemin")) {
+ return { key: "storey-ground", name: "Zemin Kat", elevationMm: 0 };
+ }
+ const floorMatch = tag.match(/(\d+)\.\s*(normal\s*)?kat/i);
+ if (floorMatch) {
+ const floorNum = parseInt(floorMatch[1], 10);
+ return {
+ key: `storey-${floorNum}`,
+ name: `${floorNum}. Normal Kat`,
+ elevationMm: floorNum * 3000,
+ };
+ }
+ if (tagLower.includes("çatı kat") || tagLower.includes("teras kat")) {
+ return { key: "storey-roof", name: "Cati Kati", elevationMm: Math.max(3000, elevMm) };
+ }
+
+ // Group by elevation bands (every 3000 mm in 1:1 scale, or 36 units in 1:100 maket scale)
+ const rawElev = shape.elevation || 0;
+ if (rawElev < -1) {
+ return { key: "storey-basement", name: "Bodrum Kat", elevationMm: elevMm };
+ }
+ const bandHeight = scaleFactorToMm > 10 ? 32 : 3000;
+ const floorIdx = Math.max(0, Math.floor(rawElev / bandHeight));
+ if (floorIdx === 0) {
+ return { key: "storey-ground", name: "Zemin Kat", elevationMm: 0 };
+ }
+ return {
+ key: `storey-${floorIdx}`,
+ name: `${floorIdx}. Normal Kat`,
+ elevationMm: Math.round(floorIdx * bandHeight * scaleFactorToMm),
+ };
+}
+
+/**
+ * Exports active 3D shapes into a standards-compliant ISO-10303-21 IFC4 BIM model.
+ * Compatible with web-ifc, Autodesk Revit, Graphisoft ArchiCAD, Tekla, FreeCAD, and BlenderBIM.
+ */
+export function exportShapesToIfc4(
+ shapes: WorkplaneShape[],
+ options: IfcExportOptions = {},
+): IfcExportSummary {
+ const solidShapes = shapes.filter((s) => !s.hole && !s.hidden);
+ if (solidShapes.length === 0) {
+ throw new Error("IFC4 dışa aktarımı için sahnede en az bir görünür katı (solid) nesne bulunmalıdır.");
+ }
+
+ const projectName = escapeStepString(options.projectName?.trim() || "SnapCAD Mimari BIM Projesi");
+ const authorName = escapeStepString(options.authorName?.trim() || "SnapCAD Architect");
+ const organizationName = escapeStepString(options.organizationName?.trim() || "SnapCAD Studio");
+ const siteName = escapeStepString(options.siteName?.trim() || "Proje Arsasi");
+ const buildingName = escapeStepString(options.buildingName?.trim() || "Ana Bina");
+ const scale = options.scaleFactorToMm && options.scaleFactorToMm > 0 ? options.scaleFactorToMm : 1;
+
+ let nextId = 1;
+ const lines: string[] = [];
+ const addEntity = (definition: string): number => {
+ const id = nextId++;
+ lines.push(`#${id}=${definition};`);
+ return id;
+ };
+
+ // 1. Ownership & Context
+ const personId = addEntity(`IFCPERSON($,$,'${authorName}',$,$,$,$,$)`);
+ const orgId = addEntity(`IFCORGANIZATION($,'${organizationName}',$,$,$)`);
+ const personOrgId = addEntity(`IFCPERSONANDORGANIZATION(#${personId},#${orgId},$)`);
+ const appId = addEntity(`IFCAPPLICATION(#${orgId},'1.0.11','SnapCAD Studio','SnapCAD_IFC4')`);
+ const ownerHistoryId = addEntity(`IFCOWNERHISTORY(#${personOrgId},#${appId},$,.NOCHANGE.,$,$,$,1700000000)`);
+
+ const origin3dId = addEntity(`IFCCARTESIANPOINT((0.,0.,0.))`);
+ const dirZId = addEntity(`IFCDIRECTION((0.,0.,1.))`);
+ const dirXId = addEntity(`IFCDIRECTION((1.,0.,0.))`);
+ const dirYId = addEntity(`IFCDIRECTION((0.,1.,0.))`);
+ const worldPlacement3dId = addEntity(`IFCAXIS2PLACEMENT3D(#${origin3dId},#${dirZId},#${dirXId})`);
+ const origin2dId = addEntity(`IFCCARTESIANPOINT((0.,0.))`);
+ const placement2dId = addEntity(`IFCAXIS2PLACEMENT2D(#${origin2dId},$)`);
+
+ const geomContextId = addEntity(
+ `IFCGEOMETRICREPRESENTATIONCONTEXT($,'Model',3,1.E-05,#${worldPlacement3dId},$)`,
+ );
+
+ // Units: Millimetre, Square Metre, Cubic Metre, Radian
+ const lengthUnitId = addEntity(`IFCSIUNIT(*,.LENGTHUNIT.,.MILLI.,.METRE.)`);
+ const areaUnitId = addEntity(`IFCSIUNIT(*,.AREAUNIT.,$,.SQUARE_METRE.)`);
+ const volumeUnitId = addEntity(`IFCSIUNIT(*,.VOLUMEUNIT.,$,.CUBIC_METRE.)`);
+ const angleUnitId = addEntity(`IFCSIUNIT(*,.PLANEANGLEUNIT.,$,.RADIAN.)`);
+ const unitAssignmentId = addEntity(
+ `IFCUNITASSIGNMENT((#${lengthUnitId},#${areaUnitId},#${volumeUnitId},#${angleUnitId}))`,
+ );
+
+ const projectId = addEntity(
+ `IFCPROJECT('${makeIfcGuid(`project:${projectName}`)}',#${ownerHistoryId},'${projectName}','SnapCAD Studio IFC4 BIM Export',$,$,$,(#${geomContextId}),#${unitAssignmentId})`,
+ );
+
+ // Spatial Hierarchy: Project -> Site -> Building -> Storeys
+ const sitePlacementId = addEntity(`IFCLOCALPLACEMENT($,#${worldPlacement3dId})`);
+ const siteId = addEntity(
+ `IFCSITE('${makeIfcGuid(`site:${siteName}`)}',#${ownerHistoryId},'${siteName}',$,$,#${sitePlacementId},$,$,.ELEMENT.,$,$,$,$,$)`,
+ );
+
+ const buildingPlacementId = addEntity(`IFCLOCALPLACEMENT(#${sitePlacementId},#${worldPlacement3dId})`);
+ const buildingId = addEntity(
+ `IFCBUILDING('${makeIfcGuid(`building:${buildingName}`)}',#${ownerHistoryId},'${buildingName}',$,$,#${buildingPlacementId},$,$,.ELEMENT.,$,$,$)`,
+ );
+
+ addEntity(
+ `IFCRELAGGREGATES('${makeIfcGuid("rel:project-site")}',#${ownerHistoryId},'ProjectToSite',$,#${projectId},(#${siteId}))`,
+ );
+ addEntity(
+ `IFCRELAGGREGATES('${makeIfcGuid("rel:site-building")}',#${ownerHistoryId},'SiteToBuilding',$,#${siteId},(#${buildingId}))`,
+ );
+
+ // Group shapes by storey
+ const storeyMap = new Map<
+ string,
+ { key: string; name: string; elevationMm: number; productIds: number[]; storeyEntityId?: number }
+ >();
+
+ const entityBreakdown: Record = {
+ IFCWALL: 0,
+ IFCSLAB: 0,
+ IFCCOLUMN: 0,
+ IFCBEAM: 0,
+ IFCROOF: 0,
+ IFCSTAIR: 0,
+ IFCRAILING: 0,
+ IFCWINDOW: 0,
+ IFCDOOR: 0,
+ IFCFURNISHINGELEMENT: 0,
+ IFCBUILDINGELEMENTPROXY: 0,
+ };
+
+ for (let idx = 0; idx < solidShapes.length; idx++) {
+ const shape = solidShapes[idx];
+ const ifcClass = classifyShapeForIfc(shape);
+ entityBreakdown[ifcClass] += 1;
+
+ const storeyInfo = inferStoreyInfo(shape, scale);
+ let storeyRecord = storeyMap.get(storeyInfo.key);
+ if (!storeyRecord) {
+ storeyRecord = {
+ ...storeyInfo,
+ productIds: [],
+ };
+ storeyMap.set(storeyInfo.key, storeyRecord);
+ }
+
+ const widthMm = Math.max(1, shape.width * scale);
+ const depthMm = Math.max(1, shape.depth * scale);
+ const heightMm = Math.max(1, shape.height * scale);
+ const centerXMm = (shape.x || 0) * scale;
+ // Note: in IFC, X-Y is ground plane and +Z is vertical elevation!
+ // In SketchForge, X-Z is ground plane and +Y (elevation) is vertical!
+ const centerYMm = -(shape.z || 0) * scale;
+ const baseElevationMm = (shape.elevation || 0) * scale;
+
+ const rotDeg = shape.rotation || 0;
+ const rotRad = (-rotDeg * Math.PI) / 180;
+ const cosR = Math.cos(rotRad);
+ const sinR = Math.sin(rotRad);
+
+ const locPointId = addEntity(
+ `IFCCARTESIANPOINT((${fmtNum(centerXMm)},${fmtNum(centerYMm)},${fmtNum(baseElevationMm)}))`,
+ );
+ const refDirId =
+ Math.abs(rotDeg) > 0.001
+ ? addEntity(`IFCDIRECTION((${fmtNum(cosR)},${fmtNum(sinR)},0.))`)
+ : dirXId;
+ const axis3dId = addEntity(`IFCAXIS2PLACEMENT3D(#${locPointId},#${dirZId},#${refDirId})`);
+ const localPlacementId = addEntity(`IFCLOCALPLACEMENT(#${buildingPlacementId},#${axis3dId})`);
+
+ // Build Solid Representation:
+ // Use CircleProfileDef for cylinders, or FacetedBrep for custom imported meshes ( up to 400 triangles ), or RectangleProfileDef
+ let solidItemId: number;
+ let representationType = "SweptSolid";
+
+ const meshPositions = shape.importedMesh?.positions;
+ if (
+ meshPositions &&
+ meshPositions.length >= 9 &&
+ meshPositions.length <= 3600 &&
+ meshPositions.length % 9 === 0
+ ) {
+ // Export as IFCFACETEDBREP for exact custom mesh topology (e.g., roofs, terrain, custom extrusions)
+ const faceIds: number[] = [];
+ const scaleX = (shape.width / Math.max(1e-3, shape.importedMesh?.baseWidth || shape.width)) * scale;
+ const scaleY = (shape.depth / Math.max(1e-3, shape.importedMesh?.baseDepth || shape.depth)) * scale;
+ const scaleZ = (shape.height / Math.max(1e-3, shape.importedMesh?.baseHeight || shape.height)) * scale;
+
+ for (let t = 0; t < meshPositions.length; t += 9) {
+ // Convert local SketchForge (x, y=up, z) -> IFC local (x, -z, y=up)
+ const p1Id = addEntity(
+ `IFCCARTESIANPOINT((${fmtNum(meshPositions[t] * scaleX)},${fmtNum(-meshPositions[t + 2] * scaleY)},${fmtNum(meshPositions[t + 1] * scaleZ)}))`,
+ );
+ const p2Id = addEntity(
+ `IFCCARTESIANPOINT((${fmtNum(meshPositions[t + 3] * scaleX)},${fmtNum(-meshPositions[t + 5] * scaleY)},${fmtNum(meshPositions[t + 4] * scaleZ)}))`,
+ );
+ const p3Id = addEntity(
+ `IFCCARTESIANPOINT((${fmtNum(meshPositions[t + 6] * scaleX)},${fmtNum(-meshPositions[t + 8] * scaleY)},${fmtNum(meshPositions[t + 7] * scaleZ)}))`,
+ );
+ const loopId = addEntity(`IFCPOLYLOOP((#${p1Id},#${p2Id},#${p3Id}))`);
+ const boundId = addEntity(`IFCFACEOUTERBOUND(#${loopId},.T.)`);
+ const faceId = addEntity(`IFCFACE((#${boundId}))`);
+ faceIds.push(faceId);
+ }
+ const shellId = addEntity(`IFCCLOSEDSHELL((${faceIds.map((id) => `#${id}`).join(",")}))`);
+ solidItemId = addEntity(`IFCFACETEDBREP(#${shellId})`);
+ representationType = "Brep";
+ } else if (shape.kind === "cylinder" || shape.kind === "cone" || shape.kind === "sphere") {
+ const radiusMm = Math.max(0.5, Math.min(widthMm, depthMm) / 2);
+ const profileId = addEntity(`IFCCIRCLEPROFILEDEF(.AREA.,$,#${placement2dId},${fmtNum(radiusMm)})`);
+ solidItemId = addEntity(
+ `IFCEXTRUDEDAREASOLID(#${profileId},#${worldPlacement3dId},#${dirZId},${fmtNum(heightMm)})`,
+ );
+ } else {
+ const profileId = addEntity(
+ `IFCRECTANGLEPROFILEDEF(.AREA.,$,#${placement2dId},${fmtNum(widthMm)},${fmtNum(depthMm)})`,
+ );
+ solidItemId = addEntity(
+ `IFCEXTRUDEDAREASOLID(#${profileId},#${worldPlacement3dId},#${dirZId},${fmtNum(heightMm)})`,
+ );
+ }
+
+ // Surface color style
+ const [r, g, b] = hexToRgb01(shape.color);
+ const colId = addEntity(`IFCCOLOURRGB($,${fmtNum(r)},${fmtNum(g)},${fmtNum(b)})`);
+ const renderingId = addEntity(
+ `IFCSURFACESTYLERENDERING(#${colId},0.,$,$,$,$,$,$,.NOTDEFINED.)`,
+ );
+ const surfStyleId = addEntity(`IFCSURFACESTYLE('${escapeStepString(shape.name || "Style")}',.BOTH.,(#${renderingId}))`);
+ addEntity(`IFCSTYLEDITEM(#${solidItemId},(#${surfStyleId}),$)`);
+
+ const shapeRepId = addEntity(
+ `IFCSHAPEREPRESENTATION(#${geomContextId},'Body','${representationType}',(#${solidItemId}))`,
+ );
+ const prodDefShapeId = addEntity(`IFCPRODUCTDEFINITIONSHAPE($,$,(#${shapeRepId}))`);
+
+ const safeName = escapeStepString(shape.name || `Eleman_${idx + 1}`);
+ const safeTag = escapeStepString(shape.tag || "Genel");
+ const guid = makeIfcGuid(`shape:${shape.id || idx}:${safeName}`);
+
+ let productId: number;
+ switch (ifcClass) {
+ case "IFCWALL":
+ productId = addEntity(
+ `IFCWALL('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}',.STANDARD.)`,
+ );
+ break;
+ case "IFCSLAB":
+ productId = addEntity(
+ `IFCSLAB('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}',.FLOOR.)`,
+ );
+ break;
+ case "IFCCOLUMN":
+ productId = addEntity(
+ `IFCCOLUMN('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}',.COLUMN.)`,
+ );
+ break;
+ case "IFCBEAM":
+ productId = addEntity(
+ `IFCBEAM('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}',.BEAM.)`,
+ );
+ break;
+ case "IFCROOF":
+ productId = addEntity(
+ `IFCROOF('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}',.GABLE_ROOF.)`,
+ );
+ break;
+ case "IFCSTAIR":
+ productId = addEntity(
+ `IFCSTAIR('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}',.STRAIGHT_RUN_STAIR.)`,
+ );
+ break;
+ case "IFCRAILING":
+ productId = addEntity(
+ `IFCRAILING('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}',.BALUSTRADE.)`,
+ );
+ break;
+ case "IFCWINDOW":
+ productId = addEntity(
+ `IFCWINDOW('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}',${fmtNum(heightMm)},${fmtNum(widthMm)},.WINDOW.,.SINGLE_PANEL.,$)`,
+ );
+ break;
+ case "IFCDOOR":
+ productId = addEntity(
+ `IFCDOOR('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}',${fmtNum(heightMm)},${fmtNum(widthMm)},.DOOR.,.SINGLE_SWING_LEFT.,$)`,
+ );
+ break;
+ case "IFCFURNISHINGELEMENT":
+ productId = addEntity(
+ `IFCFURNISHINGELEMENT('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}')`,
+ );
+ break;
+ default:
+ productId = addEntity(
+ `IFCBUILDINGELEMENTPROXY('${guid}',#${ownerHistoryId},'${safeName}','${safeTag}',$,#${localPlacementId},#${prodDefShapeId},'${shape.id}',.ELEMENT.)`,
+ );
+ break;
+ }
+
+ // Attach Base Quantities (BIM 5D Metraj: Area m², Volume m³, Length mm)
+ const footprintAreaM2 = (widthMm * depthMm) / 1_000_000;
+ const sideAreaM2 = (Math.max(widthMm, depthMm) * heightMm) / 1_000_000;
+ const volumeM3 = (widthMm * depthMm * heightMm) / 1_000_000_000;
+
+ const qLenId = addEntity(`IFCQUANTITYLENGTH('Length',$,$,${fmtNum(Math.max(widthMm, depthMm))},$)`);
+ const qHeightId = addEntity(`IFCQUANTITYLENGTH('Height',$,$,${fmtNum(heightMm)},$)`);
+ const qAreaId = addEntity(
+ `IFCQUANTITYAREA('${ifcClass === "IFCWALL" ? "NetSideArea" : "GrossFloorArea"}',$,$,${fmtNum(ifcClass === "IFCWALL" ? sideAreaM2 : footprintAreaM2)},$)`,
+ );
+ const qVolId = addEntity(`IFCQUANTITYVOLUME('NetVolume',$,$,${fmtNum(volumeM3)},$)`);
+ const elemQtyId = addEntity(
+ `IFCELEMENTQUANTITY('${makeIfcGuid(`qto:${shape.id || idx}`)}',#${ownerHistoryId},'BaseQuantities',$,'SnapCAD_BOQ',(#${qLenId},#${qHeightId},#${qAreaId},#${qVolId}))`,
+ );
+ addEntity(
+ `IFCRELDEFINESBYPROPERTIES('${makeIfcGuid(`relqto:${shape.id || idx}`)}',#${ownerHistoryId},'QuantityLink',$,(#${productId}),#${elemQtyId})`,
+ );
+
+ storeyRecord.productIds.push(productId);
+ }
+
+ // Emit IfcBuildingStorey entities and link products
+ const storeyEntityIds: number[] = [];
+ const sortedStoreys = Array.from(storeyMap.values()).sort((a, b) => a.elevationMm - b.elevationMm);
+ for (const st of sortedStoreys) {
+ const stPointId = addEntity(`IFCCARTESIANPOINT((0.,0.,${fmtNum(st.elevationMm)}))`);
+ const stAxisId = addEntity(`IFCAXIS2PLACEMENT3D(#${stPointId},#${dirZId},#${dirXId})`);
+ const stPlacementId = addEntity(`IFCLOCALPLACEMENT(#${buildingPlacementId},#${stAxisId})`);
+ const stEntityId = addEntity(
+ `IFCBUILDINGSTOREY('${makeIfcGuid(`storey:${st.key}`)}',#${ownerHistoryId},'${escapeStepString(st.name)}',$,$,#${stPlacementId},$,$,.ELEMENT.,${fmtNum(st.elevationMm)})`,
+ );
+ storeyEntityIds.push(stEntityId);
+
+ if (st.productIds.length > 0) {
+ addEntity(
+ `IFCRELCONTAINEDINSPATIALSTRUCTURE('${makeIfcGuid(`relspatial:${st.key}`)}',#${ownerHistoryId},'StoreyContainer',$,(${st.productIds.map((id) => `#${id}`).join(",")}),#${stEntityId})`,
+ );
+ }
+ }
+
+ if (storeyEntityIds.length > 0) {
+ addEntity(
+ `IFCRELAGGREGATES('${makeIfcGuid("rel:building-storeys")}',#${ownerHistoryId},'BuildingToStoreys',$,#${buildingId},(${storeyEntityIds.map((id) => `#${id}`).join(",")}))`,
+ );
+ }
+
+ const timestampIso = new Date().toISOString().slice(0, 19);
+ const header = [
+ "ISO-10303-21;",
+ "HEADER;",
+ "FILE_DESCRIPTION(('ViewDefinition [CoordinationView_V2.0]'),'2;1');",
+ `FILE_NAME('${projectName}.ifc','${timestampIso}',('${authorName}'),('${organizationName}'),'SnapCAD Studio 1.0.11','SnapCAD IFC4 BIM Engine','');`,
+ "FILE_SCHEMA(('IFC4'));",
+ "ENDSEC;",
+ "DATA;",
+ ];
+
+ const footer = ["ENDSEC;", "END-ISO-10303-21;", ""];
+ const ifcText = [...header, ...lines, ...footer].join("\n");
+ const bytes = new TextEncoder().encode(ifcText);
+
+ return {
+ ifcText,
+ bytes,
+ productCount: solidShapes.length,
+ storeyCount: sortedStoreys.length,
+ entityBreakdown,
+ };
+}
diff --git a/apps/web/src/lib/serviceWorker.ts b/apps/web/src/lib/serviceWorker.ts
index 10841f2..445e5db 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.1";
+export const SERVICE_WORKER_VERSION = "1.2.2";
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 afb8c65..4c04dd0 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 = process.env.NEXT_PUBLIC_APP_VERSION?.trim() || "1.0.10";
+export const SKF_CREATED_WITH_VERSION = process.env.NEXT_PUBLIC_APP_VERSION?.trim() || "1.0.11";
export const SKF_MEDIA_TYPE = "application/vnd.sketchforge.project+zip";
export const SKF_LIMITS = {
diff --git a/apps/web/src/lib/snapcadPrefabs.ts b/apps/web/src/lib/snapcadPrefabs.ts
index 0a28cc9..0a675a7 100644
--- a/apps/web/src/lib/snapcadPrefabs.ts
+++ b/apps/web/src/lib/snapcadPrefabs.ts
@@ -1232,4 +1232,420 @@ export const SNAPCAD_PREFABS: SnapCadPrefabItem[] = [
}),
],
},
+ {
+ id: "arch-l-sofa-living-set",
+ title: "Modern L-Koltuk & Orta Sehpa Salon Tefrişi",
+ category: "architecture",
+ categoryLabel: "Mimari Tefrişat",
+ description: "Salon ve yaşam alanları için ölçekli L-köşe koltuk grubu, sırt minderleri ve mermer orta sehpa.",
+ badge: "Salon Tefrişi",
+ accentColor: "#8b5cf6",
+ buildShapes: () => [
+ makePrimitive("box", {
+ name: "L-Koltuk Ana Oturum Modülü",
+ color: "#475569",
+ width: 30,
+ depth: 10,
+ height: 4.5,
+ x: 0,
+ z: -5,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("box", {
+ name: "L-Koltuk Uzanma (Chaise) Modülü",
+ color: "#475569",
+ width: 10,
+ depth: 20,
+ height: 4.5,
+ x: 10,
+ z: 0,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("box", {
+ name: "Koltuk Sırt Dayama Gövdesi",
+ color: "#334155",
+ width: 30,
+ depth: 2.5,
+ height: 8.5,
+ x: 0,
+ z: -8.8,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("box", {
+ name: "Mermer Salon Orta Sehpası",
+ color: "#e2e8f0",
+ texture: "marble",
+ width: 12,
+ depth: 7,
+ height: 3.8,
+ x: -4,
+ z: 5,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ ],
+ },
+ {
+ id: "arch-kitchen-island-set",
+ title: "Ada Mutfak Tezgahı, Evye & Bar Tabureleri",
+ category: "architecture",
+ categoryLabel: "Mimari Tefrişat",
+ description: "Mermer tablalı mutfak adası, evye oyuğu, ankastre bazası ve 3 adet yüksek bar taburesi.",
+ badge: "Mutfak Tefrişi",
+ accentColor: "#0ea5e9",
+ buildShapes: () => [
+ makePrimitive("box", {
+ name: "Ada Mutfak Dolap Gövdesi",
+ color: "#1e293b",
+ width: 28,
+ depth: 11,
+ height: 8.5,
+ x: 0,
+ z: 0,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("box", {
+ name: "Mermer Ada Mutfak Tezgahı",
+ color: "#f8fafc",
+ texture: "marble",
+ width: 30,
+ depth: 13,
+ height: 1.0,
+ x: 0,
+ z: 0.5,
+ elevation: 8.5,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("box", {
+ name: "Çelik Mutfak Evyesi Boşluğu",
+ color: "#64748b",
+ hole: true,
+ width: 7,
+ depth: 5,
+ height: 3.5,
+ x: -6,
+ z: -0.5,
+ elevation: 7.0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("cylinder", {
+ name: "Bar Taburesi 1",
+ color: "#d97706",
+ width: 4,
+ depth: 4,
+ height: 6.5,
+ x: -8,
+ z: 9,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("cylinder", {
+ name: "Bar Taburesi 2",
+ color: "#d97706",
+ width: 4,
+ depth: 4,
+ height: 6.5,
+ x: 0,
+ z: 9,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("cylinder", {
+ name: "Bar Taburesi 3",
+ color: "#d97706",
+ width: 4,
+ depth: 4,
+ height: 6.5,
+ x: 8,
+ z: 9,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ ],
+ },
+ {
+ id: "arch-master-bedroom-suite",
+ title: "Çift Kişilik Yatak, Komodin & Sürgülü Gardırop",
+ category: "architecture",
+ categoryLabel: "Mimari Tefrişat",
+ description: "Ebeveyn yatak odası için yatak karyolası, başlık, iki yan komodin ve boy gardırop modülü.",
+ badge: "Yatak Odası",
+ accentColor: "#ec4899",
+ buildShapes: () => [
+ makePrimitive("box", {
+ name: "Çift Kişilik Yatak Bazası",
+ color: "#78350f",
+ texture: "wood",
+ width: 18,
+ depth: 21,
+ height: 3.5,
+ x: -6,
+ z: 0,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("box", {
+ name: "Ortopedik Yatak Şiltesi",
+ color: "#f8fafc",
+ width: 16.5,
+ depth: 19.5,
+ height: 2.2,
+ x: -6,
+ z: 0.4,
+ elevation: 3.5,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("box", {
+ name: "Kapitone Yatak Başlığı",
+ color: "#334155",
+ width: 18.5,
+ depth: 1.6,
+ height: 11.5,
+ x: -6,
+ z: -10,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("box", {
+ name: "Sol Komodin",
+ color: "#78350f",
+ texture: "wood",
+ width: 5,
+ depth: 4.5,
+ height: 5,
+ x: -18.5,
+ z: -8.5,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("box", {
+ name: "Sağ Komodin",
+ color: "#78350f",
+ texture: "wood",
+ width: 5,
+ depth: 4.5,
+ height: 5,
+ x: 6.5,
+ z: -8.5,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ makePrimitive("box", {
+ name: "Sürgülü Boy Gardırop",
+ color: "#e2e8f0",
+ width: 24,
+ depth: 6.5,
+ height: 22,
+ x: 18,
+ z: -6,
+ elevation: 0,
+ tag: "Mobilyalar",
+ }),
+ ],
+ },
+ {
+ id: "arch-bioclimatic-pergola",
+ title: "Biyoklimatik Teras Pergola & Güneş Kırıcı Veranda",
+ category: "architecture",
+ categoryLabel: "Mimari & Peyzaj",
+ description: "Alüminyum taşıyıcı kolonlar, çevre kirişleri ve döner güneş kırıcı lamel tavanlı modern pergola.",
+ badge: "Pergola & Veranda",
+ accentColor: "#f59e0b",
+ buildShapes: () => {
+ const shapes: WorkplaneShape[] = [
+ makePrimitive("box", {
+ name: "Pergola Kolon Sol-Ön",
+ color: "#1e293b",
+ width: 2.5,
+ depth: 2.5,
+ height: 26,
+ x: -20,
+ z: 14,
+ elevation: 0,
+ tag: "Kolon",
+ }),
+ makePrimitive("box", {
+ name: "Pergola Kolon Sağ-Ön",
+ color: "#1e293b",
+ width: 2.5,
+ depth: 2.5,
+ height: 26,
+ x: 20,
+ z: 14,
+ elevation: 0,
+ tag: "Kolon",
+ }),
+ makePrimitive("box", {
+ name: "Pergola Kolon Sol-Arka",
+ color: "#1e293b",
+ width: 2.5,
+ depth: 2.5,
+ height: 26,
+ x: -20,
+ z: -14,
+ elevation: 0,
+ tag: "Kolon",
+ }),
+ makePrimitive("box", {
+ name: "Pergola Kolon Sağ-Arka",
+ color: "#1e293b",
+ width: 2.5,
+ depth: 2.5,
+ height: 26,
+ x: 20,
+ z: -14,
+ elevation: 0,
+ tag: "Kolon",
+ }),
+ makePrimitive("box", {
+ name: "Pergola Ön Kiriş",
+ color: "#334155",
+ width: 42.5,
+ depth: 2.5,
+ height: 2.8,
+ x: 0,
+ z: 14,
+ elevation: 25,
+ tag: "Kiriş",
+ }),
+ makePrimitive("box", {
+ name: "Pergola Arka Kiriş",
+ color: "#334155",
+ width: 42.5,
+ depth: 2.5,
+ height: 2.8,
+ x: 0,
+ z: -14,
+ elevation: 25,
+ tag: "Kiriş",
+ }),
+ ];
+ for (let i = -3; i <= 3; i++) {
+ shapes.push(
+ makePrimitive("box", {
+ name: `Biyoklimatik Lamel ${i + 4}`,
+ color: "#d97706",
+ texture: "wood",
+ width: 39,
+ depth: 2.4,
+ height: 0.9,
+ x: 0,
+ z: i * 3.8,
+ elevation: 26.2,
+ tag: "Çatı",
+ }),
+ );
+ }
+ return shapes;
+ },
+ },
+ {
+ id: "arch-landscape-trees-park",
+ title: "Mimari Peyzaj Seti (Çam Ağacı, Yapraklı Ağaç & Aydınlatma)",
+ category: "architecture",
+ categoryLabel: "Mimari & Peyzaj",
+ description: "Vaziyet planı ve dış mekan maketleri için ağaçlar, peyzaj aydınlatma direği ve bahçe oturma bankı.",
+ badge: "Vaziyet & Peyzaj",
+ accentColor: "#16a34a",
+ buildShapes: () => [
+ makePrimitive("cylinder", {
+ name: "Yapraklı Ağaç Gövdesi",
+ color: "#78350f",
+ texture: "wood",
+ width: 3.5,
+ depth: 3.5,
+ height: 14,
+ x: -16,
+ z: 0,
+ elevation: 0,
+ tag: "Peyzaj",
+ }),
+ makePrimitive("sphere", {
+ name: "Yapraklı Ağaç Taç Kısmı",
+ color: "#16a34a",
+ texture: "grass",
+ width: 18,
+ depth: 18,
+ height: 16,
+ x: -16,
+ z: 0,
+ elevation: 11,
+ tag: "Peyzaj",
+ }),
+ makePrimitive("cylinder", {
+ name: "Çam Ağacı Gövdesi",
+ color: "#78350f",
+ texture: "wood",
+ width: 3,
+ depth: 3,
+ height: 10,
+ x: 16,
+ z: -4,
+ elevation: 0,
+ tag: "Peyzaj",
+ }),
+ makePrimitive("cone", {
+ name: "Çam Ağacı Alt İğne Yaprak",
+ color: "#15803d",
+ texture: "grass",
+ width: 16,
+ depth: 16,
+ height: 18,
+ x: 16,
+ z: -4,
+ elevation: 8,
+ tag: "Peyzaj",
+ }),
+ makePrimitive("cone", {
+ name: "Çam Ağacı Üst İğne Yaprak",
+ color: "#22c55e",
+ texture: "grass",
+ width: 11,
+ depth: 11,
+ height: 14,
+ x: 16,
+ z: -4,
+ elevation: 18,
+ tag: "Peyzaj",
+ }),
+ makePrimitive("box", {
+ name: "Ahşap Bahçe Bankı",
+ color: "#b45309",
+ texture: "wood",
+ width: 14,
+ depth: 4.5,
+ height: 4.5,
+ x: 0,
+ z: 8,
+ elevation: 0,
+ tag: "Peyzaj",
+ }),
+ makePrimitive("cylinder", {
+ name: "Peyzaj Sokak Lambası Direği",
+ color: "#334155",
+ width: 1.4,
+ depth: 1.4,
+ height: 24,
+ x: 0,
+ z: -8,
+ elevation: 0,
+ tag: "Peyzaj",
+ }),
+ makePrimitive("sphere", {
+ name: "LED Armatür Küresi",
+ color: "#fef08a",
+ width: 4,
+ depth: 4,
+ height: 4,
+ x: 0,
+ z: -8,
+ elevation: 23,
+ tag: "Peyzaj",
+ }),
+ ],
+ },
];
diff --git a/apps/web/src/lib/solarSystem.ts b/apps/web/src/lib/solarSystem.ts
index 05cfc98..e252aa3 100644
--- a/apps/web/src/lib/solarSystem.ts
+++ b/apps/web/src/lib/solarSystem.ts
@@ -1,21 +1,173 @@
-import * as suncalcModule from "suncalc";
+import { getPosition, getTimes } from "suncalc";
-const SunCalc = (suncalcModule as any).getPosition ? suncalcModule : (suncalcModule as any).default;
+export type Ts825ThermalZone = 1 | 2 | 3 | 4 | 5;
+
+export interface Ts825ZoneStandard {
+ zone: Ts825ThermalZone;
+ label: string;
+ climateSummary: string;
+ recommendedWallU: number; // W/(m²·K)
+ recommendedRoofU: number; // W/(m²·K)
+ recommendedFloorU: number; // W/(m²·K)
+ recommendedWindowU: number; // W/(m²·K)
+ minInsulationThicknessMm: number;
+}
+
+export const TS825_ZONE_STANDARDS: Record = {
+ 1: {
+ zone: 1,
+ label: "1. Derece Gün Bölgesi (Akdeniz & Güney Kıyı)",
+ climateSummary: "Kışları ılık, yazları sıcak; güneş kontrolü ve gölgeleme önceliklidir.",
+ recommendedWallU: 0.66,
+ recommendedRoofU: 0.43,
+ recommendedFloorU: 0.66,
+ recommendedWindowU: 1.8,
+ minInsulationThicknessMm: 50,
+ },
+ 2: {
+ zone: 2,
+ label: "2. Derece Gün Bölgesi (Marmara, Ege & Karadeniz Kıyı)",
+ climateSummary: "Ilıman geçiş iklimi; ısı yalıtımı ve batı/güney güneş kırıcı dengesi önemlidir.",
+ recommendedWallU: 0.57,
+ recommendedRoofU: 0.38,
+ recommendedFloorU: 0.57,
+ recommendedWindowU: 1.8,
+ minInsulationThicknessMm: 60,
+ },
+ 3: {
+ zone: 3,
+ label: "3. Derece Gün Bölgesi (İç Anadolu & Geçiş Kuşağı)",
+ climateSummary: "Karasal iklim; kış ısı kaybını azaltan güney yönelim ve orta-kalın manto gerekir.",
+ recommendedWallU: 0.48,
+ recommendedRoofU: 0.28,
+ recommendedFloorU: 0.43,
+ recommendedWindowU: 1.8,
+ minInsulationThicknessMm: 80,
+ },
+ 4: {
+ zone: 4,
+ label: "4. Derece Gün Bölgesi (Soğuk Karasal & Yüksek Rakım)",
+ climateSummary: "Sert kış koşulları; yüksek performanslı dış cephe mantolama ve üçlü cam önerilir.",
+ recommendedWallU: 0.38,
+ recommendedRoofU: 0.23,
+ recommendedFloorU: 0.38,
+ recommendedWindowU: 1.6,
+ minInsulationThicknessMm: 100,
+ },
+ 5: {
+ zone: 5,
+ label: "5. Derece Gün Bölgesi (Doğu Anadolu Sert Kış Bölgesi)",
+ climateSummary: "Çok soğuk kış iklimi; kompakt bina formu, ısı köprüsüz detay ve maksimum yalıtım şarttır.",
+ recommendedWallU: 0.36,
+ recommendedRoofU: 0.21,
+ recommendedFloorU: 0.36,
+ recommendedWindowU: 1.4,
+ minInsulationThicknessMm: 120,
+ },
+};
export interface SolarLocation {
name: string;
lat: number;
lng: number;
+ plateCode?: string;
+ ts825Zone?: Ts825ThermalZone;
+ utcOffsetHours?: number;
}
+export const TURKEY_81_PROVINCES_SOLAR_LOCATIONS: SolarLocation[] = [
+ { plateCode: "01", name: "01 Adana, Türkiye (37.0° K)", lat: 37.0, lng: 35.3213, ts825Zone: 1, utcOffsetHours: 3 },
+ { plateCode: "02", name: "02 Adıyaman, Türkiye (37.8° K)", lat: 37.7648, lng: 38.2786, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "03", name: "03 Afyonkarahisar, Türkiye (38.8° K)", lat: 38.7507, lng: 30.5567, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "04", name: "04 Ağrı, Türkiye (39.7° K)", lat: 39.7191, lng: 43.0503, ts825Zone: 5, utcOffsetHours: 3 },
+ { plateCode: "05", name: "05 Amasya, Türkiye (40.7° K)", lat: 40.6499, lng: 35.8353, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "06", name: "06 Ankara, Türkiye (39.9° K)", lat: 39.9334, lng: 32.8597, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "07", name: "07 Antalya, Türkiye (36.9° K)", lat: 36.8969, lng: 30.7133, ts825Zone: 1, utcOffsetHours: 3 },
+ { plateCode: "08", name: "08 Artvin, Türkiye (41.2° K)", lat: 41.1828, lng: 41.8183, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "09", name: "09 Aydın, Türkiye (37.8° K)", lat: 37.856, lng: 27.8416, ts825Zone: 1, utcOffsetHours: 3 },
+ { plateCode: "10", name: "10 Balıkesir, Türkiye (39.6° K)", lat: 39.6484, lng: 27.8826, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "11", name: "11 Bilecik, Türkiye (40.1° K)", lat: 40.1451, lng: 29.9799, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "12", name: "12 Bingöl, Türkiye (38.9° K)", lat: 38.8854, lng: 40.498, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "13", name: "13 Bitlis, Türkiye (38.4° K)", lat: 38.4006, lng: 42.1095, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "14", name: "14 Bolu, Türkiye (40.7° K)", lat: 40.7392, lng: 31.6089, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "15", name: "15 Burdur, Türkiye (37.7° K)", lat: 37.7203, lng: 30.2908, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "16", name: "16 Bursa, Türkiye (40.2° K)", lat: 40.1885, lng: 29.061, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "17", name: "17 Çanakkale, Türkiye (40.2° K)", lat: 40.1553, lng: 26.4142, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "18", name: "18 Çankırı, Türkiye (40.6° K)", lat: 40.6013, lng: 33.6134, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "19", name: "19 Çorum, Türkiye (40.5° K)", lat: 40.5506, lng: 34.9556, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "20", name: "20 Denizli, Türkiye (37.8° K)", lat: 37.7765, lng: 29.0864, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "21", name: "21 Diyarbakır, Türkiye (37.9° K)", lat: 37.9144, lng: 40.2306, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "22", name: "22 Edirne, Türkiye (41.7° K)", lat: 41.6818, lng: 26.5623, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "23", name: "23 Elazığ, Türkiye (38.7° K)", lat: 38.681, lng: 39.2264, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "24", name: "24 Erzincan, Türkiye (39.7° K)", lat: 39.75, lng: 39.5, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "25", name: "25 Erzurum, Türkiye (39.9° K)", lat: 39.9, lng: 41.27, ts825Zone: 5, utcOffsetHours: 3 },
+ { plateCode: "26", name: "26 Eskişehir, Türkiye (39.8° K)", lat: 39.7767, lng: 30.5206, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "27", name: "27 Gaziantep, Türkiye (37.1° K)", lat: 37.0662, lng: 37.3833, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "28", name: "28 Giresun, Türkiye (40.9° K)", lat: 40.9128, lng: 38.3895, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "29", name: "29 Gümüşhane, Türkiye (40.5° K)", lat: 40.4603, lng: 39.4814, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "30", name: "30 Hakkari, Türkiye (37.6° K)", lat: 37.5833, lng: 43.7333, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "31", name: "31 Hatay, Türkiye (36.2° K)", lat: 36.2021, lng: 36.1606, ts825Zone: 1, utcOffsetHours: 3 },
+ { plateCode: "32", name: "32 Isparta, Türkiye (37.8° K)", lat: 37.7648, lng: 30.5566, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "33", name: "33 Mersin, Türkiye (36.8° K)", lat: 36.8, lng: 34.6333, ts825Zone: 1, utcOffsetHours: 3 },
+ { plateCode: "34", name: "34 İstanbul, Türkiye (41.0° K)", lat: 41.0082, lng: 28.9784, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "35", name: "35 İzmir, Türkiye (38.4° K)", lat: 38.4237, lng: 27.1428, ts825Zone: 1, utcOffsetHours: 3 },
+ { plateCode: "36", name: "36 Kars, Türkiye (40.6° K)", lat: 40.6013, lng: 43.0975, ts825Zone: 5, utcOffsetHours: 3 },
+ { plateCode: "37", name: "37 Kastamonu, Türkiye (41.4° K)", lat: 41.3887, lng: 33.7827, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "38", name: "38 Kayseri, Türkiye (38.7° K)", lat: 38.7312, lng: 35.4787, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "39", name: "39 Kırklareli, Türkiye (41.7° K)", lat: 41.7333, lng: 27.2167, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "40", name: "40 Kırşehir, Türkiye (39.1° K)", lat: 39.1425, lng: 34.1709, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "41", name: "41 Kocaeli, Türkiye (40.8° K)", lat: 40.7654, lng: 29.9408, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "42", name: "42 Konya, Türkiye (37.9° K)", lat: 37.8667, lng: 32.4833, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "43", name: "43 Kütahya, Türkiye (39.4° K)", lat: 39.4167, lng: 29.9833, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "44", name: "44 Malatya, Türkiye (38.4° K)", lat: 38.3552, lng: 38.3095, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "45", name: "45 Manisa, Türkiye (38.6° K)", lat: 38.6191, lng: 27.4289, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "46", name: "46 Kahramanmaraş, Türkiye (37.6° K)", lat: 37.5858, lng: 36.9371, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "47", name: "47 Mardin, Türkiye (37.3° K)", lat: 37.3212, lng: 40.7245, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "48", name: "48 Muğla, Türkiye (37.2° K)", lat: 37.2153, lng: 28.3636, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "49", name: "49 Muş, Türkiye (38.7° K)", lat: 38.7432, lng: 41.5065, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "50", name: "50 Nevşehir, Türkiye (38.6° K)", lat: 38.6244, lng: 34.7239, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "51", name: "51 Niğde, Türkiye (38.0° K)", lat: 37.9667, lng: 34.6833, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "52", name: "52 Ordu, Türkiye (41.0° K)", lat: 40.9839, lng: 37.8764, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "53", name: "53 Rize, Türkiye (41.0° K)", lat: 41.0201, lng: 40.5234, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "54", name: "54 Sakarya, Türkiye (40.8° K)", lat: 40.7569, lng: 30.3783, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "55", name: "55 Samsun, Türkiye (41.3° K)", lat: 41.2867, lng: 36.33, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "56", name: "56 Siirt, Türkiye (37.9° K)", lat: 37.9333, lng: 41.95, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "57", name: "57 Sinop, Türkiye (42.0° K)", lat: 42.0231, lng: 35.1531, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "58", name: "58 Sivas, Türkiye (39.7° K)", lat: 39.7477, lng: 37.0179, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "59", name: "59 Tekirdağ, Türkiye (41.0° K)", lat: 40.9833, lng: 27.5167, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "60", name: "60 Tokat, Türkiye (40.3° K)", lat: 40.3167, lng: 36.55, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "61", name: "61 Trabzon, Türkiye (41.0° K)", lat: 41.0015, lng: 39.7178, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "62", name: "62 Tunceli, Türkiye (39.1° K)", lat: 39.1079, lng: 39.5401, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "63", name: "63 Şanlıurfa, Türkiye (37.2° K)", lat: 37.1591, lng: 38.7969, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "64", name: "64 Uşak, Türkiye (38.7° K)", lat: 38.6823, lng: 29.4082, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "65", name: "65 Van, Türkiye (38.5° K)", lat: 38.4891, lng: 43.4089, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "66", name: "66 Yozgat, Türkiye (39.8° K)", lat: 39.8181, lng: 34.8147, ts825Zone: 4, utcOffsetHours: 3 },
+ { plateCode: "67", name: "67 Zonguldak, Türkiye (41.5° K)", lat: 41.4564, lng: 31.7987, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "68", name: "68 Aksaray, Türkiye (38.4° K)", lat: 38.3687, lng: 34.037, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "69", name: "69 Bayburt, Türkiye (40.3° K)", lat: 40.2552, lng: 40.2249, ts825Zone: 5, utcOffsetHours: 3 },
+ { plateCode: "70", name: "70 Karaman, Türkiye (37.2° K)", lat: 37.1759, lng: 33.2287, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "71", name: "71 Kırıkkale, Türkiye (39.8° K)", lat: 39.8468, lng: 33.5153, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "72", name: "72 Batman, Türkiye (37.9° K)", lat: 37.8812, lng: 41.1351, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "73", name: "73 Şırnak, Türkiye (37.5° K)", lat: 37.5164, lng: 42.4611, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "74", name: "74 Bartın, Türkiye (41.6° K)", lat: 41.6344, lng: 32.3375, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "75", name: "75 Ardahan, Türkiye (41.1° K)", lat: 41.1105, lng: 42.7022, ts825Zone: 5, utcOffsetHours: 3 },
+ { plateCode: "76", name: "76 Iğdır, Türkiye (39.9° K)", lat: 39.9167, lng: 44.0333, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "77", name: "77 Yalova, Türkiye (40.7° K)", lat: 40.65, lng: 29.2667, ts825Zone: 2, utcOffsetHours: 3 },
+ { plateCode: "78", name: "78 Karabük, Türkiye (41.2° K)", lat: 41.2061, lng: 32.6204, ts825Zone: 3, utcOffsetHours: 3 },
+ { plateCode: "79", name: "79 Kilis, Türkiye (36.7° K)", lat: 36.7184, lng: 37.1212, ts825Zone: 1, utcOffsetHours: 3 },
+ { plateCode: "80", name: "80 Osmaniye, Türkiye (37.1° K)", lat: 37.0742, lng: 36.2478, ts825Zone: 1, utcOffsetHours: 3 },
+ { plateCode: "81", name: "81 Düzce, Türkiye (40.8° K)", lat: 40.8438, lng: 31.1565, ts825Zone: 2, utcOffsetHours: 3 },
+];
+
export const SOLAR_LOCATIONS: SolarLocation[] = [
- { name: "İstanbul, Türkiye (41.0° K)", lat: 41.0082, lng: 28.9784 },
- { name: "Ankara, Türkiye (39.9° K)", lat: 39.9334, lng: 32.8597 },
- { name: "İzmir, Türkiye (38.4° K)", lat: 38.4237, lng: 27.1428 },
- { name: "Londra, İngiltere (51.5° K)", lat: 51.5074, lng: -0.1278 },
- { name: "New York, ABD (40.7° K)", lat: 40.7128, lng: -74.006 },
- { name: "Tokyo, Japonya (35.7° K)", lat: 35.6762, lng: 139.6503 },
- { name: "Dubai, BAE (25.2° K)", lat: 25.2048, lng: 55.2708 },
+ { name: "İstanbul, Türkiye (41.0° K)", lat: 41.0082, lng: 28.9784, plateCode: "34", ts825Zone: 2, utcOffsetHours: 3 },
+ { name: "Ankara, Türkiye (39.9° K)", lat: 39.9334, lng: 32.8597, plateCode: "06", ts825Zone: 3, utcOffsetHours: 3 },
+ { name: "İzmir, Türkiye (38.4° K)", lat: 38.4237, lng: 27.1428, plateCode: "35", ts825Zone: 1, utcOffsetHours: 3 },
+ { name: "Londra, İngiltere (51.5° K)", lat: 51.5074, lng: -0.1278, utcOffsetHours: 0 },
+ { name: "New York, ABD (40.7° K)", lat: 40.7128, lng: -74.006, utcOffsetHours: -5 },
+ { name: "Tokyo, Japonya (35.7° K)", lat: 35.6762, lng: 139.6503, utcOffsetHours: 9 },
+ { name: "Dubai, BAE (25.2° K)", lat: 25.2048, lng: 55.2708, utcOffsetHours: 4 },
+ ...TURKEY_81_PROVINCES_SOLAR_LOCATIONS,
];
export interface SolarStudySettings {
@@ -48,6 +200,38 @@ export interface CalculatedSunPosition {
intensity: number;
}
+export interface DailySolarSweepPoint {
+ hour: number;
+ timeLabel: string;
+ altitudeDegrees: number;
+ azimuthDegrees: number;
+ isDaylight: boolean;
+ lightVector: [number, number, number];
+}
+
+export interface FacadeInsolationSummary {
+ northHours: number;
+ eastHours: number;
+ southHours: number;
+ westHours: number;
+ peakAltitudeDegrees: number;
+ sunriseTime: string;
+ solarNoonTime: string;
+ sunsetTime: string;
+ daylightDurationHours: number;
+ shadingRecommendation: string;
+ ts825Standard: Ts825ZoneStandard;
+ hourlyPoints: DailySolarSweepPoint[];
+}
+
+function formatUtcDateAtOffset(date: Date | null | undefined, utcOffsetHours: number): string {
+ if (!date || Number.isNaN(date.getTime())) return "--:--";
+ const shifted = new Date(date.getTime() + utcOffsetHours * 3600_000);
+ const hh = String(shifted.getUTCHours()).padStart(2, "0");
+ const mm = String(shifted.getUTCMinutes()).padStart(2, "0");
+ return `${hh}:${mm}`;
+}
+
/**
* Calculates real-world solar angles, color temperature, and 3D light vector.
*/
@@ -57,10 +241,10 @@ export function calculateSunPosition(settings: SolarStudySettings): CalculatedSu
const hourInt = Math.floor(settings.hour);
const minute = Math.round((settings.hour - hourInt) * 60);
- // UTC approx: Turkey is UTC+3
+ // UTC approx: default Turkey UTC+3
const date = new Date(Date.UTC(year, settings.month, settings.day, hourInt - 3, minute));
- const sunPos = SunCalc.getPosition(date, loc.lat, loc.lng);
+ const sunPos = getPosition(date, loc.lat, loc.lng);
const altitudeDegrees = Number(sunPos.altitude.toFixed(1));
const azimuthDegrees = Number((((sunPos.azimuth % 360) + 360) % 360).toFixed(1));
@@ -110,3 +294,88 @@ export function calculateSunPosition(settings: SolarStudySettings): CalculatedSu
intensity,
};
}
+
+/**
+ * Full-day solar trajectory sweep & facade direct sunlight (N/E/S/W) + TS 825 thermal evaluation.
+ */
+export function calculateDailySolarSweep(
+ settings: SolarStudySettings,
+ stepMinutes = 30,
+): FacadeInsolationSummary {
+ const loc = SOLAR_LOCATIONS[settings.locationIndex] ?? SOLAR_LOCATIONS[0];
+ const utcOffsetHours = loc.utcOffsetHours ?? 3;
+ const ts825Zone: Ts825ThermalZone = loc.ts825Zone ?? 2;
+ const ts825Standard = TS825_ZONE_STANDARDS[ts825Zone];
+
+ const refDate = new Date(Date.UTC(2026, settings.month, settings.day, 12 - utcOffsetHours, 0));
+ const times = getTimes(refDate, loc.lat, loc.lng);
+
+ const stepHours = Math.max(0.25, stepMinutes / 60);
+ let northHours = 0;
+ let eastHours = 0;
+ let southHours = 0;
+ let westHours = 0;
+ let daylightDurationHours = 0;
+ let peakAltitudeDegrees = -90;
+
+ const hourlyPoints: DailySolarSweepPoint[] = [];
+
+ for (let hour = 5.0; hour <= 21.0 + 1e-6; hour += stepHours) {
+ const pos = calculateSunPosition({ ...settings, hour });
+ const hInt = Math.floor(hour);
+ const mInt = Math.round((hour - hInt) * 60);
+ const timeLabel = `${String(hInt).padStart(2, "0")}:${String(mInt).padStart(2, "0")}`;
+
+ if (pos.altitudeDegrees > peakAltitudeDegrees) {
+ peakAltitudeDegrees = pos.altitudeDegrees;
+ }
+
+ if (Math.abs(hour - Math.round(hour)) < 0.01) {
+ hourlyPoints.push({
+ hour: Number(hour.toFixed(2)),
+ timeLabel,
+ altitudeDegrees: pos.altitudeDegrees,
+ azimuthDegrees: pos.azimuthDegrees,
+ isDaylight: pos.isDaylight,
+ lightVector: pos.lightVector,
+ });
+ }
+
+ if (pos.altitudeDegrees > 2) {
+ daylightDurationHours += stepHours;
+ // Azimuth in SunCalc v2: 0=North, 90=East, 180=South, 270=West
+ const azRad = (pos.azimuthDegrees * Math.PI) / 180;
+ const dirNorth = Math.cos(azRad);
+ const dirEast = Math.sin(azRad);
+ const dirSouth = -Math.cos(azRad);
+ const dirWest = -Math.sin(azRad);
+
+ if (dirNorth > 0.15) northHours += stepHours;
+ if (dirEast > 0.15) eastHours += stepHours;
+ if (dirSouth > 0.15) southHours += stepHours;
+ if (dirWest > 0.15) westHours += stepHours;
+ }
+ }
+
+ const shadingRecommendation =
+ peakAltitudeDegrees >= 60
+ ? "Güney cephede yatay güneş kırıcı (brise-soleil / saçak), Batı ve Doğu cephelerde dikey hareketli panjur önerilir."
+ : peakAltitudeDegrees >= 40
+ ? "Mevsim geçişi açısı: Güney pencerelerde kış güneş kazancını koruyan orta derinlikli saçak (60-80 cm) idealdir."
+ : "Düşük kış güneşi açısı: Güney cephede maksimum pasif güneş kazancı sağlanmalı, Kuzey cephe açıklıkları minimize edilmelidir.";
+
+ return {
+ northHours: Number(northHours.toFixed(1)),
+ eastHours: Number(eastHours.toFixed(1)),
+ southHours: Number(southHours.toFixed(1)),
+ westHours: Number(westHours.toFixed(1)),
+ peakAltitudeDegrees: Number(peakAltitudeDegrees.toFixed(1)),
+ sunriseTime: formatUtcDateAtOffset(times.sunrise, utcOffsetHours),
+ solarNoonTime: formatUtcDateAtOffset(times.solarNoon, utcOffsetHours),
+ sunsetTime: formatUtcDateAtOffset(times.sunset, utcOffsetHours),
+ daylightDurationHours: Number(daylightDurationHours.toFixed(1)),
+ shadingRecommendation,
+ ts825Standard,
+ hourlyPoints,
+ };
+}
diff --git a/apps/web/src/lib/yaknetWidgetHelpers.ts b/apps/web/src/lib/yaknetWidgetHelpers.ts
new file mode 100644
index 0000000..fe51bbd
--- /dev/null
+++ b/apps/web/src/lib/yaknetWidgetHelpers.ts
@@ -0,0 +1,82 @@
+export interface YakNetWidgetUser {
+ id: number;
+ name: string;
+ email: string;
+ avatar?: string | null;
+ auth_source?: string;
+}
+
+export const YAKNET_OAUTH_CLIENT_ID = "01a1315f-9db9-70ee-9983-0d3397773ecd";
+export const YAKNET_CALLBACK_URI = "https://snap.yakhub.com.tr/callback.php";
+export const YAKNET_AUTH_BASE = "https://developer-console.yakhub.com.tr";
+export const YAKNET_CDN_ORIGIN = "https://cdnjs.yakhub.com.tr";
+export const YAKNET_ACCOUNT_CDN_URL = `${YAKNET_CDN_ORIGIN}/ajax/libs/yaknet-account/latest/yaknet-account.js`;
+export const YAKNET_ACCOUNT_SCRIPT_ID = "yaknet-account-cdn-script";
+export const YAKNET_SSO_IFRAME_ID = "yaknet-sso-iframe-instance";
+export const YAKNET_WEB_SESSION_HINT_KEY = "snapcad.yaknet.sessionHint.v1";
+
+export function sanitizeYakNetWidgetUser(raw: unknown): YakNetWidgetUser | null {
+ if (!raw || typeof raw !== "object") return null;
+ const candidate = raw as Record;
+ const id = Number(candidate.id ?? 0);
+ const name = typeof candidate.name === "string" ? candidate.name.trim() : "";
+ const email = typeof candidate.email === "string" ? candidate.email.trim() : "";
+ if (!Number.isFinite(id) || id <= 0 || !name) return null;
+ return {
+ id: Math.round(id),
+ name: name.slice(0, 255),
+ email: email.slice(0, 255),
+ avatar: typeof candidate.avatar === "string" ? candidate.avatar.slice(0, 512) : null,
+ auth_source: typeof candidate.auth_source === "string" ? candidate.auth_source.slice(0, 64) : undefined,
+ };
+}
+
+export function computeUserInitials(rawName?: string | null): string {
+ const parts = String(rawName ?? "")
+ .trim()
+ .split(/\s+/)
+ .filter(Boolean);
+ if (parts.length === 0) return "YN";
+ const first = parts[0].slice(0, 1).toUpperCase();
+ const second = parts.length > 1 ? parts[parts.length - 1].slice(0, 1).toUpperCase() : "";
+ return `${first}${second}` || "YN";
+}
+
+export function resolveYakNetWidgetAttributes({
+ user,
+ sessionResolved,
+ theme = "light",
+}: {
+ user: YakNetWidgetUser | null;
+ sessionResolved: boolean;
+ theme?: "light" | "dark" | "auto";
+}): Record {
+ return {
+ "base-url": YAKNET_AUTH_BASE,
+ "client-id": YAKNET_OAUTH_CLIENT_ID,
+ "redirect-uri": YAKNET_CALLBACK_URI,
+ "login-url": "/login.php",
+ "logout-url": "/logout.php",
+ theme,
+ authenticated: user ? "true" : sessionResolved ? "false" : null,
+ "user-name": user ? user.name : null,
+ "user-email": user ? user.email || "" : null,
+ };
+}
+
+export function shouldSuppressUnauthenticatedSsoMessage({
+ isDesktop,
+ sessionResolved,
+ hasAuthenticatedUser,
+ ssoFrameHadAuthenticated,
+}: {
+ isDesktop: boolean;
+ sessionResolved: boolean;
+ hasAuthenticatedUser: boolean;
+ ssoFrameHadAuthenticated: boolean;
+}): boolean {
+ if (isDesktop) return true;
+ if (!sessionResolved) return true;
+ if (hasAuthenticatedUser && !ssoFrameHadAuthenticated) return true;
+ return false;
+}
diff --git a/apps/web/src/types/desktop.d.ts b/apps/web/src/types/desktop.d.ts
index 2f98660..950146d 100644
--- a/apps/web/src/types/desktop.d.ts
+++ b/apps/web/src/types/desktop.d.ts
@@ -47,6 +47,36 @@ export type DesktopYakNetAuthEvent = {
error?: string;
};
+export type DesktopAuthStateSnapshot = {
+ authenticated: boolean;
+ user: DesktopYakNetUser | null;
+};
+
+export type DesktopActiveWorkKind =
+ | "none"
+ | "3d-project"
+ | "drawing-studio"
+ | "circuits-studio"
+ | "codeblocks-studio";
+
+export type DesktopActiveWorkState = {
+ hasOpenWork: boolean;
+ workKind: DesktopActiveWorkKind;
+ projectName: string | null;
+ shapeCount: number;
+ hasDiskFile: boolean;
+ diskFileName: string | null;
+ hasUnsavedDiskChanges: boolean;
+ pendingLocalSaveCount: number;
+};
+
+export type DesktopPreUpdatePrepareResult = DesktopActiveWorkState & {
+ localSaved: boolean;
+ cloudAttempted: boolean;
+ cloudSynced: boolean;
+ cloudStatusText: string;
+};
+
export type DesktopCloudRequestOptions = {
path: string;
method?: string;
@@ -68,12 +98,14 @@ export type DesktopMenuAction =
| "file:save"
| "file:save-as"
| "file:save-and-quit"
+ | "file:save-and-update"
| "file:import"
| "file:export-panel"
| "file:export-skf"
| "file:export-stl"
| "file:export-3mf"
| "file:export-step"
+ | "file:export-ifc"
| "file:export-obj"
| "file:export-glb"
| "file:export-dxf"
@@ -174,6 +206,10 @@ export type DesktopMenuAction =
| "tool:walk"
| "tool:wall-opening"
| "tool:terrain"
+ | "tool:bim-studio"
+ | "tool:bim-storeys"
+ | "tool:bim-boq"
+ | "tool:bim-code-audit"
| "tool:structural-test"
| "tool:ar-preview"
| "tool:physics-toggle"
@@ -251,10 +287,13 @@ export type SnapCadDesktopBridge = {
installUpdate: () => Promise;
getUpdateState?: () => Promise;
onUpdateState?: (listener: (state: DesktopUpdateResult) => void) => () => void;
+ onOpenUpdateProgress?: (listener: (state: DesktopUpdateResult) => void) => () => void;
getDesktopPrefs?: () => Promise;
setDesktopPrefs?: (patch: Partial) => Promise;
hideToTray?: () => Promise;
onDesktopPrefsChanged?: (listener: (prefs: DesktopPreferences) => void) => () => void;
+ getAuthStateSync?: () => DesktopAuthStateSnapshot;
+ getAuthState?: () => Promise;
startYakNetLogin?: () => Promise<{ started: boolean; error?: string }>;
logoutYakNet?: () => Promise<{ ok: boolean; error?: string }>;
cloudRequest?: (options: DesktopCloudRequestOptions) => Promise;
@@ -277,7 +316,12 @@ export type SnapCadDesktopBridge = {
setMenuState?: (state: Partial) => Promise;
setDirty?: (dirty: boolean) => Promise;
setWindowTitle?: (title: string) => Promise;
+ setActiveWorkState?: (state: DesktopActiveWorkState) => Promise;
+ onPrepareBeforeUpdate?: (listener: (requestId: string) => void) => () => void;
+ sendPrepareBeforeUpdateResult?: (requestId: string, result: DesktopPreUpdatePrepareResult) => Promise;
confirmCloseAfterSave?: () => Promise;
+ confirmUpdateAfterSave?: () => Promise;
+ cancelPendingUpdateInstall?: () => Promise;
openExternal?: (url: string) => Promise;
};
@@ -285,5 +329,6 @@ declare global {
interface Window {
snapcadDesktop?: SnapCadDesktopBridge;
sketchforgeDesktop?: SnapCadDesktopBridge;
+ __snapcadInitialSessionPromise?: Promise;
}
}
diff --git a/package-lock.json b/package-lock.json
index f87db4a..32c1cec 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "sketchforge",
- "version": "1.0.10",
+ "version": "1.0.11",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "sketchforge",
- "version": "1.0.10",
+ "version": "1.0.11",
"license": "AGPL-3.0-only",
"dependencies": {
"@mlightcad/libredwg-web": "^0.8.2",
@@ -48,13 +48,16 @@
"devDependencies": {
"@types/bezier-js": "^4.1.3",
"@types/canvas-confetti": "^1.9.0",
+ "@types/delaunator": "^5.0.3",
"@types/node": "^22.15.18",
"@types/react": "^19.1.4",
"@types/react-dom": "^19.1.5",
+ "delaunator": "^5.1.0",
"electron": "^43.4.0",
"electron-builder": "^26.15.3",
"js-yaml": "^4.3.1",
"playwright": "^1.64.1",
+ "simplex-noise": "^4.0.3",
"typescript": "^5.8.3",
"vitest": "^4.1.8"
}
@@ -2105,6 +2108,13 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/@types/delaunator": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/@types/delaunator/-/delaunator-5.0.3.tgz",
+ "integrity": "sha512-6tTLP8NX0OwtB/fmW9bXp4EWPptawTSsrSGjboWRuzqkxNEEJGyzRPHbr8wnV2DBWfAZ+EPTOvW3B/KysJrl2g==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/estree": {
"version": "1.0.10",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.10.tgz",
@@ -3382,6 +3392,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/delaunator": {
+ "version": "5.1.0",
+ "resolved": "https://registry.npmjs.org/delaunator/-/delaunator-5.1.0.tgz",
+ "integrity": "sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "robust-predicates": "^3.0.2"
+ }
+ },
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
@@ -6357,6 +6377,13 @@
"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==",
+ "dev": true,
+ "license": "Unlicense"
+ },
"node_modules/rolldown": {
"version": "1.2.18",
"resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.18.tgz",
@@ -6575,6 +6602,13 @@
"node": ">=10"
}
},
+ "node_modules/simplex-noise": {
+ "version": "4.0.3",
+ "resolved": "https://registry.npmjs.org/simplex-noise/-/simplex-noise-4.0.3.tgz",
+ "integrity": "sha512-qSE2I4AngLQG7BXqoZj51jokT4WUXe8mOBrvfOXpci8+6Yu44+/dD5zqDpOx3Ux792eamTd2lLcI8jqFntk/lg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
diff --git a/package.json b/package.json
index 103e1b2..1df5a0e 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "sketchforge",
- "version": "1.0.10",
+ "version": "1.0.11",
"private": true,
"description": "SnapCAD Studio — YakHub local-first 3D CAD, architecture and circuits platform.",
"author": {
@@ -86,13 +86,16 @@
"devDependencies": {
"@types/bezier-js": "^4.1.3",
"@types/canvas-confetti": "^1.9.0",
+ "@types/delaunator": "^5.0.3",
"@types/node": "^22.15.18",
"@types/react": "^19.1.4",
"@types/react-dom": "^19.1.5",
+ "delaunator": "^5.1.0",
"electron": "^43.4.0",
"electron-builder": "^26.15.3",
"js-yaml": "^4.3.1",
"playwright": "^1.64.1",
+ "simplex-noise": "^4.0.3",
"typescript": "^5.8.3",
"vitest": "^4.1.8"
}
diff --git a/tests/unit/architecturalBimEngine.test.ts b/tests/unit/architecturalBimEngine.test.ts
new file mode 100644
index 0000000..0d60a32
--- /dev/null
+++ b/tests/unit/architecturalBimEngine.test.ts
@@ -0,0 +1,188 @@
+import { describe, expect, it } from "vitest";
+import { exportShapesToIfc4, classifyShapeForIfc } from "@/lib/ifcExport";
+import { importedShapeWithDetailsFromIfc } from "@/lib/ifcImport";
+import {
+ DEFAULT_BUILDING_STOREYS,
+ calculateArchitecturalBoq,
+ exportBoqToCsv,
+ exportBoqToPdfBytes,
+ auditArchitecturalCodeCompliance,
+ isolateStoreyVisibility,
+ duplicateStoreyToLevel,
+ generateParametricStair,
+ generateParametricRoof,
+ generateParametricOpeningUnit,
+ generateStructuralFrameGrid,
+ generateAdvancedTerrainWithPad,
+} from "@/lib/architecturalBimEngine";
+import {
+ TURKEY_81_PROVINCES_SOLAR_LOCATIONS,
+ SOLAR_LOCATIONS,
+ DEFAULT_SOLAR_SETTINGS,
+ calculateDailySolarSweep,
+} from "@/lib/solarSystem";
+import { SNAPCAD_PREFABS } from "@/lib/snapcadPrefabs";
+
+describe("Architectural BIM Engine, IFC4 Export, BOQ Metraj & Code Auditor", () => {
+ it("exports 3D architectural shapes to IFC4 and round-trips through web-ifc WASM", async () => {
+ const villaPrefab = SNAPCAD_PREFABS.find((p) => p.id === "modern-terrace-villa");
+ expect(villaPrefab).toBeDefined();
+ const shapes = villaPrefab!.buildShapes();
+
+ const exported = exportShapesToIfc4(shapes, {
+ projectName: "Modern Terasli Villa",
+ scaleFactorToMm: 100, // 1:100 architectural scale -> real millimeters
+ });
+
+ expect(exported.ifcText).toContain("FILE_SCHEMA(('IFC4'));");
+ expect(exported.ifcText).toContain("IFCPROJECT(");
+ expect(exported.ifcText).toContain("IFCBUILDINGSTOREY(");
+ expect(exported.ifcText).toContain("IFCELEMENTQUANTITY(");
+ expect(exported.productCount).toBeGreaterThanOrEqual(5);
+ expect(exported.storeyCount).toBeGreaterThanOrEqual(1);
+
+ // Round-trip parse with web-ifc WASM
+ const reimported = await importedShapeWithDetailsFromIfc("villa_bim.ifc", exported.bytes);
+ expect(reimported.schema).toBe("IFC4");
+ expect(reimported.productCount).toBeGreaterThanOrEqual(5);
+ expect(reimported.triangleCount).toBeGreaterThanOrEqual(24);
+ });
+
+ it("classifies BIM entities and calculates BOQ (Metraj & Keşif) with CSV and PDF export", () => {
+ const frameShapes = generateStructuralFrameGrid({
+ baysX: 2,
+ baysZ: 2,
+ spanX: 40,
+ spanZ: 40,
+ storeyHeight: 32,
+ includeFoundationSlab: true,
+ includeCeilingSlab: true,
+ });
+ const roofShapes = generateParametricRoof({
+ kind: "gable",
+ width: 84,
+ depth: 84,
+ ridgeHeight: 18,
+ baseElevation: 64,
+ });
+ const openingShapes = [
+ ...generateParametricOpeningUnit({ kind: "double-window", width: 18, height: 15 }),
+ ...generateParametricOpeningUnit({ kind: "steel-entrance-door", width: 12, height: 21 }),
+ ];
+
+ const allShapes = [...frameShapes, ...roofShapes, ...openingShapes];
+ expect(classifyShapeForIfc(roofShapes[0])).toBe("IFCROOF");
+
+ const boq = calculateArchitecturalBoq(allShapes, {
+ projectName: "Test Mimari Bina",
+ scaleMode: "1:100",
+ });
+
+ expect(boq.grossFloorAreaM2).toBeGreaterThan(50);
+ expect(boq.totalStructuralConcreteM3).toBeGreaterThan(5);
+ expect(boq.totalRoofAreaM2).toBeGreaterThan(50);
+ expect(boq.windowCount).toBeGreaterThanOrEqual(1);
+ expect(boq.doorCount).toBeGreaterThanOrEqual(1);
+ expect(boq.totalEstimatedCostTry).toBeGreaterThan(50_000);
+ expect(boq.items.length).toBeGreaterThanOrEqual(4);
+
+ const csv = exportBoqToCsv(boq);
+ expect(csv.startsWith("\uFEFF")).toBe(true);
+ expect(csv).toContain("15.150.1005");
+ expect(csv).toContain("Test Mimari Bina");
+
+ const pdfBytes = exportBoqToPdfBytes(boq);
+ expect(pdfBytes.byteLength).toBeGreaterThan(500);
+ const pdfHeader = new TextDecoder().decode(pdfBytes.slice(0, 5));
+ expect(pdfHeader).toBe("%PDF-");
+ });
+
+ it("manages multi-storey isolation and duplicates a storey to an upper floor level", () => {
+ const groundStorey = DEFAULT_BUILDING_STOREYS[1]; // Zemin Kat (elevation 0)
+ const firstStorey = DEFAULT_BUILDING_STOREYS[2]; // 1. Normal Kat (elevation 32)
+
+ const gridShapes = generateStructuralFrameGrid({
+ baysX: 1,
+ baysZ: 1,
+ spanX: 40,
+ spanZ: 40,
+ baseElevation: groundStorey.elevation,
+ storeyTag: groundStorey.tag,
+ });
+
+ const duplicated = duplicateStoreyToLevel(
+ gridShapes,
+ groundStorey,
+ firstStorey,
+ DEFAULT_BUILDING_STOREYS,
+ );
+
+ expect(duplicated.clonedShapes.length).toBe(gridShapes.length);
+ expect(duplicated.nextShapes.length).toBe(gridShapes.length * 2);
+ expect(duplicated.clonedShapes[0].elevation).toBeCloseTo(
+ (gridShapes[0].elevation || 0) + (firstStorey.elevation - groundStorey.elevation),
+ 2,
+ );
+
+ const isolated = isolateStoreyVisibility(
+ duplicated.nextShapes,
+ firstStorey,
+ DEFAULT_BUILDING_STOREYS,
+ );
+ const visibleCount = isolated.filter((s) => !s.hidden).length;
+ expect(visibleCount).toBe(duplicated.clonedShapes.length);
+ });
+
+ it("generates parametric stairs (straight, L, U, spiral) and audits Turkish building code compliance", () => {
+ const straightStairs = generateParametricStair({ kind: "straight", stepCount: 18, totalHeight: 31 });
+ const lStairs = generateParametricStair({ kind: "l-shaped", stepCount: 18, totalHeight: 31 });
+ const uStairs = generateParametricStair({ kind: "u-shaped", stepCount: 18, totalHeight: 31 });
+ const spiralStairs = generateParametricStair({ kind: "spiral", stepCount: 16, totalHeight: 32 });
+
+ expect(straightStairs.length).toBeGreaterThanOrEqual(18);
+ expect(lStairs.length).toBeGreaterThanOrEqual(18);
+ expect(uStairs.length).toBeGreaterThanOrEqual(18);
+ expect(spiralStairs.length).toBeGreaterThanOrEqual(16);
+
+ const audit = auditArchitecturalCodeCompliance(uStairs, "1:100");
+ expect(audit.score).toBeGreaterThanOrEqual(50);
+ expect(audit.checks.some((c) => c.id === "stair-blondel")).toBe(true);
+ });
+
+ it("triangulates 3D site topography using simplex-noise + delaunator and computes cut/fill earthwork", () => {
+ const terrain = generateAdvancedTerrainWithPad({
+ preset: "hills",
+ width: 220,
+ depth: 220,
+ maxHeight: 22,
+ gridResolution: 14,
+ includeBuildingPad: true,
+ });
+
+ expect(terrain.triangleCount).toBeGreaterThanOrEqual(300);
+ expect(terrain.terrainShape.importedMesh?.positions.length).toBe(terrain.triangleCount * 9);
+ expect(terrain.padShape).not.toBeNull();
+ expect(terrain.excavationCutVolumeM3 + terrain.embankmentFillVolumeM3).toBeGreaterThan(0);
+ });
+
+ it("includes all 81 Turkish provinces with TS 825 zones and computes daily facade solar sweep", () => {
+ expect(TURKEY_81_PROVINCES_SOLAR_LOCATIONS).toHaveLength(81);
+ expect(TURKEY_81_PROVINCES_SOLAR_LOCATIONS[0].plateCode).toBe("01");
+ expect(TURKEY_81_PROVINCES_SOLAR_LOCATIONS[80].plateCode).toBe("81");
+ expect(SOLAR_LOCATIONS.length).toBeGreaterThanOrEqual(88);
+
+ const sweep = calculateDailySolarSweep({
+ ...DEFAULT_SOLAR_SETTINGS,
+ locationIndex: 0, // İstanbul
+ month: 5, // Haziran
+ day: 21,
+ });
+
+ expect(sweep.daylightDurationHours).toBeGreaterThan(12);
+ expect(sweep.southHours).toBeGreaterThan(4);
+ expect(sweep.eastHours).toBeGreaterThan(2);
+ expect(sweep.westHours).toBeGreaterThan(2);
+ expect(sweep.ts825Standard.zone).toBe(2);
+ expect(sweep.hourlyPoints.length).toBeGreaterThanOrEqual(15);
+ });
+});
diff --git a/tests/unit/desktopBridge.test.ts b/tests/unit/desktopBridge.test.ts
index 32ea264..f93d683 100644
--- a/tests/unit/desktopBridge.test.ts
+++ b/tests/unit/desktopBridge.test.ts
@@ -4,6 +4,8 @@ import { describe, expect, it } from "vitest";
import {
exportFiltersForFilename,
formatFriendlyUpdateError,
+ formatUpdateBytes,
+ formatUpdateTransferSummary,
getDesktopBridge,
isAllowedExternalUrl,
isDesktopRuntime,
@@ -61,7 +63,9 @@ describe("desktopBridge", () => {
it("distinguishes global vs 3D-editor-only menu commands", () => {
expect(isEditorOnlyMenuAction("file:new")).toBe(false);
expect(isEditorOnlyMenuAction("file:open")).toBe(false);
+ expect(isEditorOnlyMenuAction("file:save-and-update")).toBe(false);
expect(isEditorOnlyMenuAction("file:dashboard")).toBe(false);
+ expect(parseMenuAction("file:save-and-update")).toBe("file:save-and-update");
expect(isEditorOnlyMenuAction("window:drawing")).toBe(false);
expect(isEditorOnlyMenuAction("window:classrooms")).toBe(false);
expect(isEditorOnlyMenuAction("window:shared")).toBe(false);
@@ -128,6 +132,58 @@ describe("desktopBridge", () => {
expect(formatFriendlyUpdateError("Özel sunucu mesajı")).toBe("Özel sunucu mesajı");
});
+ it("formats live update download byte sizes and transfer summaries", () => {
+ expect(formatUpdateBytes(0)).toBe("0 B");
+ expect(formatUpdateBytes(512 * 1024)).toBe("512 KB");
+ expect(formatUpdateBytes(25.4 * 1024 * 1024)).toBe("25.4 MB");
+
+ expect(formatUpdateTransferSummary(null)).toBe("");
+ expect(
+ formatUpdateTransferSummary({
+ transferred: 12 * 1024 * 1024,
+ total: 0,
+ bytesPerSecond: 0,
+ }),
+ ).toBe("12.0 MB indirildi");
+ expect(
+ formatUpdateTransferSummary({
+ currentVersion: "1.0.10",
+ latestVersion: "1.0.11",
+ updateAvailable: true,
+ downloaded: false,
+ checkedAt: "2026-01-01T00:00:00.000Z",
+ status: "downloading",
+ progressPercent: 45,
+ transferred: 45 * 1024 * 1024,
+ total: 100 * 1024 * 1024,
+ bytesPerSecond: 5.2 * 1024 * 1024,
+ }),
+ ).toBe("45.0 MB / 100.0 MB • 5.2 MB/sn");
+ });
+
+ it("keeps desktop update safeguard and auth sync IPC channels in parity", () => {
+ const repoRoot = path.resolve(__dirname, "../..");
+ const mainSource = fs.readFileSync(path.join(repoRoot, "apps/desktop/main.cjs"), "utf8");
+ const preloadSource = fs.readFileSync(path.join(repoRoot, "apps/desktop/preload.cjs"), "utf8");
+ const pageSource = fs.readFileSync(path.join(repoRoot, "apps/web/src/app/page.tsx"), "utf8");
+
+ const requiredChannels = [
+ "snapcad:get-auth-state-sync",
+ "snapcad:get-auth-state",
+ "snapcad:open-update-progress",
+ "snapcad:set-active-work-state",
+ "snapcad:prepare-before-update",
+ "snapcad:prepare-before-update-result",
+ "snapcad:confirm-update-after-save",
+ "snapcad:cancel-pending-update-install",
+ ];
+ for (const channel of requiredChannels) {
+ expect(mainSource, `Missing in main.cjs: ${channel}`).toContain(channel);
+ expect(preloadSource, `Missing in preload.cjs: ${channel}`).toContain(channel);
+ }
+ expect(pageSource).toContain(`case "file:save-and-update":`);
+ });
+
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);
@@ -191,7 +247,7 @@ describe("desktopBridge", () => {
};
const swSource = fs.readFileSync(path.join(repoRoot, "apps/web/public/sw.js"), "utf8");
- expect(pkg.version).toBe("1.0.10");
+ expect(pkg.version).toBe("1.0.11");
expect(lock.version).toBe(pkg.version);
expect(lock.packages[""]?.version).toBe(pkg.version);
expect(SKF_CREATED_WITH_VERSION).toBe(pkg.version);
diff --git a/tests/unit/yaknetSsoSync.test.ts b/tests/unit/yaknetSsoSync.test.ts
index d7f5b8b..bf97ae0 100644
--- a/tests/unit/yaknetSsoSync.test.ts
+++ b/tests/unit/yaknetSsoSync.test.ts
@@ -1,4 +1,15 @@
+import fs from "node:fs";
+import path from "node:path";
import { describe, expect, it } from "vitest";
+import {
+ computeUserInitials,
+ resolveYakNetWidgetAttributes,
+ sanitizeYakNetWidgetUser,
+ shouldSuppressUnauthenticatedSsoMessage,
+ YAKNET_ACCOUNT_CDN_URL,
+ YAKNET_AUTH_BASE,
+ YAKNET_SSO_IFRAME_ID,
+} from "../../apps/web/src/lib/yaknetWidgetHelpers";
describe("YakNet SSO Cross-Subdomain Real-Time Session Synchronization", () => {
it("validates incoming YAKNET_SSO_STATUS message payload structure", () => {
@@ -80,10 +91,97 @@ describe("YakNet SSO Cross-Subdomain Real-Time Session Synchronization", () => {
});
it("ensures correct auth base URL for YakNet developer console SSO frame", () => {
- const YAKNET_AUTH_BASE = "https://developer-console.yakhub.com.tr";
const ssoFrameUrl = `${YAKNET_AUTH_BASE}/sdk/sso-frame`;
expect(ssoFrameUrl).toBe("https://developer-console.yakhub.com.tr/sdk/sso-frame");
expect(ssoFrameUrl.startsWith("https://developer-console.yakhub.com.tr")).toBe(true);
});
+
+ it("omits authenticated attribute until session resolves to prevent login-button flash", () => {
+ const unresolvedAttrs = resolveYakNetWidgetAttributes({
+ user: null,
+ sessionResolved: false,
+ theme: "light",
+ });
+ expect(unresolvedAttrs.authenticated).toBeNull();
+ expect(unresolvedAttrs["user-name"]).toBeNull();
+
+ const signedOutAttrs = resolveYakNetWidgetAttributes({
+ user: null,
+ sessionResolved: true,
+ });
+ expect(signedOutAttrs.authenticated).toBe("false");
+
+ const signedInAttrs = resolveYakNetWidgetAttributes({
+ user: { id: 7, name: "Yakup İpek", email: "yakup@yakhub.com.tr" },
+ sessionResolved: true,
+ });
+ expect(signedInAttrs.authenticated).toBe("true");
+ expect(signedInAttrs["user-name"]).toBe("Yakup İpek");
+ expect(signedInAttrs["user-email"]).toBe("yakup@yakhub.com.tr");
+ });
+
+ it("suppresses stale or cookie-less unauthenticated SSO frame messages safely", () => {
+ expect(
+ shouldSuppressUnauthenticatedSsoMessage({
+ isDesktop: true,
+ sessionResolved: true,
+ hasAuthenticatedUser: true,
+ ssoFrameHadAuthenticated: false,
+ }),
+ ).toBe(true);
+
+ expect(
+ shouldSuppressUnauthenticatedSsoMessage({
+ isDesktop: false,
+ sessionResolved: false,
+ hasAuthenticatedUser: false,
+ ssoFrameHadAuthenticated: false,
+ }),
+ ).toBe(true);
+
+ expect(
+ shouldSuppressUnauthenticatedSsoMessage({
+ isDesktop: false,
+ sessionResolved: true,
+ hasAuthenticatedUser: true,
+ ssoFrameHadAuthenticated: false,
+ }),
+ ).toBe(true);
+
+ expect(
+ shouldSuppressUnauthenticatedSsoMessage({
+ isDesktop: false,
+ sessionResolved: true,
+ hasAuthenticatedUser: true,
+ ssoFrameHadAuthenticated: true,
+ }),
+ ).toBe(false);
+ });
+
+ it("sanitizes YakNet widget users and computes avatar initials", () => {
+ expect(sanitizeYakNetWidgetUser({ id: 0, name: "Invalid" })).toBeNull();
+ expect(sanitizeYakNetWidgetUser({ id: 12, name: " Yakup İpek ", email: " yakup@yakhub.com.tr " })).toEqual({
+ id: 12,
+ name: "Yakup İpek",
+ email: "yakup@yakhub.com.tr",
+ avatar: null,
+ auth_source: undefined,
+ });
+ expect(computeUserInitials("Yakup İpek")).toBe("Yİ");
+ expect(computeUserInitials("Tekisim")).toBe("T");
+ expect(computeUserInitials("")).toBe("YN");
+ });
+
+ it("keeps yaknet-account widget dynamically loaded from CDN without vendoring", () => {
+ const repoRoot = path.resolve(__dirname, "../..");
+ const layoutSource = fs.readFileSync(path.join(repoRoot, "apps/web/src/app/layout.tsx"), "utf8");
+ const cloudBarSource = fs.readFileSync(path.join(repoRoot, "apps/web/src/components/snapcad/YakNetCloudBar.tsx"), "utf8");
+
+ expect(YAKNET_ACCOUNT_CDN_URL).toBe("https://cdnjs.yakhub.com.tr/ajax/libs/yaknet-account/latest/yaknet-account.js");
+ expect(layoutSource).toContain("YAKNET_ACCOUNT_CDN_URL");
+ expect(cloudBarSource).toContain("YAKNET_SSO_IFRAME_ID");
+ expect(YAKNET_SSO_IFRAME_ID).toBe("yaknet-sso-iframe-instance");
+ expect(fs.existsSync(path.join(repoRoot, "apps/web/public/yaknet-account.js"))).toBe(false);
+ });
});