Branchwell

Groundroom / app · groundroom.ai / commits / 7c9d4c31

App source: current code new

written by Branchwell · 7c9d4c3161357a12afe55f20c034b037a8efac1f

16 files changed

.gitignore added

1+ .DS_Store
2+ .check-build/
3+ DerivedData/
4+ xcuserdata/
5+ *.xcuserstate

Checks/LayoutChecks.swift added

1+ import Foundation
2+
3+ @main
4+ struct LayoutChecks {
5+ static func main() throws {
6+ let room = try RoomLayout.example.checked()
7+ precondition(room.blocks.count == 3)
8+ precondition(room.translation(for: .entrance).x == 0)
9+ precondition(room.translation(for: .left).x > 0 && room.translation(for: .right).x < 0)
10+ precondition(RoomLayout.Viewpoint.allCases.allSatisfy { room.translation(for: $0).y == 0 })
11+ func rejects(_ mutated: RoomLayout, _ expected: RoomLayout.LayoutError) {
12+ do { _ = try mutated.checked(); fatalError("invalid layout passed") }
13+ catch { precondition(error as? RoomLayout.LayoutError == expected) }
14+ }
15+ var invalid = room; invalid.width = .infinity; rejects(invalid, .invalidRoom)
16+ invalid = room; invalid.blocks[0].z = .nan; rejects(invalid, .invalidObject)
17+ invalid = room; invalid.blocks[0].x = 100; rejects(invalid, .outsideRoom)
18+ invalid = room; invalid.blocks = Array(repeating: room.blocks[0], count: 25)
19+ rejects(invalid, .tooManyObjects)
20+ print("8 layout assertions passed.")
21+ }
22+ }

Groundroom.xcodeproj/project.pbxproj added

