Branchwell

Groundroom / app · groundroom.ai / Sources / Groundroom.swift

1import Foundation
2import SwiftUI
3import ImageIO
4#if GROUNDROOM_SELF_TEST && os(macOS)
5import AppKit
6#endif
7import UniformTypeIdentifiers
8
9enum GardenError: LocalizedError { case bad(String); var errorDescription: String? { if case .bad(let s)=self{return s};return nil } }
10struct 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}
13enum Up:String,CaseIterable { case Y,Z }
14enum 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} } }
15enum 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}
20struct Plant: Codable,Equatable {var type:Species;var x:Double;var z:Double}
21struct HouseSpec:Codable,Equatable {var width:Double;var depth:Double;var wall:Double;var rise:Double}
22struct 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}
29enum 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
77struct 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}
84struct 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}
92struct 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}
280func 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