Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Engines/SmartScan/CardQuad.swift8// Module : SPVault9// Repository : https://git.spboucher.ai/sp-id-card-vault10// Project Website : Not specified11// Created : 2026-12-0212// Last Modified : 2026-12-0213//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import CoreGraphics42import Foundation4344/// Four corners of a card in an upright image. Coordinates are normalised to the45/// image (0…1) with the origin at the top-left, x to the right, y downwards.46struct CardQuad: Equatable, Sendable {47 var topLeft: CGPoint48 var topRight: CGPoint49 var bottomRight: CGPoint50 var bottomLeft: CGPoint5152 var corners: [CGPoint] { [topLeft, topRight, bottomRight, bottomLeft] }5354 init(topLeft: CGPoint, topRight: CGPoint, bottomRight: CGPoint, bottomLeft: CGPoint) {55 self.topLeft = topLeft56 self.topRight = topRight57 self.bottomRight = bottomRight58 self.bottomLeft = bottomLeft59 }6061 /// Orders four arbitrary points as top-left, top-right, bottom-right, bottom-left.62 init(unordered points: [CGPoint]) {63 precondition(points.count == 4)64 let centre = CGPoint(x: points.map(\.x).reduce(0, +) / 4, y: points.map(\.y).reduce(0, +) / 4)65 let sorted = points.sorted { atan2($0.y - centre.y, $0.x - centre.x) < atan2($1.y - centre.y, $1.x - centre.x) }66 // Angles ascend clockwise on screen (y down), starting in the upper-left quadrant.67 let start = sorted.enumerated().min { ($0.element.x + $0.element.y) < ($1.element.x + $1.element.y) }!.offset68 let ordered = (0..<4).map { sorted[(start + $0) % 4] }69 self.init(topLeft: ordered[0], topRight: ordered[1], bottomRight: ordered[2], bottomLeft: ordered[3])70 }7172 /// Centred rectangle with the given aspect ratio (in pixels), used when no73 /// card was detected so the owner can place the corners by hand.74 static func centred(aspect: Double, imageSize: CGSize, widthFraction: CGFloat = 0.8) -> CardQuad {75 let w = widthFraction76 var h = w * imageSize.width / CGFloat(aspect) / max(imageSize.height, 1)77 h = min(h, 0.9)78 let x = (1 - w) / 2, y = (1 - h) / 279 return CardQuad(topLeft: CGPoint(x: x, y: y), topRight: CGPoint(x: x + w, y: y),80 bottomRight: CGPoint(x: x + w, y: y + h), bottomLeft: CGPoint(x: x, y: y + h))81 }8283 static let full = CardQuad(topLeft: .zero, topRight: CGPoint(x: 1, y: 0), bottomRight: CGPoint(x: 1, y: 1), bottomLeft: CGPoint(x: 0, y: 1))8485 var boundingBox: CGRect {86 let xs = corners.map(\.x), ys = corners.map(\.y)87 return CGRect(x: xs.min()!, y: ys.min()!, width: xs.max()! - xs.min()!, height: ys.max()! - ys.min()!)88 }8990 /// Area in normalised units (shoelace formula).91 var area: CGFloat {92 let p = corners93 var sum: CGFloat = 094 for i in 0..<4 {95 let a = p[i], b = p[(i + 1) % 4]96 sum += a.x * b.y - b.x * a.y97 }98 return abs(sum) / 299 }100101 var isConvex: Bool {102 let p = corners103 var sign: CGFloat = 0104 for i in 0..<4 {105 let a = p[i], b = p[(i + 1) % 4], c = p[(i + 2) % 4]106 let cross = (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x)107 if abs(cross) < 1e-9 { return false }108 if sign == 0 { sign = cross } else if (cross > 0) != (sign > 0) { return false }109 }110 return true111 }112113 /// Largest distance between matching corners of two quads.114 func maxCornerDistance(to other: CardQuad) -> CGFloat {115 zip(corners, other.corners).map { hypot($0.x - $1.x, $0.y - $1.y) }.max() ?? 0116 }117118 /// Width / height of the card as seen in an image of `imageSize` pixels119 /// (mean of opposite edges). A first estimate; the perspective correction120 /// gives the final ratio.121 func apparentAspect(imageSize: CGSize) -> Double {122 func d(_ a: CGPoint, _ b: CGPoint) -> CGFloat {123 hypot((a.x - b.x) * imageSize.width, (a.y - b.y) * imageSize.height)124 }125 let width = (d(topLeft, topRight) + d(bottomLeft, bottomRight)) / 2126 let height = (d(topLeft, bottomLeft) + d(topRight, bottomRight)) / 2127 return height > 0 ? Double(width / height) : 1128 }129130 func clamped() -> CardQuad {131 func c(_ p: CGPoint) -> CGPoint { CGPoint(x: min(max(p.x, 0), 1), y: min(max(p.y, 0), 1)) }132 return CardQuad(topLeft: c(topLeft), topRight: c(topRight), bottomRight: c(bottomRight), bottomLeft: c(bottomLeft))133 }134}135136struct DetectedCard: Equatable, Sendable {137 var quad: CardQuad138 var confidence: Float139}140141/// Tells whether the detected card has stopped moving between video frames.142struct StabilityTracker: Sendable {143 /// Largest corner movement (normalised) still considered "steady".144 var tolerance: CGFloat = 0.012145 var requiredFrames = 6146 private var last: CardQuad?147 private(set) var steadyFrames = 0148149 init(tolerance: CGFloat = 0.012, requiredFrames: Int = 6) {150 self.tolerance = tolerance151 self.requiredFrames = requiredFrames152 }153154 var isStable: Bool { steadyFrames >= requiredFrames }155156 @discardableResult157 mutating func feed(_ quad: CardQuad?) -> Bool {158 defer { last = quad }159 guard let quad, let last, quad.maxCornerDistance(to: last) <= tolerance else {160 steadyFrames = 0161 return false162 }163 steadyFrames += 1164 return isStable165 }166167 mutating func reset() {168 last = nil169 steadyFrames = 0170 }171}172