1+ // !$*UTF8*$!
2+ { archiveVersion=1; classes={}; objectVersion=56; objects={
3+ 000000000000000000000050 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sources/GroundroomWalkthrough.swift; sourceTree = "<group>"; };
4+ 000000000000000000000051 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sources/RoomLayout.swift; sourceTree = "<group>"; };
5+ 000000000000000000000052 = { isa = PBXBuildFile; fileRef=000000000000000000000050; };
6+ 000000000000000000000053 = { isa = PBXBuildFile; fileRef=000000000000000000000051; };
7+
8+ 000000000000000000000002 = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Sources/Groundroom.swift; sourceTree = "<group>"; };
9+ 000000000000000000000001 = { isa = PBXGroup; children=(000000000000000000000002, 000000000000000000000050, 000000000000000000000051, 000000000000000000000003); sourceTree="<group>"; };
10+ 000000000000000000000014 = { isa = PBXNativeTarget; name=GroundroomMac; productName=Groundroom; productReference=000000000000000000000015; buildConfigurationList=000000000000000000000016; buildPhases=(000000000000000000000017, 000000000000000000000018, 000000000000000000000019); buildRules=(); dependencies=(); productType="com.apple.product-type.application"; };
11+ 000000000000000000000015 = { isa=PBXFileReference; explicitFileType=wrapper.application; includeInIndex=0; path=Groundroom.app; sourceTree=BUILT_PRODUCTS_DIR; };
12+ 000000000000000000000016 = { isa=XCConfigurationList; buildConfigurations=(00000000000000000000001A, 00000000000000000000001B); defaultConfigurationIsVisible=0; defaultConfigurationName=Release; };
13+ 000000000000000000000017 = { isa=PBXSourcesBuildPhase; buildActionMask=2147483647; files=(00000000000000000000001C); runOnlyForDeploymentPostprocessing=0; };
14+ 000000000000000000000018 = { isa=PBXFrameworksBuildPhase; buildActionMask=2147483647; files=(); runOnlyForDeploymentPostprocessing=0; };
15+ 000000000000000000000019 = { isa=PBXResourcesBuildPhase; buildActionMask=2147483647; files=(); runOnlyForDeploymentPostprocessing=0; };
16+ 00000000000000000000001A = { isa=XCBuildConfiguration; name=Debug; buildSettings={PRODUCT_NAME=Groundroom; PRODUCT_BUNDLE_IDENTIFIER=com.groundroom.prototype; GENERATE_INFOPLIST_FILE=YES; INFOPLIST_KEY_CFBundleDisplayName=Groundroom; SDKROOT=macosx; MACOSX_DEPLOYMENT_TARGET=14.0; MARKETING_VERSION=0.1.0; CURRENT_PROJECT_VERSION=1; SWIFT_VERSION=5.0; CODE_SIGN_STYLE=Automatic; CODE_SIGN_ENTITLEMENTS=GroundroomMac.entitlements; ENABLE_APP_SANDBOX=YES;}; };
17+ 00000000000000000000001B = { isa=XCBuildConfiguration; name=Release; buildSettings={PRODUCT_NAME=Groundroom; PRODUCT_BUNDLE_IDENTIFIER=com.groundroom.prototype; GENERATE_INFOPLIST_FILE=YES; INFOPLIST_KEY_CFBundleDisplayName=Groundroom; SDKROOT=macosx; MACOSX_DEPLOYMENT_TARGET=14.0; MARKETING_VERSION=0.1.0; CURRENT_PROJECT_VERSION=1; SWIFT_VERSION=5.0; CODE_SIGN_STYLE=Automatic; CODE_SIGN_ENTITLEMENTS=GroundroomMac.entitlements; ENABLE_APP_SANDBOX=YES;}; };
18+ 00000000000000000000001C = { isa=PBXBuildFile; fileRef=000000000000000000000002; };
19+ 000000000000000000000028 = { isa = PBXNativeTarget; name=GroundroomMobile; productName=Groundroom; productReference=000000000000000000000029; buildConfigurationList=00000000000000000000002A; buildPhases=(00000000000000000000002B, 00000000000000000000002C, 00000000000000000000002D); buildRules=(); dependencies=(); productType="com.apple.product-type.application"; };
20+ 000000000000000000000029 = { isa=PBXFileReference; explicitFileType=wrapper.application; includeInIndex=0; path=Groundroom.app; sourceTree=BUILT_PRODUCTS_DIR; };
21+ 00000000000000000000002A = { isa=XCConfigurationList; buildConfigurations=(00000000000000000000002E, 00000000000000000000002F); defaultConfigurationIsVisible=0; defaultConfigurationName=Release; };
22+ 00000000000000000000002B = { isa=PBXSourcesBuildPhase; buildActionMask=2147483647; files=(000000000000000000000030); runOnlyForDeploymentPostprocessing=0; };
23+ 00000000000000000000002C = { isa=PBXFrameworksBuildPhase; buildActionMask=2147483647; files=(); runOnlyForDeploymentPostprocessing=0; };
24+ 00000000000000000000002D = { isa=PBXResourcesBuildPhase; buildActionMask=2147483647; files=(); runOnlyForDeploymentPostprocessing=0; };
25+ 00000000000000000000002E = { isa=XCBuildConfiguration; name=Debug; buildSettings={PRODUCT_NAME=Groundroom; PRODUCT_BUNDLE_IDENTIFIER=com.groundroom.prototype; GENERATE_INFOPLIST_FILE=YES; INFOPLIST_KEY_CFBundleDisplayName=Groundroom; SDKROOT=iphoneos; IPHONEOS_DEPLOYMENT_TARGET=17.0; MARKETING_VERSION=0.1.0; CURRENT_PROJECT_VERSION=1; SWIFT_VERSION=5.0; CODE_SIGN_STYLE=Automatic; TARGETED_DEVICE_FAMILY="1,2"; INFOPLIST_KEY_UILaunchScreen_Generation=YES; SUPPORTED_PLATFORMS="iphoneos iphonesimulator";}; };
26+ 00000000000000000000002F = { isa=XCBuildConfiguration; name=Release; buildSettings={PRODUCT_NAME=Groundroom; PRODUCT_BUNDLE_IDENTIFIER=com.groundroom.prototype; GENERATE_INFOPLIST_FILE=YES; INFOPLIST_KEY_CFBundleDisplayName=Groundroom; SDKROOT=iphoneos; IPHONEOS_DEPLOYMENT_TARGET=17.0; MARKETING_VERSION=0.1.0; CURRENT_PROJECT_VERSION=1; SWIFT_VERSION=5.0; CODE_SIGN_STYLE=Automatic; TARGETED_DEVICE_FAMILY="1,2"; INFOPLIST_KEY_UILaunchScreen_Generation=YES; SUPPORTED_PLATFORMS="iphoneos iphonesimulator";}; };
27+ 000000000000000000000030 = { isa=PBXBuildFile; fileRef=000000000000000000000002; };
28+ 00000000000000000000003C = { isa = PBXNativeTarget; name=GroundroomVision; productName=Groundroom; productReference=00000000000000000000003D; buildConfigurationList=00000000000000000000003E; buildPhases=(00000000000000000000003F, 000000000000000000000040, 000000000000000000000041); buildRules=(); dependencies=(); productType="com.apple.product-type.application"; };
29+ 00000000000000000000003D = { isa=PBXFileReference; explicitFileType=wrapper.application; includeInIndex=0; path=Groundroom.app; sourceTree=BUILT_PRODUCTS_DIR; };
30+ 00000000000000000000003E = { isa=XCConfigurationList; buildConfigurations=(000000000000000000000042, 000000000000000000000043); defaultConfigurationIsVisible=0; defaultConfigurationName=Release; };
31+ 00000000000000000000003F = { isa=PBXSourcesBuildPhase; buildActionMask=2147483647; files=(000000000000000000000044, 000000000000000000000052, 000000000000000000000053); runOnlyForDeploymentPostprocessing=0; };
32+ 000000000000000000000040 = { isa=PBXFrameworksBuildPhase; buildActionMask=2147483647; files=(); runOnlyForDeploymentPostprocessing=0; };
33+ 000000000000000000000041 = { isa=PBXResourcesBuildPhase; buildActionMask=2147483647; files=(); runOnlyForDeploymentPostprocessing=0; };
34+ 000000000000000000000042 = { isa=XCBuildConfiguration; name=Debug; buildSettings={PRODUCT_NAME=Groundroom; PRODUCT_BUNDLE_IDENTIFIER=com.groundroom.prototype; GENERATE_INFOPLIST_FILE=YES; INFOPLIST_KEY_CFBundleDisplayName=Groundroom; SDKROOT=xros; XROS_DEPLOYMENT_TARGET=2.0; MARKETING_VERSION=0.1.0; CURRENT_PROJECT_VERSION=1; SWIFT_VERSION=5.0; CODE_SIGN_STYLE=Automatic; TARGETED_DEVICE_FAMILY="7"; SUPPORTED_PLATFORMS="xros xrsimulator";}; };
35+ 000000000000000000000043 = { isa=XCBuildConfiguration; name=Release; buildSettings={PRODUCT_NAME=Groundroom; PRODUCT_BUNDLE_IDENTIFIER=com.groundroom.prototype; GENERATE_INFOPLIST_FILE=YES; INFOPLIST_KEY_CFBundleDisplayName=Groundroom; SDKROOT=xros; XROS_DEPLOYMENT_TARGET=2.0; MARKETING_VERSION=0.1.0; CURRENT_PROJECT_VERSION=1; SWIFT_VERSION=5.0; CODE_SIGN_STYLE=Automatic; TARGETED_DEVICE_FAMILY="7"; SUPPORTED_PLATFORMS="xros xrsimulator";}; };
36+ 000000000000000000000044 = { isa=PBXBuildFile; fileRef=000000000000000000000002; };
37+ 000000000000000000000003 = { isa=PBXGroup; children=(000000000000000000000015, 000000000000000000000029, 00000000000000000000003D); name=Products; sourceTree="<group>"; };
38+ 000000000000000000000004 = { isa=PBXProject; attributes={LastUpgradeCheck=2720;}; buildConfigurationList=000000000000000000000005; developmentRegion=en; hasScannedForEncodings=0; knownRegions=(en,Base); mainGroup=000000000000000000000001; productRefGroup=000000000000000000000003; projectDirPath=""; projectRoot=""; targets=(000000000000000000000014, 000000000000000000000028, 00000000000000000000003C); compatibilityVersion="Xcode 14.0"; };
39+ 000000000000000000000005 = { isa=XCConfigurationList; buildConfigurations=(000000000000000000000006, 000000000000000000000007); defaultConfigurationIsVisible=0; defaultConfigurationName=Release; };
40+ 000000000000000000000006 = { isa=XCBuildConfiguration; name=Debug; buildSettings={}; };
41+ 000000000000000000000007 = { isa=XCBuildConfiguration; name=Release; buildSettings={}; };
42+ }; rootObject=000000000000000000000004; }

Groundroom.xcodeproj/xcshareddata/xcschemes/GroundroomMac.xcscheme added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <Scheme version="1.7">
3+ <BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES"><BuildActionEntries><BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="000000000000000000000014" BuildableName="Groundroom.app" BlueprintName="GroundroomMac" ReferencedContainer="container:Groundroom.xcodeproj"/></BuildActionEntry></BuildActionEntries></BuildAction>
4+ <LaunchAction buildConfiguration="Debug" launchStyle="0" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.DebuggerFoundation.Launcher.LLDB"><BuildableProductRunnable runnableDebuggingMode="0"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="000000000000000000000014" BuildableName="Groundroom.app" BlueprintName="GroundroomMac" ReferencedContainer="container:Groundroom.xcodeproj"/></BuildableProductRunnable></LaunchAction>
5+ <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/>
6+ </Scheme>

