Skip to content

Commit 0b1ec9f

Browse files
committed
Add convertTo3DSpace
1 parent 6486f0f commit 0b1ec9f

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

Sources/GateEngine/System/Rendering/Drawables/Canvas.swift

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,28 @@ import GameMath
174174
return Position2(position.x, position.y)
175175
}
176176

177+
@inlinable @inline(__always)
178+
public func convertTo3DSpace(_ position: Position2) -> Ray3D {
179+
guard let camera = camera else {preconditionFailure("Must set camera during `Canvas.init` to use \(#function).")}
180+
guard let size = size else {preconditionFailure("Must set size during `Canvas.init` to use \(#function).")}
181+
182+
let halfSize = size / 2
183+
let aspectRatio = size.aspectRatio
184+
185+
let inverseView = camera.matricies(withAspectRatio: aspectRatio).view.inverse
186+
let halfFOV = tanf(camera._fieldOfView.rawValue * 0.5)
187+
let near = camera.clippingPlane.near
188+
let far = camera.clippingPlane.far
189+
190+
let dx = halfFOV * (position.x / halfSize.width - 1.0) * aspectRatio
191+
let dy = halfFOV * (1.0 - position.y / halfSize.height)
192+
193+
let p1 = Position3(dx * near, dy * near, near) * inverseView
194+
let p2 = Position3(dx * far, dy * far, far) * inverseView
195+
196+
return Ray3D(from: p1, toward: p2)
197+
}
198+
177199
/**
178200
Create a canvas.
179201

0 commit comments

Comments
 (0)