file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
library/src/jvmMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.jvm.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostBackend: KotlinBackend = KotlinBackend.JVM
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/linuxArm64Main/kotlin/dev/zwander/kmp/platform/HostArch.linuxArm64.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.Arm64
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/linuxMain/kotlin/dev/zwander/kmp/platform/HostOS.linux.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostOS: HostOS = HostOS.Linux
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/linuxMain/kotlin/dev/zwander/kmp/platform/HostOSVersion.linux.kt | Kotlin | package dev.zwander.kmp.platform
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.alloc
import kotlinx.cinterop.cValue
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.pointed
import kotlinx.cinterop.toKString
import platform.posix.uname
import platform.posix.utsname
@OptIn(ExperimentalForeignApi::class)
internal actual val hostOSVersion: OSVersion
get() = memScoped {
val unameValue = cValue<utsname>()
return if (uname(unameValue) != -1) {
val releaseString = unameValue.ptr.pointed.release.toKString()
val versionAndBuild = releaseString.split("-")
val majorMinorAndPatch = versionAndBuild.firstOrNull()?.split(".")
val major = majorMinorAndPatch?.getOrNull(0)
val minor = majorMinorAndPatch?.getOrNull(1)
val patch = majorMinorAndPatch?.getOrNull(2)
val build = versionAndBuild.getOrNull(1)
OSVersion(
major = major?.toIntOrNull(),
minor = minor?.toIntOrNull(),
patch = patch?.toIntOrNull(),
build = build?.toLongOrNull(),
)
} else {
OSVersion.Unknown
}
}
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/linuxMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.linux.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostBackend: KotlinBackend = KotlinBackend.Native
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/linuxX64Main/kotlin/dev/zwander/kmp/platform/HostArch.linuxX64.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.X64
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/macosArm64Main/kotlin/dev/zwander/kmp/platform/HostArch.macosArm64.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.Arm64
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/macosMain/kotlin/dev/zwander/kmp/platform/HostOS.macos.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostOS: HostOS = HostOS.MacOS | zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/macosMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.macos.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostBackend: KotlinBackend = KotlinBackend.Native
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/macosX64Main/kotlin/dev/zwander/kmp/platform/HostArch.macosX64.kt | Kotlin | package dev.zwander.kmp.platform
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.IntVar
import kotlinx.cinterop.cValue
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.sizeOf
import kotlinx.cinterop.toCPointer
import platform.darwin.sysctlbyname
@OptIn(ExperimentalForeignApi::class)
internal actual val hostArch: HostArch
get() = memScoped {
val ret = cValue<IntVar>()
return if (sysctlbyname("sysctl.proc_translated", ret, sizeOf<IntVar>().toCPointer(), null, 0U) != -1) {
HostArch.EmulatedX64
} else {
HostArch.X64
}
}
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/mingwMain/kotlin/dev/zwander/kmp/platform/HostOS.mingw.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostOS: HostOS = HostOS.Windows
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/mingwMain/kotlin/dev/zwander/kmp/platform/HostOSVersion.mingw.kt | Kotlin | package dev.zwander.kmp.platform
import platform.windows.BYTE
import platform.windows.DWORD
import platform.windows.GetVersion
import platform.windows.WORD
private fun WORD.loByte(): BYTE = (this and 0xffU).toUByte()
private fun WORD.hiByte(): BYTE = ((this.toInt() shr 8) and 0xff).toUByte()
private fun DWORD.loWord(): WORD = (this and 0xffffU).toUShort()
private fun DWORD.hiWord(): WORD = ((this.toInt() shr 16) and 0xffff).toUShort()
internal actual val hostOSVersion: OSVersion
get() {
val version = GetVersion()
val majorVersion = version.loWord().loByte()
val minorVersion = version.loWord().hiByte()
val build = if (version < 0x80000000U) {
version.hiWord()
} else {
null
}
return OSVersion(
major = majorVersion.toInt(),
minor = minorVersion.toInt(),
patch = null,
build = build?.toLong(),
)
}
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/mingwMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.mingw.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostBackend: KotlinBackend = KotlinBackend.Native
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/mingwX64Main/kotlin/dev/zwander/kmp/platform/HostArch.mingwX64.kt | Kotlin | package dev.zwander.kmp.platform
import dev.zwander.kmp.platform.cinterop.IsWow64Process2
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.UShortVar
import kotlinx.cinterop.cValue
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.pointed
import kotlinx.cinterop.value
import platform.windows.GetCurrentProcess
@OptIn(ExperimentalForeignApi::class)
internal actual val hostArch: HostArch
get() = memScoped {
val processHandle = GetCurrentProcess()
val processMachine = cValue<UShortVar>()
val nativeMachine = cValue<UShortVar>()
IsWow64Process2(processHandle, processMachine, nativeMachine)
return if (nativeMachine.ptr.pointed.value.toInt() == platform.windows.IMAGE_FILE_MACHINE_ARM64) {
when (processMachine.ptr.pointed.value.toInt()) {
platform.windows.IMAGE_FILE_MACHINE_AMD64 -> HostArch.EmulatedX64
platform.windows.IMAGE_FILE_MACHINE_I386 -> HostArch.EmulatedX86
else -> HostArch.Unknown
}
} else {
HostArch.X64
}
}
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/nativeInterop/cinterop/Windows/windows.h | C/C++ Header | #include <windef.h>
BOOL IsWow64Process2(
HANDLE hProcess,
USHORT *pProcessMachine,
USHORT *pNativeMachine
);
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/tvosArm64Main/kotlin/dev/zwander/kmp/platform/HostArch.tvosArm64.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.Arm64
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/tvosMain/kotlin/dev/zwander/kmp/platform/HostOS.tvos.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostOS: HostOS = HostOS.TvOS
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/tvosMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.tvos.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostBackend: KotlinBackend = KotlinBackend.Native
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/tvosSimulatorArm64Main/kotlin/dev/zwander/kmp/platform/HostArch.tvosSimulatorArm64.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.Arm64
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/tvosX64Main/kotlin/dev/zwander/kmp/platform/HostArch.tvosX64.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.X64
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/wasmJsMain/kotlin/dev/zwander/kmp/platform/HostArch.wasmJs.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.Unknown
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/wasmJsMain/kotlin/dev/zwander/kmp/platform/HostOS.wasmJs.kt | Kotlin | package dev.zwander.kmp.platform
/**
* A string identifying the platform on which the user's browser is running; for example:
* "MacIntel", "Win32", "Linux x86_64", "Linux x86_64".
* See https://developer.mozilla.org/en-US/docs/Web/API/Navigator/platform - deprecated
*
* A string containing the platform brand. For example, "Windows".
* See https://developer.mozilla.org/en-US/docs/Web/API/NavigatorUAData/platform - new API,
* but not supported in all browsers
*/
internal fun getNavigatorInfo(): String = js("navigator.userAgentData ? navigator.userAgentData.platform : navigator.platform")
internal fun getUserAgent(): String = js("window.navigator.userAgent")
/**
* In a browser, user platform can be obtained from different places:
* - we attempt to use not-deprecated but experimental option first (not available in all browsers)
* - then we attempt to use a deprecated option
* - if both above return an empty string, we attempt to get `Platform` from `userAgent`
*
* Note: a client can spoof these values, so it's okay only for non-critical use cases.
*/
internal fun detectHostOs(): HostOS {
val platformInfo = getNavigatorInfo().takeIf {
it.isNotEmpty()
} ?: getUserAgent()
return when {
platformInfo.contains("Android", true) -> HostOS.Android
platformInfo.contains("iPhone", true) -> HostOS.IOS
platformInfo.contains("iOS", true) -> HostOS.IOS
platformInfo.contains("iPad", true) -> HostOS.IOS
platformInfo.contains("Linux", true) -> HostOS.Linux
platformInfo.contains("Mac", true) -> HostOS.MacOS
platformInfo.contains("Win", true) -> HostOS.Windows
else -> HostOS.Unknown
}
}
internal actual val hostOS: HostOS
get() = detectHostOs()
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/wasmJsMain/kotlin/dev/zwander/kmp/platform/HostOSVersion.wasmJs.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostOSVersion: OSVersion = OSVersion.Unknown
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/wasmJsMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.wasmJs.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostBackend: KotlinBackend = KotlinBackend.Wasm
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/watchosArm32Main/kotlin/dev/zwander/kmp/platform/HostArch.watchosArm32.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.Arm32
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/watchosArm64Main/kotlin/dev/zwander/kmp/platform/HostArch.watchosArm64.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.Arm64
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/watchosDeviceArm64Main/kotlin/dev/zwander/kmp/platform/HostArch.watchosDeviceArm64.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.Arm64
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/watchosMain/kotlin/dev/zwander/kmp/platform/HostOS.watchos.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostOS: HostOS = HostOS.WatchOS | zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/watchosMain/kotlin/dev/zwander/kmp/platform/KotlinBackend.watchos.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostBackend: KotlinBackend = KotlinBackend.Native
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/watchosSimulatorArm64Main/kotlin/dev/zwander/kmp/platform/HostArch.watchosSimulatorArm64.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.Arm64
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
library/src/watchosX64Main/kotlin/dev/zwander/kmp/platform/HostArch.watchosX64.kt | Kotlin | package dev.zwander.kmp.platform
internal actual val hostArch: HostArch = HostArch.X64
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
settings.gradle.kts | Kotlin | @file:Suppress("UnstableApiUsage")
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
google()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
google()
}
}
rootProject.name = "KMPPlatform"
include(":library")
| zacharee/KMPPlatform | 1 | Kotlin | zacharee | Zachary Wander | ||
build.gradle.kts | Kotlin | plugins {
alias(libs.plugins.android.library) apply false
alias(libs.plugins.compose) apply false
alias(libs.plugins.kotlin.compose) apply false
alias(libs.plugins.kotlin.multiplatform) apply false
alias(libs.plugins.maven.publish) apply false
}
tasks.withType<org.jetbrains.kotlin.gradle.tasks.KotlinCompile> {
compilerOptions {
freeCompilerArgs.addAll("-Xskip-prerelease-check", "-Xdont-warn-on-error-suppression")
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/build.gradle.kts | Kotlin | import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl
import org.jetbrains.kotlin.gradle.dsl.JvmTarget
plugins {
alias(libs.plugins.android.library)
alias(libs.plugins.compose)
alias(libs.plugins.kotlin.compose)
alias(libs.plugins.kotlin.multiplatform)
alias(libs.plugins.maven.publish)
}
group = "dev.zwander.compose.materialyou"
kotlin.sourceSets.all {
languageSettings.optIn("kotlin.RequiresOptIn")
}
val javaVersionEnum: JavaVersion = JavaVersion.VERSION_21
kotlin {
jvmToolchain(javaVersionEnum.toString().toInt())
androidTarget {
compilations.all {
compileTaskProvider.configure {
compilerOptions {
freeCompilerArgs.addAll("-opt-in=kotlin.RequiresOptIn", "-Xdont-warn-on-error-suppression")
jvmTarget = JvmTarget.fromTarget(javaVersionEnum.toString())
}
}
}
}
jvm {
compilations.all {
compileTaskProvider.configure {
compilerOptions {
jvmTarget = JvmTarget.fromTarget(javaVersionEnum.toString())
}
}
}
}
listOf(
iosX64(),
iosArm64(),
iosSimulatorArm64(),
macosX64(),
macosArm64(),
).forEach {
it.binaries.framework {
baseName = "MultiplatformMaterialYou"
isStatic = true
}
}
@OptIn(ExperimentalWasmDsl::class)
listOf(
js(IR),
wasmJs(),
).forEach {
it.outputModuleName.set("MultiplatformMaterialYou")
it.browser()
}
targets.all {
compilations.all {
compileTaskProvider.configure {
compilerOptions {
freeCompilerArgs.addAll("-Xexpect-actual-classes", "-Xdont-warn-on-error-suppression")
}
}
}
}
sourceSets {
val commonMain by getting {
dependencies {
api(compose.foundation)
api(compose.material3)
api(compose.runtime)
api(compose.ui)
api(libs.kotlin.stdlib)
api(libs.kotlin.reflect)
}
}
val jvmMain by getting {
dependsOn(commonMain)
dependencies {
api(libs.jsystemthemedetector)
api(libs.jna)
api(libs.jna.platform)
api(libs.jfa)
}
}
val androidMain by getting {
dependsOn(commonMain)
}
val iosMain by creating {
dependsOn(commonMain)
}
val iosX64Main by getting {
dependsOn(iosMain)
}
val iosArm64Main by getting {
dependsOn(iosMain)
}
val iosSimulatorArm64Main by getting {
dependsOn(iosMain)
}
val macosMain by creating {
dependsOn(commonMain)
}
val macosArm64Main by getting {
dependsOn(macosMain)
}
val macosX64Main by getting {
dependsOn(macosMain)
}
val jsAndWasmMain by creating {
dependsOn(commonMain)
}
val jsMain by getting {
dependsOn(jsAndWasmMain)
}
val wasmJsMain by getting {
dependsOn(jsAndWasmMain)
}
}
}
android {
this.compileSdk = 36
defaultConfig {
this.minSdk = 21
}
namespace = "dev.zwander.compose.materialyou"
compileOptions {
sourceCompatibility = javaVersionEnum
targetCompatibility = javaVersionEnum
}
buildFeatures {
aidl = true
}
sourceSets["main"].manifest.srcFile("src/androidMain/AndroidManifest.xml")
sourceSets["main"].res.srcDirs("src/androidMain/res")
}
tasks.withType<Copy> {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/androidMain/kotlin/dev/zwander/compose/ThemeInfo.android.kt | Kotlin | @file:Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE", "EXPOSED_PARAMETER_TYPE")
@file:JvmName("ThemeInfoAndroid")
package dev.zwander.compose
import android.os.Build
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.dynamicDarkColorScheme
import androidx.compose.material3.dynamicLightColorScheme
import androidx.compose.material3.dynamicTonalPalette
import androidx.compose.material3.dynamicDarkColorScheme31
import androidx.compose.material3.dynamicLightColorScheme31
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
@Composable
actual fun isSystemInDarkTheme(): Boolean {
return androidx.compose.foundation.isSystemInDarkTheme()
}
@Composable
actual fun rememberThemeInfo(isDarkMode: Boolean): ThemeInfo {
val context = LocalContext.current
val isAndroid12 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
val isOneUI = remember {
context.packageManager.hasSystemFeature("com.samsung.feature.samsung_experience_mobile") ||
context.packageManager.hasSystemFeature("com.samsung.feature.samsung_experience_mobile_lite")
}
val isOneUIUPre611 = isOneUI &&
Build.VERSION.SDK_INT == Build.VERSION_CODES.UPSIDE_DOWN_CAKE &&
(Class.forName("android.os.SystemProperties").getMethod("getInt", String::class.java, Int::class.java).invoke(null, "ro.build.version.oneui", 0) as Int) < 60101
val colorScheme = remember(isDarkMode, isAndroid12) {
if (isDarkMode) {
if (isAndroid12) {
if (isOneUIUPre611) {
dynamicDarkColorScheme31(dynamicTonalPalette(context))
} else {
dynamicDarkColorScheme(context)
}
} else {
darkColorScheme()
}
} else {
if (isAndroid12) {
if (isOneUIUPre611) {
dynamicLightColorScheme31(dynamicTonalPalette(context))
} else {
dynamicLightColorScheme(context)
}
} else {
lightColorScheme()
}
}
}
return remember(colorScheme) {
ThemeInfo(
isDarkMode = isDarkMode,
colors = colorScheme,
seedColor = colorScheme.primary,
)
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/ThemeInfo.kt | Kotlin | package dev.zwander.compose
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
data class ThemeInfo(
val isDarkMode: Boolean,
val colors: ColorScheme,
val seedColor: Color,
)
@Composable
expect fun rememberThemeInfo(isDarkMode: Boolean = isSystemInDarkTheme()): ThemeInfo
@Composable
expect fun isSystemInDarkTheme(): Boolean
@Suppress("unused")
@Composable
fun DynamicMaterialTheme(
isDarkMode: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit,
) {
val themeInfo = rememberThemeInfo(isDarkMode = isDarkMode)
MaterialTheme(
content = content,
colorScheme = themeInfo.colors,
)
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/blend/Blend.kt | Kotlin | package dev.zwander.compose.libmonet.blend
import dev.zwander.compose.libmonet.hct.Cam16
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.utils.ColorUtils
import dev.zwander.compose.libmonet.utils.MathUtils.differenceDegrees
import dev.zwander.compose.libmonet.utils.MathUtils.rotationDirection
import dev.zwander.compose.libmonet.utils.MathUtils.sanitizeDegreesDouble
import kotlin.math.min
/** Functions for blending in HCT and CAM16. */
object Blend {
/**
* Blend the design color's HCT hue towards the key color's HCT hue, in a way that leaves the
* original color recognizable and recognizably shifted towards the key color.
*
* @param designColor ARGB representation of an arbitrary color.
* @param sourceColor ARGB representation of the main theme color.
* @return The design color with a hue shifted towards the system's color, a slightly
* warmer/cooler variant of the design color's hue.
*/
fun harmonize(designColor: Int, sourceColor: Int): Int {
val fromHct: Hct = Hct.fromInt(designColor)
val toHct: Hct = Hct.fromInt(sourceColor)
val differenceDegrees: Double =
differenceDegrees(fromHct.getHue(), toHct.getHue())
val rotationDegrees = min(differenceDegrees * 0.5, 15.0)
val outputHue: Double =
sanitizeDegreesDouble(
fromHct.getHue()
+ rotationDegrees * rotationDirection(
fromHct.getHue(),
toHct.getHue()
)
)
return Hct.from(outputHue, fromHct.getChroma(), fromHct.getTone()).toInt()
}
/**
* Blends hue from one color into another. The chroma and tone of the original color are
* maintained.
*
* @param from ARGB representation of color
* @param to ARGB representation of color
* @param amount how much blending to perform; 0.0 >= and <= 1.0
* @return from, with a hue blended towards to. Chroma and tone are constant.
*/
fun hctHue(from: Int, to: Int, amount: Double): Int {
val ucs = cam16Ucs(from, to, amount)
val ucsCam: Cam16 = Cam16.fromInt(ucs)
val fromCam: Cam16 = Cam16.fromInt(from)
val blended: Hct =
Hct.from(ucsCam.hue, fromCam.chroma, ColorUtils.lstarFromArgb(from))
return blended.toInt()
}
/**
* Blend in CAM16-UCS space.
*
* @param from ARGB representation of color
* @param to ARGB representation of color
* @param amount how much blending to perform; 0.0 >= and <= 1.0
* @return from, blended towards to. Hue, chroma, and tone will change.
*/
fun cam16Ucs(from: Int, to: Int, amount: Double): Int {
val fromCam: Cam16 = Cam16.fromInt(from)
val toCam: Cam16 = Cam16.fromInt(to)
val fromJ: Double = fromCam.jstar
val fromA: Double = fromCam.astar
val fromB: Double = fromCam.bstar
val toJ: Double = toCam.jstar
val toA: Double = toCam.astar
val toB: Double = toCam.bstar
val jstar = fromJ + (toJ - fromJ) * amount
val astar = fromA + (toA - fromA) * amount
val bstar = fromB + (toB - fromB) * amount
return Cam16.fromUcs(jstar, astar, bstar).toInt()
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/contrast/Contrast.kt | Kotlin | package dev.zwander.compose.libmonet.contrast
import dev.zwander.compose.libmonet.utils.ColorUtils
import kotlin.math.abs
import kotlin.math.max
/**
* Color science for contrast utilities.
*
*
* Utility methods for calculating contrast given two colors, or calculating a color given one
* color and a contrast ratio.
*
*
* Contrast ratio is calculated using XYZ's Y. When linearized to match human perception, Y
* becomes HCT's tone and L*a*b*'s' L*.
*/
object Contrast {
// The minimum contrast ratio of two colors.
// Contrast ratio equation = lighter + 5 / darker + 5, if lighter == darker, ratio == 1.
const val RATIO_MIN: Double = 1.0
// The maximum contrast ratio of two colors.
// Contrast ratio equation = lighter + 5 / darker + 5. Lighter and darker scale from 0 to 100.
// If lighter == 100, darker = 0, ratio == 21.
const val RATIO_MAX: Double = 21.0
const val RATIO_30: Double = 3.0
const val RATIO_45: Double = 4.5
const val RATIO_70: Double = 7.0
// Given a color and a contrast ratio to reach, the luminance of a color that reaches that ratio
// with the color can be calculated. However, that luminance may not contrast as desired, i.e. the
// contrast ratio of the input color and the returned luminance may not reach the contrast ratio
// asked for.
//
// When the desired contrast ratio and the result contrast ratio differ by more than this amount,
// an error value should be returned, or the method should be documented as 'unsafe', meaning,
// it will return a valid luminance but that luminance may not meet the requested contrast ratio.
//
// 0.04 selected because it ensures the resulting ratio rounds to the same tenth.
private const val CONTRAST_RATIO_EPSILON = 0.04
// Color spaces that measure luminance, such as Y in XYZ, L* in L*a*b*, or T in HCT, are known as
// perceptually accurate color spaces.
//
// To be displayed, they must gamut map to a "display space", one that has a defined limit on the
// number of colors. Display spaces include sRGB, more commonly understood as RGB/HSL/HSV/HSB.
// Gamut mapping is undefined and not defined by the color space. Any gamut mapping algorithm must
// choose how to sacrifice accuracy in hue, saturation, and/or lightness.
//
// A principled solution is to maintain lightness, thus maintaining contrast/a11y, maintain hue,
// thus maintaining aesthetic intent, and reduce chroma until the color is in gamut.
//
// HCT chooses this solution, but, that doesn't mean it will _exactly_ matched desired lightness,
// if only because RGB is quantized: RGB is expressed as a set of integers: there may be an RGB
// color with, for example, 47.892 lightness, but not 47.891.
//
// To allow for this inherent incompatibility between perceptually accurate color spaces and
// display color spaces, methods that take a contrast ratio and luminance, and return a luminance
// that reaches that contrast ratio for the input luminance, purposefully darken/lighten their
// result such that the desired contrast ratio will be reached even if inaccuracy is introduced.
//
// 0.4 is generous, ex. HCT requires much less delta. It was chosen because it provides a rough
// guarantee that as long as a perceptual color space gamut maps lightness such that the resulting
// lightness rounds to the same as the requested, the desired contrast ratio will be reached.
private const val LUMINANCE_GAMUT_MAP_TOLERANCE = 0.4
/**
* Contrast ratio is a measure of legibility, its used to compare the lightness of two colors.
* This method is used commonly in industry due to its use by WCAG.
*
*
* To compare lightness, the colors are expressed in the XYZ color space, where Y is lightness,
* also known as relative luminance.
*
*
* The equation is ratio = lighter Y + 5 / darker Y + 5.
*/
fun ratioOfYs(y1: Double, y2: Double): Double {
val lighter: Double = max(y1, y2)
val darker = if ((lighter == y2)) y1 else y2
return (lighter + 5.0) / (darker + 5.0)
}
/**
* Contrast ratio of two tones. T in HCT, L* in L*a*b*. Also known as luminance or perpectual
* luminance.
*
*
* Contrast ratio is defined using Y in XYZ, relative luminance. However, relative luminance is
* linear to number of photons, not to perception of lightness. Perceptual luminance, L* in
* L*a*b*, T in HCT, is. Designers prefer color spaces with perceptual luminance since they're
* accurate to the eye.
*
*
* Y and L* are pure functions of each other, so it possible to use perceptually accurate color
* spaces, and measure contrast, and measure contrast in a much more understandable way: instead
* of a ratio, a linear difference. This allows a designer to determine what they need to adjust a
* color's lightness to in order to reach their desired contrast, instead of guessing & checking
* with hex codes.
*/
fun ratioOfTones(t1: Double, t2: Double): Double {
return ratioOfYs(ColorUtils.yFromLstar(t1), ColorUtils.yFromLstar(t2))
}
/**
* Returns T in HCT, L* in L*a*b* >= tone parameter that ensures ratio with input T/L*. Returns -1
* if ratio cannot be achieved.
*
* @param tone Tone return value must contrast with.
* @param ratio Desired contrast ratio of return value and tone parameter.
*/
fun lighter(tone: Double, ratio: Double): Double {
if (tone < 0.0 || tone > 100.0) {
return -1.0
}
// Invert the contrast ratio equation to determine lighter Y given a ratio and darker Y.
val darkY: Double = ColorUtils.yFromLstar(tone)
val lightY = ratio * (darkY + 5.0) - 5.0
if (lightY < 0.0 || lightY > 100.0) {
return -1.0
}
val realContrast = ratioOfYs(lightY, darkY)
val delta = abs(realContrast - ratio)
if (realContrast < ratio && delta > CONTRAST_RATIO_EPSILON) {
return -1.0
}
val returnValue: Double = ColorUtils.lstarFromY(lightY) + LUMINANCE_GAMUT_MAP_TOLERANCE
// NOMUTANTS--important validation step; functions it is calling may change implementation.
if (returnValue < 0 || returnValue > 100) {
return -1.0
}
return returnValue
}
/**
* Tone >= tone parameter that ensures ratio. 100 if ratio cannot be achieved.
*
*
* This method is unsafe because the returned value is guaranteed to be in bounds, but, the in
* bounds return value may not reach the desired ratio.
*
* @param tone Tone return value must contrast with.
* @param ratio Desired contrast ratio of return value and tone parameter.
*/
fun lighterUnsafe(tone: Double, ratio: Double): Double {
val lighterSafe = lighter(tone, ratio)
return if (lighterSafe < 0.0) 100.0 else lighterSafe
}
/**
* Returns T in HCT, L* in L*a*b* <= tone parameter that ensures ratio with input T/L*. Returns -1
* if ratio cannot be achieved.
*
* @param tone Tone return value must contrast with.
* @param ratio Desired contrast ratio of return value and tone parameter.
*/
fun darker(tone: Double, ratio: Double): Double {
if (tone < 0.0 || tone > 100.0) {
return -1.0
}
// Invert the contrast ratio equation to determine darker Y given a ratio and lighter Y.
val lightY: Double = ColorUtils.yFromLstar(tone)
val darkY = ((lightY + 5.0) / ratio) - 5.0
if (darkY < 0.0 || darkY > 100.0) {
return -1.0
}
val realContrast = ratioOfYs(lightY, darkY)
val delta = abs(realContrast - ratio)
if (realContrast < ratio && delta > CONTRAST_RATIO_EPSILON) {
return -1.0
}
// For information on 0.4 constant, see comment in lighter(tone, ratio).
val returnValue: Double = ColorUtils.lstarFromY(darkY) - LUMINANCE_GAMUT_MAP_TOLERANCE
// NOMUTANTS--important validation step; functions it is calling may change implementation.
if (returnValue < 0 || returnValue > 100) {
return -1.0
}
return returnValue
}
/**
* Tone <= tone parameter that ensures ratio. 0 if ratio cannot be achieved.
*
*
* This method is unsafe because the returned value is guaranteed to be in bounds, but, the in
* bounds return value may not reach the desired ratio.
*
* @param tone Tone return value must contrast with.
* @param ratio Desired contrast ratio of return value and tone parameter.
*/
fun darkerUnsafe(tone: Double, ratio: Double): Double {
val darkerSafe = darker(tone, ratio)
return max(0.0, darkerSafe)
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/dislike/DislikeAnalyzer.kt | Kotlin | package dev.zwander.compose.libmonet.dislike
import dev.zwander.compose.libmonet.hct.Hct
import kotlin.math.round
/**
* Check and/or fix universally disliked colors.
*
*
* Color science studies of color preference indicate universal distaste for dark yellow-greens,
* and also show this is correlated to distate for biological waste and rotting food.
*
*
* See Palmer and Schloss, 2010 or Schloss and Palmer's Chapter 21 in Handbook of Color
* Psychology (2015).
*/
object DislikeAnalyzer {
/**
* Returns true if color is disliked.
*
*
* Disliked is defined as a dark yellow-green that is not neutral.
*/
fun isDisliked(hct: Hct): Boolean {
val huePasses = round(hct.getHue()) in 90.0..111.0
val chromaPasses: Boolean = round(hct.getChroma()) > 16.0
val tonePasses: Boolean = round(hct.getTone()) < 65.0
return huePasses && chromaPasses && tonePasses
}
/** If color is disliked, lighten it to make it likable. */
fun fixIfDisliked(hct: Hct): Hct {
if (isDisliked(hct)) {
return Hct.from(hct.getHue(), hct.getChroma(), 70.0)
}
return hct
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/dynamiccolor/ContrastCurve.kt | Kotlin | package dev.zwander.compose.libmonet.dynamiccolor
import dev.zwander.compose.libmonet.utils.MathUtils.lerp
/**
* A class containing a value that changes with the contrast level.
*
*
* Usually represents the contrast requirements for a dynamic color on its background. The four
* values correspond to values for contrast levels -1.0, 0.0, 0.5, and 1.0, respectively.
*/
class ContrastCurve
/**
* Creates a `ContrastCurve` object.
*
* @param low Value for contrast level -1.0
* @param normal Value for contrast level 0.0
* @param medium Value for contrast level 0.5
* @param high Value for contrast level 1.0
*/(
/** Value for contrast level -1.0 */
private val low: Double,
/** Value for contrast level 0.0 */
private val normal: Double,
/** Value for contrast level 0.5 */
private val medium: Double,
/** Value for contrast level 1.0 */
private val high: Double
) {
/**
* Returns the value at a given contrast level.
*
* @param contrastLevel The contrast level. 0.0 is the default (normal); -1.0 is the lowest; 1.0
* is the highest.
* @return The value. For contrast ratios, a number between 1.0 and 21.0.
*/
fun get(contrastLevel: Double): Double {
return if (contrastLevel <= -1.0) {
low
} else if (contrastLevel < 0.0) {
lerp(this.low, this.normal, (contrastLevel - -1) / 1)
} else if (contrastLevel < 0.5) {
lerp(this.normal, this.medium, (contrastLevel - 0) / 0.5)
} else if (contrastLevel < 1.0) {
lerp(this.medium, this.high, (contrastLevel - 0.5) / 0.5)
} else {
high
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/dynamiccolor/DynamicColor.kt | Kotlin | package dev.zwander.compose.libmonet.dynamiccolor
import dev.zwander.compose.libmonet.contrast.Contrast
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
import dev.zwander.compose.libmonet.utils.MathUtils.clampDouble
import dev.zwander.compose.libmonet.utils.MathUtils.clampInt
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.round
/**
* A color that adjusts itself based on UI state, represented by DynamicScheme.
*
*
* This color automatically adjusts to accommodate a desired contrast level, or other adjustments
* such as differing in light mode versus dark mode, or what the theme is, or what the color that
* produced the theme is, etc.
*
*
* Colors without backgrounds do not change tone when contrast changes. Colors with backgrounds
* become closer to their background as contrast lowers, and further when contrast increases.
*
*
* Prefer the static constructors. They provide a much more simple interface, such as requiring
* just a hexcode, or just a hexcode and a background.
*
*
* Ultimately, each component necessary for calculating a color, adjusting it for a desired
* contrast level, and ensuring it has a certain lightness/tone difference from another color, is
* provided by a function that takes a DynamicScheme and returns a value. This ensures ultimate
* flexibility, any desired behavior of a color for any design system, but it usually unnecessary.
* See the default constructor for more information.
*/
// Prevent lint for Function.apply not being available on Android before API level 14 (4.0.1).
// "AndroidJdkLibsChecker" for Function, "NewApi" for Function.apply().
// A java_library Bazel rule with an Android constraint cannot skip these warnings without this
// annotation; another solution would be to create an android_library rule and supply
// AndroidManifest with an SDK set higher than 14.
class DynamicColor {
val name: String
val palette: (DynamicScheme) -> TonalPalette
val tone: (DynamicScheme) -> Double
val isBackground: Boolean
val background: ((DynamicScheme) -> DynamicColor)?
val secondBackground: ((DynamicScheme) -> DynamicColor)?
val contrastCurve: ContrastCurve?
val toneDeltaPair: ((DynamicScheme) -> ToneDeltaPair)?
val opacity: ((DynamicScheme) -> Double)?
private val hctCache: HashMap<DynamicScheme, Hct> = HashMap()
/**
* A constructor for DynamicColor.
*
*
* _Strongly_ prefer using one of the convenience constructors. This class is arguably too
* flexible to ensure it can support any scenario. Functional arguments allow overriding without
* risks that come with subclasses.
*
*
* For example, the default behavior of adjust tone at max contrast to be at a 7.0 ratio with
* its background is principled and matches accessibility guidance. That does not mean it's the
* desired approach for _every_ design system, and every color pairing, always, in every case.
*
*
* For opaque colors (colors with alpha = 100%).
*
* @param name The name of the dynamic color.
* @param palette Function that provides a TonalPalette given DynamicScheme. A TonalPalette is
* defined by a hue and chroma, so this replaces the need to specify hue/chroma. By providing
* a tonal palette, when contrast adjustments are made, intended chroma can be preserved.
* @param tone Function that provides a tone, given a DynamicScheme.
* @param isBackground Whether this dynamic color is a background, with some other color as the
* foreground.
* @param background The background of the dynamic color (as a function of a `DynamicScheme`), if
* it exists.
* @param secondBackground A second background of the dynamic color (as a function of a
* `DynamicScheme`), if it exists.
* @param contrastCurve A `ContrastCurve` object specifying how its contrast against its
* background should behave in various contrast levels options.
* @param toneDeltaPair A `ToneDeltaPair` object specifying a tone delta constraint between two
* colors. One of them must be the color being constructed.
*/
constructor(
name: String,
palette: (DynamicScheme) -> TonalPalette,
tone: (DynamicScheme) -> Double,
isBackground: Boolean,
background: ((DynamicScheme) -> DynamicColor)?,
secondBackground: ((DynamicScheme) -> DynamicColor)?,
contrastCurve: ContrastCurve?,
toneDeltaPair: ((DynamicScheme) -> ToneDeltaPair)?
) {
this.name = name
this.palette = palette
this.tone = tone
this.isBackground = isBackground
this.background = background
this.secondBackground = secondBackground
this.contrastCurve = contrastCurve
this.toneDeltaPair = toneDeltaPair
this.opacity = null
}
/**
* A constructor for DynamicColor.
*
*
* _Strongly_ prefer using one of the convenience constructors. This class is arguably too
* flexible to ensure it can support any scenario. Functional arguments allow overriding without
* risks that come with subclasses.
*
*
* For example, the default behavior of adjust tone at max contrast to be at a 7.0 ratio with
* its background is principled and matches accessibility guidance. That does not mean it's the
* desired approach for _every_ design system, and every color pairing, always, in every case.
*
*
* For opaque colors (colors with alpha = 100%).
*
* @param name The name of the dynamic color.
* @param palette Function that provides a TonalPalette given DynamicScheme. A TonalPalette is
* defined by a hue and chroma, so this replaces the need to specify hue/chroma. By providing
* a tonal palette, when contrast adjustments are made, intended chroma can be preserved.
* @param tone Function that provides a tone, given a DynamicScheme.
* @param isBackground Whether this dynamic color is a background, with some other color as the
* foreground.
* @param background The background of the dynamic color (as a function of a `DynamicScheme`), if
* it exists.
* @param secondBackground A second background of the dynamic color (as a function of a
* `DynamicScheme`), if it exists.
* @param contrastCurve A `ContrastCurve` object specifying how its contrast against its
* background should behave in various contrast levels options.
* @param toneDeltaPair A `ToneDeltaPair` object specifying a tone delta constraint between two
* colors. One of them must be the color being constructed.
* @param opacity A function returning the opacity of a color, as a number between 0 and 1.
*/
constructor(
name: String,
palette: (DynamicScheme) -> TonalPalette,
tone: (DynamicScheme) -> Double,
isBackground: Boolean,
background: ((DynamicScheme) -> DynamicColor)?,
secondBackground: ((DynamicScheme) -> DynamicColor)?,
contrastCurve: ContrastCurve?,
toneDeltaPair: ((DynamicScheme) -> ToneDeltaPair)?,
opacity: ((DynamicScheme) -> Double)?,
) {
this.name = name
this.palette = palette
this.tone = tone
this.isBackground = isBackground
this.background = background
this.secondBackground = secondBackground
this.contrastCurve = contrastCurve
this.toneDeltaPair = toneDeltaPair
this.opacity = opacity
}
/**
* Returns an ARGB integer (i.e. a hex code).
*
* @param scheme Defines the conditions of the user interface, for example, whether or not it is
* dark mode or light mode, and what the desired contrast level is.
*/
fun getArgb(scheme: DynamicScheme): Int {
val argb: Int = getHct(scheme).toInt()
if (opacity == null) {
return argb
}
val percentage: Double = opacity.invoke(scheme)
val alpha: Int =
clampInt(0, 255, round(percentage * 255).toInt())
return (argb and 0x00ffffff) or (alpha shl 24)
}
/**
* Returns an HCT object.
*
* @param scheme Defines the conditions of the user interface, for example, whether or not it is
* dark mode or light mode, and what the desired contrast level is.
*/
fun getHct(scheme: DynamicScheme): Hct {
val cachedAnswer = hctCache[scheme]
if (cachedAnswer != null) {
return cachedAnswer
}
// This is crucial for aesthetics: we aren't simply the taking the standard color
// and changing its tone for contrast. Rather, we find the tone for contrast, then
// use the specified chroma from the palette to construct a new color.
//
// For example, this enables colors with standard tone of T90, which has limited chroma, to
// "recover" intended chroma as contrast increases.
val tone = getTone(scheme)
val answer: Hct = palette(scheme).getHct(tone)
// NOMUTANTS--trivial test with onerous dependency injection requirement.
if (hctCache.size > 4) {
hctCache.clear()
}
// NOMUTANTS--trivial test with onerous dependency injection requirement.
hctCache.put(scheme, answer)
return answer
}
/** Returns the tone in HCT, ranging from 0 to 100, of the resolved color given scheme. */
fun getTone(scheme: DynamicScheme): Double {
val decreasingContrast: Boolean = scheme.contrastLevel < 0
// Case 1: dual foreground, pair of colors with delta constraint.
if (toneDeltaPair != null) {
val toneDeltaPair: ToneDeltaPair = toneDeltaPair.invoke(scheme)
val roleA: DynamicColor = toneDeltaPair.roleA
val roleB: DynamicColor = toneDeltaPair.roleB
val delta: Double = toneDeltaPair.delta
val polarity: TonePolarity = toneDeltaPair.getPolarity()
val stayTogether: Boolean = toneDeltaPair.stayTogether
val bg: DynamicColor = background!!(scheme)
val bgTone = bg.getTone(scheme)
val aIsNearer =
(polarity === TonePolarity.NEARER || (polarity === TonePolarity.LIGHTER && !scheme.isDark)
|| (polarity === TonePolarity.DARKER && scheme.isDark))
val nearer = if (aIsNearer) roleA else roleB
val farther = if (aIsNearer) roleB else roleA
val amNearer = name == nearer.name
val expansionDir = (if (scheme.isDark) 1 else -1).toDouble()
// 1st round: solve to min, each
val nContrast = nearer.contrastCurve!!.get(scheme.contrastLevel)
val fContrast = farther.contrastCurve!!.get(scheme.contrastLevel)
// If a color is good enough, it is not adjusted.
// Initial and adjusted tones for `nearer`
val nInitialTone: Double = nearer.tone(scheme)
var nTone =
if (Contrast.ratioOfTones(bgTone, nInitialTone) >= nContrast)
nInitialTone
else
foregroundTone(bgTone, nContrast)
// Initial and adjusted tones for `farther`
val fInitialTone: Double = farther.tone(scheme)
var fTone =
if (Contrast.ratioOfTones(bgTone, fInitialTone) >= fContrast)
fInitialTone
else
foregroundTone(bgTone, fContrast)
if (decreasingContrast) {
// If decreasing contrast, adjust color to the "bare minimum"
// that satisfies contrast.
nTone = foregroundTone(bgTone, nContrast)
fTone = foregroundTone(bgTone, fContrast)
}
// If constraint is not satisfied, try another round.
if ((fTone - nTone) * expansionDir < delta) {
// 2nd round: expand farther to match delta.
fTone = clampDouble(0.0, 100.0, nTone + delta * expansionDir)
// If constraint is not satisfied, try another round.
if ((fTone - nTone) * expansionDir < delta) {
// 3rd round: contract nearer to match delta.
nTone = clampDouble(0.0, 100.0, fTone - delta * expansionDir)
}
}
// Avoids the 50-59 awkward zone.
if (50 <= nTone && nTone < 60) {
// If `nearer` is in the awkward zone, move it away, together with
// `farther`.
if (expansionDir > 0) {
nTone = 60.0
fTone = max(fTone, nTone + delta * expansionDir)
} else {
nTone = 49.0
fTone = min(fTone, nTone + delta * expansionDir)
}
} else if (50 <= fTone && fTone < 60) {
if (stayTogether) {
// Fixes both, to avoid two colors on opposite sides of the "awkward
// zone".
if (expansionDir > 0) {
nTone = 60.0
fTone = max(fTone, nTone + delta * expansionDir)
} else {
nTone = 49.0
fTone = min(fTone, nTone + delta * expansionDir)
}
} else {
// Not required to stay together; fixes just one.
fTone = if (expansionDir > 0) {
60.0
} else {
49.0
}
}
}
// Returns `nTone` if this color is `nearer`, otherwise `fTone`.
return if (amNearer) nTone else fTone
} else {
// Case 2: No contrast pair; just solve for itself.
var answer: Double = tone(scheme)
if (background == null) {
return answer // No adjustment for colors with no background.
}
val bgTone: Double = background!!(scheme).getTone(scheme)
val desiredRatio = contrastCurve!!.get(scheme.contrastLevel)
if (Contrast.ratioOfTones(bgTone, answer) >= desiredRatio) {
// Don't "improve" what's good enough.
} else {
// Rough improvement.
answer = foregroundTone(bgTone, desiredRatio)
}
if (decreasingContrast) {
answer = foregroundTone(bgTone, desiredRatio)
}
if (isBackground && 50 <= answer && answer < 60) {
// Must adjust
answer = if (Contrast.ratioOfTones(49.0, bgTone) >= desiredRatio) {
49.0
} else {
60.0
}
}
if (secondBackground != null) {
// Case 3: Adjust for dual backgrounds.
val bgTone1: Double = background!!(scheme).getTone(scheme)
val bgTone2: Double = secondBackground!!(scheme).getTone(scheme)
val upper: Double = max(bgTone1, bgTone2)
val lower: Double = min(bgTone1, bgTone2)
if (Contrast.ratioOfTones(upper, answer) >= desiredRatio
&& Contrast.ratioOfTones(lower, answer) >= desiredRatio
) {
return answer
}
// The darkest light tone that satisfies the desired ratio,
// or -1 if such ratio cannot be reached.
val lightOption: Double = Contrast.lighter(upper, desiredRatio)
// The lightest dark tone that satisfies the desired ratio,
// or -1 if such ratio cannot be reached.
val darkOption: Double = Contrast.darker(lower, desiredRatio)
// Tones suitable for the foreground.
val availables: ArrayList<Double> = ArrayList()
if (lightOption != -1.0) {
availables.add(lightOption)
}
if (darkOption != -1.0) {
availables.add(darkOption)
}
val prefersLight =
tonePrefersLightForeground(bgTone1)
|| tonePrefersLightForeground(bgTone2)
if (prefersLight) {
return if ((lightOption == -1.0)) 100.0 else lightOption
}
if (availables.size == 1) {
return availables.get(0)
}
return if ((darkOption == -1.0)) 0.0 else darkOption
}
return answer
}
}
companion object {
/**
* A convenience constructor for DynamicColor.
*
*
* _Strongly_ prefer using one of the convenience constructors. This class is arguably too
* flexible to ensure it can support any scenario. Functional arguments allow overriding without
* risks that come with subclasses.
*
*
* For example, the default behavior of adjust tone at max contrast to be at a 7.0 ratio with
* its background is principled and matches accessibility guidance. That does not mean it's the
* desired approach for _every_ design system, and every color pairing, always, in every case.
*
*
* For opaque colors (colors with alpha = 100%).
*
*
* For colors that are not backgrounds, and do not have backgrounds.
*
* @param name The name of the dynamic color.
* @param palette Function that provides a TonalPalette given DynamicScheme. A TonalPalette is
* defined by a hue and chroma, so this replaces the need to specify hue/chroma. By providing
* a tonal palette, when contrast adjustments are made, intended chroma can be preserved.
* @param tone Function that provides a tone, given a DynamicScheme.
*/
fun fromPalette(
name: String,
palette: (DynamicScheme) -> TonalPalette,
tone: (DynamicScheme) -> Double,
): DynamicColor {
return DynamicColor(
name,
palette,
tone, /* isBackground= */
false, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
/**
* A convenience constructor for DynamicColor.
*
*
* _Strongly_ prefer using one of the convenience constructors. This class is arguably too
* flexible to ensure it can support any scenario. Functional arguments allow overriding without
* risks that come with subclasses.
*
*
* For example, the default behavior of adjust tone at max contrast to be at a 7.0 ratio with
* its background is principled and matches accessibility guidance. That does not mean it's the
* desired approach for _every_ design system, and every color pairing, always, in every case.
*
*
* For opaque colors (colors with alpha = 100%).
*
*
* For colors that do not have backgrounds.
*
* @param name The name of the dynamic color.
* @param palette Function that provides a TonalPalette given DynamicScheme. A TonalPalette is
* defined by a hue and chroma, so this replaces the need to specify hue/chroma. By providing
* a tonal palette, when contrast adjustments are made, intended chroma can be preserved.
* @param tone Function that provides a tone, given a DynamicScheme.
* @param isBackground Whether this dynamic color is a background, with some other color as the
* foreground.
*/
fun fromPalette(
name: String,
palette: (DynamicScheme) -> TonalPalette,
tone: (DynamicScheme) -> Double,
isBackground: Boolean
): DynamicColor {
return DynamicColor(
name,
palette,
tone,
isBackground, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
/**
* Create a DynamicColor from a hex code.
*
*
* Result has no background; thus no support for increasing/decreasing contrast for a11y.
*
* @param name The name of the dynamic color.
* @param argb The source color from which to extract the hue and chroma.
*/
fun fromArgb(name: String, argb: Int): DynamicColor {
val hct: Hct = Hct.fromInt(argb)
val palette: TonalPalette =
TonalPalette.fromInt(argb)
return fromPalette(name,
{ palette },
{ hct.getTone() })
}
/**
* Given a background tone, find a foreground tone, while ensuring they reach a contrast ratio
* that is as close to ratio as possible.
*/
fun foregroundTone(bgTone: Double, ratio: Double): Double {
val lighterTone: Double = Contrast.lighterUnsafe(bgTone, ratio)
val darkerTone: Double = Contrast.darkerUnsafe(bgTone, ratio)
val lighterRatio: Double = Contrast.ratioOfTones(lighterTone, bgTone)
val darkerRatio: Double = Contrast.ratioOfTones(darkerTone, bgTone)
val preferLighter = tonePrefersLightForeground(bgTone)
if (preferLighter) {
// "Neglible difference" handles an edge case where the initial contrast ratio is high
// (ex. 13.0), and the ratio passed to the function is that high ratio, and both the lighter
// and darker ratio fails to pass that ratio.
//
// This was observed with Tonal Spot's On Primary Container turning black momentarily between
// high and max contrast in light mode. PC's standard tone was T90, OPC's was T10, it was
// light mode, and the contrast level was 0.6568521221032331.
val negligibleDifference =
abs(lighterRatio - darkerRatio) < 0.1 && lighterRatio < ratio && darkerRatio < ratio
return if (lighterRatio >= ratio || lighterRatio >= darkerRatio || negligibleDifference) {
lighterTone
} else {
darkerTone
}
} else {
return if (darkerRatio >= ratio || darkerRatio >= lighterRatio) darkerTone else lighterTone
}
}
/**
* Adjust a tone down such that white has 4.5 contrast, if the tone is reasonably close to
* supporting it.
*/
fun enableLightForeground(tone: Double): Double {
if (tonePrefersLightForeground(tone) && !toneAllowsLightForeground(tone)) {
return 49.0
}
return tone
}
/**
* People prefer white foregrounds on ~T60-70. Observed over time, and also by Andrew Somers
* during research for APCA.
*
*
* T60 used as to create the smallest discontinuity possible when skipping down to T49 in order
* to ensure light foregrounds.
*
*
* Since `tertiaryContainer` in dark monochrome scheme requires a tone of 60, it should not be
* adjusted. Therefore, 60 is excluded here.
*/
fun tonePrefersLightForeground(tone: Double): Boolean {
return round(tone) < 60
}
/** Tones less than ~T50 always permit white at 4.5 contrast. */
fun toneAllowsLightForeground(tone: Double): Boolean {
return round(tone) <= 49
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/dynamiccolor/DynamicScheme.kt | Kotlin | package dev.zwander.compose.libmonet.dynamiccolor
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
import dev.zwander.compose.libmonet.utils.MathUtils.sanitizeDegreesDouble
/**
* Provides important settings for creating colors dynamically, and 6 color palettes. Requires: 1. A
* color. (source color) 2. A theme. (Variant) 3. Whether or not its dark mode. 4. Contrast level.
* (-1 to 1, currently contrast ratio 3.0 and 7.0)
*/
open class DynamicScheme(
val sourceColorHct: Hct,
val variant: Variant,
val isDark: Boolean,
val contrastLevel: Double,
val primaryPalette: TonalPalette,
val secondaryPalette: TonalPalette,
val tertiaryPalette: TonalPalette,
val neutralPalette: TonalPalette,
val neutralVariantPalette: TonalPalette
) {
val sourceColorArgb: Int = sourceColorHct.toInt()
val errorPalette: TonalPalette =
TonalPalette.fromHueAndChroma(25.0, 84.0)
fun getHct(dynamicColor: DynamicColor): Hct {
return dynamicColor.getHct(this)
}
fun getArgb(dynamicColor: DynamicColor): Int {
return dynamicColor.getArgb(this)
}
val primaryPaletteKeyColor: Int
get() = getArgb(MaterialDynamicColors().primaryPaletteKeyColor())
val secondaryPaletteKeyColor: Int
get() = getArgb(MaterialDynamicColors().secondaryPaletteKeyColor())
val tertiaryPaletteKeyColor: Int
get() = getArgb(MaterialDynamicColors().tertiaryPaletteKeyColor())
val neutralPaletteKeyColor: Int
get() = getArgb(MaterialDynamicColors().neutralPaletteKeyColor())
val neutralVariantPaletteKeyColor: Int
get() = getArgb(MaterialDynamicColors().neutralVariantPaletteKeyColor())
val background: Int
get() = getArgb(MaterialDynamicColors().background())
val onBackground: Int
get() = getArgb(MaterialDynamicColors().onBackground())
val surface: Int
get() = getArgb(MaterialDynamicColors().surface())
val surfaceDim: Int
get() = getArgb(MaterialDynamicColors().surfaceDim())
val surfaceBright: Int
get() = getArgb(MaterialDynamicColors().surfaceBright())
val surfaceContainerLowest: Int
get() = getArgb(MaterialDynamicColors().surfaceContainerLowest())
val surfaceContainerLow: Int
get() = getArgb(MaterialDynamicColors().surfaceContainerLow())
val surfaceContainer: Int
get() = getArgb(MaterialDynamicColors().surfaceContainer())
val surfaceContainerHigh: Int
get() = getArgb(MaterialDynamicColors().surfaceContainerHigh())
val surfaceContainerHighest: Int
get() = getArgb(MaterialDynamicColors().surfaceContainerHighest())
val onSurface: Int
get() = getArgb(MaterialDynamicColors().onSurface())
val surfaceVariant: Int
get() = getArgb(MaterialDynamicColors().surfaceVariant())
val onSurfaceVariant: Int
get() = getArgb(MaterialDynamicColors().onSurfaceVariant())
val inverseSurface: Int
get() = getArgb(MaterialDynamicColors().inverseSurface())
val inverseOnSurface: Int
get() = getArgb(MaterialDynamicColors().inverseOnSurface())
val outline: Int
get() = getArgb(MaterialDynamicColors().outline())
val outlineVariant: Int
get() = getArgb(MaterialDynamicColors().outlineVariant())
val shadow: Int
get() = getArgb(MaterialDynamicColors().shadow())
val scrim: Int
get() = getArgb(MaterialDynamicColors().scrim())
val surfaceTint: Int
get() = getArgb(MaterialDynamicColors().surfaceTint())
val primary: Int
get() = getArgb(MaterialDynamicColors().primary())
val onPrimary: Int
get() = getArgb(MaterialDynamicColors().onPrimary())
val primaryContainer: Int
get() = getArgb(MaterialDynamicColors().primaryContainer())
val onPrimaryContainer: Int
get() = getArgb(MaterialDynamicColors().onPrimaryContainer())
val inversePrimary: Int
get() = getArgb(MaterialDynamicColors().inversePrimary())
val secondary: Int
get() = getArgb(MaterialDynamicColors().secondary())
val onSecondary: Int
get() = getArgb(MaterialDynamicColors().onSecondary())
val secondaryContainer: Int
get() = getArgb(MaterialDynamicColors().secondaryContainer())
val onSecondaryContainer: Int
get() = getArgb(MaterialDynamicColors().onSecondaryContainer())
val tertiary: Int
get() = getArgb(MaterialDynamicColors().tertiary())
val onTertiary: Int
get() = getArgb(MaterialDynamicColors().onTertiary())
val tertiaryContainer: Int
get() = getArgb(MaterialDynamicColors().tertiaryContainer())
val onTertiaryContainer: Int
get() = getArgb(MaterialDynamicColors().onTertiaryContainer())
val error: Int
get() = getArgb(MaterialDynamicColors().error())
val onError: Int
get() = getArgb(MaterialDynamicColors().onError())
val errorContainer: Int
get() = getArgb(MaterialDynamicColors().errorContainer())
val onErrorContainer: Int
get() = getArgb(MaterialDynamicColors().onErrorContainer())
val primaryFixed: Int
get() = getArgb(MaterialDynamicColors().primaryFixed())
val primaryFixedDim: Int
get() = getArgb(MaterialDynamicColors().primaryFixedDim())
val onPrimaryFixed: Int
get() = getArgb(MaterialDynamicColors().onPrimaryFixed())
val onPrimaryFixedVariant: Int
get() = getArgb(MaterialDynamicColors().onPrimaryFixedVariant())
val secondaryFixed: Int
get() = getArgb(MaterialDynamicColors().secondaryFixed())
val secondaryFixedDim: Int
get() = getArgb(MaterialDynamicColors().secondaryFixedDim())
val onSecondaryFixed: Int
get() = getArgb(MaterialDynamicColors().onSecondaryFixed())
val onSecondaryFixedVariant: Int
get() = getArgb(MaterialDynamicColors().onSecondaryFixedVariant())
val tertiaryFixed: Int
get() = getArgb(MaterialDynamicColors().tertiaryFixed())
val tertiaryFixedDim: Int
get() = getArgb(MaterialDynamicColors().tertiaryFixedDim())
val onTertiaryFixed: Int
get() = getArgb(MaterialDynamicColors().onTertiaryFixed())
val onTertiaryFixedVariant: Int
get() = getArgb(MaterialDynamicColors().onTertiaryFixedVariant())
val controlActivated: Int
get() = getArgb(MaterialDynamicColors().controlActivated())
val controlNormal: Int
get() = getArgb(MaterialDynamicColors().controlNormal())
val controlHighlight: Int
get() = getArgb(MaterialDynamicColors().controlHighlight())
val textPrimaryInverse: Int
get() = getArgb(MaterialDynamicColors().textPrimaryInverse())
val textSecondaryAndTertiaryInverse: Int
get() = getArgb(MaterialDynamicColors().textSecondaryAndTertiaryInverse())
val textPrimaryInverseDisableOnly: Int
get() = getArgb(MaterialDynamicColors().textPrimaryInverseDisableOnly())
val textSecondaryAndTertiaryInverseDisabled: Int
get() = getArgb(MaterialDynamicColors().textSecondaryAndTertiaryInverseDisabled())
val textHintInverse: Int
get() = getArgb(MaterialDynamicColors().textHintInverse())
companion object {
/**
* Given a set of hues and set of hue rotations, locate which hues the source color's hue is
* between, apply the rotation at the same index as the first hue in the range, and return the
* rotated hue.
*
* @param sourceColorHct The color whose hue should be rotated.
* @param hues A set of hues.
* @param rotations A set of hue rotations.
* @return Color's hue with a rotation applied.
*/
fun getRotatedHue(sourceColorHct: Hct, hues: DoubleArray, rotations: DoubleArray): Double {
val sourceHue: Double = sourceColorHct.getHue()
if (rotations.size == 1) {
return sanitizeDegreesDouble(sourceHue + rotations[0])
}
val size = hues.size
for (i in 0..(size - 2)) {
val thisHue = hues[i]
val nextHue = hues[i + 1]
if (thisHue < sourceHue && sourceHue < nextHue) {
return sanitizeDegreesDouble(sourceHue + rotations[i])
}
}
// If this statement executes, something is wrong, there should have been a rotation
// found using the arrays.
return sourceHue
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/dynamiccolor/MaterialDynamicColors.kt | Kotlin | package dev.zwander.compose.libmonet.dynamiccolor
import dev.zwander.compose.libmonet.dislike.DislikeAnalyzer.fixIfDisliked
import dev.zwander.compose.libmonet.hct.Hct
import kotlin.math.abs
import kotlin.math.max
/** Named colors, otherwise known as tokens, or roles, in the Material Design system. */ // Prevent lint for Function.apply not being available on Android before API level 14 (4.0.1).
// "AndroidJdkLibsChecker" for Function, "NewApi" for Function.apply().
// A java_library Bazel rule with an Android constraint cannot skip these warnings without this
// annotation; another solution would be to create an android_library rule and supply
// AndroidManifest with an SDK set higher than 14.
class MaterialDynamicColors {
/** Optionally use fidelity on most color schemes. */
private val isExtendedFidelity: Boolean
constructor() {
this.isExtendedFidelity = false
}
// Temporary constructor to support extended fidelity experiment.
// TODO(b/291720794): Once schemes that will permanently use fidelity are identified,
// remove this and default to the decided behavior.
constructor(isExtendedFidelity: Boolean) {
this.isExtendedFidelity = isExtendedFidelity
}
fun highestSurface(s: DynamicScheme): DynamicColor {
return if (s.isDark) surfaceBright() else surfaceDim()
}
// Compatibility Keys Colors for Android
fun primaryPaletteKeyColor(): DynamicColor {
return DynamicColor.fromPalette( /* name= */
"primary_palette_key_color", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s -> s.primaryPalette.keyColor.getTone() })
}
fun secondaryPaletteKeyColor(): DynamicColor {
return DynamicColor.fromPalette( /* name= */
"secondary_palette_key_color", /* palette= */
{ s -> s.secondaryPalette }, /* tone= */
{ s -> s.secondaryPalette.keyColor.getTone() })
}
fun tertiaryPaletteKeyColor(): DynamicColor {
return DynamicColor.fromPalette( /* name= */
"tertiary_palette_key_color", /* palette= */
{ s -> s.tertiaryPalette }, /* tone= */
{ s -> s.tertiaryPalette.keyColor.getTone() })
}
fun neutralPaletteKeyColor(): DynamicColor {
return DynamicColor.fromPalette( /* name= */
"neutral_palette_key_color", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s -> s.neutralPalette.keyColor.getTone() })
}
fun neutralVariantPaletteKeyColor(): DynamicColor {
return DynamicColor.fromPalette( /* name= */
"neutral_variant_palette_key_color", /* palette= */
{ s -> s.neutralVariantPalette }, /* tone= */
{ s -> s.neutralVariantPalette.keyColor.getTone() })
}
fun background(): DynamicColor {
return DynamicColor( /* name= */
"background", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s -> if (s.isDark) 6.0 else 98.0 }, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun onBackground(): DynamicColor {
return DynamicColor( /* name= */
"on_background", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s -> if (s.isDark) 90.0 else 10.0 }, /* isBackground= */
false, /* background= */
{ s -> background() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(3.0, 3.0, 4.5, 7.0), /* toneDeltaPair= */
null
)
}
fun surface(): DynamicColor {
return DynamicColor( /* name= */
"surface", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s -> if (s.isDark) 6.0 else 98.0 }, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun surfaceDim(): DynamicColor {
return DynamicColor( /* name= */
"surface_dim", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s ->
if (s.isDark) 6.0 else ContrastCurve(
87.0,
87.0,
80.0,
75.0
).get(s.contrastLevel)
}, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun surfaceBright(): DynamicColor {
return DynamicColor( /* name= */
"surface_bright", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s ->
if (s.isDark) ContrastCurve(
24.0,
24.0,
29.0,
34.0
).get(s.contrastLevel) else 98.0
}, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun surfaceContainerLowest(): DynamicColor {
return DynamicColor( /* name= */
"surface_container_lowest", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s ->
if (s.isDark) ContrastCurve(
4.0,
4.0,
2.0,
0.0
).get(s.contrastLevel) else 100.0
}, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun surfaceContainerLow(): DynamicColor {
return DynamicColor( /* name= */
"surface_container_low", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s ->
if (s.isDark)
ContrastCurve(10.0, 10.0, 11.0, 12.0).get(s.contrastLevel)
else
ContrastCurve(96.0, 96.0, 96.0, 95.0).get(s.contrastLevel)
}, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun surfaceContainer(): DynamicColor {
return DynamicColor( /* name= */
"surface_container", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s ->
if (s.isDark)
ContrastCurve(12.0, 12.0, 16.0, 20.0).get(s.contrastLevel)
else
ContrastCurve(94.0, 94.0, 92.0, 90.0).get(s.contrastLevel)
}, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun surfaceContainerHigh(): DynamicColor {
return DynamicColor( /* name= */
"surface_container_high", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s ->
if (s.isDark)
ContrastCurve(17.0, 17.0, 21.0, 25.0).get(s.contrastLevel)
else
ContrastCurve(92.0, 92.0, 88.0, 85.0).get(s.contrastLevel)
}, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun surfaceContainerHighest(): DynamicColor {
return DynamicColor( /* name= */
"surface_container_highest", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s ->
if (s.isDark)
ContrastCurve(22.0, 22.0, 26.0, 30.0).get(s.contrastLevel)
else
ContrastCurve(90.0, 90.0, 84.0, 80.0).get(s.contrastLevel)
}, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun onSurface(): DynamicColor {
return DynamicColor( /* name= */
"on_surface", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s -> if (s.isDark) 90.0 else 10.0 }, /* isBackground= */
false, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun surfaceVariant(): DynamicColor {
return DynamicColor( /* name= */
"surface_variant", /* palette= */
{ s -> s.neutralVariantPalette }, /* tone= */
{ s -> if (s.isDark) 30.0 else 90.0 }, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun onSurfaceVariant(): DynamicColor {
return DynamicColor( /* name= */
"on_surface_variant", /* palette= */
{ s -> s.neutralVariantPalette }, /* tone= */
{ s -> if (s.isDark) 80.0 else 30.0 }, /* isBackground= */
false, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(3.0, 4.5, 7.0, 11.0), /* toneDeltaPair= */
null
)
}
fun inverseSurface(): DynamicColor {
return DynamicColor( /* name= */
"inverse_surface", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s -> if (s.isDark) 90.0 else 20.0 }, /* isBackground= */
false, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun inverseOnSurface(): DynamicColor {
return DynamicColor( /* name= */
"inverse_on_surface", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s -> if (s.isDark) 20.0 else 95.0 }, /* isBackground= */
false, /* background= */
{ s -> inverseSurface() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun outline(): DynamicColor {
return DynamicColor( /* name= */
"outline", /* palette= */
{ s -> s.neutralVariantPalette }, /* tone= */
{ s -> if (s.isDark) 60.0 else 50.0 }, /* isBackground= */
false, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.5, 3.0, 4.5, 7.0), /* toneDeltaPair= */
null
)
}
fun outlineVariant(): DynamicColor {
return DynamicColor( /* name= */
"outline_variant", /* palette= */
{ s -> s.neutralVariantPalette }, /* tone= */
{ s -> if (s.isDark) 30.0 else 80.0 }, /* isBackground= */
false, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
null
)
}
fun shadow(): DynamicColor {
return DynamicColor( /* name= */
"shadow", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s -> 0.0 }, /* isBackground= */
false, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun scrim(): DynamicColor {
return DynamicColor( /* name= */
"scrim", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s -> 0.0 }, /* isBackground= */
false, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun surfaceTint(): DynamicColor {
return DynamicColor( /* name= */
"surface_tint", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s -> if (s.isDark) 80.0 else 40.0 }, /* isBackground= */
true, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null
)
}
fun primary(): DynamicColor {
return DynamicColor( /* name= */
"primary", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s ->
if (isMonochrome(s)) {
return@DynamicColor if (s.isDark) 100.0 else 0.0
}
if (s.isDark) 80.0 else 40.0
}, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(3.0, 4.5, 7.0, 7.0), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
primaryContainer(),
primary(),
10.0,
TonePolarity.NEARER,
false
)
})
}
fun onPrimary(): DynamicColor {
return DynamicColor( /* name= */
"on_primary", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s ->
if (isMonochrome(s)) {
return@DynamicColor if (s.isDark) 10.0 else 90.0
}
if (s.isDark) 20.0 else 100.0
}, /* isBackground= */
false, /* background= */
{ s -> primary() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun primaryContainer(): DynamicColor {
return DynamicColor( /* name= */
"primary_container", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s ->
if (isFidelity(s)) {
return@DynamicColor s.sourceColorHct.getTone()
}
if (isMonochrome(s)) {
return@DynamicColor if (s.isDark) 85.0 else 25.0
}
if (s.isDark) 30.0 else 90.0
}, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
primaryContainer(),
primary(),
10.0,
TonePolarity.NEARER,
false
)
})
}
fun onPrimaryContainer(): DynamicColor {
return DynamicColor( /* name= */
"on_primary_container", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s ->
if (isFidelity(s)) {
return@DynamicColor DynamicColor.foregroundTone(
primaryContainer().tone(s), 4.5
)
}
if (isMonochrome(s)) {
return@DynamicColor if (s.isDark) 0.0 else 100.0
}
if (s.isDark) 90.0 else 10.0
}, /* isBackground= */
false, /* background= */
{ s -> primaryContainer() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun inversePrimary(): DynamicColor {
return DynamicColor( /* name= */
"inverse_primary", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s -> if (s.isDark) 40.0 else 80.0 }, /* isBackground= */
false, /* background= */
{ s -> inverseSurface() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(3.0, 4.5, 7.0, 7.0), /* toneDeltaPair= */
null
)
}
fun secondary(): DynamicColor {
return DynamicColor( /* name= */
"secondary", /* palette= */
{ s -> s.secondaryPalette }, /* tone= */
{ s -> if (s.isDark) 80.0 else 40.0 }, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(3.0, 4.5, 7.0, 7.0), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
secondaryContainer(),
secondary(),
10.0,
TonePolarity.NEARER,
false
)
})
}
fun onSecondary(): DynamicColor {
return DynamicColor( /* name= */
"on_secondary", /* palette= */
{ s -> s.secondaryPalette }, /* tone= */
{ s ->
if (isMonochrome(s)) {
return@DynamicColor if (s.isDark) 10.0 else 100.0
} else {
return@DynamicColor if (s.isDark) 20.0 else 100.0
}
}, /* isBackground= */
false, /* background= */
{ s -> secondary() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun secondaryContainer(): DynamicColor {
return DynamicColor( /* name= */
"secondary_container", /* palette= */
{ s -> s.secondaryPalette }, /* tone= */
{ s ->
val initialTone = if (s.isDark) 30.0 else 90.0
if (isMonochrome(s)) {
return@DynamicColor if (s.isDark) 30.0 else 85.0
}
if (!isFidelity(s)) {
return@DynamicColor initialTone
}
findDesiredChromaByTone(
s.secondaryPalette.hue,
s.secondaryPalette.chroma,
initialTone,
!s.isDark
)
}, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
secondaryContainer(),
secondary(),
10.0,
TonePolarity.NEARER,
false
)
})
}
fun onSecondaryContainer(): DynamicColor {
return DynamicColor( /* name= */
"on_secondary_container", /* palette= */
{ s -> s.secondaryPalette }, /* tone= */
{ s ->
if (!isFidelity(s)) {
return@DynamicColor if (s.isDark) 90.0 else 10.0
}
DynamicColor.foregroundTone(secondaryContainer().tone(s), 4.5)
}, /* isBackground= */
false, /* background= */
{ s -> secondaryContainer() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun tertiary(): DynamicColor {
return DynamicColor( /* name= */
"tertiary", /* palette= */
{ s -> s.tertiaryPalette }, /* tone= */
{ s ->
if (isMonochrome(s)) {
return@DynamicColor if (s.isDark) 90.0 else 25.0
}
if (s.isDark) 80.0 else 40.0
}, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(3.0, 4.5, 7.0, 7.0), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
tertiaryContainer(),
tertiary(),
10.0,
TonePolarity.NEARER,
false
)
})
}
fun onTertiary(): DynamicColor {
return DynamicColor( /* name= */
"on_tertiary", /* palette= */
{ s -> s.tertiaryPalette }, /* tone= */
{ s ->
if (isMonochrome(s)) {
return@DynamicColor if (s.isDark) 10.0 else 90.0
}
if (s.isDark) 20.0 else 100.0
}, /* isBackground= */
false, /* background= */
{ s -> tertiary() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun tertiaryContainer(): DynamicColor {
return DynamicColor( /* name= */
"tertiary_container", /* palette= */
{ s -> s.tertiaryPalette }, /* tone= */
{ s ->
if (isMonochrome(s)) {
return@DynamicColor if (s.isDark) 60.0 else 49.0
}
if (!isFidelity(s)) {
return@DynamicColor if (s.isDark) 30.0 else 90.0
}
val proposedHct = s.tertiaryPalette.getHct(s.sourceColorHct.getTone())
fixIfDisliked(proposedHct).getTone()
}, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
tertiaryContainer(),
tertiary(),
10.0,
TonePolarity.NEARER,
false
)
})
}
fun onTertiaryContainer(): DynamicColor {
return DynamicColor( /* name= */
"on_tertiary_container", /* palette= */
{ s -> s.tertiaryPalette }, /* tone= */
{ s ->
if (isMonochrome(s)) {
return@DynamicColor if (s.isDark) 0.0 else 100.0
}
if (!isFidelity(s)) {
return@DynamicColor if (s.isDark) 90.0 else 10.0
}
DynamicColor.foregroundTone(tertiaryContainer().tone(s), 4.5)
}, /* isBackground= */
false, /* background= */
{ s -> tertiaryContainer() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun error(): DynamicColor {
return DynamicColor( /* name= */
"error", /* palette= */
{ s -> s.errorPalette }, /* tone= */
{ s -> if (s.isDark) 80.0 else 40.0 }, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(3.0, 4.5, 7.0, 7.0), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
errorContainer(),
error(),
10.0,
TonePolarity.NEARER,
false
)
})
}
fun onError(): DynamicColor {
return DynamicColor( /* name= */
"on_error", /* palette= */
{ s -> s.errorPalette }, /* tone= */
{ s -> if (s.isDark) 20.0 else 100.0 }, /* isBackground= */
false, /* background= */
{ s -> error() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun errorContainer(): DynamicColor {
return DynamicColor( /* name= */
"error_container", /* palette= */
{ s -> s.errorPalette }, /* tone= */
{ s -> if (s.isDark) 30.0 else 90.0 }, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
errorContainer(),
error(),
10.0,
TonePolarity.NEARER,
false
)
})
}
fun onErrorContainer(): DynamicColor {
return DynamicColor( /* name= */
"on_error_container", /* palette= */
{ s -> s.errorPalette }, /* tone= */
{ s -> if (s.isDark) 90.0 else 10.0 }, /* isBackground= */
false, /* background= */
{ s -> errorContainer() }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun primaryFixed(): DynamicColor {
return DynamicColor( /* name= */
"primary_fixed", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 40.0 else 90.0 }, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
primaryFixed(),
primaryFixedDim(),
10.0,
TonePolarity.LIGHTER,
true
)
})
}
fun primaryFixedDim(): DynamicColor {
return DynamicColor( /* name= */
"primary_fixed_dim", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 30.0 else 80.0 }, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
primaryFixed(),
primaryFixedDim(),
10.0,
TonePolarity.LIGHTER,
true
)
})
}
fun onPrimaryFixed(): DynamicColor {
return DynamicColor( /* name= */
"on_primary_fixed", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 100.0 else 10.0 }, /* isBackground= */
false, /* background= */
{ s -> primaryFixedDim() }, /* secondBackground= */
{ s -> primaryFixed() }, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun onPrimaryFixedVariant(): DynamicColor {
return DynamicColor( /* name= */
"on_primary_fixed_variant", /* palette= */
{ s -> s.primaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 90.0 else 30.0 }, /* isBackground= */
false, /* background= */
{ s -> primaryFixedDim() }, /* secondBackground= */
{ s -> primaryFixed() }, /* contrastCurve= */
ContrastCurve(3.0, 4.5, 7.0, 11.0), /* toneDeltaPair= */
null
)
}
fun secondaryFixed(): DynamicColor {
return DynamicColor( /* name= */
"secondary_fixed", /* palette= */
{ s -> s.secondaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 80.0 else 90.0 }, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
secondaryFixed(), secondaryFixedDim(), 10.0, TonePolarity.LIGHTER, true
)
})
}
fun secondaryFixedDim(): DynamicColor {
return DynamicColor( /* name= */
"secondary_fixed_dim", /* palette= */
{ s -> s.secondaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 70.0 else 80.0 }, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
secondaryFixed(), secondaryFixedDim(), 10.0, TonePolarity.LIGHTER, true
)
})
}
fun onSecondaryFixed(): DynamicColor {
return DynamicColor( /* name= */
"on_secondary_fixed", /* palette= */
{ s -> s.secondaryPalette }, /* tone= */
{ s -> 10.0 }, /* isBackground= */
false, /* background= */
{ s -> secondaryFixedDim() }, /* secondBackground= */
{ s -> secondaryFixed() }, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun onSecondaryFixedVariant(): DynamicColor {
return DynamicColor( /* name= */
"on_secondary_fixed_variant", /* palette= */
{ s -> s.secondaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 25.0 else 30.0 }, /* isBackground= */
false, /* background= */
{ s -> secondaryFixedDim() }, /* secondBackground= */
{ s -> secondaryFixed() }, /* contrastCurve= */
ContrastCurve(3.0, 4.5, 7.0, 11.0), /* toneDeltaPair= */
null
)
}
fun tertiaryFixed(): DynamicColor {
return DynamicColor( /* name= */
"tertiary_fixed", /* palette= */
{ s -> s.tertiaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 40.0 else 90.0 }, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
tertiaryFixed(), tertiaryFixedDim(), 10.0, TonePolarity.LIGHTER, true
)
})
}
fun tertiaryFixedDim(): DynamicColor {
return DynamicColor( /* name= */
"tertiary_fixed_dim", /* palette= */
{ s -> s.tertiaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 30.0 else 80.0 }, /* isBackground= */
true, /* background= */
{ s: DynamicScheme -> this.highestSurface(s) }, /* secondBackground= */
null, /* contrastCurve= */
ContrastCurve(1.0, 1.0, 3.0, 4.5), /* toneDeltaPair= */
{ s ->
ToneDeltaPair(
tertiaryFixed(), tertiaryFixedDim(), 10.0, TonePolarity.LIGHTER, true
)
})
}
fun onTertiaryFixed(): DynamicColor {
return DynamicColor( /* name= */
"on_tertiary_fixed", /* palette= */
{ s -> s.tertiaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 100.0 else 10.0 }, /* isBackground= */
false, /* background= */
{ s -> tertiaryFixedDim() }, /* secondBackground= */
{ s -> tertiaryFixed() }, /* contrastCurve= */
ContrastCurve(4.5, 7.0, 11.0, 21.0), /* toneDeltaPair= */
null
)
}
fun onTertiaryFixedVariant(): DynamicColor {
return DynamicColor( /* name= */
"on_tertiary_fixed_variant", /* palette= */
{ s -> s.tertiaryPalette }, /* tone= */
{ s -> if (isMonochrome(s)) 90.0 else 30.0 }, /* isBackground= */
false, /* background= */
{ s -> tertiaryFixedDim() }, /* secondBackground= */
{ s -> tertiaryFixed() }, /* contrastCurve= */
ContrastCurve(3.0, 4.5, 7.0, 11.0), /* toneDeltaPair= */
null
)
}
/**
* These colors were present in Android framework before Android U, and used by MDC controls. They
* should be avoided, if possible. It's unclear if they're used on multiple backgrounds, and if
* they are, they can't be adjusted for contrast.* For now, they will be set with no background,
* and those won't adjust for contrast, avoiding issues.
*
*
* * For example, if the same color is on a white background _and_ black background, there's no
* way to increase contrast with either without losing contrast with the other.
*/
// colorControlActivated documented as colorAccent in M3 & GM3.
// colorAccent documented as colorSecondary in M3 and colorPrimary in GM3.
// Android used Material's Container as Primary/Secondary/Tertiary at launch.
// Therefore, this is a duplicated version of Primary Container.
fun controlActivated(): DynamicColor {
return DynamicColor.fromPalette(
"control_activated", { s -> s.primaryPalette }, { s -> if (s.isDark) 30.0 else 90.0 })
}
// colorControlNormal documented as textColorSecondary in M3 & GM3.
// In Material, textColorSecondary points to onSurfaceVariant in the non-disabled state,
// which is Neutral Variant T30/80 in light/dark.
fun controlNormal(): DynamicColor {
return DynamicColor.fromPalette(
"control_normal",
{ s -> s.neutralVariantPalette },
{ s -> if (s.isDark) 80.0 else 30.0 })
}
// colorControlHighlight documented, in both M3 & GM3:
// Light mode: #1f000000 dark mode: #33ffffff.
// These are black and white with some alpha.
// 1F hex = 31 decimal; 31 / 255 = 12% alpha.
// 33 hex = 51 decimal; 51 / 255 = 20% alpha.
// DynamicColors do not support alpha currently, and _may_ not need it for this use case,
// depending on how MDC resolved alpha for the other cases.
// Returning black in dark mode, white in light mode.
fun controlHighlight(): DynamicColor {
return DynamicColor( /* name= */
"control_highlight", /* palette= */
{ s -> s.neutralPalette }, /* tone= */
{ s -> if (s.isDark) 100.0 else 0.0 }, /* isBackground= */
false, /* background= */
null, /* secondBackground= */
null, /* contrastCurve= */
null, /* toneDeltaPair= */
null, /* opacity= */
{ s -> if (s.isDark) 0.20 else 0.12 })
}
// textColorPrimaryInverse documented, in both M3 & GM3, documented as N10/N90.
fun textPrimaryInverse(): DynamicColor {
return DynamicColor.fromPalette(
"text_primary_inverse",
{ s -> s.neutralPalette },
{ s -> if (s.isDark) 10.0 else 90.0 })
}
// textColorSecondaryInverse and textColorTertiaryInverse both documented, in both M3 & GM3, as
// NV30/NV80
fun textSecondaryAndTertiaryInverse(): DynamicColor {
return DynamicColor.fromPalette(
"text_secondary_and_tertiary_inverse",
{ s -> s.neutralVariantPalette },
{ s -> if (s.isDark) 30.0 else 80.0 })
}
// textColorPrimaryInverseDisableOnly documented, in both M3 & GM3, as N10/N90
fun textPrimaryInverseDisableOnly(): DynamicColor {
return DynamicColor.fromPalette(
"text_primary_inverse_disable_only",
{ s -> s.neutralPalette },
{ s -> if (s.isDark) 10.0 else 90.0 })
}
// textColorSecondaryInverse and textColorTertiaryInverse in disabled state both documented,
// in both M3 & GM3, as N10/N90
fun textSecondaryAndTertiaryInverseDisabled(): DynamicColor {
return DynamicColor.fromPalette(
"text_secondary_and_tertiary_inverse_disabled",
{ s -> s.neutralPalette },
{ s -> if (s.isDark) 10.0 else 90.0 })
}
// textColorHintInverse documented, in both M3 & GM3, as N10/N90
fun textHintInverse(): DynamicColor {
return DynamicColor.fromPalette(
"text_hint_inverse", { s -> s.neutralPalette }, { s -> if (s.isDark) 10.0 else 90.0 })
}
private fun isFidelity(scheme: DynamicScheme): Boolean {
if (this.isExtendedFidelity
&& scheme.variant !== Variant.MONOCHROME && scheme.variant !== Variant.NEUTRAL
) {
return true
}
return scheme.variant === Variant.FIDELITY || scheme.variant === Variant.CONTENT
}
companion object {
private fun isMonochrome(scheme: DynamicScheme): Boolean {
return scheme.variant === Variant.MONOCHROME
}
fun findDesiredChromaByTone(
hue: Double, chroma: Double, tone: Double, byDecreasingTone: Boolean
): Double {
var answer = tone
var closestToChroma: Hct = Hct.from(hue, chroma, tone)
if (closestToChroma.getChroma() < chroma) {
var chromaPeak: Double = closestToChroma.getChroma()
while (closestToChroma.getChroma() < chroma) {
answer += if (byDecreasingTone) -1.0 else 1.0
val potentialSolution: Hct = Hct.from(hue, chroma, answer)
if (chromaPeak > potentialSolution.getChroma()) {
break
}
if (abs(potentialSolution.getChroma() - chroma) < 0.4) {
break
}
val potentialDelta: Double =
abs(potentialSolution.getChroma() - chroma)
val currentDelta: Double =
abs(closestToChroma.getChroma() - chroma)
if (potentialDelta < currentDelta) {
closestToChroma = potentialSolution
}
chromaPeak = max(chromaPeak, potentialSolution.getChroma())
}
}
return answer
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/dynamiccolor/ToneDeltaPair.kt | Kotlin | package dev.zwander.compose.libmonet.dynamiccolor
/**
* Documents a constraint between two DynamicColors, in which their tones must have a certain
* distance from each other.
*
*
* Prefer a DynamicColor with a background, this is for special cases when designers want tonal
* distance, literally contrast, between two colors that don't have a background / foreground
* relationship or a contrast guarantee.
*/
class ToneDeltaPair(
/** The first role in a pair. */
val roleA: DynamicColor,
/** The second role in a pair. */
val roleB: DynamicColor,
/** Required difference between tones. Absolute value, negative values have undefined behavior. */
val delta: Double,
/** The relative relation between tones of roleA and roleB, as described above. */
private val polarity: TonePolarity,
/**
* Whether these two roles should stay on the same side of the "awkward zone" (T50-59). This is
* necessary for certain cases where one role has two backgrounds.
*/
val stayTogether: Boolean
) {
fun getPolarity(): TonePolarity {
return polarity
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/dynamiccolor/TonePolarity.kt | Kotlin | package dev.zwander.compose.libmonet.dynamiccolor
/**
* Describes the relationship in lightness between two colors.
*
*
* 'nearer' and 'farther' describes closeness to the surface roles. For instance,
* ToneDeltaPair(A, B, 10, 'nearer', stayTogether) states that A should be 10 lighter than B in
* light mode, and 10 darker than B in dark mode.
*
*
* See `ToneDeltaPair` for details.
*/
enum class TonePolarity {
DARKER,
LIGHTER,
NEARER,
FARTHER
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/dynamiccolor/Variant.kt | Kotlin | package dev.zwander.compose.libmonet.dynamiccolor
/** Themes for Dynamic Color. */
enum class Variant {
MONOCHROME,
NEUTRAL,
TONAL_SPOT,
VIBRANT,
EXPRESSIVE,
FIDELITY,
CONTENT,
RAINBOW,
FRUIT_SALAD
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/hct/Cam16.kt | Kotlin | package dev.zwander.compose.libmonet.hct
import dev.zwander.compose.libmonet.utils.ColorUtils
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.expm1
import kotlin.math.hypot
import kotlin.math.ln1p
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sign
import kotlin.math.sin
import kotlin.math.sqrt
/**
* CAM16, a color appearance model. Colors are not just defined by their hex code, but rather, a hex
* code and viewing conditions.
*
*
* CAM16 instances also have coordinates in the CAM16-UCS space, called J*, a*, b*, or jstar,
* astar, bstar in code. CAM16-UCS is included in the CAM16 specification, and should be used when
* measuring distances between colors.
*
*
* In traditional color spaces, a color can be identified solely by the observer's measurement of
* the color. Color appearance models such as CAM16 also use information about the environment where
* the color was observed, known as the viewing conditions.
*
*
* For example, white under the traditional assumption of a midday sun white point is accurately
* measured as a slightly chromatic blue by CAM16. (roughly, hue 203, chroma 3, lightness 100)
*/
class Cam16
/**
* All of the CAM16 dimensions can be calculated from 3 of the dimensions, in the following
* combinations: - {j or q} and {c, m, or s} and hue - jstar, astar, bstar Prefer using a static
* method that constructs from 3 of those dimensions. This constructor is intended for those
* methods to use to return all possible dimensions.
*
* @param hue for example, red, orange, yellow, green, etc.
* @param chroma informally, colorfulness / color intensity. like saturation in HSL, except
* perceptually accurate.
* @param j lightness
* @param q brightness; ratio of lightness to white point's lightness
* @param m colorfulness
* @param s saturation; ratio of chroma to white point's chroma
* @param jstar CAM16-UCS J coordinate
* @param astar CAM16-UCS a coordinate
* @param bstar CAM16-UCS b coordinate
*/ private constructor(
/** Hue in CAM16 */
// CAM16 color dimensions, see getters for documentation.
val hue: Double,
/** Chroma in CAM16 */
val chroma: Double,
/** Lightness in CAM16 */
val j: Double,
/**
* Brightness in CAM16.
*
*
* Prefer lightness, brightness is an absolute quantity. For example, a sheet of white paper is
* much brighter viewed in sunlight than in indoor light, but it is the lightest object under any
* lighting.
*/
val q: Double,
/**
* Colorfulness in CAM16.
*
*
* Prefer chroma, colorfulness is an absolute quantity. For example, a yellow toy car is much
* more colorful outside than inside, but it has the same chroma in both environments.
*/
val m: Double,
/**
* Saturation in CAM16.
*
*
* Colorfulness in proportion to brightness. Prefer chroma, saturation measures colorfulness
* relative to the color's own brightness, where chroma is colorfulness relative to white.
*/
val s: Double,
/** Lightness coordinate in CAM16-UCS */
// Coordinates in UCS space. Used to determine color distance, like delta E equations in L*a*b*.
val jstar: Double,
/** a* coordinate in CAM16-UCS */
val astar: Double,
/** b* coordinate in CAM16-UCS */
val bstar: Double
) {
// Avoid allocations during conversion by pre-allocating an array.
private val tempArray = doubleArrayOf(0.0, 0.0, 0.0)
/**
* CAM16 instances also have coordinates in the CAM16-UCS space, called J*, a*, b*, or jstar,
* astar, bstar in code. CAM16-UCS is included in the CAM16 specification, and is used to measure
* distances between colors.
*/
fun distance(other: Cam16): Double {
val dJ = jstar - other.jstar
val dA = astar - other.astar
val dB = bstar - other.bstar
val dEPrime = sqrt(dJ * dJ + dA * dA + dB * dB)
val dE = 1.41 * dEPrime.pow(0.63)
return dE
}
/**
* ARGB representation of the color. Assumes the color was viewed in default viewing conditions,
* which are near-identical to the default viewing conditions for sRGB.
*/
fun toInt(): Int {
return viewed(ViewingConditions.DEFAULT)
}
/**
* ARGB representation of the color, in defined viewing conditions.
*
* @param viewingConditions Information about the environment where the color will be viewed.
* @return ARGB representation of color
*/
fun viewed(viewingConditions: ViewingConditions): Int {
val xyz = xyzInViewingConditions(viewingConditions, tempArray)
return ColorUtils.argbFromXyz(xyz[0], xyz[1], xyz[2])
}
fun xyzInViewingConditions(
viewingConditions: ViewingConditions,
returnArray: DoubleArray?
): DoubleArray {
val alpha =
if ((chroma == 0.0 || j == 0.0)) 0.0 else chroma / sqrt(j / 100.0)
val t: Double =
(alpha / (1.64 - 0.29.pow(viewingConditions.n)).pow(0.73)).pow(1.0 / 0.9)
val hRad: Double = hue * PI / 180.0
val eHue = 0.25 * (cos(hRad + 2.0) + 3.8)
val ac: Double =
(viewingConditions.aw
* (j / 100.0).pow(1.0 / viewingConditions.c / viewingConditions.z))
val p1: Double =
eHue * (50000.0 / 13.0) * viewingConditions.nc * viewingConditions.ncb
val p2: Double = (ac / viewingConditions.nbb)
val hSin = sin(hRad)
val hCos = cos(hRad)
val gamma = 23.0 * (p2 + 0.305) * t / (23.0 * p1 + 11.0 * t * hCos + 108.0 * t * hSin)
val a = gamma * hCos
val b = gamma * hSin
val rA = (460.0 * p2 + 451.0 * a + 288.0 * b) / 1403.0
val gA = (460.0 * p2 - 891.0 * a - 261.0 * b) / 1403.0
val bA = (460.0 * p2 - 220.0 * a - 6300.0 * b) / 1403.0
val rCBase: Double = max(0.0, (27.13 * abs(rA)) / (400.0 - abs(rA)))
val rC: Double =
sign(rA) * (100.0 / viewingConditions.fl) * rCBase.pow(1.0 / 0.42)
val gCBase: Double = max(0.0, (27.13 * abs(gA)) / (400.0 - abs(gA)))
val gC: Double =
sign(gA) * (100.0 / viewingConditions.fl) * gCBase.pow(1.0 / 0.42)
val bCBase: Double = max(0.0, (27.13 * abs(bA)) / (400.0 - abs(bA)))
val bC: Double =
sign(bA) * (100.0 / viewingConditions.fl) * bCBase.pow(1.0 / 0.42)
val rF: Double = rC / viewingConditions.rgbD[0]
val gF: Double = gC / viewingConditions.rgbD[1]
val bF: Double = bC / viewingConditions.rgbD[2]
val matrix = CAM16RGB_TO_XYZ
val x = (rF * matrix[0][0]) + (gF * matrix[0][1]) + (bF * matrix[0][2])
val y = (rF * matrix[1][0]) + (gF * matrix[1][1]) + (bF * matrix[1][2])
val z = (rF * matrix[2][0]) + (gF * matrix[2][1]) + (bF * matrix[2][2])
if (returnArray != null) {
returnArray[0] = x
returnArray[1] = y
returnArray[2] = z
return returnArray
} else {
return doubleArrayOf(x, y, z)
}
}
companion object {
// Transforms XYZ color space coordinates to 'cone'/'RGB' responses in CAM16.
val XYZ_TO_CAM16RGB: Array<DoubleArray> = arrayOf(
doubleArrayOf(0.401288, 0.650173, -0.051461),
doubleArrayOf(-0.250268, 1.204414, 0.045854),
doubleArrayOf(-0.002079, 0.048952, 0.953127)
)
// Transforms 'cone'/'RGB' responses in CAM16 to XYZ color space coordinates.
val CAM16RGB_TO_XYZ: Array<DoubleArray> = arrayOf(
doubleArrayOf(1.8620678, -1.0112547, 0.14918678),
doubleArrayOf(0.38752654, 0.62144744, -0.00897398),
doubleArrayOf(-0.01584150, -0.03412294, 1.0499644)
)
/**
* Create a CAM16 color from a color, assuming the color was viewed in default viewing conditions.
*
* @param argb ARGB representation of a color.
*/
fun fromInt(argb: Int): Cam16 {
return fromIntInViewingConditions(argb, ViewingConditions.DEFAULT)
}
/**
* Create a CAM16 color from a color in defined viewing conditions.
*
* @param argb ARGB representation of a color.
* @param viewingConditions Information about the environment where the color was observed.
*/
// The RGB => XYZ conversion matrix elements are derived scientific constants. While the values
// may differ at runtime due to floating point imprecision, keeping the values the same, and
// accurate, across implementations takes precedence.
fun fromIntInViewingConditions(argb: Int, viewingConditions: ViewingConditions): Cam16 {
// Transform ARGB int to XYZ
val red = (argb and 0x00ff0000) shr 16
val green = (argb and 0x0000ff00) shr 8
val blue = (argb and 0x000000ff)
val redL: Double = ColorUtils.linearized(red)
val greenL: Double = ColorUtils.linearized(green)
val blueL: Double = ColorUtils.linearized(blue)
val x = 0.41233895 * redL + 0.35762064 * greenL + 0.18051042 * blueL
val y = 0.2126 * redL + 0.7152 * greenL + 0.0722 * blueL
val z = 0.01932141 * redL + 0.11916382 * greenL + 0.95034478 * blueL
return fromXyzInViewingConditions(x, y, z, viewingConditions)
}
fun fromXyzInViewingConditions(
x: Double, y: Double, z: Double, viewingConditions: ViewingConditions
): Cam16 {
// Transform XYZ to 'cone'/'rgb' responses
val matrix = XYZ_TO_CAM16RGB
val rT = (x * matrix[0][0]) + (y * matrix[0][1]) + (z * matrix[0][2])
val gT = (x * matrix[1][0]) + (y * matrix[1][1]) + (z * matrix[1][2])
val bT = (x * matrix[2][0]) + (y * matrix[2][1]) + (z * matrix[2][2])
// Discount illuminant
val rD: Double = viewingConditions.rgbD.get(0) * rT
val gD: Double = viewingConditions.rgbD.get(1) * gT
val bD: Double = viewingConditions.rgbD.get(2) * bT
// Chromatic adaptation
val rAF: Double = (viewingConditions.fl * abs(rD) / 100.0).pow(0.42)
val gAF: Double = (viewingConditions.fl * abs(gD) / 100.0).pow(0.42)
val bAF: Double = (viewingConditions.fl * abs(bD) / 100.0).pow(0.42)
val rA = sign(rD) * 400.0 * rAF / (rAF + 27.13)
val gA = sign(gD) * 400.0 * gAF / (gAF + 27.13)
val bA = sign(bD) * 400.0 * bAF / (bAF + 27.13)
// redness-greenness
val a = (11.0 * rA + -12.0 * gA + bA) / 11.0
// yellowness-blueness
val b = (rA + gA - 2.0 * bA) / 9.0
// auxiliary components
val u = (20.0 * rA + 20.0 * gA + 21.0 * bA) / 20.0
val p2 = (40.0 * rA + 20.0 * gA + bA) / 20.0
// hue
val atan2 = atan2(b, a)
val atanDegrees: Double = atan2 * 180.0 / PI
val hue =
if (atanDegrees < 0)
atanDegrees + 360.0
else
if (atanDegrees >= 360) atanDegrees - 360.0 else atanDegrees
val hueRadians: Double = hue * PI / 180.0
// achromatic response to color
val ac: Double = p2 * viewingConditions.nbb
// CAM16 lightness and brightness
val j: Double =
(100.0
* (ac / viewingConditions.aw).pow(viewingConditions.c * viewingConditions.z))
val q: Double =
((4.0
/ viewingConditions.c
) * sqrt(j / 100.0) * (viewingConditions.aw + 4.0)
* viewingConditions.flRoot)
// CAM16 chroma, colorfulness, and saturation.
val huePrime = if ((hue < 20.14)) hue + 360 else hue
val eHue = 0.25 * (cos(huePrime * PI / 180.0 + 2.0) + 3.8)
val p1: Double =
50000.0 / 13.0 * eHue * viewingConditions.nc * viewingConditions.ncb
val t = p1 * hypot(a, b) / (u + 0.305)
val alpha: Double =
(1.64 - 0.29.pow(viewingConditions.n)).pow(0.73) * t.pow(0.9)
// CAM16 chroma, colorfulness, saturation
val c = alpha * sqrt(j / 100.0)
val m: Double = c * viewingConditions.flRoot
val s =
50.0 * sqrt((alpha * viewingConditions.c) / (viewingConditions.aw + 4.0))
// CAM16-UCS components
val jstar = (1.0 + 100.0 * 0.007) * j / (1.0 + 0.007 * j)
val mstar = 1.0 / 0.0228 * ln1p(0.0228 * m)
val astar = mstar * cos(hueRadians)
val bstar = mstar * sin(hueRadians)
return Cam16(hue, c, j, q, m, s, jstar, astar, bstar)
}
/**
* @param j CAM16 lightness
* @param c CAM16 chroma
* @param h CAM16 hue
*/
fun fromJch(j: Double, c: Double, h: Double): Cam16 {
return fromJchInViewingConditions(j, c, h, ViewingConditions.DEFAULT)
}
/**
* @param j CAM16 lightness
* @param c CAM16 chroma
* @param h CAM16 hue
* @param viewingConditions Information about the environment where the color was observed.
*/
private fun fromJchInViewingConditions(
j: Double, c: Double, h: Double, viewingConditions: ViewingConditions
): Cam16 {
val q: Double =
((4.0
/ viewingConditions.c
) * sqrt(j / 100.0) * (viewingConditions.aw + 4.0)
* viewingConditions.flRoot)
val m: Double = c * viewingConditions.flRoot
val alpha = c / sqrt(j / 100.0)
val s =
50.0 * sqrt((alpha * viewingConditions.c) / (viewingConditions.aw + 4.0))
val hueRadians: Double = h * PI / 180.0
val jstar = (1.0 + 100.0 * 0.007) * j / (1.0 + 0.007 * j)
val mstar = 1.0 / 0.0228 * ln1p(0.0228 * m)
val astar = mstar * cos(hueRadians)
val bstar = mstar * sin(hueRadians)
return Cam16(h, c, j, q, m, s, jstar, astar, bstar)
}
/**
* Create a CAM16 color from CAM16-UCS coordinates.
*
* @param jstar CAM16-UCS lightness.
* @param astar CAM16-UCS a dimension. Like a* in L*a*b*, it is a Cartesian coordinate on the Y
* axis.
* @param bstar CAM16-UCS b dimension. Like a* in L*a*b*, it is a Cartesian coordinate on the X
* axis.
*/
fun fromUcs(jstar: Double, astar: Double, bstar: Double): Cam16 {
return fromUcsInViewingConditions(jstar, astar, bstar, ViewingConditions.DEFAULT)
}
/**
* Create a CAM16 color from CAM16-UCS coordinates in defined viewing conditions.
*
* @param jstar CAM16-UCS lightness.
* @param astar CAM16-UCS a dimension. Like a* in L*a*b*, it is a Cartesian coordinate on the Y
* axis.
* @param bstar CAM16-UCS b dimension. Like a* in L*a*b*, it is a Cartesian coordinate on the X
* axis.
* @param viewingConditions Information about the environment where the color was observed.
*/
fun fromUcsInViewingConditions(
jstar: Double, astar: Double, bstar: Double, viewingConditions: ViewingConditions
): Cam16 {
val m = hypot(astar, bstar)
val m2 = expm1(m * 0.0228) / 0.0228
val c: Double = m2 / viewingConditions.flRoot
var h: Double = atan2(bstar, astar) * (180.0 / PI)
if (h < 0.0) {
h += 360.0
}
val j = jstar / (1.0 - (jstar - 100.0) * 0.007)
return fromJchInViewingConditions(j, c, h, viewingConditions)
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/hct/Hct.kt | Kotlin | package dev.zwander.compose.libmonet.hct
import dev.zwander.compose.libmonet.utils.ColorUtils
/**
* A color system built using CAM16 hue and chroma, and L* from L*a*b*.
*
*
* Using L* creates a link between the color system, contrast, and thus accessibility. Contrast
* ratio depends on relative luminance, or Y in the XYZ color space. L*, or perceptual luminance can
* be calculated from Y.
*
*
* Unlike Y, L* is linear to human perception, allowing trivial creation of accurate color tones.
*
*
* Unlike contrast ratio, measuring contrast in L* is linear, and simple to calculate. A
* difference of 40 in HCT tone guarantees a contrast ratio >= 3.0, and a difference of 50
* guarantees a contrast ratio >= 4.5.
*/
/**
* HCT, hue, chroma, and tone. A color system that provides a perceptually accurate color
* measurement system that can also accurately render what colors will appear as in different
* lighting environments.
*/
class Hct private constructor(argb: Int) {
private var hue = 0.0
private var chroma = 0.0
private var tone = 0.0
private var argb = 0
init {
setInternalState(argb)
}
fun getHue(): Double {
return hue
}
fun getChroma(): Double {
return chroma
}
fun getTone(): Double {
return tone
}
fun toInt(): Int {
return argb
}
/**
* Set the hue of this color. Chroma may decrease because chroma has a different maximum for any
* given hue and tone.
*
* @param newHue 0 <= newHue < 360; invalid values are corrected.
*/
fun setHue(newHue: Double) {
setInternalState(HctSolver.solveToInt(newHue, chroma, tone))
}
/**
* Set the chroma of this color. Chroma may decrease because chroma has a different maximum for
* any given hue and tone.
*
* @param newChroma 0 <= newChroma < ?
*/
fun setChroma(newChroma: Double) {
setInternalState(HctSolver.solveToInt(hue, newChroma, tone))
}
/**
* Set the tone of this color. Chroma may decrease because chroma has a different maximum for any
* given hue and tone.
*
* @param newTone 0 <= newTone <= 100; invalid valids are corrected.
*/
fun setTone(newTone: Double) {
setInternalState(HctSolver.solveToInt(hue, chroma, newTone))
}
/**
* Translate a color into different ViewingConditions.
*
*
* Colors change appearance. They look different with lights on versus off, the same color, as
* in hex code, on white looks different when on black. This is called color relativity, most
* famously explicated by Josef Albers in Interaction of Color.
*
*
* In color science, color appearance models can account for this and calculate the appearance
* of a color in different settings. HCT is based on CAM16, a color appearance model, and uses it
* to make these calculations.
*
*
* See ViewingConditions.make for parameters affecting color appearance.
*/
fun inViewingConditions(vc: ViewingConditions): Hct {
// 1. Use CAM16 to find XYZ coordinates of color in specified VC.
val cam16 = Cam16.fromInt(toInt())
val viewedInVc = cam16.xyzInViewingConditions(vc, null)
// 2. Create CAM16 of those XYZ coordinates in default VC.
val recastInVc =
Cam16.fromXyzInViewingConditions(
viewedInVc[0], viewedInVc[1], viewedInVc[2], ViewingConditions.DEFAULT
)
// 3. Create HCT from:
// - CAM16 using default VC with XYZ coordinates in specified VC.
// - L* converted from Y in XYZ coordinates in specified VC.
return from(
recastInVc.hue, recastInVc.chroma, ColorUtils.lstarFromY(viewedInVc[1])
)
}
private fun setInternalState(argb: Int) {
this.argb = argb
val cam = Cam16.fromInt(argb)
hue = cam.hue
chroma = cam.chroma
this.tone = ColorUtils.lstarFromArgb(argb)
}
companion object {
/**
* Create an HCT color from hue, chroma, and tone.
*
* @param hue 0 <= hue < 360; invalid values are corrected.
* @param chroma 0 <= chroma < ?; Informally, colorfulness. The color returned may be lower than
* the requested chroma. Chroma has a different maximum for any given hue and tone.
* @param tone 0 <= tone <= 100; invalid values are corrected.
* @return HCT representation of a color in default viewing conditions.
*/
fun from(hue: Double, chroma: Double, tone: Double): Hct {
val argb: Int = HctSolver.solveToInt(hue, chroma, tone)
return Hct(argb)
}
/**
* Create an HCT color from a color.
*
* @param argb ARGB representation of a color.
* @return HCT representation of a color in default viewing conditions
*/
fun fromInt(argb: Int): Hct {
return Hct(argb)
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/hct/HctSolver.kt | Kotlin | package dev.zwander.compose.libmonet.hct
import dev.zwander.compose.libmonet.utils.ColorUtils
import dev.zwander.compose.libmonet.utils.MathUtils.matrixMultiply
import dev.zwander.compose.libmonet.utils.MathUtils.sanitizeDegreesDouble
import dev.zwander.compose.libmonet.utils.MathUtils.signum
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.ceil
import kotlin.math.cos
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.sqrt
/** A class that solves the HCT equation. */
object HctSolver {
val SCALED_DISCOUNT_FROM_LINRGB: Array<DoubleArray> = arrayOf(
doubleArrayOf(
0.001200833568784504, 0.002389694492170889, 0.0002795742885861124,
),
doubleArrayOf(
0.0005891086651375999, 0.0029785502573438758, 0.0003270666104008398,
),
doubleArrayOf(
0.00010146692491640572, 0.0005364214359186694, 0.0032979401770712076,
),
)
val LINRGB_FROM_SCALED_DISCOUNT: Array<DoubleArray> = arrayOf(
doubleArrayOf(
1373.2198709594231, -1100.4251190754821, -7.278681089101213,
),
doubleArrayOf(
-271.815969077903, 559.6580465940733, -32.46047482791194,
),
doubleArrayOf(
1.9622899599665666, -57.173814538844006, 308.7233197812385,
),
)
val Y_FROM_LINRGB: DoubleArray = doubleArrayOf(0.2126, 0.7152, 0.0722)
val CRITICAL_PLANES: DoubleArray = doubleArrayOf(
0.015176349177441876,
0.045529047532325624,
0.07588174588720938,
0.10623444424209313,
0.13658714259697685,
0.16693984095186062,
0.19729253930674434,
0.2276452376616281,
0.2579979360165119,
0.28835063437139563,
0.3188300904430532,
0.350925934958123,
0.3848314933096426,
0.42057480301049466,
0.458183274052838,
0.4976837250274023,
0.5391024159806381,
0.5824650784040898,
0.6277969426914107,
0.6751227633498623,
0.7244668422128921,
0.775853049866786,
0.829304845476233,
0.8848452951698498,
0.942497089126609,
1.0022825574869039,
1.0642236851973577,
1.1283421258858297,
1.1946592148522128,
1.2631959812511864,
1.3339731595349034,
1.407011200216447,
1.4823302800086415,
1.5599503113873272,
1.6398909516233677,
1.7221716113234105,
1.8068114625156377,
1.8938294463134073,
1.9832442801866852,
2.075074464868551,
2.1693382909216234,
2.2660538449872063,
2.36523901573795,
2.4669114995532007,
2.5710888059345764,
2.6777882626779785,
2.7870270208169257,
2.898822059350997,
3.0131901897720907,
3.1301480604002863,
3.2497121605402226,
3.3718988244681087,
3.4967242352587946,
3.624204428461639,
3.754355295633311,
3.887192587735158,
4.022731918402185,
4.160988767090289,
4.301978482107941,
4.445716283538092,
4.592217266055746,
4.741496401646282,
4.893568542229298,
5.048448422192488,
5.20615066083972,
5.3666897647573375,
5.5300801301023865,
5.696336044816294,
5.865471690767354,
6.037501145825082,
6.212438385869475,
6.390297286737924,
6.571091626112461,
6.7548350853498045,
6.941541251256611,
7.131223617812143,
7.323895587840543,
7.5195704746346665,
7.7182615035334345,
7.919981813454504,
8.124744458384042,
8.332562408825165,
8.543448553206703,
8.757415699253682,
8.974476575321063,
9.194643831691977,
9.417930041841839,
9.644347703669503,
9.873909240696694,
10.106627003236781,
10.342513269534024,
10.58158024687427,
10.8238400726681,
11.069304815507364,
11.317986476196008,
11.569896988756009,
11.825048221409341,
12.083451977536606,
12.345119996613247,
12.610063955123938,
12.878295467455942,
13.149826086772048,
13.42466730586372,
13.702830557985108,
13.984327217668513,
14.269168601521828,
14.55736596900856,
14.848930523210871,
15.143873411576273,
15.44220572664832,
15.743938506781891,
16.04908273684337,
16.35764934889634,
16.66964922287304,
16.985093187232053,
17.30399201960269,
17.62635644741625,
17.95219714852476,
18.281524751807332,
18.614349837764564,
18.95068293910138,
19.290534541298456,
19.633915083172692,
19.98083495742689,
20.331304511189067,
20.685334046541502,
21.042933821039977,
21.404114048223256,
21.76888489811322,
22.137256497705877,
22.50923893145328,
22.884842241736916,
23.264076429332462,
23.6469514538663,
24.033477234264016,
24.42366364919083,
24.817520537484558,
25.21505769858089,
25.61628489293138,
26.021211842414342,
26.429848230738664,
26.842203703840827,
27.258287870275353,
27.678110301598522,
28.10168053274597,
28.529008062403893,
28.96010235337422,
29.39497283293396,
29.83362889318845,
30.276079891419332,
30.722335150426627,
31.172403958865512,
31.62629557157785,
32.08401920991837,
32.54558406207592,
33.010999283389665,
33.4802739966603,
33.953417292456834,
34.430438229418264,
34.911345834551085,
35.39614910352207,
35.88485700094671,
36.37747846067349,
36.87402238606382,
37.37449765026789,
37.87891309649659,
38.38727753828926,
38.89959975977785,
39.41588851594697,
39.93615253289054,
40.460400508064545,
40.98864111053629,
41.520882981230194,
42.05713473317016,
42.597404951718396,
43.141702194811224,
43.6900349931913,
44.24241185063697,
44.798841244188324,
45.35933162437017,
45.92389141541209,
46.49252901546552,
47.065252796817916,
47.64207110610409,
48.22299226451468,
48.808024568002054,
49.3971762874833,
49.9904556690408,
50.587870934119984,
51.189430279724725,
51.79514187861014,
52.40501387947288,
53.0190544071392,
53.637271562750364,
54.259673423945976,
54.88626804504493,
55.517063457223934,
56.15206766869424,
56.79128866487574,
57.43473440856916,
58.08241284012621,
58.734331877617365,
59.39049941699807,
60.05092333227251,
60.715611475655585,
61.38457167773311,
62.057811747619894,
62.7353394731159,
63.417162620860914,
64.10328893648692,
64.79372614476921,
65.48848194977529,
66.18756403501224,
66.89098006357258,
67.59873767827808,
68.31084450182222,
69.02730813691093,
69.74813616640164,
70.47333615344107,
71.20291564160104,
71.93688215501312,
72.67524319850172,
73.41800625771542,
74.16517879925733,
74.9167682708136,
75.67278210128072,
76.43322770089146,
77.1981124613393,
77.96744375590167,
78.74122893956174,
79.51947534912904,
80.30219030335869,
81.08938110306934,
81.88105503125999,
82.67721935322541,
83.4778813166706,
84.28304815182372,
85.09272707154808,
85.90692527145302,
86.72564993000343,
87.54890820862819,
88.3767072518277,
89.2090541872801,
90.04595612594655,
90.88742016217518,
91.73345337380438,
92.58406282226491,
93.43925555268066,
94.29903859396902,
95.16341895893969,
96.03240364439274,
96.9059996312159,
97.78421388448044,
98.6670533535366,
99.55452497210776,
)
/**
* Sanitizes a small enough angle in radians.
*
* @param angle An angle in radians; must not deviate too much from 0.
* @return A coterminal angle between 0 and 2pi.
*/
fun sanitizeRadians(angle: Double): Double {
return (angle + PI * 8) % (PI * 2)
}
/**
* Delinearizes an RGB component, returning a floating-point number.
*
* @param rgbComponent 0.0 <= rgb_component <= 100.0, represents linear R/G/B channel
* @return 0.0 <= output <= 255.0, color channel converted to regular RGB space
*/
fun trueDelinearized(rgbComponent: Double): Double {
val normalized = rgbComponent / 100.0
var delinearized = 0.0
delinearized = if (normalized <= 0.0031308) {
normalized * 12.92
} else {
1.055 * normalized.pow(1.0 / 2.4) - 0.055
}
return delinearized * 255.0
}
fun chromaticAdaptation(component: Double): Double {
val af = abs(component).pow(0.42)
return signum(component) * 400.0 * af / (af + 27.13)
}
/**
* Returns the hue of a linear RGB color in CAM16.
*
* @param linrgb The linear RGB coordinates of a color.
* @return The hue of the color in CAM16, in radians.
*/
fun hueOf(linrgb: DoubleArray): Double {
val scaledDiscount: DoubleArray =
matrixMultiply(linrgb, SCALED_DISCOUNT_FROM_LINRGB)
val rA = chromaticAdaptation(scaledDiscount[0])
val gA = chromaticAdaptation(scaledDiscount[1])
val bA = chromaticAdaptation(scaledDiscount[2])
// redness-greenness
val a = (11.0 * rA + -12.0 * gA + bA) / 11.0
// yellowness-blueness
val b = (rA + gA - 2.0 * bA) / 9.0
return atan2(b, a)
}
fun areInCyclicOrder(a: Double, b: Double, c: Double): Boolean {
val deltaAB = sanitizeRadians(b - a)
val deltaAC = sanitizeRadians(c - a)
return deltaAB < deltaAC
}
/**
* Solves the lerp equation.
*
* @param source The starting number.
* @param mid The number in the middle.
* @param target The ending number.
* @return A number t such that lerp(source, target, t) = mid.
*/
fun intercept(source: Double, mid: Double, target: Double): Double {
return (mid - source) / (target - source)
}
fun lerpPoint(source: DoubleArray, t: Double, target: DoubleArray): DoubleArray {
return doubleArrayOf(
source[0] + (target[0] - source[0]) * t,
source[1] + (target[1] - source[1]) * t,
source[2] + (target[2] - source[2]) * t,
)
}
/**
* Intersects a segment with a plane.
*
* @param source The coordinates of point A.
* @param coordinate The R-, G-, or B-coordinate of the plane.
* @param target The coordinates of point B.
* @param axis The axis the plane is perpendicular with. (0: R, 1: G, 2: B)
* @return The intersection point of the segment AB with the plane R=coordinate, G=coordinate, or
* B=coordinate
*/
fun setCoordinate(
source: DoubleArray,
coordinate: Double,
target: DoubleArray,
axis: Int
): DoubleArray {
val t = intercept(source[axis], coordinate, target[axis])
return lerpPoint(source, t, target)
}
fun isBounded(x: Double): Boolean {
return 0.0 <= x && x <= 100.0
}
/**
* Returns the nth possible vertex of the polygonal intersection.
*
* @param y The Y value of the plane.
* @param n The zero-based index of the point. 0 <= n <= 11.
* @return The nth possible vertex of the polygonal intersection of the y plane and the RGB cube,
* in linear RGB coordinates, if it exists. If this possible vertex lies outside of the cube,
* [-1.0, -1.0, -1.0] is returned.
*/
fun nthVertex(y: Double, n: Int): DoubleArray {
val kR = Y_FROM_LINRGB[0]
val kG = Y_FROM_LINRGB[1]
val kB = Y_FROM_LINRGB[2]
val coordA = if (n % 4 <= 1) 0.0 else 100.0
val coordB = if (n % 2 == 0) 0.0 else 100.0
if (n < 4) {
val g = coordA
val b = coordB
val r = (y - g * kG - b * kB) / kR
return if (isBounded(r)) {
doubleArrayOf(r, g, b)
} else {
doubleArrayOf(-1.0, -1.0, -1.0)
}
} else if (n < 8) {
val b = coordA
val r = coordB
val g = (y - r * kR - b * kB) / kG
return if (isBounded(g)) {
doubleArrayOf(r, g, b)
} else {
doubleArrayOf(-1.0, -1.0, -1.0)
}
} else {
val r = coordA
val g = coordB
val b = (y - r * kR - g * kG) / kB
return if (isBounded(b)) {
doubleArrayOf(r, g, b)
} else {
doubleArrayOf(-1.0, -1.0, -1.0)
}
}
}
/**
* Finds the segment containing the desired color.
*
* @param y The Y value of the color.
* @param targetHue The hue of the color.
* @return A list of two sets of linear RGB coordinates, each corresponding to an endpoint of the
* segment containing the desired color.
*/
fun bisectToSegment(y: Double, targetHue: Double): Array<DoubleArray> {
var left = doubleArrayOf(-1.0, -1.0, -1.0)
var right = left
var leftHue = 0.0
var rightHue = 0.0
var initialized = false
var uncut = true
for (n in 0..11) {
val mid = nthVertex(y, n)
if (mid[0] < 0) {
continue
}
val midHue = hueOf(mid)
if (!initialized) {
left = mid
right = mid
leftHue = midHue
rightHue = midHue
initialized = true
continue
}
if (uncut || areInCyclicOrder(leftHue, midHue, rightHue)) {
uncut = false
if (areInCyclicOrder(leftHue, targetHue, midHue)) {
right = mid
rightHue = midHue
} else {
left = mid
leftHue = midHue
}
}
}
return arrayOf(left, right)
}
fun midpoint(a: DoubleArray, b: DoubleArray): DoubleArray {
return doubleArrayOf(
(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2,
)
}
fun criticalPlaneBelow(x: Double): Int {
return floor(x - 0.5).toInt()
}
fun criticalPlaneAbove(x: Double): Int {
return ceil(x - 0.5).toInt()
}
/**
* Finds a color with the given Y and hue on the boundary of the cube.
*
* @param y The Y value of the color.
* @param targetHue The hue of the color.
* @return The desired color, in linear RGB coordinates.
*/
fun bisectToLimit(y: Double, targetHue: Double): DoubleArray {
val segment = bisectToSegment(y, targetHue)
var left = segment[0]
var leftHue = hueOf(left)
var right = segment[1]
for (axis in 0..2) {
if (left[axis] != right[axis]) {
var lPlane = -1
var rPlane = 255
if (left[axis] < right[axis]) {
lPlane = criticalPlaneBelow(trueDelinearized(left[axis]))
rPlane = criticalPlaneAbove(trueDelinearized(right[axis]))
} else {
lPlane = criticalPlaneAbove(trueDelinearized(left[axis]))
rPlane = criticalPlaneBelow(trueDelinearized(right[axis]))
}
for (i in 0..7) {
if (abs((rPlane - lPlane).toDouble()) <= 1) {
break
} else {
val mPlane = floor((lPlane + rPlane) / 2.0).toInt()
val midPlaneCoordinate = CRITICAL_PLANES[mPlane]
val mid = setCoordinate(left, midPlaneCoordinate, right, axis)
val midHue = hueOf(mid)
if (areInCyclicOrder(leftHue, targetHue, midHue)) {
right = mid
rPlane = mPlane
} else {
left = mid
leftHue = midHue
lPlane = mPlane
}
}
}
}
}
return midpoint(left, right)
}
fun inverseChromaticAdaptation(adapted: Double): Double {
val adaptedAbs = abs(adapted)
val base = max(0.0, 27.13 * adaptedAbs / (400.0 - adaptedAbs))
return signum(adapted) * base.pow(1.0 / 0.42)
}
/**
* Finds a color with the given hue, chroma, and Y.
*
* @param hueRadians The desired hue in radians.
* @param chroma The desired chroma.
* @param y The desired Y.
* @return The desired color as a hexadecimal integer, if found; 0 otherwise.
*/
fun findResultByJ(hueRadians: Double, chroma: Double, y: Double): Int {
// Initial estimate of j.
var j = sqrt(y) * 11.0
// ===========================================================
// Operations inlined from Cam16 to avoid repeated calculation
// ===========================================================
val viewingConditions: ViewingConditions = ViewingConditions.DEFAULT
val tInnerCoeff: Double = 1 / (1.64 - 0.29.pow(viewingConditions.n)).pow(0.73)
val eHue = 0.25 * (cos(hueRadians + 2.0) + 3.8)
val p1: Double =
eHue * (50000.0 / 13.0) * viewingConditions.nc * viewingConditions.ncb
val hSin = sin(hueRadians)
val hCos = cos(hueRadians)
for (iterationRound in 0..4) {
// ===========================================================
// Operations inlined from Cam16 to avoid repeated calculation
// ===========================================================
val jNormalized = j / 100.0
val alpha = if (chroma == 0.0 || j == 0.0) 0.0 else chroma / sqrt(jNormalized)
val t = (alpha * tInnerCoeff).pow(1.0 / 0.9)
val ac: Double =
(viewingConditions.aw
* jNormalized.pow(1.0 / viewingConditions.c / viewingConditions.z))
val p2: Double = ac / viewingConditions.nbb
val gamma = 23.0 * (p2 + 0.305) * t / (23.0 * p1 + 11 * t * hCos + 108.0 * t * hSin)
val a = gamma * hCos
val b = gamma * hSin
val rA = (460.0 * p2 + 451.0 * a + 288.0 * b) / 1403.0
val gA = (460.0 * p2 - 891.0 * a - 261.0 * b) / 1403.0
val bA = (460.0 * p2 - 220.0 * a - 6300.0 * b) / 1403.0
val rCScaled = inverseChromaticAdaptation(rA)
val gCScaled = inverseChromaticAdaptation(gA)
val bCScaled = inverseChromaticAdaptation(bA)
val linrgb: DoubleArray =
matrixMultiply(
doubleArrayOf(rCScaled, gCScaled, bCScaled), LINRGB_FROM_SCALED_DISCOUNT
)
// ===========================================================
// Operations inlined from Cam16 to avoid repeated calculation
// ===========================================================
if (linrgb[0] < 0 || linrgb[1] < 0 || linrgb[2] < 0) {
return 0
}
val kR = Y_FROM_LINRGB[0]
val kG = Y_FROM_LINRGB[1]
val kB = Y_FROM_LINRGB[2]
val fnj = kR * linrgb[0] + kG * linrgb[1] + kB * linrgb[2]
if (fnj <= 0) {
return 0
}
if (iterationRound == 4 || abs(fnj - y) < 0.002) {
if (linrgb[0] > 100.01 || linrgb[1] > 100.01 || linrgb[2] > 100.01) {
return 0
}
return ColorUtils.argbFromLinrgb(linrgb)
}
// Iterates with Newton method,
// Using 2 * fn(j) / j as the approximation of fn'(j)
j -= (fnj - y) * j / (2 * fnj)
}
return 0
}
/**
* Finds an sRGB color with the given hue, chroma, and L*, if possible.
*
* @param hueDegrees The desired hue, in degrees.
* @param chroma The desired chroma.
* @param lstar The desired L*.
* @return A hexadecimal representing the sRGB color. The color has sufficiently close hue,
* chroma, and L* to the desired values, if possible; otherwise, the hue and L* will be
* sufficiently close, and chroma will be maximized.
*/
fun solveToInt(hueDegrees: Double, chroma: Double, lstar: Double): Int {
var hueDegrees = hueDegrees
if (chroma < 0.0001 || lstar < 0.0001 || lstar > 99.9999) {
return ColorUtils.argbFromLstar(lstar)
}
hueDegrees = sanitizeDegreesDouble(hueDegrees)
val hueRadians: Double = hueDegrees / 180 * PI
val y: Double = ColorUtils.yFromLstar(lstar)
val exactAnswer = findResultByJ(hueRadians, chroma, y)
if (exactAnswer != 0) {
return exactAnswer
}
val linrgb = bisectToLimit(y, hueRadians)
return ColorUtils.argbFromLinrgb(linrgb)
}
/**
* Finds an sRGB color with the given hue, chroma, and L*, if possible.
*
* @param hueDegrees The desired hue, in degrees.
* @param chroma The desired chroma.
* @param lstar The desired L*.
* @return A CAM16 object representing the sRGB color. The color has sufficiently close hue,
* chroma, and L* to the desired values, if possible; otherwise, the hue and L* will be
* sufficiently close, and chroma will be maximized.
*/
fun solveToCam(hueDegrees: Double, chroma: Double, lstar: Double): Cam16 {
return Cam16.fromInt(solveToInt(hueDegrees, chroma, lstar))
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/hct/ViewingConditions.kt | Kotlin | package dev.zwander.compose.libmonet.hct
import dev.zwander.compose.libmonet.utils.ColorUtils
import dev.zwander.compose.libmonet.utils.MathUtils.clampDouble
import dev.zwander.compose.libmonet.utils.MathUtils.lerp
import kotlin.math.PI
import kotlin.math.cbrt
import kotlin.math.exp
import kotlin.math.max
import kotlin.math.pow
import kotlin.math.sqrt
/**
* In traditional color spaces, a color can be identified solely by the observer's measurement of
* the color. Color appearance models such as CAM16 also use information about the environment where
* the color was observed, known as the viewing conditions.
*
*
* For example, white under the traditional assumption of a midday sun white point is accurately
* measured as a slightly chromatic blue by CAM16. (roughly, hue 203, chroma 3, lightness 100)
*
*
* This class caches intermediate values of the CAM16 conversion process that depend only on
* viewing conditions, enabling speed ups.
*/
class ViewingConditions
/**
* Parameters are intermediate values of the CAM16 conversion process. Their names are shorthand
* for technical color science terminology, this class would not benefit from documenting them
* individually. A brief overview is available in the CAM16 specification, and a complete overview
* requires a color science textbook, such as Fairchild's Color Appearance Models.
*/ private constructor(
val n: Double,
val aw: Double,
val nbb: Double,
val ncb: Double,
val c: Double,
val nc: Double,
val rgbD: DoubleArray,
val fl: Double,
val flRoot: Double,
val z: Double
) {
companion object {
/** sRGB-like viewing conditions. */
val DEFAULT: ViewingConditions = defaultWithBackgroundLstar(50.0)
/**
* Create ViewingConditions from a simple, physically relevant, set of parameters.
*
* @param whitePoint White point, measured in the XYZ color space. default = D65, or sunny day
* afternoon
* @param adaptingLuminance The luminance of the adapting field. Informally, how bright it is in
* the room where the color is viewed. Can be calculated from lux by multiplying lux by
* 0.0586. default = 11.72, or 200 lux.
* @param backgroundLstar The lightness of the area surrounding the color. measured by L* in
* L*a*b*. default = 50.0
* @param surround A general description of the lighting surrounding the color. 0 is pitch dark,
* like watching a movie in a theater. 1.0 is a dimly light room, like watching TV at home at
* night. 2.0 means there is no difference between the lighting on the color and around it.
* default = 2.0
* @param discountingIlluminant Whether the eye accounts for the tint of the ambient lighting,
* such as knowing an apple is still red in green light. default = false, the eye does not
* perform this process on self-luminous objects like displays.
*/
fun make(
whitePoint: DoubleArray,
adaptingLuminance: Double,
backgroundLstar: Double,
surround: Double,
discountingIlluminant: Boolean
): ViewingConditions {
// A background of pure black is non-physical and leads to infinities that represent the idea
// that any color viewed in pure black can't be seen.
var backgroundLstar = backgroundLstar
backgroundLstar = max(0.1, backgroundLstar)
// Transform white point XYZ to 'cone'/'rgb' responses
val matrix = Cam16.XYZ_TO_CAM16RGB
val xyz = whitePoint
val rW = (xyz[0] * matrix[0][0]) + (xyz[1] * matrix[0][1]) + (xyz[2] * matrix[0][2])
val gW = (xyz[0] * matrix[1][0]) + (xyz[1] * matrix[1][1]) + (xyz[2] * matrix[1][2])
val bW = (xyz[0] * matrix[2][0]) + (xyz[1] * matrix[2][1]) + (xyz[2] * matrix[2][2])
val f = 0.8 + (surround / 10.0)
val c: Double =
(if ((f >= 0.9))
lerp(0.59, 0.69, ((f - 0.9) * 10.0))
else
lerp(0.525, 0.59, ((f - 0.8) * 10.0))).toDouble()
var d =
if (discountingIlluminant)
1.0
else
f * (1.0 - ((1.0 / 3.6) * exp((-adaptingLuminance - 42.0) / 92.0)))
d = clampDouble(0.0, 1.0, d)
val nc = f
val rgbD =
doubleArrayOf(
d * (100.0 / rW) + 1.0 - d,
d * (100.0 / gW) + 1.0 - d,
d * (100.0 / bW) + 1.0 - d
)
val k = 1.0 / (5.0 * adaptingLuminance + 1.0)
val k4 = k * k * k * k
val k4F = 1.0 - k4
val fl = (k4 * adaptingLuminance) + (0.1 * k4F * k4F * cbrt(5.0 * adaptingLuminance))
val n: Double = (ColorUtils.yFromLstar(backgroundLstar) / whitePoint[1])
val z = 1.48 + sqrt(n)
val nbb = 0.725 / n.pow(0.2)
val ncb = nbb
val rgbAFactors =
doubleArrayOf(
(fl * rgbD[0] * rW / 100.0).pow(0.42),
(fl * rgbD[1] * gW / 100.0).pow(0.42),
(fl * rgbD[2] * bW / 100.0).pow(0.42)
)
val rgbA =
doubleArrayOf(
(400.0 * rgbAFactors[0]) / (rgbAFactors[0] + 27.13),
(400.0 * rgbAFactors[1]) / (rgbAFactors[1] + 27.13),
(400.0 * rgbAFactors[2]) / (rgbAFactors[2] + 27.13)
)
val aw = ((2.0 * rgbA[0]) + rgbA[1] + (0.05 * rgbA[2])) * nbb
return ViewingConditions(n, aw, nbb, ncb, c, nc, rgbD, fl, fl.pow(0.25), z)
}
/**
* Create sRGB-like viewing conditions with a custom background lstar.
*
*
* Default viewing conditions have a lstar of 50, midgray.
*/
fun defaultWithBackgroundLstar(lstar: Double): ViewingConditions {
return make(
ColorUtils.whitePointD65(),
(200.0 / PI * ColorUtils.yFromLstar(50.0) / 100f),
lstar,
2.0,
false
)
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/palettes/CorePalette.kt | Kotlin | package dev.zwander.compose.libmonet.palettes
import dev.zwander.compose.libmonet.hct.Hct
import kotlin.math.max
import kotlin.math.min
/**
* An intermediate concept between the key color for a UI theme, and a full color scheme. 5 sets of
* tones are generated, all except one use the same hue as the key color, and all vary in chroma.
*/
class CorePalette private constructor(argb: Int, isContent: Boolean) {
val a1: TonalPalette
val a2: TonalPalette
val a3: TonalPalette
val n1: TonalPalette
val n2: TonalPalette
val error: TonalPalette
init {
val hct = Hct.fromInt(argb)
val hue = hct.getHue()
val chroma = hct.getChroma()
if (isContent) {
this.a1 = TonalPalette.fromHueAndChroma(hue, chroma)
this.a2 = TonalPalette.fromHueAndChroma(hue, chroma / 3.0)
this.a3 = TonalPalette.fromHueAndChroma(hue + 60.0, chroma / 2.0)
this.n1 = TonalPalette.fromHueAndChroma(hue, min(chroma / 12.0, 4.0))
this.n2 = TonalPalette.fromHueAndChroma(hue, min(chroma / 6.0, 8.0))
} else {
this.a1 = TonalPalette.fromHueAndChroma(hue, max(48.0, chroma))
this.a2 = TonalPalette.fromHueAndChroma(hue, 16.0)
this.a3 = TonalPalette.fromHueAndChroma(hue + 60.0, 24.0)
this.n1 = TonalPalette.fromHueAndChroma(hue, 4.0)
this.n2 = TonalPalette.fromHueAndChroma(hue, 8.0)
}
this.error = TonalPalette.fromHueAndChroma(25.0, 84.0)
}
companion object {
/**
* Create key tones from a color.
*
* @param argb ARGB representation of a color
*/
fun of(argb: Int): CorePalette {
return CorePalette(argb, false)
}
/**
* Create content key tones from a color.
*
* @param argb ARGB representation of a color
*/
fun contentOf(argb: Int): CorePalette {
return CorePalette(argb, true)
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/palettes/TonalPalette.kt | Kotlin | package dev.zwander.compose.libmonet.palettes
import dev.zwander.compose.libmonet.hct.Hct
import kotlin.math.abs
import kotlin.math.round
/**
* A convenience class for retrieving colors that are constant in hue and chroma, but vary in tone.
*/
class TonalPalette private constructor(
/** The hue of the Tonal Palette, in HCT. Ranges from 0 to 360. */
var hue: Double,
/** The chroma of the Tonal Palette, in HCT. Ranges from 0 to ~130 (for sRGB gamut). */
var chroma: Double,
/** The key color is the first tone, starting from T50, that matches the palette's chroma. */
var keyColor: Hct
) {
var cache: MutableMap<Int, Int> = HashMap()
/**
* Create an ARGB color with HCT hue and chroma of this Tones instance, and the provided HCT tone.
*
* @param tone HCT tone, measured from 0 to 100.
* @return ARGB representation of a color with that tone.
*/
// AndroidJdkLibsChecker is higher priority than ComputeIfAbsentUseValue (b/119581923)
fun tone(tone: Int): Int {
var color = cache[tone]
if (color == null) {
color = Hct.from(this.hue, this.chroma, tone.toDouble()).toInt()
cache[tone] = color
}
return color
}
fun shade(shade: Int): Int {
return tone(((1000.0 - shade) / 10.0).toInt())
}
/** Given a tone, use hue and chroma of palette to create a color, and return it as HCT. */
fun getHct(tone: Double): Hct {
return Hct.from(this.hue, this.chroma, tone)
}
companion object {
/**
* Create tones using the HCT hue and chroma from a color.
*
* @param argb ARGB representation of a color
* @return Tones matching that color's hue and chroma.
*/
fun fromInt(argb: Int): TonalPalette {
return fromHct(Hct.fromInt(argb))
}
/**
* Create tones using a HCT color.
*
* @param hct HCT representation of a color.
* @return Tones matching that color's hue and chroma.
*/
fun fromHct(hct: Hct): TonalPalette {
return TonalPalette(hct.getHue(), hct.getChroma(), hct)
}
/**
* Create tones from a defined HCT hue and chroma.
*
* @param hue HCT hue
* @param chroma HCT chroma
* @return Tones matching hue and chroma.
*/
fun fromHueAndChroma(hue: Double, chroma: Double): TonalPalette {
return TonalPalette(hue, chroma, createKeyColor(hue, chroma))
}
/** The key color is the first tone, starting from T50, matching the given hue and chroma. */
private fun createKeyColor(hue: Double, chroma: Double): Hct {
val startTone = 50.0
var smallestDeltaHct = Hct.from(hue, chroma, startTone)
var smallestDelta = abs(smallestDeltaHct.getChroma() - chroma)
// Starting from T50, check T+/-delta to see if they match the requested
// chroma.
//
// Starts from T50 because T50 has the most chroma available, on
// average. Thus it is most likely to have a direct answer and minimize
// iteration.
var delta = 1.0
while (delta < 50.0) {
// Termination condition rounding instead of minimizing delta to avoid
// case where requested chroma is 16.51, and the closest chroma is 16.49.
// Error is minimized, but when rounded and displayed, requested chroma
// is 17, key color's chroma is 16.
if (round(chroma) == round(smallestDeltaHct.getChroma())) {
return smallestDeltaHct
}
val hctAdd = Hct.from(hue, chroma, startTone + delta)
val hctAddDelta = abs(hctAdd.getChroma() - chroma)
if (hctAddDelta < smallestDelta) {
smallestDelta = hctAddDelta
smallestDeltaHct = hctAdd
}
val hctSubtract = Hct.from(hue, chroma, startTone - delta)
val hctSubtractDelta = abs(hctSubtract.getChroma() - chroma)
if (hctSubtractDelta < smallestDelta) {
smallestDelta = hctSubtractDelta
smallestDeltaHct = hctSubtract
}
delta += 1.0
}
return smallestDeltaHct
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/quantize/PointProvider.kt | Kotlin | package dev.zwander.compose.libmonet.quantize
/** An interface to allow use of different color spaces by quantizers. */
interface PointProvider {
/** The four components in the color space of an sRGB color. */
fun fromInt(argb: Int): DoubleArray
/** The ARGB (i.e. hex code) representation of this color. */
fun toInt(point: DoubleArray): Int
/**
* Squared distance between two colors. Distance is defined by scientific color spaces and
* referred to as delta E.
*/
fun distance(a: DoubleArray, b: DoubleArray): Double
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/quantize/PointProviderLab.kt | Kotlin | package dev.zwander.compose.libmonet.quantize
import dev.zwander.compose.libmonet.utils.ColorUtils
/**
* Provides conversions needed for K-Means quantization. Converting input to points, and converting
* the final state of the K-Means algorithm to colors.
*/
class PointProviderLab : PointProvider {
/**
* Convert a color represented in ARGB to a 3-element array of L*a*b* coordinates of the color.
*/
override fun fromInt(argb: Int): DoubleArray {
val lab: DoubleArray = ColorUtils.labFromArgb(argb)
return doubleArrayOf(lab[0], lab[1], lab[2])
}
/** Convert a 3-element array to a color represented in ARGB. */
override fun toInt(point: DoubleArray): Int {
return ColorUtils.argbFromLab(point[0], point[1], point[2])
}
/**
* Standard CIE 1976 delta E formula also takes the square root, unneeded here. This method is
* used by quantization algorithms to compare distance, and the relative ordering is the same,
* with or without a square root.
*
*
* This relatively minor optimization is helpful because this method is called at least once
* for each pixel in an image.
*/
override fun distance(one: DoubleArray, two: DoubleArray): Double {
val dL = (one[0] - two[0])
val dA = (one[1] - two[1])
val dB = (one[2] - two[2])
return (dL * dL + dA * dA + dB * dB)
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/quantize/Quantizer.kt | Kotlin | package dev.zwander.compose.libmonet.quantize
internal interface Quantizer {
fun quantize(pixels: IntArray?, maxColors: Int): QuantizerResult
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/quantize/QuantizerCelebi.kt | Kotlin | package dev.zwander.compose.libmonet.quantize
/**
* An image quantizer that improves on the quality of a standard K-Means algorithm by setting the
* K-Means initial state to the output of a Wu quantizer, instead of random centroids. Improves on
* speed by several optimizations, as implemented in Wsmeans, or Weighted Square Means, K-Means with
* those optimizations.
*
*
* This algorithm was designed by M. Emre Celebi, and was found in their 2011 paper, Improving
* the Performance of K-Means for Color Quantization. https://arxiv.org/abs/1101.0395
*/
object QuantizerCelebi {
/**
* Reduce the number of colors needed to represented the input, minimizing the difference between
* the original image and the recolored image.
*
* @param pixels Colors in ARGB format.
* @param maxColors The number of colors to divide the image into. A lower number of colors may be
* returned.
* @return Map with keys of colors in ARGB format, and values of number of pixels in the original
* image that correspond to the color in the quantized image.
*/
fun quantize(pixels: IntArray, maxColors: Int): Map<Int, Int> {
val wu: QuantizerWu = QuantizerWu()
val wuResult: QuantizerResult = wu.quantize(pixels, maxColors)
val wuClustersAsObjects: Set<Int> = wuResult.colorToCount.keys
var index = 0
val wuClusters = IntArray(wuClustersAsObjects.size)
for (argb in wuClustersAsObjects) {
wuClusters[index++] = argb
}
return QuantizerWsmeans.quantize(pixels, wuClusters, maxColors)
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/quantize/QuantizerMap.kt | Kotlin | package dev.zwander.compose.libmonet.quantize
/** Creates a dictionary with keys of colors, and values of count of the color */
class QuantizerMap : Quantizer {
var colorToCount: Map<Int, Int>? = null
override fun quantize(pixels: IntArray?, colorCount: Int): QuantizerResult {
val pixelByCount: MutableMap<Int, Int> = LinkedHashMap()
for (pixel in pixels!!) {
val currentPixelCount = pixelByCount[pixel]
val newPixelCount = if (currentPixelCount == null) 1 else currentPixelCount + 1
pixelByCount[pixel] = newPixelCount
}
colorToCount = pixelByCount
return QuantizerResult(pixelByCount)
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/quantize/QuantizerResult.kt | Kotlin | package dev.zwander.compose.libmonet.quantize
/** Represents result of a quantizer run */
class QuantizerResult internal constructor(val colorToCount: Map<Int, Int>)
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/quantize/QuantizerWsmeans.kt | Kotlin | package dev.zwander.compose.libmonet.quantize
import kotlin.math.abs
import kotlin.math.min
import kotlin.math.sqrt
import kotlin.random.Random
/**
* An image quantizer that improves on the speed of a standard K-Means algorithm by implementing
* several optimizations, including deduping identical pixels and a triangle inequality rule that
* reduces the number of comparisons needed to identify which cluster a point should be moved to.
*
*
* Wsmeans stands for Weighted Square Means.
*
*
* This algorithm was designed by M. Emre Celebi, and was found in their 2011 paper, Improving
* the Performance of K-Means for Color Quantization. https://arxiv.org/abs/1101.0395
*/
object QuantizerWsmeans {
private const val MAX_ITERATIONS = 10
private const val MIN_MOVEMENT_DISTANCE = 3.0
/**
* Reduce the number of colors needed to represented the input, minimizing the difference between
* the original image and the recolored image.
*
* @param inputPixels Colors in ARGB format.
* @param startingClusters Defines the initial state of the quantizer. Passing an empty array is
* fine, the implementation will create its own initial state that leads to reproducible
* results for the same inputs. Passing an array that is the result of Wu quantization leads
* to higher quality results.
* @param maxColors The number of colors to divide the image into. A lower number of colors may be
* returned.
* @return Map with keys of colors in ARGB format, values of how many of the input pixels belong
* to the color.
*/
fun quantize(
inputPixels: IntArray, startingClusters: IntArray, maxColors: Int
): Map<Int, Int> {
// Uses a seeded random number generator to ensure consistent results.
val random = Random(0x42688)
val pixelToCount: MutableMap<Int, Int> = LinkedHashMap<Int, Int>()
val points = arrayOfNulls<DoubleArray>(inputPixels.size)
val pixels = IntArray(inputPixels.size)
val pointProvider: PointProvider = PointProviderLab()
var pointCount = 0
for (i in inputPixels.indices) {
val inputPixel = inputPixels[i]
val pixelCount = pixelToCount[inputPixel]
if (pixelCount == null) {
points[pointCount] = pointProvider.fromInt(inputPixel)
pixels[pointCount] = inputPixel
pointCount++
pixelToCount[inputPixel] = 1
} else {
pixelToCount[inputPixel] = pixelCount + 1
}
}
val counts = IntArray(pointCount)
for (i in 0 until pointCount) {
val pixel = pixels[i]
val count = pixelToCount[pixel]!!
counts[i] = count
}
var clusterCount: Int = min(maxColors, pointCount)
if (startingClusters.isNotEmpty()) {
clusterCount = min(clusterCount, startingClusters.size)
}
val clusters = arrayOfNulls<DoubleArray>(clusterCount)
var clustersCreated = 0
for (i in startingClusters.indices) {
clusters[i] = pointProvider.fromInt(startingClusters[i])
clustersCreated++
}
val additionalClustersNeeded = clusterCount - clustersCreated
if (additionalClustersNeeded > 0) {
for (i in 0 until additionalClustersNeeded) {}
}
val clusterIndices = IntArray(pointCount)
for (i in 0 until pointCount) {
clusterIndices[i] = random.nextInt(clusterCount)
}
val indexMatrix = arrayOfNulls<IntArray>(clusterCount)
for (i in 0 until clusterCount) {
indexMatrix[i] = IntArray(clusterCount)
}
val distanceToIndexMatrix: Array<Array<Distance?>?> = arrayOfNulls(clusterCount)
for (i in 0 until clusterCount) {
distanceToIndexMatrix[i] = arrayOfNulls(clusterCount)
for (j in 0 until clusterCount) {
distanceToIndexMatrix[i]!![j] = Distance()
}
}
val pixelCountSums = IntArray(clusterCount)
for (iteration in 0 until MAX_ITERATIONS) {
for (i in 0 until clusterCount) {
for (j in i + 1 until clusterCount) {
val distance = pointProvider.distance(clusters[i]!!, clusters[j]!!)
distanceToIndexMatrix[j]!![i]!!.distance = distance
distanceToIndexMatrix[j]!![i]!!.index = i
distanceToIndexMatrix[i]!![j]!!.distance = distance
distanceToIndexMatrix[i]!![j]!!.index = j
}
distanceToIndexMatrix[i] = distanceToIndexMatrix[i]?.filterNotNull()?.sorted()?.toTypedArray()
for (j in 0 until clusterCount) {
indexMatrix[i]!![j] = distanceToIndexMatrix[i]!![j]!!.index
}
}
var pointsMoved = 0
for (i in 0 until pointCount) {
val point = points[i]!!
val previousClusterIndex = clusterIndices[i]
val previousCluster = clusters[previousClusterIndex]!!
val previousDistance = pointProvider.distance(point, previousCluster)
var minimumDistance = previousDistance
var newClusterIndex = -1
for (j in 0 until clusterCount) {
if (distanceToIndexMatrix[previousClusterIndex]!![j]!!.distance >= 4 * previousDistance) {
continue
}
val distance = pointProvider.distance(point, clusters[j]!!)
if (distance < minimumDistance) {
minimumDistance = distance
newClusterIndex = j
}
}
if (newClusterIndex != -1) {
val distanceChange = abs(sqrt(minimumDistance) - sqrt(previousDistance))
if (distanceChange > MIN_MOVEMENT_DISTANCE) {
pointsMoved++
clusterIndices[i] = newClusterIndex
}
}
}
if (pointsMoved == 0 && iteration != 0) {
break
}
val componentASums = DoubleArray(clusterCount)
val componentBSums = DoubleArray(clusterCount)
val componentCSums = DoubleArray(clusterCount)
pixelCountSums.fill(0)
for (i in 0 until pointCount) {
val clusterIndex = clusterIndices[i]
val point = points[i]
val count = counts[i]
pixelCountSums[clusterIndex] += count
componentASums[clusterIndex] += (point!![0] * count)
componentBSums[clusterIndex] += (point[1] * count)
componentCSums[clusterIndex] += (point[2] * count)
}
for (i in 0 until clusterCount) {
val count = pixelCountSums[i]
if (count == 0) {
clusters[i] = doubleArrayOf(0.0, 0.0, 0.0)
continue
}
val a = componentASums[i] / count
val b = componentBSums[i] / count
val c = componentCSums[i] / count
clusters[i]!![0] = a
clusters[i]!![1] = b
clusters[i]!![2] = c
}
}
val argbToPopulation: MutableMap<Int, Int> = LinkedHashMap()
for (i in 0 until clusterCount) {
val count = pixelCountSums[i]
if (count == 0) {
continue
}
val possibleNewCluster = pointProvider.toInt(clusters[i]!!)
if (argbToPopulation.containsKey(possibleNewCluster)) {
continue
}
argbToPopulation[possibleNewCluster] = count
}
return argbToPopulation
}
private class Distance : Comparable<Distance> {
var index: Int = -1
var distance: Double = -1.0
override fun compareTo(other: Distance): Int {
return distance.compareTo(other.distance)
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/quantize/QuantizerWu.kt | Kotlin | package dev.zwander.compose.libmonet.quantize
import dev.zwander.compose.libmonet.utils.ColorUtils
/**
* An image quantizer that divides the image's pixels into clusters by recursively cutting an RGB
* cube, based on the weight of pixels in each area of the cube.
*
*
* The algorithm was described by Xiaolin Wu in Graphic Gems II, published in 1991.
*/
class QuantizerWu : Quantizer {
lateinit var weights: IntArray
lateinit var momentsR: IntArray
lateinit var momentsG: IntArray
lateinit var momentsB: IntArray
lateinit var moments: DoubleArray
lateinit var cubes: Array<Box?>
override fun quantize(pixels: IntArray?, maxColors: Int): QuantizerResult {
val mapResult = QuantizerMap().quantize(pixels, maxColors)
constructHistogram(mapResult.colorToCount)
createMoments()
val createBoxesResult = createBoxes(maxColors)
val colors = createResult(createBoxesResult.resultCount)
val resultMap: MutableMap<Int, Int> = LinkedHashMap()
for (color in colors) {
resultMap[color] = 0
}
return QuantizerResult(resultMap)
}
fun constructHistogram(pixels: Map<Int, Int>) {
weights = IntArray(TOTAL_SIZE)
momentsR = IntArray(TOTAL_SIZE)
momentsG = IntArray(TOTAL_SIZE)
momentsB = IntArray(TOTAL_SIZE)
moments = DoubleArray(TOTAL_SIZE)
for ((pixel, count) in pixels) {
val red: Int = ColorUtils.redFromArgb(pixel)
val green: Int = ColorUtils.greenFromArgb(pixel)
val blue: Int = ColorUtils.blueFromArgb(pixel)
val bitsToRemove = 8 - INDEX_BITS
val iR = (red shr bitsToRemove) + 1
val iG = (green shr bitsToRemove) + 1
val iB = (blue shr bitsToRemove) + 1
val index = getIndex(iR, iG, iB)
weights[index] += count
momentsR[index] += (red * count)
momentsG[index] += (green * count)
momentsB[index] += (blue * count)
moments[index] += (count * ((red * red) + (green * green) + (blue * blue))).toDouble()
}
}
fun createMoments() {
for (r in 1 until INDEX_COUNT) {
val area = IntArray(INDEX_COUNT)
val areaR = IntArray(INDEX_COUNT)
val areaG = IntArray(INDEX_COUNT)
val areaB = IntArray(INDEX_COUNT)
val area2 = DoubleArray(INDEX_COUNT)
for (g in 1 until INDEX_COUNT) {
var line = 0
var lineR = 0
var lineG = 0
var lineB = 0
var line2 = 0.0
for (b in 1 until INDEX_COUNT) {
val index = getIndex(r, g, b)
line += weights[index]
lineR += momentsR[index]
lineG += momentsG[index]
lineB += momentsB[index]
line2 += moments[index]
area[b] += line
areaR[b] += lineR
areaG[b] += lineG
areaB[b] += lineB
area2[b] += line2
val previousIndex = getIndex(r - 1, g, b)
weights[index] = weights[previousIndex] + area[b]
momentsR[index] = momentsR[previousIndex] + areaR[b]
momentsG[index] = momentsG[previousIndex] + areaG[b]
momentsB[index] = momentsB[previousIndex] + areaB[b]
moments[index] = moments[previousIndex] + area2[b]
}
}
}
}
fun createBoxes(maxColorCount: Int): CreateBoxesResult {
cubes = arrayOfNulls(maxColorCount)
for (i in 0 until maxColorCount) {
cubes[i] = Box()
}
val volumeVariance = DoubleArray(maxColorCount)
val firstBox = cubes[0]
firstBox!!.r1 = INDEX_COUNT - 1
firstBox.g1 = INDEX_COUNT - 1
firstBox.b1 = INDEX_COUNT - 1
var generatedColorCount = maxColorCount
var next = 0
var i = 1
while (i < maxColorCount) {
if (cut(cubes[next], cubes[i])) {
volumeVariance[next] = if ((cubes[next]!!.vol > 1)) variance(cubes[next]) else 0.0
volumeVariance[i] = if ((cubes[i]!!.vol > 1)) variance(cubes[i]) else 0.0
} else {
volumeVariance[next] = 0.0
i--
}
next = 0
var temp = volumeVariance[0]
for (j in 1..i) {
if (volumeVariance[j] > temp) {
temp = volumeVariance[j]
next = j
}
}
if (temp <= 0.0) {
generatedColorCount = i + 1
break
}
i++
}
return CreateBoxesResult(maxColorCount, generatedColorCount)
}
fun createResult(colorCount: Int): List<Int> {
val colors: MutableList<Int> = ArrayList()
for (i in 0 until colorCount) {
val cube = cubes[i]
val weight = volume(cube, weights)
if (weight > 0) {
val r = volume(cube, momentsR) / weight
val g = volume(cube, momentsG) / weight
val b = volume(cube, momentsB) / weight
val color =
(255 shl 24) or ((r and 0x0ff) shl 16) or ((g and 0x0ff) shl 8) or (b and 0x0ff)
colors.add(color)
}
}
return colors
}
fun variance(cube: Box?): Double {
val dr = volume(cube, momentsR)
val dg = volume(cube, momentsG)
val db = volume(cube, momentsB)
val xx =
((((moments[getIndex(cube!!.r1, cube.g1, cube.b1)]
- moments[getIndex(cube.r1, cube.g1, cube.b0)]
- moments[getIndex(cube.r1, cube.g0, cube.b1)])
+ moments[getIndex(cube.r1, cube.g0, cube.b0)]
- moments[getIndex(cube.r0, cube.g1, cube.b1)]
) + moments[getIndex(cube.r0, cube.g1, cube.b0)]
+ moments[getIndex(cube.r0, cube.g0, cube.b1)])
- moments[getIndex(cube.r0, cube.g0, cube.b0)])
val hypotenuse = dr * dr + dg * dg + db * db
val volume = volume(cube, weights)
return xx - hypotenuse / (volume.toDouble())
}
fun cut(one: Box?, two: Box?): Boolean {
val wholeR = volume(one, momentsR)
val wholeG = volume(one, momentsG)
val wholeB = volume(one, momentsB)
val wholeW = volume(one, weights)
val maxRResult =
maximize(one, Direction.RED, one!!.r0 + 1, one.r1, wholeR, wholeG, wholeB, wholeW)
val maxGResult =
maximize(one, Direction.GREEN, one.g0 + 1, one.g1, wholeR, wholeG, wholeB, wholeW)
val maxBResult =
maximize(one, Direction.BLUE, one.b0 + 1, one.b1, wholeR, wholeG, wholeB, wholeW)
val cutDirection: Direction
val maxR = maxRResult.maximum
val maxG = maxGResult.maximum
val maxB = maxBResult.maximum
if (maxR >= maxG && maxR >= maxB) {
if (maxRResult.cutLocation < 0) {
return false
}
cutDirection = Direction.RED
} else if (maxG >= maxR && maxG >= maxB) {
cutDirection = Direction.GREEN
} else {
cutDirection = Direction.BLUE
}
two!!.r1 = one.r1
two.g1 = one.g1
two.b1 = one.b1
when (cutDirection) {
Direction.RED -> {
one.r1 = maxRResult.cutLocation
two.r0 = one.r1
two.g0 = one.g0
two.b0 = one.b0
}
Direction.GREEN -> {
one.g1 = maxGResult.cutLocation
two.r0 = one.r0
two.g0 = one.g1
two.b0 = one.b0
}
Direction.BLUE -> {
one.b1 = maxBResult.cutLocation
two.r0 = one.r0
two.g0 = one.g0
two.b0 = one.b1
}
}
one.vol = (one.r1 - one.r0) * (one.g1 - one.g0) * (one.b1 - one.b0)
two.vol = (two.r1 - two.r0) * (two.g1 - two.g0) * (two.b1 - two.b0)
return true
}
fun maximize(
cube: Box?,
direction: Direction,
first: Int,
last: Int,
wholeR: Int,
wholeG: Int,
wholeB: Int,
wholeW: Int
): MaximizeResult {
val bottomR = bottom(cube, direction, momentsR)
val bottomG = bottom(cube, direction, momentsG)
val bottomB = bottom(cube, direction, momentsB)
val bottomW = bottom(cube, direction, weights)
var max = 0.0
var cut = -1
var halfR: Int
var halfG: Int
var halfB: Int
var halfW: Int
for (i in first until last) {
halfR = bottomR + top(cube, direction, i, momentsR)
halfG = bottomG + top(cube, direction, i, momentsG)
halfB = bottomB + top(cube, direction, i, momentsB)
halfW = bottomW + top(cube, direction, i, weights)
if (halfW == 0) {
continue
}
var tempNumerator = (halfR * halfR + halfG * halfG + halfB * halfB).toDouble()
var tempDenominator = halfW.toDouble()
var temp = tempNumerator / tempDenominator
halfR = wholeR - halfR
halfG = wholeG - halfG
halfB = wholeB - halfB
halfW = wholeW - halfW
if (halfW == 0) {
continue
}
tempNumerator = (halfR * halfR + halfG * halfG + halfB * halfB).toDouble()
tempDenominator = halfW.toDouble()
temp += (tempNumerator / tempDenominator)
if (temp > max) {
max = temp
cut = i
}
}
return MaximizeResult(cut, max)
}
enum class Direction {
RED,
GREEN,
BLUE
}
class MaximizeResult(// < 0 if cut impossible
var cutLocation: Int, var maximum: Double
)
class CreateBoxesResult(var requestedCount: Int, var resultCount: Int)
class Box {
var r0: Int = 0
var r1: Int = 0
var g0: Int = 0
var g1: Int = 0
var b0: Int = 0
var b1: Int = 0
var vol: Int = 0
}
companion object {
// A histogram of all the input colors is constructed. It has the shape of a
// cube. The cube would be too large if it contained all 16 million colors:
// historical best practice is to use 5 bits of the 8 in each channel,
// reducing the histogram to a volume of ~32,000.
private const val INDEX_BITS = 5
private const val INDEX_COUNT = 33 // ((1 << INDEX_BITS) + 1)
private const val TOTAL_SIZE = 35937 // INDEX_COUNT * INDEX_COUNT * INDEX_COUNT
fun getIndex(r: Int, g: Int, b: Int): Int {
return (r shl (INDEX_BITS * 2)) + (r shl (INDEX_BITS + 1)) + r + (g shl INDEX_BITS) + g + b
}
fun volume(cube: Box?, moment: IntArray): Int {
return ((((moment[getIndex(cube!!.r1, cube.g1, cube.b1)]
- moment[getIndex(cube.r1, cube.g1, cube.b0)]
- moment[getIndex(cube.r1, cube.g0, cube.b1)])
+ moment[getIndex(cube.r1, cube.g0, cube.b0)]
- moment[getIndex(cube.r0, cube.g1, cube.b1)]
) + moment[getIndex(cube.r0, cube.g1, cube.b0)]
+ moment[getIndex(cube.r0, cube.g0, cube.b1)])
- moment[getIndex(cube.r0, cube.g0, cube.b0)])
}
fun bottom(cube: Box?, direction: Direction, moment: IntArray): Int {
return when (direction) {
Direction.RED -> ((-moment[getIndex(
cube!!.r0, cube.g1, cube.b1
)]
+ moment[getIndex(cube.r0, cube.g1, cube.b0)]
+ moment[getIndex(cube.r0, cube.g0, cube.b1)])
- moment[getIndex(cube.r0, cube.g0, cube.b0)])
Direction.GREEN -> ((-moment[getIndex(
cube!!.r1, cube.g0, cube.b1
)]
+ moment[getIndex(cube.r1, cube.g0, cube.b0)]
+ moment[getIndex(cube.r0, cube.g0, cube.b1)])
- moment[getIndex(cube.r0, cube.g0, cube.b0)])
Direction.BLUE -> ((-moment[getIndex(
cube!!.r1, cube.g1, cube.b0
)]
+ moment[getIndex(cube.r1, cube.g0, cube.b0)]
+ moment[getIndex(cube.r0, cube.g1, cube.b0)])
- moment[getIndex(cube.r0, cube.g0, cube.b0)])
}
}
fun top(cube: Box?, direction: Direction, position: Int, moment: IntArray): Int {
return when (direction) {
Direction.RED -> ((moment[getIndex(position, cube!!.g1, cube.b1)]
- moment[getIndex(position, cube.g1, cube.b0)]
- moment[getIndex(position, cube.g0, cube.b1)])
+ moment[getIndex(position, cube.g0, cube.b0)])
Direction.GREEN -> ((moment[getIndex(
cube!!.r1, position, cube.b1
)]
- moment[getIndex(cube.r1, position, cube.b0)]
- moment[getIndex(cube.r0, position, cube.b1)])
+ moment[getIndex(cube.r0, position, cube.b0)])
Direction.BLUE -> ((moment[getIndex(
cube!!.r1, cube.g1, position
)]
- moment[getIndex(cube.r1, cube.g0, position)]
- moment[getIndex(cube.r0, cube.g1, position)])
+ moment[getIndex(cube.r0, cube.g0, position)])
}
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/scheme/ColorScheme.kt | Kotlin | package dev.zwander.compose.libmonet.scheme
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.utils.toComposeColorScheme
enum class Style {
SPRITZ,
TONAL_SPOT,
VIBRANT,
EXPRESSIVE,
RAINBOW,
FRUIT_SALAD,
CONTENT,
MONOCHROMATIC,
FIDELITY,
}
class ColorScheme(
val seedColor: Int,
val isDark: Boolean,
val style: Style = Style.TONAL_SPOT,
// -1 to 1
val contrast: Double = 0.0,
) {
val sourceColorHct = Hct.fromInt(seedColor)
val scheme = when (style) {
Style.SPRITZ -> SchemeNeutral(sourceColorHct, isDark, contrast)
Style.TONAL_SPOT -> SchemeTonalSpot(sourceColorHct, isDark, contrast)
Style.VIBRANT -> SchemeVibrant(sourceColorHct, isDark, contrast)
Style.EXPRESSIVE -> SchemeExpressive(sourceColorHct, isDark, contrast)
Style.RAINBOW -> SchemeRainbow(sourceColorHct, isDark, contrast)
Style.FRUIT_SALAD -> SchemeFruitSalad(sourceColorHct, isDark, contrast)
Style.CONTENT -> SchemeContent(sourceColorHct, isDark, contrast)
Style.MONOCHROMATIC -> SchemeMonochrome(sourceColorHct, isDark, contrast)
Style.FIDELITY -> SchemeFidelity(sourceColorHct, isDark, contrast)
}
fun toComposeColorScheme() = scheme.toComposeColorScheme()
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/scheme/SchemeContent.kt | Kotlin | package dev.zwander.compose.libmonet.scheme
import dev.zwander.compose.libmonet.dislike.DislikeAnalyzer.fixIfDisliked
import dev.zwander.compose.libmonet.dynamiccolor.DynamicScheme
import dev.zwander.compose.libmonet.dynamiccolor.Variant
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
import dev.zwander.compose.libmonet.temperature.TemperatureCache
import kotlin.math.max
/**
* A scheme that places the source color in Scheme.primaryContainer.
*
*
* Primary Container is the source color, adjusted for color relativity. It maintains constant
* appearance in light mode and dark mode. This adds ~5 tone in light mode, and subtracts ~5 tone in
* dark mode.
*
*
* Tertiary Container is an analogous color, specifically, the analog of a color wheel divided
* into 6, and the precise analog is the one found by increasing hue. This is a scientifically
* grounded equivalent to rotating hue clockwise by 60 degrees. It also maintains constant
* appearance.
*/
class SchemeContent(sourceColorHct: Hct, isDark: Boolean, contrastLevel: Double) :
DynamicScheme(
sourceColorHct,
Variant.CONTENT,
isDark,
contrastLevel,
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), sourceColorHct.getChroma()),
TonalPalette.fromHueAndChroma(
sourceColorHct.getHue(),
max(sourceColorHct.getChroma() - 32.0, sourceColorHct.getChroma() * 0.5)
),
TonalPalette.fromHct(
fixIfDisliked(
TemperatureCache(sourceColorHct)
.getAnalogousColors( /* count= */3, /* divisions= */6)[2]
)
),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), sourceColorHct.getChroma() / 8.0),
TonalPalette.fromHueAndChroma(
sourceColorHct.getHue(), (sourceColorHct.getChroma() / 8.0) + 4.0
)
)
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/scheme/SchemeExpressive.kt | Kotlin | package dev.zwander.compose.libmonet.scheme
import dev.zwander.compose.libmonet.dynamiccolor.DynamicScheme
import dev.zwander.compose.libmonet.dynamiccolor.Variant
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
import dev.zwander.compose.libmonet.utils.MathUtils.sanitizeDegreesDouble
/** A playful theme - the source color's hue does not appear in the theme. */
class SchemeExpressive(sourceColorHct: Hct, isDark: Boolean, contrastLevel: Double) :
DynamicScheme(
sourceColorHct,
Variant.EXPRESSIVE,
isDark,
contrastLevel,
TonalPalette.fromHueAndChroma(
sanitizeDegreesDouble(sourceColorHct.getHue() + 240.0), 40.0
),
TonalPalette.fromHueAndChroma(
getRotatedHue(sourceColorHct, HUES, SECONDARY_ROTATIONS), 24.0
),
TonalPalette.fromHueAndChroma(
getRotatedHue(sourceColorHct, HUES, TERTIARY_ROTATIONS), 32.0
),
TonalPalette.fromHueAndChroma(
sanitizeDegreesDouble(sourceColorHct.getHue() + 15.0), 8.0
),
TonalPalette.fromHueAndChroma(
sanitizeDegreesDouble(sourceColorHct.getHue() + 15.0), 12.0
)
) {
companion object {
// NOMUTANTS--arbitrary increments/decrements, correctly, still passes tests.
private val HUES = doubleArrayOf(0.0, 21.0, 51.0, 121.0, 151.0, 191.0, 271.0, 321.0, 360.0)
private val SECONDARY_ROTATIONS =
doubleArrayOf(45.0, 95.0, 45.0, 20.0, 45.0, 90.0, 45.0, 45.0, 45.0)
private val TERTIARY_ROTATIONS =
doubleArrayOf(120.0, 120.0, 20.0, 45.0, 20.0, 15.0, 20.0, 120.0, 120.0)
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/scheme/SchemeFidelity.kt | Kotlin | package dev.zwander.compose.libmonet.scheme
import dev.zwander.compose.libmonet.dislike.DislikeAnalyzer.fixIfDisliked
import dev.zwander.compose.libmonet.dynamiccolor.DynamicScheme
import dev.zwander.compose.libmonet.dynamiccolor.Variant
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
import dev.zwander.compose.libmonet.temperature.TemperatureCache
import kotlin.math.max
/**
* A scheme that places the source color in Scheme.primaryContainer.
*
*
* Primary Container is the source color, adjusted for color relativity. It maintains constant
* appearance in light mode and dark mode. This adds ~5 tone in light mode, and subtracts ~5 tone in
* dark mode.
*
*
* Tertiary Container is the complement to the source color, using TemperatureCache. It also
* maintains constant appearance.
*/
class SchemeFidelity(sourceColorHct: Hct, isDark: Boolean, contrastLevel: Double) :
DynamicScheme(
sourceColorHct,
Variant.FIDELITY,
isDark,
contrastLevel,
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), sourceColorHct.getChroma()),
TonalPalette.fromHueAndChroma(
sourceColorHct.getHue(),
max(sourceColorHct.getChroma() - 32.0, sourceColorHct.getChroma() * 0.5)
),
TonalPalette.fromHct(
fixIfDisliked(TemperatureCache(sourceColorHct).complement)
),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), sourceColorHct.getChroma() / 8.0),
TonalPalette.fromHueAndChroma(
sourceColorHct.getHue(), (sourceColorHct.getChroma() / 8.0) + 4.0
)
)
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/scheme/SchemeFruitSalad.kt | Kotlin | package dev.zwander.compose.libmonet.scheme
import dev.zwander.compose.libmonet.dynamiccolor.DynamicScheme
import dev.zwander.compose.libmonet.dynamiccolor.Variant
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
import dev.zwander.compose.libmonet.utils.MathUtils.sanitizeDegreesDouble
/** A playful theme - the source color's hue does not appear in the theme. */
class SchemeFruitSalad(sourceColorHct: Hct, isDark: Boolean, contrastLevel: Double) :
DynamicScheme(
sourceColorHct,
Variant.FRUIT_SALAD,
isDark,
contrastLevel,
TonalPalette.fromHueAndChroma(
sanitizeDegreesDouble(sourceColorHct.getHue() - 50.0), 48.0
),
TonalPalette.fromHueAndChroma(
sanitizeDegreesDouble(sourceColorHct.getHue() - 50.0), 36.0
),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 36.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 10.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 16.0)
) | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/scheme/SchemeMonochrome.kt | Kotlin | package dev.zwander.compose.libmonet.scheme
import dev.zwander.compose.libmonet.dynamiccolor.DynamicScheme
import dev.zwander.compose.libmonet.dynamiccolor.Variant
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
/** A monochrome theme, colors are purely black / white / gray. */
class SchemeMonochrome(sourceColorHct: Hct, isDark: Boolean, contrastLevel: Double) :
DynamicScheme(
sourceColorHct,
Variant.MONOCHROME,
isDark,
contrastLevel,
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 0.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 0.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 0.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 0.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 0.0)
)
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/scheme/SchemeNeutral.kt | Kotlin | package dev.zwander.compose.libmonet.scheme
import dev.zwander.compose.libmonet.dynamiccolor.DynamicScheme
import dev.zwander.compose.libmonet.dynamiccolor.Variant
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
/** A theme that's slightly more chromatic than monochrome, which is purely black / white / gray. */
class SchemeNeutral(sourceColorHct: Hct, isDark: Boolean, contrastLevel: Double) :
DynamicScheme(
sourceColorHct,
Variant.NEUTRAL,
isDark,
contrastLevel,
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 12.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 8.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 16.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 2.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 2.0)
)
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/scheme/SchemeRainbow.kt | Kotlin | package dev.zwander.compose.libmonet.scheme
import dev.zwander.compose.libmonet.dynamiccolor.DynamicScheme
import dev.zwander.compose.libmonet.dynamiccolor.Variant
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
import dev.zwander.compose.libmonet.utils.MathUtils.sanitizeDegreesDouble
/** A playful theme - the source color's hue does not appear in the theme. */
class SchemeRainbow(sourceColorHct: Hct, isDark: Boolean, contrastLevel: Double) :
DynamicScheme(
sourceColorHct,
Variant.RAINBOW,
isDark,
contrastLevel,
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 48.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 16.0),
TonalPalette.fromHueAndChroma(
sanitizeDegreesDouble(sourceColorHct.getHue() + 60.0), 24.0
),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 0.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 0.0)
) | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/scheme/SchemeTonalSpot.kt | Kotlin | package dev.zwander.compose.libmonet.scheme
import dev.zwander.compose.libmonet.dynamiccolor.DynamicScheme
import dev.zwander.compose.libmonet.dynamiccolor.Variant
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
import dev.zwander.compose.libmonet.utils.MathUtils.sanitizeDegreesDouble
/** A calm theme, sedated colors that aren't particularly chromatic. */
class SchemeTonalSpot(sourceColorHct: Hct, isDark: Boolean, contrastLevel: Double) :
DynamicScheme(
sourceColorHct,
Variant.TONAL_SPOT,
isDark,
contrastLevel,
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 36.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 16.0),
TonalPalette.fromHueAndChroma(
sanitizeDegreesDouble(sourceColorHct.getHue() + 60.0), 24.0
),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 6.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 8.0)
)
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/scheme/SchemeVibrant.kt | Kotlin | package dev.zwander.compose.libmonet.scheme
import dev.zwander.compose.libmonet.dynamiccolor.DynamicScheme
import dev.zwander.compose.libmonet.dynamiccolor.Variant
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.palettes.TonalPalette
/** A loud theme, colorfulness is maximum for Primary palette, increased for others. */
class SchemeVibrant(sourceColorHct: Hct, isDark: Boolean, contrastLevel: Double) :
DynamicScheme(
sourceColorHct,
Variant.VIBRANT,
isDark,
contrastLevel,
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 200.0),
TonalPalette.fromHueAndChroma(
getRotatedHue(sourceColorHct, HUES, SECONDARY_ROTATIONS), 24.0
),
TonalPalette.fromHueAndChroma(
getRotatedHue(sourceColorHct, HUES, TERTIARY_ROTATIONS), 32.0
),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 10.0),
TonalPalette.fromHueAndChroma(sourceColorHct.getHue(), 12.0)
) {
companion object {
private val HUES = doubleArrayOf(0.0, 41.0, 61.0, 101.0, 131.0, 181.0, 251.0, 301.0, 360.0)
private val SECONDARY_ROTATIONS =
doubleArrayOf(18.0, 15.0, 10.0, 12.0, 15.0, 18.0, 15.0, 12.0, 12.0)
private val TERTIARY_ROTATIONS =
doubleArrayOf(35.0, 30.0, 20.0, 25.0, 30.0, 35.0, 30.0, 25.0, 25.0)
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/score/Score.kt | Kotlin | package dev.zwander.compose.libmonet.score
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.utils.MathUtils.differenceDegrees
import dev.zwander.compose.libmonet.utils.MathUtils.sanitizeDegreesInt
import kotlin.jvm.JvmOverloads
import kotlin.math.floor
import kotlin.math.round
/**
* Given a large set of colors, remove colors that are unsuitable for a UI theme, and rank the rest
* based on suitability.
*
*
* Enables use of a high cluster count for image quantization, thus ensuring colors aren't
* muddied, while curating the high cluster count to a much smaller number of appropriate choices.
*/
object Score {
private const val TARGET_CHROMA = 48.0 // A1 Chroma
private const val WEIGHT_PROPORTION = 0.7
private const val WEIGHT_CHROMA_ABOVE = 0.3
private const val WEIGHT_CHROMA_BELOW = 0.1
private const val CUTOFF_CHROMA = 5.0
private const val CUTOFF_EXCITED_PROPORTION = 0.01
/**
* Given a map with keys of colors and values of how often the color appears, rank the colors
* based on suitability for being used for a UI theme.
*
* @param colorsToPopulation map with keys of colors and values of how often the color appears,
* usually from a source image.
* @param desired max count of colors to be returned in the list.
* @param fallbackColorArgb color to be returned if no other options available.
* @param filter whether to filter out undesireable combinations.
* @return Colors sorted by suitability for a UI theme. The most suitable color is the first item,
* the least suitable is the last. There will always be at least one color returned. If all
* the input colors were not suitable for a theme, a default fallback color will be provided,
* Google Blue.
*/
@JvmOverloads
fun score(
colorsToPopulation: Map<Int?, Int>,
desired: Int = 4,
fallbackColorArgb: Int = -0xbd7a0c,
filter: Boolean = true
): List<Int> {
// Get the HCT color for each Argb value, while finding the per hue count and
// total count.
val colorsHct: MutableList<Hct> = ArrayList()
val huePopulation = IntArray(360)
var populationSum = 0.0
for ((key, value) in colorsToPopulation) {
val hct = Hct.fromInt(key!!)
colorsHct.add(hct)
val hue = floor(hct.getHue()).toInt()
huePopulation[hue] += value
populationSum += value.toDouble()
}
// Hues with more usage in neighboring 30 degree slice get a larger number.
val hueExcitedProportions = DoubleArray(360)
for (hue in 0..359) {
val proportion = huePopulation[hue] / populationSum
for (i in hue - 14 until hue + 16) {
val neighborHue: Int = sanitizeDegreesInt(i)
hueExcitedProportions[neighborHue] += proportion
}
}
// Scores each HCT color based on usage and chroma, while optionally
// filtering out values that do not have enough chroma or usage.
val scoredHcts: MutableList<ScoredHCT> = ArrayList()
for (hct in colorsHct) {
val hue: Int = sanitizeDegreesInt(round(hct.getHue()).toInt())
val proportion = hueExcitedProportions[hue]
if (filter && (hct.getChroma() < CUTOFF_CHROMA || proportion <= CUTOFF_EXCITED_PROPORTION)) {
continue
}
val proportionScore = proportion * 100.0 * WEIGHT_PROPORTION
val chromaWeight =
if (hct.getChroma() < TARGET_CHROMA) WEIGHT_CHROMA_BELOW else WEIGHT_CHROMA_ABOVE
val chromaScore = (hct.getChroma() - TARGET_CHROMA) * chromaWeight
val score = proportionScore + chromaScore
scoredHcts.add(ScoredHCT(hct, score))
}
// Sorted so that colors with higher scores come first.
scoredHcts.sortWith(ScoredComparator())
// Iterates through potential hue differences in degrees in order to select
// the colors with the largest distribution of hues possible. Starting at
// 90 degrees(maximum difference for 4 colors) then decreasing down to a
// 15 degree minimum.
val chosenColors: MutableList<Hct> = ArrayList<Hct>()
for (differenceDegrees in 90 downTo 15) {
chosenColors.clear()
for (entry in scoredHcts) {
val hct = entry.hct
var hasDuplicateHue = false
for (chosenHct in chosenColors) {
if (differenceDegrees(
hct.getHue(),
chosenHct.getHue()
) < differenceDegrees
) {
hasDuplicateHue = true
break
}
}
if (!hasDuplicateHue) {
chosenColors.add(hct)
}
if (chosenColors.size >= desired) {
break
}
}
if (chosenColors.size >= desired) {
break
}
}
val colors: MutableList<Int> = ArrayList<Int>()
if (chosenColors.isEmpty()) {
colors.add(fallbackColorArgb)
}
for (chosenHct in chosenColors) {
colors.add(chosenHct.toInt())
}
return colors
}
private class ScoredHCT(val hct: Hct, val score: Double)
private class ScoredComparator : Comparator<ScoredHCT> {
override fun compare(a: ScoredHCT, b: ScoredHCT): Int {
return b.score.compareTo(a.score)
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/temperature/TemperatureCache.kt | Kotlin | package dev.zwander.compose.libmonet.temperature
import dev.zwander.compose.libmonet.hct.Hct
import dev.zwander.compose.libmonet.utils.ColorUtils
import dev.zwander.compose.libmonet.utils.MathUtils.sanitizeDegreesDouble
import dev.zwander.compose.libmonet.utils.MathUtils.sanitizeDegreesInt
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.floor
import kotlin.math.hypot
import kotlin.math.pow
import kotlin.math.round
/**
* Design utilities using color temperature theory.
*
*
* Analogous colors, complementary color, and cache to efficiently, lazily, generate data for
* calculations when needed.
*/
class TemperatureCache
/**
* Create a cache that allows calculation of ex. complementary and analogous colors.
*
* @param input Color to find complement/analogous colors of. Any colors will have the same tone,
* and chroma as the input color, modulo any restrictions due to the other hues having lower
* limits on chroma.
*/(private val input: Hct) {
private var precomputedComplement: Hct? = null
private var precomputedHctsByTemp: List<Hct>? = null
private var precomputedHctsByHue: List<Hct>? = null
private var precomputedTempsByHct: Map<Hct, Double>? = null
val complement: Hct
/**
* A color that complements the input color aesthetically.
*
*
* In art, this is usually described as being across the color wheel. History of this shows
* intent as a color that is just as cool-warm as the input color is warm-cool.
*/
get() {
if (precomputedComplement != null) {
return precomputedComplement!!
}
val coldestHue = coldest.getHue()
val coldestTemp = tempsByHct!![coldest]!!
val warmestHue = warmest.getHue()
val warmestTemp = tempsByHct!![warmest]!!
val range = warmestTemp - coldestTemp
val startHueIsColdestToWarmest = isBetween(input.getHue(), coldestHue, warmestHue)
val startHue = if (startHueIsColdestToWarmest) warmestHue else coldestHue
val endHue = if (startHueIsColdestToWarmest) coldestHue else warmestHue
val directionOfRotation = 1.0
var smallestError = 1000.0
var answer: Hct? = hctsByHue[round(input.getHue()).toInt()]
val complementRelativeTemp = (1.0 - getRelativeTemperature(input))
// Find the color in the other section, closest to the inverse percentile
// of the input color. This is the complement.
var hueAddend = 0.0
while (hueAddend <= 360.0) {
val hue: Double = sanitizeDegreesDouble(
startHue + directionOfRotation * hueAddend
)
if (!isBetween(hue, startHue, endHue)) {
hueAddend += 1.0
continue
}
val possibleAnswer = hctsByHue[round(hue).toInt()]
val relativeTemp =
(tempsByHct!![possibleAnswer]!! - coldestTemp) / range
val error = abs(complementRelativeTemp - relativeTemp)
if (error < smallestError) {
smallestError = error
answer = possibleAnswer
}
hueAddend += 1.0
}
precomputedComplement = answer
return precomputedComplement!!
}
val analogousColors: List<Hct>
/**
* 5 colors that pair well with the input color.
*
*
* The colors are equidistant in temperature and adjacent in hue.
*/
get() = getAnalogousColors(5, 12)
/**
* A set of colors with differing hues, equidistant in temperature.
*
*
* In art, this is usually described as a set of 5 colors on a color wheel divided into 12
* sections. This method allows provision of either of those values.
*
*
* Behavior is undefined when count or divisions is 0. When divisions < count, colors repeat.
*
* @param count The number of colors to return, includes the input color.
* @param divisions The number of divisions on the color wheel.
*/
fun getAnalogousColors(count: Int, divisions: Int): List<Hct> {
// The starting hue is the hue of the input color.
val startHue: Int = round(input.getHue()).toInt()
val startHct = hctsByHue[startHue]
var lastTemp = getRelativeTemperature(startHct)
val allColors: MutableList<Hct> = ArrayList()
allColors.add(startHct)
var absoluteTotalTempDelta = 0.0
for (i in 0..359) {
val hue: Int = sanitizeDegreesInt(startHue + i)
val hct = hctsByHue[hue]
val temp = getRelativeTemperature(hct)
val tempDelta = abs(temp - lastTemp)
lastTemp = temp
absoluteTotalTempDelta += tempDelta
}
var hueAddend = 1
val tempStep = absoluteTotalTempDelta / divisions.toDouble()
var totalTempDelta = 0.0
lastTemp = getRelativeTemperature(startHct)
while (allColors.size < divisions) {
val hue: Int = sanitizeDegreesInt(startHue + hueAddend)
val hct = hctsByHue[hue]
val temp = getRelativeTemperature(hct)
val tempDelta = abs(temp - lastTemp)
totalTempDelta += tempDelta
var desiredTotalTempDeltaForIndex = (allColors.size * tempStep)
var indexSatisfied = totalTempDelta >= desiredTotalTempDeltaForIndex
var indexAddend = 1
// Keep adding this hue to the answers until its temperature is
// insufficient. This ensures consistent behavior when there aren't
// `divisions` discrete steps between 0 and 360 in hue with `tempStep`
// delta in temperature between them.
//
// For example, white and black have no analogues: there are no other
// colors at T100/T0. Therefore, they should just be added to the array
// as answers.
while (indexSatisfied && allColors.size < divisions) {
allColors.add(hct)
desiredTotalTempDeltaForIndex = ((allColors.size + indexAddend) * tempStep)
indexSatisfied = totalTempDelta >= desiredTotalTempDeltaForIndex
indexAddend++
}
lastTemp = temp
hueAddend++
if (hueAddend > 360) {
while (allColors.size < divisions) {
allColors.add(hct)
}
break
}
}
val answers: MutableList<Hct> = ArrayList()
answers.add(input)
val ccwCount = floor((count.toDouble() - 1.0) / 2.0).toInt()
for (i in 1 until (ccwCount + 1)) {
var index = 0 - i
while (index < 0) {
index += allColors.size
}
if (index >= allColors.size) {
index %= allColors.size
}
answers.add(0, allColors[index])
}
val cwCount = count - ccwCount - 1
for (i in 1 until (cwCount + 1)) {
var index = i
while (index < 0) {
index += allColors.size
}
if (index >= allColors.size) index = index % allColors.size
answers.add(allColors[index])
}
return answers
}
/**
* Temperature relative to all colors with the same chroma and tone.
*
* @param hct HCT to find the relative temperature of.
* @return Value on a scale from 0 to 1.
*/
fun getRelativeTemperature(hct: Hct): Double {
val range = tempsByHct!![warmest]!! - tempsByHct!![coldest]!!
val differenceFromColdest =
tempsByHct!![hct]!! - tempsByHct!![coldest]!!
// Handle when there's no difference in temperature between warmest and
// coldest: for example, at T100, only one color is available, white.
if (range == 0.0) {
return 0.5
}
return differenceFromColdest / range
}
private val coldest: Hct
/** Coldest color with same chroma and tone as input. */
get() = hctsByTemp!![0]
private val hctsByHue: List<Hct>
/**
* HCTs for all colors with the same chroma/tone as the input.
*
*
* Sorted by hue, ex. index 0 is hue 0.
*/
get() {
if (precomputedHctsByHue != null) {
return precomputedHctsByHue!!
}
val hcts: MutableList<Hct> = ArrayList()
var hue = 0.0
while (hue <= 360.0) {
val colorAtHue = Hct.from(hue, input.getChroma(), input.getTone())
hcts.add(colorAtHue)
hue += 1.0
}
precomputedHctsByHue = hcts.toList()
return precomputedHctsByHue!!
}
private val hctsByTemp: List<Hct>?
/**
* HCTs for all colors with the same chroma/tone as the input.
*
*
* Sorted from coldest first to warmest last.
*/
get() {
if (precomputedHctsByTemp != null) {
return precomputedHctsByTemp
}
val hcts: MutableList<Hct> = ArrayList(hctsByHue)
hcts.add(input)
hcts.sortWith { hct1, hct2 ->
val hct1Double = tempsByHct!![hct1]
val hct2Double = tempsByHct!![hct2]
hct1Double!!.compareTo(hct2Double!!)
}
precomputedHctsByTemp = hcts
return precomputedHctsByTemp
}
private val tempsByHct: Map<Hct, Double>?
/** Keys of HCTs in getHctsByTemp, values of raw temperature. */
get() {
if (precomputedTempsByHct != null) {
return precomputedTempsByHct
}
val allHcts: MutableList<Hct> = ArrayList<Hct>(hctsByHue)
allHcts.add(input)
val temperaturesByHct: MutableMap<Hct, Double> = HashMap<Hct, Double>()
for (hct in allHcts) {
temperaturesByHct[hct] = rawTemperature(hct)
}
precomputedTempsByHct = temperaturesByHct
return precomputedTempsByHct
}
private val warmest: Hct
/** Warmest color with same chroma and tone as input. */
get() = hctsByTemp!![hctsByTemp!!.size - 1]
companion object {
/**
* Value representing cool-warm factor of a color. Values below 0 are considered cool, above,
* warm.
*
*
* Color science has researched emotion and harmony, which art uses to select colors. Warm-cool
* is the foundation of analogous and complementary colors. See: - Li-Chen Ou's Chapter 19 in
* Handbook of Color Psychology (2015). - Josef Albers' Interaction of Color chapters 19 and 21.
*
*
* Implementation of Ou, Woodcock and Wright's algorithm, which uses Lab/LCH color space.
* Return value has these properties:<br></br>
* - Values below 0 are cool, above 0 are warm.<br></br>
* - Lower bound: -9.66. Chroma is infinite. Assuming max of Lab chroma 130.<br></br>
* - Upper bound: 8.61. Chroma is infinite. Assuming max of Lab chroma 130.
*/
fun rawTemperature(color: Hct): Double {
val lab: DoubleArray = ColorUtils.labFromArgb(color.toInt())
val hue: Double = sanitizeDegreesDouble(
atan2(
lab[2], lab[1]
) * 180.0 / PI
)
val chroma = hypot(lab[1], lab[2])
return (-0.5
+ (0.02
* chroma.pow(1.07) * cos(
sanitizeDegreesDouble(
hue - 50.0
) * PI / 180.0
)))
}
/** Determines if an angle is between two other angles, rotating clockwise. */
private fun isBetween(angle: Double, a: Double, b: Double): Boolean {
if (a < b) {
return angle in a..b
}
return a <= angle || angle <= b
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/utils/ColorUtils.kt | Kotlin | package dev.zwander.compose.libmonet.utils
import dev.zwander.compose.libmonet.utils.MathUtils.clampInt
import dev.zwander.compose.libmonet.utils.MathUtils.matrixMultiply
import kotlin.math.pow
import kotlin.math.round
/**
* Color science utilities.
*
*
* Utility methods for color science constants and color space conversions that aren't HCT or
* CAM16.
*/
object ColorUtils {
val SRGB_TO_XYZ: Array<DoubleArray> = arrayOf(
doubleArrayOf(0.41233895, 0.35762064, 0.18051042),
doubleArrayOf(0.2126, 0.7152, 0.0722),
doubleArrayOf(0.01932141, 0.11916382, 0.95034478),
)
val XYZ_TO_SRGB: Array<DoubleArray> = arrayOf(
doubleArrayOf(
3.2413774792388685, -1.5376652402851851, -0.49885366846268053,
),
doubleArrayOf(
-0.9691452513005321, 1.8758853451067872, 0.04156585616912061,
),
doubleArrayOf(
0.05562093689691305, -0.20395524564742123, 1.0571799111220335,
),
)
val WHITE_POINT_D65: DoubleArray = doubleArrayOf(95.047, 100.0, 108.883)
/** Converts a color from RGB components to ARGB format. */
fun argbFromRgb(red: Int, green: Int, blue: Int): Int {
return (255 shl 24) or ((red and 255) shl 16) or ((green and 255) shl 8) or (blue and 255)
}
/** Converts a color from linear RGB components to ARGB format. */
fun argbFromLinrgb(linrgb: DoubleArray): Int {
val r = delinearized(linrgb[0])
val g = delinearized(linrgb[1])
val b = delinearized(linrgb[2])
return argbFromRgb(r, g, b)
}
/** Returns the alpha component of a color in ARGB format. */
fun alphaFromArgb(argb: Int): Int {
return (argb shr 24) and 255
}
/** Returns the red component of a color in ARGB format. */
fun redFromArgb(argb: Int): Int {
return (argb shr 16) and 255
}
/** Returns the green component of a color in ARGB format. */
fun greenFromArgb(argb: Int): Int {
return (argb shr 8) and 255
}
/** Returns the blue component of a color in ARGB format. */
fun blueFromArgb(argb: Int): Int {
return argb and 255
}
/** Returns whether a color in ARGB format is opaque. */
fun isOpaque(argb: Int): Boolean {
return alphaFromArgb(argb) >= 255
}
/** Converts a color from ARGB to XYZ. */
fun argbFromXyz(x: Double, y: Double, z: Double): Int {
val matrix = XYZ_TO_SRGB
val linearR = matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z
val linearG = matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z
val linearB = matrix[2][0] * x + matrix[2][1] * y + matrix[2][2] * z
val r = delinearized(linearR)
val g = delinearized(linearG)
val b = delinearized(linearB)
return argbFromRgb(r, g, b)
}
/** Converts a color from XYZ to ARGB. */
fun xyzFromArgb(argb: Int): DoubleArray {
val r = linearized(redFromArgb(argb))
val g = linearized(greenFromArgb(argb))
val b = linearized(blueFromArgb(argb))
return matrixMultiply(doubleArrayOf(r, g, b), SRGB_TO_XYZ)
}
/** Converts a color represented in Lab color space into an ARGB integer. */
fun argbFromLab(l: Double, a: Double, b: Double): Int {
val whitePoint = WHITE_POINT_D65
val fy = (l + 16.0) / 116.0
val fx = a / 500.0 + fy
val fz = fy - b / 200.0
val xNormalized = labInvf(fx)
val yNormalized = labInvf(fy)
val zNormalized = labInvf(fz)
val x = xNormalized * whitePoint[0]
val y = yNormalized * whitePoint[1]
val z = zNormalized * whitePoint[2]
return argbFromXyz(x, y, z)
}
/**
* Converts a color from ARGB representation to L*a*b* representation.
*
* @param argb the ARGB representation of a color
* @return a Lab object representing the color
*/
fun labFromArgb(argb: Int): DoubleArray {
val linearR = linearized(redFromArgb(argb))
val linearG = linearized(greenFromArgb(argb))
val linearB = linearized(blueFromArgb(argb))
val matrix = SRGB_TO_XYZ
val x = matrix[0][0] * linearR + matrix[0][1] * linearG + matrix[0][2] * linearB
val y = matrix[1][0] * linearR + matrix[1][1] * linearG + matrix[1][2] * linearB
val z = matrix[2][0] * linearR + matrix[2][1] * linearG + matrix[2][2] * linearB
val whitePoint = WHITE_POINT_D65
val xNormalized = x / whitePoint[0]
val yNormalized = y / whitePoint[1]
val zNormalized = z / whitePoint[2]
val fx = labF(xNormalized)
val fy = labF(yNormalized)
val fz = labF(zNormalized)
val l = 116.0 * fy - 16
val a = 500.0 * (fx - fy)
val b = 200.0 * (fy - fz)
return doubleArrayOf(l, a, b)
}
/**
* Converts an L* value to an ARGB representation.
*
* @param lstar L* in L*a*b*
* @return ARGB representation of grayscale color with lightness matching L*
*/
fun argbFromLstar(lstar: Double): Int {
val y = yFromLstar(lstar)
val component = delinearized(y)
return argbFromRgb(component, component, component)
}
/**
* Computes the L* value of a color in ARGB representation.
*
* @param argb ARGB representation of a color
* @return L*, from L*a*b*, coordinate of the color
*/
fun lstarFromArgb(argb: Int): Double {
val y = xyzFromArgb(argb)[1]
return 116.0 * labF(y / 100.0) - 16.0
}
/**
* Converts an L* value to a Y value.
*
*
* L* in L*a*b* and Y in XYZ measure the same quantity, luminance.
*
*
* L* measures perceptual luminance, a linear scale. Y in XYZ measures relative luminance, a
* logarithmic scale.
*
* @param lstar L* in L*a*b*
* @return Y in XYZ
*/
fun yFromLstar(lstar: Double): Double {
return 100.0 * labInvf((lstar + 16.0) / 116.0)
}
/**
* Converts a Y value to an L* value.
*
*
* L* in L*a*b* and Y in XYZ measure the same quantity, luminance.
*
*
* L* measures perceptual luminance, a linear scale. Y in XYZ measures relative luminance, a
* logarithmic scale.
*
* @param y Y in XYZ
* @return L* in L*a*b*
*/
fun lstarFromY(y: Double): Double {
return labF(y / 100.0) * 116.0 - 16.0
}
/**
* Linearizes an RGB component.
*
* @param rgbComponent 0 <= rgb_component <= 255, represents R/G/B channel
* @return 0.0 <= output <= 100.0, color channel converted to linear RGB space
*/
fun linearized(rgbComponent: Int): Double {
val normalized = rgbComponent / 255.0
return if (normalized <= 0.040449936) {
normalized / 12.92 * 100.0
} else {
((normalized + 0.055) / 1.055).pow(2.4) * 100.0
}
}
/**
* Delinearizes an RGB component.
*
* @param rgbComponent 0.0 <= rgb_component <= 100.0, represents linear R/G/B channel
* @return 0 <= output <= 255, color channel converted to regular RGB space
*/
fun delinearized(rgbComponent: Double): Int {
val normalized = rgbComponent / 100.0
val delinearized = if (normalized <= 0.0031308) {
normalized * 12.92
} else {
1.055 * normalized.pow(1.0 / 2.4) - 0.055
}
return clampInt(
0,
255,
round(delinearized * 255.0).toInt(),
)
}
/**
* Returns the standard white point; white on a sunny day.
*
* @return The white point
*/
fun whitePointD65(): DoubleArray {
return WHITE_POINT_D65
}
fun labF(t: Double): Double {
val e = 216.0 / 24389.0
val kappa = 24389.0 / 27.0
return if (t > e) {
t.pow(1.0 / 3.0)
} else {
(kappa * t + 16) / 116
}
}
fun labInvf(ft: Double): Double {
val e = 216.0 / 24389.0
val kappa = 24389.0 / 27.0
val ft3 = ft * ft * ft
return if (ft3 > e) {
ft3
} else {
(116 * ft - 16) / kappa
}
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/utils/MathUtils.kt | Kotlin | package dev.zwander.compose.libmonet.utils
import kotlin.math.abs
/** Utility methods for mathematical operations. */
object MathUtils {
/**
* The signum function.
*
* @return 1 if num > 0, -1 if num < 0, and 0 if num = 0
*/
fun signum(num: Double): Int {
return if (num < 0) {
-1
} else if (num == 0.0) {
0
} else {
1
}
}
/**
* The linear interpolation function.
*
* @return start if amount = 0 and stop if amount = 1
*/
fun lerp(start: Double, stop: Double, amount: Double): Double {
return (1.0 - amount) * start + amount * stop
}
/**
* Clamps an integer between two integers.
*
* @return input when min <= input <= max, and either min or max otherwise.
*/
fun clampInt(min: Int, max: Int, input: Int): Int {
if (input < min) {
return min
} else if (input > max) {
return max
}
return input
}
/**
* Clamps an integer between two floating-point numbers.
*
* @return input when min <= input <= max, and either min or max otherwise.
*/
fun clampDouble(min: Double, max: Double, input: Double): Double {
if (input < min) {
return min
} else if (input > max) {
return max
}
return input
}
/**
* Sanitizes a degree measure as an integer.
*
* @return a degree measure between 0 (inclusive) and 360 (exclusive).
*/
fun sanitizeDegreesInt(degrees: Int): Int {
var degreesTmp = degrees
degreesTmp %= 360
if (degreesTmp < 0) {
degreesTmp += 360
}
return degreesTmp
}
/**
* Sanitizes a degree measure as a floating-point number.
*
* @return a degree measure between 0.0 (inclusive) and 360.0 (exclusive).
*/
fun sanitizeDegreesDouble(degrees: Double): Double {
var degreesTmp = degrees
degreesTmp %= 360.0
if (degreesTmp < 0) {
degreesTmp += 360.0
}
return degreesTmp
}
/**
* Sign of direction change needed to travel from one angle to another.
*
*
* For angles that are 180 degrees apart from each other, both directions have the same travel
* distance, so either direction is shortest. The value 1.0 is returned in this case.
*
* @param from The angle travel starts from, in degrees.
* @param to The angle travel ends at, in degrees.
* @return -1 if decreasing from leads to the shortest travel distance, 1 if increasing from leads
* to the shortest travel distance.
*/
fun rotationDirection(from: Double, to: Double): Double {
val increasingDifference = sanitizeDegreesDouble(to - from)
return if (increasingDifference <= 180.0) 1.0 else -1.0
}
/** Distance of two points on a circle, represented using degrees. */
fun differenceDegrees(a: Double, b: Double): Double {
return 180.0 - abs(abs(a - b) - 180.0)
}
/** Multiplies a 1x3 row vector with a 3x3 matrix. */
fun matrixMultiply(row: DoubleArray, matrix: Array<DoubleArray>): DoubleArray {
val a = row[0] * matrix[0][0] + row[1] * matrix[0][1] + row[2] * matrix[0][2]
val b = row[0] * matrix[1][0] + row[1] * matrix[1][1] + row[2] * matrix[1][2]
val c = row[0] * matrix[2][0] + row[1] * matrix[2][1] + row[2] * matrix[2][2]
return doubleArrayOf(a, b, c)
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/libmonet/utils/SchemeUtils.kt | Kotlin | package dev.zwander.compose.libmonet.utils
import androidx.compose.material3.ColorScheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.colorspace.ColorSpaces
import dev.zwander.compose.libmonet.dynamiccolor.DynamicScheme
import kotlin.math.pow
import kotlin.math.roundToInt
fun DynamicScheme.toComposeColorScheme(): ColorScheme {
val accent1 = primaryPalette
val accent2 = secondaryPalette
val accent3 = tertiaryPalette
val neutral1 = neutralPalette
val neutral2 = neutralVariantPalette
return if (isDark) {
darkColorScheme(
primary = accent1.shade(200).toColor(),
onPrimary = accent1.shade(800).toColor(),
primaryContainer = accent1.shade(700).toColor(),
onPrimaryContainer = accent1.shade(100).toColor(),
inversePrimary = accent1.shade(600).toColor(),
secondary = accent2.shade(200).toColor(),
onSecondary = accent2.shade(800).toColor(),
secondaryContainer = accent2.shade(700).toColor(),
onSecondaryContainer = accent2.shade(100).toColor(),
tertiary = accent3.shade(200).toColor(),
onTertiary = accent3.shade(800).toColor(),
tertiaryContainer = accent3.shade(700).toColor(),
onTertiaryContainer = accent3.shade(100).toColor(),
background = neutral1.shade(900).toColor(),
onBackground = neutral1.shade(100).toColor(),
surface = neutral1.shade(900).toColor(),
onSurface = neutral1.shade(100).toColor(),
surfaceVariant = neutral2.shade(700).toColor(),
onSurfaceVariant = neutral2.shade(200).toColor(),
inverseSurface = neutral1.shade(100).toColor(),
inverseOnSurface = neutral1.shade(800).toColor(),
outline = neutral2.shade(400).toColor(),
surfaceContainerLowest = neutral2.shade(600).toColor(),
surfaceContainer = neutral2.shade(600).toColor().setLuminance(4f),
surfaceContainerLow = neutral2.shade(900).toColor(),
surfaceContainerHigh = neutral2.shade(600).toColor().setLuminance(17f),
surfaceContainerHighest = neutral2.shade(600).toColor().setLuminance(22f),
outlineVariant = neutral2.shade(700).toColor(),
scrim = neutral2.shade(1000).toColor(),
surfaceBright = neutral2.shade(600).toColor().setLuminance(98f),
surfaceDim = neutral2.shade(600).toColor().setLuminance(6f),
surfaceTint = accent1.shade(200).toColor(),
)
} else {
lightColorScheme(
primary = accent1.shade(600).toColor(),
onPrimary = accent1.shade(0).toColor(),
primaryContainer = accent1.shade(100).toColor(),
onPrimaryContainer = accent1.shade(900).toColor(),
inversePrimary = accent1.shade(200).toColor(),
secondary = accent2.shade(600).toColor(),
onSecondary = accent2.shade(0).toColor(),
secondaryContainer = accent2.shade(100).toColor(),
onSecondaryContainer = accent2.shade(900).toColor(),
tertiary = accent3.shade(600).toColor(),
onTertiary = accent3.shade(0).toColor(),
tertiaryContainer = accent3.shade(100).toColor(),
onTertiaryContainer = accent3.shade(900).toColor(),
background = neutral1.shade(10).toColor(),
onBackground = neutral1.shade(900).toColor(),
surface = neutral1.shade(10).toColor(),
onSurface = neutral1.shade(900).toColor(),
surfaceVariant = neutral2.shade(100).toColor(),
onSurfaceVariant = neutral2.shade(700).toColor(),
inverseSurface = neutral1.shade(800).toColor(),
inverseOnSurface = neutral1.shade(50).toColor(),
outline = neutral2.shade(500).toColor(),
surfaceContainerLowest = neutral2.shade(0).toColor(),
surfaceContainer = neutral2.shade(600).toColor().setLuminance(94f),
surfaceContainerLow = neutral2.shade(600).toColor().setLuminance(96f),
surfaceContainerHigh = neutral2.shade(600).toColor().setLuminance(92f),
surfaceContainerHighest = neutral2.shade(10-0).toColor(),
outlineVariant = neutral2.shade(200).toColor(),
scrim = neutral2.shade(1000).toColor(),
surfaceBright = neutral2.shade(600).toColor().setLuminance(98f),
surfaceDim = neutral2.shade(600).toColor().setLuminance(87f),
surfaceTint = accent1.shade(600).toColor(),
)
}
}
private fun Int.toColor(): Color {
return Color(this)
}
internal fun Color.setLuminance(newLuminance: Float): Color {
if ((newLuminance < 0.0001) or (newLuminance > 99.9999)) {
// aRGBFromLstar() from monet ColorUtil.java
val y = 100 * labInvf((newLuminance + 16) / 116)
val component = delinearized(y)
return Color(
/* red = */ component,
/* green = */ component,
/* blue = */ component,
)
}
val sLAB = this.convert(ColorSpaces.CieLab)
return Color(
/* luminance = */ newLuminance,
/* a = */ sLAB.component2(),
/* b = */ sLAB.component3(),
colorSpace = ColorSpaces.CieLab
)
.convert(ColorSpaces.Srgb)
}
private fun labInvf(ft: Float): Float {
val e = 216f / 24389f
val kappa = 24389f / 27f
val ft3 = ft * ft * ft
return if (ft3 > e) {
ft3
} else {
(116 * ft - 16) / kappa
}
}
private fun delinearized(rgbComponent: Float): Int {
val normalized = rgbComponent / 100
val delinearized =
if (normalized <= 0.0031308) {
normalized * 12.92
} else {
1.055 * normalized.toDouble().pow(1.0 / 2.4) - 0.055
}
return (delinearized * 255.0).roundToInt().coerceAtLeast(0).coerceAtMost(255)
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/monet/Cam.kt | Kotlin | package dev.zwander.compose.monet
import dev.zwander.compose.monet.CamUtils.signum
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.ln
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
import kotlin.math.round
import kotlin.math.sin
import kotlin.math.sqrt
/**
* A color appearance model, based on CAM16, extended to use L* as the lightness dimension, and
* coupled to a gamut mapping algorithm. Creates a color system, enables a digital design system.
*/
@Suppress("unused", "MemberVisibilityCanBePrivate")
class Cam internal constructor(
/** Hue in CAM16 */
// CAM16 color dimensions, see getters for documentation.
val hue: Double,
/** Chroma in CAM16 */
val chroma: Double,
/** Lightness in CAM16 */
val j: Double,
/**
* Brightness in CAM16.
*
*
* Prefer lightness, brightness is an absolute quantity. For example, a sheet of white paper
* is much brighter viewed in sunlight than in indoor light, but it is the lightest object under
* any lighting.
*/
val q: Double,
/**
* Colorfulness in CAM16.
*
*
* Prefer chroma, colorfulness is an absolute quantity. For example, a yellow toy car is much
* more colorful outside than inside, but it has the same chroma in both environments.
*/
val m: Double,
/**
* Saturation in CAM16.
*
*
* Colorfulness in proportion to brightness. Prefer chroma, saturation measures colorfulness
* relative to the color's own brightness, where chroma is colorfulness relative to white.
*/
val s: Double,
/** Lightness coordinate in CAM16-UCS */
// Coordinates in UCS space. Used to determine color distance, like delta E equations in L*a*b*.
val jstar: Double,
/** a* coordinate in CAM16-UCS */
val astar: Double,
/** b* coordinate in CAM16-UCS */
val bstar: Double
) {
/**
* Distance in CAM16-UCS space between two colors.
*
*
* Much like L*a*b* was designed to measure distance between colors, the CAM16 standard
* defined a color space called CAM16-UCS to measure distance between CAM16 colors.
*/
fun distance(other: Cam): Double {
val dJ = jstar - other.jstar
val dA = astar - other.astar
val dB = bstar - other.bstar
val dEPrime: Double = sqrt((dJ * dJ + dA * dA + dB * dB))
val dE: Double = 1.41 * dEPrime.pow(0.63)
return dE
}
/** Returns perceived color as an ARGB integer, as viewed in standard sRGB frame. */
fun viewedInSrgb(): Int {
return viewed(Frame.DEFAULT)
}
/** Returns color perceived in a frame as an ARGB integer. */
fun viewed(frame: Frame): Int {
val alpha =
if (chroma == 0.0 || j == 0.0) 0.0 else chroma / sqrt(
j / 100.0
)
val t: Double = pow(
alpha / pow(
1.64 - pow(0.29, frame.n),
0.73
),
1.0 / 0.9
)
val hRad: Double = hue * PI / 180.0
val eHue: Double = 0.25 * (cos(hRad + 2.0) + 3.8)
val ac: Double = frame.aw * pow(
j / 100.0,
1.0 / frame.c / frame.z
)
val p1: Double = eHue * (50000.0 / 13.0) * frame.nc * frame.ncb
val p2: Double = ac / frame.nbb
val hSin: Double = sin(hRad)
val hCos: Double = cos(hRad)
val gamma =
23.0 * (p2 + 0.305) * t / (23.0 * p1 + 11.0 * t * hCos + 108.0 * t * hSin)
val a = gamma * hCos
val b = gamma * hSin
val rA = (460.0 * p2 + 451.0 * a + 288.0 * b) / 1403.0
val gA = (460.0 * p2 - 891.0 * a - 261.0 * b) / 1403.0
val bA = (460.0 * p2 - 220.0 * a - 6300.0 * b) / 1403.0
val rCBase: Double = max(
0.0,
27.13 * abs(rA) / (400.0 - abs(rA))
)
val rC: Double =
signum(rA) * (100.0 / frame.fl) * pow(
rCBase,
1.0 / 0.42
)
val gCBase: Double = max(
0.0,
27.13 * abs(gA) / (400.0 - abs(gA))
)
val gC: Double =
signum(gA) * (100.0 / frame.fl) * pow(
gCBase,
1.0 / 0.42
)
val bCBase: Double = max(
0.0,
27.13 * abs(bA) / (400.0 - abs(bA))
)
val bC: Double =
signum(bA) * (100.0 / frame.fl) * pow(
bCBase,
1.0 / 0.42
)
val rF: Double = rC / frame.rgbD[0]
val gF: Double = gC / frame.rgbD[1]
val bF: Double = bC / frame.rgbD[2]
val matrix: Array<DoubleArray> =
CamUtils.CAM16RGB_TO_XYZ
val x =
rF * matrix[0][0] + gF * matrix[0][1] + bF * matrix[0][2]
val y =
rF * matrix[1][0] + gF * matrix[1][1] + bF * matrix[1][2]
val z =
rF * matrix[2][0] + gF * matrix[2][1] + bF * matrix[2][2]
return ColorUtils.XYZToColor(
x,
y,
z
)
}
companion object {
// The maximum difference between the requested L* and the L* returned.
private const val DL_MAX = 0.2
// The maximum color distance, in CAM16-UCS, between a requested color and the color returned.
private const val DE_MAX = 1.0
// When the delta between the floor & ceiling of a binary search for chroma is less than this,
// the binary search terminates.
private const val CHROMA_SEARCH_ENDPOINT = 0.4
// When the delta between the floor & ceiling of a binary search for J, lightness in CAM16,
// is less than this, the binary search terminates.
private const val LIGHTNESS_SEARCH_ENDPOINT = 0.01
/**
* Given a hue & chroma in CAM16, L* in L*a*b*, return an ARGB integer. The chroma of the color
* returned may, and frequently will, be lower than requested. Assumes the color is viewed in
* the
* frame defined by the sRGB standard.
*/
fun getInt(hue: Double, chroma: Double, lstar: Double): Int {
return getInt(hue, chroma, lstar, Frame.DEFAULT)
}
/**
* Create a color appearance model from a ARGB integer representing a color. It is assumed the
* color was viewed in the frame defined in the sRGB standard.
*/
fun fromInt(argb: Int): Cam {
return fromIntInFrame(argb, Frame.DEFAULT)
}
/**
* Create a color appearance model from a ARGB integer representing a color, specifying the
* frame in which the color was viewed. Prefer Cam.fromInt.
*/
fun fromIntInFrame(argb: Int, frame: Frame): Cam {
// Transform ARGB int to XYZ
val xyz: DoubleArray = CamUtils.xyzFromInt(argb)
// Transform XYZ to 'cone'/'rgb' responses
val matrix: Array<DoubleArray> =
CamUtils.XYZ_TO_CAM16RGB
val rT = xyz[0] * matrix[0][0] + xyz[1] * matrix[0][1] + xyz[2] * matrix[0][2]
val gT = xyz[0] * matrix[1][0] + xyz[1] * matrix[1][1] + xyz[2] * matrix[1][2]
val bT = xyz[0] * matrix[2][0] + xyz[1] * matrix[2][1] + xyz[2] * matrix[2][2]
// Discount illuminant
val rD: Double = frame.rgbD[0] * rT
val gD: Double = frame.rgbD[1] * gT
val bD: Double = frame.rgbD[2] * bT
// Chromatic adaptation
val rAF: Double =
pow(frame.fl * abs(rD) / 100.0, 0.42)
val gAF: Double =
pow(frame.fl * abs(gD) / 100.0, 0.42)
val bAF: Double =
pow(frame.fl * abs(bD) / 100.0, 0.42)
val rA: Double = signum(rD) * 400.0 * rAF / (rAF + 27.13)
val gA: Double = signum(gD) * 400.0 * gAF / (gAF + 27.13)
val bA: Double = signum(bD) * 400.0 * bAF / (bAF + 27.13)
// redness-greenness
val a = (11.0 * rA + -12.0 * gA + bA) / 11.0
// yellowness-blueness
val b = (rA + gA - 2.0 * bA) / 9.0
// auxiliary components
val u = (20.0 * rA + 20.0 * gA + 21.0 * bA) / 20.0
val p2 = (40.0 * rA + 20.0 * gA + bA) / 20.0
// hue
val atan2: Double = atan2(b, a)
val atanDegrees: Double = atan2 * 180.0 / PI
val hue =
if (atanDegrees < 0) atanDegrees + 360.0 else if (atanDegrees >= 360) atanDegrees - 360.0 else atanDegrees
val hueRadians: Double = hue * PI / 180.0
// achromatic response to color
val ac: Double = p2 * frame.nbb
// CAM16 lightness and brightness
val j: Double = 100.0 * pow(
(ac / frame.aw),
(frame.c * frame.z)
)
val q: Double = ((4.0
/ frame.c) * sqrt((j / 100.0))
* (frame.aw + 4.0)
* frame.flRoot)
// CAM16 chroma, colorfulness, and saturation.
val huePrime = if (hue < 20.14) hue + 360 else hue
val eHue: Double =
0.25 * (cos(huePrime * PI / 180.0 + 2.0) + 3.8)
val p1: Double = 50000.0 / 13.0 * eHue * frame.nc * frame.ncb
val t: Double =
p1 * sqrt((a * a + b * b)) / (u + 0.305)
val alpha: Double = pow(t, 0.9) * pow(
1.64 - pow(0.29, frame.n),
0.73
)
// CAM16 chroma, colorfulness, saturation
val c: Double = alpha * sqrt(j / 100.0)
val m: Double = c * frame.flRoot
val s: Double =
50.0 * sqrt((alpha * frame.c / (frame.aw + 4.0)))
// CAM16-UCS components
val jstar = (1.0 + 100.0 * 0.007) * j / (1.0 + 0.007 * j)
val mstar: Double =
1.0 / 0.0228 * ln((1.0 + 0.0228 * m))
val astar: Double = mstar * cos(hueRadians)
val bstar: Double = mstar * sin(hueRadians)
return Cam(hue, c, j, q, m, s, jstar, astar, bstar)
}
/**
* Create a CAM from lightness, chroma, and hue coordinates. It is assumed those coordinates
* were measured in the sRGB standard frame.
*/
private fun fromJch(j: Double, c: Double, h: Double): Cam {
return fromJchInFrame(j, c, h, Frame.DEFAULT)
}
/**
* Create a CAM from lightness, chroma, and hue coordinates, and also specify the frame in which
* the color is being viewed.
*/
private fun fromJchInFrame(
j: Double,
c: Double,
h: Double,
frame: Frame
): Cam {
val q: Double = ((4.0
/ frame.c) * sqrt(j / 100.0)
* (frame.aw + 4.0)
* frame.flRoot)
val m: Double = c * frame.flRoot
val alpha: Double = c / sqrt(j / 100.0)
val s: Double =
50.0 * sqrt((alpha * frame.c / (frame.aw + 4.0)))
val hueRadians: Double = h * PI / 180.0
val jstar = (1.0 + 100.0 * 0.007) * j / (1.0 + 0.007 * j)
val mstar: Double = 1.0 / 0.0228 * ln(1.0 + 0.0228 * m)
val astar: Double = mstar * cos(hueRadians)
val bstar: Double = mstar * sin(hueRadians)
return Cam(h, c, j, q, m, s, jstar, astar, bstar)
}
/**
* Given a hue & chroma in CAM16, L* in L*a*b*, and the frame in which the color will be
* viewed,
* return an ARGB integer.
*
*
* The chroma of the color returned may, and frequently will, be lower than requested. This
* is
* a fundamental property of color that cannot be worked around by engineering. For example, a
* red
* hue, with high chroma, and high L* does not exist: red hues have a maximum chroma below 10
* in
* light shades, creating pink.
*/
fun getInt(
hue: Double,
chroma: Double,
lstar: Double,
frame: Frame
): Int {
// This is a crucial routine for building a color system, CAM16 itself is not sufficient.
//
// * Why these dimensions?
// Hue and chroma from CAM16 are used because they're the most accurate measures of those
// quantities. L* from L*a*b* is used because it correlates with luminance, luminance is
// used to measure contrast for a11y purposes, thus providing a key constraint on what
// colors
// can be used.
//
// * Why is this routine required to build a color system?
// In all perceptually accurate color spaces (i.e. L*a*b* and later), `chroma` may be
// impossible for a given `hue` and `lstar`.
// For example, a high chroma light red does not exist - chroma is limited to below 10 at
// light red shades, we call that pink. High chroma light green does exist, but not dark
// Also, when converting from another color space to RGB, the color may not be able to be
// represented in RGB. In those cases, the conversion process ends with RGB values
// outside 0-255
// The vast majority of color libraries surveyed simply round to 0 to 255. That is not an
// option for this library, as it distorts the expected luminance, and thus the expected
// contrast needed for a11y
//
// * What does this routine do?
// Dealing with colors in one color space not fitting inside RGB is, loosely referred to as
// gamut mapping or tone mapping. These algorithms are traditionally idiosyncratic, there is
// no universal answer. However, because the intent of this library is to build a system for
// digital design, and digital design uses luminance to measure contrast/a11y, we have one
// very important constraint that leads to an objective algorithm: the L* of the returned
// color _must_ match the requested L*.
//
// Intuitively, if the color must be distorted to fit into the RGB gamut, and the L*
// requested *must* be fulfilled, than the hue or chroma of the returned color will need
// to be different from the requested hue/chroma.
//
// After exploring both options, it was more intuitive that if the requested chroma could
// not be reached, it used the highest possible chroma. The alternative was finding the
// closest hue where the requested chroma could be reached, but that is not nearly as
// intuitive, as the requested hue is so fundamental to the color description.
// If the color doesn't have meaningful chroma, return a gray with the requested Lstar.
//
// Yellows are very chromatic at L = 100, and blues are very chromatic at L = 0. All the
// other hues are white at L = 100, and black at L = 0. To preserve consistency for users of
// this system, it is better to simply return white at L* > 99, and black and L* < 0.
var mutableHue = hue
if (frame == Frame.DEFAULT) {
// If the viewing conditions are the same as the default sRGB-like viewing conditions,
// skip to using HctSolver: it uses geometrical insights to find the closest in-gamut
// match to hue/chroma/lstar.
return HctSolver.solveToInt(
mutableHue,
chroma,
lstar
)
}
if (chroma < 1.0 || round(lstar) <= 0.0 || round(lstar) >= 100.0) {
return CamUtils.intFromLstar(lstar)
}
mutableHue = if (mutableHue < 0) 0.0 else min(360.0, mutableHue)
// The highest chroma possible. Updated as binary search proceeds.
var high = chroma
// The guess for the current binary search iteration. Starts off at the highest chroma,
// thus, if a color is possible at the requested chroma, the search can stop after one try.
var mid = chroma
var low = 0.0
var isFirstLoop = true
var answer: Cam? = null
while (abs(low - high) >= CHROMA_SEARCH_ENDPOINT) {
// Given the current chroma guess, mid, and the desired hue, find J, lightness in
// CAM16 color space, that creates a color with L* = `lstar` in the L*a*b* color space.
val possibleAnswer = findCamByJ(mutableHue, mid, lstar)
if (isFirstLoop) {
return if (possibleAnswer != null) {
possibleAnswer.viewed(frame)
} else {
// If this binary search iteration was the first iteration, and this point
// has been reached, it means the requested chroma was not available at the
// requested hue and L*.
// Proceed to a traditional binary search that starts at the midpoint between
// the requested chroma and 0.
isFirstLoop = false
mid = low + (high - low) / 2.0
continue
}
}
if (possibleAnswer == null) {
// There isn't a CAM16 J that creates a color with L* `lstar`. Try a lower chroma.
high = mid
} else {
answer = possibleAnswer
// It is possible to create a color. Try higher chroma.
low = mid
}
mid = low + (high - low) / 2.0
}
// There was no answer: meaning, for the desired hue, there was no chroma low enough to
// generate a color with the desired L*.
// All values of L* are possible when there is 0 chroma. Return a color with 0 chroma, i.e.
// a shade of gray, with the desired L*.
return answer?.viewed(frame) ?: CamUtils.intFromLstar(
lstar
)
}
// Find J, lightness in CAM16 color space, that creates a color with L* = `lstar` in the L*a*b*
// color space.
//
// Returns null if no J could be found that generated a color with L* `lstar`.
private fun findCamByJ(hue: Double, chroma: Double, lstar: Double): Cam? {
var low = 0.0
var high = 100.0
var mid: Double
var bestdL = 1000.0
var bestdE = 1000.0
var bestCam: Cam? = null
while (abs(low - high) > LIGHTNESS_SEARCH_ENDPOINT) {
mid = low + (high - low) / 2
// Create the intended CAM color
val camBeforeClip = fromJch(mid, chroma, hue)
// Convert the CAM color to RGB. If the color didn't fit in RGB, during the conversion,
// the initial RGB values will be outside 0 to 255. The final RGB values are clipped to
// 0 to 255, distorting the intended color.
val clipped = camBeforeClip.viewedInSrgb()
val clippedLstar: Double =
CamUtils.lstarFromInt(clipped)
val dL: Double = abs(lstar - clippedLstar)
// If the clipped color's L* is within error margin...
if (dL < DL_MAX) {
// ...check if the CAM equivalent of the clipped color is far away from intended CAM
// color. For the intended color, use lightness and chroma from the clipped color,
// and the intended hue. Callers are wondering what the lightness is, they know
// chroma may be distorted, so the only concern here is if the hue slipped too far.
val camClipped = fromInt(clipped)
val dE = camClipped.distance(
fromJch(camClipped.j, camClipped.chroma, hue)
)
if (dE <= DE_MAX) {
bestdL = dL
bestdE = dE
bestCam = camClipped
}
}
// If there's no error at all, there's no need to search more.
//
// Note: this happens much more frequently than expected, but this is a very delicate
// property which relies on extremely precise sRGB <=> XYZ calculations, as well as fine
// tuning of the constants that determine error margins and when the binary search can
// terminate.
if (bestdL == 0.0 && bestdE == 0.0) {
break
}
if (clippedLstar < lstar) {
low = mid
} else {
high = mid
}
}
return bestCam
}
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/monet/CamUtils.kt | Kotlin | package dev.zwander.compose.monet
import androidx.compose.ui.graphics.Color
import dev.zwander.compose.util.blue
import dev.zwander.compose.util.green
import dev.zwander.compose.util.red
import kotlin.math.cbrt
import kotlin.math.pow
import kotlin.math.round
/**
* Collection of methods for transforming between color spaces.
*
*
* Methods are named $xFrom$Y. For example, lstarFromInt() returns L* from an ARGB integer.
*
*
* These methods, generally, convert colors between the L*a*b*, XYZ, and sRGB spaces.
*
*
* L*a*b* is a perceptually accurate color space. This is particularly important in the L*
* dimension: it measures luminance and unlike lightness measures traditionally used in UI work via
* RGB or HSL, this luminance transitions smoothly, permitting creation of pleasing shades of a
* color, and more pleasing transitions between colors.
*
*
* XYZ is commonly used as an intermediate color space for converting between one color space to
* another. For example, to convert RGB to L*a*b*, first RGB is converted to XYZ, then XYZ is
* convered to L*a*b*.
*
*
* sRGB is a "specification originated from work in 1990s through cooperation by Hewlett-Packard
* and Microsoft, and it was designed to be a standard definition of RGB for the internet, which it
* indeed became...The standard is based on a sampling of computer monitors at the time...The whole
* idea of sRGB is that if everyone assumed that RGB meant the same thing, then the results would be
* consistent, and reasonably good. It worked." - Fairchild, Color Models and Systems: Handbook of
* Color Psychology, 2015
*/
@Suppress("unused", "MemberVisibilityCanBePrivate")
object CamUtils {
// Transforms XYZ color space coordinates to 'cone'/'RGB' responses in CAM16.
val XYZ_TO_CAM16RGB = arrayOf(
doubleArrayOf(0.401288, 0.650173, -0.051461),
doubleArrayOf(-0.250268, 1.204414, 0.045854),
doubleArrayOf(-0.002079, 0.048952, 0.953127)
)
// Transforms 'cone'/'RGB' responses in CAM16 to XYZ color space coordinates.
val CAM16RGB_TO_XYZ = arrayOf(
doubleArrayOf(1.86206786, -1.01125463, 0.14918677),
doubleArrayOf(0.38752654, 0.62144744, -0.00897398),
doubleArrayOf(-0.01584150, -0.03412294, 1.04996444)
)
// Need this, XYZ coordinates in internal ColorUtils are private
// sRGB specification has D65 whitepoint - Stokes, Anderson, Chandrasekar, Motta - A Standard
// Default Color Space for the Internet: sRGB, 1996
val WHITE_POINT_D65 = doubleArrayOf(95.047, 100.0, 108.883)
// This is a more precise sRGB to XYZ transformation matrix than traditionally
// used. It was derived using Schlomer's technique of transforming the xyY
// primaries to XYZ, then applying a correction to ensure mapping from sRGB
// 1, 1, 1 to the reference white point, D65.
private val SRGB_TO_XYZ = arrayOf(
doubleArrayOf(0.41233895, 0.35762064, 0.18051042),
doubleArrayOf(0.2126, 0.7152, 0.0722),
doubleArrayOf(0.01932141, 0.11916382, 0.95034478)
)
private val XYZ_TO_SRGB = arrayOf(
doubleArrayOf(
3.2413774792388685, -1.5376652402851851, -0.49885366846268053
), doubleArrayOf(
-0.9691452513005321, 1.8758853451067872, 0.04156585616912061
), doubleArrayOf(
0.05562093689691305, -0.20395524564742123, 1.0571799111220335
)
)
/**
* The signum function.
*
* @return 1 if num > 0, -1 if num < 0, and 0 if num = 0
*/
fun signum(num: Double): Int {
return if (num < 0) {
-1
} else if (num == 0.0) {
0
} else {
1
}
}
/**
* Converts an L* value to an ARGB representation.
*
* @param lstar L* in L*a*b*
* @return ARGB representation of grayscale color with lightness matching L*
*/
fun argbFromLstar(lstar: Double): Int {
val fy = (lstar + 16.0) / 116.0
val kappa = 24389.0 / 27.0
val epsilon = 216.0 / 24389.0
val lExceedsEpsilonKappa = lstar > 8.0
val y = if (lExceedsEpsilonKappa) fy * fy * fy else lstar / kappa
val cubeExceedEpsilon = fy * fy * fy > epsilon
val x = if (cubeExceedEpsilon) fy * fy * fy else lstar / kappa
val z = if (cubeExceedEpsilon) fy * fy * fy else lstar / kappa
val whitePoint = WHITE_POINT_D65
return argbFromXyz(x * whitePoint[0], y * whitePoint[1], z * whitePoint[2])
}
/** Converts a color from ARGB to XYZ. */
fun argbFromXyz(x: Double, y: Double, z: Double): Int {
val matrix = XYZ_TO_SRGB
val linearR = matrix[0][0] * x + matrix[0][1] * y + matrix[0][2] * z
val linearG = matrix[1][0] * x + matrix[1][1] * y + matrix[1][2] * z
val linearB = matrix[2][0] * x + matrix[2][1] * y + matrix[2][2] * z
val r = delinearized(linearR)
val g = delinearized(linearG)
val b = delinearized(linearB)
return argbFromRgb(r, g, b)
}
/** Converts a color from linear RGB components to ARGB format. */
fun argbFromLinrgb(linrgb: DoubleArray): Int {
val r = delinearized(linrgb[0])
val g = delinearized(linrgb[1])
val b = delinearized(linrgb[2])
return argbFromRgb(r, g, b)
}
/** Converts a color from linear RGB components to ARGB format. */
fun argbFromLinrgbComponents(r: Double, g: Double, b: Double): Int {
return argbFromRgb(delinearized(r), delinearized(g), delinearized(b))
}
/**
* Delinearizes an RGB component.
*
* @param rgbComponent 0.0 <= rgb_component <= 100.0, represents linear R/G/B channel
* @return 0 <= output <= 255, color channel converted to regular RGB space
*/
fun delinearized(rgbComponent: Double): Int {
val normalized = rgbComponent / 100.0
val delinearized = if (normalized <= 0.0031308) {
normalized * 12.92
} else {
1.055 * normalized.pow(1.0 / 2.4) - 0.055
}
return clampInt(0, 255, round(delinearized * 255.0).toInt())
}
/**
* Clamps an integer between two integers.
*
* @return input when min <= input <= max, and either min or max otherwise.
*/
fun clampInt(min: Int, max: Int, input: Int): Int {
if (input < min) {
return min
} else if (input > max) {
return max
}
return input
}
/** Converts a color from RGB components to ARGB format. */
fun argbFromRgb(red: Int, green: Int, blue: Int): Int {
return 255 shl 24 or (red and 255 shl 16) or (green and 255 shl 8) or (blue and 255)
}
fun intFromLstar(lstar: Double): Int {
if (lstar < 1) {
return -0x1000000
} else if (lstar > 99) {
return -0x1
}
// XYZ to LAB conversion routine, assume a and b are 0.
val fy = (lstar + 16.0) / 116.0
// fz = fx = fy because a and b are 0
val kappa = 24389f / 27f
val epsilon = 216f / 24389f
val lExceedsEpsilonKappa = lstar > 8.0f
val yT = if (lExceedsEpsilonKappa) fy * fy * fy else lstar / kappa
val cubeExceedEpsilon = fy * fy * fy > epsilon
val xT = if (cubeExceedEpsilon) fy * fy * fy else (116f * fy - 16f) / kappa
val zT = if (cubeExceedEpsilon) fy * fy * fy else (116f * fy - 16f) / kappa
return ColorUtils.XYZToColor(
(xT * WHITE_POINT_D65[0]),
(yT * WHITE_POINT_D65[1]), (zT * WHITE_POINT_D65[2])
)
}
/** Returns L* from L*a*b*, perceptual luminance, from an ARGB integer (ColorInt). */
fun lstarFromInt(argb: Int): Double {
return lstarFromY(yFromInt(argb))
}
fun lstarFromY(y: Double): Double {
val yMutable = y / 100.0
val e = 216.0 / 24389.0
val yIntermediate = if (yMutable <= e) {
return 24389.0 / 27.0 * yMutable
} else {
cbrt(yMutable)
}
return 116.0 * yIntermediate - 16.0
}
fun yFromInt(argb: Int): Double {
val r = linearized(Color.red(argb))
val g = linearized(Color.green(argb))
val b = linearized(Color.blue(argb))
val matrix = SRGB_TO_XYZ
val y = r * matrix[1][0] + g * matrix[1][1] + b * matrix[1][2]
return y
}
fun xyzFromInt(argb: Int): DoubleArray {
val r = linearized(Color.red(argb))
val g = linearized(Color.green(argb))
val b = linearized(Color.blue(argb))
val matrix = SRGB_TO_XYZ
val x = r * matrix[0][0] + g * matrix[0][1] + b * matrix[0][2]
val y = r * matrix[1][0] + g * matrix[1][1] + b * matrix[1][2]
val z = r * matrix[2][0] + g * matrix[2][1] + b * matrix[2][2]
return doubleArrayOf(x, y, z)
}
/**
* Converts an L* value to a Y value.
*
*
* L* in L*a*b* and Y in XYZ measure the same quantity, luminance.
*
*
* L* measures perceptual luminance, a linear scale. Y in XYZ measures relative luminance, a
* logarithmic scale.
*
* @param lstar L* in L*a*b*
* @return Y in XYZ
*/
fun yFromLstar(lstar: Double): Double {
val ke = 8.0
return if (lstar > ke) {
((lstar + 16.0) / 116.0).pow(3.0) * 100.0
} else {
lstar / (24389.0 / 27.0) * 100.0
}
}
fun linearized(rgbComponent: Int): Double {
val normalized = rgbComponent.toDouble() / 255.0
return if (normalized <= 0.04045) {
normalized / 12.92 * 100.0
} else {
((normalized + 0.055) / 1.055).pow(2.4) * 100.0
}
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/monet/ColorScheme.kt | Kotlin | @file:Suppress("unused", "MemberVisibilityCanBePrivate")
package dev.zwander.compose.monet
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.colorspace.ColorSpaces
import androidx.compose.ui.graphics.toArgb
import kotlin.math.absoluteValue
import kotlin.math.pow
import kotlin.math.roundToInt
const val ACCENT1_CHROMA = 48.0f
const val GOOGLE_BLUE = 0xFF1b6ef3.toInt()
const val MIN_CHROMA = 5
internal interface Hue {
fun get(sourceColor: Cam): Double
/**
* Given a hue, and a mapping of hues to hue rotations, find which hues in the mapping the
* hue fall betweens, and use the hue rotation of the lower hue.
*
* @param sourceHue hue of source color
* @param hueAndRotations list of pairs, where the first item in a pair is a hue, and the
* second item in the pair is a hue rotation that should be applied
*/
fun getHueRotation(sourceHue: Double, hueAndRotations: List<Pair<Int, Int>>): Double {
val sanitizedSourceHue = (if (sourceHue < 0 || sourceHue >= 360) 0.0 else sourceHue)
for (i in 0..hueAndRotations.size - 2) {
val thisHue = hueAndRotations[i].first
val nextHue = hueAndRotations[i + 1].first
if (thisHue <= sanitizedSourceHue && sanitizedSourceHue < nextHue) {
return ColorScheme.wrapDegreesDouble(sanitizedSourceHue + hueAndRotations[i].second)
}
}
// If this statement executes, something is wrong, there should have been a rotation
// found using the arrays.
return sourceHue
}
}
internal class HueSource : Hue {
override fun get(sourceColor: Cam): Double {
return sourceColor.hue
}
}
internal class HueAdd(val amountDegrees: Double) : Hue {
override fun get(sourceColor: Cam): Double {
return ColorScheme.wrapDegreesDouble(sourceColor.hue + amountDegrees)
}
}
internal class HueSubtract(val amountDegrees: Double) : Hue {
override fun get(sourceColor: Cam): Double {
return ColorScheme.wrapDegreesDouble(sourceColor.hue - amountDegrees)
}
}
internal class HueVibrantSecondary : Hue {
val hueToRotations = listOf(Pair(0, 18), Pair(41, 15), Pair(61, 10), Pair(101, 12),
Pair(131, 15), Pair(181, 18), Pair(251, 15), Pair(301, 12), Pair(360, 12))
override fun get(sourceColor: Cam): Double {
return getHueRotation(sourceColor.hue, hueToRotations)
}
}
internal class HueVibrantTertiary : Hue {
val hueToRotations = listOf(Pair(0, 35), Pair(41, 30), Pair(61, 20), Pair(101, 25),
Pair(131, 30), Pair(181, 35), Pair(251, 30), Pair(301, 25), Pair(360, 25))
override fun get(sourceColor: Cam): Double {
return getHueRotation(sourceColor.hue, hueToRotations)
}
}
internal class HueExpressiveSecondary : Hue {
val hueToRotations = listOf(Pair(0, 45), Pair(21, 95), Pair(51, 45), Pair(121, 20),
Pair(151, 45), Pair(191, 90), Pair(271, 45), Pair(321, 45), Pair(360, 45))
override fun get(sourceColor: Cam): Double {
return getHueRotation(sourceColor.hue, hueToRotations)
}
}
internal class HueExpressiveTertiary : Hue {
val hueToRotations = listOf(Pair(0, 120), Pair(21, 120), Pair(51, 20), Pair(121, 45),
Pair(151, 20), Pair(191, 15), Pair(271, 20), Pair(321, 120), Pair(360, 120))
override fun get(sourceColor: Cam): Double {
return getHueRotation(sourceColor.hue, hueToRotations)
}
}
internal interface Chroma {
fun get(sourceColor: Cam): Double
}
internal class ChromaMaxOut : Chroma {
override fun get(sourceColor: Cam): Double {
// Intentionally high. Gamut mapping from impossible HCT to sRGB will ensure that
// the maximum chroma is reached, even if lower than this constant.
return 130.0
}
}
internal class ChromaMultiple(val multiple: Double) : Chroma {
override fun get(sourceColor: Cam): Double {
return sourceColor.chroma * multiple
}
}
internal class ChromaConstant(val chroma: Double) : Chroma {
override fun get(sourceColor: Cam): Double {
return chroma
}
}
internal class ChromaSource : Chroma {
override fun get(sourceColor: Cam): Double {
return sourceColor.chroma
}
}
internal class TonalSpec(val hue: Hue = HueSource(), val chroma: Chroma) {
fun shades(sourceColor: Cam): List<Int> {
val hue = hue.get(sourceColor)
val chroma = chroma.get(sourceColor)
return Shades.of(hue, chroma).toList()
}
}
internal class CoreSpec(
val a1: TonalSpec,
val a2: TonalSpec,
val a3: TonalSpec,
val n1: TonalSpec,
val n2: TonalSpec
)
@Deprecated("Use dev.zwander.compose.libmonet.Style instead.")
enum class Style(internal val coreSpec: CoreSpec) {
SPRITZ(CoreSpec(
a1 = TonalSpec(HueSource(), ChromaConstant(12.0)),
a2 = TonalSpec(HueSource(), ChromaConstant(8.0)),
a3 = TonalSpec(HueSource(), ChromaConstant(16.0)),
n1 = TonalSpec(HueSource(), ChromaConstant(2.0)),
n2 = TonalSpec(HueSource(), ChromaConstant(2.0))
)),
TONAL_SPOT(CoreSpec(
a1 = TonalSpec(HueSource(), ChromaConstant(36.0)),
a2 = TonalSpec(HueSource(), ChromaConstant(16.0)),
a3 = TonalSpec(HueAdd(60.0), ChromaConstant(24.0)),
n1 = TonalSpec(HueSource(), ChromaConstant(4.0)),
n2 = TonalSpec(HueSource(), ChromaConstant(8.0))
)),
VIBRANT(CoreSpec(
a1 = TonalSpec(HueSource(), ChromaMaxOut()),
a2 = TonalSpec(HueVibrantSecondary(), ChromaConstant(24.0)),
a3 = TonalSpec(HueVibrantTertiary(), ChromaConstant(32.0)),
n1 = TonalSpec(HueSource(), ChromaConstant(10.0)),
n2 = TonalSpec(HueSource(), ChromaConstant(12.0))
)),
EXPRESSIVE(CoreSpec(
a1 = TonalSpec(HueAdd(240.0), ChromaConstant(40.0)),
a2 = TonalSpec(HueExpressiveSecondary(), ChromaConstant(24.0)),
a3 = TonalSpec(HueExpressiveTertiary(), ChromaConstant(32.0)),
n1 = TonalSpec(HueAdd(15.0), ChromaConstant(8.0)),
n2 = TonalSpec(HueAdd(15.0), ChromaConstant(12.0))
)),
RAINBOW(CoreSpec(
a1 = TonalSpec(HueSource(), ChromaConstant(48.0)),
a2 = TonalSpec(HueSource(), ChromaConstant(16.0)),
a3 = TonalSpec(HueAdd(60.0), ChromaConstant(24.0)),
n1 = TonalSpec(HueSource(), ChromaConstant(0.0)),
n2 = TonalSpec(HueSource(), ChromaConstant(0.0))
)),
FRUIT_SALAD(CoreSpec(
a1 = TonalSpec(HueSubtract(50.0), ChromaConstant(48.0)),
a2 = TonalSpec(HueSubtract(50.0), ChromaConstant(36.0)),
a3 = TonalSpec(HueSource(), ChromaConstant(36.0)),
n1 = TonalSpec(HueSource(), ChromaConstant(10.0)),
n2 = TonalSpec(HueSource(), ChromaConstant(16.0))
)),
CONTENT(CoreSpec(
a1 = TonalSpec(HueSource(), ChromaSource()),
a2 = TonalSpec(HueSource(), ChromaMultiple(0.33)),
a3 = TonalSpec(HueSource(), ChromaMultiple(0.66)),
n1 = TonalSpec(HueSource(), ChromaMultiple(0.0833)),
n2 = TonalSpec(HueSource(), ChromaMultiple(0.1666))
)),
}
@Deprecated("Use dev.zwander.compose.libmonet.ColorScheme instead.")
class ColorScheme(
val seed: Int,
val darkTheme: Boolean,
val style: Style = Style.TONAL_SPOT,
) {
val accent1: List<Int>
val accent2: List<Int>
val accent3: List<Int>
val neutral1: List<Int>
val neutral2: List<Int>
constructor(seed: Int, darkTheme: Boolean):
this(seed, darkTheme, Style.TONAL_SPOT)
constructor(
wallpaperColors: WallpaperColors,
darkTheme: Boolean,
style: Style = Style.TONAL_SPOT
): this(getSeedColor(wallpaperColors, style != Style.CONTENT), darkTheme, style)
val allAccentColors: List<Int>
get() {
val allColors = mutableListOf<Int>()
allColors.addAll(accent1)
allColors.addAll(accent2)
allColors.addAll(accent3)
return allColors
}
val allNeutralColors: List<Int>
get() {
val allColors = mutableListOf<Int>()
allColors.addAll(neutral1)
allColors.addAll(neutral2)
return allColors
}
val backgroundColor
get() = ColorUtils.setAlphaComponent(if (darkTheme) neutral1[8] else neutral1[0], 0xFF)
val accentColor
get() = ColorUtils.setAlphaComponent(if (darkTheme) accent1[2] else accent1[6], 0xFF)
init {
val proposedSeedCam = Cam.fromInt(seed)
val seedArgb = if (seed == Color.Transparent.toArgb()) {
GOOGLE_BLUE
} else if (style != Style.CONTENT && proposedSeedCam.chroma < 5) {
GOOGLE_BLUE
} else {
seed
}
val camSeed = Cam.fromInt(seedArgb)
accent1 = style.coreSpec.a1.shades(camSeed)
accent2 = style.coreSpec.a2.shades(camSeed)
accent3 = style.coreSpec.a3.shades(camSeed)
neutral1 = style.coreSpec.n1.shades(camSeed)
neutral2 = style.coreSpec.n2.shades(camSeed)
}
override fun toString(): String {
return "ColorScheme {\n" +
" seed color: ${stringForColor(seed)}\n" +
" style: $style\n" +
" palettes: \n" +
" ${humanReadable("PRIMARY", accent1)}\n" +
" ${humanReadable("SECONDARY", accent2)}\n" +
" ${humanReadable("TERTIARY", accent3)}\n" +
" ${humanReadable("NEUTRAL", neutral1)}\n" +
" ${humanReadable("NEUTRAL VARIANT", neutral2)}\n" +
"}"
}
fun toComposeColorScheme(): androidx.compose.material3.ColorScheme {
val paletteSize = accent1.size
fun getColor(type: Type, paletteIndex: Int, num: Int): Color {
val shades = when (type) {
Type.Accent -> allAccentColors
Type.Neutral -> allNeutralColors
}
val lum = when (num) {
10 -> 0
50 -> 1
else -> 1 + num / 100
}
return Color(
shades.filterIndexed { index, _ ->
val l = index % paletteSize
val idx = index / paletteSize + 1
l == lum && idx == paletteIndex
}.first()
)
}
return if (darkTheme) {
darkColorScheme(
primary = getColor(Type.Accent, 1, 200),
onPrimary = getColor(Type.Accent, 1, 800),
primaryContainer = getColor(Type.Accent, 1, 700),
onPrimaryContainer = getColor(Type.Accent, 1, 100),
inversePrimary = getColor(Type.Accent, 1, 600),
secondary = getColor(Type.Accent, 2, 200),
onSecondary = getColor(Type.Accent, 2, 800),
secondaryContainer = getColor(Type.Accent, 2, 700),
onSecondaryContainer = getColor(Type.Accent, 2, 100),
tertiary = getColor(Type.Accent, 3, 200),
onTertiary = getColor(Type.Accent, 3, 800),
tertiaryContainer = getColor(Type.Accent, 3, 700),
onTertiaryContainer = getColor(Type.Accent, 3, 100),
background = getColor(Type.Neutral, 1, 900),
onBackground = getColor(Type.Neutral, 1, 100),
surface = getColor(Type.Neutral, 1, 900),
onSurface = getColor(Type.Neutral, 1, 100),
surfaceVariant = getColor(Type.Neutral, 2, 700),
onSurfaceVariant = getColor(Type.Neutral, 2, 200),
inverseSurface = getColor(Type.Neutral, 1, 100),
inverseOnSurface = getColor(Type.Neutral, 1, 800),
outline = getColor(Type.Neutral, 2, 400),
surfaceContainerLowest = getColor(Type.Neutral, 2, 600),
surfaceContainer = getColor(Type.Neutral, 2, 600).setLuminance(4f),
surfaceContainerLow = getColor(Type.Neutral, 2, 900),
surfaceContainerHigh = getColor(Type.Neutral, 2, 600).setLuminance(17f),
outlineVariant = getColor(Type.Neutral, 2, 700),
scrim = getColor(Type.Neutral, 2, 1000),
surfaceBright = getColor(Type.Neutral, 2, 600).setLuminance(98f),
surfaceDim = getColor(Type.Neutral, 2, 600).setLuminance(6f),
surfaceTint = getColor(Type.Accent, 1, 200),
surfaceContainerHighest = getColor(Type.Neutral, 2, 600).setLuminance(22f),
)
} else {
lightColorScheme(
primary = getColor(Type.Accent, 1, 600),
onPrimary = getColor(Type.Accent, 1, 0),
primaryContainer = getColor(Type.Accent, 1, 100),
onPrimaryContainer = getColor(Type.Accent, 1, 900),
inversePrimary = getColor(Type.Accent, 1, 200),
secondary = getColor(Type.Accent, 2, 600),
onSecondary = getColor(Type.Accent, 2, 0),
secondaryContainer = getColor(Type.Accent, 2, 100),
onSecondaryContainer = getColor(Type.Accent, 2, 900),
tertiary = getColor(Type.Accent, 3, 600),
onTertiary = getColor(Type.Accent, 3, 0),
tertiaryContainer = getColor(Type.Accent, 3, 100),
onTertiaryContainer = getColor(Type.Accent, 3, 900),
background = getColor(Type.Neutral, 1, 10),
onBackground = getColor(Type.Neutral, 1, 900),
surface = getColor(Type.Neutral, 1, 10),
onSurface = getColor(Type.Neutral, 1, 900),
surfaceVariant = getColor(Type.Neutral, 2, 100),
onSurfaceVariant = getColor(Type.Neutral, 2, 700),
inverseSurface = getColor(Type.Neutral, 1, 800),
inverseOnSurface = getColor(Type.Neutral, 1, 50),
outline = getColor(Type.Neutral, 2, 500),
surfaceContainerLowest = getColor(Type.Neutral, 2, 0),
surfaceContainer = getColor(Type.Neutral, 2, 600).setLuminance(94f),
surfaceContainerLow = getColor(Type.Neutral, 2, 600).setLuminance(96f),
surfaceContainerHigh = getColor(Type.Neutral, 2, 600).setLuminance(92f),
outlineVariant = getColor(Type.Neutral, 2, 200),
scrim = getColor(Type.Neutral, 2, 1000),
surfaceBright = getColor(Type.Neutral, 2, 600).setLuminance(98f),
surfaceDim = getColor(Type.Neutral, 2, 600).setLuminance(87f),
surfaceTint = getColor(Type.Accent, 1, 600),
surfaceContainerHighest = getColor(Type.Neutral, 2, 100),
)
}
}
internal fun Color.setLuminance(newLuminance: Float): Color {
if ((newLuminance < 0.0001) or (newLuminance > 99.9999)) {
// aRGBFromLstar() from monet ColorUtil.java
val y = 100 * labInvf((newLuminance + 16) / 116)
val component = delinearized(y)
return Color(
/* red = */ component,
/* green = */ component,
/* blue = */ component,
)
}
val sLAB = this.convert(ColorSpaces.CieLab)
return Color(
/* luminance = */ newLuminance,
/* a = */ sLAB.component2(),
/* b = */ sLAB.component3(),
colorSpace = ColorSpaces.CieLab
)
.convert(ColorSpaces.Srgb)
}
private fun labInvf(ft: Float): Float {
val e = 216f / 24389f
val kappa = 24389f / 27f
val ft3 = ft * ft * ft
return if (ft3 > e) {
ft3
} else {
(116 * ft - 16) / kappa
}
}
private fun delinearized(rgbComponent: Float): Int {
val normalized = rgbComponent / 100
val delinearized =
if (normalized <= 0.0031308) {
normalized * 12.92
} else {
1.055 * normalized.toDouble().pow(1.0 / 2.4) - 0.055
}
return (delinearized * 255.0).roundToInt().coerceAtLeast(0).coerceAtMost(255)
}
companion object {
enum class Type {
Accent,
Neutral,
}
/**
* Identifies a color to create a color scheme from.
*
* @param wallpaperColors Colors extracted from an image via quantization.
* @param filter If false, allow colors that have low chroma, creating grayscale themes.
* @return ARGB int representing the color
*/
fun getSeedColor(wallpaperColors: WallpaperColors, filter: Boolean = true): Int {
return getSeedColors(wallpaperColors, filter).first()
}
/**
* Filters and ranks colors from WallpaperColors.
*
* @param wallpaperColors Colors extracted from an image via quantization.
* @param filter If false, allow colors that have low chroma, creating grayscale themes.
* @return List of ARGB ints, ordered from highest scoring to lowest.
*/
fun getSeedColors(wallpaperColors: WallpaperColors, filter: Boolean = true): List<Int> {
val totalPopulation = wallpaperColors.allColors.values.reduce { a, b -> a + b }
val totalPopulationMeaningless = (totalPopulation.toDouble() == 0.0)
if (totalPopulationMeaningless) {
// WallpaperColors with a population of 0 indicate the colors didn't come from
// quantization. Instead of scoring, trust the ordering of the provided primary
// secondary/tertiary colors.
//
// In this case, the colors are usually from a Live Wallpaper.
val distinctColors = wallpaperColors.mainColors.map {
it.toArgb()
}.distinct().filter {
!filter || Cam.fromInt(it).chroma >= MIN_CHROMA
}.toList()
if (distinctColors.isEmpty()) {
return listOf(GOOGLE_BLUE)
}
return distinctColors
}
val intToProportion = wallpaperColors.allColors.mapValues {
it.value / totalPopulation.toDouble()
}
val intToCam = wallpaperColors.allColors.mapValues { Cam.fromInt(it.key) }
// Get an array with 360 slots. A slot contains the percentage of colors with that hue.
val hueProportions = huePopulations(intToCam, intToProportion, filter)
// Map each color to the percentage of the image with its hue.
val intToHueProportion = wallpaperColors.allColors.mapValues {
val cam = intToCam[it.key]!!
val hue = cam.hue.roundToInt()
var proportion = 0.0
for (i in hue - 15..hue + 15) {
proportion += hueProportions[wrapDegrees(i)]
}
proportion
}
// Remove any inappropriate seed colors. For example, low chroma colors look grayscale
// raising their chroma will turn them to a much louder color that may not have been
// in the image.
val filteredIntToCam = if (!filter) intToCam else (intToCam.filter {
val cam = it.value
val proportion = intToHueProportion[it.key]!!
cam.chroma >= MIN_CHROMA &&
(totalPopulationMeaningless || proportion > 0.01)
})
// Sort the colors by score, from high to low.
val intToScoreIntermediate = filteredIntToCam.mapValues {
score(it.value, intToHueProportion[it.key]!!)
}
val intToScore = intToScoreIntermediate.entries.toMutableList()
intToScore.sortByDescending { it.value }
// Go through the colors, from high score to low score.
// If the color is distinct in hue from colors picked so far, pick the color.
// Iteratively decrease the amount of hue distinctness required, thus ensuring we
// maximize difference between colors.
val minimumHueDistance = 15
val seeds = mutableListOf<Int>()
maximizeHueDistance@ for (i in 90 downTo minimumHueDistance step 1) {
seeds.clear()
for (entry in intToScore) {
val int = entry.key
val existingSeedNearby = seeds.find {
val hueA = intToCam[int]!!.hue
val hueB = intToCam[it]!!.hue
hueDiff(hueA, hueB) < i } != null
if (existingSeedNearby) {
continue
}
seeds.add(int)
if (seeds.size >= 4) {
break@maximizeHueDistance
}
}
}
if (seeds.isEmpty()) {
// Use gBlue 500 if there are 0 colors
seeds.add(GOOGLE_BLUE)
}
return seeds
}
private fun wrapDegrees(degrees: Int): Int {
return when {
degrees < 0 -> {
(degrees % 360) + 360
}
degrees >= 360 -> {
degrees % 360
}
else -> {
degrees
}
}
}
fun wrapDegreesDouble(degrees: Double): Double {
return when {
degrees < 0 -> {
(degrees % 360) + 360
}
degrees >= 360 -> {
degrees % 360
}
else -> {
degrees
}
}
}
private fun hueDiff(a: Double, b: Double): Double {
return 180.0 - ((a - b).absoluteValue - 180.0).absoluteValue
}
@OptIn(ExperimentalStdlibApi::class)
private fun stringForColor(color: Int): String {
val width = 4
val hct = Cam.fromInt(color)
val h = "H${hct.hue.roundToInt().toString().padEnd(width)}"
val c = "C${hct.chroma.roundToInt().toString().padEnd(width)}"
val t = "T${CamUtils.lstarFromInt(color).roundToInt().toString().padEnd(width)}"
val hex = (color and 0xffffff).toHexString().uppercase()
return "$h$c$t = #$hex"
}
private fun humanReadable(paletteName: String, colors: List<Int>): String {
return "$paletteName\n" + colors.map {
stringForColor(it)
}.joinToString(separator = "\n") { it }
}
private fun score(cam: Cam, proportion: Double): Double {
val proportionScore = 0.7 * 100.0 * proportion
val chromaScore = if (cam.chroma < ACCENT1_CHROMA) 0.1 * (cam.chroma - ACCENT1_CHROMA)
else 0.3 * (cam.chroma - ACCENT1_CHROMA)
return chromaScore + proportionScore
}
private fun huePopulations(
camByColor: Map<Int, Cam>,
populationByColor: Map<Int, Double>,
filter: Boolean = true
): List<Double> {
val huePopulation = List(size = 360, init = { 0.0 }).toMutableList()
for (entry in populationByColor.entries) {
val population = populationByColor[entry.key]!!
val cam = camByColor[entry.key]!!
val hue = cam.hue.roundToInt() % 360
if (filter && cam.chroma <= MIN_CHROMA) {
continue
}
huePopulation[hue] = huePopulation[hue] + population
}
return huePopulation
}
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/monet/ColorUtils.kt | Kotlin | package dev.zwander.compose.monet
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
import kotlin.math.pow
import kotlin.math.round
@Suppress("FunctionName", "MemberVisibilityCanBePrivate")
object ColorUtils {
fun XYZToColor(
x: Double,
y: Double,
z: Double
): Int {
var r = (x * 3.2406 + y * -1.5372 + z * -0.4986) / 100
var g = (x * -0.9689 + y * 1.8758 + z * 0.0415) / 100
var b = (x * 0.0557 + y * -0.2040 + z * 1.0570) / 100
r = if (r > 0.0031308) 1.055 * r.pow(1 / 2.4) - 0.055 else 12.92 * r
g = if (g > 0.0031308) 1.055 * g.pow(1 / 2.4) - 0.055 else 12.92 * g
b = if (b > 0.0031308) 1.055 * b.pow(1 / 2.4) - 0.055 else 12.92 * b
return Color(
red = r.coerceIn(0.0, 1.0).toFloat(),
green = g.coerceIn(0.0, 1.0).toFloat(),
blue = b.coerceIn(0.0, 1.0).toFloat(),
).toArgb()
}
/**
* Convert a color appearance model representation to an ARGB color.
*
* Note: the returned color may have a lower chroma than requested. Whether a chroma is
* available depends on luminance. For example, there's no such thing as a high chroma light
* red, due to the limitations of our eyes and/or physics. If the requested chroma is
* unavailable, the highest possible chroma at the requested luminance is returned.
*
* @param hue hue, in degrees, in CAM coordinates
* @param chroma chroma in CAM coordinates.
* @param lstar perceptual luminance, L* in L*a*b*
*/
fun CAMToColor(hue: Double, chroma: Double, lstar: Double): Int {
return Cam.getInt(hue, chroma, lstar)
}
/**
* Convert the ARGB color to its HSL (hue-saturation-lightness) components.
*
* * outHsl[0] is Hue [0 .. 360)
* * outHsl[1] is Saturation [0...1]
* * outHsl[2] is Lightness [0...1]
*
*
* @param color the ARGB color to convert. The alpha component is ignored
* @param outHsl 3-element array which holds the resulting HSL components
*/
fun colorToHSL(color: Int, outHsl: DoubleArray) {
val c = Color(color)
RGBToHSL(
(c.red * 255).toInt(),
(c.green * 255).toInt(),
(c.blue * 255).toInt(),
outHsl
)
}
/**
* Convert RGB components to HSL (hue-saturation-lightness).
*
* * outHsl[0] is Hue [0 .. 360)
* * outHsl[1] is Saturation [0...1]
* * outHsl[2] is Lightness [0...1]
*
*
* @param r red component value [0..255]
* @param g green component value [0..255]
* @param b blue component value [0..255]
* @param outHsl 3-element array which holds the resulting HSL components
*/
fun RGBToHSL(
r: Int,
g: Int,
b: Int,
outHsl: DoubleArray
) {
val rf = r / 255.0
val gf = g / 255.0
val bf = b / 255.0
val max: Double = max(rf, max(gf, bf))
val min: Double = min(rf, min(gf, bf))
val deltaMaxMin = max - min
var h: Double
val s: Double
val l = (max + min) / 2f
if (max == min) {
// Monochromatic
s = 0.0
h = s
} else {
h = when (max) {
rf -> {
(gf - bf) / deltaMaxMin % 6f
}
gf -> {
(bf - rf) / deltaMaxMin + 2f
}
else -> {
(rf - gf) / deltaMaxMin + 4f
}
}
s = deltaMaxMin / (1f - abs(2f * l - 1f))
}
h = h * 60f % 360f
if (h < 0) {
h += 360f
}
outHsl[0] = h.coerceIn(0.0, 360.0)
outHsl[1] = s.coerceIn(0.0, 1.0)
outHsl[2] = l.coerceIn(0.0, 1.0)
}
/**
* Set the alpha component of `color` to be `alpha`.
*/
fun setAlphaComponent(
color: Int,
alpha: Int
): Int {
if (alpha < 0 || alpha > 255) {
throw IllegalArgumentException("alpha must be between 0 and 255.")
}
return color and 0x00ffffff or (alpha shl 24)
}
/**
* Convert HSL (hue-saturation-lightness) components to a RGB color.
*
* * hsl[0] is Hue [0 .. 360)
* * hsl[1] is Saturation [0...1]
* * hsl[2] is Lightness [0...1]
*
* If hsv values are out of range, they are pinned.
*
* @param hsl 3-element array which holds the input HSL components
* @return the resulting RGB color
*/
fun HSLToColor(hsl: DoubleArray): Int {
val h = hsl[0]
val s = hsl[1]
val l = hsl[2]
val c = ((1f - abs((2 * l - 1f))) * s).toFloat()
val m = l - 0.5f * c
val x = (c * (1f - abs(((h / 60f % 2f) - 1f)))).toFloat()
val hueSegment = h.toInt() / 60
var r = 0
var g = 0
var b = 0
when (hueSegment) {
0 -> {
r = round(255 * (c + m)).toInt()
g = round(255 * (x + m)).toInt()
b = round(255 * m).toInt()
}
1 -> {
r = round(255 * (x + m)).toInt()
g = round(255 * (c + m)).toInt()
b = round(255 * m).toInt()
}
2 -> {
r = round(255 * m).toInt()
g = round(255 * (c + m)).toInt()
b = round(255 * (x + m)).toInt()
}
3 -> {
r = round(255 * m).toInt()
g = round(255 * (x + m)).toInt()
b = round(255 * (c + m)).toInt()
}
4 -> {
r = round(255 * (x + m)).toInt()
g = round(255 * m).toInt()
b = round(255 * (c + m)).toInt()
}
5, 6 -> {
r = round(255 * (c + m)).toInt()
g = round(255 * m).toInt()
b = round(255 * (x + m)).toInt()
}
}
r = r.coerceIn(0..255)
g = g.coerceIn(0..255)
b = b.coerceIn(0..255)
return Color(r, g, b).toArgb()
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/monet/Frame.kt | Kotlin | package dev.zwander.compose.monet
import kotlin.math.PI
import kotlin.math.cbrt
import kotlin.math.exp
import kotlin.math.sqrt
/**
* The frame, or viewing conditions, where a color was seen. Used, along with a color, to create a
* color appearance model representing the color.
*
*
* To convert a traditional color to a color appearance model, it requires knowing what
* conditions the color was observed in. Our perception of color depends on, for example, the tone
* of the light illuminating the color, how bright that light was, etc.
*
*
* This class is modelled separately from the color appearance model itself because there are a
* number of calculations during the color => CAM conversion process that depend only on the viewing
* conditions. Caching those calculations in a Frame instance saves a significant amount of time.
*/
class Frame private constructor(
val n: Double,
val aw: Double,
val nbb: Double,
val ncb: Double,
val c: Double,
val nc: Double,
val rgbD: DoubleArray,
val fl: Double,
val flRoot: Double,
val z: Double
) {
companion object {
// Standard viewing conditions assumed in RGB specification - Stokes, Anderson, Chandrasekar,
// Motta - A Standard Default Color Space for the Internet: sRGB, 1996.
//
// White point = D65
// Luminance of adapting field: 200 / Pi / 5, units are cd/m^2.
// sRGB ambient illuminance = 64 lux (per sRGB spec). However, the spec notes this is
// artificially low and based on monitors in 1990s. Use 200, the sRGB spec says this is the
// real average, and a survey of lux values on Wikipedia confirms this is a comfortable
// default: somewhere between a very dark overcast day and office lighting.
// Per CAM16 introduction paper (Li et al, 2017) Ew = pi * lw, and La = lw * Yb/Yw
// Ew = ambient environment luminance, in lux.
// Yb/Yw is taken to be midgray, ~20% relative luminance (XYZ Y 18.4, CIELAB L* 50).
// Therefore La = (Ew / pi) * .184
// La = 200 / pi * .184
// Image surround to 10 degrees = ~20% relative luminance = CIELAB L* 50
//
// Not from sRGB standard:
// Surround = average, 2.0.
// Discounting illuminant = false, doesn't occur for self-luminous displays
val DEFAULT = make(
CamUtils.WHITE_POINT_D65,
(200.0 / PI * CamUtils.yFromLstar(50.0) / 100.0),
50.0,
2.0,
false
)
/** Create a custom frame. */
fun make(
whitepoint: DoubleArray, adaptingLuminance: Double,
backgroundLstar: Double, surround: Double, discountingIlluminant: Boolean
): Frame {
// Transform white point XYZ to 'cone'/'rgb' responses
val matrix = CamUtils.XYZ_TO_CAM16RGB
val rW =
whitepoint[0] * matrix[0][0] + whitepoint[1] * matrix[0][1] + whitepoint[2] * matrix[0][2]
val gW =
whitepoint[0] * matrix[1][0] + whitepoint[1] * matrix[1][1] + whitepoint[2] * matrix[1][2]
val bW =
whitepoint[0] * matrix[2][0] + whitepoint[1] * matrix[2][1] + whitepoint[2] * matrix[2][2]
// Scale input surround, domain (0, 2), to CAM16 surround, domain (0.8, 1.0)
val f = 0.8 + surround / 10.0
// "Exponential non-linearity"
val c: Double = if (f >= 0.9) lerp(
0.59, 0.69,
(f - 0.9) * 10.0
) else lerp(
0.525, 0.59, (f - 0.8) * 10.0
)
// Calculate degree of adaptation to illuminant
var d =
if (discountingIlluminant) 1.0 else f * (1.0 - 1.0f / 3.6 * exp(
((-adaptingLuminance - 42.0) / 92.0)
))
// Per Li et al, if D is greater than 1 or less than 0, set it to 1 or 0.
d = if (d > 1.0) 1.0 else if (d < 0.0) 0.0 else d
// Chromatic induction factor
// Cone responses to the whitepoint, adjusted for illuminant discounting.
//
// Why use 100.0 instead of the white point's relative luminance?
//
// Some papers and implementations, for both CAM02 and CAM16, use the Y
// value of the reference white instead of 100. Fairchild's Color Appearance
// Models (3rd edition) notes that this is in error: it was included in the
// CIE 2004a report on CIECAM02, but, later parts of the conversion process
// account for scaling of appearance relative to the white point relative
// luminance. This part should simply use 100 as luminance.
val rgbD = doubleArrayOf(
d * (100.0 / rW) + 1.0 - d, d * (100.0 / gW) + 1.0 - d,
d * (100.0 / bW) + 1.0 - d
)
// Luminance-level adaptation factor
val k = 1.0 / (5.0 * adaptingLuminance + 1.0)
val k4 = k * k * k * k
val k4F = 1.0 - k4
val fl: Double = k4 * adaptingLuminance + 0.1 * k4F * k4F * cbrt(
5.0 * adaptingLuminance
)
// Intermediate factor, ratio of background relative luminance to white relative luminance
val n = CamUtils.yFromLstar(backgroundLstar) / whitepoint[1]
// Base exponential nonlinearity
// note Schlomer 2018 has a typo and uses 1.58, the correct factor is 1.48
val z: Double = 1.48 + sqrt(n)
// Luminance-level induction factors
val nbb: Double = 0.725 / pow(n, 0.2)
// Discounted cone responses to the white point, adjusted for post-chromatic
// adaptation perceptual nonlinearities.
val rgbAFactors = doubleArrayOf(
pow(fl * rgbD[0] * rW / 100.0, 0.42),
pow(fl * rgbD[1] * gW / 100.0, 0.42),
pow(
fl * rgbD[2] * bW / 100.0, 0.42
),
)
val rgbA = doubleArrayOf(
400.0 * rgbAFactors[0] / (rgbAFactors[0] + 27.13),
400.0 * rgbAFactors[1] / (rgbAFactors[1] + 27.13),
400.0 * rgbAFactors[2] / (rgbAFactors[2] + 27.13)
)
val aw = (2.0 * rgbA[0] + rgbA[1] + 0.05 * rgbA[2]) * nbb
return Frame(
n,
aw,
nbb,
nbb,
c,
f,
rgbD,
fl,
pow(fl, 0.25),
z
)
}
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/monet/HctSolver.kt | Kotlin | package dev.zwander.compose.monet
import kotlin.math.PI
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.ceil
import kotlin.math.cos
import kotlin.math.floor
import kotlin.math.max
import kotlin.math.sin
import kotlin.math.sqrt
/**
* An efficient algorithm for determining the closest sRGB color to a set of HCT coordinates,
* based on geometrical insights for finding intersections in linear RGB, CAM16, and L*a*b*.
*
* Algorithm identified and implemented by Tianguang Zhang.
* Copied from //java/com/google/ux/material/libmonet/hct on May 22 2022.
* ColorUtils/MathUtils functions that were required were added to CamUtils.
*/
object HctSolver {
// Matrix used when converting from linear RGB to CAM16.
private val SCALED_DISCOUNT_FROM_LINRGB = arrayOf(
doubleArrayOf(
0.001200833568784504, 0.002389694492170889, 0.0002795742885861124
), doubleArrayOf(
0.0005891086651375999, 0.0029785502573438758, 0.0003270666104008398
), doubleArrayOf(
0.00010146692491640572, 0.0005364214359186694, 0.0032979401770712076
)
)
// Matrix used when converting from CAM16 to linear RGB.
private val LINRGB_FROM_SCALED_DISCOUNT = arrayOf(
doubleArrayOf(
1373.2198709594231, -1100.4251190754821, -7.278681089101213
), doubleArrayOf(
-271.815969077903, 559.6580465940733, -32.46047482791194
), doubleArrayOf(
1.9622899599665666, -57.173814538844006, 308.7233197812385
)
)
// Weights for transforming a set of linear RGB coordinates to Y in XYZ.
private val Y_FROM_LINRGB = doubleArrayOf(0.2126, 0.7152, 0.0722)
// Lookup table for plane in XYZ's Y axis (relative luminance) that corresponds to a given
// L* in L*a*b*. HCT's T is L*, and XYZ's Y is directly correlated to linear RGB, this table
// allows us to thus find the intersection between HCT and RGB, giving a solution to the
// RGB coordinates that correspond to a given set of HCT coordinates.
private val CRITICAL_PLANES = doubleArrayOf(
0.015176349177441876,
0.045529047532325624,
0.07588174588720938,
0.10623444424209313,
0.13658714259697685,
0.16693984095186062,
0.19729253930674434,
0.2276452376616281,
0.2579979360165119,
0.28835063437139563,
0.3188300904430532,
0.350925934958123,
0.3848314933096426,
0.42057480301049466,
0.458183274052838,
0.4976837250274023,
0.5391024159806381,
0.5824650784040898,
0.6277969426914107,
0.6751227633498623,
0.7244668422128921,
0.775853049866786,
0.829304845476233,
0.8848452951698498,
0.942497089126609,
1.0022825574869039,
1.0642236851973577,
1.1283421258858297,
1.1946592148522128,
1.2631959812511864,
1.3339731595349034,
1.407011200216447,
1.4823302800086415,
1.5599503113873272,
1.6398909516233677,
1.7221716113234105,
1.8068114625156377,
1.8938294463134073,
1.9832442801866852,
2.075074464868551,
2.1693382909216234,
2.2660538449872063,
2.36523901573795,
2.4669114995532007,
2.5710888059345764,
2.6777882626779785,
2.7870270208169257,
2.898822059350997,
3.0131901897720907,
3.1301480604002863,
3.2497121605402226,
3.3718988244681087,
3.4967242352587946,
3.624204428461639,
3.754355295633311,
3.887192587735158,
4.022731918402185,
4.160988767090289,
4.301978482107941,
4.445716283538092,
4.592217266055746,
4.741496401646282,
4.893568542229298,
5.048448422192488,
5.20615066083972,
5.3666897647573375,
5.5300801301023865,
5.696336044816294,
5.865471690767354,
6.037501145825082,
6.212438385869475,
6.390297286737924,
6.571091626112461,
6.7548350853498045,
6.941541251256611,
7.131223617812143,
7.323895587840543,
7.5195704746346665,
7.7182615035334345,
7.919981813454504,
8.124744458384042,
8.332562408825165,
8.543448553206703,
8.757415699253682,
8.974476575321063,
9.194643831691977,
9.417930041841839,
9.644347703669503,
9.873909240696694,
10.106627003236781,
10.342513269534024,
10.58158024687427,
10.8238400726681,
11.069304815507364,
11.317986476196008,
11.569896988756009,
11.825048221409341,
12.083451977536606,
12.345119996613247,
12.610063955123938,
12.878295467455942,
13.149826086772048,
13.42466730586372,
13.702830557985108,
13.984327217668513,
14.269168601521828,
14.55736596900856,
14.848930523210871,
15.143873411576273,
15.44220572664832,
15.743938506781891,
16.04908273684337,
16.35764934889634,
16.66964922287304,
16.985093187232053,
17.30399201960269,
17.62635644741625,
17.95219714852476,
18.281524751807332,
18.614349837764564,
18.95068293910138,
19.290534541298456,
19.633915083172692,
19.98083495742689,
20.331304511189067,
20.685334046541502,
21.042933821039977,
21.404114048223256,
21.76888489811322,
22.137256497705877,
22.50923893145328,
22.884842241736916,
23.264076429332462,
23.6469514538663,
24.033477234264016,
24.42366364919083,
24.817520537484558,
25.21505769858089,
25.61628489293138,
26.021211842414342,
26.429848230738664,
26.842203703840827,
27.258287870275353,
27.678110301598522,
28.10168053274597,
28.529008062403893,
28.96010235337422,
29.39497283293396,
29.83362889318845,
30.276079891419332,
30.722335150426627,
31.172403958865512,
31.62629557157785,
32.08401920991837,
32.54558406207592,
33.010999283389665,
33.4802739966603,
33.953417292456834,
34.430438229418264,
34.911345834551085,
35.39614910352207,
35.88485700094671,
36.37747846067349,
36.87402238606382,
37.37449765026789,
37.87891309649659,
38.38727753828926,
38.89959975977785,
39.41588851594697,
39.93615253289054,
40.460400508064545,
40.98864111053629,
41.520882981230194,
42.05713473317016,
42.597404951718396,
43.141702194811224,
43.6900349931913,
44.24241185063697,
44.798841244188324,
45.35933162437017,
45.92389141541209,
46.49252901546552,
47.065252796817916,
47.64207110610409,
48.22299226451468,
48.808024568002054,
49.3971762874833,
49.9904556690408,
50.587870934119984,
51.189430279724725,
51.79514187861014,
52.40501387947288,
53.0190544071392,
53.637271562750364,
54.259673423945976,
54.88626804504493,
55.517063457223934,
56.15206766869424,
56.79128866487574,
57.43473440856916,
58.08241284012621,
58.734331877617365,
59.39049941699807,
60.05092333227251,
60.715611475655585,
61.38457167773311,
62.057811747619894,
62.7353394731159,
63.417162620860914,
64.10328893648692,
64.79372614476921,
65.48848194977529,
66.18756403501224,
66.89098006357258,
67.59873767827808,
68.31084450182222,
69.02730813691093,
69.74813616640164,
70.47333615344107,
71.20291564160104,
71.93688215501312,
72.67524319850172,
73.41800625771542,
74.16517879925733,
74.9167682708136,
75.67278210128072,
76.43322770089146,
77.1981124613393,
77.96744375590167,
78.74122893956174,
79.51947534912904,
80.30219030335869,
81.08938110306934,
81.88105503125999,
82.67721935322541,
83.4778813166706,
84.28304815182372,
85.09272707154808,
85.90692527145302,
86.72564993000343,
87.54890820862819,
88.3767072518277,
89.2090541872801,
90.04595612594655,
90.88742016217518,
91.73345337380438,
92.58406282226491,
93.43925555268066,
94.29903859396902,
95.16341895893969,
96.03240364439274,
96.9059996312159,
97.78421388448044,
98.6670533535366,
99.55452497210776
)
/**
* Sanitizes a small enough angle in radians.
*
* @param angle An angle in radians; must not deviate too much from 0.
* @return A coterminal angle between 0 and 2pi.
*/
fun sanitizeRadians(angle: Double): Double {
return (angle + PI * 8) % (PI * 2)
}
/**
* Delinearizes an RGB component, returning a floating-point number.
*
* @param rgbComponent 0.0 <= rgb_component <= 100.0, represents linear R/G/B channel
* @return 0.0 <= output <= 255.0, color channel converted to regular RGB space
*/
fun trueDelinearized(rgbComponent: Double): Double {
val normalized = rgbComponent / 100.0
val delinearized = if (normalized <= 0.0031308) {
normalized * 12.92
} else {
1.055 * pow(normalized, 1.0 / 2.4) - 0.055
}
return delinearized * 255.0
}
fun chromaticAdaptation(component: Double): Double {
val af: Double = pow(abs(component), 0.42)
return CamUtils.signum(component) * 400.0 * af / (af + 27.13)
}
/**
* Returns the hue of a linear RGB color in CAM16.
*
* @param linrgb The linear RGB coordinates of a color.
* @return The hue of the color in CAM16, in radians.
*/
fun hueOf(linrgb: DoubleArray): Double {
// Calculate scaled discount components using in-lined matrix multiplication to avoid
// an array allocation.
val matrix = SCALED_DISCOUNT_FROM_LINRGB
val rD = linrgb[0] * matrix[0][0] + linrgb[1] * matrix[0][1] + linrgb[2] * matrix[0][2]
val gD = linrgb[0] * matrix[1][0] + linrgb[1] * matrix[1][1] + linrgb[2] * matrix[1][2]
val bD = linrgb[0] * matrix[2][0] + linrgb[1] * matrix[2][1] + linrgb[2] * matrix[2][2]
val rA = chromaticAdaptation(rD)
val gA = chromaticAdaptation(gD)
val bA = chromaticAdaptation(bD)
// redness-greenness
val a = (11.0 * rA + -12.0 * gA + bA) / 11.0
// yellowness-blueness
val b = (rA + gA - 2.0 * bA) / 9.0
return atan2(b, a)
}
/**
* Cyclic order is the idea that 330° → 5° → 200° is in order, but, 180° → 270° → 210° is not.
* Visually, A B and C are angles, and they are in cyclic order if travelling from A to C
* in a way that increases angle (ex. counter-clockwise if +x axis = 0 degrees and +y = 90)
* means you must cross B.
* @param a first angle in possibly cyclic triplet
* @param b second angle in possibly cyclic triplet
* @param c third angle in possibly cyclic triplet
* @return true if B is between A and C
*/
fun areInCyclicOrder(a: Double, b: Double, c: Double): Boolean {
val deltaAB = sanitizeRadians(b - a)
val deltaAC = sanitizeRadians(c - a)
return deltaAB < deltaAC
}
/**
* Find an intercept using linear interpolation.
*
* @param source The starting number.
* @param mid The number in the middle.
* @param target The ending number.
* @return A number t such that lerp(source, target, t) = mid.
*/
fun intercept(source: Double, mid: Double, target: Double): Double {
return if (target == source) {
target
} else (mid - source) / (target - source)
}
/**
* Linearly interpolate between two points in three dimensions.
*
* @param source three dimensions representing the starting point
* @param t the percentage to travel between source and target, from 0 to 1
* @param target three dimensions representing the end point
* @return three dimensions representing the point t percent from source to target.
*/
fun lerpPoint(source: DoubleArray, t: Double, target: DoubleArray): DoubleArray {
return doubleArrayOf(
source[0] + (target[0] - source[0]) * t,
source[1] + (target[1] - source[1]) * t,
source[2] + (target[2] - source[2]) * t
)
}
/**
* Intersects a segment with a plane.
*
* @param source The coordinates of point A.
* @param coordinate The R-, G-, or B-coordinate of the plane.
* @param target The coordinates of point B.
* @param axis The axis the plane is perpendicular with. (0: R, 1: G, 2: B)
* @return The intersection point of the segment AB with the plane R=coordinate, G=coordinate,
* or B=coordinate
*/
fun setCoordinate(
source: DoubleArray,
coordinate: Double,
target: DoubleArray,
axis: Int
): DoubleArray {
val t = intercept(source[axis], coordinate, target[axis])
return lerpPoint(source, t, target)
}
/** Ensure X is between 0 and 100. */
fun isBounded(x: Double): Boolean {
return x in 0.0..100.0
}
/**
* Returns the nth possible vertex of the polygonal intersection.
*
* @param y The Y value of the plane.
* @param n The zero-based index of the point. 0 <= n <= 11.
* @return The nth possible vertex of the polygonal intersection of the y plane and the RGB cube
* in linear RGB coordinates, if it exists. If the possible vertex lies outside of the cube,
* [-1.0, -1.0, -1.0] is returned.
*/
fun nthVertex(y: Double, n: Int): DoubleArray {
val kR = Y_FROM_LINRGB[0]
val kG = Y_FROM_LINRGB[1]
val kB = Y_FROM_LINRGB[2]
val coordA = if (n % 4 <= 1) 0.0 else 100.0
val coordB = if (n % 2 == 0) 0.0 else 100.0
return if (n < 4) {
val r = (y - coordA * kG - coordB * kB) / kR
if (isBounded(r)) {
doubleArrayOf(r, coordA, coordB)
} else {
doubleArrayOf(-1.0, -1.0, -1.0)
}
} else if (n < 8) {
val g = (y - coordB * kR - coordA * kB) / kG
if (isBounded(g)) {
doubleArrayOf(coordB, g, coordA)
} else {
doubleArrayOf(-1.0, -1.0, -1.0)
}
} else {
val b = (y - coordA * kR - coordB * kG) / kB
if (isBounded(b)) {
doubleArrayOf(coordA, coordB, b)
} else {
doubleArrayOf(-1.0, -1.0, -1.0)
}
}
}
/**
* Finds the segment containing the desired color.
*
* @param y The Y value of the color.
* @param targetHue The hue of the color.
* @return A list of two sets of linear RGB coordinates, each corresponding to an endpoint of
* the segment containing the desired color.
*/
fun bisectToSegment(y: Double, targetHue: Double): Array<DoubleArray> {
var left = doubleArrayOf(-1.0, -1.0, -1.0)
var right = left
var leftHue = 0.0
var rightHue = 0.0
var initialized = false
var uncut = true
for (n in 0..11) {
val mid = nthVertex(y, n)
if (mid[0] < 0) {
continue
}
val midHue = hueOf(mid)
if (!initialized) {
left = mid
right = mid
leftHue = midHue
rightHue = midHue
initialized = true
continue
}
if (uncut || areInCyclicOrder(leftHue, midHue, rightHue)) {
uncut = false
if (areInCyclicOrder(leftHue, targetHue, midHue)) {
right = mid
rightHue = midHue
} else {
left = mid
leftHue = midHue
}
}
}
return arrayOf(left, right)
}
fun criticalPlaneBelow(x: Double): Int {
return floor(x - 0.5).toInt()
}
fun criticalPlaneAbove(x: Double): Int {
return ceil(x - 0.5).toInt()
}
/**
* Finds a color with the given Y and hue on the boundary of the cube.
*
* @param y The Y value of the color.
* @param targetHue The hue of the color.
* @return The desired color, in linear RGB coordinates.
*/
fun bisectToLimit(y: Double, targetHue: Double): Int {
val segment = bisectToSegment(y, targetHue)
var left = segment[0]
var leftHue = hueOf(left)
var right = segment[1]
for (axis in 0..2) {
if (left[axis] != right[axis]) {
var lPlane: Int
var rPlane: Int
if (left[axis] < right[axis]) {
lPlane = criticalPlaneBelow(trueDelinearized(left[axis]))
rPlane = criticalPlaneAbove(trueDelinearized(right[axis]))
} else {
lPlane = criticalPlaneAbove(trueDelinearized(left[axis]))
rPlane = criticalPlaneBelow(trueDelinearized(right[axis]))
}
for (i in 0..7) {
if (abs(rPlane - lPlane) <= 1) {
break
} else {
val mPlane: Int = floor((lPlane + rPlane) / 2.0).toInt()
val midPlaneCoordinate = CRITICAL_PLANES[mPlane]
val mid = setCoordinate(left, midPlaneCoordinate, right, axis)
val midHue = hueOf(mid)
if (areInCyclicOrder(leftHue, targetHue, midHue)) {
right = mid
rPlane = mPlane
} else {
left = mid
leftHue = midHue
lPlane = mPlane
}
}
}
}
}
return CamUtils.argbFromLinrgbComponents(
(left[0] + right[0]) / 2,
(left[1] + right[1]) / 2, (left[2] + right[2]) / 2
)
}
/** Equation used in CAM16 conversion that removes the effect of chromatic adaptation. */
fun inverseChromaticAdaptation(adapted: Double): Double {
val adaptedAbs: Double = abs(adapted)
val base: Double = max(0.0, 27.13 * adaptedAbs / (400.0 - adaptedAbs))
return CamUtils.signum(adapted) * pow(base, 1.0 / 0.42)
}
/**
* Finds a color with the given hue, chroma, and Y.
*
* @param hueRadians The desired hue in radians.
* @param chroma The desired chroma.
* @param y The desired Y.
* @return The desired color as a hexadecimal integer, if found; 0 otherwise.
*/
fun findResultByJ(hueRadians: Double, chroma: Double, y: Double): Int {
// Initial estimate of j.
var j: Double = sqrt(y) * 11.0
// ===========================================================
// Operations inlined from Cam16 to avoid repeated calculation
// ===========================================================
val viewingConditions = Frame.DEFAULT
val tInnerCoeff: Double = 1 / pow(
1.64 - pow(0.29, viewingConditions.n),
0.73
)
val eHue: Double = 0.25 * (cos(hueRadians + 2.0) + 3.8)
val p1 = (eHue * (50000.0 / 13.0) * viewingConditions.nc
* viewingConditions.ncb)
val hSin: Double = sin(hueRadians)
val hCos: Double = cos(hueRadians)
for (iterationRound in 0..4) {
// ===========================================================
// Operations inlined from Cam16 to avoid repeated calculation
// ===========================================================
val jNormalized = j / 100.0
val alpha =
if (chroma == 0.0 || j == 0.0) 0.0 else chroma / sqrt(jNormalized)
val t: Double = pow(alpha * tInnerCoeff, 1.0 / 0.9)
val acExponent = 1.0 / viewingConditions.c / viewingConditions.z
val ac: Double = viewingConditions.aw * pow(jNormalized, acExponent)
val p2 = ac / viewingConditions.nbb
val gamma = 23.0 * (p2 + 0.305) * t / (23.0 * p1 + 11 * t * hCos + 108.0 * t * hSin)
val a = gamma * hCos
val b = gamma * hSin
val rA = (460.0 * p2 + 451.0 * a + 288.0 * b) / 1403.0
val gA = (460.0 * p2 - 891.0 * a - 261.0 * b) / 1403.0
val bA = (460.0 * p2 - 220.0 * a - 6300.0 * b) / 1403.0
val rCScaled = inverseChromaticAdaptation(rA)
val gCScaled = inverseChromaticAdaptation(gA)
val bCScaled = inverseChromaticAdaptation(bA)
val matrix = LINRGB_FROM_SCALED_DISCOUNT
val linrgbR =
rCScaled * matrix[0][0] + gCScaled * matrix[0][1] + bCScaled * matrix[0][2]
val linrgbG =
rCScaled * matrix[1][0] + gCScaled * matrix[1][1] + bCScaled * matrix[1][2]
val linrgbB =
rCScaled * matrix[2][0] + gCScaled * matrix[2][1] + bCScaled * matrix[2][2]
// ===========================================================
// Operations inlined from Cam16 to avoid repeated calculation
// ===========================================================
if (linrgbR < 0 || linrgbG < 0 || linrgbB < 0) {
return 0
}
val kR = Y_FROM_LINRGB[0]
val kG = Y_FROM_LINRGB[1]
val kB = Y_FROM_LINRGB[2]
val fnj = kR * linrgbR + kG * linrgbG + kB * linrgbB
if (fnj <= 0) {
return 0
}
if (iterationRound == 4 || abs(fnj - y) < 0.002) {
return if (linrgbR > 100.01 || linrgbG > 100.01 || linrgbB > 100.01) {
0
} else CamUtils.argbFromLinrgbComponents(linrgbR, linrgbG, linrgbB)
}
// Iterates with Newton method,
// Using 2 * fn(j) / j as the approximation of fn'(j)
j -= (fnj - y) * j / (2 * fnj)
}
return 0
}
/**
* Finds an sRGB color with the given hue, chroma, and L*, if possible.
*
* @param hueDegrees The desired hue, in degrees.
* @param chroma The desired chroma.
* @param lstar The desired L*.
* @return A hexadecimal representing the sRGB color. The color has sufficiently close hue,
* chroma, and L* to the desired values, if possible; otherwise, the hue and L* will be
* sufficiently close, and chroma will be maximized.
*/
fun solveToInt(hueDegrees: Double, chroma: Double, lstar: Double): Int {
var mutableHueDegrees = hueDegrees
if (chroma < 0.0001 || lstar < 0.0001 || lstar > 99.9999) {
return CamUtils.argbFromLstar(lstar)
}
mutableHueDegrees = sanitizeDegreesDouble(mutableHueDegrees)
val hueRadians: Double = mutableHueDegrees * PI / 180.0
val y = CamUtils.yFromLstar(lstar)
val exactAnswer = findResultByJ(hueRadians, chroma, y)
return if (exactAnswer != 0) {
exactAnswer
} else bisectToLimit(y, hueRadians)
}
/**
* Sanitizes a degree measure as a floating-point number.
*
* @return a degree measure between 0.0 (inclusive) and 360.0 (exclusive).
*/
fun sanitizeDegreesDouble(degrees: Double): Double {
var mutableDegrees = degrees
mutableDegrees %= 360.0
if (mutableDegrees < 0) {
mutableDegrees += 360.0
}
return mutableDegrees
}
/**
* Finds an sRGB color with the given hue, chroma, and L*, if possible.
*
* @param hueDegrees The desired hue, in degrees.
* @param chroma The desired chroma.
* @param lstar The desired L*.
* @return An CAM16 object representing the sRGB color. The color has sufficiently close hue,
* chroma, and L* to the desired values, if possible; otherwise, the hue and L* will be
* sufficiently close, and chroma will be maximized.
*/
fun solveToCam(hueDegrees: Double, chroma: Double, lstar: Double): Cam {
return Cam.fromInt(solveToInt(hueDegrees, chroma, lstar))
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/monet/MathUtils.kt | Kotlin | package dev.zwander.compose.monet
import kotlin.math.pow
fun pow(b: Double, p: Double): Double {
return b.pow(p)
}
fun lerp(start: Double, stop: Double, amount: Double): Double {
return start + (stop - start) * amount
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/monet/Shades.kt | Kotlin | package dev.zwander.compose.monet
import kotlin.math.min
/**
* Generate sets of colors that are shades of the same color
*/
object Shades {
/**
* Combining the ability to convert between relative luminance and perceptual luminance with
* contrast leads to a design system that can be based on a linear value to determine contrast,
* rather than a ratio.
*
* This codebase implements a design system that has that property, and as a result, we can
* guarantee that any shades 5 steps from each other have a contrast ratio of at least 4.5.
* 4.5 is the requirement for smaller text contrast in WCAG 2.1 and earlier.
*
* However, lstar 50 does _not_ have a contrast ratio >= 4.5 with lstar 100.
* lstar 49.6 is the smallest lstar that will lead to a contrast ratio >= 4.5 with lstar 100,
* and it also contrasts >= 4.5 with lstar 100.
*/
private const val MIDDLE_LSTAR = 49.6
/**
* Generate shades of a color. Ordered in lightness _descending_.
*
*
* The first shade will be at 95% lightness, the next at 90, 80, etc. through 0.
*
* @param hue hue in CAM16 color space
* @param chroma chroma in CAM16 color space
* @return shades of a color, as argb integers. Ordered by lightness descending.
*/
fun of(hue: Double, chroma: Double): IntArray {
val shades = IntArray(12)
// At tone 90 and above, blue and yellow hues can reach a much higher chroma.
// To preserve a consistent appearance across all hues, use a maximum chroma of 40.
shades[0] = ColorUtils.CAMToColor(hue, min(40.0, chroma), 99.0)
shades[1] = ColorUtils.CAMToColor(hue, min(40.0, chroma), 95.0)
for (i in 2..11) {
val lStar = if (i == 6) MIDDLE_LSTAR else (100 - 10 * (i - 1)).toDouble()
shades[i] = ColorUtils.CAMToColor(hue, chroma, lStar)
}
return shades
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/monet/WallpaperColors.kt | Kotlin | package dev.zwander.compose.monet
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import kotlin.math.abs
import kotlin.math.round
/**
* Provides information about the colors of a wallpaper.
*
*
* Exposes the 3 most visually representative colors of a wallpaper. Can be either
* [WallpaperColors.primaryColor], [WallpaperColors.secondaryColor]
* or [WallpaperColors.tertiaryColor].
*/
@Suppress("unused", "MemberVisibilityCanBePrivate")
class WallpaperColors {
annotation class ColorsHints
private val mMainColors: MutableList<Color>
private val mAllColors: MutableMap<Int, Int>
/**
* Returns the color hints for this instance.
* @return The color hints.
*/
@get:ColorsHints
var colorHints: Int
private set
/**
* Constructs a new object from three colors.
*
* @param primaryColor Primary color.
* @param secondaryColor Secondary color.
* @param tertiaryColor Tertiary color.
*/
constructor(
primaryColor: Color, secondaryColor: Color?,
tertiaryColor: Color?
) : this(primaryColor, secondaryColor, tertiaryColor, 0) {
// Calculate dark theme support based on primary color.
val tmpHsl = DoubleArray(3)
ColorUtils.colorToHSL(primaryColor.toArgb(), tmpHsl)
val luminance = tmpHsl[2]
if (luminance < DARK_THEME_MEAN_LUMINANCE) {
colorHints = colorHints or HINT_SUPPORTS_DARK_THEME
}
}
/**
* Constructs a new object from three colors, where hints can be specified.
*
* @param primaryColor Primary color.
* @param secondaryColor Secondary color.
* @param tertiaryColor Tertiary color.
* @param colorHints A combination of color hints.
*/
constructor(
primaryColor: Color, secondaryColor: Color?,
tertiaryColor: Color?, @ColorsHints colorHints: Int
) {
mMainColors = ArrayList(3)
mAllColors = HashMap()
mMainColors.add(primaryColor)
mAllColors[primaryColor.toArgb()] = 0
if (secondaryColor != null) {
mMainColors.add(secondaryColor)
mAllColors[secondaryColor.toArgb()] = 0
}
if (tertiaryColor != null) {
if (secondaryColor == null) {
throw IllegalArgumentException(
"tertiaryColor can't be specified when "
+ "secondaryColor is null"
)
}
mMainColors.add(tertiaryColor)
mAllColors[tertiaryColor.toArgb()] = 0
}
this.colorHints = colorHints
}
/**
* Constructs a new object from a set of colors, where hints can be specified.
*
* @param colorToPopulation Map with keys of colors, and value representing the number of
* occurrences of color in the wallpaper.
* @param colorHints A combination of color hints.
* @hide
* @see WallpaperColors.HINT_SUPPORTS_DARK_TEXT
*/
constructor(
colorToPopulation: MutableMap<Int, Int>,
@ColorsHints colorHints: Int
) {
mAllColors = colorToPopulation
val colorToCam: MutableMap<Int, Cam> = HashMap()
for (color: Int in colorToPopulation.keys) {
colorToCam[color] = Cam.fromInt(color)
}
val hueProportions = hueProportions(colorToCam, colorToPopulation)
val colorToHueProportion = colorToHueProportion(
colorToPopulation.keys, colorToCam, hueProportions
)
val colorToScore: MutableMap<Int, Double> = HashMap()
for (mapEntry: Map.Entry<Int, Double> in colorToHueProportion.entries) {
val color = mapEntry.key
val proportion = mapEntry.value
val score = score(colorToCam[color], proportion)
colorToScore[color] = score
}
val mapEntries: ArrayList<Map.Entry<Int, Double>> =
ArrayList(colorToScore.entries)
mapEntries.sortWith { a: Map.Entry<Int?, Double?>, b: Map.Entry<Int?, Double> ->
b.value.compareTo(
(a.value)!!
)
}
val colorsByScoreDescending: MutableList<Int> = ArrayList()
for (colorToScoreEntry: Map.Entry<Int, Double?> in mapEntries) {
colorsByScoreDescending.add(colorToScoreEntry.key)
}
val mainColorInts: MutableList<Int> = ArrayList()
findSeedColorLoop@ for (color: Int in colorsByScoreDescending) {
val cam = colorToCam[color]
for (otherColor: Int in mainColorInts) {
val otherCam = colorToCam[otherColor]
if (hueDiff(cam, otherCam) < 15) {
continue@findSeedColorLoop
}
}
mainColorInts.add(color)
}
val mainColors: MutableList<Color> =
ArrayList()
for (colorInt: Int in mainColorInts) {
mainColors.add(Color(colorInt))
}
mMainColors = mainColors
this.colorHints = colorHints
}
val primaryColor: Color
/**
* Gets the most visually representative color of the wallpaper.
* "Visually representative" means easily noticeable in the image,
* probably happening at high frequency.
*
* @return A color.
*/
get() = mMainColors[0]
val secondaryColor: Color?
/**
* Gets the second most preeminent color of the wallpaper. Can be null.
*
* @return A color, may be null.
*/
get() = if (mMainColors.size < 2) null else mMainColors[1]
val tertiaryColor: Color?
/**
* Gets the third most preeminent color of the wallpaper. Can be null.
*
* @return A color, may be null.
*/
get() = if (mMainColors.size < 3) null else mMainColors[2]
val mainColors: List<Color>
/**
* List of most preeminent colors, sorted by importance.
*
* @return List of colors.
* @hide
*/
get() = mMainColors.toList()
val allColors: Map<Int, Int>
/**
* Map of all colors. Key is rgb integer, value is importance of color.
*
* @return List of colors.
* @hide
*/
get() = mAllColors.toMap()
override fun equals(other: Any?): Boolean {
return other is WallpaperColors &&
((mMainColors == other.mMainColors) &&
(mAllColors == other.mAllColors) &&
(colorHints == other.colorHints))
}
override fun hashCode(): Int {
return (31 * mMainColors.hashCode() * mAllColors.hashCode()) + colorHints
}
@OptIn(ExperimentalStdlibApi::class)
override fun toString(): String {
val colors = StringBuilder()
for (i in mMainColors.indices) {
colors.append(mMainColors[i].toArgb().toHexString()).append(" ")
}
return "[WallpaperColors: " + colors.toString() + "h: " + colorHints + "]"
}
companion object {
private const val DEBUG_DARK_PIXELS = false
/**
* Specifies that dark text is preferred over the current wallpaper for best presentation.
*
*
* eg. A launcher may set its text color to black if this flag is specified.
*/
const val HINT_SUPPORTS_DARK_TEXT = 1 shl 0
/**
* Specifies that dark theme is preferred over the current wallpaper for best presentation.
*
*
* eg. A launcher may set its drawer color to black if this flag is specified.
*/
const val HINT_SUPPORTS_DARK_THEME = 1 shl 1
/**
* Specifies that this object was generated by extracting colors from a bitmap.
* @hide
*/
const val HINT_FROM_BITMAP = 1 shl 2
// Maximum size that a bitmap can have to keep our calculations valid
private const val MAX_BITMAP_SIZE = 112
// Even though we have a maximum size, we'll mainly match bitmap sizes
// using the area instead. This way our comparisons are aspect ratio independent.
private const val MAX_WALLPAPER_EXTRACTION_AREA = MAX_BITMAP_SIZE * MAX_BITMAP_SIZE
// When extracting the main colors, only consider colors
// present in at least MIN_COLOR_OCCURRENCE of the image
private const val MIN_COLOR_OCCURRENCE = 0.05f
// Decides when dark theme is optimal for this wallpaper
private const val DARK_THEME_MEAN_LUMINANCE = 0.3f
// Minimum mean luminosity that an image needs to have to support dark text
private const val BRIGHT_IMAGE_MEAN_LUMINANCE = 0.7f
// We also check if the image has dark pixels in it,
// to avoid bright images with some dark spots.
private const val DARK_PIXEL_CONTRAST = 5.5f
private const val MAX_DARK_AREA = 0.05f
private fun hueDiff(a: Cam?, b: Cam?): Double {
return (180f - abs(abs(a!!.hue - b!!.hue) - 180f))
}
private fun score(cam: Cam?, proportion: Double): Double {
return cam!!.chroma + (proportion * 100)
}
private fun colorToHueProportion(
colors: Set<Int>,
colorToCam: Map<Int, Cam>, hueProportions: DoubleArray
): Map<Int, Double> {
val colorToHueProportion: MutableMap<Int, Double> = HashMap()
for (color: Int in colors) {
val hue = wrapDegrees(
round(
colorToCam[color]!!.hue
).toInt()
)
var proportion = 0.0
for (i in hue - 15 until (hue + 15)) {
proportion += hueProportions[wrapDegrees(i)]
}
colorToHueProportion[color] = proportion
}
return colorToHueProportion
}
private fun wrapDegrees(degrees: Int): Int {
return if (degrees < 0) {
(degrees % 360) + 360
} else if (degrees >= 360) {
degrees % 360
} else {
degrees
}
}
private fun hueProportions(
colorToCam: Map<Int, Cam>,
colorToPopulation: Map<Int, Int>
): DoubleArray {
val proportions = DoubleArray(360)
var totalPopulation = 0.0
for (entry: Map.Entry<Int, Int> in colorToPopulation.entries) {
totalPopulation += entry.value.toDouble()
}
for (entry: Map.Entry<Int, Int> in colorToPopulation.entries) {
val color = entry.key
val population = (colorToPopulation[color])!!
val cam = colorToCam[color]
val hue = wrapDegrees(
round(
cam!!.hue
).toInt()
)
proportions[hue] = proportions[hue] + (population.toDouble() / totalPopulation)
}
return proportions
}
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/util/BridgeUtils.kt | Kotlin | package dev.zwander.compose.util
import androidx.compose.ui.graphics.Color
fun Color.Companion.alpha(color: Int): Int {
return (Color(color).alpha * 255).toInt()
}
fun Color.Companion.red(color: Int): Int {
return (Color(color).red * 255).toInt()
}
fun Color.Companion.green(color: Int): Int {
return (Color(color).green * 255).toInt()
}
fun Color.Companion.blue(color: Int): Int {
return (Color(color).blue * 255).toInt()
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/commonMain/kotlin/dev/zwander/compose/util/UserDefaults.kt | Kotlin | package dev.zwander.compose.util
import androidx.compose.ui.graphics.Color
fun macOsColorKeyToColor(key: Int?): Color {
return when (key) {
-1 -> MacOSColors.ACCENT_GRAPHITE
0 -> MacOSColors.ACCENT_RED
1 -> MacOSColors.ACCENT_ORANGE
2 -> MacOSColors.ACCENT_YELLOW
3 -> MacOSColors.ACCENT_GREEN
4 -> MacOSColors.ACCENT_BLUE
5 -> MacOSColors.ACCENT_LILAC
6 -> MacOSColors.ACCENT_ROSE
else -> MacOSColors.ACCENT_BLUE
}
}
/**
* https://github.com/weisJ/darklaf/blob/master/macos/src/main/java/com/github/weisj/darklaf/platform/macos/theme/MacOSColors.java#L28
*/
object MacOSColors {
// 0.000000 0.478431 1.000000
val ACCENT_BLUE = color(0.000000f, 0.478431f, 1.000000f)
// 0.584314 0.239216 0.588235
val ACCENT_LILAC = color(0.584314f, 0.239216f, 0.588235f)
// 0.968627 0.309804 0.619608
val ACCENT_ROSE = color(0.968627f, 0.309804f, 0.619608f)
// 0.878431 0.219608 0.243137
val ACCENT_RED = color(0.878431f, 0.219608f, 0.243137f)
// 0.968627 0.509804 0.105882
val ACCENT_ORANGE = color(0.968627f, 0.509804f, 0.105882f)
// 0.988235 0.721569 0.152941
val ACCENT_YELLOW = color(0.988235f, 0.721569f, 0.152941f)
// 0.384314 0.729412 0.274510
val ACCENT_GREEN = color(0.384314f, 0.729412f, 0.274510f)
// 0.596078 0.596078 0.596078
val ACCENT_GRAPHITE = color(0.596078f, 0.596078f, 0.596078f)
private fun color(r: Float, g: Float, b: Float): Color {
/*
* For consistency with the native code we mirror the implementation of the float to int conversion
* of the Color class.
*/
return Color(
red = (r * 255 + 0.5).toInt(),
green = (g * 255 + 0.5).toInt(),
blue = (b * 255 + 0.5).toInt(),
alpha = 255
)
}
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/iosMain/kotlin/dev/zwander/compose/ThemeInfo.ios.kt | Kotlin | package dev.zwander.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.uikit.LocalUIViewController
import dev.zwander.compose.libmonet.scheme.ColorScheme
import dev.zwander.compose.util.MacOSColors
import dev.zwander.compose.util.TraitEffect
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.alloc
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.ptr
import kotlinx.cinterop.value
import platform.CoreGraphics.CGFloat
import platform.CoreGraphics.CGFloatVar
import platform.UIKit.UIColor
import platform.UIKit.UITraitCollection
import platform.UIKit.UIUserInterfaceStyle
import platform.UIKit.currentTraitCollection
@Composable
actual fun isSystemInDarkTheme(): Boolean {
var style: UIUserInterfaceStyle by remember {
mutableStateOf(UITraitCollection.currentTraitCollection.userInterfaceStyle)
}
val dark by remember {
derivedStateOf { style == UIUserInterfaceStyle.UIUserInterfaceStyleDark }
}
TraitEffect {
style = UITraitCollection.currentTraitCollection.userInterfaceStyle
}
return dark
}
@OptIn(ExperimentalForeignApi::class)
@Composable
actual fun rememberThemeInfo(isDarkMode: Boolean): ThemeInfo {
val controller = LocalUIViewController.current
val rootViewController = controller.view.window?.rootViewController
val rootTint = rootViewController?.view?.tintColor
val (red, green, blue, alpha) = remember(rootTint) {
rootTint?.run {
memScoped {
val red = alloc<CGFloatVar>()
val green = alloc<CGFloatVar>()
val blue = alloc<CGFloatVar>()
val alpha = alloc<CGFloatVar>()
val success = getRed(red.ptr, green.ptr, blue.ptr, alpha.ptr)
if (success) {
arrayOf(
red.value,
green.value,
blue.value,
alpha.value,
)
} else {
arrayOfNulls<CGFloat?>(4)
}
}
} ?: arrayOfNulls(4)
}
val seedColor = if (red != null && green != null && blue != null && alpha != null) {
Color(red.toFloat(), green.toFloat(), blue.toFloat(), alpha.toFloat())
} else {
MacOSColors.ACCENT_BLUE
}.toArgb()
val colorScheme = ColorScheme(
seedColor,
isDarkMode,
).toComposeColorScheme()
val colors = ThemeInfo(
isDarkMode = isDarkMode,
colors = colorScheme,
seedColor = Color(seedColor),
)
val backgroundColor = colorScheme.background
val uiColor = UIColor.colorWithRed(
backgroundColor.red.toDouble(),
backgroundColor.green.toDouble(),
backgroundColor.blue.toDouble(),
backgroundColor.alpha.toDouble(),
)
val rv = controller.view.window?.rootViewController?.view
rv?.backgroundColor = uiColor
return colors
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/iosMain/kotlin/dev/zwander/compose/util/TraitEffect.kt | Kotlin | package dev.zwander.compose.util
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.ui.interop.LocalUIViewController
import kotlinx.cinterop.BetaInteropApi
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.cinterop.ExportObjCClass
import kotlinx.cinterop.readValue
import platform.CoreGraphics.CGRectZero
import platform.UIKit.UITraitCollection
import platform.UIKit.UIView
@Composable
fun TraitEffect(
key: Any? = Unit,
onTraitsChanged: () -> Unit,
) {
val viewController = LocalUIViewController.current
DisposableEffect(key) {
val view: UIView = viewController.view
val traitView = TraitView(onTraitsChanged)
traitView.onCreate(view)
onDispose {
traitView.onDestroy()
}
}
}
// https://github.com/JetBrains/compose-multiplatform/issues/3213#issuecomment-1572378546
@ExportObjCClass
@OptIn(ExperimentalForeignApi::class, BetaInteropApi::class)
private class TraitView(
private val onTraitChanged: () -> Unit,
) : UIView(frame = CGRectZero.readValue()) {
override fun traitCollectionDidChange(previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
onTraitChanged()
}
fun onCreate(parent: UIView) {
parent.addSubview(this)
}
fun onDestroy() {
removeFromSuperview()
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/jsAndWasmMain/kotlin/dev/zwander/compose/ThemeInfo.jsAndWasm.kt | Kotlin | package dev.zwander.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import dev.zwander.compose.libmonet.scheme.ColorScheme
val LocalAccentColor = compositionLocalOf { Color(red = 208, green = 188, blue = 255) }
@Composable
actual fun isSystemInDarkTheme(): Boolean {
return androidx.compose.foundation.isSystemInDarkTheme()
}
@Composable
actual fun rememberThemeInfo(isDarkMode: Boolean): ThemeInfo {
return ThemeInfo(
isDarkMode = isDarkMode,
colors = ColorScheme(LocalAccentColor.current.toArgb(), isDarkMode).toComposeColorScheme(),
seedColor = LocalAccentColor.current,
)
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/jvmMain/kotlin/dev/zwander/compose/ThemeInfo.jvm.kt | Kotlin | package dev.zwander.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import com.jthemedetecor.OsThemeDetector
import com.sun.jna.platform.win32.Advapi32Util
import com.sun.jna.platform.win32.WinReg
import dev.zwander.jfa.appkit.NSUserDefaults
import dev.zwander.compose.libmonet.scheme.ColorScheme
import dev.zwander.compose.util.LinuxAccentColorGetter
import dev.zwander.compose.util.macOsColorKeyToColor
import org.jetbrains.skiko.OS
import org.jetbrains.skiko.hostOs
import java.util.function.Consumer
@Composable
actual fun isSystemInDarkTheme(): Boolean {
val (osThemeDetector, isSupported) = remember {
OsThemeDetector.detector to OsThemeDetector.isSupported
}
var dark by remember {
mutableStateOf(isSupported && osThemeDetector.isDark)
}
DisposableEffect(osThemeDetector, isSupported) {
val listener = Consumer { darkMode: Boolean ->
dark = darkMode
}
if (isSupported) {
osThemeDetector.registerListener(listener)
}
onDispose {
if (isSupported) {
osThemeDetector.removeListener(listener)
}
}
}
return dark
}
@Composable
actual fun rememberThemeInfo(isDarkMode: Boolean): ThemeInfo {
val accentColor = remember {
val defaultColor = Color(red = 208, green = 188, blue = 255)
when (hostOs) {
OS.Windows -> {
try {
java.awt.Color(
Advapi32Util.registryGetIntValue(
WinReg.HKEY_CURRENT_USER,
"Software\\Microsoft\\Windows\\DWM",
"AccentColor",
)
).let {
// AccentColor is ABGR so we need to swap blue and red.
Color(it.blue, it.green, it.red).toArgb()
}
} catch (_: Throwable) {
try {
Color(
Advapi32Util.registryGetIntValue(
WinReg.HKEY_CURRENT_USER,
"Software\\Microsoft\\Windows\\DWM",
"ColorizationColor",
)
).toArgb()
} catch (_: Throwable) {
println("Unable to retrieve Windows accent color.")
defaultColor.toArgb()
}
}
}
OS.MacOS -> {
macOsColorKeyToColor(NSUserDefaults.standardUserDefaults().objectForKey("AppleAccentColor")?.toString()?.toIntOrNull()).toArgb()
}
OS.Linux -> {
(LinuxAccentColorGetter.getAccentColor() ?: defaultColor).toArgb()
}
else -> {
defaultColor.toArgb()
}
}
}
val composeColorScheme = remember(accentColor, isDarkMode) {
ColorScheme(accentColor, isDarkMode).toComposeColorScheme()
}
return remember(composeColorScheme) {
ThemeInfo(
isDarkMode = isDarkMode,
colors = composeColorScheme,
seedColor = Color(accentColor),
)
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/jvmMain/kotlin/dev/zwander/compose/util/LinuxAccentColorGetter.kt | Kotlin | package dev.zwander.compose.util
import androidx.compose.ui.graphics.Color
import java.io.File
object LinuxAccentColorGetter {
fun getAccentColor(): Color? {
return try {
val environmentValue = System.getenv()["XDG_SESSION_DESKTOP"]
DESpecificGetter.findGetter(environmentValue)?.getAccentColor()
} catch (e: Throwable) {
e.printStackTrace()
null
}
}
}
sealed class DESpecificGetter(val sessionValue: String) {
companion object {
fun findGetter(de: String?): DESpecificGetter? {
return DESpecificGetter::class.sealedSubclasses.firstNotNullOfOrNull {
val obj = it.objectInstance
if (obj?.sessionValue?.lowercase() == de?.lowercase()) {
obj
} else {
null
}
}
}
}
protected val runtime: Runtime? by lazy { Runtime.getRuntime() }
abstract fun getAccentColor(): Color?
data object KDE : DESpecificGetter("KDE") {
override fun getAccentColor(): Color? {
val rgb = runtime?.run {
try {
getLinesFromCommand(arrayOf("kreadconfig5", "--key", "AccentColor", "--group", "General"))
} catch (e: Exception) {
getLinesFromCommand(arrayOf("kreadconfig6", "--key", "AccentColor", "--group", "General"))
}
}?.firstOrNull()
if (rgb.isNullOrBlank()) {
return null
}
val (r, g, b) = rgb.split(",")
return Color(r.toInt(), g.toInt(), b.toInt())
}
}
data object UBUNTU : DESpecificGetter("ubuntu") {
override fun getAccentColor(): Color? {
val color = runtime?.getLinesFromCommand(arrayOf("gsettings", "get", "org.gnome.desktop.interface", "accent-color"))
?.firstOrNull()
?.trim()
// typical output is 'yellow' format, so remove the beginning and ending char
?.removeSurrounding("'")
// Colors sampled from Ubuntu 25.10 (questing) desktop
val rgb = when (color) {
"blue" -> "0,115,229"
"teal" -> "48,130,128"
"green" -> "75,133,1"
"yellow" -> "200,136,0"
"orange" -> "233,84,32"
"red" -> "218,52,80"
"pink" -> "179,76,179"
"purple" -> "119,100,216"
"slate" -> "101,123,105"
"brown" -> "179,145,105"
else -> null
}
if (rgb.isNullOrBlank()) {
return null
}
val (r, g, b) = rgb.split(",")
return Color(r.toInt(), g.toInt(), b.toInt())
}
}
data object LXDE : DESpecificGetter("LXDE") {
override fun getAccentColor(): Color? {
val file = File("${System.getProperty("user.home")}/.config/lxsession/LXDE/desktop.conf")
val line = file.useLines { lines ->
lines.find { it.startsWith("sGtk/ColorScheme") }
}
if (line.isNullOrBlank()) {
return null
}
val value = line.split("=").getOrNull(1) ?: return null
val selectedBgColor = value.split("\\n").find { it.startsWith("selected_bg_color") } ?: return null
val colorValue = selectedBgColor.split(":#").getOrNull(1) ?: return null
val realColor = if (colorValue.length == 6) {
colorValue
} else {
// LXDE sets a 12-character color with the 6-char color (sort of) interleaved.
// It isn't always exactly accurate, but the format makes no sense, and this is close enough.
"${colorValue.slice(0..1)}${colorValue.slice(4..5)}${colorValue.slice(8..9)}"
}
return try {
Color(java.awt.Color.decode("#${realColor}").rgb)
} catch (e: Exception) {
null
}
}
}
}
fun Runtime.getLinesFromCommand(command: Array<String>): List<String>? {
val proc = exec(command)
proc?.inputStream?.bufferedReader()?.use { input ->
return input.readLines()
}
proc?.waitFor()
return null
}
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
library/src/macosMain/kotlin/dev/zwander/compose/ThemeInfo.macos.kt | Kotlin | package dev.zwander.compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.toArgb
import dev.zwander.compose.libmonet.scheme.ColorScheme
import dev.zwander.compose.util.macOsColorKeyToColor
import platform.Foundation.NSUserDefaults
import platform.Foundation.NSDistributedNotificationCenter
import platform.Foundation.NSNotification
@Composable
actual fun isSystemInDarkTheme(): Boolean {
var isDark by remember {
mutableStateOf(
NSUserDefaults.standardUserDefaults.objectForKey("AppleInterfaceStyle") == "Dark"
)
}
DisposableEffect(null) {
val observer = { _: NSNotification? ->
isDark = NSUserDefaults.standardUserDefaults.objectForKey("AppleInterfaceStyle") == "Dark"
}
NSDistributedNotificationCenter.defaultCenter.addObserverForName(
"AppleInterfaceThemeChangedNotification",
null,
null,
observer,
)
onDispose {
NSDistributedNotificationCenter.defaultCenter.removeObserver(observer)
}
}
return isDark
}
@Composable
actual fun rememberThemeInfo(isDarkMode: Boolean): ThemeInfo {
var accentColor by remember {
mutableStateOf(
macOsColorKeyToColor(
NSUserDefaults.standardUserDefaults.objectForKey("AppleAccentColor")?.toString()?.toIntOrNull(),
)
)
}
DisposableEffect(null) {
val observer = { _: NSNotification? ->
accentColor = macOsColorKeyToColor(
NSUserDefaults.standardUserDefaults.objectForKey("AppleAccentColor")?.toString()?.toIntOrNull(),
)
}
NSDistributedNotificationCenter.defaultCenter.addObserverForName(
"AppleInterfaceThemeChangedNotification",
null,
null,
observer,
)
onDispose {
NSDistributedNotificationCenter.defaultCenter.removeObserver(observer)
}
}
return remember(accentColor, isDarkMode) {
ThemeInfo(
isDarkMode = isDarkMode,
colors = ColorScheme(accentColor.toArgb(), isDarkMode).toComposeColorScheme(),
seedColor = accentColor,
)
}
} | zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
settings.gradle.kts | Kotlin | @file:Suppress("UnstableApiUsage")
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
google()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/dev/")
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
google()
maven("https://maven.pkg.jetbrains.space/public/p/compose/dev")
maven("https://maven.pkg.jetbrains.space/kotlin/p/kotlin/dev/")
maven("https://maven.pkg.jetbrains.space/public/p/ktor/eap/")
maven("https://jitpack.io")
maven("https://s01.oss.sonatype.org/content/repositories/snapshots/")
}
}
rootProject.name = "MultiplatformMaterialYou"
include(":library")
| zacharee/MultiplatformMaterialYou | 20 | Kotlin | zacharee | Zachary Wander | ||
lib/portable_text.rb | Ruby | require "portable_text/version"
require "portable_text/configuration"
require "portable_text/parser"
require "portable_text/renderer"
# Serializers
require "portable_text/serializer/html_element"
require "portable_text/serializer/underline"
require "portable_text/serializer/span"
require "portable_text/serializer/link"
require "portable_text/serializer/image"
require "portable_text/serializer/list_item"
require "portable_text/serializer/registry"
# Elements
require "portable_text/block"
require "portable_text/list"
| zachgoll/ruby-portabletext | 0 | A Portable Text Renderer in Ruby | Ruby | zachgoll | Zach Gollwitzer | |
lib/portable_text/block.rb | Ruby | require_relative "mark"
require_relative "mark_def"
require_relative "span"
require_relative "children"
require_relative "renderable"
module PortableText
class Block
include Renderable
class << self
def from_json(json)
key = json["_key"]
type = json["_type"]
style = json["style"]
list_level = json["level"]
list_type = json["listItem"]
children = Children.from_json(json["children"] || [], json["markDefs"] || [])
serializer_key = type == "block" ? style : type
serializer_key = "li" if list_type
serializer = PortableText.configuration.serializer_registry.get(serializer_key, fallback: "normal", ctx: json)
new \
serializer: serializer,
attributes: {
key: key,
type: type,
style: style,
list_level: list_level,
list_type: list_type,
children: children,
},
raw_json: json
end
end
attr_reader :list_level, :list_type, :children
def initialize(serializer:, attributes: {}, raw_json: {})
@serializer = serializer
@raw_json = raw_json
@key = attributes[:key]
@type = attributes[:type]
@style = attributes[:style]
@mark_defs = attributes[:mark_defs]
@children = attributes[:children]
@list_level = attributes[:list_level]
@list_type = attributes[:list_type]
end
def to_html
rendered_children = children ? children.to_html : ""
@serializer.call(rendered_children, @raw_json)
end
def marks
[]
end
end
end | zachgoll/ruby-portabletext | 0 | A Portable Text Renderer in Ruby | Ruby | zachgoll | Zach Gollwitzer | |
lib/portable_text/children.rb | Ruby | require_relative "renderable"
module PortableText
class Children
include Renderable
class << self
def from_json(items, mark_defs)
defs = mark_defs.map { |md| MarkDef.from_json(md) }
parsed_items = items.map do |item|
Span.from_json(item, defs)
end
new parsed_items, raw_json: items
end
end
def initialize(elements = [], raw_json: {})
@elements = elements
@raw_json = raw_json
end
def to_html
chunk_and_render(elements)
end
private
attr_reader :elements, :raw_json
def chunk_and_render(elements)
chunks = Mark.chunk_by_marks(elements)
chunks.map { |chunk| render_chunk(chunk) }.join
end
def render_chunk(chunk)
if chunk.size == 1 && chunk.first.marks.empty?
chunk.first.to_html
else
outer_mark = Mark.outermost_mark(chunk)
inner_html = chunk_and_render(nodes_without_outer_mark(chunk, outer_mark.key))
outer_mark.serialize(inner_html)
end
end
def nodes_without_outer_mark(nodes, mark_key)
nodes.map do |node|
new_node = node.dup
new_node.marks = new_node.marks.reject { |mark| mark.key == mark_key }
new_node
end
end
end
end | zachgoll/ruby-portabletext | 0 | A Portable Text Renderer in Ruby | Ruby | zachgoll | Zach Gollwitzer | |
lib/portable_text/configuration.rb | Ruby | module PortableText
class Configuration
attr_accessor :serializer_registry, :project_id, :dataset, :cdn_base_url, :on_missing_serializer
end
class << self
def configuration
@configuration ||= Configuration.new
end
def configure
yield(configuration)
configuration.serializer_registry = Serializer::Registry.new \
base_image_url: base_image_url,
on_missing_serializer: configuration.on_missing_serializer
end
def base_image_url
[
configuration.cdn_base_url,
configuration.project_id,
configuration.dataset
].join("/")
end
end
end | zachgoll/ruby-portabletext | 0 | A Portable Text Renderer in Ruby | Ruby | zachgoll | Zach Gollwitzer | |
lib/portable_text/list.rb | Ruby | require_relative 'renderable'
module PortableText
class List
include Renderable
class << self
def list_item?(json)
json.key?("listItem")
end
def default_level
1
end
end
def initialize(list_items)
@list_items = list_items
end
def to_html
start_level = list_items.first.list_level || List.default_level
chunks = list_items.chunk_while do |_li1, li2|
li2_level = li2.list_level || List.default_level
li2_level > start_level
end.to_a
items = chunks.map { |chunk| render_chunk(chunk) }.join
serializer.call(items)
end
private
attr_reader :list_items
def serializer
serializer_key = list_items.first&.list_type == "number" ? "ol" : "ul"
serializer = PortableText.configuration.serializer_registry.get(serializer_key, fallback: "ul", ctx: list_items)
serializer
end
def render_chunk(chunk)
if chunk.size == 1
chunk.first.to_html
else
wrap_sub_list(chunk.first, List.new(chunk.drop(1)))
end
end
def wrap_sub_list(block, sub_list)
"<li>" + block.children.to_html + sub_list.to_html + "</li>"
end
end
end | zachgoll/ruby-portabletext | 0 | A Portable Text Renderer in Ruby | Ruby | zachgoll | Zach Gollwitzer | |
lib/portable_text/mark.rb | Ruby | module PortableText
class Mark
KNOWN_TYPES = %w[ strong em code underline strike-through ]
class << self
def from_key(key, mark_defs)
definition = mark_defs.find { |md| md.key == key }
serializer_key = definition ? definition.type : key
serializer = PortableText.configuration.serializer_registry.get(serializer_key, fallback: "missing_mark", ctx: mark_defs)
new \
key: key,
serializer: serializer,
definition: definition
end
def chunk_by_marks(nodes)
# nodes.chunk_while { |e1, e2| e1.marks.any? && e2.marks.any? }
nodes.chunk_while do |e1, e2|
e1_mark_keys = e1.marks.map(&:key)
e2_mark_keys = e2.marks.map(&:key)
(e1_mark_keys & e2_mark_keys).any?
end
end
# Finds the outermost mark in a "chunk" of spans
# Ties are broken based on whether the mark key is known (decorator) or unknown (annotation)
def outermost_mark(nodes)
all_marks = nodes.flat_map(&:marks)
mark_counts = all_marks.group_by(&:key).transform_values(&:count)
return nil if mark_counts.empty?
max_count = mark_counts.values.max
most_frequent_marks = mark_counts.select { |_, count| count == max_count }
if most_frequent_marks.size > 1
unknown_mark_keys = most_frequent_marks.keys - Mark::KNOWN_TYPES
if unknown_mark_keys.any?
all_marks.find { |mark| mark.key == unknown_mark_keys.first }
else
sorted_keys = most_frequent_marks.keys.sort_by { |key| Mark::KNOWN_TYPES.index(key) || Float::INFINITY }
all_marks.find { |mark| mark.key == sorted_keys.first }
end
else
all_marks.find { |mark| mark.key == most_frequent_marks.keys.first }
end
end
end
attr_reader :key, :serializer, :definition
def initialize(key:, serializer:, definition: nil)
@key = key
@serializer = serializer
@definition = definition
end
def serialize(inner_html)
serializer.call(inner_html, definition&.raw_json)
end
end
end | zachgoll/ruby-portabletext | 0 | A Portable Text Renderer in Ruby | Ruby | zachgoll | Zach Gollwitzer | |
lib/portable_text/mark_def.rb | Ruby | module PortableText
class MarkDef
class << self
def from_json(json)
new key: json["_key"], type: json["_type"], raw_json: json
end
end
attr_reader :key, :type, :raw_json
def initialize(key:, type:, raw_json:)
@key = key
@type = type
@raw_json = raw_json
end
end
end | zachgoll/ruby-portabletext | 0 | A Portable Text Renderer in Ruby | Ruby | zachgoll | Zach Gollwitzer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.