Groundroom.xcodeproj/xcshareddata/xcschemes/GroundroomMobile.xcscheme added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <Scheme version="1.7">
3+ <BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES"><BuildActionEntries><BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="000000000000000000000028" BuildableName="Groundroom.app" BlueprintName="GroundroomMobile" ReferencedContainer="container:Groundroom.xcodeproj"/></BuildActionEntry></BuildActionEntries></BuildAction>
4+ <LaunchAction buildConfiguration="Debug" launchStyle="0" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.DebuggerFoundation.Launcher.LLDB"><BuildableProductRunnable runnableDebuggingMode="0"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="000000000000000000000028" BuildableName="Groundroom.app" BlueprintName="GroundroomMobile" ReferencedContainer="container:Groundroom.xcodeproj"/></BuildableProductRunnable></LaunchAction>
5+ <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/>
6+ </Scheme>

Groundroom.xcodeproj/xcshareddata/xcschemes/GroundroomVision.xcscheme added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <Scheme version="1.7">
3+ <BuildAction parallelizeBuildables="YES" buildImplicitDependencies="YES"><BuildActionEntries><BuildActionEntry buildForTesting="YES" buildForRunning="YES" buildForProfiling="YES" buildForArchiving="YES" buildForAnalyzing="YES"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="00000000000000000000003C" BuildableName="Groundroom.app" BlueprintName="GroundroomVision" ReferencedContainer="container:Groundroom.xcodeproj"/></BuildActionEntry></BuildActionEntries></BuildAction>
4+ <LaunchAction buildConfiguration="Debug" launchStyle="0" selectedDebuggerIdentifier="Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier="Xcode.DebuggerFoundation.Launcher.LLDB"><BuildableProductRunnable runnableDebuggingMode="0"><BuildableReference BuildableIdentifier="primary" BlueprintIdentifier="00000000000000000000003C" BuildableName="Groundroom.app" BlueprintName="GroundroomVision" ReferencedContainer="container:Groundroom.xcodeproj"/></BuildableProductRunnable></LaunchAction>
5+ <ArchiveAction buildConfiguration="Release" revealArchiveInOrganizer="YES"/>
6+ </Scheme>

GroundroomMac.entitlements added

1+ <?xml version="1.0" encoding="UTF-8"?>
2+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
3+ <plist version="1.0"><dict><key>com.apple.security.app-sandbox</key><true/><key>com.apple.security.files.user-selected.read-write</key><true/></dict></plist>

LICENSE added

1+ MIT License
2+
3+ Copyright (c) 2026 Groundroom contributors
4+
5+ Permission is hereby granted, free of charge, to any person obtaining a copy
6+ of this software and associated documentation files (the "Software"), to deal
7+ in the Software without restriction, including without limitation the rights
8+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+ copies of the Software, and to permit persons to whom the Software is
10+ furnished to do so, subject to the following conditions:
11+
12+ The above copyright notice and this permission notice shall be included in all
13+ copies or substantial portions of the Software.
14+
15+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+ SOFTWARE.

README.md added

