~ knotless Search/
↑↓ move↵ open⇧↵ all results

geesawra.industries/old-fella

Old people's social media app

0
1
main
186 lines · 8.0 KB Raw History
import CoreGraphics
import UIKit

struct AvatarRingColors: Equatable {
    struct RGB: Equatable {
        let red: Double
        let green: Double
        let blue: Double

        var color: UIColor { UIColor(red: red, green: green, blue: blue, alpha: 1) }
        var luminance: Double {
            func linear(_ value: Double) -> Double {
                value <= 0.04045 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4)
            }
            return 0.2126 * linear(red) + 0.7152 * linear(green) + 0.0722 * linear(blue)
        }
    }

    let light: RGB
    let dark: RGB
    static let fallback = AvatarRingColors(
        light: RGB(red: 0.45, green: 0.45, blue: 0.45),
        dark: RGB(red: 0.65, green: 0.65, blue: 0.65)
    )
    private static let linearBytes = (0...255).map { value -> Double in
        let value = Double(value) / 255
        return value <= 0.04045 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4)
    }

    static func calculate(for image: CGImage) -> AvatarRingColors {
        guard let pixels = pixels(for: image), let (source, samples) = sampledColors(pixels, side: 16) else {
            return fallback
        }
        return AvatarRingColors(
            light: selectColor(source: source, samples: samples, background: 1),
            dark: selectColor(source: source, samples: samples, background: 0))
    }

    private static func pixels(for image: CGImage) -> [UInt8]? {
        let side = 16
        var pixels = [UInt8](repeating: 0, count: side * side * 4)
        let drawn = pixels.withUnsafeMutableBytes { bytes -> Bool in
            guard
                let context = CGContext(
                    data: bytes.baseAddress, width: side, height: side,
                    bitsPerComponent: 8, bytesPerRow: side * 4,
                    space: CGColorSpace(name: CGColorSpace.sRGB)!,
                    bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue
                        | CGBitmapInfo.byteOrder32Big.rawValue)
            else { return false }
            let scale = max(Double(side) / Double(image.width), Double(side) / Double(image.height))
            let width = Double(image.width) * scale
            let height = Double(image.height) * scale
            context.interpolationQuality = .low
            context.draw(image, in: CGRect(x: (16 - width) / 2, y: (16 - height) / 2, width: width, height: height))
            return true
        }
        return drawn ? pixels : nil
    }

    private static func sampledColors(_ pixels: [UInt8], side: Int) -> (RGB, [Double])? {
        var samples: [Double] = []
        var weights = [Double](repeating: 0, count: 12)
        var reds = weights
        var greens = weights
        var blues = weights
        var neutralTotal = 0.0
        var opacityTotal = 0.0
        for row in 0..<side {
            for column in 0..<side {
                let horizontalDistance = Double(column) - 7.5
                let verticalDistance = Double(row) - 7.5
                let radiusSquared = horizontalDistance * horizontalDistance + verticalDistance * verticalDistance
                let offset = (row * side + column) * 4
                let alpha = Double(pixels[offset + 3]) / 255
                guard radiusSquared <= 64, alpha > 0.1 else { continue }
                func channel(_ index: Int) -> Double {
                    min(1, Double(pixels[offset + index]) / (255 * alpha))
                }
                let red = channel(0)
                let green = channel(1)
                let blue = channel(2)
                let maximum = max(red, green, blue)
                let minimum = min(red, green, blue)
                let chroma = maximum - minimum
                neutralTotal += (red + green + blue) / 3 * alpha
                opacityTotal += alpha
                if radiusSquared >= 36 {
                    func linear(_ value: Double) -> Double { linearBytes[Int((value * 255).rounded())] }
                    samples.append(0.2126 * linear(red) + 0.7152 * linear(green) + 0.0722 * linear(blue))
                }
                guard maximum > 0.05, chroma / maximum >= 0.15 else { continue }
                let hue = hue(red: red, green: green, blue: blue, maximum: maximum, chroma: chroma)
                // Group nearby hues, then use their actual sampled color.
                let bucket = min(11, Int(hue * 2))
                let weight = chroma * alpha
                weights[bucket] += weight
                reds[bucket] += red * weight
                greens[bucket] += green * weight
                blues[bucket] += blue * weight
            }
        }
        guard !samples.isEmpty else { return nil }
        let source = dominantColor(
            weights: weights, reds: reds, greens: greens, blues: blues,
            neutral: neutralTotal / opacityTotal)
        return (source, samples)
    }

    private static func hue(red: Double, green: Double, blue: Double, maximum: Double, chroma: Double) -> Double {
        if maximum == red {
            return ((green - blue) / chroma + 6).truncatingRemainder(dividingBy: 6)
        } else if maximum == green {
            return (blue - red) / chroma + 2
        } else {
            return (red - green) / chroma + 4
        }
    }

    private static func dominantColor(
        weights: [Double], reds: [Double], greens: [Double], blues: [Double],
        neutral: Double
    ) -> RGB {
        let dominant = weights.indices.max { weights[$0] < weights[$1] }!
        if weights[dominant] > 0 {
            return RGB(
                red: reds[dominant] / weights[dominant], green: greens[dominant] / weights[dominant],
                blue: blues[dominant] / weights[dominant])
        } else {
            let value = neutral
            return RGB(red: value, green: value, blue: value)
        }
    }

    private static func adjustedColor(source: RGB, brightness: Double) -> RGB {
        func linear(_ value: Double) -> Double {
            value <= 0.04045 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4)
        }
        let channels = [linear(source.red), linear(source.green), linear(source.blue)]
        let sourceBrightness = source.luminance
        let peak = channels.max()!

        let adjusted: [Double]
        if sourceBrightness < 0.00001 {
            adjusted = [Double](repeating: brightness, count: 3)
        } else if peak * brightness / sourceBrightness <= 1 {
            adjusted = channels.map { $0 * brightness / sourceBrightness }
        } else {
            let fullBrightness = sourceBrightness / peak
            // Limit white mixing so a brighter ring keeps its source color.
            let whiteAmount = min(0.12, max(0, (brightness - fullBrightness) / (1 - fullBrightness)))
            adjusted = channels.map { $0 / peak + (1 - $0 / peak) * whiteAmount }
        }
        let encoded = adjusted.map { value in
            value <= 0.0031308 ? value * 12.92 : 1.055 * pow(value, 1 / 2.4) - 0.055
        }
        return RGB(red: encoded[0], green: encoded[1], blue: encoded[2])

    }

    private static func contrast(_ first: Double, _ second: Double) -> Double {
        (max(first, second) + 0.05) / (min(first, second) + 0.05)
    }

    private static func selectColor(source: RGB, samples: [Double], background: Double) -> RGB {
        let edgeBrightness = samples.reduce(0, +) / Double(samples.count)
        let targetContrast = 2.0

        let minimum = background == 0 ? 0.05 : 0.02
        let maximum = background == 1 ? 0.22 : 0.55
        let darker = (edgeBrightness + 0.05) / targetContrast - 0.05
        let lighter = (edgeBrightness + 0.05) * targetContrast - 0.05
        let candidates = [darker, lighter].map {
            adjustedColor(source: source, brightness: min(maximum, max(minimum, $0)))
        }
        return candidates.max { first, second in
            func score(_ value: RGB) -> Double {
                let luminance = value.luminance
                return samples.reduce(0) { $0 + min(targetContrast, contrast(luminance, $1)) }
            }
            return score(first) < score(second)
        }!

    }

}