diff --git a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt index 6e354d47a6..efa24f7e21 100644 --- a/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt +++ b/app/src/main/java/com/droiddeck/launcher/SessionActivity.kt @@ -36,9 +36,12 @@ import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.unit.dp import com.droiddeck.launcher.core.FileUtils +import com.droiddeck.launcher.core.TextureFiltering import com.droiddeck.launcher.files.InAppFilePicker import com.droiddeck.launcher.frontend.Library import com.droiddeck.launcher.gpu.FrameGen +import com.droiddeck.launcher.gpu.ScreenEffectLooks +import com.droiddeck.launcher.gpu.ScreenEffects import com.droiddeck.launcher.gpu.Lossless import com.droiddeck.launcher.gpu.TurnipDriver import com.droiddeck.launcher.input.EvdevKeys @@ -56,6 +59,7 @@ import com.droiddeck.launcher.runtime.LinuxRuntime import com.droiddeck.launcher.session.LoadingState import com.droiddeck.launcher.session.PerfHud import com.droiddeck.launcher.session.PerfMode +import com.droiddeck.launcher.session.GameEnvironmentStore import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.SessionEvents import com.droiddeck.launcher.session.SessionArtifacts @@ -210,6 +214,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { private var fillScreen by mutableStateOf(true) private var upscaler by mutableStateOf(0) private var upscaleSharpness by mutableStateOf(75) + private var effects by mutableStateOf(ScreenEffects.OFF) + private var textureAnisotropy by mutableStateOf(0) + private var textureLodBias by mutableStateOf(TextureFiltering.LOD_BIAS_OFF) private var lossless by mutableStateOf(Lossless.State.NONE) private val pickLossless = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { r -> if (r.resultCode == RESULT_OK) InAppFilePicker.pickedFile(r.data)?.let { importLossless(it) } @@ -464,6 +471,7 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { hudOn = hudOn, fillScreen = if (SessionState.mode == SessionService.MODE_STEAM) fillScreen else null, upscaler = upscaler, upscaleSharpness = upscaleSharpness, + effects = effects, textureAnisotropy = textureAnisotropy, textureLodBias = textureLodBias, frameGen = frameGen, lossless = lossless, oscMode = oscMode, suspendPolicy = suspendPolicy, touchMode = touchMode, @@ -477,11 +485,19 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { onUpscaler = { m -> SessionPrefs.setUpscaler(this@SessionActivity, m); upscaler = m WaylandCompositor.nativeSetUpscaler(m) + // Two Looks carry a scaling mode of their own, so the mode decides which one the log names. + WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(effects, m)?.name) }, onUpscaleSharpness = { pct -> SessionPrefs.setUpscaleSharpness(this@SessionActivity, pct); upscaleSharpness = pct WaylandCompositor.nativeSetUpscaleSharpness(pct) }, + onEffects = { e -> + SessionPrefs.setScreenEffects(this@SessionActivity, e); effects = e + e.push(upscaler) + }, + onTextureAnisotropy = { v -> SessionPrefs.setTextureAnisotropy(this@SessionActivity, v); textureAnisotropy = v }, + onTextureLodBias = { v -> SessionPrefs.setTextureLodBias(this@SessionActivity, v); textureLodBias = v }, onFrameGenPick = { mode -> FrameGen.set(this@SessionActivity, mode) readPrefs() @@ -721,6 +737,9 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { fillScreen = SessionPrefs.forceFullscreen(this) upscaler = SessionPrefs.upscaler(this) upscaleSharpness = SessionPrefs.upscaleSharpness(this) + effects = SessionPrefs.screenEffects(this) + textureAnisotropy = SessionPrefs.textureAnisotropy(this) + textureLodBias = SessionPrefs.textureLodBias(this) val nextTouchMode = SessionPrefs.touchMode(this) if (touchMode != nextTouchMode) { if (::touchpad.isInitialized) touchpad.cancel() @@ -885,11 +904,20 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { val size = if (SessionState.running) SessionState.outputSize else outputSize() SessionState.outputSize = size if (!SessionState.running) SessionState.refreshHz = refreshHz() + // How far the panel enlarges the session, for texture sharpness "Auto" (TextureFiltering): + // the game environment is published again so the next launch derives it from this session. + val panel = panelBounds() + SessionState.upscaleRatio = maxOf(panel.width(), panel.height()).toFloat() / maxOf(size.first, size.second).coerceAtLeast(1) + Thread({ + runCatching { GameEnvironmentStore.publish(this) } + .onFailure { Log.e(TAG, "Could not update game environment", it) } + }, "game-env-publish").start() // Letterbox, never stretch or crop: the output can be a different shape from the panel, // and a game's picture must keep its proportions with bars, not lose its edges. WaylandCompositor.nativeSetScaleMode(SCALE_FIT, ALIGN_CENTER) WaylandCompositor.nativeSetUpscaler(SessionPrefs.upscaler(this)) WaylandCompositor.nativeSetUpscaleSharpness(SessionPrefs.upscaleSharpness(this)) + SessionPrefs.screenEffects(this).push(SessionPrefs.upscaler(this)) // The session's folder, claimed here because the compositor starts before the service and // opens its log once. The compositor reads the path from its environment; setting it after // it has started changes nothing, which is why the service copies the file in at teardown. @@ -973,17 +1001,18 @@ class SessionActivity : ComponentActivity(), SurfaceHolder.Callback { * The size the session renders at. gamescope is told this and scales its output onto whatever * the panel is, so a 1440p phone can run the client at 1080p without the client knowing. */ + /** The panel, not the window: resources.displayMetrics is what is left after the system bars and the cutout are taken out. */ + private fun panelBounds(): android.graphics.Rect = if (Build.VERSION.SDK_INT >= 30) { + windowManager.maximumWindowMetrics.bounds + } else { + val metrics = android.util.DisplayMetrics() + @Suppress("DEPRECATION") + windowManager.defaultDisplay.getRealMetrics(metrics) + android.graphics.Rect(0, 0, metrics.widthPixels, metrics.heightPixels) + } + private fun outputSize(): Pair { - // The panel, not the window: resources.displayMetrics is what is left after the system - // bars and the cutout are taken out. - val bounds = if (Build.VERSION.SDK_INT >= 30) { - windowManager.maximumWindowMetrics.bounds - } else { - val metrics = android.util.DisplayMetrics() - @Suppress("DEPRECATION") - windowManager.defaultDisplay.getRealMetrics(metrics) - android.graphics.Rect(0, 0, metrics.widthPixels, metrics.heightPixels) - } + val bounds = panelBounds() val panelW = maxOf(bounds.width(), bounds.height()).toFloat() val panelH = minOf(bounds.width(), bounds.height()).toFloat() // Never narrower than 16:9. A foldable's inner panel is nearly square, and a game handed a diff --git a/app/src/main/java/com/droiddeck/launcher/core/TextureFiltering.kt b/app/src/main/java/com/droiddeck/launcher/core/TextureFiltering.kt new file mode 100644 index 0000000000..97c07289f2 --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/core/TextureFiltering.kt @@ -0,0 +1,59 @@ +package com.droiddeck.launcher.core + +import java.util.Locale +import kotlin.math.ln +import kotlin.math.max +import kotlin.math.min + +/** + * Texture filtering for DirectX 9-11 games, as DXVK configuration options + * (d3d9/d3d11.samplerAnisotropy and samplerLodBias). VKD3D-Proton and WineD3D do not read them. + * Published into the game environment and read by DXVK when a game starts, so a change lands on + * the next launch, not the running game. + */ +object TextureFiltering { + /** 0 = the game's own filtering; otherwise that anisotropy on every linearly filtered sampler. */ + val ANISOTROPY = listOf(0, 2, 4, 8, 16) + + /** Negative mip LOD bias added to the game's own: sharper textures at the cost of some shimmer. */ + const val LOD_BIAS_OFF = "0" + /** Derived from how far the session is enlarged to the panel (see [autoLodBias]). */ + const val LOD_BIAS_AUTO = "auto" + val LOD_BIAS = listOf(LOD_BIAS_OFF, LOD_BIAS_AUTO, "-0.25", "-0.5", "-0.75", "-1.0") + + private const val LOD_BIAS_MIN = -2f + + /** + * The mip LOD bias for a picture enlarged by [scale] (panel size over session size, long side + * to long side): -log2(scale), AMD's FSR 1 guidance (a 1.5x enlargement - 720p on a 1080p + * panel - gives -0.58). 0 when the session is not enlarged or the scale is unknown. + */ + fun autoLodBias(scale: Float): Float { + if (scale.isNaN() || scale <= 1f) return 0f + return max((-ln(scale.toDouble()) / ln(2.0)).toFloat(), LOD_BIAS_MIN) + } + + fun lodBias(choice: String, autoBias: Float): Float = when (choice) { + LOD_BIAS_OFF, "" -> 0f + LOD_BIAS_AUTO -> autoBias + else -> choice.toFloatOrNull()?.let { max(min(it, 0f), LOD_BIAS_MIN) } ?: 0f + } + + /** The DXVK_CONFIG options for the two settings, "" when both are left to the game. */ + fun dxvkOptions(anisotropy: Int, lodBiasChoice: String, autoBias: Float): String { + val parts = ArrayList(4) + val aniso = if (anisotropy in ANISOTROPY) anisotropy else 0 + if (aniso > 0) { + parts += "d3d9.samplerAnisotropy = $aniso" + parts += "d3d11.samplerAnisotropy = $aniso" + } + val bias = lodBias(lodBiasChoice, autoBias) + if (bias < 0f) { + // Locale.US: DXVK parses "-0.58", never "-0,58". + val b = String.format(Locale.US, "%.2f", bias) + parts += "d3d9.samplerLodBias = $b" + parts += "d3d11.samplerLodBias = $b" + } + return parts.joinToString("; ") + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt b/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt new file mode 100644 index 0000000000..28adc4f51b --- /dev/null +++ b/app/src/main/java/com/droiddeck/launcher/gpu/ScreenEffects.kt @@ -0,0 +1,136 @@ +package com.droiddeck.launcher.gpu + +import com.droiddeck.launcher.wayland.WaylandCompositor +import org.json.JSONObject +import kotlin.math.abs + +/** + * The compositor's post chain (waylandcomp/src/effects_chain.c) as the session menu drives it: + * the colour grade, the sharpening, the shader toggles and terminal debanding. Units are the + * menu's own, so a value goes straight from a row into the setter it drives: + * + * - [brightness] / [contrast] -100..100, 0 = neutral + * - [gamma] 0.5..3.0, 1.0 = neutral + * - [saturation] 0..200 percent, 100 = neutral + * - [casLevel] 0..100; the pass runs only while [cas] is on + * - [debandStrength] 0..200, 100 = one LSB + * + * Applies live: the compositor picks the change up on its next frame. While any pass is on, a + * zero-copy game goes through the compositor pass instead, which costs a little GPU time. + */ +data class ScreenEffects( + val brightness: Int = 0, + val contrast: Int = 0, + val gamma: Float = 1f, + val saturation: Int = 100, + val cas: Boolean = false, + val casLevel: Int = 50, + val hdr: Boolean = false, + val deband: Boolean = false, + val debandStrength: Int = 100, + val fxaa: Boolean = false, + val toon: Boolean = false, + val crt: Boolean = false, + val ntsc: Boolean = false, +) { + /** The sharpening level the picture gets: 0 while the pass is off, whatever its level is parked at. */ + val effectiveCas: Int get() = if (cas) casLevel else 0 + + /** Whether any pass runs, so the menu can say when the picture is untouched. */ + val any: Boolean get() = brightness != 0 || contrast != 0 || abs(gamma - 1f) > 0.005f || saturation != 100 || + effectiveCas > 0 || hdr || deband || fxaa || toon || crt || ntsc + + /** Hands every pass to the compositor, with the Look's name for its log line. */ + fun push(upscaler: Int) { + WaylandCompositor.nativeSetCas(cas, casLevel) + WaylandCompositor.nativeSetHdr(hdr) + WaylandCompositor.nativeSetDeband(deband, debandStrength) + WaylandCompositor.nativeSetScreenEffects(brightness.toFloat(), contrast.toFloat(), gamma, saturation.toFloat(), fxaa, toon, crt, ntsc) + WaylandCompositor.nativeSetLookName(ScreenEffectLooks.match(this, upscaler)?.name) + } + + fun encode(): JSONObject = JSONObject() + .put("brightness", brightness).put("contrast", contrast).put("gamma", gamma.toDouble()).put("saturation", saturation) + .put("cas", cas).put("casLevel", casLevel).put("hdr", hdr).put("deband", deband).put("debandStrength", debandStrength) + .put("fxaa", fxaa).put("toon", toon).put("crt", crt).put("ntsc", ntsc) + + companion object { + val OFF = ScreenEffects() + + fun decode(json: JSONObject): ScreenEffects = ScreenEffects( + brightness = json.optInt("brightness", 0).coerceIn(-100, 100), + contrast = json.optInt("contrast", 0).coerceIn(-100, 100), + gamma = json.optDouble("gamma", 1.0).toFloat().coerceIn(0.5f, 3f), + saturation = json.optInt("saturation", 100).coerceIn(0, 200), + cas = json.optBoolean("cas", false), + casLevel = json.optInt("casLevel", 50).coerceIn(0, 100), + hdr = json.optBoolean("hdr", false), + deband = json.optBoolean("deband", false), + debandStrength = json.optInt("debandStrength", 100).coerceIn(0, 200), + fxaa = json.optBoolean("fxaa", false), + toon = json.optBoolean("toon", false), + crt = json.optBoolean("crt", false), + ntsc = json.optBoolean("ntsc", false), + ) + } +} + +/** + * One Look: a named set of values for the rows that already exist on the Display page. Picking + * a Look moves those rows; each stays adjustable afterwards, and the moment one moves the Look + * row reads Custom. [scalingMode] null leaves the scaling mode alone; otherwise it is a + * SessionPrefs.upscalerChoices mode the Look switches to. + */ +data class Look( + val name: String, + val effects: ScreenEffects, + val scalingMode: Int? = null, + /** One line under the row while this Look is picked. */ + val desc: String, +) + +object ScreenEffectLooks { + // Scaling modes as the compositor numbers them (WaylandCompositor.nativeSetUpscaler). + private const val SCALING_NEAREST = 2 + private const val SCALING_FSR = 4 + + /** Index 0 is the neutral state a fresh session matches, so the row always names something. */ + val LOOKS: List = listOf( + Look("Off", ScreenEffects.OFF, desc = "Nothing applied."), + Look("Game Clarity", ScreenEffects(brightness = 2, contrast = 12, saturation = 108, cas = true, casLevel = 55), + desc = "Sharpening with a touch of contrast - the everyday one."), + Look("Vivid", ScreenEffects(brightness = 3, contrast = 10, gamma = 0.98f, saturation = 145, cas = true, casLevel = 30, deband = true), + desc = "Colour pushed hard. Deband on so skies don't stripe."), + Look("Cinematic", ScreenEffects(brightness = -4, contrast = 22, gamma = 1.10f, saturation = 88, cas = true, casLevel = 20, fxaa = true, deband = true), + desc = "Deeper contrast, cooler colour, edges smoothed."), + Look("Competitive", ScreenEffects(brightness = 16, contrast = 18, gamma = 0.92f, saturation = 82, cas = true, casLevel = 75), + desc = "Shadows lifted and heavy sharpening - spot people first."), + Look("Adaptive Sharpen", ScreenEffects(cas = true, casLevel = 85), + desc = "Sharpening only, colour untouched."), + Look("Filmic", ScreenEffects(brightness = -2, contrast = 16, gamma = 1.14f, saturation = 92, cas = true, casLevel = 15, fxaa = true, deband = true), + desc = "Film-like curve, slightly muted."), + Look("Arcade", ScreenEffects(brightness = 6, contrast = 20, gamma = 0.95f, saturation = 170, cas = true, casLevel = 45, deband = true), + desc = "Loud and punchy."), + Look("Retro CRT", ScreenEffects(brightness = 6, contrast = 14, gamma = 1.05f, saturation = 115, crt = true, ntsc = true), + desc = "The CRT tube and analogue signal passes together."), + Look("Upscale Sharp", ScreenEffects(contrast = 6, saturation = 104, cas = true, casLevel = 70), scalingMode = SCALING_FSR, + desc = "For running below panel resolution."), + Look("Pixel Clean", ScreenEffects(contrast = 8, deband = true), scalingMode = SCALING_NEAREST, + desc = "Crisp pixels for 2D and old titles."), + Look("Anime Edge", ScreenEffects(brightness = 2, contrast = 10, saturation = 125, cas = true, casLevel = 50, toon = true, deband = true), + desc = "Toon outlines plus sharpening."), + ) + + /** + * The Look the live values are, or null for Custom. A Look's sharpening is compared as the + * effective level, so a pass switched off matches a Look without one whatever its level is + * parked at; a Look with no scaling mode of its own matches under any. + */ + fun match(e: ScreenEffects, upscaler: Int): Look? = LOOKS.firstOrNull { l -> + val t = l.effects + t.brightness == e.brightness && t.contrast == e.contrast && abs(t.gamma - e.gamma) < 0.005f && + t.saturation == e.saturation && t.effectiveCas == e.effectiveCas && + t.fxaa == e.fxaa && t.crt == e.crt && t.toon == e.toon && t.ntsc == e.ntsc && t.deband == e.deband && + (l.scalingMode == null || l.scalingMode == upscaler) + } +} diff --git a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt index 4210d07e6a..12c7bba366 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/GameEnvironmentStore.kt @@ -3,6 +3,7 @@ package com.droiddeck.launcher.session import android.content.Context import android.util.AtomicFile import com.droiddeck.launcher.core.GameEnvironment +import com.droiddeck.launcher.core.TextureFiltering import com.droiddeck.launcher.runtime.LinuxRuntime import org.json.JSONObject import java.io.File @@ -10,6 +11,8 @@ import java.io.File object GameEnvironmentStore { private const val SETTINGS = "game-environment.json" private const val GUEST_FILE = "root/.config/droiddeck/game-environment.json" + /** The published file's extra DXVK options (bannerlator-game-env reads it; the app's own file has none). */ + const val DXVK_CONFIG = "dxvkConfig" @Synchronized fun read(context: Context): GameEnvironment.Config { @@ -57,7 +60,15 @@ object GameEnvironmentStore { @Synchronized fun publish(context: Context, config: GameEnvironment.Config = read(context)) { val resolved = config.copy(shared = GameEnvironment.defaults(SessionPrefs.fexPreset(context)) + config.shared) - write(File(LinuxRuntime.rootDir(context), GUEST_FILE), encode(resolved).toString()) + val json = encode(resolved) + // The Display page's texture filtering, as DXVK options the launcher appends to + // DXVK_CONFIG after the profiles - a user's own DXVK_CONFIG entry keeps its options. + val dxvk = TextureFiltering.dxvkOptions( + SessionPrefs.textureAnisotropy(context), SessionPrefs.textureLodBias(context), + TextureFiltering.autoLodBias(SessionState.upscaleRatio), + ) + if (dxvk.isNotEmpty()) json.put(DXVK_CONFIG, dxvk) + write(File(LinuxRuntime.rootDir(context), GUEST_FILE), json.toString()) } private fun write(file: File, text: String) { diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt index 0a7e760acd..26e234e284 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionPrefs.kt @@ -1,6 +1,9 @@ package com.droiddeck.launcher.session import android.content.Context +import com.droiddeck.launcher.core.TextureFiltering +import com.droiddeck.launcher.gpu.ScreenEffects +import org.json.JSONObject /** The in-session switches: the HUD and how the on-screen controls decide to appear. */ object SessionPrefs { @@ -610,9 +613,15 @@ object SessionPrefs { val fpsLimitChoices = listOf(0 to "Off", 30 to "30", 40 to "40", 45 to "45", 60 to "60", 90 to "90", 120 to "120") + /** + * How the compositor resizes the session onto the panel (WaylandCompositor.nativeSetUpscaler's + * modes): Off and Linear both filter bilinearly, Nearest keeps pixels square for 2D and old + * titles, the rest sharpen where the picture is enlarged; FSR (fit) rounds the picture to + * FSR's preferred size first. Sharpen only works at any size. + */ val upscalerChoices = listOf( - 0 to "Off", 4 to "AMD FSR 1", 3 to "Snapdragon GSR", 8 to "Snapdragon GSR (quality)", - 7 to "NVIDIA NIS", 6 to "Sharpen only", + 0 to "Off", 1 to "Linear", 2 to "Nearest", 4 to "AMD FSR 1", 5 to "AMD FSR 1 (fit)", 3 to "Snapdragon GSR", + 8 to "Snapdragon GSR (quality)", 7 to "NVIDIA NIS", 6 to "Sharpen only", ) fun upscaler(context: Context): Int = @@ -622,14 +631,58 @@ object SessionPrefs { prefs(context).edit().putInt("upscaler", mode).apply() } - val upscaleSharpnessChoices = listOf(0 to "0%", 25 to "25%", 50 to "50%", 75 to "75%", 100 to "100%") - fun upscaleSharpness(context: Context): Int = prefs(context).getInt("upscaleSharpness", 75).coerceIn(0, 100) fun setUpscaleSharpness(context: Context, pct: Int) { prefs(context).edit().putInt("upscaleSharpness", pct.coerceIn(0, 100)).apply() } + // ── Screen effects and texture filtering (the Display page) ───────────────────────────── + + /** The compositor's post chain as last set; off until the user picks a Look or moves a row. */ + fun screenEffects(context: Context): ScreenEffects { + val text = prefs(context).getString("screenEffects", null) ?: return ScreenEffects.OFF + return runCatching { ScreenEffects.decode(JSONObject(text)) }.getOrDefault(ScreenEffects.OFF) + } + + fun setScreenEffects(context: Context, effects: ScreenEffects) { + prefs(context).edit().putString("screenEffects", effects.encode().toString()).apply() + } + + val textureAnisotropyChoices = TextureFiltering.ANISOTROPY.map { it to if (it == 0) "Off" else "${it}x" } + + val textureLodBiasChoices = TextureFiltering.LOD_BIAS.map { + it to when (it) { + TextureFiltering.LOD_BIAS_OFF -> "Off" + TextureFiltering.LOD_BIAS_AUTO -> "Auto (match scaling)" + else -> it + } + } + + /** Anisotropic filtering forced on DirectX 9-11 games (core/TextureFiltering); 0 = the game's own. */ + fun textureAnisotropy(context: Context): Int = + prefs(context).getInt("textureAnisotropy", 0).takeIf { it in TextureFiltering.ANISOTROPY } ?: 0 + + fun setTextureAnisotropy(context: Context, value: Int) { + prefs(context).edit().putInt("textureAnisotropy", value).apply() + publishGameEnvironment(context) + } + + /** Texture sharpness: the mip LOD bias choice (TextureFiltering.LOD_BIAS), "0" = the game's own. */ + fun textureLodBias(context: Context): String = + prefs(context).getString("textureLodBias", null)?.takeIf { it in TextureFiltering.LOD_BIAS } ?: TextureFiltering.LOD_BIAS_OFF + + fun setTextureLodBias(context: Context, choice: String) { + prefs(context).edit().putString("textureLodBias", choice).apply() + publishGameEnvironment(context) + } + + /** Hands the change to the next game launch (GameEnvironmentStore); the running game keeps its own. */ + private fun publishGameEnvironment(context: Context) { + runCatching { GameEnvironmentStore.publish(context) } + .onFailure { android.util.Log.e("GameEnvironment", "Could not update game environment", it) } + } + /** * The mode whose per-mode settings apply: a program run under gamescope (MODE_RUN) is a * fullscreen session like Steam's, so it takes Steam's display, driver and HDR choices. diff --git a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt index 4ad975e12e..c6c03f7dbb 100644 --- a/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt +++ b/app/src/main/java/com/droiddeck/launcher/session/SessionState.kt @@ -96,6 +96,14 @@ object SessionState { @Volatile var refreshHz: Float = 60f + /** + * How far the compositor enlarges the session onto the panel (panel over outputSize, long + * side to long side); set with outputSize. 0 before a session has been sized. Texture + * sharpness "Auto" (core/TextureFiltering) is derived from it when a game launches. + */ + @Volatile + var upscaleRatio: Float = 0f + /** The session's frame cap (SessionPrefs.fpsLimit), fixed when it starts; 0 = none. */ @Volatile var fpsLimit: Int = 0 diff --git a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt index a7673fea45..ff6a32d59b 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/ModeSettingsDialog.kt @@ -197,15 +197,14 @@ fun ModeSettingsPage(s: ModeSettings, a: ModeSettingsActions) { onPick = a.onFpsLimit, ) ChoiceRow( - host, "upscaler", "Upscaler", "Sharpens the picture where it is enlarged to the screen.", + host, "upscaler", stringResource(R.string.drawer_scaling), "How the picture is resized to the screen; the sharpening modes sharpen where it is enlarged.", com.droiddeck.launcher.session.SessionPrefs.upscalerChoices, s.upscaler, - note = "Works only when the session is smaller than the screen; Sharpen only works at any size. Costs a little GPU time.", + note = "The sharpening modes work only when the session is smaller than the screen; Linear, Nearest and Sharpen only work at any size. Costs a little GPU time.", onPick = a.onUpscaler, ) - ChoiceRow( - host, "upscale-sharpness", "Upscaler sharpness", null, - com.droiddeck.launcher.session.SessionPrefs.upscaleSharpnessChoices, s.upscaleSharpness, - enabled = s.upscaler != 0, onPick = a.onUpscaleSharpness, + SliderRow( + stringResource(R.string.drawer_scaling_sharpness), null, s.upscaleSharpness, 0..100, step = 5, + enabled = s.upscaler != 0, format = { "$it%" }, onChange = a.onUpscaleSharpness, ) if (editCustom) CustomResolutionDialog( initial = custom, diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt index 752485baf6..5d0f851d25 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SessionOverlay.kt @@ -27,6 +27,7 @@ import androidx.compose.animation.core.FastOutSlowInEasing import androidx.compose.foundation.layout.offset import androidx.compose.material.icons.Icons import androidx.compose.foundation.layout.heightIn +import androidx.compose.material.icons.outlined.AutoFixHigh import androidx.compose.material.icons.outlined.Home import androidx.compose.material.icons.outlined.MoreHoriz import androidx.compose.material.icons.outlined.PowerSettingsNew @@ -116,20 +117,24 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.platform.LocalContext import com.droiddeck.launcher.R import com.droiddeck.launcher.core.FexPreset +import com.droiddeck.launcher.core.TextureFiltering import com.droiddeck.launcher.gpu.FrameGen import com.droiddeck.launcher.gpu.Lossless +import com.droiddeck.launcher.gpu.ScreenEffectLooks +import com.droiddeck.launcher.gpu.ScreenEffects import com.droiddeck.launcher.session.SessionPrefs import com.droiddeck.launcher.session.ComponentsManager import com.droiddeck.launcher.input.SecondScreenDisplay import com.droiddeck.launcher.input.SecondScreenMode import kotlinx.coroutines.flow.collect +import java.util.Locale -private val drawerPageTitles = listOf(R.string.drawer_page_display, R.string.drawer_page_controls, R.string.drawer_page_components, R.string.drawer_page_settings) +private val drawerPageTitles = listOf(R.string.drawer_page_display, R.string.drawer_page_effects, R.string.drawer_page_controls, R.string.drawer_page_components, R.string.drawer_page_settings) /** One icon per drawer page, in page order (QAM-style tabs). */ -private val drawerPageIcons = listOf(Icons.Outlined.DesktopWindows, Icons.Outlined.SportsEsports, Icons.Outlined.Layers, Icons.Outlined.Settings) +private val drawerPageIcons = listOf(Icons.Outlined.DesktopWindows, Icons.Outlined.AutoFixHigh, Icons.Outlined.SportsEsports, Icons.Outlined.Layers, Icons.Outlined.Settings) -private val drawerPageEntries = listOf("hud", "touch", "cmp-proton", "suspend") +private val drawerPageEntries = listOf("hud", "look", "touch", "cmp-proton", "suspend") private class DrawerFocus { private val requesters = HashMap() @@ -173,6 +178,11 @@ class DrawerActions( val fillScreen: Boolean? = null, val upscaler: Int = 0, val upscaleSharpness: Int = 75, + /** The compositor's post chain (gpu/ScreenEffects), changed live. */ + val effects: ScreenEffects = ScreenEffects.OFF, + /** Texture filtering for DirectX 9-11 games (core/TextureFiltering); lands on their next launch. */ + val textureAnisotropy: Int = 0, + val textureLodBias: String = TextureFiltering.LOD_BIAS_OFF, val secondScreenMode: SecondScreenMode, val secondScreenDisplays: List, val selectedSecondScreenDisplay: Int, @@ -199,6 +209,9 @@ class DrawerActions( val onFillScreen: (Boolean) -> Unit = {}, val onUpscaler: (Int) -> Unit = {}, val onUpscaleSharpness: (Int) -> Unit = {}, + val onEffects: (ScreenEffects) -> Unit = {}, + val onTextureAnisotropy: (Int) -> Unit = {}, + val onTextureLodBias: (String) -> Unit = {}, val onSecondScreenMode: (SecondScreenMode) -> Unit, val onSecondScreenDisplay: (Int) -> Unit, val onLaunchAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit, @@ -348,30 +361,36 @@ fun SessionDrawer(open: Boolean, page: Int, controllerActive: Boolean, onPageCha modifier = Modifier.weight(1f).fillMaxWidth().verticalScroll(pageScroll[page]), ) { CompositionLocalProvider(LocalChipMinWidth provides 120.dp) { when (page) { - 0 -> SettingsGroup(stringResource(R.string.drawer_page_display)) { - ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, - chipModifier = focus.track(page, "hud"), onChange = a.onHud) - if (a.fillScreen != null) ToggleRow( - host, "fill", stringResource(R.string.drawer_fill), null, a.fillScreen, - chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen, - ) - ChoiceRow(host, "upscaler", "Upscaler", null, - SessionPrefs.upscalerChoices, a.upscaler, - chipModifier = focus.track(page, "upscaler"), onPick = a.onUpscaler) - ChoiceRow(host, "upscale-sharpness", "Upscaler sharpness", null, - SessionPrefs.upscaleSharpnessChoices, a.upscaleSharpness, enabled = a.upscaler != 0, - chipModifier = focus.track(page, "upscale-sharpness"), onPick = a.onUpscaleSharpness) - val fgOpen = host.open == "fg" - val fgLabel = FrameGen.label(LocalContext.current, a.frameGen) - SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) { - Box { - ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" } - FrameGenMenu(host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless) + 0 -> { + SettingsGroup(stringResource(R.string.drawer_page_display)) { + ToggleRow(host, "hud", stringResource(R.string.drawer_hud), null, a.hudOn, + chipModifier = focus.track(page, "hud"), onChange = a.onHud) + if (a.fillScreen != null) ToggleRow( + host, "fill", stringResource(R.string.drawer_fill), null, a.fillScreen, + chipModifier = focus.track(page, "fill"), onChange = a.onFillScreen, + ) + ChoiceRow(host, "upscaler", stringResource(R.string.drawer_scaling), null, + SessionPrefs.upscalerChoices, a.upscaler, + chipModifier = focus.track(page, "upscaler"), onPick = a.onUpscaler) + SliderRow(stringResource(R.string.drawer_scaling_sharpness), null, a.upscaleSharpness, 0..100, step = 5, + enabled = a.upscaler != 0, format = { "$it%" }, modifier = focus.track(page, "upscale-sharpness"), + onChange = a.onUpscaleSharpness) + val fgOpen = host.open == "fg" + val fgLabel = FrameGen.label(LocalContext.current, a.frameGen) + SettingsRow(stringResource(R.string.frame_gen_title), null, highlighted = fgOpen) { + Box { + ValueChip(fgLabel, fgOpen, modifier = focus.track(page, "fg")) { host.open = if (fgOpen) null else "fg" } + FrameGenMenu(host, a.frameGen, a.lossless, a.onFrameGenPick, a.onImportLossless) + } } } } + DRAWER_PAGE_EFFECTS -> { + ScreenEffectsGroup(host, a) { key -> focus.track(page, key) } + TextureFilteringGroup(host, a) { key -> focus.track(page, key) } + } DRAWER_PAGE_COMPONENTS -> ComponentsDrawerPage(host, a) { key -> focus.track(page, key) } - 1 -> { + DRAWER_PAGE_CONTROLS -> { SettingsGroup(stringResource(R.string.drawer_page_controls)) { ChoiceRow(host, "touch", stringResource(R.string.mode_touch), null, listOf(SessionPrefs.TOUCH_AUTO to stringResource(R.string.drawer_touch_auto, a.touchAuto), SessionPrefs.TOUCH_PAD to stringResource(R.string.mode_touch_touchpad), SessionPrefs.TOUCH_DIRECT to stringResource(R.string.mode_touch_direct), SessionPrefs.TOUCH_OFF to stringResource(R.string.widgets_off)), @@ -674,10 +693,71 @@ private fun DrawerPageTabs(page: Int, modifier: Modifier = Modifier, compact: Bo } } -/** Display, Controls, Components, Settings. */ -const val DRAWER_PAGES = 4 +/** The Look row's value when the rows below match no Look. */ +private const val LOOK_CUSTOM = "custom" -private const val DRAWER_PAGE_COMPONENTS = 2 +/** + * Screen effects on the Effects page: a Look row that moves every row under it, then the rows + * themselves: switches and sliders the d-pad steps (SliderRow), so a pad drives them. + */ +@Composable +private fun ScreenEffectsGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + val e = a.effects + val look = ScreenEffectLooks.match(e, a.upscaler) + SettingsGroup(stringResource(R.string.drawer_effects)) { + val looks = ScreenEffectLooks.LOOKS.map { it.name to it.name } + ChoiceRow(host, "look", stringResource(R.string.drawer_look), + look?.desc ?: stringResource(R.string.drawer_effects_hint), + if (look == null) listOf(LOOK_CUSTOM to stringResource(R.string.drawer_look_custom)) + looks else looks, + look?.name ?: LOOK_CUSTOM, chipModifier = track("look"), hintLines = 2) { name -> + ScreenEffectLooks.LOOKS.firstOrNull { it.name == name }?.let { picked -> + picked.scalingMode?.let(a.onUpscaler) + a.onEffects(picked.effects) + } + } + ToggleRow(host, "cas", stringResource(R.string.drawer_cas), null, e.cas, chipModifier = track("cas")) { a.onEffects(e.copy(cas = it)) } + SliderRow(stringResource(R.string.drawer_cas_level), null, e.casLevel, 0..100, step = 5, enabled = e.cas, + format = { "$it%" }, modifier = track("cas-level")) { a.onEffects(e.copy(casLevel = it)) } + ToggleRow(host, "fake-hdr", stringResource(R.string.drawer_fake_hdr), null, e.hdr, chipModifier = track("fake-hdr")) { a.onEffects(e.copy(hdr = it)) } + ToggleRow(host, "deband", stringResource(R.string.drawer_deband), null, e.deband, chipModifier = track("deband")) { a.onEffects(e.copy(deband = it)) } + SliderRow(stringResource(R.string.drawer_deband_strength), null, e.debandStrength, 0..200, step = 5, enabled = e.deband, + format = { "$it%" }, modifier = track("deband-strength")) { a.onEffects(e.copy(debandStrength = it)) } + SliderRow(stringResource(R.string.drawer_brightness), null, e.brightness, -100..100, step = 2, + format = ::signed, modifier = track("brightness")) { a.onEffects(e.copy(brightness = it)) } + SliderRow(stringResource(R.string.drawer_contrast), null, e.contrast, -100..100, step = 2, + format = ::signed, modifier = track("contrast")) { a.onEffects(e.copy(contrast = it)) } + SliderRow(stringResource(R.string.drawer_gamma), null, (e.gamma * 100f).roundToInt(), 50..300, step = 5, + format = { String.format(Locale.US, "%.2f", it / 100f) }, modifier = track("gamma")) { a.onEffects(e.copy(gamma = it / 100f)) } + SliderRow(stringResource(R.string.drawer_saturation), null, e.saturation, 0..200, step = 5, + format = { "$it%" }, modifier = track("saturation")) { a.onEffects(e.copy(saturation = it)) } + ToggleRow(host, "fxaa", stringResource(R.string.drawer_fxaa), null, e.fxaa, chipModifier = track("fxaa")) { a.onEffects(e.copy(fxaa = it)) } + ToggleRow(host, "toon", stringResource(R.string.drawer_toon), null, e.toon, chipModifier = track("toon")) { a.onEffects(e.copy(toon = it)) } + ToggleRow(host, "crt", stringResource(R.string.drawer_crt), null, e.crt, chipModifier = track("crt")) { a.onEffects(e.copy(crt = it)) } + ToggleRow(host, "ntsc", stringResource(R.string.drawer_ntsc), null, e.ntsc, chipModifier = track("ntsc")) { a.onEffects(e.copy(ntsc = it)) } + } +} + +/** Texture filtering on the Effects page: DXVK options for the next DirectX 9-11 launch. */ +@Composable +private fun TextureFilteringGroup(host: MenuHost, a: DrawerActions, track: (String) -> Modifier) { + SettingsGroup(stringResource(R.string.drawer_texture)) { + ChoiceRow(host, "anisotropy", stringResource(R.string.drawer_anisotropy), stringResource(R.string.drawer_texture_hint), + SessionPrefs.textureAnisotropyChoices, a.textureAnisotropy, chipModifier = track("anisotropy"), onPick = a.onTextureAnisotropy) + ChoiceRow(host, "texture-sharpness", stringResource(R.string.drawer_texture_sharpness), stringResource(R.string.drawer_texture_hint), + SessionPrefs.textureLodBiasChoices, a.textureLodBias, note = stringResource(R.string.drawer_texture_sharpness_note), + chipModifier = track("texture-sharpness"), onPick = a.onTextureLodBias) + } +} + +private fun signed(v: Int) = if (v > 0) "+$v" else "$v" + +/** Display, Effects, Controls, Components, Settings. */ +const val DRAWER_PAGES = 5 + +private const val DRAWER_PAGE_EFFECTS = 1 +private const val DRAWER_PAGE_CONTROLS = 2 + +private const val DRAWER_PAGE_COMPONENTS = 3 /** * The drawer's Components tab: quick swaps between what is already installed, per Proton. A swap diff --git a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt index 2d745c78bc..323cdb0809 100644 --- a/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt +++ b/app/src/main/java/com/droiddeck/launcher/ui/SettingsWidgets.kt @@ -67,6 +67,17 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.TransformOrigin import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.key.onPreviewKeyEvent +import androidx.compose.foundation.focusable +import androidx.compose.foundation.gestures.detectHorizontalDragGestures +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.fillMaxHeight +import androidx.compose.runtime.mutableIntStateOf +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onSizeChanged +import androidx.compose.ui.semantics.ProgressBarRangeInfo +import androidx.compose.ui.semantics.progressBarRangeInfo +import androidx.compose.ui.text.style.TextAlign +import kotlin.math.roundToInt import androidx.compose.ui.input.InputMode import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalInputModeManager @@ -338,17 +349,26 @@ fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable Column(modifier = Modifier.fillMaxWidth().clip(GroupShape).background(colors.surface).border(1.dp, pal.line, GroupShape)) { content() } } +/** + * One setting: its label and [hint] with the [control] beside them. [hintLines] fixes the hint to + * that many lines, for a hint that changes with the value - the row keeps its height, so the rows + * under it stay put. + */ @Composable -fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, control: @Composable () -> Unit) { +fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, hintLines: Int? = null, control: @Composable () -> Unit) { val colors = MaterialTheme.colorScheme val pal = LocalPalette.current val bg by animateColorAsState(if (highlighted) pal.signal.copy(alpha = 0.10f) else Color.Transparent, Motion.tw(200), label = "rowBg") + val hintText: @Composable (androidx.compose.ui.unit.TextUnit) -> Unit = { size -> + Text(hint ?: "", fontSize = size, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp), + minLines = hintLines ?: 1, maxLines = hintLines ?: Int.MAX_VALUE, overflow = TextOverflow.Ellipsis) + } // A narrow page stacks the control under its label, so neither squeezes the other. if (LocalNarrowPane.current) Column( modifier = Modifier.fillMaxWidth().background(bg).padding(start = 14.dp, end = 14.dp, top = 11.dp, bottom = 12.dp), ) { Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) - if (hint != null) Text(hint, fontSize = 13.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) + if (hint != null || hintLines != null) hintText(13.sp) Box(Modifier.padding(top = 8.dp)) { control() } } else Row( verticalAlignment = Alignment.CenterVertically, @@ -356,7 +376,7 @@ fun SettingsRow(label: String, hint: String?, highlighted: Boolean = false, cont ) { Column(modifier = Modifier.weight(1f).padding(end = 12.dp)) { Text(label, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground) - if (hint != null) Text(hint, fontSize = 12.5.sp, color = colors.onSurfaceVariant, modifier = Modifier.padding(top = 2.dp)) + if (hint != null || hintLines != null) hintText(12.5.sp) } control() } @@ -369,10 +389,12 @@ fun ChoiceRow( options: List>, selected: T, enabled: Boolean = true, note: String? = null, /** For the box itself - a page's FocusRequester for its first control. */ chipModifier: Modifier = Modifier, + /** See SettingsRow: a fixed height for a hint that changes with the choice. */ + hintLines: Int? = null, onPick: (T) -> Unit, ) { val open = host.open == key - SettingsRow(label, hint, highlighted = open) { + SettingsRow(label, hint, highlighted = open, hintLines = hintLines) { Box { ValueChip(options.firstOrNull { it.first == selected }?.second ?: "-", open, enabled, modifier = chipModifier) { host.open = if (open) null else key } AnchoredMenu(open, onDismiss = { if (host.open == key) host.open = null }, title = label, note = note) { firstItemFocus -> @@ -431,6 +453,88 @@ fun ToggleSwitch(checked: Boolean, enabled: Boolean = true, label: String? = nul } } +/** + * A bounded value as a track: the d-pad's left and right step it by [step] (held, it keeps + * going), a finger drags or taps it, and [format] prints the value beside it. [modifier] goes on + * the focusable part, for a page's focus tracking. + */ +@Composable +fun SliderRow( + label: String, hint: String?, value: Int, range: IntRange, step: Int = 1, enabled: Boolean = true, + format: (Int) -> String = { it.toString() }, modifier: Modifier = Modifier, onChange: (Int) -> Unit, +) = SettingsRow(label, hint) { + ValueSlider(value, range, step, enabled, label, format, modifier, onChange) +} + +@Composable +fun ValueSlider( + value: Int, range: IntRange, step: Int, enabled: Boolean, label: String?, format: (Int) -> String, + modifier: Modifier = Modifier, onChange: (Int) -> Unit, +) { + val colors = MaterialTheme.colorScheme + val pal = LocalPalette.current + val src = remember { MutableInteractionSource() } + val hot = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value + val span = (range.last - range.first).coerceAtLeast(1) + val fraction = ((value - range.first).toFloat() / span).coerceIn(0f, 1f) + val shape = RoundedCornerShape(99.dp) + var trackPx by remember { mutableIntStateOf(0) } + val text = format(value) + // A step from the d-pad lands on the grid of [step] from the range's start; a Look's own + // value, which need not be on it, is kept until the user moves. + fun stepped(v: Int) = (((v - range.first).toFloat() / step).roundToInt() * step + range.first).coerceIn(range.first, range.last) + fun fromX(x: Float) { if (trackPx > 0) onChange(stepped(range.first + (x / trackPx * span).roundToInt())) } + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = modifier + .heightIn(min = 48.dp) + .alpha(if (enabled) 1f else 0.5f) + .hoverable(src) + .focusable(enabled, src) + .onPreviewKeyEvent { event -> + val keyEvent = event.nativeKeyEvent + val left = keyEvent.keyCode == KeyEvent.KEYCODE_DPAD_LEFT + if (!left && keyEvent.keyCode != KeyEvent.KEYCODE_DPAD_RIGHT) { + false + } else { + // Every down counts, repeats included, so a held direction keeps stepping. + if (enabled && keyEvent.action == KeyEvent.ACTION_DOWN) { + val next = stepped(value + if (left) -step else step) + if (next != value) onChange(next) + } + true + } + } + .semantics { + stateDescription = text + progressBarRangeInfo = ProgressBarRangeInfo(value.toFloat(), range.first.toFloat()..range.last.toFloat()) + if (label != null) contentDescription = label + }, + ) { + Text(text, fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground, textAlign = TextAlign.End, + maxLines = 1, modifier = Modifier.width(56.dp)) + Spacer(Modifier.width(10.dp)) + Box( + contentAlignment = Alignment.CenterStart, + modifier = Modifier.size(width = 164.dp, height = 30.dp).clip(shape).background(colors.surfaceVariant) + .glideBorder(hot, shape, colors.onBackground, pal.line2) + .onSizeChanged { trackPx = it.width } + .pointerInput(enabled, range, step) { if (enabled) detectTapGestures { fromX(it.x) } } + .pointerInput(enabled, range, step) { + if (enabled) detectHorizontalDragGestures { change, _ -> fromX(change.position.x); change.consume() } + }, + ) { + Box(Modifier.fillMaxWidth(fraction).fillMaxHeight().background(pal.signal)) + Box( + Modifier.padding(4.dp).size(22.dp) + .graphicsLayer { translationX = fraction * (trackPx - 30.dp.toPx()).coerceAtLeast(0f) } + .clip(CircleShape) + .background(pal.onSignal), + ) + } + } +} + @Composable fun MultiRow( host: MenuHost, key: String, label: String, hint: String?, diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 4d89059f52..347916beba 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -400,6 +400,7 @@ Sus archivos se eliminan de la app. Sus archivos se eliminan. Está en uso, así que pasa a usarse el predeterminado. Pantalla + Efectos Controles Componentes Ajustes @@ -412,6 +413,30 @@ Página siguiente HUD de rendimiento Estirar juegos para llenar + Modo de escalado + Nitidez del escalado + Efectos de pantalla + En vivo. Usa algo de GPU mientras haya un efecto activo. + Estilo + Personalizado + Nitidez (CAS) + Nivel de nitidez + HDR simulado + Reducción de bandas + Intensidad de reducción de bandas + Brillo + Contraste + Gamma + Saturación + FXAA (suavizado de bordes) + Contornos toon + CRT + NTSC + Filtrado de texturas + Juegos DirectX 9–11, desde su próximo inicio. + Filtrado anisotrópico + Nitidez de texturas + Un sesgo de mip negativo: texturas más nítidas, algo de parpadeo. Auto sigue cuánto se amplía la sesión a la pantalla. Auto (%1$s) Teclado Teclado de PC diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 8f50aa99f8..81d0b87d8e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -430,6 +430,7 @@ Its files are removed from the app. Its files are removed. It\'s in use, so the default takes over. Display + Effects Controls Components Settings @@ -443,6 +444,30 @@ Next page Performance HUD Stretch games to fill + Scaling mode + Scaling sharpness + Screen effects + Live. Costs a little GPU time while any effect is on. + Look + Custom + Sharpening (CAS) + Sharpening level + Fake HDR + Debanding + Debanding strength + Brightness + Contrast + Gamma + Saturation + FXAA (edge smoothing) + Toon outlines + CRT + NTSC + Texture filtering + DirectX 9–11 games, from their next launch. + Anisotropic filtering + Texture sharpness + A negative mip bias: sharper textures, some shimmer. Auto matches how far the session is enlarged to the screen. Auto (%1$s) Keyboard PC keyboard diff --git a/app/src/test/java/com/droiddeck/launcher/core/TextureFilteringTest.kt b/app/src/test/java/com/droiddeck/launcher/core/TextureFilteringTest.kt new file mode 100644 index 0000000000..f35256fdcb --- /dev/null +++ b/app/src/test/java/com/droiddeck/launcher/core/TextureFilteringTest.kt @@ -0,0 +1,35 @@ +package com.droiddeck.launcher.core + +import org.junit.Assert.* +import org.junit.Test + +class TextureFilteringTest { + @Test fun autoBiasFollowsFsrGuidanceAndStopsAtNoEnlargement() { + assertEquals(0f, TextureFiltering.autoLodBias(1f), 0f) + assertEquals(0f, TextureFiltering.autoLodBias(0f), 0f) + assertEquals(0f, TextureFiltering.autoLodBias(Float.NaN), 0f) + assertEquals(-0.58f, TextureFiltering.autoLodBias(1.5f), 0.01f) + assertEquals(-1f, TextureFiltering.autoLodBias(2f), 0.001f) + assertEquals(-2f, TextureFiltering.autoLodBias(16f), 0f) + } + + @Test fun optionsNameBothApisAndUseDotDecimals() { + assertEquals("", TextureFiltering.dxvkOptions(0, TextureFiltering.LOD_BIAS_OFF, -0.58f)) + assertEquals("d3d9.samplerAnisotropy = 16; d3d11.samplerAnisotropy = 16", TextureFiltering.dxvkOptions(16, "0", 0f)) + assertEquals( + "d3d9.samplerLodBias = -0.58; d3d11.samplerLodBias = -0.58", + TextureFiltering.dxvkOptions(0, TextureFiltering.LOD_BIAS_AUTO, -0.58f), + ) + assertEquals( + "d3d9.samplerAnisotropy = 8; d3d11.samplerAnisotropy = 8; d3d9.samplerLodBias = -0.50; d3d11.samplerLodBias = -0.50", + TextureFiltering.dxvkOptions(8, "-0.5", 0f), + ) + } + + @Test fun unknownValuesLeaveTheGameAlone() { + assertEquals("", TextureFiltering.dxvkOptions(3, "junk", 0f)) + assertEquals("", TextureFiltering.dxvkOptions(0, TextureFiltering.LOD_BIAS_AUTO, 0f)) + assertEquals("", TextureFiltering.dxvkOptions(0, "0.5", 0f)) + assertEquals(-2f, TextureFiltering.lodBias("-9", 0f), 0f) + } +} diff --git a/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt b/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt index 604c9456ae..07cbc6efe9 100644 --- a/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt +++ b/app/src/test/java/com/droiddeck/launcher/session/GameEnvironmentStoreTest.kt @@ -49,6 +49,26 @@ class GameEnvironmentStoreTest { assertFalse(JSONObject(guest.readText()).getJSONObject("shared").has("FEX_SMCCHECKS")) } + @Test fun textureFilteringPublishesDxvkOptionsBesideTheProfiles() { + GameEnvironmentStore.save(context, GameEnvironment.Config(shared = mapOf("DXVK_CONFIG" to "dxvk.tearFree = True"))) + assertFalse(JSONObject(guest.readText()).has(GameEnvironmentStore.DXVK_CONFIG)) + SessionState.upscaleRatio = 1.5f + SessionPrefs.setTextureAnisotropy(context, 16) + SessionPrefs.setTextureLodBias(context, com.droiddeck.launcher.core.TextureFiltering.LOD_BIAS_AUTO) + val json = JSONObject(guest.readText()) + assertEquals( + "d3d9.samplerAnisotropy = 16; d3d11.samplerAnisotropy = 16; d3d9.samplerLodBias = -0.58; d3d11.samplerLodBias = -0.58", + json.getString(GameEnvironmentStore.DXVK_CONFIG), + ) + // The user's own entry is untouched; the launcher appends the options at launch. + assertEquals("dxvk.tearFree = True", json.getJSONObject("shared").getString("DXVK_CONFIG")) + assertEquals(GameEnvironment.Config(shared = mapOf("DXVK_CONFIG" to "dxvk.tearFree = True")), GameEnvironmentStore.read(context)) + SessionPrefs.setTextureAnisotropy(context, 0) + SessionPrefs.setTextureLodBias(context, "0") + assertFalse(JSONObject(guest.readText()).has(GameEnvironmentStore.DXVK_CONFIG)) + SessionState.upscaleRatio = 0f + } + @Test fun unchosenFexPresetPublishesPerformanceTso() { GameEnvironmentStore.save(context, GameEnvironment.Config()) val shared = JSONObject(guest.readText()).getJSONObject("shared") diff --git a/docs/development/game-environment.md b/docs/development/game-environment.md index 5b9244a662..92e4ede45d 100644 --- a/docs/development/game-environment.md +++ b/docs/development/game-environment.md @@ -68,6 +68,13 @@ Proton. Probe prefix `compatdata/0` and non-launch verbs are unchanged. Malforme configuration falls back to the inherited environment without evaluating its contents. Signed non-Steam prefix IDs are normalized to unsigned IDs. +The published file also carries a `dxvkConfig` string the app's own file never +has: the session menu's texture filtering (Effects page; `core/TextureFiltering`) +as `d3d9/d3d11.samplerAnisotropy` and `samplerLodBias` options. The launcher +appends it to `DXVK_CONFIG` after the profiles, so a user's own `DXVK_CONFIG` +entry keeps its options. "Auto" texture sharpness is `-log2(panel / session)`, +derived when the session is sized, and applies from the next launch. + Upstream references: [VKD3D capability parsing](https://github.com/HansKristian-Work/vkd3d-proton/blob/master/libs/vkd3d/device.c), [VKD3D options](https://github.com/HansKristian-Work/vkd3d-proton#environment-variables), [Proton runtime options](https://github.com/ValveSoftware/Proton/tree/proton_11.0#runtime-config-options), diff --git a/tools/linuxfs/overlay/usr/local/bin/bannerlator-game-env b/tools/linuxfs/overlay/usr/local/bin/bannerlator-game-env index ff9e87449b..a9859affc6 100755 --- a/tools/linuxfs/overlay/usr/local/bin/bannerlator-game-env +++ b/tools/linuxfs/overlay/usr/local/bin/bannerlator-game-env @@ -34,6 +34,15 @@ def apply_config(env, config, app_id): result[name] = value else: raise ValueError("invalid environment value") + # The app's texture filtering (Display page), as DXVK options appended after the profiles so + # a DXVK_CONFIG entry of the user's keeps its own. + dxvk = config.get("dxvkConfig") + if dxvk is not None: + if not isinstance(dxvk, str) or "\0" in dxvk or len(dxvk) > 8192: + raise ValueError("invalid dxvk configuration") + if dxvk: + own = result.get("DXVK_CONFIG", "").strip().rstrip(";").strip() + result["DXVK_CONFIG"] = own + "; " + dxvk if own else dxvk return result diff --git a/tools/tests/test_game_environment.py b/tools/tests/test_game_environment.py index 8c37d1123c..49a3dea5fb 100644 --- a/tools/tests/test_game_environment.py +++ b/tools/tests/test_game_environment.py @@ -27,6 +27,19 @@ class GameEnvironmentTest(unittest.TestCase): MODULE["apply_config"](env, {"version": 1, "shared": entries}, "42") self.assertEqual(env, {"ORIGINAL": "unchanged"}) + def test_texture_filtering_is_appended_to_dxvk_config(self): + options = "d3d9.samplerAnisotropy = 16; d3d11.samplerAnisotropy = 16" + config = {"version": 1, "shared": {}, "games": {}, "dxvkConfig": options} + self.assertEqual(MODULE["apply_config"]({}, config, "42")["DXVK_CONFIG"], options) + own = {"DXVK_CONFIG": "dxvk.maxFrameRate = 60; "} + self.assertEqual(MODULE["apply_config"](own, config, "42")["DXVK_CONFIG"], "dxvk.maxFrameRate = 60; " + options) + shared = {"version": 1, "shared": {"DXVK_CONFIG": "dxvk.tearFree = True"}, "games": {}, "dxvkConfig": options} + self.assertEqual(MODULE["apply_config"]({}, shared, "42")["DXVK_CONFIG"], "dxvk.tearFree = True; " + options) + self.assertNotIn("DXVK_CONFIG", MODULE["apply_config"]({}, {**config, "dxvkConfig": ""}, "42")) + for bad in (1, "a\0b", "x" * 8193): + with self.assertRaises(ValueError): + MODULE["apply_config"]({}, {**config, "dxvkConfig": bad}, "42") + def test_game_ids_and_probes(self): for prefix in ("", "/compatdata/0", "/compatdata/0-123", "/compatdata/nope", "/compatdata/4294967296"): self.assertIsNone(MODULE["game_id"]({"STEAM_COMPAT_DATA_PATH": prefix}))