1+ # Groundroom
2+
3+ **Design your home and garden together.** Groundroom is an open-source native prototype for Mac, iPhone, iPad and Vision Pro. It starts with a house you can measure and edit, and a local workspace for trying planting layouts.
4+
5+ ## The editor
6+
7+ ![Groundroom Mac editor showing a measured house with surrounding plants, project controls and a planted site preview](docs/screenshots/groundroom-macos-native.png)
8+
9+ *Actual native SwiftUI render on Mac, using a fictional site. The [compact editor capture](docs/screenshots/groundroom-compact-native.png) is the same native UI rendered at a narrow width on Mac, not an iPhone screenshot.*
10+
11+ ## What works now
12+
13+ 1. Enter the width, depth, wall height, and roof rise for a starter house. Optionally open a local photo as a visual reference. Groundroom does **not** reconstruct the photo yet.
14+ 2. Place procedural trees, shrubs, and grass on the site. Click the canvas or enter coordinates, then rotate the view.
15+ 3. Save and reopen the layout as a local JSON document. Importing an existing STL is optional; confirm its units and up axis.
16+ 4. On Vision Pro, the **Sample walkthrough** tab opens an opt-in, life-size sample room in mixed immersion. Select fixed viewpoints and exit back to the window. It does **not** yet walk through your saved home, and headset comfort has not been tested.
17+
18+ ## Build from source
19+
20+ Open `Groundroom.xcodeproj` in Xcode and choose one of these schemes:
21+
22+ | Scheme | Platform | Verified in this prototype |
23+ | --- | --- | --- |
24+ | `GroundroomMac` | macOS 14+ | Native SDK compile and link, core tests, native editor captures |
25+ | `GroundroomMobile` | iOS and iPadOS 17+ | iPhone/iPad target compiles and links; no hardware or simulator run verified |
26+ | `GroundroomVision` | visionOS 2+ | Window and sample immersion compile and link against device and simulator SDKs; immersive launch and headset movement not verified |
27+
28+ To repeat the source checks on a Mac with Xcode and these SDKs:
29+
30+ ```sh
31+ ./tools/check.sh
32+ ```
33+
34+ The Xcode project uses a development bundle identifier. No signed installer, App Store submission, or TestFlight build is provided by this repository.
35+
36+ ## Next
37+
38+ - Create measured, editable exterior proxies from a single photo and interior room layouts from multiple photos. Keep uncertain geometry visible and let users correct it.
39+ - Add replaceable furniture, a sourced plant library, and simple reusable indoor and outdoor models.
40+ - Use the same saved layout for a comfortable Vision Pro walkthrough, with explicit entry and exit and hardware verification.
41+
42+ ## Privacy, license, and contributions
43+
44+ Manual design runs locally. The prototype has no login, cloud upload, or AI requests. Reference photos stay out of the saved plan; share a project file only when you intend to share its geometry. The prototype is for layout exploration, not measurements for construction.
45+
46+ Source is [MIT licensed](LICENSE). Start with the [project roles on Jobley](https://jobley.ai/volunteer/#open-garden-design). The primary website is planned for **groundroom.com**.

Sources/Groundroom.swift added

1+ import Foundation
2+ import SwiftUI
3+ import ImageIO
4+ #if GROUNDROOM_SELF_TEST && os(macOS)
5+ import AppKit
6+ #endif
7+ import UniformTypeIdentifiers
8+
9+ enum GardenError: LocalizedError { case bad(String); var errorDescription: String? { if case .bad(let s)=self{return s};return nil } }
10+ struct Point: Codable, Equatable { var x:Double; var y:Double; var z:Double
11+ func valid(_ bound:Double=1e12)->Bool {[x,y,z].allSatisfy{$0.isFinite && abs($0)<bound}}
12+ }
13+ enum Up:String,CaseIterable { case Y,Z }
14+ enum Units:String,CaseIterable { case m,cm,mm,ft,inch; var scale:Double { switch self {case .m:1;case .cm:0.01;case .mm:0.001;case .ft:0.3048;case .inch:0.0254} } }
15+ enum Species:String,Codable,CaseIterable { case Tree,Shrub,Grass
16+ var height:Double {switch self{case .Tree:4;case .Shrub:1.2;case .Grass:0.55}}
17+ var spread:Double {switch self{case .Tree:1.65;case .Shrub:0.7;case .Grass:0.32}}
18+ var color:Color {switch self{case .Tree:Color(red:0.29,green:0.43,blue:0.24);case .Shrub:Color(red:0.49,green:0.62,blue:0.36);case .Grass:Color(red:0.55,green:0.50,blue:0.29)}}
19+ }
20+ struct Plant: Codable,Equatable {var type:Species;var x:Double;var z:Double}
21+ struct HouseSpec:Codable,Equatable {var width:Double;var depth:Double;var wall:Double;var rise:Double}
22+ struct Garden: Codable,Equatable {
23+ var version=1;var spec:HouseSpec?=nil;var house:[Point]=[];var plants:[Plant]=[]
24+ func checked()throws->Self {
25+ guard version==1,house.count%3==0,house.count<=Mesh.maxTriangles*3,house.allSatisfy({$0.valid(1001)}),plants.count<=500,plants.allSatisfy({[$0.x,$0.z].allSatisfy{$0.isFinite && abs($0)<=1000}}) else {throw GardenError.bad("Invalid project geometry or plant count.")}
26+ return self
27+ }
28+ }
29+ enum Mesh {
30+ static let maxBytes=8*1024*1024,maxTriangles=60_000
31+ static func checked(_ v:[Point])throws->[Point] {
32+ guard !v.isEmpty,v.count%3==0,v.count<=maxTriangles*3,v.allSatisfy({$0.valid()}) else {throw GardenError.bad("Invalid STL mesh. Check coordinate and triangle limits.")}
33+ return v
34+ }
35+ static func parse(_ data:Data)throws->[Point] {
36+ guard data.count>=15,data.count<=maxBytes else {throw GardenError.bad("Use an STL below 8 MB.")}
37+ func word(_ k:Int)->UInt32 { data.withUnsafeBytes{UInt32(littleEndian:$0.loadUnaligned(fromByteOffset:k,as:UInt32.self))} }
38+ if data.count>=84 {
39+ let n=Int(word(80))
40+ if n>0,84+n*50==data.count {
41+ guard n<=maxTriangles else {throw GardenError.bad("Up to 60,000 triangles are supported.")}
42+ var v:[Point]=[];v.reserveCapacity(n*3)
43+ for i in 0..<n { for j in 0..<3 {
44+ let k=96+i*50+j*12
45+ v.append(.init(x:Double(Float(bitPattern:word(k))),y:Double(Float(bitPattern:word(k+4))),z:Double(Float(bitPattern:word(k+8)))))
46+ }}
47+ return try checked(v)
48+ }
49+ }
50+ guard let s=String(data:data,encoding:.ascii) else {throw GardenError.bad("Unsupported STL data.")}
51+ let l=s.split(whereSeparator:\.isNewline).map{$0.split(whereSeparator:\.isWhitespace).map(String.init)}.filter{ !$0.isEmpty }
52+ guard l.first?.first?.lowercased()=="solid",l.last?.first?.lowercased()=="endsolid",l.count>2,(l.count-2)%7==0 else {throw GardenError.bad("Invalid ASCII STL structure.")}
53+ guard (l.count-2)/7<=maxTriangles else {throw GardenError.bad("Up to 60,000 triangles are supported.")}
54+ var v:[Point]=[]
55+ for i in stride(from:1,to:l.count-1,by:7) {
56+ guard l[i].count==5,l[i][0...1].map({$0.lowercased()})==["facet","normal"],l[i].dropFirst(2).allSatisfy({Double($0)?.isFinite==true}),l[i+1].map({$0.lowercased()})==["outer","loop"],l[i+5].map({$0.lowercased()})==["endloop"],l[i+6].map({$0.lowercased()})==["endfacet"] else {throw GardenError.bad("Invalid ASCII STL face.")}
57+ for j in 2...4 { let p=l[i+j];guard p.count==4,p[0].lowercased()=="vertex",let x=Double(p[1]),let y=Double(p[2]),let z=Double(p[3]) else {throw GardenError.bad("Invalid ASCII STL vertex.")};v.append(.init(x:x,y:y,z:z)) }
58+ }
59+ return try checked(v)
60+ }
61+ static func orient(_ v:[Point],units:Units,up:Up)throws->[Point] {
62+ let scale=units.scale
63+ let a=try checked(v).map{up == .Y ? Point(x:$0.x*scale,y:$0.y*scale,z:$0.z*scale) : Point(x:$0.x*scale,y:$0.z*scale,z:(-$0.y)*scale)}
64+ let x=a.map(\.x),y=a.map(\.y),z=a.map(\.z)
65+ let mx=x.min()!,my=y.min()!,mz=z.min()!
66+ let dx=x.max()!-mx,dy=y.max()!-my,dz=z.max()!-mz
67+ guard max(dx,dy,dz)<=1000 else {throw GardenError.bad("House exceeds 1,000 metres. Check the export units.")}
68+ return a.map{Point(x:$0.x-(mx+dx/2),y:$0.y-my,z:$0.z-(mz+dz/2))}
69+ }
70+ static func house(width:Double=6,depth:Double=4,wall:Double=2,rise:Double=1)->[Point] {
71+ let p:[Point]=[.init(x:-3,y:0,z:-2),.init(x:3,y:0,z:-2),.init(x:3,y:0,z:2),.init(x:-3,y:0,z:2),.init(x:-3,y:2,z:-2),.init(x:3,y:2,z:-2),.init(x:3,y:2,z:2),.init(x:-3,y:2,z:2),.init(x:0,y:3,z:-2),.init(x:0,y:3,z:2)]
72+ let scaled=p.map { Point(x:$0.x * width/6,y:$0.y<=2 ? $0.y*wall/2 : wall+rise,z:$0.z*depth/4) }
73+ return [[0,1,5],[0,5,4],[1,2,6],[1,6,5],[2,3,7],[2,7,6],[3,0,4],[3,4,7],[4,5,8],[7,6,9],[4,8,9],[4,9,7],[8,5,6],[8,6,9]].flatMap{$0.map{scaled[$0]}}
74+ }
75+ }
76+
77+ struct GardenDocument:FileDocument {
78+ static var readableContentTypes:[UTType]{[.json]}
79+ var value:Garden
80+ init(value:Garden){self.value=value}
81+ init(configuration:ReadConfiguration)throws {guard let data=configuration.file.regularFileContents,data.count<=16*1024*1024 else{throw GardenError.bad("Project exceeds 16 MB.")};value=try JSONDecoder().decode(Garden.self,from:data).checked()}
82+ func fileWrapper(configuration:WriteConfiguration)throws->FileWrapper {.init(regularFileWithContents:try JSONEncoder().encode(value.checked()))}
83+ }
84+ struct Projection {
85+ let size:CGSize;let angle:Double;let scale:Double
86+ func point(_ p:Point)->(CGPoint,Double) {let u=p.x*cos(angle)-p.z*sin(angle),v=p.x*sin(angle)+p.z*cos(angle);return (CGPoint(x:size.width/2+u*scale,y:size.height*0.61+(v*0.46-p.y)*scale),v+p.y*0.23)}
87+ func ground(_ p:CGPoint)->(Double,Double) {
88+ let u=(p.x-size.width/2)/scale,v=(p.y-size.height*0.61)/(0.46*scale)
89+ return (u*cos(angle)+v*sin(angle),(-u)*sin(angle)+v*cos(angle))
90+ }
91+ }
92+ struct GardenView: View {
93+ @State private var garden:Garden
94+ let snapshot:Bool
95+ init(initial:Garden=Garden(),snapshot:Bool=false){_garden=State(initialValue:initial);self.snapshot=snapshot}
96+ @State private var pending:[Point]=[]
97+ @State private var units:Units?=nil
98+ @State private var up:Up?=nil
99+ @State private var species:Species = .Tree
100+ @State private var coordsX="2"
101+ @State private var coordsZ="2"
102+ @State private var status="Build a house template or choose a reference photo."
103+ @State private var angle=Double.pi/4
104+ enum ImportKind {case stl,plan,photo}
105+ @State private var importKind:ImportKind = .stl
106+ @State private var importing=false
107+ @State private var exporting=false
108+ @State private var photo:CGImage?
109+ @State private var width="6"
110+ @State private var depth="4"
111+ @State private var wall="2"
112+ @State private var rise="1"
113+ var body:some View {
114+ GeometryReader { metrics in
115+ if metrics.size.width >= 740 {
116+ HStack(spacing:0){ controls.frame(width:260); Divider(); workspace }
117+ } else {
118+ VStack(spacing:0){
119+ workspace.frame(height:min(350,max(200,metrics.size.height*0.48)))
120+ Divider()
121+ controls
122+ }
123+ }
124+ }
125+ .fileImporter(isPresented:$importing,allowedContentTypes:allowedType){r in
126+ switch importKind {
127+ case .stl:
128+ pending=[];units=nil;up=nil
129+ file(r,max:Mesh.maxBytes){d in pending=try Mesh.parse(d);status="Loaded \(pending.count/3) triangles. Choose units and up axis."}
130+ case .plan:
131+ file(r,max:16*1024*1024){d in garden=try JSONDecoder().decode(Garden.self,from:d).checked();photo=nil;if let q=garden.spec{width=String(q.width);depth=String(q.depth);wall=String(q.wall);rise=String(q.rise)};status="Saved garden loaded."}
132+ case .photo:
133+ file(r,max:12*1024*1024){d in
134+ let options = [kCGImageSourceCreateThumbnailFromImageAlways:true, kCGImageSourceCreateThumbnailWithTransform:true, kCGImageSourceThumbnailMaxPixelSize:1024] as CFDictionary
135+ guard let imageSource=CGImageSourceCreateWithData(d as CFData,nil),let thumbnail=CGImageSourceCreateThumbnailAtIndex(imageSource,0,options) else {throw GardenError.bad("Couldn’t read that photo.")}
136+ photo=thumbnail
137+ if garden.house.isEmpty {makeTemplate()}
138+ status="Reference photo added. Adjust the editable starter house to match."
139+ }
140+ }
141+ }
142+ .fileExporter(isPresented:$exporting,document:GardenDocument(value:garden),contentType:.json,defaultFilename:"Groundroom Plan"){result in
143+ switch result{case .success:status="Garden plan saved.";case .failure(let e):status=e.localizedDescription}
144+ }
145+ }
146+ @ViewBuilder private var controls:some View {
147+ if snapshot {controlFields} else { ScrollView {controlFields} }
148+ }
149+ private var controlFields:some View {
150+ VStack(alignment:.leading,spacing:13){
151+ Text("Groundroom").font(.title2.bold())
152+ Text("Local prototype").font(.subheadline).foregroundStyle(.secondary)
153+ Divider()
154+ Text("House model").font(.headline)
155+ LabeledContent("Width (m)"){TextField("",text:$width).textFieldStyle(.roundedBorder).frame(width:68)}
156+ LabeledContent("Depth (m)"){TextField("",text:$depth).textFieldStyle(.roundedBorder).frame(width:68)}
157+ LabeledContent("Wall height (m)"){TextField("",text:$wall).textFieldStyle(.roundedBorder).frame(width:68)}
158+ LabeledContent("Roof rise (m)"){TextField("",text:$rise).textFieldStyle(.roundedBorder).frame(width:68)}
159+ Button("Apply house dimensions"){makeTemplate()}
160+ Button("Choose reference photo…"){importKind = .photo;importing=true}
161+ if let photo {Image(decorative:photo,scale:1).resizable().scaledToFit().frame(maxHeight:105).accessibilityLabel("Local reference photo")
162+ Text("Adjust the starter house dimensions to match. The photo isn’t automatically reconstructed.").font(.caption).foregroundStyle(.secondary)
163+ }
164+ Button("Import STL (optional)…"){importKind = .stl;importing=true}
165+ Picker("Export units",selection:$units){Text("Choose").tag(Units?.none);ForEach(Units.allCases,id:\.self){Text($0.rawValue).tag(Optional($0))}}
166+ Picker("Up axis",selection:$up){Text("Choose").tag(Up?.none);ForEach(Up.allCases,id:\.self){Text($0.rawValue).tag(Optional($0))}}
167+ Button("Apply scale and orientation"){if let units,let up {do{garden.house=try Mesh.orient(pending,units:units,up:up);garden.spec=nil;status="House centred on the ground."}catch{status=error.localizedDescription}}}
168+ .disabled(pending.isEmpty || units==nil || up==nil)
169+ Text("STL does not include units. Match your CAD export.").font(.caption).foregroundStyle(.secondary)
170+ Divider()
171+ Text("Place plants").font(.headline)
172+ Picker("Plant form", selection:$species){ForEach(Species.allCases,id:\.self){Text($0.rawValue).tag($0)}}
173+ TextField("East / west (m)",text:$coordsX)
174+ TextField("North / south (m)",text:$coordsZ)
175+ Button("Place at coordinates"){if let x=Double(coordsX),let z=Double(coordsZ){plant(x,z)}else{status="Enter numeric metre coordinates."}}
176+ Button("Undo last plant"){_ = garden.plants.popLast();status="Last plant removed."}.disabled(garden.plants.isEmpty)
177+ Divider()
178+ Button("Save project…"){exporting=true}
179+ Button("Open project…"){importKind = .plan;importing=true}
180+ }.padding(22).frame(maxWidth:.infinity,alignment:.leading)
181+ }
182+ private var workspace:some View {
183+ VStack(alignment:.leading,spacing:12){
184+ HStack{Text("Garden workspace").font(.headline);Spacer();Button("Rotate view"){angle += .pi/4}}
185+ GeometryReader{ geo in
186+ let p=projection(geo.size)
187+ Canvas{ context,_ in render(context,p) }
188+ .background(Color(red:0.87,green:0.90,blue:0.83))
189+ .clipShape(.rect(cornerRadius:12))
190+ .contentShape(Rectangle())
191+ .gesture(SpatialTapGesture().onEnded{v in let (x,z)=p.ground(v.location);plant(x,z)})
192+ .accessibilityLabel("Isometric garden preview")
193+ .accessibilityHint("Use the coordinate fields to place a plant without a pointer.")
194+ }
195+ Text(status).accessibilityAddTraits(.updatesFrequently)
196+ Text("\(garden.plants.count) plants · No upload · Placeholder plant forms").font(.caption).foregroundStyle(.secondary)
197+ }.padding(20)
198+ }
199+ private var allowedType:[UTType]{switch importKind{case .stl:[UTType(filenameExtension:"stl") ?? .data];case .plan:[.json];case .photo:[.jpeg,.png,.heic]}}
200+ private func makeTemplate(){
201+ guard let a=Double(width),let b=Double(depth),let c=Double(wall),let d=Double(rise),[a,b,c].allSatisfy({$0.isFinite && $0>0 && $0<=100}),d.isFinite,d>=0,d<=30 else {status="Use dimensions above 0 and up to 100 metres, and a roof rise from 0 to 30.";return}
202+ garden.spec=HouseSpec(width:a,depth:b,wall:c,rise:d);garden.house=Mesh.house(width:a,depth:b,wall:c,rise:d);status="Editable house template added."
203+ }
204+ private func file(_ r:Result<URL,Error>,max:Int,action:(Data)throws->Void){
205+ do{let url=try r.get(),scope=url.startAccessingSecurityScopedResource();defer{if scope{url.stopAccessingSecurityScopedResource()}}
206+ let h=try FileHandle(forReadingFrom:url);defer{try? h.close()}
207+ let data=try h.read(upToCount:max+1) ?? Data();guard data.count<=max else{throw GardenError.bad("File exceeds the prototype size limit.")};try action(data)
208+ }catch{status=error.localizedDescription}
209+ }
210+ private func plant(_ x:Double,_ z:Double){
211+ guard x.isFinite,z.isFinite,abs(x)<=1000,abs(z)<=1000,garden.plants.count<500 else{status="Try coordinates within ±1,000 metres, or remove a plant (500 max).";return}
212+ garden.plants.append(.init(type:species,x:x,z:z));status="\(species.rawValue) placed."
213+ }
214+ private func projection(_ s:CGSize)->Projection {
215+ let span=max(12,garden.house.map{hypot($0.x,$0.z)*2}.max() ?? 0)
216+ let height=garden.house.map(\.y).max() ?? 0
217+ return .init(size:s,angle:angle,scale:max(1,min(s.width*0.78/span,s.height*0.48/(span*0.36+height))))
218+ }
219+ private struct DrawItem{let depth:Double;let path:Path;let fill:Color?;let stroke:Color?}
220+ private func render(_ context:GraphicsContext,_ p:Projection){
221+ let extent=min(1000,max(18,Int(p.size.width/max(1,p.scale))))
222+ let step=max(1,extent/25)
223+ let grid=Color(red:0.73,green:0.77,blue:0.68)
224+ func ground(_ x:Int,_ z:Int)->CGPoint{p.point(.init(x:Double(x),y:0,z:Double(z))).0}
225+ for i in stride(from:-extent,to:extent+1,by:step){context.stroke(Path{v in v.move(to:ground(i,-extent));v.addLine(to:ground(i,extent));v.move(to:ground(-extent,i));v.addLine(to:ground(extent,i))},with:.color(grid),lineWidth:0.6)}
226+ var items:[DrawItem]=[]
227+ for n in stride(from:0,to:garden.house.count,by:3) {
228+ let (a,da)=p.point(garden.house[n]),(b,db)=p.point(garden.house[n+1]),(c,dc)=p.point(garden.house[n+2])
229+ let face=Path{v in v.move(to:a);v.addLine(to:b);v.addLine(to:c);v.closeSubpath()}
230+ items.append(.init(depth:(da+db+dc)/3,path:face,fill:Color(red:0.81,green:0.75,blue:0.66),stroke:.brown))
231+ }
232+ for plant in garden.plants{
233+ let (base,depth)=p.point(.init(x:plant.x,y:0,z:plant.z)),(top,_)=p.point(.init(x:plant.x,y:plant.type.height,z:plant.z)),radius=max(2,p.scale*plant.type.spread)
234+ items.append(.init(depth:depth,path:Path{v in v.move(to:base);v.addLine(to:top)},fill:nil,stroke:.brown))
235+ items.append(.init(depth:depth+0.01,path:Path(ellipseIn:.init(x:top.x-radius,y:top.y-radius*0.69,width:radius*2,height:radius*1.38)),fill:plant.type.color,stroke:nil))
236+ }
237+ for i in items.sorted(by:{$0.depth<$1.depth}){if let fill=i.fill{context.fill(i.path,with:.color(fill))};if let stroke=i.stroke{context.stroke(i.path,with:.color(stroke),lineWidth:0.8)}}
238+ }
239+ }
240+ @main struct GroundroomApp:App {
241+ #if GROUNDROOM_SELF_TEST
242+ @MainActor static func main() {
243+ if let i=CommandLine.arguments.firstIndex(of:"--snapshot"),CommandLine.arguments.count>i+1 {
244+ do {try capture(to:CommandLine.arguments[i+1]);return}
245+ catch {print(error.localizedDescription);exit(2)}
246+ }
247+ do {try tests();print("Groundroom tests passed: ASCII/binary STL, malformed/oversize input, units and orientation, editable house dimensions, projection round trip, project save/load.")}
248+ catch {print(error.localizedDescription);exit(1)}
249+ }
250+ #endif
251+ #if os(visionOS)
252+ @StateObject private var walkthrough = WalkthroughState()
253+ #endif
254+ var body:some Scene {
255+ WindowGroup("Groundroom"){
256+ #if os(visionOS)
257+ TabView {
258+ GardenView().tabItem { Label("Design", systemImage: "square.grid.2x2") }
259+ WalkthroughWindow(state: walkthrough).tabItem { Label("Sample walkthrough", systemImage: "visionpro") }
260+ }
261+ #else
262+ GardenView()
263+ #endif
264+ }
265+ #if os(visionOS)
266+ ImmersiveSpace(id:"groundroom-walkthrough"){WalkthroughRoom(state:walkthrough)}
267+ .immersionStyle(selection:.constant(.mixed),in:.mixed)
268+ #endif
269+ }
270+ }
271+ #if GROUNDROOM_SELF_TEST
272+ @MainActor func capture(to path:String)throws {
273+ let sample=Garden(spec:.init(width:6,depth:4,wall:2,rise:1),house:Mesh.house(),plants:[.init(type:.Tree,x:2,z:3),.init(type:.Shrub,x:-3,z:3),.init(type:.Grass,x:4,z:2)])
274+ let renderer=ImageRenderer(content:GardenView(initial:sample,snapshot:true).frame(width:1200,height:840).background(Color.white).environment(\.colorScheme,.light))
275+ renderer.scale=1
276+ guard let image=renderer.nsImage,let tiff=image.tiffRepresentation,let rep=NSBitmapImageRep(data:tiff),let png=rep.representation(using:.png,properties:[:]) else{throw GardenError.bad("Could not render native preview.")}
277+ try png.write(to:URL(fileURLWithPath:path))
278+ print("Rendered native Groundroom SwiftUI editor (synthetic model).")
279+ }
280+ func tests()throws{
281+ let ascii=Data("solid demo\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1000 0 0\nvertex 0 1500 2000\nendloop\nendfacet\nendsolid demo".utf8)
282+ let mesh=try Mesh.parse(ascii);precondition(mesh.count==3)
283+ var binary=Data(repeating:0,count:134)
284+ func put(_ name:UInt32,_ location:Int){var word=name.littleEndian;withUnsafeBytes(of:&word){binary.replaceSubrange(location..<location+4,with:$0)}}
285+ put(1,80)
286+ for(i,n) in [0,0,0,1000,0,0,0,1500,2000].enumerated(){put(Float(n).bitPattern,96+i*4)}
287+ let b=try Mesh.parse(binary);precondition(mesh==b)
288+ for invalid in [binary.dropLast(),Data(count:Mesh.maxBytes+1),Data("solid x\nendfacet\nendsolid".utf8)]{do{_ = try Mesh.parse(invalid);preconditionFailure("Accepted invalid mesh")}catch{}}
289+ let v=try Mesh.orient(mesh,units:.mm,up:.Z);precondition(v[2].y==2 && v[1].x-v[0].x==1)
290+ do {_ = try Mesh.orient(mesh,units:.m,up:.Z);preconditionFailure("Accepted excessive scale")}catch{}
291+ let gable=Mesh.house(width:8,depth:6,wall:3,rise:2)
292+ precondition(gable.map(\.y).max()==5 && gable.map(\.x).max()==4 && gable.map(\.z).max()==3)
293+ let d=Garden(spec:.init(width:8,depth:6,wall:3,rise:2),house:v,plants:[.init(type:.Shrub,x:4,z:-4)])
294+ let round=try JSONDecoder().decode(Garden.self,from:JSONEncoder().encode(d)).checked();precondition(round==d)
295+ let p=Projection(size:.init(width:600,height:400),angle:.pi/4,scale:28)
296+ let (x,z)=p.ground(p.point(.init(x:4,y:0,z:-4)).0)
297+ precondition(abs(x-4)<1e-9 && abs(z+4)<1e-9)
298+ }
299+
300+ #endif

Sources/GroundroomWalkthrough.swift added

1+ #if os(visionOS)
2+ import SwiftUI
3+ import RealityKit
4+ import Combine
5+
6+ @MainActor
7+ final class WalkthroughState: ObservableObject {
8+ enum Phase: Equatable { case window, opening, immersive, closing }
9+ @Published var phase = Phase.window
10+ @Published var viewpoint = RoomLayout.Viewpoint.entrance
11+ @Published var openError = false
12+ }
13+
14+ // Embedded by GroundroomApp on visionOS.
15+ struct WalkthroughWindow: View {
16+ @ObservedObject var state: WalkthroughState
17+ @Environment(\.openImmersiveSpace) private var openSpace
18+ @Environment(\.dismissImmersiveSpace) private var dismissSpace
19+
20+ var body: some View {
21+ VStack(alignment: .leading, spacing: 16) {
22+ Text("Groundroom Walkthrough").font(.title2.bold())
23+ Text("Preview a sample room at life size with your surroundings visible. Stay in one comfortable spot and choose a viewpoint.")
24+ .foregroundStyle(.secondary)
25+ if state.phase == .immersive {
26+ Picker("Viewpoint", selection: $state.viewpoint) {
27+ ForEach(RoomLayout.Viewpoint.allCases) { view in Text(view.rawValue).tag(view) }
28+ }
29+ Button("Exit walkthrough", systemImage: "xmark") {
30+ state.phase = .closing
31+ Task {
32+ await dismissSpace()
33+ state.phase = .window
34+ }
35+ }
36+ } else {
37+ Button("Enter walkthrough", systemImage: "visionpro") {
38+ state.openError = false
39+ state.phase = .opening
40+ state.viewpoint = .entrance
41+ Task {
42+ switch await openSpace(id: "groundroom-walkthrough") {
43+ case .opened: state.phase = .immersive
44+ case .userCancelled: state.phase = .window
45+ default:
46+ state.phase = .window
47+ state.openError = true
48+ }
49+ }
50+ }
51+ .disabled(state.phase != .window)
52+ }
53+ if state.openError { Text("The walkthrough couldn’t open. Try again.").foregroundStyle(.secondary) }
54+ }
55+ .padding(32)
56+ .frame(maxWidth: 560, alignment: .leading)
57+ }
58+ }
59+
60+ struct WalkthroughRoom: View {
61+ @ObservedObject var state: WalkthroughState
62+
63+ var body: some View {
64+ RealityView { content in
65+ guard let room = try? RoomLayout.example.checked() else { return }
66+ let root = Entity()
67+ root.name = "groundroom-preview"
68+ root.position = room.translation(for: state.viewpoint)
69+ let width = Float(room.width), depth = Float(room.depth)
70+ let tone = SimpleMaterial(color: .systemTeal, isMetallic: false)
71+ for sign: Float in [-1, 1] {
72+ let side = ModelEntity(mesh: .generateBox(size: [0.025, 0.025, depth]), materials: [tone])
73+ side.position = [sign * width / 2, 0.013, 0]
74+ root.addChild(side)
75+ let edge = ModelEntity(mesh: .generateBox(size: [width, 0.025, 0.025]), materials: [tone])
76+ edge.position = [0, 0.013, sign * depth / 2]
77+ root.addChild(edge)
78+ }
79+ for (index, b) in room.blocks.enumerated() {
80+ let material = SimpleMaterial(color: index == 1 ? .systemBrown : .systemGray, isMetallic: false)
81+ let block = ModelEntity(mesh: .generateBox(size: [Float(b.width), Float(b.height), Float(b.depth)]),
82+ materials: [material])
83+ block.position = [Float(b.x), Float(b.height / 2), Float(b.z)]
84+ root.addChild(block)
85+ }
86+ content.add(root)
87+ } update: { content in
88+ if let root = content.entities.first(where: { $0.name == "groundroom-preview" }) {
89+ root.position = RoomLayout.example.translation(for: state.viewpoint)
90+ }
91+ }
92+ .onDisappear { state.phase = .window }
93+ }
94+ }
95+
96+ #endif

Sources/RoomLayout.swift added

1+ import Foundation
2+
3+ struct RoomLayout: Equatable, Sendable {
4+ enum LayoutError: Error, Equatable { case invalidRoom, invalidObject, outsideRoom, tooManyObjects }
5+ struct Block: Equatable, Sendable {
6+ var x: Double
7+ var z: Double
8+ var width: Double
9+ var depth: Double
10+ var height: Double
11+ }
12+ enum Viewpoint: String, CaseIterable, Identifiable {
13+ case entrance = "Entrance"
14+ case left = "Left side"
15+ case right = "Right side"
16+ var id: Self { self }
17+ }
18+ var width: Double
19+ var depth: Double
20+ var height: Double
21+ var blocks: [Block]
22+
23+ func checked() throws -> RoomLayout {
24+ guard (2...12).contains(width), (2...12).contains(depth), (2...5).contains(height)
25+ else { throw LayoutError.invalidRoom }
26+ guard blocks.count <= 24 else { throw LayoutError.tooManyObjects }
27+ for b in blocks {
28+ guard b.x.isFinite, b.z.isFinite, (0.1...4).contains(b.width),
29+ (0.1...4).contains(b.depth), (0.1...3).contains(b.height)
30+ else { throw LayoutError.invalidObject }
31+ guard abs(b.x) + b.width / 2 <= width / 2,
32+ abs(b.z) + b.depth / 2 <= depth / 2, b.height <= height
33+ else { throw LayoutError.outsideRoom }
34+ }
35+ return self
36+ }
37+
38+ /// Offset the preview rather than moving the headset/user camera.
39+ func translation(for viewpoint: Viewpoint) -> SIMD3<Float> {
40+ let fraction: Double
41+ switch viewpoint {
42+ case .entrance: fraction = 0
43+ case .left: fraction = 0.20
44+ case .right: fraction = -0.20
45+ }
46+ return SIMD3(Float(fraction * width), 0, Float(-0.8 - depth / 2))
47+ }
48+
49+ static let example = RoomLayout(width: 4, depth: 4.6, height: 2.6, blocks: [
50+ Block(x: -1.05, z: 0.15, width: 1.5, depth: 0.8, height: 0.66),
51+ Block(x: 0.8, z: -0.45, width: 0.9, depth: 0.52, height: 0.42),
52+ Block(x: 1.25, z: 1.3, width: 0.55, depth: 0.65, height: 0.95)
53+ ])
54+ }

docs/screenshots/groundroom-compact-native.png added

Not a text file.

docs/screenshots/groundroom-macos-native.png added

Not a text file.

project.yml added

1+ name: Groundroom
2+ options:
3+ minimumXcodeGenVersion: 2.42.0
4+ settings:
5+ base:
6+ PRODUCT_NAME: Groundroom
7+ PRODUCT_BUNDLE_IDENTIFIER: com.groundroom.prototype
8+ MARKETING_VERSION: 0.1.0
9+ CURRENT_PROJECT_VERSION: 1
10+ GENERATE_INFOPLIST_FILE: YES
11+ INFOPLIST_KEY_CFBundleDisplayName: Groundroom
12+ SWIFT_VERSION: 5.0
13+ CODE_SIGN_STYLE: Automatic
14+ targets:
15+ GroundroomMac:
16+ type: application
17+ platform: macOS
18+ deploymentTarget: "14.0"
19+ sources: [Sources]
20+ entitlements:
21+ path: GroundroomMac.entitlements
22+ properties:
23+ com.apple.security.app-sandbox: true
24+ com.apple.security.files.user-selected.read-write: true
25+ GroundroomMobile:
26+ type: application
27+ platform: iOS
28+ deploymentTarget: "17.0"
29+ sources: [Sources]
30+ settings:
31+ base:
32+ TARGETED_DEVICE_FAMILY: "1,2"
33+ INFOPLIST_KEY_UILaunchScreen_Generation: YES
34+ GroundroomVision:
35+ type: application
36+ platform: visionOS
37+ deploymentTarget: "2.0"
38+ sources: [Sources]
39+ settings:
40+ base:
41+ TARGETED_DEVICE_FAMILY: "7"
42+ schemes:
43+ GroundroomMac:
44+ build:
45+ targets:
46+ GroundroomMac: all
47+ GroundroomMobile:
48+ build:
49+ targets:
50+ GroundroomMobile: all
51+ GroundroomVision:
52+ build:
53+ targets:
54+ GroundroomVision: all

tools/check.sh added

1+ #!/bin/bash
2+ set -euo pipefail
3+ cd "$(dirname "$0")/.."
4+ out="${1:-.check-build}"
5+ mkdir -p "$out/tmp" "$out/modules"
6+ out="$(cd "$out" && pwd)"
7+ export TMPDIR="$out/tmp" CLANG_MODULE_CACHE_PATH="$out/modules"
8+ swift=(xcrun swiftc -parse-as-library -module-cache-path "$out/modules")
9+ "${swift[@]}" -D GROUNDROOM_SELF_TEST Sources/Groundroom.swift -o "$out/GroundroomChecks"
10+ "$out/GroundroomChecks"
11+ "${swift[@]}" Sources/RoomLayout.swift Checks/LayoutChecks.swift -o "$out/LayoutChecks"
12+ "$out/LayoutChecks"
13+ for entry in 'macosx arm64-apple-macosx14.0 Mac' 'iphoneos arm64-apple-ios17.0 iPhone-iPad' 'xros arm64-apple-xros2.0 VisionPro' 'xrsimulator arm64-apple-xros2.0-simulator VisionSimulator'; do
14+ set -- $entry
15+ sdk=$1 target=$2 name=$3
16+ "${swift[@]}" -target "$target" -sdk "$(xcrun --sdk "$sdk" --show-sdk-path)" Sources/*.swift -o "$out/$name"
17+ xcrun vtool -show-build "$out/$name" | grep -E 'platform|minos' | tr -s ' '
18+ done

Browse files at this commit