mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-12-05 12:35:42 +00:00
Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14ae112a7b | ||
|
|
f27a4f6c95 | ||
|
|
34a17acaba | ||
|
|
c20a166134 | ||
|
|
162fa8e2de | ||
|
|
ae5614d212 | ||
|
|
b72d8a8bab | ||
|
|
d4cf890d8a | ||
|
|
82e494269d | ||
|
|
c3b0d8ef03 | ||
|
|
73e2fc58a0 | ||
|
|
911ad29004 | ||
|
|
aa843b5a31 | ||
|
|
f249acc50f | ||
|
|
9422608960 | ||
|
|
de37ddcfb5 | ||
|
|
4c90196890 | ||
|
|
30f6ca6ffc | ||
|
|
ecff3240a6 | ||
|
|
ddd4a0c24d | ||
|
|
019949847a | ||
|
|
4dcbf269d2 |
No files matched your search
@@ -121,6 +121,10 @@ android {
|
||||
}
|
||||
|
||||
packagingOptions {
|
||||
resources {
|
||||
// Kadb's Bouncy Castle artifacts repeat the same multi-release JAR manifest.
|
||||
excludes += ['META-INF/versions/9/OSGI-INF/MANIFEST.MF']
|
||||
}
|
||||
jniLibs {
|
||||
// The PulseAudio daemon is executed from the native library directory and its
|
||||
// libraries are read out of the apk by the class loader: both want the old,
|
||||
@@ -160,6 +164,9 @@ dependencies {
|
||||
implementation 'androidx.compose.material:material-icons-extended'
|
||||
implementation 'io.coil-kt:coil-compose:2.6.0'
|
||||
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
|
||||
// ADB-over-Wi-Fi pairing and authenticated shell client. Users still approve pairing from
|
||||
// Android's Wireless debugging screen; DroidDeck only runs its one fixed setting command.
|
||||
implementation 'com.flyfishxu:kadb-android:1.2.1'
|
||||
// Android terminal view/emulator used by the in-session secondary-display Linux shell.
|
||||
implementation 'com.termux.termux-app:terminal-view:0.118.0'
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
|
||||
<uses-permission android:name="android.permission.INTERNET" />
|
||||
<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />
|
||||
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||
<!-- Session logs go to Downloads so a failed run can be handed over as one folder. -->
|
||||
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
|
||||
|
||||
Binary file not shown.
@@ -18,6 +18,7 @@ add_library(bannerwayland SHARED
|
||||
src/wl_toplevel_icon.c
|
||||
src/wl_color_mgmt.c
|
||||
src/hdr_compose.c
|
||||
src/blend_pass.c
|
||||
generated/color-management-v1-protocol.c
|
||||
generated/xdg-shell-protocol.c
|
||||
generated/linux-dmabuf-v1-protocol.c
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#version 450
|
||||
// Wayland buffers carry premultiplied alpha; the pipeline blends ONE, ONE_MINUS_SRC_ALPHA.
|
||||
layout(binding = 0) uniform sampler2D Surface;
|
||||
layout(location = 0) in vec2 uv;
|
||||
layout(location = 0) out vec4 outColor;
|
||||
|
||||
void main() {
|
||||
outColor = texture(Surface, uv);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#version 450
|
||||
// One surface as a quad: dst = the target rectangle in NDC, src = the buffer rectangle in UV.
|
||||
layout(push_constant) uniform PC { vec4 dst; vec4 src; } pc;
|
||||
layout(location = 0) out vec2 uv;
|
||||
|
||||
void main() {
|
||||
vec2 t = vec2(gl_VertexIndex & 1, gl_VertexIndex >> 1);
|
||||
gl_Position = vec4(mix(pc.dst.xy, pc.dst.zw, t), 0.0, 1.0);
|
||||
uv = mix(pc.src.xy, pc.src.zw, t);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
// 1115.1.0
|
||||
#pragma once
|
||||
const uint32_t blend_frag_code[] = {
|
||||
0x07230203,0x00010000,0x0008000b,0x00000014,0x00000000,0x00020011,0x00000001,0x0006000b,
|
||||
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
|
||||
0x0007000f,0x00000004,0x00000004,0x6e69616d,0x00000000,0x00000009,0x00000011,0x00030010,
|
||||
0x00000004,0x00000007,0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,
|
||||
0x00000000,0x00050005,0x00000009,0x4374756f,0x726f6c6f,0x00000000,0x00040005,0x0000000d,
|
||||
0x66727553,0x00656361,0x00030005,0x00000011,0x00007675,0x00040047,0x00000009,0x0000001e,
|
||||
0x00000000,0x00040047,0x0000000d,0x00000021,0x00000000,0x00040047,0x0000000d,0x00000022,
|
||||
0x00000000,0x00040047,0x00000011,0x0000001e,0x00000000,0x00020013,0x00000002,0x00030021,
|
||||
0x00000003,0x00000002,0x00030016,0x00000006,0x00000020,0x00040017,0x00000007,0x00000006,
|
||||
0x00000004,0x00040020,0x00000008,0x00000003,0x00000007,0x0004003b,0x00000008,0x00000009,
|
||||
0x00000003,0x00090019,0x0000000a,0x00000006,0x00000001,0x00000000,0x00000000,0x00000000,
|
||||
0x00000001,0x00000000,0x0003001b,0x0000000b,0x0000000a,0x00040020,0x0000000c,0x00000000,
|
||||
0x0000000b,0x0004003b,0x0000000c,0x0000000d,0x00000000,0x00040017,0x0000000f,0x00000006,
|
||||
0x00000002,0x00040020,0x00000010,0x00000001,0x0000000f,0x0004003b,0x00000010,0x00000011,
|
||||
0x00000001,0x00050036,0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,
|
||||
0x0004003d,0x0000000b,0x0000000e,0x0000000d,0x0004003d,0x0000000f,0x00000012,0x00000011,
|
||||
0x00050057,0x00000007,0x00000013,0x0000000e,0x00000012,0x0003003e,0x00000009,0x00000013,
|
||||
0x000100fd,0x00010038
|
||||
};
|
||||
@@ -0,0 +1,315 @@
|
||||
/* Alpha composition: one surface drawn source-over onto the scene - see blend_pass.h. Compositor thread. */
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#include "blend_pass.h"
|
||||
#include "vk_loader.h"
|
||||
#include "vk_present.h" /* banner_log, vkp_gpu_name */
|
||||
#include <string.h>
|
||||
|
||||
/* SPIR-V, pre-compiled (glslangValidator -V blend.vert --vn blend_vert_code, the same for blend.frag)
|
||||
* and committed next to the GLSL: the NDK build compiles no shaders. */
|
||||
#include "blend_vert.h"
|
||||
#include "blend_frag.h"
|
||||
|
||||
struct pc_blend { float dst[4]; float src[4]; };
|
||||
|
||||
static VkDevice g_dev;
|
||||
static int g_ready; /* 0 = not built, 1 = ok, -1 = unavailable (said once) */
|
||||
static VkSampler g_sampler;
|
||||
static VkDescriptorSetLayout g_dsl;
|
||||
static VkPipelineLayout g_pl;
|
||||
static VkDescriptorPool g_dpool;
|
||||
static VkShaderModule g_vert, g_frag;
|
||||
static unsigned g_frame = 1;
|
||||
|
||||
/* One render pass + pipeline per target format: the screen swapchain's, the scene image's, the HDR
|
||||
* composition's. */
|
||||
#define NFMT 4
|
||||
static struct { VkFormat fmt; VkRenderPass rp; VkPipeline pipe; } g_out[NFMT];
|
||||
|
||||
#define NSRC 32
|
||||
static struct { VkImage img; VkImageView view; VkDescriptorSet ds; unsigned frame; } g_src[NSRC];
|
||||
#define NDST 12
|
||||
static struct { VkImage img; VkFormat fmt; int w, h; VkImageView view; VkFramebuffer fb; unsigned frame; } g_dst[NDST];
|
||||
|
||||
void blendp_bind_device(VkDevice dev) { g_dev = dev; }
|
||||
|
||||
void blendp_begin_frame(void) { g_frame++; }
|
||||
|
||||
static void src_release(int i) {
|
||||
if (g_src[i].ds) g_vk.FreeDescriptorSets(g_dev, g_dpool, 1, &g_src[i].ds);
|
||||
if (g_src[i].view) g_vk.DestroyImageView(g_dev, g_src[i].view, NULL);
|
||||
memset(&g_src[i], 0, sizeof(g_src[i]));
|
||||
}
|
||||
|
||||
static void dst_release(int i) {
|
||||
if (g_dst[i].fb) g_vk.DestroyFramebuffer(g_dev, g_dst[i].fb, NULL);
|
||||
if (g_dst[i].view) g_vk.DestroyImageView(g_dev, g_dst[i].view, NULL);
|
||||
memset(&g_dst[i], 0, sizeof(g_dst[i]));
|
||||
}
|
||||
|
||||
void blendp_forget_image(VkImage img) {
|
||||
if (!g_dev || !img) return;
|
||||
for (int i = 0; i < NSRC; i++) if (g_src[i].img == img) src_release(i);
|
||||
for (int i = 0; i < NDST; i++) if (g_dst[i].img == img) dst_release(i);
|
||||
}
|
||||
|
||||
static VkShaderModule shader(const uint32_t *code, size_t size) {
|
||||
VkShaderModule m = VK_NULL_HANDLE;
|
||||
VkShaderModuleCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, .codeSize = size, .pCode = code};
|
||||
if (g_vk.CreateShaderModule(g_dev, &ci, NULL, &m) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
return m;
|
||||
}
|
||||
|
||||
/* The target keeps what the blits put there (LOAD) and stays in TRANSFER_DST_OPTIMAL for the blits
|
||||
* that follow. The dependencies order the pass between them. */
|
||||
static VkRenderPass make_rp(VkFormat fmt) {
|
||||
VkAttachmentDescription att = {.format = fmt, .samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD, .storeOp = VK_ATTACHMENT_STORE_OP_STORE,
|
||||
.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE,
|
||||
.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
|
||||
.finalLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL};
|
||||
VkAttachmentReference ref = {0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
|
||||
VkSubpassDescription sub = {.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS, .colorAttachmentCount = 1,
|
||||
.pColorAttachments = &ref};
|
||||
VkSubpassDependency deps[2] = {
|
||||
{.srcSubpass = VK_SUBPASS_EXTERNAL, .dstSubpass = 0,
|
||||
.srcStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
|
||||
.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
|
||||
.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
|
||||
.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT},
|
||||
{.srcSubpass = 0, .dstSubpass = VK_SUBPASS_EXTERNAL,
|
||||
.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
|
||||
.dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT | VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
|
||||
.srcAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,
|
||||
.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT | VK_ACCESS_TRANSFER_WRITE_BIT |
|
||||
VK_ACCESS_COLOR_ATTACHMENT_READ_BIT | VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT}};
|
||||
VkRenderPassCreateInfo rci = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, .attachmentCount = 1,
|
||||
.pAttachments = &att, .subpassCount = 1, .pSubpasses = &sub,
|
||||
.dependencyCount = 2, .pDependencies = deps};
|
||||
VkRenderPass rp = VK_NULL_HANDLE;
|
||||
if (g_vk.CreateRenderPass(g_dev, &rci, NULL, &rp) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
return rp;
|
||||
}
|
||||
|
||||
static VkPipeline make_pipe(VkRenderPass rp) {
|
||||
VkPipelineShaderStageCreateInfo st[2] = {
|
||||
{.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_VERTEX_BIT,
|
||||
.module = g_vert, .pName = "main"},
|
||||
{.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, .stage = VK_SHADER_STAGE_FRAGMENT_BIT,
|
||||
.module = g_frag, .pName = "main"}};
|
||||
VkPipelineVertexInputStateCreateInfo vi = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
|
||||
VkPipelineInputAssemblyStateCreateInfo ia = {.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO,
|
||||
.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP};
|
||||
VkDynamicState dyn[2] = {VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR};
|
||||
VkPipelineDynamicStateCreateInfo ds = {.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO,
|
||||
.dynamicStateCount = 2, .pDynamicStates = dyn};
|
||||
VkPipelineViewportStateCreateInfo vp = {.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO,
|
||||
.viewportCount = 1, .scissorCount = 1};
|
||||
VkPipelineRasterizationStateCreateInfo rs = {.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO,
|
||||
.polygonMode = VK_POLYGON_MODE_FILL, .cullMode = VK_CULL_MODE_NONE,
|
||||
.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE, .lineWidth = 1.0f};
|
||||
VkPipelineMultisampleStateCreateInfo ms = {.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO,
|
||||
.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT};
|
||||
/* The target's alpha is left alone: the screen is opaque whatever is drawn onto it. */
|
||||
VkPipelineColorBlendAttachmentState ba = {
|
||||
.blendEnable = VK_TRUE, .srcColorBlendFactor = VK_BLEND_FACTOR_ONE,
|
||||
.dstColorBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, .colorBlendOp = VK_BLEND_OP_ADD,
|
||||
.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE, .dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
|
||||
.alphaBlendOp = VK_BLEND_OP_ADD,
|
||||
.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT};
|
||||
VkPipelineColorBlendStateCreateInfo cb = {.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO,
|
||||
.attachmentCount = 1, .pAttachments = &ba};
|
||||
VkGraphicsPipelineCreateInfo pi = {.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, .stageCount = 2,
|
||||
.pStages = st, .pVertexInputState = &vi, .pInputAssemblyState = &ia,
|
||||
.pViewportState = &vp, .pRasterizationState = &rs, .pMultisampleState = &ms,
|
||||
.pColorBlendState = &cb, .pDynamicState = &ds, .layout = g_pl,
|
||||
.renderPass = rp, .subpass = 0};
|
||||
VkPipeline p = VK_NULL_HANDLE;
|
||||
if (g_vk.CreateGraphicsPipelines(g_dev, VK_NULL_HANDLE, 1, &pi, NULL, &p) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
return p;
|
||||
}
|
||||
|
||||
static void objects_destroy(void) {
|
||||
if (g_vert) g_vk.DestroyShaderModule(g_dev, g_vert, NULL);
|
||||
if (g_frag) g_vk.DestroyShaderModule(g_dev, g_frag, NULL);
|
||||
if (g_dpool) g_vk.DestroyDescriptorPool(g_dev, g_dpool, NULL);
|
||||
if (g_pl) g_vk.DestroyPipelineLayout(g_dev, g_pl, NULL);
|
||||
if (g_dsl) g_vk.DestroyDescriptorSetLayout(g_dev, g_dsl, NULL);
|
||||
if (g_sampler) g_vk.DestroySampler(g_dev, g_sampler, NULL);
|
||||
g_vert = g_frag = VK_NULL_HANDLE; g_dpool = VK_NULL_HANDLE; g_pl = VK_NULL_HANDLE;
|
||||
g_dsl = VK_NULL_HANDLE; g_sampler = VK_NULL_HANDLE;
|
||||
}
|
||||
|
||||
static int objects_ensure(void) {
|
||||
if (g_ready) return g_ready == 1 ? 0 : -1;
|
||||
g_ready = -1;
|
||||
if (!g_dev || !g_vk.CreateGraphicsPipelines) goto fail;
|
||||
VkSamplerCreateInfo sci = {.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, .magFilter = VK_FILTER_LINEAR,
|
||||
.minFilter = VK_FILTER_LINEAR, .mipmapMode = VK_SAMPLER_MIPMAP_MODE_NEAREST,
|
||||
.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.addressModeV = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE,
|
||||
.addressModeW = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_EDGE};
|
||||
if (g_vk.CreateSampler(g_dev, &sci, NULL, &g_sampler) != VK_SUCCESS) goto fail;
|
||||
VkDescriptorSetLayoutBinding b = {.binding = 0, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.descriptorCount = 1, .stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT};
|
||||
VkDescriptorSetLayoutCreateInfo dli = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO,
|
||||
.bindingCount = 1, .pBindings = &b};
|
||||
if (g_vk.CreateDescriptorSetLayout(g_dev, &dli, NULL, &g_dsl) != VK_SUCCESS) goto fail;
|
||||
VkPushConstantRange pcr = {.stageFlags = VK_SHADER_STAGE_VERTEX_BIT, .offset = 0, .size = sizeof(struct pc_blend)};
|
||||
VkPipelineLayoutCreateInfo pli = {.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, .setLayoutCount = 1,
|
||||
.pSetLayouts = &g_dsl, .pushConstantRangeCount = 1, .pPushConstantRanges = &pcr};
|
||||
if (g_vk.CreatePipelineLayout(g_dev, &pli, NULL, &g_pl) != VK_SUCCESS) goto fail;
|
||||
VkDescriptorPoolSize ps = {VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, NSRC};
|
||||
VkDescriptorPoolCreateInfo dpi = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO,
|
||||
.flags = VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT, .maxSets = NSRC,
|
||||
.poolSizeCount = 1, .pPoolSizes = &ps};
|
||||
if (g_vk.CreateDescriptorPool(g_dev, &dpi, NULL, &g_dpool) != VK_SUCCESS) goto fail;
|
||||
if (!(g_vert = shader(blend_vert_code, sizeof(blend_vert_code)))) goto fail;
|
||||
if (!(g_frag = shader(blend_frag_code, sizeof(blend_frag_code)))) goto fail;
|
||||
g_ready = 1;
|
||||
banner_log("gpu", "alpha composition ready on %s: translucent surfaces are blended over what is under them",
|
||||
vkp_gpu_name());
|
||||
return 0;
|
||||
fail:
|
||||
objects_destroy();
|
||||
banner_log("error", "gpu: the alpha composition pass could not be built on this driver; translucent surfaces "
|
||||
"are drawn opaque this session");
|
||||
return -1;
|
||||
}
|
||||
|
||||
static int out_slot(VkFormat fmt) {
|
||||
int i;
|
||||
for (i = 0; i < NFMT && g_out[i].pipe; i++) if (g_out[i].fmt == fmt) return i;
|
||||
if (i == NFMT) return -1;
|
||||
VkRenderPass rp = make_rp(fmt);
|
||||
VkPipeline pipe = rp ? make_pipe(rp) : VK_NULL_HANDLE;
|
||||
if (!pipe) {
|
||||
if (rp) g_vk.DestroyRenderPass(g_dev, rp, NULL);
|
||||
return -1;
|
||||
}
|
||||
g_out[i].fmt = fmt; g_out[i].rp = rp; g_out[i].pipe = pipe;
|
||||
return i;
|
||||
}
|
||||
|
||||
static VkImageView make_view(VkImage img, VkFormat fmt) {
|
||||
VkImageView v = VK_NULL_HANDLE;
|
||||
VkImageViewCreateInfo ci = {.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, .image = img,
|
||||
.viewType = VK_IMAGE_VIEW_TYPE_2D, .format = fmt,
|
||||
.subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}};
|
||||
if (g_vk.CreateImageView(g_dev, &ci, NULL, &v) != VK_SUCCESS) return VK_NULL_HANDLE;
|
||||
return v;
|
||||
}
|
||||
|
||||
/* The slot to recycle: a free one, else the one unused for longest - never one this command buffer
|
||||
* already refers to. -1 = every slot is in this frame. */
|
||||
#define OLDEST(arr, n, out) do { \
|
||||
unsigned age_ = 0; \
|
||||
(out) = -1; \
|
||||
for (int k_ = 0; k_ < (n); k_++) { \
|
||||
if (!(arr)[k_].img) { (out) = k_; break; } \
|
||||
if ((arr)[k_].frame != g_frame && g_frame - (arr)[k_].frame > age_) { age_ = g_frame - (arr)[k_].frame; (out) = k_; } \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
static VkDescriptorSet src_ensure(VkImage img, VkFormat fmt, VkImageLayout layout) {
|
||||
int i;
|
||||
for (i = 0; i < NSRC; i++)
|
||||
if (g_src[i].img == img) { g_src[i].frame = g_frame; return g_src[i].ds; }
|
||||
OLDEST(g_src, NSRC, i);
|
||||
if (i < 0) return VK_NULL_HANDLE;
|
||||
src_release(i);
|
||||
if (!(g_src[i].view = make_view(img, fmt))) return VK_NULL_HANDLE;
|
||||
VkDescriptorSetAllocateInfo ai = {.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO,
|
||||
.descriptorPool = g_dpool, .descriptorSetCount = 1, .pSetLayouts = &g_dsl};
|
||||
if (g_vk.AllocateDescriptorSets(g_dev, &ai, &g_src[i].ds) != VK_SUCCESS) {
|
||||
g_src[i].ds = VK_NULL_HANDLE;
|
||||
src_release(i);
|
||||
return VK_NULL_HANDLE;
|
||||
}
|
||||
VkDescriptorImageInfo ii = {.sampler = g_sampler, .imageView = g_src[i].view, .imageLayout = layout};
|
||||
VkWriteDescriptorSet wr = {.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, .dstSet = g_src[i].ds, .dstBinding = 0,
|
||||
.descriptorCount = 1, .descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,
|
||||
.pImageInfo = &ii};
|
||||
g_vk.UpdateDescriptorSets(g_dev, 1, &wr, 0, NULL);
|
||||
g_src[i].img = img; g_src[i].frame = g_frame;
|
||||
return g_src[i].ds;
|
||||
}
|
||||
|
||||
static VkFramebuffer dst_ensure(VkImage img, VkFormat fmt, int w, int h, VkRenderPass rp) {
|
||||
int i;
|
||||
for (i = 0; i < NDST; i++) {
|
||||
if (g_dst[i].img != img) continue;
|
||||
if (g_dst[i].fmt == fmt && g_dst[i].w == w && g_dst[i].h == h) { g_dst[i].frame = g_frame; return g_dst[i].fb; }
|
||||
if (g_dst[i].frame == g_frame) return VK_NULL_HANDLE;
|
||||
break;
|
||||
}
|
||||
if (i == NDST) OLDEST(g_dst, NDST, i);
|
||||
if (i < 0) return VK_NULL_HANDLE;
|
||||
dst_release(i);
|
||||
if (!(g_dst[i].view = make_view(img, fmt))) return VK_NULL_HANDLE;
|
||||
VkFramebufferCreateInfo fi = {.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, .renderPass = rp,
|
||||
.attachmentCount = 1, .pAttachments = &g_dst[i].view, .width = (uint32_t)w,
|
||||
.height = (uint32_t)h, .layers = 1};
|
||||
if (g_vk.CreateFramebuffer(g_dev, &fi, NULL, &g_dst[i].fb) != VK_SUCCESS) {
|
||||
g_dst[i].fb = VK_NULL_HANDLE;
|
||||
dst_release(i);
|
||||
return VK_NULL_HANDLE;
|
||||
}
|
||||
g_dst[i].img = img; g_dst[i].fmt = fmt; g_dst[i].w = w; g_dst[i].h = h; g_dst[i].frame = g_frame;
|
||||
return g_dst[i].fb;
|
||||
}
|
||||
|
||||
static void src_layout(VkCommandBuffer cmd, VkImage img, VkImageLayout from, VkImageLayout to) {
|
||||
int sampling = to == VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||||
VkImageMemoryBarrier b = {.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, .oldLayout = from, .newLayout = to,
|
||||
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED, .dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
|
||||
.image = img, .subresourceRange = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1},
|
||||
.srcAccessMask = sampling ? VK_ACCESS_TRANSFER_READ_BIT : VK_ACCESS_SHADER_READ_BIT,
|
||||
.dstAccessMask = sampling ? VK_ACCESS_SHADER_READ_BIT : VK_ACCESS_TRANSFER_READ_BIT};
|
||||
g_vk.CmdPipelineBarrier(cmd, sampling ? VK_PIPELINE_STAGE_TRANSFER_BIT : VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT,
|
||||
sampling ? VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT : VK_PIPELINE_STAGE_TRANSFER_BIT,
|
||||
0, 0, NULL, 0, NULL, 1, &b);
|
||||
}
|
||||
|
||||
int blendp_draw(VkCommandBuffer cmd, VkImage src, VkFormat src_fmt, int src_w, int src_h, int src_general,
|
||||
VkImage dst, VkFormat dst_fmt, int dst_w, int dst_h, const VkImageBlit *blit) {
|
||||
if (!src || !dst || src_w <= 0 || src_h <= 0 || dst_w <= 0 || dst_h <= 0 || objects_ensure() != 0) return -1;
|
||||
int slot = out_slot(dst_fmt);
|
||||
if (slot < 0) return -1;
|
||||
VkImageLayout sampled = src_general ? VK_IMAGE_LAYOUT_GENERAL : VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
|
||||
VkDescriptorSet ds = src_ensure(src, src_fmt, sampled);
|
||||
if (!ds) return -1;
|
||||
VkFramebuffer fb = dst_ensure(dst, dst_fmt, dst_w, dst_h, g_out[slot].rp);
|
||||
if (!fb) return -1;
|
||||
|
||||
const VkOffset3D *d = blit->dstOffsets, *s = blit->srcOffsets;
|
||||
int x0 = d[0].x < d[1].x ? d[0].x : d[1].x, x1 = d[0].x < d[1].x ? d[1].x : d[0].x;
|
||||
int y0 = d[0].y < d[1].y ? d[0].y : d[1].y, y1 = d[0].y < d[1].y ? d[1].y : d[0].y;
|
||||
if (x0 < 0) x0 = 0;
|
||||
if (y0 < 0) y0 = 0;
|
||||
if (x1 > dst_w) x1 = dst_w;
|
||||
if (y1 > dst_h) y1 = dst_h;
|
||||
if (x1 <= x0 || y1 <= y0) return 0;
|
||||
|
||||
struct pc_blend pc = {
|
||||
.dst = {2.0f * d[0].x / dst_w - 1.0f, 2.0f * d[0].y / dst_h - 1.0f,
|
||||
2.0f * d[1].x / dst_w - 1.0f, 2.0f * d[1].y / dst_h - 1.0f},
|
||||
.src = {(float)s[0].x / src_w, (float)s[0].y / src_h, (float)s[1].x / src_w, (float)s[1].y / src_h}};
|
||||
|
||||
if (!src_general) src_layout(cmd, src, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, sampled);
|
||||
VkRenderPassBeginInfo rpi = {.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, .renderPass = g_out[slot].rp,
|
||||
.framebuffer = fb,
|
||||
.renderArea = {{x0, y0}, {(uint32_t)(x1 - x0), (uint32_t)(y1 - y0)}}};
|
||||
VkViewport vp = {0, 0, (float)dst_w, (float)dst_h, 0, 1};
|
||||
g_vk.CmdBeginRenderPass(cmd, &rpi, VK_SUBPASS_CONTENTS_INLINE);
|
||||
g_vk.CmdSetViewport(cmd, 0, 1, &vp);
|
||||
g_vk.CmdSetScissor(cmd, 0, 1, &rpi.renderArea);
|
||||
g_vk.CmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_out[slot].pipe);
|
||||
g_vk.CmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, g_pl, 0, 1, &ds, 0, NULL);
|
||||
g_vk.CmdPushConstants(cmd, g_pl, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(pc), &pc);
|
||||
g_vk.CmdDraw(cmd, 4, 1, 0, 0);
|
||||
g_vk.CmdEndRenderPass(cmd);
|
||||
if (!src_general) src_layout(cmd, src, sampled, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#ifndef BLEND_PASS_H
|
||||
#define BLEND_PASS_H
|
||||
/*
|
||||
* Alpha composition. The scene is composed with blits, which replace what is under them; a surface
|
||||
* with translucent pixels (gamescope's overlay and notification planes over a game, a toolkit's
|
||||
* shadowed popup) is drawn through this pass instead, source-over with premultiplied alpha.
|
||||
*
|
||||
* Compositor thread. Objects are built on the first use; if the driver refuses them the pass is
|
||||
* unavailable for the session (logged once) and the caller keeps blitting.
|
||||
*/
|
||||
#define VK_USE_PLATFORM_ANDROID_KHR
|
||||
#include <vulkan/vulkan.h>
|
||||
|
||||
/* Called from dev_init (device up). */
|
||||
void blendp_bind_device(VkDevice dev);
|
||||
/* A source or target image is about to be destroyed: drop what is cached for it. Frames are fenced,
|
||||
* so nothing submitted still uses it. */
|
||||
void blendp_forget_image(VkImage img);
|
||||
/* A new command buffer is being recorded: what the previous one used may be recycled again. */
|
||||
void blendp_begin_frame(void);
|
||||
|
||||
/* Record one surface over `dst`. `dst` is in TRANSFER_DST_OPTIMAL before and after. `src` was created
|
||||
* with SAMPLED usage and is in GENERAL (src_general) or TRANSFER_SRC_OPTIMAL, and is left there.
|
||||
* `blit` is the draw as the blit path maps it. 0 = recorded, -1 = unavailable (nothing recorded). */
|
||||
int blendp_draw(VkCommandBuffer cmd, VkImage src, VkFormat src_fmt, int src_w, int src_h, int src_general,
|
||||
VkImage dst, VkFormat dst_fmt, int dst_w, int dst_h, const VkImageBlit *blit);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,55 @@
|
||||
// 1115.1.0
|
||||
#pragma once
|
||||
const uint32_t blend_vert_code[] = {
|
||||
0x07230203,0x00010000,0x0008000b,0x0000003a,0x00000000,0x00020011,0x00000001,0x0006000b,
|
||||
0x00000001,0x4c534c47,0x6474732e,0x3035342e,0x00000000,0x0003000e,0x00000000,0x00000001,
|
||||
0x0008000f,0x00000000,0x00000004,0x6e69616d,0x00000000,0x0000000c,0x0000001b,0x00000031,
|
||||
0x00030003,0x00000002,0x000001c2,0x00040005,0x00000004,0x6e69616d,0x00000000,0x00030005,
|
||||
0x00000009,0x00000074,0x00060005,0x0000000c,0x565f6c67,0x65747265,0x646e4978,0x00007865,
|
||||
0x00060005,0x00000019,0x505f6c67,0x65567265,0x78657472,0x00000000,0x00060006,0x00000019,
|
||||
0x00000000,0x505f6c67,0x7469736f,0x006e6f69,0x00070006,0x00000019,0x00000001,0x505f6c67,
|
||||
0x746e696f,0x657a6953,0x00000000,0x00070006,0x00000019,0x00000002,0x435f6c67,0x4470696c,
|
||||
0x61747369,0x0065636e,0x00070006,0x00000019,0x00000003,0x435f6c67,0x446c6c75,0x61747369,
|
||||
0x0065636e,0x00030005,0x0000001b,0x00000000,0x00030005,0x0000001d,0x00004350,0x00040006,
|
||||
0x0000001d,0x00000000,0x00747364,0x00040006,0x0000001d,0x00000001,0x00637273,0x00030005,
|
||||
0x0000001f,0x00006370,0x00030005,0x00000031,0x00007675,0x00040047,0x0000000c,0x0000000b,
|
||||
0x0000002a,0x00030047,0x00000019,0x00000002,0x00050048,0x00000019,0x00000000,0x0000000b,
|
||||
0x00000000,0x00050048,0x00000019,0x00000001,0x0000000b,0x00000001,0x00050048,0x00000019,
|
||||
0x00000002,0x0000000b,0x00000003,0x00050048,0x00000019,0x00000003,0x0000000b,0x00000004,
|
||||
0x00030047,0x0000001d,0x00000002,0x00050048,0x0000001d,0x00000000,0x00000023,0x00000000,
|
||||
0x00050048,0x0000001d,0x00000001,0x00000023,0x00000010,0x00040047,0x00000031,0x0000001e,
|
||||
0x00000000,0x00020013,0x00000002,0x00030021,0x00000003,0x00000002,0x00030016,0x00000006,
|
||||
0x00000020,0x00040017,0x00000007,0x00000006,0x00000002,0x00040020,0x00000008,0x00000007,
|
||||
0x00000007,0x00040015,0x0000000a,0x00000020,0x00000001,0x00040020,0x0000000b,0x00000001,
|
||||
0x0000000a,0x0004003b,0x0000000b,0x0000000c,0x00000001,0x0004002b,0x0000000a,0x0000000e,
|
||||
0x00000001,0x00040017,0x00000015,0x00000006,0x00000004,0x00040015,0x00000016,0x00000020,
|
||||
0x00000000,0x0004002b,0x00000016,0x00000017,0x00000001,0x0004001c,0x00000018,0x00000006,
|
||||
0x00000017,0x0006001e,0x00000019,0x00000015,0x00000006,0x00000018,0x00000018,0x00040020,
|
||||
0x0000001a,0x00000003,0x00000019,0x0004003b,0x0000001a,0x0000001b,0x00000003,0x0004002b,
|
||||
0x0000000a,0x0000001c,0x00000000,0x0004001e,0x0000001d,0x00000015,0x00000015,0x00040020,
|
||||
0x0000001e,0x00000009,0x0000001d,0x0004003b,0x0000001e,0x0000001f,0x00000009,0x00040020,
|
||||
0x00000020,0x00000009,0x00000015,0x0004002b,0x00000006,0x00000029,0x00000000,0x0004002b,
|
||||
0x00000006,0x0000002a,0x3f800000,0x00040020,0x0000002e,0x00000003,0x00000015,0x00040020,
|
||||
0x00000030,0x00000003,0x00000007,0x0004003b,0x00000030,0x00000031,0x00000003,0x00050036,
|
||||
0x00000002,0x00000004,0x00000000,0x00000003,0x000200f8,0x00000005,0x0004003b,0x00000008,
|
||||
0x00000009,0x00000007,0x0004003d,0x0000000a,0x0000000d,0x0000000c,0x000500c7,0x0000000a,
|
||||
0x0000000f,0x0000000d,0x0000000e,0x0004006f,0x00000006,0x00000010,0x0000000f,0x0004003d,
|
||||
0x0000000a,0x00000011,0x0000000c,0x000500c3,0x0000000a,0x00000012,0x00000011,0x0000000e,
|
||||
0x0004006f,0x00000006,0x00000013,0x00000012,0x00050050,0x00000007,0x00000014,0x00000010,
|
||||
0x00000013,0x0003003e,0x00000009,0x00000014,0x00050041,0x00000020,0x00000021,0x0000001f,
|
||||
0x0000001c,0x0004003d,0x00000015,0x00000022,0x00000021,0x0007004f,0x00000007,0x00000023,
|
||||
0x00000022,0x00000022,0x00000000,0x00000001,0x00050041,0x00000020,0x00000024,0x0000001f,
|
||||
0x0000001c,0x0004003d,0x00000015,0x00000025,0x00000024,0x0007004f,0x00000007,0x00000026,
|
||||
0x00000025,0x00000025,0x00000002,0x00000003,0x0004003d,0x00000007,0x00000027,0x00000009,
|
||||
0x0008000c,0x00000007,0x00000028,0x00000001,0x0000002e,0x00000023,0x00000026,0x00000027,
|
||||
0x00050051,0x00000006,0x0000002b,0x00000028,0x00000000,0x00050051,0x00000006,0x0000002c,
|
||||
0x00000028,0x00000001,0x00070050,0x00000015,0x0000002d,0x0000002b,0x0000002c,0x00000029,
|
||||
0x0000002a,0x00050041,0x0000002e,0x0000002f,0x0000001b,0x0000001c,0x0003003e,0x0000002f,
|
||||
0x0000002d,0x00050041,0x00000020,0x00000032,0x0000001f,0x0000000e,0x0004003d,0x00000015,
|
||||
0x00000033,0x00000032,0x0007004f,0x00000007,0x00000034,0x00000033,0x00000033,0x00000000,
|
||||
0x00000001,0x00050041,0x00000020,0x00000035,0x0000001f,0x0000000e,0x0004003d,0x00000015,
|
||||
0x00000036,0x00000035,0x0007004f,0x00000007,0x00000037,0x00000036,0x00000036,0x00000002,
|
||||
0x00000003,0x0004003d,0x00000007,0x00000038,0x00000009,0x0008000c,0x00000007,0x00000039,
|
||||
0x00000001,0x0000002e,0x00000034,0x00000037,0x00000038,0x0003003e,0x00000031,0x00000039,
|
||||
0x000100fd,0x00010038
|
||||
};
|
||||
@@ -170,6 +170,9 @@ struct client_info {
|
||||
/* An OpenGL program whose EGL gave up on the GPU: it asked for dma-buf feedback (EGL's
|
||||
* Wayland GPU path always does), never made a dma-buf buffer, and draws wl_shm frames. */
|
||||
unsigned asked_feedback : 1, shm_gl_said : 1;
|
||||
/* Clients that describe opaque regions can use alpha outside those regions. Wine windows
|
||||
* never describe them, and their unused alpha channel must not make them translucent. */
|
||||
unsigned declares_opaque : 1;
|
||||
unsigned dmabuf_buffers, shm_frames;
|
||||
struct client_info *next;
|
||||
};
|
||||
@@ -248,6 +251,8 @@ struct surface {
|
||||
struct dmabuf_buffer *dmabuf_buf; /* its imported image, kept until replaced or the surface goes */
|
||||
struct wl_listener dmabuf_destroy;
|
||||
int buf_w, buf_h, has_content;
|
||||
int buf_alpha;
|
||||
int opaque[4], pending_opaque[4], pending_opaque_set; /* x, y, w, h; w = 0: none */
|
||||
int src_set, dst_set;
|
||||
float src[4];
|
||||
int dst[2];
|
||||
@@ -743,6 +748,7 @@ static void take_shm(struct surface *s, struct wl_shm_buffer *shm, struct wl_res
|
||||
wl_buffer_send_release(buffer);
|
||||
s->buf_w = w;
|
||||
s->buf_h = h;
|
||||
s->buf_alpha = wl_shm_buffer_get_format(shm) == WL_SHM_FORMAT_ARGB8888;
|
||||
s->has_content = s->shm_img != NULL;
|
||||
g_stat_shm++;
|
||||
struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
|
||||
@@ -794,6 +800,7 @@ static void take_dmabuf(struct surface *s, struct dmabuf_buffer *b, struct wl_re
|
||||
}
|
||||
s->buf_w = b->width;
|
||||
s->buf_h = b->height;
|
||||
s->buf_alpha = (b->format & 0xff) == 'A';
|
||||
s->has_content = b->img != NULL;
|
||||
g_stat_dmabuf++;
|
||||
const int announced_now = !s->announced_vulkan;
|
||||
@@ -965,8 +972,27 @@ static void surface_frame(struct wl_client *c, struct wl_resource *r, uint32_t c
|
||||
wl_resource_set_implementation(callback, NULL, NULL, frame_callback_destroy);
|
||||
wl_list_insert(s->pending_frames.prev, wl_resource_get_link(callback));
|
||||
}
|
||||
/* The bounding box serves pointer confinement. The exact flag also tells opaque-region handling
|
||||
* whether the bounding box itself is the whole region. */
|
||||
struct region { int set, exact; int x, y, w, h; };
|
||||
|
||||
/* A wl_surface's opaque region is pending until its next commit. An exact region that covers
|
||||
* the surface lets the blit path keep handling an otherwise alpha-capable buffer. */
|
||||
static void surface_set_opaque(struct wl_client *c, struct wl_resource *r,
|
||||
struct wl_resource *region) {}
|
||||
struct wl_resource *region) {
|
||||
struct surface *s = wl_resource_get_user_data(r);
|
||||
struct region *rg = region ? wl_resource_get_user_data(region) : NULL;
|
||||
memset(s->pending_opaque, 0, sizeof(s->pending_opaque));
|
||||
s->pending_opaque_set = 1;
|
||||
if (rg && rg->set && rg->exact) {
|
||||
s->pending_opaque[0] = rg->x;
|
||||
s->pending_opaque[1] = rg->y;
|
||||
s->pending_opaque[2] = rg->w;
|
||||
s->pending_opaque[3] = rg->h;
|
||||
}
|
||||
struct client_info *ci = client_info_of(c);
|
||||
if (ci) ci->declares_opaque = 1;
|
||||
}
|
||||
static void surface_set_input(struct wl_client *c, struct wl_resource *r,
|
||||
struct wl_resource *region) {}
|
||||
|
||||
@@ -995,6 +1021,10 @@ static void surface_commit(struct wl_client *c, struct wl_resource *r) {
|
||||
memcpy(s->dst, s->pending_dst, sizeof(s->dst));
|
||||
s->pending_dst_set = 0;
|
||||
}
|
||||
if (s->pending_opaque_set) {
|
||||
memcpy(s->opaque, s->pending_opaque, sizeof(s->opaque));
|
||||
s->pending_opaque_set = 0;
|
||||
}
|
||||
|
||||
if (s->pending_attach) {
|
||||
struct wl_resource *buffer = s->pending_buffer;
|
||||
@@ -1139,24 +1169,29 @@ static void surface_resource_destroy(struct wl_resource *r) {
|
||||
|
||||
/* ------------------------------------------------------------------ wl_region */
|
||||
|
||||
/* A region is kept as the bounding box of its rectangles: enough for pointer confinement,
|
||||
* where winewayland sends one rectangle (the ClipCursor area). Subtractions are ignored. */
|
||||
struct region { int set; int x, y, w, h; };
|
||||
|
||||
static void region_destroy(struct wl_client *c, struct wl_resource *r) { wl_resource_destroy(r); }
|
||||
static void region_add(struct wl_client *c, struct wl_resource *r,
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {
|
||||
struct region *rg = wl_resource_get_user_data(r);
|
||||
if (!rg || w <= 0 || h <= 0) return;
|
||||
if (!rg->set) { rg->x = x; rg->y = y; rg->w = w; rg->h = h; rg->set = 1; return; }
|
||||
int x2 = rg->x + rg->w > x + w ? rg->x + rg->w : x + w;
|
||||
int y2 = rg->y + rg->h > y + h ? rg->y + rg->h : y + h;
|
||||
if (!rg->set) { rg->x = x; rg->y = y; rg->w = w; rg->h = h; rg->set = rg->exact = 1; return; }
|
||||
long long x2 = (long long)rg->x + rg->w, y2 = (long long)rg->y + rg->h;
|
||||
long long nx2 = (long long)x + w, ny2 = (long long)y + h;
|
||||
int inside = x >= rg->x && y >= rg->y && nx2 <= x2 && ny2 <= y2;
|
||||
int around = x <= rg->x && y <= rg->y && nx2 >= x2 && ny2 >= y2;
|
||||
if (!inside && !around) rg->exact = 0;
|
||||
if (nx2 > x2) x2 = nx2;
|
||||
if (ny2 > y2) y2 = ny2;
|
||||
if (x < rg->x) rg->x = x;
|
||||
if (y < rg->y) rg->y = y;
|
||||
rg->w = x2 - rg->x; rg->h = y2 - rg->y;
|
||||
rg->w = (int)(x2 - rg->x > INT32_MAX ? INT32_MAX : x2 - rg->x);
|
||||
rg->h = (int)(y2 - rg->y > INT32_MAX ? INT32_MAX : y2 - rg->y);
|
||||
}
|
||||
static void region_subtract(struct wl_client *c, struct wl_resource *r,
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {}
|
||||
int32_t x, int32_t y, int32_t w, int32_t h) {
|
||||
struct region *rg = wl_resource_get_user_data(r);
|
||||
if (rg && w > 0 && h > 0) rg->exact = 0;
|
||||
}
|
||||
static void region_resource_destroy(struct wl_resource *r) { free(wl_resource_get_user_data(r)); }
|
||||
static const struct wl_region_interface region_impl = {
|
||||
.destroy = region_destroy,
|
||||
@@ -1942,6 +1977,17 @@ static void note_hdr_unimported(const struct draw_list *dl, struct surface *s, i
|
||||
g_hdr_unimported_below = dl->n;
|
||||
}
|
||||
|
||||
/* A client that describes opaque regions can intentionally leave part of an alpha buffer see-through.
|
||||
* Gamescope uses this for its full-size Steam notification and overlay planes. */
|
||||
static int surface_translucent(const struct surface *s, int w, int h) {
|
||||
if (!s->buf_alpha) return 0;
|
||||
const struct client_info *ci = client_info_of(wl_resource_get_client(s->resource));
|
||||
if (!ci || !ci->declares_opaque) return 0;
|
||||
const int *o = s->opaque;
|
||||
return !(o[2] > 0 && o[0] <= 0 && o[1] <= 0 &&
|
||||
(long long)o[0] + o[2] >= w && (long long)o[1] + o[3] >= h);
|
||||
}
|
||||
|
||||
static void add_surface(struct draw_list *dl, struct surface *s, int ox, int oy) {
|
||||
struct vkp_image *img = surface_image(s);
|
||||
float sx = 0, sy = 0, sw = (float)s->buf_w, sh = (float)s->buf_h;
|
||||
@@ -1961,7 +2007,8 @@ static void add_surface(struct draw_list *dl, struct surface *s, int ox, int oy)
|
||||
dl->d = d;
|
||||
dl->cap = cap;
|
||||
}
|
||||
dl->d[dl->n++] = (struct vkp_draw){img, sx, sy, sw, sh, ox, oy, dw, dh};
|
||||
dl->d[dl->n++] = (struct vkp_draw){img, sx, sy, sw, sh, ox, oy, dw, dh,
|
||||
surface_translucent(s, dw, dh)};
|
||||
s->drawn = 1;
|
||||
}
|
||||
|
||||
@@ -2032,6 +2079,7 @@ static int on_frame_timer(void *data) {
|
||||
static int layer_candidate(const struct draw_list *dl, int scene_w, int scene_h) {
|
||||
for (int i = dl->n - 1; i >= 0 && i >= dl->n - 2; i--) {
|
||||
const struct vkp_draw *d = &dl->d[i];
|
||||
if (d->blend) continue; /* the translucent plane must not replace the opaque game layer */
|
||||
if (!vkp_image_is_dmabuf(d->img)) continue;
|
||||
if (d->dx != 0 || d->dy != 0 || d->dw != scene_w || d->dh != scene_h) continue;
|
||||
if (d->sx != 0 || d->sy != 0 || (int)d->sw != vkp_image_width(d->img) ||
|
||||
@@ -2370,7 +2418,7 @@ static void render_scene(void) {
|
||||
* its own layer, cropped and placed by the display. */
|
||||
int go[8], ov = 0;
|
||||
if (over == 1 && li >= 0 && vkp_map_draw(&dl.d[li + 1], go))
|
||||
ov = sc_layer_present_overlay(dl.d[li + 1].img, go) == 0 ? 1 : -1;
|
||||
ov = sc_layer_present_overlay(dl.d[li + 1].img, go, dl.d[li + 1].blend) == 0 ? 1 : -1;
|
||||
if (ov <= 0) sc_layer_hide_overlay();
|
||||
if (ov < 0) { /* the overlay layer refused it: draw the whole scene the old way */
|
||||
sc_layer_hide();
|
||||
|
||||
@@ -85,6 +85,7 @@ static struct {
|
||||
|
||||
#define ASC_VISIBILITY_HIDE 0
|
||||
#define ASC_VISIBILITY_SHOW 1
|
||||
#define ASC_TRANSPARENCY_TRANSLUCENT 1
|
||||
#define ASC_TRANSPARENCY_OPAQUE 2
|
||||
|
||||
static int load_api(void) {
|
||||
@@ -766,7 +767,8 @@ static ASurfaceControl *swap_sc_begin(struct layer *l) {
|
||||
|
||||
/* The transaction that puts pool slot `idx` of layer `l` on screen at `r`, as `color` (NULL = no
|
||||
* description). 0 = applied. */
|
||||
static int present_slot(struct layer *l, int idx, const int r[8], const struct banner_color *color) {
|
||||
static int present_slot(struct layer *l, int idx, const int r[8], const struct banner_color *color,
|
||||
int translucent) {
|
||||
struct slot *s = &l->slots[idx];
|
||||
ASurfaceTransaction *tx = api.txCreate();
|
||||
if (!tx) return -1;
|
||||
@@ -774,9 +776,8 @@ static int present_slot(struct layer *l, int idx, const int r[8], const struct b
|
||||
if (old) api.setZOrder(tx, l->sc, l->z);
|
||||
/* The blit was waited for on the CPU, so no acquire fence is needed (-1). */
|
||||
api.setBuffer(tx, l->sc, s->ahb, -1);
|
||||
/* The compositor composes with blits, which overwrite: nothing is ever alpha-blended on the
|
||||
* copy path either, so every layer is opaque and the picture matches it pixel for pixel. */
|
||||
api.setBufferTransparency(tx, l->sc, ASC_TRANSPARENCY_OPAQUE);
|
||||
api.setBufferTransparency(tx, l->sc,
|
||||
translucent ? ASC_TRANSPARENCY_TRANSLUCENT : ASC_TRANSPARENCY_OPAQUE);
|
||||
apply_geometry(tx, l, r);
|
||||
apply_frame_rate(tx, l);
|
||||
apply_colour(tx, l, color);
|
||||
@@ -883,7 +884,7 @@ int sc_layer_present(struct vkp_image *src, int scene_w, int scene_h, const stru
|
||||
int idx = take_free_slot(l, sw, sh, AHB_RGBA8, &wait_fd);
|
||||
if (idx < 0) { log_drop(l); return 0; }
|
||||
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
|
||||
if (present_slot(l, idx, r, color) != 0) return -1;
|
||||
if (present_slot(l, idx, r, color, 0) != 0) return -1;
|
||||
if (color && color->dataspace) banner_color_frame_shown(color, BANNER_HDR_LAYER_COPY, AHB_RGBA8);
|
||||
if (!l->first_logged) {
|
||||
l->first_logged = 1;
|
||||
@@ -908,7 +909,7 @@ int sc_layer_present_pass(const struct vkp_draw *draws, int n, int scene_w, int
|
||||
int idx = take_free_slot(l, rw, rh, AHB_RGBA8, &wait_fd);
|
||||
if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; }
|
||||
if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1;
|
||||
if (present_slot(l, idx, r, NULL) != 0) return -1; /* the effects chain's result is 8-bit sRGB */
|
||||
if (present_slot(l, idx, r, NULL, 0) != 0) return -1; /* the effects chain's result is 8-bit sRGB */
|
||||
if (!l->first_logged) {
|
||||
l->first_logged = 1;
|
||||
banner_log("layer", "presenting %dx%d frames on their own SurfaceControl layer (%s pool, %d buffers); "
|
||||
@@ -950,7 +951,7 @@ int sc_layer_present_hdr_scene(const struct vkp_draw *draws, int n, const struct
|
||||
}
|
||||
if (idx < 0) { vkp_pass_abort(); log_drop(l); return 0; }
|
||||
if (vkp_pass_copy_to(l->slots[idx].img, wait_fd) != 0) return -1;
|
||||
if (present_slot(l, idx, r, tm ? NULL : color) != 0) return -1; /* tone-mapped = plain sRGB: no tag */
|
||||
if (present_slot(l, idx, r, tm ? NULL : color, 0) != 0) return -1; /* tone-mapped = plain sRGB: no tag */
|
||||
if (color && color->dataspace)
|
||||
banner_color_frame_shown(color, tm ? BANNER_HDR_TONEMAPPED : BANNER_HDR_COMPOSED, tm ? AHB_RGBA8 : g_hdr_pool_fmt);
|
||||
static int said = -1;
|
||||
@@ -1031,7 +1032,7 @@ int sc_layer_overlay_affordable(void) {
|
||||
return ok;
|
||||
}
|
||||
|
||||
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8]) {
|
||||
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent) {
|
||||
struct layer *l = layer_of(SC_LAYER_OVERLAY);
|
||||
if (!src || !geo) return -1;
|
||||
/* The caller decides with sc_layer_overlay_affordable() BEFORE it commits the game to a layer;
|
||||
@@ -1046,7 +1047,7 @@ int sc_layer_present_overlay(struct vkp_image *src, const int geo[8]) {
|
||||
/* The window is copied into the layer buffer 1:1; `geo` crops it and places it, so the layer
|
||||
* is exactly the window's rectangle on screen and nothing else is blended anywhere. */
|
||||
if (vkp_blit_image(src, l->slots[idx].img, wait_fd) != 0) return -1;
|
||||
if (present_slot(l, idx, geo, NULL) != 0) return -1;
|
||||
if (present_slot(l, idx, geo, NULL, translucent) != 0) return -1;
|
||||
if (!l->first_logged) {
|
||||
l->first_logged = 1;
|
||||
log_layer_count();
|
||||
|
||||
@@ -150,8 +150,9 @@ int sc_layer_overlay_affordable(void);
|
||||
|
||||
/* OVERLAY layer: show `src` (one window's imported frame) above the game layer, at the placement
|
||||
* `geo` = {src x0,y0,x1,y1 in image pixels, dst x0,y0,x1,y1 in output pixels} from vkp_map_draw.
|
||||
* `translucent` preserves a client's alpha over the game for Steam notifications and overlays.
|
||||
* 0 = shown or dropped, -1 = unavailable (the caller must fall back to the copy path). */
|
||||
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8]);
|
||||
int sc_layer_present_overlay(struct vkp_image *src, const int geo[8], int translucent);
|
||||
|
||||
/* The scene is not a single fullscreen window this frame: hide every layer that is up. */
|
||||
void sc_layer_hide(void);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
#include "effects_chain.h"
|
||||
#include "framegen_bridge.h"
|
||||
#include "hdr_compose.h"
|
||||
#include "blend_pass.h"
|
||||
#include "banner_color.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -32,6 +33,8 @@ struct vkp_image {
|
||||
void *map; /* shm images: persistently mapped linear memory */
|
||||
VkDeviceSize offset, row_pitch;
|
||||
int in_general; /* shm images: moved from PREINITIALIZED to GENERAL */
|
||||
VkFormat fmt;
|
||||
int sampled; /* created with SAMPLED usage: the alpha pass can read it */
|
||||
};
|
||||
|
||||
static ANativeWindow *g_window; /* the window frames go to; compositor thread only */
|
||||
@@ -230,6 +233,7 @@ static void destroy_swapchain(void) {
|
||||
if (g_dev_state != 1) return;
|
||||
g_vk.DeviceWaitIdle(g_dev);
|
||||
reset_sync();
|
||||
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
|
||||
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
|
||||
g_swapchain = VK_NULL_HANDLE;
|
||||
g_swap_md_identity = 0; /* a new swapchain gets the metadata again */
|
||||
@@ -525,6 +529,7 @@ static int dev_init(void) {
|
||||
|
||||
vkp_effects_bind_device(g_dev, g_pd, &g_memprops);
|
||||
hdrc_bind_device(g_dev, &g_memprops);
|
||||
blendp_bind_device(g_dev);
|
||||
g_dev_state = 1;
|
||||
reset_sync();
|
||||
init_black_image();
|
||||
@@ -873,9 +878,8 @@ const char *vkp_modifier_name(uint64_t modifier) {
|
||||
return other;
|
||||
}
|
||||
|
||||
/* Can the driver create the image vkp_image_import_dmabuf() creates for this format+modifier
|
||||
* (2D, DRM_FORMAT_MODIFIER tiling, TRANSFER_SRC, dma-buf memory) - and import it? */
|
||||
static int modifier_importable(VkFormat fmt, uint64_t modifier) {
|
||||
/* Can the driver create and import this format/modifier with the requested image usage? */
|
||||
static int modifier_importable(VkFormat fmt, uint64_t modifier, VkImageUsageFlags usage) {
|
||||
if (!g_vk.GetPhysicalDeviceImageFormatProperties2) return 1; /* can't ask; the create will tell */
|
||||
VkPhysicalDeviceExternalImageFormatInfo ext = {
|
||||
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO,
|
||||
@@ -886,7 +890,7 @@ static int modifier_importable(VkFormat fmt, uint64_t modifier) {
|
||||
VkPhysicalDeviceImageFormatInfo2 info = {
|
||||
.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2, .pNext = &mod,
|
||||
.format = fmt, .type = VK_IMAGE_TYPE_2D, .tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT};
|
||||
.usage = usage};
|
||||
VkExternalImageFormatProperties extp = {.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES};
|
||||
VkImageFormatProperties2 props = {.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2, .pNext = &extp};
|
||||
if (g_vk.GetPhysicalDeviceImageFormatProperties2(g_pd, &info, &props) != VK_SUCCESS) return 0;
|
||||
@@ -914,7 +918,7 @@ int vkp_dmabuf_modifiers(uint32_t drm_format, uint64_t *out, int max) {
|
||||
if (m != VKP_MOD_LINEAR && m != VKP_MOD_QCOM_COMPRESSED) why = "unknown layout";
|
||||
else if (props[i].drmFormatModifierPlaneCount != 1) why = "not single-plane";
|
||||
else if (!(props[i].drmFormatModifierTilingFeatures & VK_FORMAT_FEATURE_BLIT_SRC_BIT)) why = "no blit source";
|
||||
else if (!modifier_importable(fmt, m)) why = "not importable as a dma-buf";
|
||||
else if (!modifier_importable(fmt, m, VK_IMAGE_USAGE_TRANSFER_SRC_BIT)) why = "not importable as a dma-buf";
|
||||
if (why) {
|
||||
LOGI("dmabuf: %c%c%c%c %s reported by the driver but not advertised: %s",
|
||||
drm_format & 0xff, (drm_format >> 8) & 0xff, (drm_format >> 16) & 0xff,
|
||||
@@ -942,6 +946,10 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||
if (!img) return NULL;
|
||||
img->w = w; img->h = h; img->dmabuf = 1; img->blit_dst = as_blit_dst ? 1 : 0;
|
||||
img->fmt = drm_to_vk(drm_format);
|
||||
const VkImageUsageFlags sampled_usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
|
||||
img->sampled = !as_blit_dst && g_vk.GetPhysicalDeviceImageFormatProperties2 &&
|
||||
modifier_importable(img->fmt, modifier, sampled_usage);
|
||||
|
||||
VkSubresourceLayout plane = {.offset = offset, .rowPitch = stride};
|
||||
VkImageDrmFormatModifierExplicitCreateInfoEXT modInfo = {
|
||||
@@ -952,10 +960,11 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
||||
.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_DMA_BUF_BIT_EXT};
|
||||
VkImageCreateInfo ici = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .pNext = &extImg,
|
||||
.imageType = VK_IMAGE_TYPE_2D, .format = drm_to_vk(drm_format), .extent = {w, h, 1},
|
||||
.imageType = VK_IMAGE_TYPE_2D, .format = img->fmt, .extent = {w, h, 1},
|
||||
.mipLevels = 1, .arrayLayers = 1, .samples = VK_SAMPLE_COUNT_1_BIT,
|
||||
.tiling = VK_IMAGE_TILING_DRM_FORMAT_MODIFIER_EXT,
|
||||
.usage = as_blit_dst ? VK_IMAGE_USAGE_TRANSFER_DST_BIT : VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
|
||||
.usage = as_blit_dst ? VK_IMAGE_USAGE_TRANSFER_DST_BIT
|
||||
: img->sampled ? sampled_usage : VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE, .initialLayout = VK_IMAGE_LAYOUT_UNDEFINED};
|
||||
VkResult cr = g_vk.CreateImage(g_dev, &ici, NULL, &img->image);
|
||||
if (cr != VK_SUCCESS) {
|
||||
@@ -1008,18 +1017,35 @@ struct vkp_image *vkp_image_import_dmabuf(int fd, uint32_t drm_format, uint64_t
|
||||
return img;
|
||||
}
|
||||
|
||||
/* Linear wl_shm images can use the blend pass only if the driver samples them with a linear filter. */
|
||||
static int shm_sampled(void) {
|
||||
static int known;
|
||||
if (!known) {
|
||||
const VkFormatFeatureFlags need = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT |
|
||||
VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT;
|
||||
VkFormatProperties2 fp = {.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2};
|
||||
if (g_vk.GetPhysicalDeviceFormatProperties2)
|
||||
g_vk.GetPhysicalDeviceFormatProperties2(g_pd, VK_FORMAT_B8G8R8A8_UNORM, &fp);
|
||||
known = (fp.formatProperties.linearTilingFeatures & need) == need ? 1 : -1;
|
||||
}
|
||||
return known == 1;
|
||||
}
|
||||
|
||||
struct vkp_image *vkp_image_create_shm(int w, int h) {
|
||||
if (w <= 0 || h <= 0 || dev_init() != 0) return NULL;
|
||||
|
||||
struct vkp_image *img = calloc(1, sizeof(*img));
|
||||
if (!img) return NULL;
|
||||
img->w = w; img->h = h;
|
||||
img->fmt = VK_FORMAT_B8G8R8A8_UNORM;
|
||||
img->sampled = shm_sampled();
|
||||
|
||||
VkImageCreateInfo ici = {
|
||||
.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, .imageType = VK_IMAGE_TYPE_2D,
|
||||
.format = VK_FORMAT_B8G8R8A8_UNORM, .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = 1,
|
||||
.format = img->fmt, .extent = {w, h, 1}, .mipLevels = 1, .arrayLayers = 1,
|
||||
.samples = VK_SAMPLE_COUNT_1_BIT, .tiling = VK_IMAGE_TILING_LINEAR,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT, .sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | (img->sampled ? VK_IMAGE_USAGE_SAMPLED_BIT : 0),
|
||||
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
|
||||
.initialLayout = VK_IMAGE_LAYOUT_PREINITIALIZED};
|
||||
if (g_vk.CreateImage(g_dev, &ici, NULL, &img->image) != VK_SUCCESS) { free(img); return NULL; }
|
||||
|
||||
@@ -1062,6 +1088,7 @@ int vkp_image_height(const struct vkp_image *img) { return img ? img->h : 0; }
|
||||
void vkp_image_destroy(struct vkp_image *img) {
|
||||
if (!img) return;
|
||||
if (g_dev) {
|
||||
blendp_forget_image(img->image);
|
||||
if (img->map) g_vk.UnmapMemory(g_dev, img->mem);
|
||||
if (img->image) g_vk.DestroyImage(g_dev, img->image, NULL);
|
||||
if (img->mem) g_vk.FreeMemory(g_dev, img->mem, NULL);
|
||||
@@ -1111,8 +1138,21 @@ static int draw_to_scene_blit(const struct vkp_draw *d, int scene_w, int scene_h
|
||||
return map_draw(d, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, (float)scene_w, (float)scene_h, blit);
|
||||
}
|
||||
|
||||
/* A translucent draw needs source-over blending; every other draw keeps the existing blit path. */
|
||||
static void record_draw(VkCommandBuffer cmd, const struct vkp_draw *d, const VkImageBlit *blit, VkImage target,
|
||||
VkFormat target_fmt, int target_w, int target_h, VkFilter filter) {
|
||||
const struct vkp_image *im = d->img;
|
||||
if (d->blend && im->sampled &&
|
||||
blendp_draw(cmd, im->image, im->fmt, im->w, im->h, !im->dmabuf, target, target_fmt, target_w, target_h,
|
||||
blit) == 0)
|
||||
return;
|
||||
g_vk.CmdBlitImage(cmd, im->image, im->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, blit, filter);
|
||||
}
|
||||
|
||||
static void destroy_scene_image(void) {
|
||||
if (g_scene.img) hdrc_forget_image(g_scene.img); /* the HDR pass may have drawn into it */
|
||||
if (g_scene.img) blendp_forget_image(g_scene.img);
|
||||
if (g_scene.img) g_vk.DestroyImage(g_dev, g_scene.img, NULL);
|
||||
if (g_scene.mem) g_vk.FreeMemory(g_dev, g_scene.mem, NULL);
|
||||
memset(&g_scene, 0, sizeof(g_scene));
|
||||
@@ -1150,6 +1190,7 @@ static int ensure_scene_image(int w, int h) {
|
||||
static int ensure_img(struct vkp_img_slot *s, int w, int h, VkFormat fmt, VkImageUsageFlags usage, const char *what) {
|
||||
if (s->img && s->w == w && s->h == h && s->fmt == fmt) return 0;
|
||||
if (s->img) hdrc_forget_image(s->img);
|
||||
if (s->img) blendp_forget_image(s->img);
|
||||
if (s->img) g_vk.DestroyImage(g_dev, s->img, NULL);
|
||||
if (s->mem) g_vk.FreeMemory(g_dev, s->mem, NULL);
|
||||
memset(s, 0, sizeof(*s));
|
||||
@@ -1190,7 +1231,8 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n,
|
||||
int scene_w, int scene_h, VkImage out, VkFormat out_fmt, enum hdrc_mode mode) {
|
||||
if (!hf || !hf->is_hdr || n <= 0) return -1;
|
||||
if (ensure_img(&g_mixed, scene_w, scene_h, HDR_FMT,
|
||||
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT,
|
||||
VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT |
|
||||
VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT,
|
||||
"HDR composition (mixed)") != 0)
|
||||
return -1;
|
||||
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||
@@ -1214,9 +1256,7 @@ static int compose_hdr(VkCommandBuffer cmd, const struct vkp_draw *draws, int n,
|
||||
VkImageBlit blit;
|
||||
if (!draws[i].img || !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit)) continue;
|
||||
/* A blit converts UNORM to UNORM by value: 8-bit sRGB and 10-bit PQ both land unchanged. */
|
||||
g_vk.CmdBlitImage(cmd, draws[i].img->image,
|
||||
draws[i].img->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
g_mixed.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR);
|
||||
record_draw(cmd, &draws[i], &blit, g_mixed.img, HDR_FMT, scene_w, scene_h, VK_FILTER_LINEAR);
|
||||
if (hf->is_hdr[i] && lowest_hdr < 0) lowest_hdr = i;
|
||||
}
|
||||
static int truncated_said;
|
||||
@@ -1249,6 +1289,7 @@ static void device_lost(const char *where) {
|
||||
vkp_framegen_device_lost();
|
||||
banner_log("error", "GPU device lost (VK_ERROR_DEVICE_LOST in %s): the compositor has stopped presenting; "
|
||||
"restart the session", where);
|
||||
for (uint32_t i = 0; i < g_nimg; i++) blendp_forget_image(g_images[i]);
|
||||
if (g_swapchain) g_vk.DestroySwapchainKHR(g_dev, g_swapchain, NULL);
|
||||
g_swapchain = VK_NULL_HANDLE;
|
||||
if (g_surface) g_vk.DestroySurfaceKHR(g_inst, g_surface, NULL);
|
||||
@@ -1547,6 +1588,7 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
|
||||
g_vk.BeginCommandBuffer(cmd, &bi);
|
||||
blendp_begin_frame();
|
||||
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||
|
||||
/* Source images: take dmabufs from the client's queue family, move shm images to
|
||||
@@ -1589,8 +1631,8 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
free(bars);
|
||||
|
||||
/* Clear the composition target to black (the letterbox on the direct path, the desktop's
|
||||
* background on the pass) before the draws land on it. A draw that covers the whole scene
|
||||
* overwrites every pixel of its rectangle (blits never blend), so then only what lies outside it
|
||||
* background on the pass) before the draws land on it. An opaque draw that covers the whole scene
|
||||
* overwrites every pixel of its rectangle, so then only what lies outside it
|
||||
* needs black: the letterbox bars on the direct path, nothing at all on the pass (the scene image
|
||||
* is exactly the scene). Anything else - no such draw, the HDR composition - clears the whole
|
||||
* target as before. */
|
||||
@@ -1600,7 +1642,8 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
if (!(hf && pass)) {
|
||||
for (int i = n - 1; i >= 0 && !covered; i--) {
|
||||
const struct vkp_draw *d = &draws[i];
|
||||
if (!d->img || d->dx > 0 || d->dy > 0 || d->dx + d->dw < scene_w || d->dy + d->dh < scene_h) continue;
|
||||
if (!d->img || d->blend || d->dx > 0 || d->dy > 0 || d->dx + d->dw < scene_w ||
|
||||
d->dy + d->dh < scene_h) continue;
|
||||
covered = pass ? draw_to_scene_blit(d, scene_w, scene_h, &cover_blit) : draw_to_blit(d, &cover_blit);
|
||||
}
|
||||
}
|
||||
@@ -1633,10 +1676,9 @@ static int render_impl(int scene_w, int scene_h, const struct vkp_draw *draws, i
|
||||
VkImageBlit blit;
|
||||
if (!draws[i].img) continue;
|
||||
if (pass ? !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit) : !draw_to_blit(&draws[i], &blit)) continue;
|
||||
g_vk.CmdBlitImage(cmd, draws[i].img->image,
|
||||
draws[i].img->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
target, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit,
|
||||
pass ? VK_FILTER_LINEAR : blit_filter);
|
||||
record_draw(cmd, &draws[i], &blit, target, pass ? scene_fmt : g_swap_fmt,
|
||||
pass ? scene_w : (int)g_extent.width, pass ? scene_h : (int)g_extent.height,
|
||||
pass ? VK_FILTER_LINEAR : blit_filter);
|
||||
drawn++;
|
||||
}
|
||||
|
||||
@@ -2073,6 +2115,7 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
VkCommandBufferBeginInfo bi = {.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO,
|
||||
.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT};
|
||||
g_vk.BeginCommandBuffer(cmd, &bi);
|
||||
blendp_begin_frame();
|
||||
VkImageSubresourceRange range = {VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1};
|
||||
|
||||
/* Same acquisition as vkp_render's compositor pass: the sources come from the client's queue
|
||||
@@ -2132,9 +2175,8 @@ static int pass_begin_impl(int scene_w, int scene_h, const struct vkp_draw *draw
|
||||
for (int i = 0; i < n; i++) {
|
||||
VkImageBlit blit;
|
||||
if (!draws[i].img || !draw_to_scene_blit(&draws[i], scene_w, scene_h, &blit)) continue;
|
||||
g_vk.CmdBlitImage(cmd, draws[i].img->image,
|
||||
draws[i].img->dmabuf ? VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL : VK_IMAGE_LAYOUT_GENERAL,
|
||||
g_scene.img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &blit, VK_FILTER_LINEAR);
|
||||
record_draw(cmd, &draws[i], &blit, g_scene.img, SCENE_FMT, scene_w, scene_h,
|
||||
VK_FILTER_LINEAR);
|
||||
}
|
||||
if (vkp_effects_active()) vkp_effects_set_formats(VK_FORMAT_R8G8B8A8_UNORM, VK_FORMAT_R8G8B8A8_UNORM);
|
||||
}
|
||||
|
||||
@@ -79,6 +79,7 @@ struct vkp_draw {
|
||||
struct vkp_image *img;
|
||||
float sx, sy, sw, sh;
|
||||
int dx, dy, dw, dh;
|
||||
int blend; /* translucent: composed over what is under it (blend_pass.h) */
|
||||
};
|
||||
|
||||
// The GPU the renderer runs on ("Adreno (TM) 750"), empty before the device is up.
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package com.droiddeck.launcher
|
||||
|
||||
import android.Manifest
|
||||
import android.app.ActivityOptions
|
||||
import android.content.Intent
|
||||
import android.content.ClipData
|
||||
import android.content.ClipboardManager
|
||||
import java.io.File
|
||||
import android.content.pm.PackageManager
|
||||
import android.hardware.display.DisplayManager
|
||||
@@ -39,6 +42,9 @@ import com.droiddeck.launcher.session.SessionPrefs
|
||||
import com.droiddeck.launcher.ui.ProtonPage
|
||||
import com.droiddeck.launcher.ui.ProtonRow
|
||||
import com.droiddeck.launcher.core.CpuCores
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import com.droiddeck.launcher.ui.CoreRow
|
||||
import com.droiddeck.launcher.ui.PerformancePage
|
||||
import com.droiddeck.launcher.ui.ModeSettingsPage
|
||||
@@ -120,6 +126,8 @@ class MainActivity : ComponentActivity() {
|
||||
private var noXalia by mutableStateOf(false)
|
||||
private var prootNoSeccomp by mutableStateOf(false)
|
||||
private var phantomWarning by mutableStateOf<String?>(null)
|
||||
private var phantomProcessStatus by mutableStateOf(PhantomProcessStatus.NOT_APPLICABLE)
|
||||
private var showPhantomGate by mutableStateOf(false)
|
||||
private var directAudio by mutableStateOf(false)
|
||||
private var clientDirectAudio by mutableStateOf(false)
|
||||
private var forceFullscreen by mutableStateOf(true)
|
||||
@@ -238,6 +246,7 @@ class MainActivity : ComponentActivity() {
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
displayManager = getSystemService(DISPLAY_SERVICE) as DisplayManager
|
||||
refreshPhantomStatus()
|
||||
theme = SessionPrefs.theme(this)
|
||||
backActionsInverted = SessionPrefs.backActionsInverted(this)
|
||||
setContent {
|
||||
@@ -277,19 +286,21 @@ class MainActivity : ComponentActivity() {
|
||||
buildLabel = BuildConfig.BUILD_LABEL,
|
||||
oscMode = oscMode,
|
||||
controller = controllerSettings,
|
||||
phantomProcessStatus = phantomProcessStatus,
|
||||
showPhantomGate = showPhantomGate,
|
||||
),
|
||||
FrontEndActions(
|
||||
onPlay = { startSession(Intent(this, SessionActivity::class.java)) },
|
||||
onPlay = { startSession(Intent(this, SessionActivity::class.java), steamSession = true) },
|
||||
// Steam's desktop client as a window on the desktop: under gamescope the
|
||||
// client puts itself into Big Picture whatever it is started with.
|
||||
onPlayDesktopUi = {
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_MODE, SessionService.MODE_DESKTOP)
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"))
|
||||
.putExtra(SessionService.EXTRA_STEAM_UI, "desktop"), steamSession = true)
|
||||
},
|
||||
onSteamGame = { g ->
|
||||
startActivity(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_STEAM_URL, "steam://rungameid/${g.gameId}"))
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
.putExtra(SessionService.EXTRA_STEAM_URL, "steam://rungameid/${g.gameId}"), steamSession = true)
|
||||
},
|
||||
onDesktop = {
|
||||
startSession(Intent(this, SessionActivity::class.java)
|
||||
@@ -351,6 +362,50 @@ class MainActivity : ComponentActivity() {
|
||||
onCheckLatestBuild = {
|
||||
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://github.com/The412Banner/DroidDeck/actions/workflows/build.yml")))
|
||||
},
|
||||
onRefreshPhantomStatus = { refreshPhantomStatus() },
|
||||
onOpenDeveloperOptions = { displayId -> openDeveloperOptions(displayId) },
|
||||
onWirelessAdbPair = { host, port, code, complete ->
|
||||
Thread({
|
||||
val result = runCatching {
|
||||
kotlinx.coroutines.runBlocking { WirelessAdbFix.pair(this@MainActivity, host, port, code) }
|
||||
}
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB pairing failed" }
|
||||
ui.post { complete(error) }
|
||||
}, "wireless-adb-pair").start()
|
||||
},
|
||||
onFindWirelessAdbPort = { host, complete ->
|
||||
Thread({
|
||||
val port = WirelessAdbFix.findConnectPort(this@MainActivity, host)
|
||||
ui.post { complete(port) }
|
||||
}, "wireless-adb-discovery").start()
|
||||
},
|
||||
onWirelessAdbApply = { host, port, enabled, complete ->
|
||||
Thread({
|
||||
val result = runCatching { WirelessAdbFix.setChildProcessLimit(this@MainActivity, host, port, enabled) }
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB command failed" }
|
||||
ui.post {
|
||||
if (error == null) refreshPhantomStatus()
|
||||
complete(error)
|
||||
}
|
||||
}, "wireless-adb-fix").start()
|
||||
},
|
||||
onSetPhantomProcessLimit = { enabled, complete ->
|
||||
Thread({
|
||||
val result = runCatching { WirelessAdbFix.setUsingSavedPairing(this@MainActivity, enabled) }
|
||||
val error = result.exceptionOrNull()?.let { it.localizedMessage ?: "Wireless ADB is unavailable" }
|
||||
ui.post {
|
||||
if (error == null) refreshPhantomStatus()
|
||||
complete(error)
|
||||
}
|
||||
}, "wireless-adb-setting").start()
|
||||
},
|
||||
onCopyPhantomCommand = { enabled ->
|
||||
(getSystemService(CLIPBOARD_SERVICE) as ClipboardManager).setPrimaryClip(
|
||||
ClipData.newPlainText("DroidDeck child-process setting", PhantomProcessLimit.adbCommand(enabled)),
|
||||
)
|
||||
android.widget.Toast.makeText(this, "ADB command copied", android.widget.Toast.LENGTH_SHORT).show()
|
||||
},
|
||||
onDismissPhantomGate = { showPhantomGate = false },
|
||||
controller = ControllerActions(
|
||||
onOsc = { o -> SessionPrefs.setOscMode(this, o); oscMode = o },
|
||||
onTint = { t -> ControllerPrefs.setTint(this, t); refreshController() },
|
||||
@@ -419,6 +474,7 @@ class MainActivity : ComponentActivity() {
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
refreshPhantomStatus()
|
||||
oscMode = SessionPrefs.oscMode(this)
|
||||
refreshController()
|
||||
refreshHomeAppState()
|
||||
@@ -1008,17 +1064,7 @@ class MainActivity : ComponentActivity() {
|
||||
zinkLazy = SessionPrefs.zinkLazy(this)
|
||||
noXalia = SessionPrefs.noXalia(this)
|
||||
prootNoSeccomp = SessionPrefs.prootNoSeccomp(this)
|
||||
// Android 12 kills the children an app forks itself once there are more than a handful.
|
||||
// A session is nothing but those, so where this is on the OS ends the session and no log
|
||||
// of ours says why. We cannot change a secure setting from here - only say so.
|
||||
phantomWarning = runCatching {
|
||||
android.provider.Settings.Global.getString(contentResolver, "settings_enable_monitor_phantom_procs")
|
||||
}.getOrNull().let { v ->
|
||||
when (v?.lowercase()) {
|
||||
"false", "0" -> null
|
||||
else -> "Android 12 and later kill the extra processes an app starts for itself once there are more than a few, and a session is made of dozens: proot, gamescope, the client and its helpers, Wine. Where that is left on, the client dies with nothing in its log, because nothing in the session did it. Some phones have a \"restrict child processes\" switch in Developer options - turn it off. Otherwise, over adb:\n\n adb shell settings put global settings_enable_monitor_phantom_procs false\n\nThis phone " + (if (v == null) "has not been set either way, so the ROM's default applies." else "currently reports it as on.")
|
||||
}
|
||||
}
|
||||
refreshPhantomStatus()
|
||||
}
|
||||
|
||||
private fun refreshProtons() {
|
||||
@@ -1075,12 +1121,41 @@ class MainActivity : ComponentActivity() {
|
||||
}
|
||||
|
||||
/** Starts a session; with no runtime on a non-Adreno, the same warning Setup gives comes first, before any download. */
|
||||
private fun startSession(intent: Intent) {
|
||||
private fun startSession(intent: Intent, steamSession: Boolean = false) {
|
||||
refreshPhantomStatus()
|
||||
if (steamSession && PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
showPhantomGate = true
|
||||
return
|
||||
}
|
||||
val warn = installed == null && !com.droiddeck.launcher.core.DeviceSupport.adreno()
|
||||
if (warn && available != null) showNonAdreno = available
|
||||
else startActivity(intent)
|
||||
}
|
||||
|
||||
private fun refreshPhantomStatus() {
|
||||
phantomProcessStatus = PhantomProcessLimit.read(contentResolver)
|
||||
phantomWarning = if (PhantomProcessLimit.blocksSteam(phantomProcessStatus)) {
|
||||
"${PhantomProcessLimit.title(phantomProcessStatus)}. ${PhantomProcessLimit.instructions(phantomProcessStatus)}\n\n${PhantomProcessLimit.ADB_COMMAND}"
|
||||
} else null
|
||||
}
|
||||
|
||||
private fun openDeveloperOptions(displayId: Int?) {
|
||||
val intent = Intent(android.provider.Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
try {
|
||||
if (displayId == null) startActivity(intent)
|
||||
else startActivity(intent, ActivityOptions.makeBasic().setLaunchDisplayId(displayId).toBundle())
|
||||
} catch (error: Exception) {
|
||||
if (displayId != null) {
|
||||
runCatching { startActivity(intent) }
|
||||
android.widget.Toast.makeText(this, "Could not open Settings on the bottom screen; opened it on the main screen.", android.widget.Toast.LENGTH_LONG).show()
|
||||
} else {
|
||||
startActivity(Intent(android.provider.Settings.ACTION_SETTINGS).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
|
||||
android.widget.Toast.makeText(this, "Open Developer options in Settings", android.widget.Toast.LENGTH_LONG).show()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun install(release: LinuxRuntimeInstaller.Release) {
|
||||
busy = true
|
||||
failed = false
|
||||
|
||||
@@ -5,7 +5,6 @@ import android.content.Context
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.os.StatFs
|
||||
import android.provider.Settings
|
||||
import android.util.Log
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriver
|
||||
import com.droiddeck.launcher.gpu.LinuxVulkanDriverManager
|
||||
@@ -162,21 +161,7 @@ object DeviceReport {
|
||||
})
|
||||
|
||||
h("Android process limits")
|
||||
// Android 12 kills "phantom" processes - the children an app forks itself rather than
|
||||
// starting through the framework - once there are more than a handful of them. A session is
|
||||
// nothing but those: proot, gamescope, Xwayland, the client, its helpers, Wine, FEX. Where
|
||||
// this is left on, the OS kills the session and nothing in our logs says why, because
|
||||
// nothing in the session did it. Some ROMs expose it in Developer options as a
|
||||
// "restrict child processes" switch; otherwise it is
|
||||
// adb shell settings put global settings_enable_monitor_phantom_procs false
|
||||
val phantom = runCatching {
|
||||
Settings.Global.getString(context.contentResolver, "settings_enable_monitor_phantom_procs")
|
||||
}.getOrNull()
|
||||
k("Phantom proc monitor", when (phantom?.lowercase()) {
|
||||
"false", "0" -> "disabled (good - the OS will not kill the session's children)"
|
||||
null, "" -> "not set (ROM default, usually ENABLED - see the note below)"
|
||||
else -> "ENABLED (the OS may kill the session with no log; turn off \"restrict child processes\")"
|
||||
})
|
||||
k("Phantom proc monitor", PhantomProcessLimit.reportValue(PhantomProcessLimit.read(context.contentResolver)))
|
||||
|
||||
h("Device switch files in Download")
|
||||
for (name in listOf("droiddeck-env", "droiddeck-tu-debug", "droiddeck-driver",
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.ContentResolver
|
||||
import android.os.Build
|
||||
import android.provider.Settings
|
||||
|
||||
/** Android's phantom process monitor can kill the many child processes used by a Steam session. */
|
||||
enum class PhantomProcessStatus {
|
||||
NOT_APPLICABLE,
|
||||
DISABLED,
|
||||
ENABLED,
|
||||
UNSET,
|
||||
UNREADABLE,
|
||||
}
|
||||
|
||||
object PhantomProcessLimit {
|
||||
const val ADB_COMMAND = "adb shell settings put global settings_enable_monitor_phantom_procs false"
|
||||
const val SHELL_COMMAND = "settings put global settings_enable_monitor_phantom_procs false"
|
||||
private const val SETTING = "settings_enable_monitor_phantom_procs"
|
||||
|
||||
fun adbCommand(enabled: Boolean): String =
|
||||
"adb shell settings put global $SETTING ${if (enabled) "true" else "false"}"
|
||||
|
||||
fun read(resolver: ContentResolver, sdk: Int = Build.VERSION.SDK_INT): PhantomProcessStatus {
|
||||
if (sdk < Build.VERSION_CODES.S) return PhantomProcessStatus.NOT_APPLICABLE
|
||||
val value = try {
|
||||
Settings.Global.getString(resolver, SETTING)
|
||||
} catch (_: Exception) {
|
||||
return PhantomProcessStatus.UNREADABLE
|
||||
}
|
||||
return when (value?.trim()?.lowercase()) {
|
||||
"false", "0" -> PhantomProcessStatus.DISABLED
|
||||
null, "" -> PhantomProcessStatus.UNSET
|
||||
else -> PhantomProcessStatus.ENABLED
|
||||
}
|
||||
}
|
||||
|
||||
fun blocksSteam(status: PhantomProcessStatus): Boolean =
|
||||
status != PhantomProcessStatus.NOT_APPLICABLE && status != PhantomProcessStatus.DISABLED
|
||||
|
||||
fun title(status: PhantomProcessStatus): String = when (status) {
|
||||
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
|
||||
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
|
||||
PhantomProcessStatus.UNREADABLE -> "Child-process limit could not be checked"
|
||||
PhantomProcessStatus.DISABLED -> "Child-process limit is off"
|
||||
PhantomProcessStatus.NOT_APPLICABLE -> "Child-process limit not required"
|
||||
}
|
||||
|
||||
fun instructions(status: PhantomProcessStatus): String = when (status) {
|
||||
PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
|
||||
PhantomProcessStatus.UNSET -> "This setting is unset, so the ROM default applies and may enforce the limit. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
|
||||
PhantomProcessStatus.UNREADABLE -> "DroidDeck could not read the setting. Set “Restrict child processes” to off in Developer options. If you cannot find that option, connect this device to a computer with ADB and run the command below. Return here and check again."
|
||||
PhantomProcessStatus.DISABLED -> "Steam sessions can start."
|
||||
PhantomProcessStatus.NOT_APPLICABLE -> "This Android version does not use this limit."
|
||||
}
|
||||
|
||||
fun gateInstructions(status: PhantomProcessStatus): String = when (status) {
|
||||
PhantomProcessStatus.ENABLED -> "Turn off “Restrict child processes” in Developer options."
|
||||
PhantomProcessStatus.UNSET -> "The ROM default may enforce this limit. Explicitly turn off “Restrict child processes” in Developer options."
|
||||
PhantomProcessStatus.UNREADABLE -> "DroidDeck could not check this setting. Turn off “Restrict child processes” in Developer options."
|
||||
else -> instructions(status)
|
||||
}
|
||||
|
||||
fun reportValue(status: PhantomProcessStatus): String = when (status) {
|
||||
PhantomProcessStatus.DISABLED -> "disabled (good - the OS will not kill the session's children)"
|
||||
PhantomProcessStatus.ENABLED -> "ENABLED (the OS may kill the session with no log; turn off Restrict child processes)"
|
||||
PhantomProcessStatus.UNSET -> "not set (ROM default applies; DroidDeck requires an explicit disabled value)"
|
||||
PhantomProcessStatus.UNREADABLE -> "unreadable (DroidDeck could not verify the setting)"
|
||||
PhantomProcessStatus.NOT_APPLICABLE -> "not applicable before Android 12"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
package com.droiddeck.launcher.core
|
||||
|
||||
import android.content.Context
|
||||
import android.net.nsd.NsdManager
|
||||
import android.net.nsd.NsdServiceInfo
|
||||
import com.flyfishxu.kadb.Kadb
|
||||
import com.flyfishxu.kadb.cert.KadbCert
|
||||
import java.io.File
|
||||
import java.net.InetAddress
|
||||
import java.util.concurrent.CountDownLatch
|
||||
import java.util.concurrent.TimeUnit
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
import java.util.concurrent.atomic.AtomicInteger
|
||||
import java.util.ArrayDeque
|
||||
|
||||
/** A narrowly scoped Wireless debugging client for the child-process setting repair. */
|
||||
object WirelessAdbFix {
|
||||
private const val CERT_FILE = "wireless-adb-cert.pem"
|
||||
private const val KEY_FILE = "wireless-adb-key.pem"
|
||||
private const val HOST_FILE = "wireless-adb-host.txt"
|
||||
private const val CONNECTION_FILE = "wireless-adb-connection.txt"
|
||||
|
||||
private data class SavedConnection(val host: String, val port: Int?)
|
||||
|
||||
@Synchronized
|
||||
private fun loadOrCreateIdentity(context: Context) {
|
||||
val directory = context.noBackupFilesDir
|
||||
val cert = File(directory, CERT_FILE)
|
||||
val key = File(directory, KEY_FILE)
|
||||
if (cert.isFile && key.isFile) {
|
||||
KadbCert.set(cert.readBytes(), key.readBytes())
|
||||
return
|
||||
}
|
||||
|
||||
val identity = KadbCert.get(notAfter = System.currentTimeMillis() + TimeUnit.DAYS.toMillis(3650))
|
||||
KadbCert.set(identity.first, identity.second)
|
||||
writeAtomically(cert, identity.first)
|
||||
writeAtomically(key, identity.second)
|
||||
}
|
||||
|
||||
private fun writeAtomically(destination: File, contents: ByteArray) {
|
||||
val temporary = File(destination.parentFile, "${destination.name}.tmp")
|
||||
temporary.writeBytes(contents)
|
||||
check(temporary.renameTo(destination)) { "Could not save Wireless debugging identity" }
|
||||
}
|
||||
|
||||
suspend fun pair(context: Context, host: String, port: Int, pairingCode: String) {
|
||||
loadOrCreateIdentity(context.applicationContext)
|
||||
Kadb.pair(host, port, pairingCode, "DroidDeck")
|
||||
writeAtomically(File(context.noBackupFilesDir, HOST_FILE), host.toByteArray())
|
||||
writeAtomically(File(context.noBackupFilesDir, CONNECTION_FILE), ByteArray(0))
|
||||
}
|
||||
|
||||
private fun savedConnection(context: Context): SavedConnection? {
|
||||
val directory = context.applicationContext.noBackupFilesDir
|
||||
if (!File(directory, CERT_FILE).isFile || !File(directory, KEY_FILE).isFile) return null
|
||||
val host = File(directory, HOST_FILE).takeIf(File::isFile)?.readText()?.trim()
|
||||
?.takeIf(String::isNotEmpty) ?: return null
|
||||
val lines = File(directory, CONNECTION_FILE).takeIf(File::isFile)?.readLines()
|
||||
val port = lines?.takeIf { it.size == 2 && it[0] == host }
|
||||
?.get(1)?.toIntOrNull()?.takeIf { it in 1..65535 }
|
||||
return SavedConnection(host, port)
|
||||
}
|
||||
|
||||
/** A saved pairing skips the PIN; an unknown connection port can be filled in from Settings. */
|
||||
fun savedConnectionAddress(context: Context): String? = savedConnection(context)?.let { saved ->
|
||||
val host = if (':' in saved.host) "[${saved.host}]" else saved.host
|
||||
"$host:${saved.port ?: ""}"
|
||||
}
|
||||
|
||||
private fun saveConnection(context: Context, host: String, port: Int) {
|
||||
writeAtomically(
|
||||
File(context.applicationContext.noBackupFilesDir, CONNECTION_FILE),
|
||||
"$host\n$port".toByteArray(),
|
||||
)
|
||||
}
|
||||
|
||||
/** Finds this paired device's separate TLS connection port from Android's ADB mDNS record. */
|
||||
fun findConnectPort(context: Context, pairedHost: String, timeoutSeconds: Long = 12): Int? {
|
||||
val manager = context.applicationContext.getSystemService(Context.NSD_SERVICE) as NsdManager
|
||||
val expectedAddress = runCatching { InetAddress.getByName(pairedHost).address }.getOrNull() ?: return null
|
||||
val resolvedPort = AtomicInteger(-1)
|
||||
val finished = AtomicBoolean(false)
|
||||
val latch = CountDownLatch(1)
|
||||
val queue = ArrayDeque<NsdServiceInfo>()
|
||||
val seen = mutableSetOf<String>()
|
||||
var resolving = false
|
||||
val lock = Any()
|
||||
|
||||
lateinit var resolveNext: () -> Unit
|
||||
resolveNext = {
|
||||
val next = synchronized(lock) {
|
||||
if (finished.get() || resolving || queue.isEmpty()) null
|
||||
else queue.removeFirst().also { resolving = true }
|
||||
}
|
||||
if (next != null) {
|
||||
val listener = object : NsdManager.ResolveListener {
|
||||
override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) {
|
||||
synchronized(lock) { resolving = false }
|
||||
resolveNext()
|
||||
}
|
||||
|
||||
override fun onServiceResolved(serviceInfo: NsdServiceInfo) {
|
||||
val address = serviceInfo.host?.address
|
||||
if (address != null && address.contentEquals(expectedAddress) && finished.compareAndSet(false, true)) {
|
||||
resolvedPort.set(serviceInfo.port)
|
||||
latch.countDown()
|
||||
} else {
|
||||
synchronized(lock) { resolving = false }
|
||||
resolveNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
runCatching { manager.resolveService(next, listener) }.onFailure {
|
||||
synchronized(lock) { resolving = false }
|
||||
resolveNext()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
val discoveryListener = object : NsdManager.DiscoveryListener {
|
||||
override fun onDiscoveryStarted(serviceType: String) = Unit
|
||||
override fun onServiceFound(serviceInfo: NsdServiceInfo) {
|
||||
if (serviceInfo.serviceType?.contains("_adb-tls-connect._tcp") == true) {
|
||||
synchronized(lock) {
|
||||
if (seen.add(serviceInfo.serviceName)) queue.addLast(serviceInfo)
|
||||
}
|
||||
resolveNext()
|
||||
}
|
||||
}
|
||||
override fun onServiceLost(serviceInfo: NsdServiceInfo) = Unit
|
||||
override fun onDiscoveryStopped(serviceType: String) { latch.countDown() }
|
||||
override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { latch.countDown() }
|
||||
override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) { latch.countDown() }
|
||||
}
|
||||
|
||||
try {
|
||||
manager.discoverServices("_adb-tls-connect._tcp.", NsdManager.PROTOCOL_DNS_SD, discoveryListener)
|
||||
latch.await(timeoutSeconds, TimeUnit.SECONDS)
|
||||
} catch (_: Exception) {
|
||||
return null
|
||||
} finally {
|
||||
runCatching { manager.stopServiceDiscovery(discoveryListener) }
|
||||
}
|
||||
return resolvedPort.get().takeIf { it in 1..65535 }
|
||||
}
|
||||
|
||||
fun setChildProcessLimit(context: Context, host: String, port: Int, enabled: Boolean) {
|
||||
loadOrCreateIdentity(context.applicationContext)
|
||||
Kadb.create(host, port).use { adb ->
|
||||
val value = if (enabled) "true" else "false"
|
||||
val change = adb.shell("settings put global settings_enable_monitor_phantom_procs $value")
|
||||
check(change.exitCode == 0) { change.allOutput.ifBlank { "ADB command failed (${change.exitCode})" } }
|
||||
val result = adb.shell("settings get global settings_enable_monitor_phantom_procs")
|
||||
check(result.exitCode == 0 && result.output.trim() == value) {
|
||||
"Android did not confirm the child-process limit was changed: ${result.allOutput.trim()}"
|
||||
}
|
||||
}
|
||||
saveConnection(context, host, port)
|
||||
}
|
||||
|
||||
/** Tries the app's saved pairing without asking for a new pairing code. */
|
||||
fun setUsingSavedPairing(context: Context, enabled: Boolean) {
|
||||
val appContext = context.applicationContext
|
||||
val saved = savedConnection(appContext)
|
||||
?: error("No Wireless debugging pairing is saved")
|
||||
val cachedPort = saved.port
|
||||
if (cachedPort != null) {
|
||||
val cachedResult = runCatching {
|
||||
setChildProcessLimit(appContext, saved.host, cachedPort, enabled)
|
||||
}
|
||||
if (cachedResult.isSuccess) return
|
||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||
if (discoveredPort != null && discoveredPort != cachedPort) {
|
||||
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||
} else {
|
||||
cachedResult.getOrThrow()
|
||||
}
|
||||
} else {
|
||||
val discoveredPort = findConnectPort(appContext, saved.host)
|
||||
?: error("Enter the current Wireless debugging IP address & Port")
|
||||
setChildProcessLimit(appContext, saved.host, discoveredPort, enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -148,8 +148,142 @@ object SessionFiles {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write ld.so.preload")
|
||||
}
|
||||
|
||||
val startupMovie = File(root, "root/.local/share/Steam/config/uioverrides/movies/droiddeck-startup.webm")
|
||||
val stagedMovie = File(startupMovie.parentFile, startupMovie.name + ".staged")
|
||||
var movieInstalled = false
|
||||
try {
|
||||
startupMovie.parentFile?.mkdirs()
|
||||
context.assets.open("steam-startup/droiddeck-startup.webm").use { input ->
|
||||
stagedMovie.outputStream().use { output -> FileUtils.copy(input, output) }
|
||||
}
|
||||
movieInstalled = stagedMovie.setReadable(true, false) && stagedMovie.renameTo(startupMovie)
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not stage Steam startup movie", e)
|
||||
} finally {
|
||||
if (!movieInstalled) stagedMovie.delete()
|
||||
}
|
||||
if (!movieInstalled) Log.e(TAG, "Steam startup movie NOT staged")
|
||||
if (movieInstalled) ensureStartupMovieDefault(File(root, "root/.local/share/Steam/config/config.vdf"))
|
||||
}
|
||||
|
||||
private data class VdfBlock(val keyStart: Int, val open: Int, val close: Int)
|
||||
|
||||
private fun ensureStartupMovieDefault(config: File) {
|
||||
val path = "/uioverrides/movies/droiddeck-startup.webm"
|
||||
var text = if (config.isFile) runCatching { config.readText() }.getOrElse {
|
||||
Log.w(TAG, "could not read Steam config for startup movie", it)
|
||||
return
|
||||
} else ""
|
||||
val newline = if (text.contains("\r\n")) "\r\n" else "\n"
|
||||
val movie = findObject(text, "StartupMovie", 0, text.length)
|
||||
if (movie != null) {
|
||||
val block = text.substring(movie.keyStart, movie.close + 1)
|
||||
val selectedId = scalar(block, "MovieID")
|
||||
val selectedPath = scalar(block, "LocalPath")
|
||||
if (selectedPath == path) {
|
||||
Log.i(TAG, "Steam startup movie is set to DroidDeck")
|
||||
return
|
||||
}
|
||||
if ((!selectedId.isNullOrEmpty() && selectedId != "0") || !selectedPath.isNullOrEmpty()) {
|
||||
Log.i(TAG, "Steam startup movie selection preserved")
|
||||
return
|
||||
}
|
||||
val updated = setScalar(block, "MovieID", "0", newline)
|
||||
.let { setScalar(it, "LocalPath", path, newline) }
|
||||
text = text.replaceRange(movie.keyStart, movie.close + 1, updated)
|
||||
} else {
|
||||
val steam = findSteamBlock(text)
|
||||
if (steam == null) {
|
||||
if (text.isNotBlank()) {
|
||||
Log.w(TAG, "Steam config has no Steam settings block; startup movie default not set")
|
||||
return
|
||||
}
|
||||
text = "\"InstallConfigStore\"${newline}{${newline}\t\"Software\"${newline}\t{${newline}\t\t\"Valve\"${newline}\t\t{${newline}\t\t\t\"Steam\"${newline}\t\t\t{${newline}"
|
||||
val section = startupMovieSection("\t\t\t\t", path, newline)
|
||||
text += section + newline + "\t\t\t}" + newline + "\t\t}" + newline + "\t}" + newline + "}"
|
||||
} else {
|
||||
val lineStart = text.lastIndexOf('\n', steam.close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = text.substring(lineStart, steam.close).takeWhile { it == '\t' || it == ' ' }
|
||||
val section = startupMovieSection(indent + "\t", path, newline)
|
||||
text = text.substring(0, lineStart) + section + newline + indent + text.substring(lineStart)
|
||||
}
|
||||
}
|
||||
val staged = File(config.parentFile, config.name + ".staged")
|
||||
try {
|
||||
config.parentFile?.mkdirs()
|
||||
staged.writeText(text)
|
||||
if (!staged.renameTo(config)) {
|
||||
staged.delete()
|
||||
Log.e(TAG, "could not write Steam startup movie selection")
|
||||
} else {
|
||||
Log.i(TAG, "Steam startup movie default selected")
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
staged.delete()
|
||||
Log.w(TAG, "could not write Steam startup movie selection", e)
|
||||
}
|
||||
}
|
||||
|
||||
private fun findSteamBlock(text: String): VdfBlock? {
|
||||
val install = findObject(text, "InstallConfigStore", 0, text.length) ?: return null
|
||||
val software = findObject(text, "Software", install.open + 1, install.close) ?: return null
|
||||
val valve = findObject(text, "Valve", software.open + 1, software.close) ?: return null
|
||||
return findObject(text, "Steam", valve.open + 1, valve.close)
|
||||
}
|
||||
|
||||
private fun findObject(text: String, key: String, start: Int, end: Int): VdfBlock? {
|
||||
val pattern = Regex("(?m)^[\\t ]*\"${Regex.escape(key)}\"[\\t ]*(?:\\r?\\n[\\t ]*)?\\{")
|
||||
val match = pattern.find(text, start)?.takeIf { it.range.first < end && it.range.last < end } ?: return null
|
||||
val open = text.indexOf('{', match.range.first).takeIf { it < end } ?: return null
|
||||
var depth = 0
|
||||
var quoted = false
|
||||
var escaped = false
|
||||
for (index in open until end) {
|
||||
val char = text[index]
|
||||
if (quoted) {
|
||||
if (escaped) escaped = false
|
||||
else if (char == '\\') escaped = true
|
||||
else if (char == '\"') quoted = false
|
||||
} else {
|
||||
when (char) {
|
||||
'\"' -> quoted = true
|
||||
'{' -> depth++
|
||||
'}' -> {
|
||||
depth--
|
||||
if (depth == 0) return VdfBlock(match.range.first, open, index)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
private fun scalar(block: String, key: String): String? {
|
||||
val pattern = Regex("(?m)^[\\t ]*\"${Regex.escape(key)}\"[\\t ]+\"([^\"\\r\\n]*)\"")
|
||||
return pattern.find(block)?.groupValues?.get(1)
|
||||
}
|
||||
|
||||
private fun setScalar(block: String, key: String, value: String, newline: String): String {
|
||||
val pattern = Regex("(?m)^([\\t ]*\"${Regex.escape(key)}\"[\\t ]+)\"[^\"\\r\\n]*\"([\\t ]*)$")
|
||||
val match = pattern.find(block)
|
||||
if (match != null) return block.replaceRange(match.range, match.groupValues[1] + "\"" + value + "\"" + match.groupValues[2])
|
||||
val close = block.lastIndexOf('}')
|
||||
if (close < 0) return block
|
||||
val lineStart = block.lastIndexOf('\n', close).let { if (it < 0) 0 else it + 1 }
|
||||
val indent = block.substring(lineStart, close).takeWhile { it == '\t' || it == ' ' } + "\t"
|
||||
val entry = indent + "\"" + key + "\"\t\t\"" + value + "\"" + newline
|
||||
return block.substring(0, lineStart) + entry + block.substring(lineStart)
|
||||
}
|
||||
|
||||
private fun startupMovieSection(indent: String, path: String, newline: String): String = listOf(
|
||||
indent + "\"StartupMovie\"",
|
||||
indent + "{",
|
||||
indent + "\t\"MovieID\"\t\t\"0\"",
|
||||
indent + "\t\"LocalPath\"\t\t\"" + path + "\"",
|
||||
indent + "}",
|
||||
).joinToString(newline)
|
||||
|
||||
/**
|
||||
* Where the session writes its log. Downloads is the point - a failed run is handed over as a
|
||||
* folder rather than dug out of app-private storage - but the session script redirects its own
|
||||
|
||||
@@ -71,6 +71,7 @@ import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.systemBarsPadding
|
||||
import androidx.compose.foundation.layout.width
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.rememberScrollState
|
||||
import androidx.compose.foundation.shape.CircleShape
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
@@ -136,6 +137,8 @@ import com.droiddeck.launcher.HomeApp
|
||||
import com.droiddeck.launcher.frontend.Library
|
||||
import com.droiddeck.launcher.gpu.FrameGen
|
||||
import com.droiddeck.launcher.input.SecondScreenDisplay
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
import com.droiddeck.launcher.session.SessionPrefs
|
||||
import java.io.File
|
||||
import kotlin.math.roundToInt
|
||||
@@ -176,6 +179,8 @@ class FrontEndState(
|
||||
val buildLabel: String = "local",
|
||||
val oscMode: String = SessionPrefs.OSC_AUTO,
|
||||
val controller: com.droiddeck.launcher.input.ControllerPrefs.Settings? = null,
|
||||
val phantomProcessStatus: PhantomProcessStatus = PhantomProcessStatus.NOT_APPLICABLE,
|
||||
val showPhantomGate: Boolean = false,
|
||||
)
|
||||
|
||||
class FrontEndActions(
|
||||
@@ -207,6 +212,14 @@ class FrontEndActions(
|
||||
val onAndroidApp: (HomeApp.LaunchableApp, Int?) -> Unit = { _, _ -> },
|
||||
val onBackActionsInverted: (Boolean) -> Unit = {},
|
||||
val onCheckLatestBuild: () -> Unit = {},
|
||||
val onRefreshPhantomStatus: () -> Unit = {},
|
||||
val onOpenDeveloperOptions: (Int?) -> Unit = {},
|
||||
val onWirelessAdbPair: (String, Int, String, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless ADB is unavailable") },
|
||||
val onFindWirelessAdbPort: (String, (Int?) -> Unit) -> Unit = { _, done -> done(null) },
|
||||
val onWirelessAdbApply: (String, Int, Boolean, (String?) -> Unit) -> Unit = { _, _, _, done -> done("Wireless ADB is unavailable") },
|
||||
val onSetPhantomProcessLimit: (Boolean, (String?) -> Unit) -> Unit = { _, done -> done("Wireless ADB is unavailable") },
|
||||
val onCopyPhantomCommand: (Boolean) -> Unit = {},
|
||||
val onDismissPhantomGate: () -> Unit = {},
|
||||
val controller: ControllerActions? = null,
|
||||
)
|
||||
|
||||
@@ -343,14 +356,35 @@ fun FrontEndScreen(s: FrontEndState, a: FrontEndActions, page: (@Composable () -
|
||||
private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Composable () -> Unit)?, frontFocus: FrontFocus) {
|
||||
var selected by rememberSaveable { mutableStateOf("steam") }
|
||||
var navOpen by rememberSaveable { mutableStateOf(false) }
|
||||
var showWirelessAdbFix by rememberSaveable { mutableStateOf(false) }
|
||||
var showDeveloperDisplayChoice by rememberSaveable { mutableStateOf(false) }
|
||||
var wirelessAdbDesiredEnabled by rememberSaveable { mutableStateOf(false) }
|
||||
var appToChooseDisplay by remember { mutableStateOf<HomeApp.LaunchableApp?>(null) }
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val ctx = LocalContext.current
|
||||
BackHandler(enabled = s.pageKey != null && page != null) { a.onPageBack() }
|
||||
val phantomGateVisible = s.showPhantomGate && PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)
|
||||
val processSettingsPageVisible = phantomGateVisible || showWirelessAdbFix || showDeveloperDisplayChoice
|
||||
val requestDeveloperOptions = {
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onOpenDeveloperOptions(null)
|
||||
else showDeveloperDisplayChoice = true
|
||||
}
|
||||
val requestWirelessAdbFix: (Boolean) -> Unit = { enabled ->
|
||||
wirelessAdbDesiredEnabled = enabled
|
||||
showWirelessAdbFix = true
|
||||
}
|
||||
LaunchedEffect(s.showPhantomGate, s.phantomProcessStatus) {
|
||||
if (phantomGateVisible) {
|
||||
while (true) {
|
||||
kotlinx.coroutines.delay(2_000)
|
||||
a.onRefreshPhantomStatus()
|
||||
}
|
||||
}
|
||||
}
|
||||
BackHandler(enabled = !processSettingsPageVisible && s.pageKey != null && page != null) { a.onPageBack() }
|
||||
// Back (and B) from a game or an emulator steps out one level, as its "‹" link does, instead
|
||||
// of leaving the app: a game -> its emulator (or Steam), an emulator -> Desktop.
|
||||
BackHandler(
|
||||
enabled = (s.pageKey == null || page == null) &&
|
||||
enabled = !processSettingsPageVisible && (s.pageKey == null || page == null) &&
|
||||
(selected.startsWith("app:") || selected.startsWith("emu:") || selected.startsWith("rom:")),
|
||||
) {
|
||||
selected = when {
|
||||
@@ -381,7 +415,8 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
// Start controllers on the current page's main action; the rail is initially collapsed.
|
||||
val window = LocalWindowInfo.current
|
||||
val inputMode = LocalInputModeManager.current
|
||||
LaunchedEffect(Unit) {
|
||||
LaunchedEffect(processSettingsPageVisible) {
|
||||
if (processSettingsPageVisible) return@LaunchedEffect
|
||||
snapshotFlow { window.isWindowFocused }.first { it }
|
||||
repeat(20) {
|
||||
if (anyFocused) return@LaunchedEffect
|
||||
@@ -395,14 +430,16 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
// the pad then had nothing to move from (a press landed back on the rail's first item). So
|
||||
// once the new page is in, a controller lands on its main button.
|
||||
val inputModeManager = LocalInputModeManager.current
|
||||
LaunchedEffect(selected, s.pageKey) {
|
||||
LaunchedEffect(selected, s.pageKey, processSettingsPageVisible) {
|
||||
if (processSettingsPageVisible) return@LaunchedEffect
|
||||
kotlinx.coroutines.delay(450)
|
||||
if (!anyFocused && inputModeManager.inputMode == InputMode.Keyboard) runCatching {
|
||||
if (frontFocus.primaryAttached > 0) frontFocus.primary.requestFocus()
|
||||
else frontFocus.menuToggle.requestFocus()
|
||||
}
|
||||
}
|
||||
LaunchedEffect(navOpen, railSelection) {
|
||||
LaunchedEffect(navOpen, railSelection, processSettingsPageVisible) {
|
||||
if (processSettingsPageVisible) return@LaunchedEffect
|
||||
if (navOpen) {
|
||||
frontFocus.focusedRail = null
|
||||
repeat(12) {
|
||||
@@ -423,14 +460,19 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
.focusProperties { enter = { frontFocus.paneEntry() } }
|
||||
.focusGroup()
|
||||
val content: @Composable (Modifier) -> Unit = { m ->
|
||||
Pane(s, selected, a, page, m.then(paneFocus), { selected = it }) { app ->
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
}
|
||||
Pane(
|
||||
s, selected, a, page, m.then(paneFocus), { selected = it },
|
||||
onAndroidAppClick = { app ->
|
||||
if (s.secondScreenDisplays.isEmpty()) a.onAndroidApp(app, null)
|
||||
else appToChooseDisplay = app
|
||||
},
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onRequestWirelessAdb = requestWirelessAdbFix,
|
||||
)
|
||||
}
|
||||
Box(modifier = Modifier.fillMaxSize()) {
|
||||
Column(modifier = Modifier.fillMaxSize()) {
|
||||
LauncherTopBar(frontFocus.menuToggle) { navOpen = true }
|
||||
LauncherTopBar(frontFocus.menuToggle, s.buildLabel, a.onCheckLatestBuild) { navOpen = true }
|
||||
content(Modifier.weight(1f).fillMaxWidth())
|
||||
}
|
||||
AnimatedVisibility(
|
||||
@@ -473,17 +515,60 @@ private fun FrontEndScreenBody(s: FrontEndState, a: FrontEndActions, page: (@Com
|
||||
onDismiss = { appToChooseDisplay = null },
|
||||
)
|
||||
}
|
||||
if (phantomGateVisible && !showWirelessAdbFix) {
|
||||
Box(Modifier.fillMaxSize().background(colors.background)) {
|
||||
PhantomProcessGatePage(
|
||||
status = s.phantomProcessStatus,
|
||||
onDismiss = a.onDismissPhantomGate,
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onSetUpWirelessAdb = { requestWirelessAdbFix(false) },
|
||||
)
|
||||
}
|
||||
}
|
||||
if (showWirelessAdbFix) {
|
||||
Box(Modifier.fillMaxSize().background(colors.background)) {
|
||||
WirelessAdbFixPage(
|
||||
onBack = { showWirelessAdbFix = false },
|
||||
desiredEnabled = wirelessAdbDesiredEnabled,
|
||||
onOpenDeveloperOptions = requestDeveloperOptions,
|
||||
onPair = a.onWirelessAdbPair,
|
||||
onFindConnectPort = a.onFindWirelessAdbPort,
|
||||
onApply = a.onWirelessAdbApply,
|
||||
)
|
||||
}
|
||||
}
|
||||
if (showDeveloperDisplayChoice) {
|
||||
DeveloperDisplayChoiceDialog(
|
||||
displays = s.secondScreenDisplays.map { display ->
|
||||
display.id to if (s.secondScreenDisplays.size == 1) "Bottom screen" else display.label
|
||||
},
|
||||
onMainScreen = {
|
||||
showDeveloperDisplayChoice = false
|
||||
a.onOpenDeveloperOptions(null)
|
||||
},
|
||||
onSecondaryScreen = { displayId ->
|
||||
showDeveloperDisplayChoice = false
|
||||
a.onOpenDeveloperOptions(displayId)
|
||||
},
|
||||
onDismiss = { showDeveloperDisplayChoice = false },
|
||||
)
|
||||
}
|
||||
}
|
||||
BackHandler(enabled = navOpen) { navOpen = false }
|
||||
BackHandler(enabled = navOpen && !processSettingsPageVisible) { navOpen = false }
|
||||
val hasBackTarget = (s.pageKey != null && page != null) ||
|
||||
((s.pageKey == null || page == null) &&
|
||||
(selected.startsWith("app:") || selected.startsWith("emu:") || selected.startsWith("rom:")))
|
||||
BackHandler(enabled = !navOpen && !hasBackTarget) { navOpen = true }
|
||||
BackHandler(enabled = !processSettingsPageVisible && !navOpen && !hasBackTarget) { navOpen = true }
|
||||
}
|
||||
|
||||
|
||||
@Composable
|
||||
private fun LauncherTopBar(menuRequester: FocusRequester, onMenu: () -> Unit) {
|
||||
private fun LauncherTopBar(
|
||||
menuRequester: FocusRequester,
|
||||
buildLabel: String,
|
||||
onCheckLatestBuild: () -> Unit,
|
||||
onMenu: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val palette = LocalPalette.current
|
||||
var menuFocused by remember { mutableStateOf(false) }
|
||||
@@ -502,6 +587,12 @@ private fun LauncherTopBar(menuRequester: FocusRequester, onMenu: () -> Unit) {
|
||||
Image(painterResource(R.drawable.logo), null, modifier = Modifier.size(24.dp))
|
||||
Spacer(Modifier.width(8.dp))
|
||||
Text("DroidDeck", fontSize = 14.sp, fontWeight = FontWeight.SemiBold, color = colors.onBackground)
|
||||
Spacer(Modifier.weight(1f))
|
||||
BuildStatus(
|
||||
label = buildLabel,
|
||||
onCheckLatest = onCheckLatestBuild,
|
||||
modifier = Modifier.widthIn(max = 220.dp).padding(start = 12.dp, end = 8.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -595,11 +686,6 @@ private fun Rail(
|
||||
.padding(horizontal = 10.dp, vertical = 8.dp),
|
||||
)
|
||||
}
|
||||
BuildStatus(
|
||||
label = s.buildLabel,
|
||||
onCheckLatest = a.onCheckLatestBuild,
|
||||
modifier = Modifier.align(Alignment.Start).padding(start = 8.dp, top = 4.dp, bottom = 2.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -691,6 +777,7 @@ private fun NavItem(
|
||||
private fun Pane(
|
||||
s: FrontEndState, selected: String, a: FrontEndActions, page: (@Composable () -> Unit)?, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
|
||||
) {
|
||||
Box(modifier = modifier) {
|
||||
val wash: Pair<File?, Float> = when {
|
||||
@@ -712,7 +799,10 @@ private fun Pane(
|
||||
.apply { targetContentZIndex = 1f }
|
||||
},
|
||||
label = "pane",
|
||||
) { key -> if (page != null && key == s.pageKey) page() else Content(s, key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick) }
|
||||
) { key ->
|
||||
if (page != null && key == s.pageKey) page()
|
||||
else Content(s, key, a, Modifier.fillMaxSize(), onSelect, onAndroidAppClick, onOpenDeveloperOptions, onRequestWirelessAdb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -749,11 +839,11 @@ private fun BuildStatus(label: String, onCheckLatest: () -> Unit, modifier: Modi
|
||||
horizontalArrangement = Arrangement.spacedBy(5.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
Text(branch, modifier = Modifier.weight(1f), fontSize = 9.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = if (hot) colors.onSurfaceVariant else colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (commit.isNotEmpty()) Text("@$commit", fontSize = 8.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1)
|
||||
Text(branch, modifier = Modifier.weight(1f), fontSize = 10.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = if (hot) colors.onSurfaceVariant else colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
if (commit.isNotEmpty()) Text("@$commit", fontSize = 9.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1)
|
||||
Icon(Icons.Filled.Refresh, contentDescription = null, tint = if (hot) pal.signal else colors.onSurfaceVariant.copy(alpha = 0.82f), modifier = Modifier.size(12.dp))
|
||||
}
|
||||
if (context.isNotEmpty()) Text(context, fontSize = 8.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1)
|
||||
if (context.isNotEmpty()) Text(context, fontSize = 9.sp, fontFamily = FontFamily.Monospace, fontWeight = FontWeight.Medium, color = colors.onSurfaceVariant.copy(alpha = 0.82f), maxLines = 1, overflow = TextOverflow.Ellipsis)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -785,6 +875,7 @@ private fun romFor(s: FrontEndState, selected: String): Pair<Library.Emulator, L
|
||||
private fun Content(
|
||||
s: FrontEndState, selected: String, a: FrontEndActions, modifier: Modifier,
|
||||
onSelect: (String) -> Unit, onAndroidAppClick: (HomeApp.LaunchableApp) -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit, onRequestWirelessAdb: (Boolean) -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val detailPosterWidth = if (LocalConfiguration.current.screenHeightDp < 600) 72.dp else 120.dp
|
||||
@@ -868,7 +959,7 @@ private fun Content(
|
||||
ArtGrid(s.emulators.map { e -> Tile(e.name, if (e.installed) (if (e.id == "retroarch") null else "${e.games.size} game${if (e.games.size == 1) "" else "s"}") else "Select to install", null, "emu:${e.id}", e.iconRes, dim = !e.installed) { onSelect("emu:${e.id}") } })
|
||||
}
|
||||
}
|
||||
selected == "setup" -> SetupPanel(s, a)
|
||||
selected == "setup" -> SetupPanel(s, a, onOpenDeveloperOptions, onRequestWirelessAdb)
|
||||
selected.startsWith("emu:") -> {
|
||||
val e = s.emulators.firstOrNull { "emu:${it.id}" == selected }
|
||||
if (e == null) Note("Not installed.") else {
|
||||
@@ -987,8 +1078,28 @@ private fun Content(
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun SetupPanel(s: FrontEndState, a: FrontEndActions) {
|
||||
private fun SetupPanel(
|
||||
s: FrontEndState,
|
||||
a: FrontEndActions,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onRequestWirelessAdb: (Boolean) -> Unit,
|
||||
) {
|
||||
val host = rememberMenuHost()
|
||||
var processLimitBusy by remember { mutableStateOf(false) }
|
||||
var processLimitMessage by remember { mutableStateOf<String?>(null) }
|
||||
val setProcessLimit: (Boolean) -> Unit = { enabled ->
|
||||
processLimitBusy = true
|
||||
processLimitMessage = null
|
||||
a.onSetPhantomProcessLimit(enabled) { error ->
|
||||
processLimitBusy = false
|
||||
if (error == null) {
|
||||
a.onRefreshPhantomStatus()
|
||||
} else {
|
||||
processLimitMessage = "Check the Wireless debugging IP address & Port, or pair again if Android removed this device."
|
||||
onRequestWirelessAdb(enabled)
|
||||
}
|
||||
}
|
||||
}
|
||||
val runtime = when {
|
||||
s.busy -> "Working…"
|
||||
!s.ready -> "Install"
|
||||
@@ -999,6 +1110,34 @@ private fun SetupPanel(s: FrontEndState, a: FrontEndActions) {
|
||||
Column(modifier = Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(bottom = 24.dp)) {
|
||||
Rise(0) { Eyebrow("Setup") }
|
||||
Rise(1) { Title("Setup") }
|
||||
SettingsGroup("Android process limit") {
|
||||
Text(
|
||||
PhantomProcessLimit.title(s.phantomProcessStatus),
|
||||
fontWeight = FontWeight.SemiBold,
|
||||
color = if (PhantomProcessLimit.blocksSteam(s.phantomProcessStatus)) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onBackground,
|
||||
modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp),
|
||||
)
|
||||
Text(
|
||||
"Enabling restores Android’s child-process limit. Disabling it is recommended for Steam sessions.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(horizontal = 14.dp),
|
||||
)
|
||||
if (s.phantomProcessStatus != PhantomProcessStatus.NOT_APPLICABLE) {
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) {
|
||||
SecondaryButton("Enable limit", enabled = !processLimitBusy && s.phantomProcessStatus != PhantomProcessStatus.ENABLED) { setProcessLimit(true) }
|
||||
SecondaryButton("Disable limit", enabled = !processLimitBusy && s.phantomProcessStatus != PhantomProcessStatus.DISABLED) { setProcessLimit(false) }
|
||||
}
|
||||
if (processLimitBusy) LinearProgressIndicator(modifier = Modifier.fillMaxWidth().padding(horizontal = 14.dp, vertical = 8.dp))
|
||||
processLimitMessage?.let { Text(it, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 4.dp)) }
|
||||
}
|
||||
Text(PhantomProcessLimit.instructions(s.phantomProcessStatus), color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 4.dp))
|
||||
Text(PhantomProcessLimit.ADB_COMMAND, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 14.dp, vertical = 4.dp))
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(8.dp), modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)) {
|
||||
SecondaryButton("Developer options", onClick = onOpenDeveloperOptions)
|
||||
SecondaryButton("Check again", onClick = a.onRefreshPhantomStatus)
|
||||
SecondaryButton("Copy ADB", onClick = { a.onCopyPhantomCommand(false) })
|
||||
}
|
||||
}
|
||||
SettingsGroup("Launcher tools") {
|
||||
ActionRow("Files", "Browse and manage files", "Open", a.onFiles)
|
||||
ActionRow("Compatibility tools", "Install ARM64 Proton builds", "Manage", a.onProtons)
|
||||
@@ -1112,7 +1251,13 @@ private fun Chip(t: String, ok: Boolean) {
|
||||
private fun rememberHot(src: MutableInteractionSource): Boolean = src.collectIsFocusedAsState().value || src.collectIsHoveredAsState().value
|
||||
|
||||
@Composable
|
||||
private fun PrimaryButton(text: String, enabled: Boolean = true, main: Boolean = false, onClick: () -> Unit) {
|
||||
internal fun PrimaryButton(
|
||||
text: String,
|
||||
enabled: Boolean = true,
|
||||
main: Boolean = false,
|
||||
compact: Boolean = false,
|
||||
onClick: () -> Unit,
|
||||
) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
// The page's main button is where the pane is entered from the rail.
|
||||
@@ -1139,14 +1284,14 @@ private fun PrimaryButton(text: String, enabled: Boolean = true, main: Boolean =
|
||||
// controller is on it, as the other controls are.
|
||||
.border(2.dp, if (hot) pal.signal else Color.Transparent, Shape12)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 18.dp, vertical = 11.dp),
|
||||
.padding(horizontal = if (compact) 10.dp else 18.dp, vertical = if (compact) 7.dp else 11.dp),
|
||||
) {
|
||||
Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = if (enabled) colors.onPrimary else colors.onSurfaceVariant, maxLines = 1)
|
||||
Text(text, fontSize = if (compact) 12.sp else 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = if (enabled) colors.onPrimary else colors.onSurfaceVariant, maxLines = 1)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
internal fun SecondaryButton(text: String, enabled: Boolean = true, onClick: () -> Unit) {
|
||||
internal fun SecondaryButton(text: String, enabled: Boolean = true, compact: Boolean = false, onClick: () -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val src = remember { MutableInteractionSource() }
|
||||
val hot = rememberHot(src) && enabled
|
||||
@@ -1160,8 +1305,8 @@ internal fun SecondaryButton(text: String, enabled: Boolean = true, onClick: ()
|
||||
.alpha(if (enabled) 1f else 0.5f)
|
||||
.hoverable(src).clickable(interactionSource = src, indication = LocalIndication.current, enabled = enabled, onClick = onClick)
|
||||
.controllerConfirm(enabled = enabled, onClick = onClick)
|
||||
.padding(horizontal = 16.dp, vertical = 11.dp),
|
||||
) { Text(text, fontSize = 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) }
|
||||
.padding(horizontal = if (compact) 10.dp else 16.dp, vertical = if (compact) 7.dp else 11.dp),
|
||||
) { Text(text, fontSize = if (compact) 12.sp else 15.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 0.5.sp, color = colors.onBackground, maxLines = 1) }
|
||||
}
|
||||
|
||||
@Composable
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.material3.AlertDialog
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.material3.TextButton
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.unit.sp
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.PhantomProcessStatus
|
||||
|
||||
@Composable
|
||||
fun PhantomProcessGatePage(
|
||||
status: PhantomProcessStatus,
|
||||
onDismiss: () -> Unit,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onSetUpWirelessAdb: () -> Unit,
|
||||
) {
|
||||
BackHandler(onBack = onDismiss)
|
||||
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val compact = maxWidth < 620.dp && maxHeight < 500.dp
|
||||
SettingsPage(
|
||||
host = rememberMenuHost(),
|
||||
title = if (compact) "Steam paused" else "Steam cannot start yet",
|
||||
eyebrow = "Steam",
|
||||
lede = if (compact) compactStatus(status) else "${PhantomProcessLimit.title(status)} · checking again every two seconds",
|
||||
onBack = onDismiss,
|
||||
scrollContent = false,
|
||||
compactLayout = compact,
|
||||
) {
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val wide = maxWidth >= 620.dp
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
when {
|
||||
compact -> CompactGateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
|
||||
wide -> Row(horizontalArrangement = Arrangement.spacedBy(14.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Column(Modifier.weight(1f)) {
|
||||
GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
|
||||
}
|
||||
Column(Modifier.weight(1f)) { AdbFallback() }
|
||||
}
|
||||
else -> {
|
||||
GateInstructions(status, onOpenDeveloperOptions, onSetUpWirelessAdb)
|
||||
AdbFallback()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun compactStatus(status: PhantomProcessStatus): String {
|
||||
val state = when (status) {
|
||||
PhantomProcessStatus.ENABLED -> "Child-process limit is on"
|
||||
PhantomProcessStatus.UNSET -> "Child-process limit is unset"
|
||||
PhantomProcessStatus.UNREADABLE -> "Child-process limit is unreadable"
|
||||
else -> PhantomProcessLimit.title(status)
|
||||
}
|
||||
return "$state · retrying every 2 sec"
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CompactGateInstructions(
|
||||
status: PhantomProcessStatus,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onSetUpWirelessAdb: () -> Unit,
|
||||
) {
|
||||
SettingsGroup("1 · Developer options", compact = true) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 7.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(5.dp),
|
||||
) {
|
||||
Text(
|
||||
PhantomProcessLimit.gateInstructions(status),
|
||||
style = MaterialTheme.typography.bodySmall.copy(fontSize = 12.sp),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
|
||||
PrimaryButton("Open Developer options", compact = true, onClick = onOpenDeveloperOptions)
|
||||
SecondaryButton("Use on-device ADB", compact = true, onClick = onSetUpWirelessAdb)
|
||||
}
|
||||
}
|
||||
}
|
||||
SettingsGroup("3 · Computer ADB last resort", compact = true) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp, vertical = 6.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(3.dp),
|
||||
) {
|
||||
Text(
|
||||
"If the setting is missing and Wireless debugging is unavailable, run this from a computer:",
|
||||
style = MaterialTheme.typography.bodySmall.copy(fontSize = 11.sp),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
Text(
|
||||
PhantomProcessLimit.ADB_COMMAND,
|
||||
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace, fontSize = 9.sp),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun GateInstructions(
|
||||
status: PhantomProcessStatus,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onSetUpWirelessAdb: () -> Unit,
|
||||
) {
|
||||
SettingsGroup("1 · Developer options first") {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
PhantomProcessLimit.gateInstructions(status),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
PrimaryButton("Open Developer options", onClick = onOpenDeveloperOptions)
|
||||
SecondaryButton("Use on-device ADB", onClick = onSetUpWirelessAdb)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AdbFallback() {
|
||||
SettingsGroup("3 · Computer ADB last resort") {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(14.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(8.dp),
|
||||
) {
|
||||
Text(
|
||||
"Use this only if Developer options has no setting and Wireless debugging is unavailable. Connect this device to a computer with ADB and run:",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
)
|
||||
Text(
|
||||
PhantomProcessLimit.ADB_COMMAND,
|
||||
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun DeveloperDisplayChoiceDialog(
|
||||
displays: List<Pair<Int, String>>,
|
||||
onMainScreen: () -> Unit,
|
||||
onSecondaryScreen: (Int) -> Unit,
|
||||
onDismiss: () -> Unit,
|
||||
) {
|
||||
AlertDialog(
|
||||
onDismissRequest = onDismiss,
|
||||
title = { Text("Open Developer options") },
|
||||
text = {
|
||||
Column(verticalArrangement = Arrangement.spacedBy(4.dp), modifier = Modifier.fillMaxWidth()) {
|
||||
Text("Choose which display to open Android Settings on.")
|
||||
TextButton(modifier = Modifier.fillMaxWidth(), onClick = onMainScreen) { Text("Main screen") }
|
||||
displays.forEach { (id, label) ->
|
||||
TextButton(modifier = Modifier.fillMaxWidth(), onClick = { onSecondaryScreen(id) }) { Text(label) }
|
||||
}
|
||||
}
|
||||
},
|
||||
confirmButton = { TextButton(onClick = onDismiss) { Text("Cancel") } },
|
||||
)
|
||||
}
|
||||
@@ -235,10 +235,14 @@ fun ValueChip(text: String, open: Boolean, enabled: Boolean = true, modifier: Mo
|
||||
}
|
||||
|
||||
@Composable
|
||||
fun SettingsGroup(title: String, content: @Composable ColumnScope.() -> Unit) {
|
||||
fun SettingsGroup(title: String, compact: Boolean = false, content: @Composable ColumnScope.() -> Unit) {
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val pal = LocalPalette.current
|
||||
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp), modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 6.dp)) {
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(if (compact) 6.dp else 10.dp),
|
||||
modifier = Modifier.fillMaxWidth().padding(top = if (compact) 4.dp else 16.dp, bottom = if (compact) 3.dp else 6.dp),
|
||||
) {
|
||||
Text(title.uppercase(), fontSize = 11.sp, fontWeight = FontWeight.SemiBold, letterSpacing = 2.sp, color = colors.onSurfaceVariant)
|
||||
Box(modifier = Modifier.weight(1f).height(1.dp).background(pal.line))
|
||||
}
|
||||
@@ -332,24 +336,32 @@ fun SettingsPage(
|
||||
action: (@Composable () -> Unit)? = null,
|
||||
/** Pass one held above the page to keep its scroll position across a page opened over it. */
|
||||
scroll: androidx.compose.foundation.ScrollState? = null,
|
||||
scrollContent: Boolean = true,
|
||||
compactLayout: Boolean = false,
|
||||
content: @Composable ColumnScope.() -> Unit,
|
||||
) {
|
||||
val scrollState = scroll ?: rememberScrollState()
|
||||
val colors = MaterialTheme.colorScheme
|
||||
val dim by animateFloatAsState(if (host.open != null) 0.6f else 1f, Motion.tw(220), label = "pageDim")
|
||||
Column(modifier = Modifier.fillMaxSize().padding(horizontal = 22.dp, vertical = 18.dp)) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxSize().padding(
|
||||
horizontal = if (compactLayout) 14.dp else 22.dp,
|
||||
vertical = if (compactLayout) 6.dp else 18.dp,
|
||||
),
|
||||
verticalArrangement = Arrangement.spacedBy(if (compactLayout) 2.dp else 0.dp),
|
||||
) {
|
||||
Rise(0) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
// Outlined when a controller's focus is on it, like every other control here.
|
||||
val backSrc = remember { MutableInteractionSource() }
|
||||
val backHot = backSrc.collectIsFocusedAsState().value || backSrc.collectIsHoveredAsState().value
|
||||
Text(
|
||||
"‹ Back", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
"‹ Back", fontSize = if (compactLayout) 11.sp else 12.sp, fontWeight = FontWeight.SemiBold,
|
||||
color = if (backHot) LocalPalette.current.signal else colors.onSurfaceVariant,
|
||||
modifier = Modifier.clip(RoundedCornerShape(8.dp))
|
||||
.border(2.dp, if (backHot) LocalPalette.current.signal else Color.Transparent, RoundedCornerShape(8.dp))
|
||||
.hoverable(backSrc).clickable(interactionSource = backSrc, indication = null, onClick = onBack)
|
||||
.padding(horizontal = 6.dp, vertical = 4.dp),
|
||||
.padding(horizontal = 6.dp, vertical = if (compactLayout) 2.dp else 4.dp),
|
||||
)
|
||||
if (eyebrow != null) {
|
||||
Spacer(Modifier.width(10.dp))
|
||||
@@ -359,13 +371,44 @@ fun SettingsPage(
|
||||
}
|
||||
Rise(1) {
|
||||
Row(verticalAlignment = Alignment.CenterVertically) {
|
||||
Box(Modifier.weight(1f)) { Title(title) }
|
||||
Box(Modifier.weight(1f)) {
|
||||
if (compactLayout) {
|
||||
Text(
|
||||
title,
|
||||
fontSize = 20.sp,
|
||||
fontWeight = FontWeight.Bold,
|
||||
color = colors.onBackground,
|
||||
modifier = Modifier.padding(vertical = 2.dp),
|
||||
)
|
||||
} else {
|
||||
Title(title)
|
||||
}
|
||||
}
|
||||
if (action != null) action()
|
||||
}
|
||||
}
|
||||
if (lede != null) Rise(2) { Lede(lede) }
|
||||
if (lede != null) Rise(2) {
|
||||
if (compactLayout) {
|
||||
Text(
|
||||
lede,
|
||||
fontSize = 11.sp,
|
||||
color = colors.onSurfaceVariant,
|
||||
modifier = Modifier.padding(bottom = 3.dp),
|
||||
maxLines = 1,
|
||||
overflow = TextOverflow.Ellipsis,
|
||||
)
|
||||
} else {
|
||||
Lede(lede)
|
||||
}
|
||||
}
|
||||
Rise(3, Modifier.weight(1f).fillMaxWidth()) {
|
||||
Column(modifier = Modifier.fillMaxSize().graphicsLayer { alpha = dim }.verticalScroll(scrollState).padding(bottom = 24.dp)) { content() }
|
||||
Column(
|
||||
modifier = Modifier
|
||||
.fillMaxSize()
|
||||
.graphicsLayer { alpha = dim }
|
||||
.then(if (scrollContent) Modifier.verticalScroll(scrollState) else Modifier)
|
||||
.padding(bottom = if (compactLayout) 0.dp else 24.dp),
|
||||
) { content() }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
package com.droiddeck.launcher.ui
|
||||
|
||||
import android.text.Editable
|
||||
import android.text.InputType
|
||||
import android.text.TextWatcher
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.EditText
|
||||
import androidx.activity.compose.BackHandler
|
||||
import androidx.compose.foundation.background
|
||||
import androidx.compose.foundation.border
|
||||
import androidx.compose.foundation.layout.Arrangement
|
||||
import androidx.compose.foundation.layout.Box
|
||||
import androidx.compose.foundation.layout.BoxWithConstraints
|
||||
import androidx.compose.foundation.layout.Column
|
||||
import androidx.compose.foundation.layout.Row
|
||||
import androidx.compose.foundation.layout.fillMaxSize
|
||||
import androidx.compose.foundation.layout.fillMaxWidth
|
||||
import androidx.compose.foundation.layout.height
|
||||
import androidx.compose.foundation.layout.padding
|
||||
import androidx.compose.foundation.layout.size
|
||||
import androidx.compose.foundation.layout.widthIn
|
||||
import androidx.compose.foundation.shape.RoundedCornerShape
|
||||
import androidx.compose.material3.CircularProgressIndicator
|
||||
import androidx.compose.material3.MaterialTheme
|
||||
import androidx.compose.material3.Text
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.runtime.getValue
|
||||
import androidx.compose.runtime.mutableStateOf
|
||||
import androidx.compose.runtime.remember
|
||||
import androidx.compose.runtime.rememberUpdatedState
|
||||
import androidx.compose.runtime.saveable.rememberSaveable
|
||||
import androidx.compose.runtime.setValue
|
||||
import androidx.compose.ui.Alignment
|
||||
import androidx.compose.ui.Modifier
|
||||
import androidx.compose.ui.focus.FocusDirection
|
||||
import androidx.compose.ui.focus.FocusManager
|
||||
import androidx.compose.ui.graphics.toArgb
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalFocusManager
|
||||
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
|
||||
import androidx.compose.ui.text.font.FontFamily
|
||||
import androidx.compose.ui.text.font.FontWeight
|
||||
import androidx.compose.ui.text.input.ImeAction
|
||||
import androidx.compose.ui.text.input.KeyboardType
|
||||
import androidx.compose.ui.unit.dp
|
||||
import androidx.compose.ui.viewinterop.AndroidView
|
||||
import com.droiddeck.launcher.core.PhantomProcessLimit
|
||||
import com.droiddeck.launcher.core.WirelessAdbFix
|
||||
import kotlin.math.min
|
||||
import kotlin.math.roundToInt
|
||||
|
||||
@Composable
|
||||
fun WirelessAdbFixPage(
|
||||
onBack: () -> Unit,
|
||||
desiredEnabled: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
onPair: (String, Int, String, (String?) -> Unit) -> Unit,
|
||||
onFindConnectPort: (String, (Int?) -> Unit) -> Unit,
|
||||
onApply: (String, Int, Boolean, (String?) -> Unit) -> Unit,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val savedAddress = remember { WirelessAdbFix.savedConnectionAddress(context) }
|
||||
var step by rememberSaveable { mutableStateOf(if (savedAddress == null) 0 else 1) }
|
||||
var pairingAddress by rememberSaveable { mutableStateOf("") }
|
||||
var connectionAddress by rememberSaveable { mutableStateOf(savedAddress.orEmpty()) }
|
||||
var pairingCode by rememberSaveable { mutableStateOf("") }
|
||||
var busy by remember { mutableStateOf(false) }
|
||||
var editing by remember { mutableStateOf(false) }
|
||||
var message by remember { mutableStateOf<String?>(null) }
|
||||
var messageIsError by remember { mutableStateOf(false) }
|
||||
val focusManager = LocalFocusManager.current
|
||||
val keyboardController = LocalSoftwareKeyboardController.current
|
||||
val pairingEndpoint = parseAdbAddress(pairingAddress)
|
||||
|
||||
val pairNow: () -> Unit = {
|
||||
parseAdbAddress(pairingAddress)?.let { endpoint ->
|
||||
keyboardController?.hide()
|
||||
focusManager.clearFocus()
|
||||
busy = true
|
||||
editing = false
|
||||
message = null
|
||||
messageIsError = false
|
||||
onPair(endpoint.host, endpoint.port, pairingCode) { error ->
|
||||
pairingCode = ""
|
||||
if (error != null) {
|
||||
busy = false
|
||||
message = error
|
||||
messageIsError = true
|
||||
} else {
|
||||
step = 1
|
||||
busy = true
|
||||
message = "Paired. Finding the Wireless debugging port…"
|
||||
onFindConnectPort(endpoint.host) { discoveredPort ->
|
||||
if (discoveredPort == null) {
|
||||
connectionAddress = formatAddressHost(endpoint.host) + ":"
|
||||
busy = false
|
||||
message = "Paired. Enter the port from Settings."
|
||||
} else {
|
||||
connectionAddress = formatAdbAddress(endpoint.host, discoveredPort)
|
||||
message = "Device found. Applying the setting…"
|
||||
onApply(endpoint.host, discoveredPort, desiredEnabled) { applyError ->
|
||||
busy = false
|
||||
if (applyError == null) {
|
||||
step = 2
|
||||
message = null
|
||||
} else {
|
||||
message = "Could not apply automatically. Check the address below and retry. $applyError"
|
||||
messageIsError = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val applyAddress: () -> Unit = {
|
||||
parseAdbAddress(connectionAddress)?.let { endpoint ->
|
||||
keyboardController?.hide()
|
||||
focusManager.clearFocus()
|
||||
busy = true
|
||||
editing = false
|
||||
message = null
|
||||
messageIsError = false
|
||||
onApply(endpoint.host, endpoint.port, desiredEnabled) { error ->
|
||||
busy = false
|
||||
if (error == null) {
|
||||
step = 2
|
||||
message = null
|
||||
} else {
|
||||
message = error
|
||||
messageIsError = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
val pairAgain: () -> Unit = {
|
||||
step = 0
|
||||
pairingAddress = ""
|
||||
pairingCode = ""
|
||||
message = null
|
||||
messageIsError = false
|
||||
}
|
||||
|
||||
BackHandler { if (!busy) onBack() }
|
||||
|
||||
BoxWithConstraints(Modifier.fillMaxSize()) {
|
||||
val compactSplit = maxWidth < 620.dp && maxHeight < 500.dp
|
||||
val form: @Composable () -> Unit = {
|
||||
WirelessStepForm(
|
||||
step = step,
|
||||
pairingAddress = pairingAddress,
|
||||
onPairingAddressChange = { pairingAddress = it },
|
||||
pairingCode = pairingCode,
|
||||
onPairingCodeChange = { pairingCode = it.filter(Char::isDigit).take(6) },
|
||||
connectionAddress = connectionAddress,
|
||||
onConnectionAddressChange = { connectionAddress = it },
|
||||
busy = busy,
|
||||
message = message,
|
||||
messageIsError = messageIsError,
|
||||
compact = compactSplit,
|
||||
editing = editing,
|
||||
onEditingChanged = { editing = it },
|
||||
focusManager = focusManager,
|
||||
desiredEnabled = desiredEnabled,
|
||||
canPair = pairingEndpoint != null && pairingCode.length == 6,
|
||||
onPair = pairNow,
|
||||
onApply = applyAddress,
|
||||
onPairAgain = pairAgain,
|
||||
)
|
||||
}
|
||||
SettingsPage(
|
||||
host = rememberMenuHost(),
|
||||
title = when {
|
||||
compactSplit && step < 2 -> "Wireless ADB"
|
||||
step == 2 -> "Wireless ADB ready"
|
||||
else -> "Set up on-device ADB"
|
||||
},
|
||||
eyebrow = "Setup",
|
||||
lede = when {
|
||||
compactSplit && step == 0 -> "If the option is missing, pair over Wireless debugging."
|
||||
compactSplit && step == 1 -> "Paired. Check IP address & Port in Wireless debugging."
|
||||
compactSplit -> "The child-process limit was updated."
|
||||
step == 0 -> "Use step 2 if Developer options has no child-process setting. In Android Settings, open Developer options → Wireless debugging → Pair device with pairing code."
|
||||
step == 1 -> "Paired. Use the address below; update it from Wireless debugging → IP address & Port if needed."
|
||||
else -> "The child-process limit was updated over Wireless debugging."
|
||||
},
|
||||
onBack = { if (!busy) onBack() },
|
||||
action = if (compactSplit && step < 2) {
|
||||
{ SecondaryButton("Developer options", compact = true, enabled = !busy, onClick = onOpenDeveloperOptions) }
|
||||
} else null,
|
||||
scrollContent = !compactSplit,
|
||||
compactLayout = compactSplit,
|
||||
) {
|
||||
BoxWithConstraints(Modifier.fillMaxWidth()) {
|
||||
val wide = maxWidth >= 620.dp
|
||||
if (step == 2) {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 680.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(10.dp),
|
||||
) {
|
||||
SettingsGroup("Child-process limit", compact = compactSplit) {
|
||||
Text(
|
||||
"Android confirmed the limit is ${if (desiredEnabled) "enabled" else "disabled"}.",
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.padding(14.dp),
|
||||
)
|
||||
}
|
||||
PrimaryButton("Done", enabled = !busy, onClick = onBack)
|
||||
}
|
||||
} else if (compactSplit) {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
form()
|
||||
if (!editing) CompactComputerFallback(desiredEnabled)
|
||||
}
|
||||
} else {
|
||||
val routes: @Composable () -> Unit = {
|
||||
FallbackOrder(desiredEnabled, busy, onOpenDeveloperOptions)
|
||||
}
|
||||
if (wide) {
|
||||
Row(
|
||||
modifier = Modifier.widthIn(max = 900.dp).fillMaxWidth(),
|
||||
horizontalArrangement = Arrangement.spacedBy(14.dp),
|
||||
verticalAlignment = Alignment.Top,
|
||||
) {
|
||||
Column(Modifier.weight(1f)) { routes() }
|
||||
Column(Modifier.weight(1f)) { form() }
|
||||
}
|
||||
} else {
|
||||
Column(
|
||||
modifier = Modifier.widthIn(max = 600.dp).fillMaxWidth(),
|
||||
verticalArrangement = Arrangement.spacedBy(2.dp),
|
||||
) {
|
||||
routes()
|
||||
form()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun WirelessStepForm(
|
||||
step: Int,
|
||||
pairingAddress: String,
|
||||
onPairingAddressChange: (String) -> Unit,
|
||||
pairingCode: String,
|
||||
onPairingCodeChange: (String) -> Unit,
|
||||
connectionAddress: String,
|
||||
onConnectionAddressChange: (String) -> Unit,
|
||||
busy: Boolean,
|
||||
message: String?,
|
||||
messageIsError: Boolean,
|
||||
compact: Boolean,
|
||||
editing: Boolean,
|
||||
onEditingChanged: (Boolean) -> Unit,
|
||||
focusManager: FocusManager,
|
||||
desiredEnabled: Boolean,
|
||||
canPair: Boolean,
|
||||
onPair: () -> Unit,
|
||||
onApply: () -> Unit,
|
||||
onPairAgain: () -> Unit,
|
||||
) {
|
||||
if (step == 0) {
|
||||
SettingsGroup("2 · Pair Wireless debugging", compact = compact) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
|
||||
) {
|
||||
AdbTextField(
|
||||
value = pairingAddress,
|
||||
onValueChange = onPairingAddressChange,
|
||||
label = "Pairing pop-up IP address & Port",
|
||||
placeholder = "192.168.1.42:37123",
|
||||
keyboardType = KeyboardType.Ascii,
|
||||
imeAction = ImeAction.Next,
|
||||
compact = compact,
|
||||
onFocusChange = onEditingChanged,
|
||||
onNext = { focusManager.moveFocus(FocusDirection.Next) },
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.Bottom,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
AdbTextField(
|
||||
value = pairingCode,
|
||||
onValueChange = onPairingCodeChange,
|
||||
label = "Pairing code (PIN)",
|
||||
placeholder = "6 digits",
|
||||
keyboardType = KeyboardType.Number,
|
||||
imeAction = ImeAction.Done,
|
||||
compact = compact,
|
||||
onFocusChange = onEditingChanged,
|
||||
onDone = {
|
||||
focusManager.clearFocus()
|
||||
},
|
||||
modifier = Modifier.weight(1f),
|
||||
)
|
||||
PrimaryButton("Pair", compact = compact, enabled = !busy && canPair, onClick = onPair)
|
||||
}
|
||||
StatusMessage(busy, message, isError = messageIsError)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
SettingsGroup("2 · Apply over Wireless debugging", compact = compact) {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = if (compact) 8.dp else 12.dp, vertical = if (compact) 6.dp else 12.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(if (compact) 5.dp else 6.dp),
|
||||
) {
|
||||
AdbTextField(
|
||||
value = connectionAddress,
|
||||
onValueChange = onConnectionAddressChange,
|
||||
label = "Connection IP address & Port",
|
||||
placeholder = "192.168.1.42:45678",
|
||||
keyboardType = KeyboardType.Ascii,
|
||||
imeAction = ImeAction.Done,
|
||||
compact = compact,
|
||||
onFocusChange = onEditingChanged,
|
||||
onDone = { focusManager.clearFocus() },
|
||||
)
|
||||
Row(
|
||||
verticalAlignment = Alignment.CenterVertically,
|
||||
horizontalArrangement = Arrangement.spacedBy(8.dp),
|
||||
modifier = Modifier.fillMaxWidth(),
|
||||
) {
|
||||
StatusMessage(busy, message, Modifier.weight(1f), isError = messageIsError)
|
||||
SecondaryButton("Pair again", compact = compact, enabled = !busy, onClick = onPairAgain)
|
||||
PrimaryButton(
|
||||
if (desiredEnabled) "Enable limit" else "Disable limit",
|
||||
compact = compact,
|
||||
enabled = !busy && parseAdbAddress(connectionAddress) != null,
|
||||
onClick = onApply,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun AdbTextField(
|
||||
value: String,
|
||||
onValueChange: (String) -> Unit,
|
||||
label: String,
|
||||
keyboardType: KeyboardType,
|
||||
imeAction: ImeAction,
|
||||
modifier: Modifier = Modifier,
|
||||
placeholder: String? = null,
|
||||
compact: Boolean = false,
|
||||
onFocusChange: (Boolean) -> Unit = {},
|
||||
onNext: (() -> Unit)? = null,
|
||||
onDone: (() -> Unit)? = null,
|
||||
) {
|
||||
val context = LocalContext.current
|
||||
val palette = LocalPalette.current
|
||||
val onValueChangeLatest = rememberUpdatedState(onValueChange)
|
||||
val onNextLatest = rememberUpdatedState(onNext)
|
||||
val onDoneLatest = rememberUpdatedState(onDone)
|
||||
val onFocusChangeLatest = rememberUpdatedState(onFocusChange)
|
||||
var focused by remember { mutableStateOf(false) }
|
||||
val shape = RoundedCornerShape(8.dp)
|
||||
val inputHeight = if (compact) 44.dp else 52.dp
|
||||
val colors = MaterialTheme.colorScheme
|
||||
|
||||
Column(modifier = modifier.fillMaxWidth()) {
|
||||
Text(
|
||||
label,
|
||||
style = MaterialTheme.typography.labelSmall,
|
||||
fontWeight = FontWeight.Medium,
|
||||
color = colors.onSurfaceVariant,
|
||||
maxLines = 1,
|
||||
)
|
||||
Box(
|
||||
modifier = Modifier
|
||||
.fillMaxWidth()
|
||||
.height(inputHeight)
|
||||
.background(colors.surfaceVariant, shape)
|
||||
.border(1.dp, if (focused) palette.signal else palette.line2, shape)
|
||||
.padding(horizontal = 10.dp),
|
||||
contentAlignment = Alignment.CenterStart,
|
||||
) {
|
||||
AndroidView(
|
||||
modifier = Modifier.fillMaxSize(),
|
||||
factory = { viewContext ->
|
||||
EditText(viewContext).apply {
|
||||
isSingleLine = true
|
||||
setHorizontallyScrolling(true)
|
||||
background = null
|
||||
setPadding((2 * context.resources.displayMetrics.density).roundToInt(), 0, 0, 0)
|
||||
setTextSize(android.util.TypedValue.COMPLEX_UNIT_SP, if (compact) 13f else 14f)
|
||||
setTextColor(colors.onBackground.toArgb())
|
||||
setHintTextColor(colors.onSurfaceVariant.toArgb())
|
||||
contentDescription = label
|
||||
inputType = if (keyboardType == KeyboardType.Number) {
|
||||
InputType.TYPE_CLASS_NUMBER
|
||||
} else {
|
||||
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_URI or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
|
||||
}
|
||||
imeOptions = imeActionFlag(imeAction) or EditorInfo.IME_FLAG_NO_FULLSCREEN or EditorInfo.IME_FLAG_NO_EXTRACT_UI
|
||||
hint = placeholder
|
||||
setOnEditorActionListener { _, actionId, event ->
|
||||
val isEnter = event?.keyCode == android.view.KeyEvent.KEYCODE_ENTER
|
||||
when {
|
||||
imeAction == ImeAction.Next && (actionId == EditorInfo.IME_ACTION_NEXT || isEnter) -> {
|
||||
onNextLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
imeAction == ImeAction.Done && (actionId == EditorInfo.IME_ACTION_DONE || isEnter) -> {
|
||||
onDoneLatest.value?.invoke()
|
||||
true
|
||||
}
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
setOnFocusChangeListener { _, hasFocus ->
|
||||
focused = hasFocus
|
||||
onFocusChangeLatest.value(hasFocus)
|
||||
}
|
||||
addTextChangedListener(object : TextWatcher {
|
||||
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = Unit
|
||||
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) = Unit
|
||||
override fun afterTextChanged(s: Editable?) {
|
||||
onValueChangeLatest.value(s?.toString().orEmpty())
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
update = { editText ->
|
||||
editText.setTextColor(colors.onBackground.toArgb())
|
||||
editText.setHintTextColor(colors.onSurfaceVariant.toArgb())
|
||||
editText.hint = placeholder
|
||||
editText.contentDescription = label
|
||||
if (editText.text.toString() != value) {
|
||||
val cursor = if (editText.hasFocus()) editText.selectionStart.coerceAtLeast(0) else value.length
|
||||
editText.setText(value)
|
||||
editText.setSelection(min(cursor, value.length))
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun FallbackOrder(
|
||||
desiredEnabled: Boolean,
|
||||
busy: Boolean,
|
||||
onOpenDeveloperOptions: () -> Unit,
|
||||
) {
|
||||
SettingsGroup("Other ways to change it") {
|
||||
Column(
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 8.dp),
|
||||
verticalArrangement = Arrangement.spacedBy(4.dp),
|
||||
) {
|
||||
Text("1 · Developer options (try first)", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text("Set “Restrict child processes” ${if (desiredEnabled) "on" else "off"}.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
SecondaryButton("Open Developer options", enabled = !busy, onClick = onOpenDeveloperOptions)
|
||||
Text("3 · Computer ADB (last resort)", style = MaterialTheme.typography.bodySmall, fontWeight = FontWeight.SemiBold, color = MaterialTheme.colorScheme.onBackground)
|
||||
Text("Only if Wireless debugging is unavailable.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
|
||||
Text(
|
||||
PhantomProcessLimit.adbCommand(desiredEnabled),
|
||||
style = MaterialTheme.typography.bodySmall.copy(fontFamily = FontFamily.Monospace),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun CompactComputerFallback(desiredEnabled: Boolean) {
|
||||
SettingsGroup("3 · Computer ADB last resort", compact = true) {
|
||||
Text(
|
||||
PhantomProcessLimit.adbCommand(desiredEnabled),
|
||||
style = MaterialTheme.typography.labelSmall.copy(fontFamily = FontFamily.Monospace),
|
||||
color = MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 10.dp, vertical = 4.dp),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@Composable
|
||||
private fun StatusMessage(busy: Boolean, message: String?, modifier: Modifier = Modifier, isError: Boolean = false) {
|
||||
if (busy) {
|
||||
Row(modifier = modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
|
||||
CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp)
|
||||
Text(message ?: "Working…", style = MaterialTheme.typography.bodySmall)
|
||||
}
|
||||
} else {
|
||||
message?.let {
|
||||
Text(
|
||||
it,
|
||||
modifier = modifier,
|
||||
style = MaterialTheme.typography.bodySmall,
|
||||
color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private data class AdbEndpoint(val host: String, val port: Int)
|
||||
|
||||
private fun parseAdbAddress(value: String): AdbEndpoint? {
|
||||
val address = value.trim()
|
||||
val host: String
|
||||
val portText: String
|
||||
if (address.startsWith("[")) {
|
||||
val closingBracket = address.indexOf(']')
|
||||
if (closingBracket <= 1 || address.getOrNull(closingBracket + 1) != ':') return null
|
||||
host = address.substring(1, closingBracket)
|
||||
if (':' !in host) return null
|
||||
portText = address.substring(closingBracket + 2)
|
||||
} else {
|
||||
val colon = address.lastIndexOf(':')
|
||||
if (colon <= 0 || address.indexOf(':') != colon) return null
|
||||
host = address.substring(0, colon)
|
||||
portText = address.substring(colon + 1)
|
||||
}
|
||||
if (host.isBlank() || host.any(Char::isWhitespace)) return null
|
||||
val port = portText.toIntOrNull()?.takeIf { it in 1..65535 } ?: return null
|
||||
return AdbEndpoint(host, port)
|
||||
}
|
||||
|
||||
private fun formatAddressHost(host: String): String = if (':' in host) "[$host]" else host
|
||||
private fun formatAdbAddress(host: String, port: Int): String = "${formatAddressHost(host)}:$port"
|
||||
|
||||
private fun imeActionFlag(action: ImeAction): Int = when (action) {
|
||||
ImeAction.Next -> EditorInfo.IME_ACTION_NEXT
|
||||
ImeAction.Done -> EditorInfo.IME_ACTION_DONE
|
||||
ImeAction.Go -> EditorInfo.IME_ACTION_GO
|
||||
ImeAction.Search -> EditorInfo.IME_ACTION_SEARCH
|
||||
else -> EditorInfo.IME_ACTION_UNSPECIFIED
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
# DroidDeck boot animation
|
||||
|
||||
This source accompanies the single Steam startup movie bundled by the app:
|
||||
`app/src/main/assets/steam-startup/droiddeck-startup.webm` (1920×1080, dark theme, VP9 video
|
||||
with Opus audio). `droiddeck-boot.html` is the editable animation; the scripts and WAV below
|
||||
reproduce the selected render. No alternate MP4 or WebM exports are kept in the repository.
|
||||
|
||||
From the repository root, render the movie with:
|
||||
|
||||
python3 artwork/boot-animation-source/render.py 1920 1080 60 app/src/main/assets/steam-startup/droiddeck-startup.webm dark
|
||||
|
||||
The app stages that file into Steam's `config/uioverrides/movies` folder before each session. If
|
||||
Steam still has its built-in startup movie selected, DroidDeck sets this movie as the device's
|
||||
startup default before Steam starts. A custom startup movie the user selected later is preserved.
|
||||
|
||||
To regenerate the soundtrack, run these commands from this directory:
|
||||
|
||||
python3 events.py
|
||||
python3 sound.py
|
||||
|
||||
The animation and audio are both procedurally generated; the included WAV is the soundtrack used
|
||||
for the bundled render.
|
||||
|
||||
`droiddeck-boot.html` holds the whole animation. Every frame is a pure function of time, so the
|
||||
preview page and the video render draw exactly the same thing. Open it in a browser to scrub, slow
|
||||
it down or step frame by frame (arrow keys).
|
||||
|
||||
## Re-render the video
|
||||
|
||||
pip install playwright && playwright install chromium # ffmpeg with libvpx-vp9 also required
|
||||
python3 render.py 1280 800 60 droiddeck-boot-1280x800.webm
|
||||
python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.webm
|
||||
python3 render.py 1920 1080 60 droiddeck-boot-1920x1080.mp4 # .mp4 = H.264 for sharing
|
||||
python3 render.py 1280 800 60 droiddeck-boot-dark-1280x800.webm dark # dark version
|
||||
|
||||
Each frame gets real motion blur (180° shutter, adaptive sub-frames). Output is VP9 for .webm or H.264 for .mp4, both BT.709,
|
||||
so the orb stays #1A9FFF after compression.
|
||||
|
||||
## Sound
|
||||
|
||||
Every sound is synthesized in `sound.py` (no samples) and placed on the exact physics events the
|
||||
animation reports, so hits stay frame-accurate even after you change the timing. Key: D major.
|
||||
|
||||
python3 events.py # export impact times, rocking, piece speeds from the animation
|
||||
python3 sound.py # -> droiddeck-boot-sound.wav (-18 LUFS, -1 dBFS peak)
|
||||
python3 embed_sound.py # put it in the preview page
|
||||
python3 render.py ... # muxes the wav in automatically (Opus in .webm, AAC in .mp4)
|
||||
|
||||
The soundtrack is built from the final chord. Each piece lands on one of its notes as a soft, muted
|
||||
tone (legs D, ball A with a quieter echo, bowl F#), the wobble and jump play in silence, and the
|
||||
lock lands with the same soft voice and plays all the notes together. Tweak the cue sheet in `sound.py`: the `tock(...)` calls under
|
||||
`# 1. the stack`, the chord list under `# 4. lock`, and the room reverb mix (`.14 * wet`).
|
||||
|
||||
## Where to tweak
|
||||
|
||||
- Timing of the drops: `archDrop`, `ballDrop`, `domeDrop` (start time, height, bounciness `e`).
|
||||
- The balancing act: `SWAY` keyframes (time, lean). Bigger values = bigger wobble. The bowl leads,
|
||||
the ball chases it (`sway(t - .12)`), the legs follow (`sway(t - .10)`).
|
||||
- The catch-hop on the big wobble: `HOP` (start time, duration, sideways distance, height).
|
||||
- Crouch before the jump: `crouchA/B/D`.
|
||||
- Jump and lock-in: `FL` (rise time, apex height, lock time, how far pieces spread).
|
||||
- Colors for each version (pieces, background, shadows, lock glow): `THEMES` (light, dark).
|
||||
- Total length: `DUR`.
|
||||
|
||||
## Install as the Steam startup movie
|
||||
|
||||
Put the .webm in `~/.steam/root/config/uioverrides/movies/`, then pick it in
|
||||
Steam > Settings > Customization > Startup Movie.
|
||||
Binary file not shown.
@@ -0,0 +1,699 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
|
||||
<title>DroidDeck boot animation</title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
:root{
|
||||
box-sizing:border-box;
|
||||
padding-top:env(safe-area-inset-top,0px);
|
||||
padding-bottom:env(safe-area-inset-bottom,0px);
|
||||
--page:#E2E8EE; --panel:#F3F6F9; --ink:#131a21; --muted:#56636F; --line:rgba(19,26,33,.12);
|
||||
--track:rgba(19,26,33,.14); --accent:#1A9FFF; --accent-ink:#0B6FC2; --stage-edge:rgba(19,26,33,.10);
|
||||
--font:"Sora", ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
|
||||
--code:ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
||||
}
|
||||
@media (prefers-color-scheme: dark){
|
||||
:root:not([data-theme="light"]){
|
||||
--page:#0D1319; --panel:#151D25; --ink:#DCE5ED; --muted:#8A98A6; --line:rgba(220,229,237,.12);
|
||||
--track:rgba(220,229,237,.16); --accent-ink:#5CB8FF; --stage-edge:rgba(0,0,0,.5);
|
||||
}
|
||||
}
|
||||
:root[data-theme="dark"]{
|
||||
--page:#0D1319; --panel:#151D25; --ink:#DCE5ED; --muted:#8A98A6; --line:rgba(220,229,237,.12);
|
||||
--track:rgba(220,229,237,.16); --accent-ink:#5CB8FF; --stage-edge:rgba(0,0,0,.5);
|
||||
}
|
||||
*,*::before,*::after{box-sizing:inherit}
|
||||
html{scroll-padding-top:env(safe-area-inset-top,0px)}
|
||||
body{margin:0;background:var(--page);color:var(--ink);font-family:var(--font);font-size:15px;line-height:1.55;-webkit-font-smoothing:antialiased}
|
||||
main{max-width:980px;margin:0 auto;padding:28px 20px 40px}
|
||||
header{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:18px}
|
||||
h1{font-size:1.35rem;font-weight:600;letter-spacing:-.01em;margin:0}
|
||||
.meta{color:var(--muted);font-size:.9rem;margin:0}
|
||||
.stage{position:relative;width:100%;aspect-ratio:16/10;border-radius:14px;overflow:hidden;background:#D6E1EA;box-shadow:0 0 0 1px var(--stage-edge),0 18px 50px -24px rgba(10,20,30,.45)}
|
||||
.stage canvas{display:block;width:100%;height:100%;cursor:pointer}
|
||||
.stage.dark{background:#07090C}
|
||||
.stage.dark .hint{color:#C9D3DD}
|
||||
.head-l{display:flex;align-items:baseline;gap:14px;flex-wrap:wrap}
|
||||
.version{display:inline-flex;border-radius:999px;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:3px}
|
||||
.version button{border:0;background:none;border-radius:999px;padding:5px 14px;font-size:.85rem;cursor:pointer;color:var(--muted)}
|
||||
.version button[aria-pressed="true"]{background:var(--ink);color:var(--page)}
|
||||
.version button:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
||||
.stage .hint{position:absolute;inset:auto 0 14px 0;text-align:center;font-size:.85rem;color:#2c3a47;opacity:0;transition:opacity .25s}
|
||||
.stage.ended .hint{opacity:.75}
|
||||
.controls{display:grid;grid-template-columns:auto 1fr auto;align-items:center;gap:14px;margin-top:16px}
|
||||
button{font:inherit;color:inherit}
|
||||
.play{display:inline-flex;align-items:center;gap:8px;border:0;background:var(--accent);color:#fff;border-radius:999px;padding:9px 16px 9px 12px;font-weight:600;font-size:.9rem;cursor:pointer}
|
||||
.play svg{width:18px;height:18px}
|
||||
.play:hover{filter:brightness(1.06)}
|
||||
.play:focus-visible,.speed button:focus-visible,.beat:focus-visible,input[type=range]:focus-visible,.fs:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
||||
.scrub{position:relative;padding-bottom:22px}
|
||||
input[type=range]{-webkit-appearance:none;appearance:none;width:100%;height:28px;background:transparent;margin:0;cursor:pointer}
|
||||
input[type=range]::-webkit-slider-runnable-track{height:4px;border-radius:4px;background:linear-gradient(to right,var(--accent) var(--p,0%),var(--track) var(--p,0%))}
|
||||
input[type=range]::-moz-range-track{height:4px;border-radius:4px;background:linear-gradient(to right,var(--accent) var(--p,0%),var(--track) var(--p,0%))}
|
||||
input[type=range]::-webkit-slider-thumb{-webkit-appearance:none;width:16px;height:16px;border-radius:50%;background:var(--ink);margin-top:-6px;border:3px solid var(--page)}
|
||||
input[type=range]::-moz-range-thumb{width:12px;height:12px;border-radius:50%;background:var(--ink);border:3px solid var(--page)}
|
||||
.beats{position:absolute;left:8px;right:8px;bottom:0;height:20px}
|
||||
.beat{position:absolute;transform:translateX(-50%);border:0;background:none;padding:0 2px;font-size:.74rem;color:var(--muted);cursor:pointer;white-space:nowrap}
|
||||
.beat:first-child{transform:translateX(-4px)}
|
||||
.beat:first-child::before{left:4px}
|
||||
.beat::before{content:"";position:absolute;left:50%;top:-9px;width:1px;height:6px;background:var(--muted);opacity:.6}
|
||||
.beat:hover,.beat.on{color:var(--ink)}
|
||||
.right{display:flex;align-items:center;gap:10px}
|
||||
.time{font-variant-numeric:tabular-nums;font-size:.85rem;color:var(--muted);min-width:78px;text-align:right}
|
||||
.speed{display:inline-flex;border-radius:999px;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:3px}
|
||||
.speed button{border:0;background:none;border-radius:999px;padding:4px 10px;font-size:.8rem;cursor:pointer;color:var(--muted)}
|
||||
.speed button[aria-pressed="true"]{background:var(--ink);color:var(--page)}
|
||||
.snd{display:inline-flex;align-items:center;gap:6px;border:0;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);border-radius:999px;height:32px;padding:0 12px 0 9px;font-size:.8rem;cursor:pointer;color:var(--ink)}
|
||||
.snd svg{width:18px;height:18px}
|
||||
.snd[aria-pressed="true"]{background:var(--accent);color:#fff;box-shadow:none}
|
||||
.snd:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
|
||||
.fs{border:0;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);border-radius:999px;width:32px;height:32px;display:grid;place-items:center;cursor:pointer;color:var(--ink)}
|
||||
.fs svg{width:16px;height:16px}
|
||||
.install{margin-top:34px;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:28px;border-top:1px solid var(--line);padding-top:24px}
|
||||
.install h2{font-size:1rem;font-weight:600;margin:0 0 8px}
|
||||
.install p,.install ol{margin:0;color:var(--muted);font-size:.9rem;max-width:62ch}
|
||||
.install ol{padding-left:1.2em}
|
||||
.install li+li{margin-top:6px}
|
||||
code{font-family:var(--code);font-size:.84em;background:var(--panel);box-shadow:inset 0 0 0 1px var(--line);padding:1px 6px;border-radius:6px;color:var(--ink);overflow-wrap:anywhere}
|
||||
@media (max-width:640px){
|
||||
main{padding:18px 14px 32px}
|
||||
.controls{grid-template-columns:auto 1fr;row-gap:6px}
|
||||
.right{grid-column:1 / -1;justify-content:space-between}
|
||||
.install{grid-template-columns:1fr}
|
||||
.beat{font-size:.68rem}
|
||||
.snd span{display:none}
|
||||
.snd{padding:0 8px}
|
||||
.right{gap:8px}
|
||||
}
|
||||
body.render{background:#000;margin:0}
|
||||
body.render main{display:none}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header>
|
||||
<div class="head-l">
|
||||
<h1>DroidDeck boot animation</h1>
|
||||
<p class="meta" id="meta">6.3 s at 60 fps, with sound</p>
|
||||
</div>
|
||||
<div class="version" role="group" aria-label="Version">
|
||||
<button data-v="light" aria-pressed="true">Light</button>
|
||||
<button data-v="dark" aria-pressed="false">Dark</button>
|
||||
</div>
|
||||
</header>
|
||||
<div class="stage" id="stage">
|
||||
<canvas id="cv" aria-label="DroidDeck boot animation: three logo pieces stack into a little droid balancing a bowl on its head, then jump and lock into the DroidDeck mark"></canvas>
|
||||
<div class="hint" id="hint">Tap to replay</div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<button class="play" id="play" aria-label="Pause">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path id="playIcon" fill="currentColor" d="M7 5h4v14H7zM13 5h4v14h-4z"/></svg>
|
||||
<span id="playLabel">Pause</span>
|
||||
</button>
|
||||
<div class="scrub">
|
||||
<input type="range" id="scrub" min="0" max="1000" step="1" value="0" aria-label="Timeline">
|
||||
<div class="beats" id="beats"></div>
|
||||
</div>
|
||||
<div class="right">
|
||||
<span class="time" id="time">0.00 / 6.30</span>
|
||||
<div class="speed" role="group" aria-label="Playback speed">
|
||||
<button data-s="1" aria-pressed="true">1×</button>
|
||||
<button data-s="0.5" aria-pressed="false">½×</button>
|
||||
<button data-s="0.25" aria-pressed="false">¼×</button>
|
||||
</div>
|
||||
<button class="snd" id="snd" aria-pressed="false" aria-label="Sound">
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="currentColor" d="M3 9.5h4l5-4.2v13.4l-5-4.2H3z"/><path id="sndMark" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M16 9.5l5 5M21 9.5l-5 5"/></svg>
|
||||
<span>Sound</span>
|
||||
</button>
|
||||
<button class="fs" id="fs" aria-label="Full screen" hidden>
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<section class="install">
|
||||
<div>
|
||||
<h2>Use it as the Steam startup movie</h2>
|
||||
<ol>
|
||||
<li>Put the <code>.webm</code> file in <code>~/.steam/<wbr>root/<wbr>config/<wbr>uioverrides/<wbr>movies/</code>. Create the folders if they don’t exist.</li>
|
||||
<li>In Steam, open Settings > Customization > Startup Movie and pick it.</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div>
|
||||
<h2>Which file to ship</h2>
|
||||
<p>Ship the dark version if your Steam UI is dark: it hands off to the library without a bright flash. The 1280×800 cut matches Steam Deck and is the safe default. The 1920×1080 cut is sharper on phones and TVs. Steam needs the <code>.webm</code>; the <code>.mp4</code> files are for sharing. Everything is drawn and synthesized in code, so the included scripts can output any other size.</p>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<script>
|
||||
/* =====================================================================
|
||||
DroidDeck boot animation engine
|
||||
Every frame is a pure function of time t, so the live preview and the
|
||||
offline video render draw exactly the same thing.
|
||||
Units: logo units from droiddeck-mark.svg. World origin = frame centre,
|
||||
y points down. The frame is always 690 units tall.
|
||||
===================================================================== */
|
||||
const DD = (() => {
|
||||
'use strict';
|
||||
const deg = Math.PI / 180;
|
||||
const clamp = (x, a = 0, b = 1) => Math.min(b, Math.max(a, x));
|
||||
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a)); return t * t * (3 - 2 * t); };
|
||||
const eio = t => { t = clamp(t); return t < .5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2; };
|
||||
const eInQ = t => { t = clamp(t); return t * t; };
|
||||
const eOutC = t => { t = clamp(t); return 1 - Math.pow(1 - t, 3); };
|
||||
|
||||
// ---- 2D affine helpers. m = [a,b,c,d,e,f] (canvas setTransform order)
|
||||
const mul = (m, n) => [
|
||||
m[0]*n[0] + m[2]*n[1], m[1]*n[0] + m[3]*n[1],
|
||||
m[0]*n[2] + m[2]*n[3], m[1]*n[2] + m[3]*n[3],
|
||||
m[0]*n[4] + m[2]*n[5] + m[4], m[1]*n[4] + m[3]*n[5] + m[5]];
|
||||
const T = (x, y) => [1, 0, 0, 1, x, y];
|
||||
const R = a => { const c = Math.cos(a), s = Math.sin(a); return [c, s, -s, c, 0, 0]; };
|
||||
const S = (x, y) => [x, 0, 0, y, 0, 0];
|
||||
const chain = (...ms) => ms.reduce(mul);
|
||||
const ap = (m, p) => ({ x: m[0]*p.x + m[2]*p.y + m[4], y: m[1]*p.x + m[3]*p.y + m[5] });
|
||||
const rv = (a, x, y) => { const c = Math.cos(a), s = Math.sin(a); return { x: c*x - s*y, y: s*x + c*y }; };
|
||||
|
||||
// ---- Geometry straight from the SVG
|
||||
const G = { L: -31.98, B: 223.72, slotL: 56.055, slotR: 71.885, cy: 111.86,
|
||||
dcx: 63.97, dR: 111.86, hcx: 63.98, hR: 71.81, ocx: 63.98, oR: 55.98 };
|
||||
const ORB = '#1A9FFF';
|
||||
const THEMES = {
|
||||
light: { ink: '#1b1b1b', bg: ['#EDF3F8', '#DCE6EE', '#B6C7D6'], shadow: '22,40,58', shadowK: 1, ringA: 1, ringGlow: 0, glow: 0, noise: 3 },
|
||||
dark: { ink: '#FFFFFF', bg: ['#1B222B', '#0F1419', '#030405'], shadow: '0,0,0', shadowK: 2.3, ringA: 1.5, ringGlow: 14, glow: .34, noise: 4 },
|
||||
};
|
||||
let TH = THEMES.light, THN = 'light';
|
||||
const setTheme = n => { THN = THEMES[n] ? n : 'light'; TH = THEMES[THN]; };
|
||||
const ORB_C = { x: G.ocx, y: G.cy };
|
||||
|
||||
function archPath() { // left piece: the "bridge"
|
||||
const p = new Path2D();
|
||||
const dx = G.slotL - G.hcx, hy = Math.sqrt(G.hR*G.hR - dx*dx);
|
||||
p.moveTo(G.L, 0); p.lineTo(G.slotL, 0); p.lineTo(G.slotL, G.cy - hy);
|
||||
p.arc(G.hcx, G.cy, G.hR, Math.atan2(-hy, dx), Math.atan2(hy, dx), true);
|
||||
p.lineTo(G.slotL, G.B); p.lineTo(G.L, G.B); p.closePath();
|
||||
return p;
|
||||
}
|
||||
function domePath() { // right piece: the curve of the D
|
||||
const dxo = G.slotR - G.dcx, hyo = Math.sqrt(G.dR*G.dR - dxo*dxo);
|
||||
const dxi = G.slotR - G.hcx, hyi = Math.sqrt(G.hR*G.hR - dxi*dxi);
|
||||
const p = new Path2D();
|
||||
p.moveTo(G.slotR, G.cy - hyo);
|
||||
p.arc(G.dcx, G.cy, G.dR, Math.atan2(-hyo, dxo), Math.atan2(hyo, dxo), false);
|
||||
p.lineTo(G.slotR, G.cy + hyi);
|
||||
p.arc(G.hcx, G.cy, G.hR, Math.atan2(hyi, dxi), Math.atan2(-hyi, dxi), true);
|
||||
p.closePath();
|
||||
return p;
|
||||
}
|
||||
function orbPath() { const p = new Path2D(); p.arc(G.ocx, G.cy, G.oR, 0, Math.PI*2); return p; }
|
||||
|
||||
const PATH = { arch: archPath(), dome: domePath(), orb: orbPath() };
|
||||
|
||||
// centroids (numerical, symmetric in y)
|
||||
function centroid(path, x0, x1) {
|
||||
const c = document.createElement('canvas').getContext('2d');
|
||||
let n = 0, sx = 0;
|
||||
for (let x = x0; x <= x1; x += .5) for (let y = 0; y <= G.B; y += .5)
|
||||
if (c.isPointInPath(path, x, y)) { n++; sx += x; }
|
||||
return { x: sx / n, y: G.cy };
|
||||
}
|
||||
const CEN = { arch: centroid(PATH.arch, G.L, G.slotL), dome: centroid(PATH.dome, G.slotR, 176) };
|
||||
|
||||
// anchors: the point of each piece that touches whatever it stands on
|
||||
const ANC = { arch: { x: G.slotL, y: G.cy }, ball: { x: G.ocx, y: G.cy + G.oR }, dome: { x: G.hcx + G.hR, y: G.cy } };
|
||||
const HA = G.slotL - G.L; // arch height when standing (88.035)
|
||||
const WA = G.cy; // arch half width (111.86)
|
||||
const FOOT_HALF = (G.cy - (G.cy - Math.sqrt(G.hR*G.hR - (G.slotL-G.hcx)**2))) ; // unused helper
|
||||
const FEET = [{ x: G.slotL, y: 20.24 }, { x: G.slotL, y: G.B - 20.24 }]; // foot centres (piece coords)
|
||||
|
||||
// ---- Scene constants
|
||||
const VIEW_H = 690; // world units visible vertically
|
||||
const FLOOR = 150;
|
||||
const GRAV = 6500;
|
||||
const DUR = 6.30;
|
||||
const T_L = 4.00; // lift-off
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Drops: exact ballistic bounces (height above whatever you land on)
|
||||
// ------------------------------------------------------------------
|
||||
function drop(o) {
|
||||
const g = GRAV, segs = [], impacts = [];
|
||||
let t = o.t0, v = o.v0;
|
||||
let tau = (-v + Math.sqrt(v*v + 2*g*o.h0)) / g;
|
||||
segs.push({ ts: t, te: t + tau, h0: o.h0, vu: -v });
|
||||
t += tau; v = v + g*tau; impacts.push({ t, v });
|
||||
for (;;) {
|
||||
const vu = o.e * v; if (vu < o.minV) break;
|
||||
const d = 2*vu / g; segs.push({ ts: t, te: t + d, h0: 0, vu });
|
||||
t += d; v = vu; impacts.push({ t, v });
|
||||
}
|
||||
const rest = t;
|
||||
const seg = tt => { for (const s of segs) if (tt < s.te) return s; return null; };
|
||||
return {
|
||||
o, impacts, rest, land: impacts[0].t,
|
||||
h(tt) { if (tt <= o.t0) return o.h0; const s = seg(tt); if (!s) return 0; const u = tt - s.ts; return Math.max(0, s.h0 + s.vu*u - .5*g*u*u); },
|
||||
v(tt) { if (tt <= o.t0 || tt >= rest) return 0; const s = seg(tt); return s ? s.vu - g*(tt - s.ts) : 0; },
|
||||
air(tt) { return tt > o.t0 && tt < rest; }
|
||||
};
|
||||
}
|
||||
|
||||
const archDrop = drop({ t0: 0.10, h0: 520, v0: 250, e: 0.20, minV: 300 });
|
||||
const ballDrop = drop({ t0: 0.50, h0: 440, v0: 250, e: 0.45, minV: 170 });
|
||||
const domeDrop = drop({ t0: 1.15, h0: 330, v0: 250, e: 0.24, minV: 250 });
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// The balancing act: one master sway curve, everything else follows it
|
||||
// through springs so the parts lag, overshoot and settle on their own.
|
||||
// ------------------------------------------------------------------
|
||||
const SWAY = [[1.60, 0], [1.90, .42], [2.24, -.70], [2.62, .95], [2.82, 1.10],
|
||||
[3.08, -.44], [3.30, .16], [3.50, 0]];
|
||||
function sway(t) {
|
||||
if (t <= SWAY[0][0] || t >= SWAY[SWAY.length-1][0]) return 0;
|
||||
for (let i = 0; i < SWAY.length - 1; i++) {
|
||||
const [ta, va] = SWAY[i], [tb, vb] = SWAY[i+1];
|
||||
if (t < tb) { const p = (t - ta)/(tb - ta); return va + (vb - va)*(.5 - .5*Math.cos(Math.PI*p)); }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
// legs hop sideways to get back under the bowl on the big wobble
|
||||
const HOP = { t: 2.70, d: .19, dx: 26, h: 16 };
|
||||
const hopX = t => HOP.dx*eio((t - HOP.t)/HOP.d);
|
||||
const hopH = t => (t > HOP.t && t < HOP.t + HOP.d) ? HOP.h*Math.sin(Math.PI*(t - HOP.t)/HOP.d) : 0;
|
||||
// crouch before the jump (added straight onto squash)
|
||||
function crouch(t, amt, a, b, hold) {
|
||||
if (t < a || t >= T_L) return 0;
|
||||
if (t < b) return amt * eio((t - a)/(b - a));
|
||||
if (t < hold) return amt;
|
||||
return amt * (1 - eInQ((t - hold)/(T_L - hold)));
|
||||
}
|
||||
const crouchA = t => crouch(t, .17, 3.56, 3.84, 3.91);
|
||||
const crouchB = t => crouch(t, .12, 3.60, 3.86, 3.91);
|
||||
const crouchD = t => crouch(t, .09, 3.64, 3.88, 3.91);
|
||||
|
||||
const PHI_FALL = 5*deg, PSI_FALL = -6*deg, U0 = 12;
|
||||
const ROLL = G.oR/G.dR; // bowl radius is 2x the ball: it turns 1.5x as it rolls
|
||||
const DT = 1/1200, N = Math.ceil((DUR + .2)/DT);
|
||||
const SIG = { phi: new Float32Array(N), u: new Float32Array(N), psi: new Float32Array(N),
|
||||
qA: new Float32Array(N), qB: new Float32Array(N), qD: new Float32Array(N) };
|
||||
|
||||
function peakFactor(w, z) { // peak of a unit-velocity kick
|
||||
const wd = w*Math.sqrt(1 - z*z), ts = Math.atan(wd/(z*w))/wd;
|
||||
return Math.exp(-z*w*ts)*Math.sin(wd*ts)/wd;
|
||||
}
|
||||
const SPR = { A: [40, .32], B: [34, .28], D: [36, .34] };
|
||||
const kick = (k, peak) => peak / peakFactor(SPR[k][0], SPR[k][1]);
|
||||
|
||||
(function simulate() {
|
||||
const K = [];
|
||||
const v1a = archDrop.impacts[0].v, v1b = ballDrop.impacts[0].v, v1d = domeDrop.impacts[0].v;
|
||||
archDrop.impacts.forEach(i => K.push({ t: i.t, k: 'A', dv: kick('A', .13 * i.v/v1a) }));
|
||||
ballDrop.impacts.forEach(i => { const r = i.v/v1b;
|
||||
K.push({ t: i.t, k: 'B', dv: kick('B', .24*r) }); K.push({ t: i.t, k: 'A', dv: kick('A', .06*r) });
|
||||
K.push({ t: i.t, k: 'phi', dv: .55*r }); });
|
||||
domeDrop.impacts.forEach(i => { const r = i.v/v1d;
|
||||
K.push({ t: i.t, k: 'D', dv: kick('D', .11*r) }); K.push({ t: i.t, k: 'B', dv: kick('B', .17*r) });
|
||||
K.push({ t: i.t, k: 'A', dv: kick('A', .07*r) }); });
|
||||
K.push({ t: HOP.t + HOP.d, k: 'A', dv: kick('A', .07) }); K.push({ t: HOP.t + HOP.d, k: 'B', dv: kick('B', .06) });
|
||||
K.push({ t: HOP.t + HOP.d, k: 'D', dv: kick('D', .04) });
|
||||
K.sort((a, b) => a.t - b.t);
|
||||
|
||||
let phi = PHI_FALL, phiV = 0, phiA = 0, u = U0, uV = 0, psi = PSI_FALL, psiV = 0;
|
||||
const q = { A: [0, 0], B: [0, 0], D: [0, 0] };
|
||||
let ki = 0, crossings = 0, lastSign = 1;
|
||||
for (let i = 0; i < N; i++) {
|
||||
const t = i*DT;
|
||||
while (ki < K.length && K[ki].t <= t) {
|
||||
const k = K[ki++];
|
||||
if (k.k === 'phi') phiV += k.dv; else q[k.k][1] += k.dv;
|
||||
}
|
||||
const s = sway(t);
|
||||
// arch rocking on its feet
|
||||
if (t < archDrop.land) { phi = PHI_FALL; phiV = 0; phiA = 0; }
|
||||
else {
|
||||
const w = 20, z = .38, tgt = 5.6*deg*sway(t - .10);
|
||||
phiA = -w*w*(phi - tgt) - 2*z*w*phiV; phiV += phiA*DT; phi += phiV*DT;
|
||||
const sg = Math.sign(phi) || lastSign;
|
||||
if (sg !== lastSign && crossings < 2 && t < 1.0) { q.A[1] += kick('A', .035); crossings++; }
|
||||
lastSign = sg;
|
||||
}
|
||||
// ball rolling along the arch top
|
||||
if (t < ballDrop.rest) { u = U0; uV = 0; }
|
||||
else { const w = 13, z = .5, tgt = 24*sway(t - .12); const a = -w*w*(u - tgt) - 2*z*w*uV; uV += a*DT; u += uV*DT; }
|
||||
// dome: floppy hat with inertia (it lags the body)
|
||||
if (t < domeDrop.land) { psi = PSI_FALL; psiV = 0; }
|
||||
else { const w = 13, z = .22, tgt = 11*deg*s; const a = -w*w*(psi - tgt) - 2*z*w*psiV - .6*phiA; psiV += a*DT; psi += psiV*DT; }
|
||||
// squash springs; falling pieces stretch along their velocity
|
||||
const tgA = archDrop.air(t) ? -Math.min(.12, Math.abs(archDrop.v(t))*4.6e-5) : 0;
|
||||
const tgB = ballDrop.air(t) ? -Math.min(.14, Math.abs(ballDrop.v(t))*6.5e-5) : 0;
|
||||
const tgD = domeDrop.air(t) ? -Math.min(.10, Math.abs(domeDrop.v(t))*4.0e-5) : 0;
|
||||
for (const [k, tg] of [['A', tgA], ['B', tgB], ['D', tgD]]) {
|
||||
const [w, z] = SPR[k]; const st = q[k];
|
||||
const a = -w*w*(st[0] - tg) - 2*z*w*st[1]; st[1] += a*DT; st[0] += st[1]*DT;
|
||||
}
|
||||
SIG.phi[i] = phi; SIG.u[i] = u; SIG.psi[i] = psi;
|
||||
SIG.qA[i] = q.A[0]; SIG.qB[i] = q.B[0]; SIG.qD[i] = q.D[0];
|
||||
}
|
||||
})();
|
||||
const sig = (name, t) => {
|
||||
const x = clamp(t/DT, 0, N - 1.001), i = Math.floor(x), f = x - i, a = SIG[name];
|
||||
return a[i] + (a[i+1] - a[i])*f;
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Standing pose: a kinematic chain floor → arch → ball → dome
|
||||
// ------------------------------------------------------------------
|
||||
function standPose(t) {
|
||||
const hA = archDrop.h(t) + hopH(t), hx = hopX(t), phi = sig('phi', t), u = sig('u', t), psi = sig('psi', t);
|
||||
const qA = sig('qA', t) + crouchA(t), qB = sig('qB', t) + crouchB(t), qD = sig('qD', t) + crouchD(t);
|
||||
const hB = ballDrop.h(t), hD = domeDrop.h(t);
|
||||
|
||||
const sxA = 1 + .55*qA, syA = 1 - qA;
|
||||
const side = phi >= 0 ? 1 : -1; // rock on the outer corner of one foot
|
||||
const piv = { x: hx + side*WA*sxA, y: FLOOR - hA };
|
||||
const off = rv(phi, -side*WA*sxA, 0);
|
||||
const A = { x: piv.x + off.x, y: piv.y + off.y };
|
||||
const mA = chain(T(A.x, A.y), R(phi), S(sxA, syA), R(90*deg), T(-ANC.arch.x, -ANC.arch.y));
|
||||
|
||||
const top = rv(phi, u, -HA*syA);
|
||||
const cB = { x: A.x + top.x, y: A.y + top.y - hB };
|
||||
const sxB = 1 + .8*qB, syB = 1 - qB;
|
||||
const mB = chain(T(cB.x, cB.y), R(phi), S(sxB, syB), T(-ANC.ball.x, -ANC.ball.y));
|
||||
const bc = rv(phi, 0, -G.oR*syB), O = { x: cB.x + bc.x, y: cB.y + bc.y };
|
||||
|
||||
// bowl: outer curve resting on the ball, rolling without slipping
|
||||
const ang = phi + psi, dd = rv(ang, 0, -G.oR*syB);
|
||||
const cD = { x: O.x + dd.x, y: O.y + dd.y - hD };
|
||||
const sxD = 1 + .6*qD, syD = 1 - qD;
|
||||
const mD = chain(T(cD.x, cD.y), R(ang), S(sxD, syD), T(0, -G.dR), R(psi*ROLL), R(90*deg), T(-G.dcx, -G.cy));
|
||||
return { arch: mA, ball: mB, dome: mD, O, hA };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Flight: lift-off, unfold around the orb, magnetic clack, hover settle
|
||||
// ------------------------------------------------------------------
|
||||
const FL = { TR: .34, APEX: -108, TC: .44, X: 48, ROT: .40 };
|
||||
const H0 = (() => {
|
||||
const p = standPose(T_L), O = p.O, h = { O };
|
||||
for (const k of ['arch', 'dome']) {
|
||||
const c = ap(p[k], CEN[k]), m = p[k];
|
||||
const fin = { x: CEN[k].x - ORB_C.x, y: 0 };
|
||||
h[k] = { a0: Math.atan2(c.y - O.y, c.x - O.x), r0: Math.hypot(c.x - O.x, c.y - O.y),
|
||||
th0: Math.atan2(m[1], m[0]), aF: k === 'arch' ? Math.PI : 0, rF: Math.abs(fin.x) };
|
||||
}
|
||||
return h;
|
||||
})();
|
||||
const damp = (s, w, z) => { const wd = w*Math.sqrt(1 - z*z); return Math.exp(-z*w*s)*Math.sin(wd*s)/wd; };
|
||||
const fromRest = (x0, s, w, z) => { const wd = w*Math.sqrt(1 - z*z);
|
||||
return Math.exp(-z*w*s)*(x0*Math.cos(wd*s) + (z*w*x0/wd)*Math.sin(wd*s)); };
|
||||
|
||||
function flightPose(t) {
|
||||
const tau = t - T_L, sC = tau - FL.TC;
|
||||
const done = tau > 1.7;
|
||||
let Oy = tau < FL.TR ? H0.O.y + (FL.APEX - H0.O.y)*(1 - (1 - tau/FL.TR)**2)
|
||||
: fromRest(FL.APEX, tau - FL.TR, 9.5, .75);
|
||||
let Ox = H0.O.x*(1 - eio(tau/.4));
|
||||
if (done) { Ox = 0; Oy = 0; }
|
||||
const O = { x: Ox, y: Oy };
|
||||
const st = -Math.sin(Math.PI*clamp(tau/.30))*.085; // stretch on the way up
|
||||
const gs = sC > 0 && !done ? 1 + .05*Math.exp(-6*sC)*Math.sin(20*sC) : 1;
|
||||
const G_ = chain(T(O.x, O.y), S(gs, gs), T(-O.x, -O.y));
|
||||
|
||||
const piece = (k, jsign, kq) => {
|
||||
const h = H0[k];
|
||||
const a = h.a0 + (h.aF - h.a0)*eio(tau/FL.ROT);
|
||||
let r = h.rF + (h.r0 - h.rF)*(1 - smooth(0, .30, tau));
|
||||
r += FL.X*smooth(0, .22, tau)*(1 - eInQ((tau - .30)/(FL.TC - .30)));
|
||||
if (sC > 0 && !done) r += 3.6*Math.exp(-14*sC)*Math.abs(Math.sin(38*sC)); // hard stop, tiny rebound
|
||||
let th = h.th0 + (0 - h.th0)*eio((tau - .02)/FL.ROT);
|
||||
if (done) { r = h.rF; th = 0; }
|
||||
const q = st*kq, c = CEN[k];
|
||||
const C = { x: O.x + r*Math.cos(done ? h.aF : a), y: O.y + r*Math.sin(done ? h.aF : a) };
|
||||
return mul(G_, chain(T(C.x, C.y), S(1 + .6*q, 1 - q), R(th), T(-c.x, -c.y)));
|
||||
};
|
||||
const qb = st*1.1;
|
||||
const ball = mul(G_, chain(T(O.x, O.y), S(1 + .8*qb, 1 - qb), T(-ORB_C.x, -ORB_C.y)));
|
||||
return { arch: piece('arch', 1, .8), dome: piece('dome', -1, .8), ball, O, tau };
|
||||
}
|
||||
|
||||
function pose(t) {
|
||||
t = clamp(t, 0, DUR);
|
||||
const p = t < T_L ? standPose(t) : flightPose(t);
|
||||
// contact shadows
|
||||
const fade = t < T_L ? 1 : 1 - smooth(0, .2, t - T_L);
|
||||
const sh = [];
|
||||
if (fade > 0) {
|
||||
let lowest = Infinity, cx = 0;
|
||||
for (const f of FEET) {
|
||||
const w = ap(p.arch, f), hf = Math.max(0, FLOOR - w.y);
|
||||
lowest = Math.min(lowest, hf); cx += w.x/2;
|
||||
sh.push({ x: w.x, rx: 30 + hf*.35, ry: 5.5 + hf*.05, a: .34*Math.exp(-hf/22)*fade });
|
||||
}
|
||||
sh.unshift({ x: cx, rx: 150 + lowest*.35, ry: 15 + lowest*.03, a: .17*Math.exp(-lowest/210)*fade });
|
||||
}
|
||||
p.shadows = sh;
|
||||
// shock ring when the pieces lock
|
||||
const sC = t - (T_L + FL.TC);
|
||||
p.sC = sC;
|
||||
p.ring = sC > 0 && sC < .8 ? { O: p.O, r: 118 + 210*eOutC(sC/.8), a: .34*(1 - sC/.8)**2, w: 4*(1 - .7*sC/.8) } : null;
|
||||
return p;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// Drawing
|
||||
// ------------------------------------------------------------------
|
||||
function makeBG(W, H, noise) {
|
||||
const c = document.createElement('canvas'); c.width = W; c.height = H;
|
||||
const g = c.getContext('2d');
|
||||
const cx = W/2, cy = H*.47, R = Math.hypot(W, H)*.6;
|
||||
const gr = g.createRadialGradient(cx, cy, 0, cx, cy, R);
|
||||
gr.addColorStop(0, TH.bg[0]); gr.addColorStop(.42, TH.bg[1]); gr.addColorStop(1, TH.bg[2]);
|
||||
g.fillStyle = gr; g.fillRect(0, 0, W, H);
|
||||
if (noise) { // static dither: kills banding in the video
|
||||
const id = g.getImageData(0, 0, W, H), d = id.data; let s = 1337;
|
||||
for (let i = 0; i < d.length; i += 4) {
|
||||
s = (s*1664525 + 1013904223) >>> 0; const n = ((s >>> 24)/255 - .5)*noise;
|
||||
d[i] += n; d[i+1] += n; d[i+2] += n;
|
||||
}
|
||||
g.putImageData(id, 0, 0);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
function draw(ctx, W, H, t, bg) {
|
||||
const px = H/VIEW_H, base = [px, 0, 0, px, W/2, H/2];
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
ctx.drawImage(bg, 0, 0, W, H);
|
||||
const p = pose(t);
|
||||
for (const s of p.shadows) {
|
||||
if (s.a < .003) continue;
|
||||
ctx.setTransform(...mul(base, [s.rx, 0, 0, s.ry, s.x, FLOOR]));
|
||||
const g = ctx.createRadialGradient(0, 0, 0, 0, 0, 1);
|
||||
const a = Math.min(.9, s.a*TH.shadowK), c = TH.shadow;
|
||||
g.addColorStop(0, `rgba(${c},${a})`); g.addColorStop(.55, `rgba(${c},${a*.45})`); g.addColorStop(1, `rgba(${c},0)`);
|
||||
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(0, 0, 1, 0, Math.PI*2); ctx.fill();
|
||||
}
|
||||
if (p.ring) {
|
||||
ctx.setTransform(...base);
|
||||
ctx.strokeStyle = `rgba(26,159,255,${Math.min(1, p.ring.a*TH.ringA)})`; ctx.lineWidth = p.ring.w;
|
||||
if (TH.ringGlow) { ctx.shadowColor = `rgba(26,159,255,${Math.min(1, p.ring.a*2)})`; ctx.shadowBlur = TH.ringGlow*px; }
|
||||
ctx.beginPath(); ctx.arc(p.ring.O.x, p.ring.O.y, p.ring.r, 0, Math.PI*2); ctx.stroke();
|
||||
ctx.shadowBlur = 0; ctx.shadowColor = 'transparent';
|
||||
}
|
||||
if (TH.glow && p.sC > 0 && p.sC < 1.4) { // dark only: the orb flashes on at lock, light leaks through the halo gap
|
||||
const ga = TH.glow*Math.min(1, p.sC/.03)*Math.exp(-p.sC/.32)*(1 - smooth(1.0, 1.4, p.sC));
|
||||
ctx.setTransform(...base);
|
||||
const g = ctx.createRadialGradient(p.O.x, p.O.y, G.oR*.9, p.O.x, p.O.y, G.oR*2.6);
|
||||
g.addColorStop(0, `rgba(26,159,255,${ga})`); g.addColorStop(.35, `rgba(26,159,255,${ga*.45})`); g.addColorStop(1, 'rgba(26,159,255,0)');
|
||||
ctx.fillStyle = g; ctx.beginPath(); ctx.arc(p.O.x, p.O.y, G.oR*2.6, 0, Math.PI*2); ctx.fill();
|
||||
}
|
||||
ctx.fillStyle = TH.ink;
|
||||
ctx.setTransform(...mul(base, p.arch)); ctx.fill(PATH.arch);
|
||||
ctx.setTransform(...mul(base, p.dome)); ctx.fill(PATH.dome);
|
||||
ctx.fillStyle = ORB;
|
||||
ctx.setTransform(...mul(base, p.ball)); ctx.fill(PATH.orb);
|
||||
ctx.setTransform(1, 0, 0, 1, 0, 0);
|
||||
}
|
||||
|
||||
// how far (px) things move during an exposure: drives motion-blur sample count
|
||||
const PROBE = { arch: [{x:G.L,y:0},{x:G.L,y:G.B},{x:G.slotL,y:0},{x:G.slotL,y:G.B}],
|
||||
dome: [{x:G.slotR,y:0},{x:G.slotR,y:G.B},{x:176,y:G.cy}],
|
||||
ball: [{x:G.ocx-G.oR,y:G.cy},{x:G.ocx+G.oR,y:G.cy},{x:G.ocx,y:G.cy-G.oR},{x:G.ocx,y:G.cy+G.oR}] };
|
||||
function motionPx(t0, t1, H) {
|
||||
const a = pose(t0), b = pose(t1), px = H/VIEW_H; let m = 0;
|
||||
for (const k of ['arch', 'dome', 'ball']) for (const q of PROBE[k]) {
|
||||
const p0 = ap(a[k], q), p1 = ap(b[k], q); m = Math.max(m, Math.hypot(p1.x - p0.x, p1.y - p0.y));
|
||||
}
|
||||
if (b.ring) m = Math.max(m, Math.abs(b.ring.r - (a.ring ? a.ring.r : 116)));
|
||||
return m*px;
|
||||
}
|
||||
|
||||
// Offline render with real motion blur (180° shutter, adaptive samples)
|
||||
let RC = null;
|
||||
function renderFrame(i, fps = 60, shutter = .5) {
|
||||
const cv = document.getElementById('cv'), W = cv.width, H = cv.height;
|
||||
if (!RC || RC.W !== W || RC.H !== H || RC.theme !== THN) {
|
||||
const ctx = cv.getContext('2d', { willReadFrequently: true });
|
||||
RC = { W, H, theme: THN, ctx, bg: makeBG(W, H, TH.noise), acc: new Uint16Array(W*H*4) };
|
||||
}
|
||||
const t = i/fps, ex = shutter/fps;
|
||||
const t0 = Math.max(0, t - ex/2), t1 = Math.min(DUR, t + ex/2);
|
||||
const n = Math.max(1, Math.min(48, Math.ceil(motionPx(t0, t1, H)/.45)));
|
||||
if (n === 1) { draw(RC.ctx, W, H, t, RC.bg); }
|
||||
else {
|
||||
const acc = RC.acc; acc.fill(0);
|
||||
for (let k = 0; k < n; k++) {
|
||||
draw(RC.ctx, W, H, t0 + (k + .5)/n*(t1 - t0), RC.bg);
|
||||
const d = RC.ctx.getImageData(0, 0, W, H).data;
|
||||
for (let j = 0; j < d.length; j++) acc[j] += d[j];
|
||||
}
|
||||
const out = RC.ctx.createImageData(W, H), o = out.data;
|
||||
for (let j = 0; j < o.length; j++) o[j] = (acc[j] + (n >> 1))/n;
|
||||
RC.ctx.putImageData(out, 0, 0);
|
||||
}
|
||||
return { url: cv.toDataURL('image/png'), samples: n };
|
||||
}
|
||||
|
||||
return { DUR, T_L, HOP, setTheme, get theme() { return THN; }, draw, makeBG, renderFrame, pose, sig, sway, drops: { archDrop, ballDrop, domeDrop },
|
||||
BEATS: [['Drop', .10], ['Wobble', 1.60], ['Jump', 3.56], ['Lock', T_L + FL.TC]],
|
||||
frameCount: fps => Math.round(DUR*fps) + 1, CEN, H0 };
|
||||
})();
|
||||
|
||||
/* =====================================================================
|
||||
Preview player (or bare canvas when ?render=1)
|
||||
===================================================================== */
|
||||
(() => {
|
||||
const qs = new URLSearchParams(location.search);
|
||||
const cv = document.getElementById('cv');
|
||||
if (qs.get('render')) {
|
||||
document.body.classList.add('render');
|
||||
DD.setTheme(qs.get('theme') || 'light');
|
||||
document.body.appendChild(cv);
|
||||
cv.width = +qs.get('w') || 1280; cv.height = +qs.get('h') || 800;
|
||||
cv.style.width = cv.width + 'px'; cv.style.height = cv.height + 'px';
|
||||
return;
|
||||
}
|
||||
const stage = document.getElementById('stage'), ctx = cv.getContext('2d');
|
||||
const scrub = document.getElementById('scrub'), timeEl = document.getElementById('time');
|
||||
const playBtn = document.getElementById('play'), playIcon = document.getElementById('playIcon'), playLabel = document.getElementById('playLabel');
|
||||
const beatsEl = document.getElementById('beats'), fsBtn = document.getElementById('fs');
|
||||
const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
const sndBtn = document.getElementById('snd'), sndMark = document.getElementById('sndMark'), hint = document.getElementById('hint');
|
||||
let W = 0, H = 0, bg = null, t = reduce ? DD.DUR : 0, playing = !reduce, speed = 1, last = 0, raf = 0;
|
||||
|
||||
// Soundtrack through Web Audio. When it's playing, the audio clock drives the picture.
|
||||
const Sound = (() => {
|
||||
let ctx = null, buf = null, src = null, on = false, pending = null, t0 = 0, c0 = 0, rate = 1;
|
||||
const bytes = () => { const b = atob(DD_SOUND), u = new Uint8Array(b.length); for (let i = 0; i < b.length; i++) u[i] = b.charCodeAt(i); return u.buffer; };
|
||||
async function ensure() { // call from a tap: browsers only allow sound after one
|
||||
if (!ctx) { const AC = window.AudioContext || window.webkitAudioContext; if (!AC) return false; ctx = new AC(); }
|
||||
if (ctx.state !== 'running') { try { await ctx.resume(); } catch (e) {} }
|
||||
if (!buf) { pending = pending || new Promise((ok, no) => ctx.decodeAudioData(bytes(), ok, no));
|
||||
try { buf = await pending; } catch (e) { pending = null; return false; } }
|
||||
return ctx.state === 'running';
|
||||
}
|
||||
function stop() { if (src) { try { src.stop(); } catch (e) {} src.disconnect(); src = null; } }
|
||||
function start(at, r) {
|
||||
stop(); if (!on || !buf || !ctx || ctx.state !== 'running' || at >= buf.duration) return;
|
||||
src = ctx.createBufferSource(); src.buffer = buf; src.playbackRate.value = r; src.connect(ctx.destination);
|
||||
c0 = ctx.currentTime; t0 = at; rate = r; src.start(c0, at);
|
||||
}
|
||||
function clock() { return src ? t0 + Math.max(0, ctx.currentTime - c0 - (ctx.outputLatency || 0))*rate : null; }
|
||||
return { ensure, start, stop, clock, get on() { return on; }, set on(v) { on = v; if (!v) stop(); } };
|
||||
})();
|
||||
|
||||
// version: remembered per viewer, otherwise follows the system theme
|
||||
let ver = null; try { ver = localStorage.getItem('dd-version'); } catch (e) {}
|
||||
if (ver !== 'light' && ver !== 'dark') ver = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||
function setVersion(v) {
|
||||
ver = v; DD.setTheme(v); stage.classList.toggle('dark', v === 'dark');
|
||||
document.querySelectorAll('.version button').forEach(b => b.setAttribute('aria-pressed', b.dataset.v === v));
|
||||
if (W) bg = DD.makeBG(W, H, 0);
|
||||
try { localStorage.setItem('dd-version', v); } catch (e) {}
|
||||
}
|
||||
document.querySelectorAll('.version button').forEach(b => b.onclick = () => { setVersion(b.dataset.v); render(); });
|
||||
setVersion(ver);
|
||||
function size() {
|
||||
const r = stage.getBoundingClientRect(), dpr = Math.min(window.devicePixelRatio || 1, 2.5);
|
||||
const w = Math.round(r.width*dpr), h = Math.round(r.height*dpr);
|
||||
if (w !== W || h !== H) { W = cv.width = w; H = cv.height = h; bg = DD.makeBG(W, H, 0); }
|
||||
render();
|
||||
}
|
||||
const ICON = { pause: 'M7 5h4v14H7zM13 5h4v14h-4z', play: 'M8 5.5v13l11-6.5z', replay: 'M12 5a7 7 0 1 1-6.6 4.7l1.9.6A5 5 0 1 0 12 7v3L7.5 6 12 2z' };
|
||||
function ui() {
|
||||
const ended = t >= DD.DUR - 1e-6;
|
||||
const mode = playing ? 'pause' : ended ? 'replay' : 'play';
|
||||
playIcon.setAttribute('d', ICON[mode]);
|
||||
playLabel.textContent = mode === 'pause' ? 'Pause' : mode === 'replay' ? 'Replay' : 'Play';
|
||||
playBtn.setAttribute('aria-label', playLabel.textContent);
|
||||
stage.classList.toggle('ended', ended && !playing);
|
||||
hint.textContent = Sound.on ? 'Tap to replay' : 'Turn on Sound to hear it';
|
||||
sndBtn.setAttribute('aria-pressed', Sound.on);
|
||||
sndMark.setAttribute('d', Sound.on ? 'M15.5 9.2a4 4 0 0 1 0 5.6M18.3 6.6a7.6 7.6 0 0 1 0 10.8' : 'M16 9.5l5 5M21 9.5l-5 5');
|
||||
const p = t/DD.DUR; scrub.value = Math.round(p*1000); scrub.style.setProperty('--p', (p*100) + '%');
|
||||
timeEl.textContent = `${t.toFixed(2)} / ${DD.DUR.toFixed(2)}`;
|
||||
let cur = -1; DD.BEATS.forEach((b, i) => { if (t >= b[1]) cur = i; });
|
||||
[...beatsEl.children].forEach((el, i) => el.classList.toggle('on', i === cur));
|
||||
}
|
||||
function render() { if (bg) DD.draw(ctx, W, H, t, bg); ui(); }
|
||||
function loop(now) {
|
||||
raf = 0;
|
||||
if (playing) {
|
||||
const heard = Sound.clock();
|
||||
if (heard !== null) t = Math.min(DD.DUR, heard);
|
||||
else t = Math.min(DD.DUR, t + Math.min(.05, (now - last)/1000)*speed);
|
||||
if (t >= DD.DUR) playing = false;
|
||||
}
|
||||
last = now; render();
|
||||
if (playing) raf = requestAnimationFrame(loop);
|
||||
}
|
||||
function play() {
|
||||
if (t >= DD.DUR - 1e-6) t = 0;
|
||||
playing = true; Sound.start(t, speed); last = performance.now();
|
||||
if (!raf) raf = requestAnimationFrame(loop);
|
||||
}
|
||||
function pause() { playing = false; Sound.stop(); render(); }
|
||||
sndBtn.onclick = async () => {
|
||||
if (Sound.on) { Sound.on = false; ui(); return; }
|
||||
Sound.on = true; ui();
|
||||
if (!(await Sound.ensure())) { Sound.on = false; ui(); return; }
|
||||
t = 0; play(); // replay from the top so it's heard in sync
|
||||
};
|
||||
playBtn.onclick = () => playing ? pause() : play();
|
||||
cv.onclick = () => playing ? pause() : play();
|
||||
scrub.oninput = () => { playing = false; Sound.stop(); t = scrub.value/1000*DD.DUR; render(); };
|
||||
document.querySelectorAll('.speed button').forEach(b => b.onclick = () => {
|
||||
speed = +b.dataset.s; document.querySelectorAll('.speed button').forEach(x => x.setAttribute('aria-pressed', x === b));
|
||||
if (playing) Sound.start(t, speed);
|
||||
});
|
||||
DD.BEATS.forEach(([name, bt]) => {
|
||||
const b = document.createElement('button'); b.className = 'beat'; b.textContent = name;
|
||||
b.style.left = (bt/DD.DUR*100) + '%'; b.onclick = () => { t = bt; play(); };
|
||||
beatsEl.appendChild(b);
|
||||
});
|
||||
addEventListener('keydown', e => {
|
||||
if (e.target.closest('input,button') && e.key !== ' ') return;
|
||||
if (e.key === ' ') { e.preventDefault(); playing ? pause() : play(); }
|
||||
else if (e.key === 'ArrowRight' || e.key === 'ArrowLeft') {
|
||||
e.preventDefault(); playing = false; Sound.stop(); t = Math.max(0, Math.min(DD.DUR, t + (e.key === 'ArrowRight' ? 1 : -1)/60)); render();
|
||||
}
|
||||
});
|
||||
if (stage.requestFullscreen) {
|
||||
fsBtn.hidden = false;
|
||||
fsBtn.onclick = () => document.fullscreenElement ? document.exitFullscreen() : stage.requestFullscreen().catch(() => {});
|
||||
}
|
||||
new ResizeObserver(size).observe(stage);
|
||||
addEventListener('resize', size);
|
||||
size();
|
||||
if (playing) play();
|
||||
})();
|
||||
</script>
|
||||
<script id="dd-sound">/* soundtrack: MP3, base64. Rebuild with embed_sound.py */
|
||||
const DD_SOUND = /*SOUND*/"SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjYwLjE2LjEwMAAAAAAAAAAAAAAA//uUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAASW5mbwAAAA8AAAEJAAGPAAADBggLDhATFhgaHR8iJScqLS8yNDY5Oz5BQ0ZJS01QUlVYWl1gYmVnaWxucXR2eXx+gIOFiIuNkJOVmJqcn6Gkp6msr7Gztri7vsDDxsjLzc/S1Nfa3N/i5Obp6+7x8/b5+/4AAAAATGF2YzYwLjMxAAAAAAAAAAAAAAAAJAXgAAAAAAABjwC+eaeUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//uUZAAP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAETEFNRTMuMTAwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//uUZFGP8AAAaQAAAAgAAA0gAAABAAABpAAAACAAADSAAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVMQU1FMy4xLine truncated
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Embed droiddeck-boot-sound.wav into droiddeck-boot.html (MP3, base64) for the preview page."""
|
||||
import base64, re, subprocess
|
||||
from pathlib import Path
|
||||
here = Path(__file__).parent
|
||||
subprocess.run(["ffmpeg", "-y", "-loglevel", "error", "-i", str(here / "droiddeck-boot-sound.wav"),
|
||||
"-c:a", "libmp3lame", "-b:a", "128k", str(here / "_snd.mp3")], check=True)
|
||||
b64 = base64.b64encode((here / "_snd.mp3").read_bytes()).decode(); (here / "_snd.mp3").unlink()
|
||||
html = (here / "droiddeck-boot.html").read_text()
|
||||
html = re.sub(r'/\*SOUND\*/".*?"/\*END\*/', lambda m: f'/*SOUND*/"{b64}"/*END*/', html, flags=re.S)
|
||||
(here / "droiddeck-boot.html").write_text(html)
|
||||
print(f"embedded {len(b64)/1024:.0f} KB of sound")
|
||||
@@ -0,0 +1,20 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
JS = """(() => {
|
||||
const d = DD.drops, c = (m, q) => ({x: m[0]*q.x + m[2]*q.y + m[4], y: m[1]*q.x + m[3]*q.y + m[5]});
|
||||
const ev = {DUR: DD.DUR, T_L: DD.T_L, LOCK: DD.BEATS[3][1], HOP: DD.HOP,
|
||||
drops: Object.fromEntries(['archDrop','ballDrop','domeDrop'].map(k => [k, {t0: d[k].o.t0, impacts: d[k].impacts}]))};
|
||||
const tr = {t:[], phi:[], u:[], psi:[], ax:[], ay:[], bx:[], by:[], dx:[], dy:[]}, dt = 1/1200;
|
||||
for (let i = 0; i*dt <= DD.DUR + 1e-9; i++) { const t = i*dt, p = DD.pose(t);
|
||||
const a = c(p.arch, DD.CEN.arch), b = c(p.ball, {x: 63.98, y: 111.86}), q = c(p.dome, DD.CEN.dome);
|
||||
tr.t.push(t); tr.phi.push(DD.sig('phi', t)); tr.u.push(DD.sig('u', t)); tr.psi.push(DD.sig('psi', t));
|
||||
tr.ax.push(a.x); tr.ay.push(a.y); tr.bx.push(b.x); tr.by.push(b.y); tr.dx.push(q.x); tr.dy.push(q.y); }
|
||||
ev.tr = tr; return ev; })()"""
|
||||
with sync_playwright() as p:
|
||||
b = p.chromium.launch(); pg = b.new_page()
|
||||
pg.goto(Path(__file__).with_name('droiddeck-boot.html').resolve().as_uri() + '?render=1&w=320&h=200')
|
||||
pg.wait_for_function("typeof DD !== 'undefined'", timeout=15000)
|
||||
ev = pg.evaluate(JS); b.close()
|
||||
json.dump(ev, open('events.json', 'w'))
|
||||
print({k: v for k, v in ev.items() if k != 'tr'})
|
||||
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Render the DroidDeck boot animation to .webm (Steam) or .mp4 (H.264).
|
||||
|
||||
Usage: python3 render.py [WIDTH] [HEIGHT] [FPS] [OUT] [light|dark]
|
||||
python3 render.py 1280 800 60 droiddeck-boot.webm
|
||||
python3 render.py 1920 1080 60 droiddeck-boot.mp4
|
||||
python3 render.py 1280 800 60 droiddeck-boot-dark.webm dark
|
||||
|
||||
Needs: pip install playwright && playwright install chromium, plus ffmpeg with libvpx-vp9.
|
||||
The animation is drawn by droiddeck-boot.html (same folder); each frame gets real
|
||||
motion blur (180-degree shutter, up to 48 sub-frames when things move fast).
|
||||
"""
|
||||
import base64, os, shutil, subprocess, sys, tempfile, time
|
||||
from pathlib import Path
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
W = int(sys.argv[1]) if len(sys.argv) > 1 else 1280
|
||||
H = int(sys.argv[2]) if len(sys.argv) > 2 else 800
|
||||
FPS = int(sys.argv[3]) if len(sys.argv) > 3 else 60
|
||||
OUT = sys.argv[4] if len(sys.argv) > 4 else f"droiddeck-boot-{W}x{H}.webm"
|
||||
THEME = sys.argv[5] if len(sys.argv) > 5 else "light" # light | dark
|
||||
ONLY = [int(x) for x in os.environ.get("FRAMES", "").split(",") if x] # debug: render some frames only
|
||||
|
||||
html = Path(__file__).with_name("droiddeck-boot.html").resolve()
|
||||
tmp = Path(os.environ["FRAMEDIR"]) if os.environ.get("FRAMEDIR") else Path(tempfile.mkdtemp(prefix="ddframes_"))
|
||||
tmp.mkdir(parents=True, exist_ok=True) # FRAMEDIR=... makes a long render resumable
|
||||
t0 = time.time()
|
||||
with sync_playwright() as p:
|
||||
browser = p.chromium.launch()
|
||||
page = browser.new_page(viewport={"width": W, "height": H})
|
||||
page.goto(f"{html.as_uri()}?render=1&w={W}&h={H}&theme={THEME}")
|
||||
page.wait_for_function("typeof DD !== 'undefined'", timeout=30000)
|
||||
n = page.evaluate(f"DD.frameCount({FPS})")
|
||||
frames = ONLY or range(n)
|
||||
for i in frames:
|
||||
if (tmp / f"f{i:05d}.png").exists() and not ONLY:
|
||||
continue
|
||||
r = page.evaluate(f"DD.renderFrame({i}, {FPS})")
|
||||
(tmp / f"f{i:05d}.png").write_bytes(base64.b64decode(r["url"].split(",", 1)[1]))
|
||||
if i % 30 == 0 or ONLY:
|
||||
print(f"frame {i+1}/{n} blur samples {r['samples']:>2} {time.time()-t0:5.1f}s", flush=True)
|
||||
browser.close()
|
||||
|
||||
if ONLY:
|
||||
print("frames left in", tmp); sys.exit(0)
|
||||
|
||||
COLOR = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv"]
|
||||
SOUND = Path(__file__).with_name("droiddeck-boot-sound.wav") # made by sound.py; muxed in if present
|
||||
cmd = ["ffmpeg", "-y", "-loglevel", "error", "-framerate", str(FPS), "-i", str(tmp / "f%05d.png")]
|
||||
if SOUND.exists():
|
||||
cmd += ["-i", str(SOUND), "-map", "0:v", "-map", "1:a"]
|
||||
cmd += ["-c:a", "aac", "-b:a", "192k"] if OUT.lower().endswith(".mp4") else ["-c:a", "libopus", "-b:a", "160k"]
|
||||
cmd += ["-vf", "scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+full_chroma_int,format=yuv420p"]
|
||||
if OUT.lower().endswith(".mp4"): # H.264 for sharing, previews and anything that won't play webm
|
||||
cmd += ["-c:v", "libx264", "-preset", "slow", "-crf", "15", "-profile:v", "high", "-tune", "animation",
|
||||
"-g", str(FPS * 2), "-movflags", "+faststart"]
|
||||
else: # VP9 webm for Steam's startup movie
|
||||
cmd += ["-c:v", "libvpx-vp9", "-b:v", "0", "-crf", "18", "-deadline", "good", "-cpu-used", "2",
|
||||
"-row-mt", "1", "-g", str(FPS * 2)]
|
||||
cmd += COLOR + ([] if SOUND.exists() else ["-an"]) + [OUT]
|
||||
subprocess.run(cmd, check=True)
|
||||
if not os.environ.get("FRAMEDIR"):
|
||||
shutil.rmtree(tmp)
|
||||
print(f"wrote {OUT} ({os.path.getsize(OUT)/1e6:.2f} MB) in {time.time()-t0:.0f}s")
|
||||
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env python3
|
||||
"""DroidDeck boot animation: procedural sound design.
|
||||
|
||||
Every sound is synthesized (no samples) and placed on the exact physics events the animation
|
||||
engine reports (events.json, exported by events.py). Key: D major.
|
||||
|
||||
legs (arch) lands on a muted D
|
||||
ball lands on A, the second bounce a quieter echo
|
||||
bowl lands on F#
|
||||
balancing silence
|
||||
jump silence
|
||||
lock a soft landing in the same voice, then all those notes together as the D chord
|
||||
|
||||
Usage: python3 sound.py [events.json] [out.wav]
|
||||
"""
|
||||
import json, sys
|
||||
import numpy as np
|
||||
from scipy import signal
|
||||
|
||||
SR = 48000
|
||||
FPS = 60
|
||||
ev = json.load(open(sys.argv[1] if len(sys.argv) > 1 else 'events.json'))
|
||||
OUT = sys.argv[2] if len(sys.argv) > 2 else 'droiddeck-boot-sound.wav'
|
||||
FRAMES = round(ev['DUR'] * FPS) + 1
|
||||
N = int(np.ceil(FRAMES / FPS * SR)) # exactly the video length
|
||||
rng = np.random.default_rng(20260925)
|
||||
|
||||
# note frequencies
|
||||
def hz(n): return 440.0 * 2 ** ((n - 69) / 12)
|
||||
D2 = 440.0 * 2 ** ((38 - 69) / 12)
|
||||
D3, A3, D4, E4, Fs4, A4, B4, Cs5, D5, E5, Fs5, A5, D6 = [hz(n) for n in (50, 57, 62, 64, 66, 69, 71, 73, 74, 76, 78, 81, 86)]
|
||||
|
||||
# ------------------------------------------------------------------ building blocks
|
||||
def tt(dur): return np.arange(int(dur * SR)) / SR
|
||||
|
||||
def edge(x, a_ms=1.0, r_ms=4.0):
|
||||
"""Click-free start and end."""
|
||||
na, nr = max(1, int(a_ms * SR / 1000)), max(1, int(r_ms * SR / 1000))
|
||||
x[:na] *= np.sin(np.linspace(0, np.pi / 2, na)) ** 2
|
||||
x[-nr:] *= np.cos(np.linspace(0, np.pi / 2, nr)) ** 2
|
||||
return x
|
||||
|
||||
def bp(x, lo, hi, order=2):
|
||||
return signal.sosfilt(signal.butter(order, [lo, min(hi, SR * .45)], 'bandpass', fs=SR, output='sos'), x)
|
||||
|
||||
def lp(x, f, order=2): return signal.sosfilt(signal.butter(order, f, 'lowpass', fs=SR, output='sos'), x)
|
||||
def hp(x, f, order=2): return signal.sosfilt(signal.butter(order, f, 'highpass', fs=SR, output='sos'), x)
|
||||
|
||||
def modal(freqs, decays, amps, dur):
|
||||
t = tt(dur); y = np.zeros_like(t)
|
||||
for f, d, a in zip(freqs, decays, amps):
|
||||
if f < SR * .45: y += a * np.sin(2 * np.pi * f * t) * np.exp(-t / d)
|
||||
return y
|
||||
|
||||
def glide(f0, f1, tau, dur):
|
||||
"""Sine whose pitch moves exponentially from f0 to f1."""
|
||||
t = tt(dur); f = f1 + (f0 - f1) * np.exp(-t / tau)
|
||||
return np.sin(2 * np.pi * np.cumsum(f) / SR)
|
||||
|
||||
def noise_burst(dur, lo, hi, tau):
|
||||
t = tt(dur); return bp(rng.standard_normal(len(t)), lo, hi) * np.exp(-t / tau)
|
||||
|
||||
def pan(x, p):
|
||||
p = np.clip(p, -1, 1); a = (p + 1) * np.pi / 4
|
||||
return np.stack([x * np.cos(a), x * np.sin(a)])
|
||||
|
||||
MIX = np.zeros((2, N))
|
||||
def put(t0, st, gain=1.0):
|
||||
i = int(round(t0 * SR))
|
||||
if i >= N: return
|
||||
j = min(N, i + st.shape[1]); MIX[:, i:j] += gain * st[:, :j - i]
|
||||
|
||||
# ------------------------------------------------------------------ instruments
|
||||
def wood(amp, f0=520, size=1.0, thump=0.0, dur=.35):
|
||||
"""Hard wood / toy-block clack. thump adds body for heavy landings."""
|
||||
r = [1, 1.93, 2.81, 4.13, 5.62]
|
||||
y = modal([f0 * k for k in r], [s * size for s in (.055, .034, .022, .014, .009)], [1, .55, .42, .26, .16], dur)
|
||||
y += .7 * noise_burst(dur, 1400, 7500, .0035)
|
||||
if thump: y += thump * glide(118, 52, .035, dur) * np.exp(-tt(dur) / .075)
|
||||
return edge(y * amp)
|
||||
|
||||
def bonk(amp, f):
|
||||
"""Hollow rubber ball on a board: round pitched body, soft click, tiny board knock."""
|
||||
d = .42; t = tt(d)
|
||||
y = glide(f * 1.28, f, .018, d) * np.exp(-t / (.09 + .05 * amp))
|
||||
y += .22 * glide(f * 2.45, f * 2.3, .02, d) * np.exp(-t / .035)
|
||||
y += .55 * glide(95, 60, .03, d) * np.exp(-t / .045)
|
||||
y += .22 * noise_burst(d, 1800, 5000, .002)
|
||||
y += .25 * wood(1, f0=640, size=.6, dur=d)
|
||||
return edge(y * amp, a_ms=.6)
|
||||
|
||||
def bowl_ring(amp, f=A4, dur=2.4, dscale=1.0):
|
||||
"""Struck metal bowl: inharmonic partials, each split in two for the slow beating shimmer."""
|
||||
t = tt(dur); y = np.zeros_like(t)
|
||||
for k, dec, a, beat in zip((1, 2.71, 5.12, 8.21), tuple(d * dscale for d in (1.25, .62, .3, .15)), (1, .45, .24, .12), (.9, 1.7, 2.6, 3.1)):
|
||||
for s in (-1, 1):
|
||||
y += .5 * a * np.sin(2 * np.pi * (f * k + s * beat / 2) * t + (s > 0) * .8) * np.exp(-t / dec)
|
||||
return edge(y * amp, a_ms=.8, r_ms=30)
|
||||
|
||||
def clonk(amp, ring):
|
||||
d = .5; t = tt(d)
|
||||
y = .8 * glide(160, 92, .03, d) * np.exp(-t / .06) + .45 * wood(1, f0=880, size=.7, dur=d)
|
||||
return edge(y * amp), bowl_ring(ring)
|
||||
|
||||
def marimba(f, amp, damp=1.0):
|
||||
d = 1.2; t = tt(d)
|
||||
tau = .55 * (440 / f) ** .5 * damp
|
||||
y = modal([f, f * 3.93, f * 9.2], [tau, tau * .22, .03], [1, .32, .07], d)
|
||||
y += .05 * lp(rng.standard_normal(len(t)), 2500) * np.exp(-t / .002)
|
||||
return edge(y * amp, a_ms=1.5, r_ms=40)
|
||||
|
||||
def svf_whoosh(env, fc, q=.9):
|
||||
"""Noise through a band-pass whose centre follows fc(t): air moving past a spinning piece."""
|
||||
x = rng.standard_normal(len(env)); y = np.zeros_like(x); ic1 = ic2 = 0.0
|
||||
for i in range(len(x)):
|
||||
g = np.tan(np.pi * min(fc[i], SR * .45) / SR); k = 1 / q
|
||||
a1 = 1 / (1 + g * (g + k)); a2 = g * a1; a3 = g * a2
|
||||
v3 = x[i] - ic2; v1 = a1 * ic1 + a2 * v3; v2 = ic2 + a2 * ic1 + a3 * v3
|
||||
ic1 = 2 * v1 - ic1; ic2 = 2 * v2 - ic2; y[i] = v1
|
||||
return y * env
|
||||
|
||||
def epiano(f, amp, dur=2.8, decay=1.5):
|
||||
"""FM electric piano: bright tine at the strike that mellows as the index falls."""
|
||||
t = tt(dur)
|
||||
idx = 1.7 * np.exp(-t / .22) + .22
|
||||
y = np.sin(2 * np.pi * f * t + idx * np.sin(2 * np.pi * f * t))
|
||||
y += .18 * np.sin(2 * np.pi * f * t + .9 * np.exp(-t / .012) * np.sin(2 * np.pi * 14 * f * t)) * np.exp(-t / .05)
|
||||
return edge(y * np.exp(-t / decay) * amp, a_ms=3, r_ms=60)
|
||||
|
||||
def tock(f, amp, decay=.42, sub=0.0):
|
||||
"""A landing as a muted note in the chord's own FM e-piano voice: felt contact, no pitch bend."""
|
||||
d = 1.5; t = tt(d)
|
||||
idx = 1.3 * np.exp(-t / .07) + .18
|
||||
y = np.sin(2 * np.pi * f * t + idx * np.sin(2 * np.pi * f * t)) * np.exp(-t / decay)
|
||||
y = lp(y, 2600)
|
||||
y += .30 * lp(rng.standard_normal(len(t)), 1600) * np.exp(-t / .0016)
|
||||
if sub: y += sub * np.sin(2 * np.pi * D2 * t) * np.exp(-t / .075)
|
||||
return edge(y * amp, a_ms=1.5, r_ms=80)
|
||||
|
||||
def bell(f, amp, dur=1.6):
|
||||
t = tt(dur)
|
||||
y = np.sin(2 * np.pi * f * t + 1.1 * np.exp(-t / .3) * np.sin(2 * np.pi * 3.5 * f * t)) * np.exp(-t / .7)
|
||||
return edge(y * amp, a_ms=2, r_ms=40)
|
||||
|
||||
# ------------------------------------------------------------------ tracks from the engine
|
||||
tr = {k: np.array(v) for k, v in ev['tr'].items()}
|
||||
TT = tr['t']; dT = TT[1] - TT[0]
|
||||
def at(name, t): return np.interp(t, TT, tr[name])
|
||||
def speed(xk, yk):
|
||||
return np.hypot(np.gradient(tr[xk], dT), np.gradient(tr[yk], dT))
|
||||
X2PAN = 1 / 330 # world units to stereo pan
|
||||
drops = ev['drops']; T_L = ev['T_L']; LOCK = ev['LOCK']; HOP = ev['HOP']
|
||||
events_log = []
|
||||
def log(t, what): events_log.append((round(t, 3), what))
|
||||
|
||||
# ------------------------------------------------------------------ cue sheet
|
||||
# Kept deliberately sparse: one sound per story beat, with silence between them.
|
||||
|
||||
tsamp = np.arange(N) / SR
|
||||
|
||||
# 1. the stack: each piece lands on a muted note of the final chord (D, A, A-echo, F#);
|
||||
# the lock then plays them all together
|
||||
ai = drops['archDrop']['impacts']
|
||||
put(ai[0]['t'], pan(tock(D3, .40, decay=.5, sub=.8), .1)); log(ai[0]['t'], 'legs land: D')
|
||||
|
||||
bi = drops['ballDrop']['impacts']
|
||||
for k, imp in enumerate(bi[:2]):
|
||||
a = .32 * (imp['v'] / bi[0]['v']) ** .9
|
||||
put(imp['t'], pan(tock(A3, a, decay=.36, sub=.3 * a / .32), 0)); log(imp['t'], f'ball: A {a:.2f}')
|
||||
|
||||
di = drops['domeDrop']['impacts']
|
||||
put(di[0]['t'], pan(tock(Fs4, .28, decay=.45, sub=.45), -.05)); log(di[0]['t'], 'bowl lands: F#')
|
||||
|
||||
# 2-3. the balancing act and the jump play in silence: the stack and the lock carry it
|
||||
|
||||
# 4. lock: one snap, then a four-note chord that rings out
|
||||
put(LOCK, pan(tock(D3, .24, decay=.28, sub=.8), 0)); log(LOCK, 'lock: soft landing in the stack voice')
|
||||
for f, a, p, off in ((D3, .24, -.1, 0), (A3, .28, .2, .02), (D4, .30, -.2, .04), (Fs4, .26, .15, .06)):
|
||||
put(LOCK + .018 + off, pan(epiano(f, a, decay=1.3 if f < 300 else 1.1), p))
|
||||
log(LOCK + .018, 'D chord')
|
||||
|
||||
# ------------------------------------------------------------------ room, master
|
||||
def room_ir(dur=1.1, rt60=.75):
|
||||
t = tt(dur); tau = rt60 / 6.9; irs = []
|
||||
for ch in range(2):
|
||||
n = rng.standard_normal(len(t))
|
||||
ir = lp(n, 7000) * np.exp(-t / (tau * .6)) * .5 + lp(n, 2200) * np.exp(-t / tau)
|
||||
ir[:int(.011 * SR)] = 0 # pre-delay
|
||||
for d_ms, g in ((13, .5), (19, .35), (27, .3), (38, .2)):
|
||||
ir[int((d_ms + ch * 1.3) * SR / 1000)] += g
|
||||
irs.append(ir / np.sqrt(np.sum(ir ** 2)))
|
||||
return irs
|
||||
irs = room_ir()
|
||||
wet = np.stack([signal.fftconvolve(MIX[ch], irs[ch])[:N] for ch in range(2)])
|
||||
out = MIX + .14 * wet
|
||||
out = hp(out, 28)
|
||||
fade = np.ones(N); nf = int(.45 * SR); fade[-nf:] = np.cos(np.linspace(0, np.pi / 2, nf)) ** 2
|
||||
out *= fade
|
||||
# gentle peak control: soft-knee compress only the loudest transients, then normalise
|
||||
pk = np.max(np.abs(out)); x = out / pk
|
||||
knee = .5; ax = np.abs(x); over = ax > knee
|
||||
x[over] = np.sign(x[over]) * (knee + (1 - knee) * np.tanh((ax[over] - knee) / (1 - knee)))
|
||||
L0, L1 = int((LOCK + .06) * SR), int((LOCK + .76) * SR)
|
||||
body_rms = np.sqrt(np.mean(x[:, L0:L1].mean(0) ** 2))
|
||||
out = x * (10 ** (-14.9 / 20) / body_rms) # chord body held at the level the team liked (-14.9 dB RMS)
|
||||
assert np.max(np.abs(out)) < 10 ** (-1 / 20), 'would clip'
|
||||
|
||||
import wave
|
||||
pcm = (np.clip(out.T, -1, 1) * 32767).astype('<i2')
|
||||
with wave.open(OUT, 'wb') as w:
|
||||
w.setnchannels(2); w.setsampwidth(2); w.setframerate(SR); w.writeframes(pcm.tobytes())
|
||||
json.dump(sorted(events_log), open('sound_events.json', 'w'), indent=0)
|
||||
print(f'wrote {OUT}: {N / SR:.3f}s, {len(events_log)} cues')
|
||||
for t, w_ in sorted(events_log): print(f' {t:6.3f} {w_}')
|
||||
+2
-2
@@ -6,7 +6,7 @@ buildscript {
|
||||
}
|
||||
dependencies {
|
||||
classpath 'com.android.tools.build:gradle:8.8.0'
|
||||
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.0.21'
|
||||
classpath 'org.jetbrains.kotlin:compose-compiler-gradle-plugin:2.0.21'
|
||||
classpath 'org.jetbrains.kotlin:kotlin-gradle-plugin:2.1.0'
|
||||
classpath 'org.jetbrains.kotlin:compose-compiler-gradle-plugin:2.1.0'
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,44 @@ the timeline, then lessons and backlog. Companion to the README (what the app *d
|
||||
|
||||
---
|
||||
|
||||
## 2026-09-25 - main `8cdedbe`: melonDS out of the box, touch in Big Picture, log privacy, Decky
|
||||
|
||||
State: **main = `8cdedbe`** (PR #22 merge). Device-tested on the AYANEO Pocket FIT (repacked test builds)
|
||||
unless marked. gamescope now staged from release **`gamescope-3.16.29-p3`**.
|
||||
|
||||
- **PR #18 → `9369dc3`** (`feat/melonds-preset`) - melonDS and the session:
|
||||
- **melonDS preset** (`bannerlator-pad-defaults`): the top screen as big as the panel allows with the bottom
|
||||
screen alone beside it, centred (Horizontal + Emphasize top; Hybrid repeats the top screen), sharp pixels;
|
||||
full screen from the front end (`-f`) at the panel's own resolution; the guide button toggles full
|
||||
screen, leaving to a 1x-wide 16:9 window whose menus gamescope stretches to a usable size; DS/DSi BIOS,
|
||||
firmware and NAND found in `ROMs/nds/{bios,firmware}` (BIOS by checksum). Existing installs moved once.
|
||||
- **Desktop**: `QT_QPA_PLATFORM="wayland;xcb"` (the melonDS AppImage ships only xcb and exited at once);
|
||||
a labwc window rule opens melonDS at 800x600, centred.
|
||||
- **HUD** follows the game window, not gamescope's 1x1 cursor or Qt menus (read 0 fps at 60).
|
||||
- **Cursor**: hides on pad / on-screen-control input (Bannerlator's 1.2 s rule), and shows the program's own
|
||||
shape - labwc's resize arrows, I-beams, a hide (Bannerlator's `wl_pointer.set_cursor` port; new here:
|
||||
labwc's GPU cursor is a UBWC dma-buf, read back through `vkp_image_readback`).
|
||||
- **Steam desktop switching**: "Steam Desktop UI" opens the desktop with Steam's desktop client in it (under
|
||||
gamescope the client picks Big Picture regardless); the drawer's **DESKTOP** button does it from Big
|
||||
Picture; relaunches restart the singleTop activity in place (`startActivity` from it was swallowed).
|
||||
Big Picture's own Power → Switch to Desktop still hangs: it waits on SteamOS Manager before its
|
||||
`steamos-session-select` fallback (stub included; a session bus did not help - tried and reverted).
|
||||
- **PR #19 → `ce0da01`** (`fix/log-privacy`) - no credentials or identities in session logs: the device's
|
||||
public addresses (the client's IPv6 check logs "external address" ~20x a session), `network.txt` addresses
|
||||
as their kind and the MAC masked, every Steam AccountName/PersonaName (plain account names leaked in the
|
||||
UI log's login lines), and every text file scrubbed at session end and in the share-logs zip. Verified:
|
||||
0 hits across 83 session folders.
|
||||
- **PR #16 → `5270574`** (Decky Loader, Kurt) - merged with the Steam CEF debugging marker tied to the
|
||||
supervisor toggle (it was created at install; on Android any app can reach 127.0.0.1:8080 - proven from
|
||||
another uid). Decky's own updater still points at the official project (no ARM64 build there).
|
||||
- **PR #20 → `036317f`** (Kurt) - local builds carry the CI payload (NDK proot, patched gamescope).
|
||||
- **PR #22 → `8cdedbe`** (`feat/steam-touch`) - touch in Big Picture: gamescope `0110` binds `wl_touch` in the
|
||||
nested backend and feeds wlserver's touch path (Big Picture sets Passthrough: tap and swipe rows as on a
|
||||
Deck); `0111` makes the nested pointer warp in Passthrough (touchpad mode: hover and tap-to-click work);
|
||||
the compositor's pointer fallback no longer jams on a lost finger-up.
|
||||
- **In design, not built**: the drawer's page dots as QAM-style icons (Display / Controls / Settings), the
|
||||
selected one "stepping forward" in a line; mock `droiddeck-drawer-tabs-preview.html`.
|
||||
|
||||
## 2026-09-24 (afternoon) - main `94f9935`: PS1, controller focus, own signing key, CI hardening
|
||||
|
||||
State: **main = `94f9935`** (PR #41 merge), main build run 36036219740 - the first one signed with
|
||||
|
||||
Reference in new issue
Block a user