Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Cosmos9// File : DataPipeline/textures/tools/imgtool.swift10// Module : DataPipeline11// Repository : https://git.spboucher.ai/orix-cosmos12// Project Website : https://www.orixlab.dev13// Created : 2026-11-2414// Last Modified : 2026-11-2415//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// ORIX Cosmos89// File: DataPipeline/textures/tools/imgtool.swift90// Description: Command-line image tool of the texture pipeline (ImageIO/CoreGraphics only): decodes TIFF/JPEG/PNG/OpenEXR, raw PDS grids and WMTS tile directories, rolls/flips longitudes to the ORIX map convention, area-averages to a resolution pyramid, derives masks and normal maps, and writes JPEG/PNG.91//92// Author: Simon-Pierre Boucher93// Contact: contact@spboucher.ai94//95// Build: swiftc -O -o imgtool imgtool.swift96// Usage: imgtool info <image>97// imgtool sample <image> <lonEastDeg> <latDeg> [halfWidthDeg] (image in the ORIX convention)98// imgtool build --in <image | tile directory> --mode <mode> --levels 4096,2048 --out <pattern with {w}> [options]99// Modes: color (sRGB JPEG, averaged in linear light) · mono (grey imagery replicated to RGB JPEG) ·100// hdr (float OpenEXR, exposure, sRGB JPEG) · data8 / data16 (grey PNG, plain average) ·101// mask (grey PNG: 255 where the source is below --threshold) · cloud (RGBA PNG, white, alpha = source grey) ·102// normal (RGB PNG tangent-space normals from a height grid)103// Options: --src-lon-left <deg> east longitude of the left edge of the source (default -180)104// --west-positive source longitude increases to the left (west-positive maps)105// --lat-top/--lat-bottom latitude coverage of the source rows (default 90 / -90); missing bands are106// filled by repeating the nearest source row and must be declared as a coverage gap107// --valid-lat-top/--valid-lat-bottom rows outside this latitude band hold no usable data: they are replaced108// by the zonal mean of the nearest valid row (a declared fill, never presented as data)109// --raw16be W H the input is a headerless big-endian signed 16-bit grid110// --height-scale s --height-offset o metres = o + s * source value (normal, data16 re-encoding)111// --radius-m R --exaggeration E body radius and slope exaggeration of the normal map112// --out-offset o --out-scale s data16 output value = (metres - o) / s113// --quality q (JPEG, default 0.9) · --exposure k (hdr) · --threshold t (mask, source units)114import CoreGraphics115import Foundation116import ImageIO117import UniformTypeIdentifiers118119func fail(_ message: String) -> Never {120 FileHandle.standardError.write((message + "\n").data(using: .utf8)!)121 exit(1)122}123124/// Planar float raster, row-major, first row at the top. Colour planes hold linear-light values in [0, 1]125/// (or unbounded for HDR); data planes hold the source numbers unchanged.126struct Raster {127 var width: Int128 var height: Int129 var channels: Int130 var data: [Float]131 init(width: Int, height: Int, channels: Int) {132 self.width = width; self.height = height; self.channels = channels133 data = [Float](repeating: 0, count: width * height * channels)134 }135}136137let srgbToLinear: [Float] = (0..<256).map { i in138 let c = Float(i) / 255139 return c <= 0.04045 ? c / 12.92 : powf((c + 0.055) / 1.055, 2.4)140}141142func linearToSRGB8(_ v: Float) -> UInt8 {143 let c = min(max(v, 0), 1)144 let e = c <= 0.0031308 ? c * 12.92 : 1.055 * powf(c, 1 / 2.4) - 0.055145 return UInt8((e * 255).rounded())146}147148struct Decoded {149 var width: Int150 var height: Int151 var channels: Int // 1 or 3152 var bits: Int // 8, 16 or 32 (float)153 var bytes8: [UInt8] = []154 var words16: [UInt16] = []155 var floats: [Float] = []156}157158func loadCGImage(_ path: String) -> CGImage {159 guard let src = CGImageSourceCreateWithURL(URL(fileURLWithPath: path) as CFURL, nil),160 let image = CGImageSourceCreateImageAtIndex(src, 0, nil) else { fail("cannot decode \(path)") }161 return image162}163164/// Decodes without colour management: the context uses the image's own colour space, so stored numbers are preserved.165func decode(_ path: String) -> Decoded {166 let image = loadCGImage(path)167 let w = image.width, h = image.height168 let model = image.colorSpace?.model ?? .rgb169 let isGray = model == .monochrome170 let isFloat = image.bitmapInfo.contains(.floatComponents)171 if isFloat {172 let space = CGColorSpace(name: CGColorSpace.extendedLinearSRGB)!173 var out = Decoded(width: w, height: h, channels: 3, bits: 32)174 var buf = [Float](repeating: 0, count: w * h * 4)175 buf.withUnsafeMutableBytes { p in176 let info = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue | CGBitmapInfo.floatComponents.rawValue177 guard let ctx = CGContext(data: p.baseAddress, width: w, height: h, bitsPerComponent: 32, bytesPerRow: w * 16, space: space, bitmapInfo: info) else { fail("float context") }178 ctx.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))179 }180 out.floats = [Float](repeating: 0, count: w * h * 3)181 for i in 0..<(w * h) { out.floats[i * 3] = buf[i * 4]; out.floats[i * 3 + 1] = buf[i * 4 + 1]; out.floats[i * 3 + 2] = buf[i * 4 + 2] }182 return out183 }184 if isGray && image.bitsPerComponent == 16 {185 var out = Decoded(width: w, height: h, channels: 1, bits: 16)186 out.words16 = [UInt16](repeating: 0, count: w * h)187 out.words16.withUnsafeMutableBytes { p in188 let info = CGImageAlphaInfo.none.rawValue | CGBitmapInfo.byteOrder16Little.rawValue189 guard let ctx = CGContext(data: p.baseAddress, width: w, height: h, bitsPerComponent: 16, bytesPerRow: w * 2,190 space: image.colorSpace ?? CGColorSpaceCreateDeviceGray(), bitmapInfo: info) else { fail("gray16 context") }191 ctx.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))192 }193 return out194 }195 if isGray {196 var out = Decoded(width: w, height: h, channels: 1, bits: 8)197 out.bytes8 = [UInt8](repeating: 0, count: w * h)198 out.bytes8.withUnsafeMutableBytes { p in199 guard let ctx = CGContext(data: p.baseAddress, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w,200 space: image.colorSpace ?? CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { fail("gray8 context") }201 ctx.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))202 }203 return out204 }205 var out = Decoded(width: w, height: h, channels: 3, bits: 8)206 var rgba = [UInt8](repeating: 0, count: w * h * 4)207 let space = (model == .rgb ? image.colorSpace : nil) ?? CGColorSpace(name: CGColorSpace.sRGB)!208 rgba.withUnsafeMutableBytes { p in209 // Transparent pixels (tiles without data) composite over black.210 guard let ctx = CGContext(data: p.baseAddress, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4, space: space,211 bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { fail("rgba context") }212 ctx.draw(image, in: CGRect(x: 0, y: 0, width: w, height: h))213 }214 out.bytes8 = [UInt8](repeating: 0, count: w * h * 3)215 for i in 0..<(w * h) { out.bytes8[i * 3] = rgba[i * 4]; out.bytes8[i * 3 + 1] = rgba[i * 4 + 1]; out.bytes8[i * 3 + 2] = rgba[i * 4 + 2] }216 return out217}218219func decodeRaw16BE(_ path: String, _ w: Int, _ h: Int) -> Raster {220 guard let d = FileManager.default.contents(atPath: path), d.count == w * h * 2 else { fail("raw16be: \(path) is not \(w) x \(h) x 2 bytes") }221 var r = Raster(width: w, height: h, channels: 1)222 d.withUnsafeBytes { p in223 for i in 0..<(w * h) { r.data[i] = Float(Int16(bitPattern: UInt16(p[i * 2]) << 8 | UInt16(p[i * 2 + 1]))) }224 }225 return r226}227228/// Stitches a WMTS tile directory written by fetch_textures.py into one 8-bit RGB image.229func decodeTiles(_ dir: String) -> Decoded {230 guard let meta = FileManager.default.contents(atPath: dir + "/tiles.json"),231 let j = try? JSONSerialization.jsonObject(with: meta) as? [String: Any],232 let tile = j["tile"] as? Int, let cols = j["cols"] as? Int, let rows = j["rows"] as? Int, let ext = j["ext"] as? String else { fail("no tiles.json in \(dir)") }233 if (j["missing"] as? Int ?? 0) != 0 { fail("\(dir): tile set is incomplete") }234 let w = cols * tile, h = rows * tile235 var out = Decoded(width: w, height: h, channels: 3, bits: 8)236 out.bytes8 = [UInt8](repeating: 0, count: w * h * 3)237 for row in 0..<rows {238 for col in 0..<cols {239 let t = decode("\(dir)/\(row)_\(col).\(ext)")240 guard t.width == tile, t.height == tile, t.bits == 8 else { fail("tile \(row)_\(col): unexpected size or depth") }241 for y in 0..<tile {242 let dst = ((row * tile + y) * w + col * tile) * 3243 for x in 0..<tile {244 if t.channels == 3 {245 let s = (y * tile + x) * 3246 out.bytes8[dst + x * 3] = t.bytes8[s]; out.bytes8[dst + x * 3 + 1] = t.bytes8[s + 1]; out.bytes8[dst + x * 3 + 2] = t.bytes8[s + 2]247 } else {248 let v = t.bytes8[y * tile + x]249 out.bytes8[dst + x * 3] = v; out.bytes8[dst + x * 3 + 1] = v; out.bytes8[dst + x * 3 + 2] = v250 }251 }252 }253 }254 }255 return out256}257258/// Converts decoded pixels to a float raster. `linearise` turns 8-bit sRGB code values into linear light.259func toRaster(_ d: Decoded, linearise: Bool, forceGray: Bool) -> Raster {260 let n = d.width * d.height261 let outChannels = forceGray ? 1 : d.channels262 var r = Raster(width: d.width, height: d.height, channels: outChannels)263 func value(_ i: Int, _ c: Int) -> Float {264 switch d.bits {265 case 8: let b = d.bytes8[i * d.channels + c]; return linearise ? srgbToLinear[Int(b)] : Float(b)266 case 16: return Float(d.words16[i * d.channels + c])267 default: return d.floats[i * d.channels + c]268 }269 }270 r.data.withUnsafeMutableBufferPointer { out in271 let ptr = SendablePointer(out.baseAddress!)272 DispatchQueue.concurrentPerform(iterations: d.height) { y in273 for x in 0..<d.width {274 let i = y * d.width + x275 if forceGray && d.channels == 3 {276 ptr.p[i] = (value(i, 0) + value(i, 1) + value(i, 2)) / 3277 } else {278 for c in 0..<outChannels { ptr.p[i * outChannels + c] = value(i, c) }279 }280 }281 }282 }283 _ = n284 return r285}286287struct SendablePointer<T>: @unchecked Sendable { let p: UnsafeMutablePointer<T>; init(_ p: UnsafeMutablePointer<T>) { self.p = p } }288289/// Brings a source map to the ORIX convention: east-positive to the right, left edge at -180, rows from +90 to -90.290func normaliseGeometry(_ r: Raster, srcLonLeft: Double, westPositive: Bool, latTop: Double, latBottom: Double) -> Raster {291 var src = r292 if westPositive {293 // Column i shows longitude decreasing eastwards: mirror so that east is to the right.294 var m = Raster(width: r.width, height: r.height, channels: r.channels)295 for y in 0..<r.height { for x in 0..<r.width { for c in 0..<r.channels {296 m.data[(y * r.width + x) * r.channels + c] = r.data[(y * r.width + (r.width - 1 - x)) * r.channels + c] } } }297 src = m298 }299 // After mirroring, the left edge of a west-positive map is at east longitude -(srcLonLeft) - 360, i.e. (360 - left) - 360.300 let left = westPositive ? -srcLonLeft : srcLonLeft301 var shift = Int(((-180 - left) / 360 * Double(src.width)).rounded())302 shift = ((shift % src.width) + src.width) % src.width303 let fullHeight = (latTop == 90 && latBottom == -90) ? src.height : Int((180 / (latTop - latBottom) * Double(src.height)).rounded())304 let rowOffset = Int(((90 - latTop) / 180 * Double(fullHeight)).rounded())305 if shift == 0 && fullHeight == src.height { return src }306 var out = Raster(width: src.width, height: fullHeight, channels: src.channels)307 let ch = src.channels, w = src.width308 for y in 0..<fullHeight {309 let sy = min(max(y - rowOffset, 0), src.height - 1)310 for x in 0..<w {311 let sx = (x + shift) % w312 for c in 0..<ch { out.data[(y * w + x) * ch + c] = src.data[(sy * w + sx) * ch + c] }313 }314 }315 return out316}317318/// Separable area-average (box) resampling to a smaller or equal size.319func resample(_ r: Raster, toWidth w: Int, height h: Int) -> Raster {320 if w == r.width && h == r.height { return r }321 precondition(w <= r.width && h <= r.height, "the pipeline never upsamples")322 let ch = r.channels323 var mid = Raster(width: w, height: r.height, channels: ch)324 let sx = Double(r.width) / Double(w)325 r.data.withUnsafeBufferPointer { src in326 mid.data.withUnsafeMutableBufferPointer { dst in327 let d = SendablePointer(dst.baseAddress!)328 let s = SendablePointer(UnsafeMutablePointer(mutating: src.baseAddress!))329 DispatchQueue.concurrentPerform(iterations: r.height) { y in330 for x in 0..<w {331 let a = Double(x) * sx, b = Double(x + 1) * sx332 let i0 = Int(a), i1 = min(Int(b.rounded(.up)), r.width)333 for c in 0..<ch {334 var acc: Float = 0335 for i in i0..<i1 {336 let cover = Float(min(Double(i + 1), b) - max(Double(i), a))337 acc += s.p[(y * r.width + i) * ch + c] * cover338 }339 d.p[(y * w + x) * ch + c] = acc / Float(sx)340 }341 }342 }343 }344 }345 var out = Raster(width: w, height: h, channels: ch)346 let sy = Double(r.height) / Double(h)347 mid.data.withUnsafeBufferPointer { src in348 out.data.withUnsafeMutableBufferPointer { dst in349 let d = SendablePointer(dst.baseAddress!)350 let s = SendablePointer(UnsafeMutablePointer(mutating: src.baseAddress!))351 DispatchQueue.concurrentPerform(iterations: h) { y in352 let a = Double(y) * sy, b = Double(y + 1) * sy353 let j0 = Int(a), j1 = min(Int(b.rounded(.up)), r.height)354 for x in 0..<w {355 for c in 0..<ch {356 var acc: Float = 0357 for j in j0..<j1 {358 let cover = Float(min(Double(j + 1), b) - max(Double(j), a))359 acc += s.p[(j * w + x) * ch + c] * cover360 }361 d.p[(y * w + x) * ch + c] = acc / Float(sy)362 }363 }364 }365 }366 }367 return out368}369370func write(_ path: String, width: Int, height: Int, bits: Int, channels: Int, alpha: Bool, bytes: Data, jpegQuality: Double?, tagSRGB: Bool) {371 let space: CGColorSpace = channels >= 3 ? (tagSRGB ? CGColorSpace(name: CGColorSpace.sRGB)! : CGColorSpaceCreateDeviceRGB())372 : (tagSRGB ? CGColorSpace(name: CGColorSpace.genericGrayGamma2_2)! : CGColorSpaceCreateDeviceGray())373 var info = alpha ? CGImageAlphaInfo.last.rawValue : CGImageAlphaInfo.none.rawValue374 if bits == 16 { info |= CGBitmapInfo.byteOrder16Little.rawValue }375 guard let provider = CGDataProvider(data: bytes as CFData),376 let image = CGImage(width: width, height: height, bitsPerComponent: bits, bitsPerPixel: bits * channels, bytesPerRow: width * channels * bits / 8,377 space: space, bitmapInfo: CGBitmapInfo(rawValue: info), provider: provider, decode: nil, shouldInterpolate: false, intent: .defaultIntent) else { fail("cannot build image for \(path)") }378 let type = jpegQuality != nil ? UTType.jpeg.identifier : UTType.png.identifier379 try? FileManager.default.createDirectory(atPath: (path as NSString).deletingLastPathComponent, withIntermediateDirectories: true)380 guard let dest = CGImageDestinationCreateWithURL(URL(fileURLWithPath: path) as CFURL, type as CFString, 1, nil) else { fail("cannot create \(path)") }381 var props: [CFString: Any] = [:]382 if let q = jpegQuality { props[kCGImageDestinationLossyCompressionQuality] = q }383 CGImageDestinationAddImage(dest, image, props as CFDictionary)384 if !CGImageDestinationFinalize(dest) { fail("cannot write \(path)") }385}386387// MARK: - Commands388389var args = Array(CommandLine.arguments.dropFirst())390guard let command = args.first else { fail("usage: imgtool info|sample|build … (see the file header)") }391args.removeFirst()392393func option(_ name: String) -> String? {394 guard let i = args.firstIndex(of: name), i + 1 < args.count else { return nil }395 return args[i + 1]396}397func flag(_ name: String) -> Bool { args.contains(name) }398399switch command {400case "info":401 let image = loadCGImage(args[0])402 let name = (image.colorSpace?.name as String?) ?? "untagged"403 let model: String404 switch image.colorSpace?.model {405 case .monochrome: model = "gray"406 case .rgb: model = "rgb"407 case .indexed: model = "indexed"408 default: model = "other"409 }410 print("{\"width\": \(image.width), \"height\": \(image.height), \"bitsPerComponent\": \(image.bitsPerComponent), \"bitsPerPixel\": \(image.bitsPerPixel), \"model\": \"\(model)\", \"colorSpace\": \"\(name)\", \"float\": \(image.bitmapInfo.contains(.floatComponents)), \"alpha\": \(image.alphaInfo != .none && image.alphaInfo != .noneSkipLast && image.alphaInfo != .noneSkipFirst)}")411412case "sample":413 // Mean stored value in a window around (east longitude, latitude) of an image in the ORIX convention.414 let d = decode(args[0])415 let lon = Double(args[1])!, lat = Double(args[2])!, half = args.count > 3 ? Double(args[3])! : 0.5416 var sums = [Double](repeating: 0, count: d.channels), n = 0.0417 let x0 = Int(((lon - half + 180) / 360 * Double(d.width)).rounded(.down)), x1 = Int(((lon + half + 180) / 360 * Double(d.width)).rounded(.up))418 let y0 = max(Int(((90 - lat - half) / 180 * Double(d.height)).rounded(.down)), 0), y1 = min(Int(((90 - lat + half) / 180 * Double(d.height)).rounded(.up)), d.height)419 for y in y0..<y1 { for xx in x0..<x1 {420 let x = ((xx % d.width) + d.width) % d.width421 for c in 0..<d.channels {422 let i = (y * d.width + x) * d.channels + c423 sums[c] += d.bits == 8 ? Double(d.bytes8[i]) : d.bits == 16 ? Double(d.words16[i]) : Double(d.floats[i])424 }425 n += 1426 } }427 print(sums.map { String(format: "%.3f", $0 / n) }.joined(separator: " "))428429case "rowstats":430 // Per-latitude statistics of an image (any longitude origin): fraction of black pixels and zonal standard deviation.431 let d = decode(args[0])432 let step = args.count > 1 ? Double(args[1])! : 5433 var lat = 90.0 - step / 2434 while lat > -90 {435 let y = min(Int((90 - lat) / 180 * Double(d.height)), d.height - 1)436 var black = 0, mean = [Double](repeating: 0, count: d.channels), sq = 0.0437 for x in 0..<d.width {438 var s = 0.0439 for c in 0..<d.channels { let v = Double(d.bits == 8 ? Double(d.bytes8[(y * d.width + x) * d.channels + c]) : Double(d.words16[(y * d.width + x) * d.channels + c])); mean[c] += v; s += v }440 if s < 6 { black += 1 }441 sq += (s / Double(d.channels)) * (s / Double(d.channels))442 }443 let m = mean.map { $0 / Double(d.width) }444 let avg = m.reduce(0, +) / Double(d.channels)445 let sd = max(sq / Double(d.width) - avg * avg, 0).squareRoot()446 print(String(format: "lat %6.1f black %.3f mean %@ sd %.1f", lat, Double(black) / Double(d.width), m.map { String(format: "%.0f", $0) }.joined(separator: ","), sd))447 lat -= step448 }449450case "build":451 guard let input = option("--in"), let mode = option("--mode"), let levelText = option("--levels"), let pattern = option("--out") else { fail("build needs --in --mode --levels --out") }452 let levels = levelText.split(separator: ",").map { Int($0)! }453 let srcLonLeft = Double(option("--src-lon-left") ?? "-180")!454 let latTop = Double(option("--lat-top") ?? "90")!, latBottom = Double(option("--lat-bottom") ?? "-90")!455 let quality = Double(option("--quality") ?? "0.9")!456 let heightScale = Float(option("--height-scale") ?? "1")!, heightOffset = Float(option("--height-offset") ?? "0")!457 var isDir: ObjCBool = false458 FileManager.default.fileExists(atPath: input, isDirectory: &isDir)459460 var raster: Raster461 if let raw = option("--raw16be") {462 let dims = Array(args[(args.firstIndex(of: "--raw16be")! + 1)...].prefix(2)).map { Int($0)! }463 _ = raw464 raster = decodeRaw16BE(input, dims[0], dims[1])465 } else {466 let decoded = isDir.boolValue ? decodeTiles(input) : decode(input)467 let colourModes: Set<String> = ["color", "mono"]468 if mode == "hdr" && decoded.bits != 32 { fail("hdr mode needs a floating-point image") }469 raster = toRaster(decoded, linearise: colourModes.contains(mode) && decoded.bits == 8,470 forceGray: ["mono", "data8", "data16", "mask", "cloud", "normal"].contains(mode))471 if colourModes.contains(mode) && decoded.bits == 16 { for i in raster.data.indices { raster.data[i] /= 65535 } }472 }473 raster = normaliseGeometry(raster, srcLonLeft: srcLonLeft, westPositive: flag("--west-positive"), latTop: latTop, latBottom: latBottom)474 if let vt = option("--valid-lat-top").flatMap(Double.init), let vb = option("--valid-lat-bottom").flatMap(Double.init) {475 let h = raster.height, w = raster.width, ch = raster.channels476 let first = min(max(Int(((90 - vt) / 180 * Double(h)).rounded(.up)), 0), h - 1)477 let last = min(max(Int(((90 - vb) / 180 * Double(h)).rounded(.down)) - 1, first), h - 1)478 func zonalMean(_ y: Int) -> [Float] {479 var m = [Float](repeating: 0, count: ch)480 for x in 0..<w { for c in 0..<ch { m[c] += raster.data[(y * w + x) * ch + c] } }481 return m.map { $0 / Float(w) }482 }483 let top = zonalMean(first), bottom = zonalMean(last)484 for y in 0..<h where y < first || y > last {485 let m = y < first ? top : bottom486 for x in 0..<w { for c in 0..<ch { raster.data[(y * w + x) * ch + c] = m[c] } }487 }488 }489 if raster.width != raster.height * 2 { FileHandle.standardError.write("note: source is \(raster.width) x \(raster.height), not exactly 2:1; resampled to 2:1\n".data(using: .utf8)!) }490491 for w in levels {492 let h = w / 2493 if w > raster.width { fail("level \(w) exceeds the source width \(raster.width): the pipeline never upsamples") }494 let r = resample(raster, toWidth: w, height: h)495 let path = pattern.replacingOccurrences(of: "{w}", with: String(w))496 switch mode {497 case "color", "mono", "hdr":498 let exposure = Float(option("--exposure") ?? "1")!499 var out = Data(count: w * h * 3)500 out.withUnsafeMutableBytes { p in501 for i in 0..<(w * h) {502 for c in 0..<3 {503 let v = r.channels == 1 ? r.data[i] : r.data[i * 3 + c]504 p[i * 3 + c] = linearToSRGB8(mode == "hdr" ? v * exposure : v)505 }506 }507 }508 write(path, width: w, height: h, bits: 8, channels: 3, alpha: false, bytes: out, jpegQuality: quality, tagSRGB: true)509 case "data8":510 var out = Data(count: w * h)511 out.withUnsafeMutableBytes { p in for i in 0..<(w * h) { p[i] = UInt8(min(max(r.data[i].rounded(), 0), 255)) } }512 write(path, width: w, height: h, bits: 8, channels: 1, alpha: false, bytes: out, jpegQuality: nil, tagSRGB: false)513 case "data16":514 // Output value = (metres - outOffset) / outScale, metres = heightOffset + heightScale * source.515 let outOffset = Float(option("--out-offset") ?? "0")!, outScale = Float(option("--out-scale") ?? "1")!516 var words = [UInt16](repeating: 0, count: w * h)517 for i in 0..<(w * h) {518 let metres = heightOffset + heightScale * r.data[i]519 words[i] = UInt16(min(max(((metres - outOffset) / outScale).rounded(), 0), 65535))520 }521 let out = words.withUnsafeBufferPointer { Data(buffer: $0) }522 write(path, width: w, height: h, bits: 16, channels: 1, alpha: false, bytes: out, jpegQuality: nil, tagSRGB: false)523 case "mask":524 // Fraction of each output pixel whose source value is below the threshold, computed before averaging.525 let threshold = Float(option("--threshold") ?? "128")!526 var binary = raster527 for i in binary.data.indices { binary.data[i] = binary.data[i] < threshold ? 255 : 0 }528 let m = resample(binary, toWidth: w, height: h)529 var out = Data(count: w * h)530 out.withUnsafeMutableBytes { p in for i in 0..<(w * h) { p[i] = UInt8(min(max(m.data[i].rounded(), 0), 255)) } }531 write(path, width: w, height: h, bits: 8, channels: 1, alpha: false, bytes: out, jpegQuality: nil, tagSRGB: false)532 case "cloud":533 var out = Data(count: w * h * 4)534 out.withUnsafeMutableBytes { p in535 for i in 0..<(w * h) { p[i * 4] = 255; p[i * 4 + 1] = 255; p[i * 4 + 2] = 255; p[i * 4 + 3] = UInt8(min(max(r.data[i].rounded(), 0), 255)) }536 }537 write(path, width: w, height: h, bits: 8, channels: 4, alpha: true, bytes: out, jpegQuality: nil, tagSRGB: true)538 case "normal":539 // Tangent-space normal (east, north, up) from central differences of the height grid on the sphere.540 guard let radius = option("--radius-m").flatMap(Double.init) else { fail("normal mode needs --radius-m") }541 let exaggeration = Double(option("--exaggeration") ?? "1")!542 var out = Data(count: w * h * 3)543 let dLat = Double.pi / Double(h), dLon = 2 * Double.pi / Double(w)544 out.withUnsafeMutableBytes { p in545 for y in 0..<h {546 let lat = (0.5 - (Double(y) + 0.5) / Double(h)) * Double.pi547 let cosLat = max(cos(lat), 0.02)548 for x in 0..<w {549 func z(_ xx: Int, _ yy: Int) -> Double {550 Double(heightOffset + heightScale * r.data[min(max(yy, 0), h - 1) * w + ((xx % w) + w) % w])551 }552 let dzdx = (z(x + 1, y) - z(x - 1, y)) / (2 * dLon * radius * cosLat) // eastwards553 let dzdy = (z(x, y - 1) - z(x, y + 1)) / (2 * dLat * radius) // northwards554 var nx = -dzdx * exaggeration, ny = -dzdy * exaggeration, nz = 1.0555 let len = (nx * nx + ny * ny + nz * nz).squareRoot()556 nx /= len; ny /= len; nz /= len557 let i = (y * w + x) * 3558 p[i] = UInt8(((nx * 0.5 + 0.5) * 255).rounded()); p[i + 1] = UInt8(((ny * 0.5 + 0.5) * 255).rounded()); p[i + 2] = UInt8(((nz * 0.5 + 0.5) * 255).rounded())559 }560 }561 }562 write(path, width: w, height: h, bits: 8, channels: 3, alpha: false, bytes: out, jpegQuality: nil, tagSRGB: false)563 default:564 fail("unknown mode \(mode)")565 }566 print("wrote \(path)")567 }568569default:570 fail("unknown command \(command)")571}572