[Feat] (Android plugin, renderer samples): add interactive tests and external trace replay

This commit is contained in:
BZLZHH committed 2026-11-29 11:10:39 +08:00
1 parent 9560cca571
commit 04f7faedc1
17 files changed
+2328 -30

No files matched your search

+1
View File
@@ -805,6 +805,7 @@ if (ANDROID)
list(APPEND SOURCE_FILES
MobileGL/MG_Util/SelfTest/DriverPostJni.cpp
MobileGL/MG_Util/SelfTest/DriverBenchJni.cpp
MobileGL/AndroidTestScenes.cpp
)
if (MOBILEGL_BUILD_DISAGGREGATED)
# P12 (on-screen server window): the APK's MobileGLDisplayActivity - the in-process
+382
View File
@@ -0,0 +1,382 @@
// MobileGL - MobileGL/AndroidTestScenes.cpp
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
#ifdef __ANDROID__
#include <android/native_window_jni.h>
#include <jni.h>
#include <algorithm>
#include <initializer_list>
#include <chrono>
#include <memory>
#include <string>
#include <string_view>
#include <vector>
#include <Includes.h>
#include <MG_Impl/EGLImpl/EGLImpl.h>
#include <MG_Impl/GLImpl/Buffer/GL_Buffer.h>
#include <MG_Impl/GLImpl/Drawing/GL_Drawing.h>
#include <MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h>
#include <MG_Impl/GLImpl/Getter/GL_Getter.h>
#include <MG_Impl/GLImpl/Program/GL_Program.h>
#include <MG_Impl/GLImpl/RenderState/GL_RenderState.h>
#include <MG_Impl/GLImpl/Texture/GL_Texture.h>
#include <MG_Impl/GLImpl/VertexArray/GL_VertexArray.h>
namespace {
namespace Egl = MobileGL::MG_Impl::EGLImpl;
namespace Gl = MobileGL::MG_Impl::GLImpl;
using Clock = std::chrono::steady_clock;
#include "MG_Util/SelfTest/AndroidTestLandscapeScenes.inc"
#include "MG_Util/SelfTest/AndroidTestGeometricScenes.inc"
#include "MG_Util/SelfTest/AndroidTestOceanSunrise.inc"
#include "MG_Util/SelfTest/AndroidTestOceanHdr.inc"
#include "MG_Util/SelfTest/AndroidTestApiChurn.inc"
enum class SceneKind {
Fragment,
ApiChurn,
OceanHdr
};
struct Scene {
const char* title;
const char* fragment;
SceneKind kind = SceneKind::Fragment;
};
constexpr Scene kScenes[] = {{"Aurora", kAurora},
{"Ocean Sunset", kOcean},
{"Wind-Swept Dunes", kDunes},
{"Neon Skyline", kCity},
{"Orbital Dawn", kOrbit},
{"Light Tunnel", kTunnel},
{"Kaleidoscope", kKaleidoscope},
{"Starfield", kParticles},
{"Liquid Metaballs", kMetaballs},
{"Rotating Prism", kPrism},
{"API Churn", kApiChurn, SceneKind::ApiChurn},
{"Ocean Sunrise (Stress)", kOceanSunrise},
{"Ocean Sunrise (GL 4.5)", kOceanSunrise, SceneKind::OceanHdr}};
constexpr const char* kVertex = R"glsl(
in vec2 aPosition;
void main() { gl_Position = vec4(aPosition, 0.0, 1.0); }
)glsl";
constexpr const char* kFragmentInputs = R"glsl(
uniform vec2 uExtent;
uniform float uTime;
out vec4 outColor;
)glsl";
constexpr const char* kFragmentMain = R"glsl(
void main() {
vec2 uv = gl_FragCoord.xy / uExtent;
vec2 p = (2.0 * gl_FragCoord.xy - uExtent) / uExtent.y;
outColor = vec4(clamp(scene(p, uv, uTime), 0.0, 1.0), 1.0);
}
)glsl";
std::string JsonString(std::string_view text) {
std::string result = "\"";
for (const unsigned char ch : text) {
if (ch == '"' || ch == '\\') result += '\\';
result += ch < 32 ? ' ' : static_cast<char>(ch);
}
return result + '"';
}
std::string Error(std::string_view message) {
return "{\"error\":" + JsonString(message) + "}";
}
struct SceneWindow {
EGLDisplay display = EGL_NO_DISPLAY;
EGLSurface surface = EGL_NO_SURFACE;
EGLContext context = EGL_NO_CONTEXT;
EGLint width = 0;
EGLint height = 0;
~SceneWindow() {
if (display == EGL_NO_DISPLAY) return;
Egl::MakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (context != EGL_NO_CONTEXT) Egl::DestroyContext(display, context);
if (surface != EGL_NO_SURFACE) Egl::DestroySurface(display, surface);
Egl::Terminate(display);
}
void Open(ANativeWindow* window, bool vsync) {
display = Egl::GetDisplay(EGL_DEFAULT_DISPLAY);
if (display == EGL_NO_DISPLAY || !Egl::Initialize(display, nullptr, nullptr)) {
throw MobileGL::RuntimeError("eglInitialize failed");
}
const EGLint configAttributes[] = {
EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_NONE};
EGLConfig config = nullptr;
EGLint count = 0;
if (!Egl::ChooseConfig(display, configAttributes, &config, 1, &count) || count == 0) {
throw MobileGL::RuntimeError("No EGL window config");
}
const EGLint contextAttributes[] = {EGL_CONTEXT_CLIENT_VERSION, 3, EGL_NONE};
context = Egl::CreateContext(display, config, EGL_NO_CONTEXT, contextAttributes);
surface = Egl::CreateWindowSurface(display, config, window, nullptr);
if (context == EGL_NO_CONTEXT || surface == EGL_NO_SURFACE ||
!Egl::MakeCurrent(display, surface, surface, context)) {
throw MobileGL::RuntimeError("Could not bind EGL window context");
}
width = ANativeWindow_getWidth(window);
height = ANativeWindow_getHeight(window);
if (width < 1 || height < 1) throw MobileGL::RuntimeError("Surface has no size");
if (!Egl::SwapInterval(display, vsync ? 1 : 0)) {
throw MobileGL::RuntimeError("eglSwapInterval failed");
}
}
};
GLuint CompileShader(GLenum kind, const std::string& source) {
const GLuint shader = Gl::CreateShader(kind);
const char* sources[] = {source.c_str()};
Gl::ShaderSource(shader, 1, sources, nullptr);
Gl::CompileShader(shader);
GLint compiled = GL_FALSE;
Gl::GetShaderiv(shader, GL_COMPILE_STATUS, &compiled);
if (!compiled) {
char log[512]{};
Gl::GetShaderInfoLog(shader, sizeof log, nullptr, log);
throw MobileGL::RuntimeError(std::string("Shader compile failed: ") + log);
}
return shader;
}
GLuint LinkProgram(std::initializer_list<GLuint> shaders) {
const GLuint program = Gl::CreateProgram();
for (const auto shader : shaders)
Gl::AttachShader(program, shader);
Gl::BindAttribLocation(program, 0, "aPosition");
Gl::LinkProgram(program);
for (const auto shader : shaders)
Gl::DeleteShader(shader);
GLint linked = GL_FALSE;
Gl::GetProgramiv(program, GL_LINK_STATUS, &linked);
if (!linked) {
char log[512]{};
Gl::GetProgramInfoLog(program, sizeof log, nullptr, log);
throw MobileGL::RuntimeError(std::string("Program link failed: ") + log);
}
return program;
}
GLuint BuildProgram(const std::string& version, const std::string& fragment, const char* main) {
const GLuint vertex = CompileShader(GL_VERTEX_SHADER, version + kVertex);
const GLuint pixel = CompileShader(GL_FRAGMENT_SHADER, version + kFragmentInputs + fragment + main);
return LinkProgram({vertex, pixel});
}
struct OceanHdrPasses {
static constexpr int WaveSize = 256;
GLuint spectrumProgram = 0;
GLuint synthesisProgram = 0;
GLuint waterProgram = 0;
GLuint postProgram = 0;
GLuint spectrumBuffer = 0;
GLuint waveImage = 0;
GLuint hdrImage = 0;
GLuint hdrTarget = 0;
GLint spectrumTime = -1;
GLint waterTime = -1;
void Setup(const SceneWindow& egl) {
GLint major = 0;
GLint minor = 0;
Gl::GetIntegerv(GL_MAJOR_VERSION, &major);
Gl::GetIntegerv(GL_MINOR_VERSION, &minor);
if (major < 4 || (major == 4 && minor < 5)) {
throw MobileGL::RuntimeError("Ocean Sunrise requires desktop GL 4.5");
}
const std::string version = "#version 450 core\n";
spectrumProgram = LinkProgram({CompileShader(GL_COMPUTE_SHADER, version + kOceanSpectrum)});
synthesisProgram = LinkProgram({CompileShader(GL_COMPUTE_SHADER, version + kOceanSynthesis)});
waterProgram =
BuildProgram(version, std::string("#define MOBILEGL_OCEAN_HDR\n") + kOceanSunrise, kOceanHdrMain);
postProgram = BuildProgram(version, "", kOceanPost);
spectrumTime = Gl::GetUniformLocation(spectrumProgram, "uTime");
waterTime = Gl::GetUniformLocation(waterProgram, "uTime");
Gl::CreateBuffers(1, &spectrumBuffer);
Gl::NamedBufferStorage(spectrumBuffer, 24 * 4 * sizeof(float), nullptr, 0);
Gl::BindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, spectrumBuffer);
Gl::CreateTextures(GL_TEXTURE_2D, 1, &waveImage);
Gl::TextureStorage2D(waveImage, 1, GL_RGBA32F, WaveSize, WaveSize);
Gl::TextureParameteri(waveImage, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
Gl::TextureParameteri(waveImage, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Gl::CreateTextures(GL_TEXTURE_2D, 1, &hdrImage);
Gl::TextureStorage2D(hdrImage, 1, GL_RGBA16F, egl.width, egl.height);
Gl::TextureParameteri(hdrImage, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
Gl::TextureParameteri(hdrImage, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Gl::TextureParameteri(hdrImage, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
Gl::TextureParameteri(hdrImage, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
Gl::CreateFramebuffers(1, &hdrTarget);
Gl::NamedFramebufferTexture(hdrTarget, GL_COLOR_ATTACHMENT0, hdrImage, 0);
if (Gl::CheckNamedFramebufferStatus(hdrTarget, GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
throw MobileGL::RuntimeError("RGBA16F framebuffer unavailable");
}
Gl::UseProgram(waterProgram);
Gl::Uniform2f(Gl::GetUniformLocation(waterProgram, "uExtent"), egl.width, egl.height);
Gl::Uniform1i(Gl::GetUniformLocation(waterProgram, "uCapillaryWaves"), 0);
Gl::UseProgram(postProgram);
Gl::Uniform2f(Gl::GetUniformLocation(postProgram, "uExtent"), egl.width, egl.height);
Gl::Uniform1i(Gl::GetUniformLocation(postProgram, "uRadiance"), 1);
if (Gl::GetError() != GL_NO_ERROR) throw MobileGL::RuntimeError("Ocean GL 4.5 setup failed");
}
void Draw(float time) const {
Gl::UseProgram(spectrumProgram);
Gl::Uniform1f(spectrumTime, time + 4.0f);
Gl::DispatchCompute(1, 1, 1);
Gl::MemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
Gl::UseProgram(synthesisProgram);
Gl::BindImageTexture(0, waveImage, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);
Gl::DispatchCompute(WaveSize / 8, WaveSize / 8, 1);
Gl::MemoryBarrier(GL_TEXTURE_FETCH_BARRIER_BIT | GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);
Gl::BindFramebuffer(GL_FRAMEBUFFER, hdrTarget);
Gl::UseProgram(waterProgram);
Gl::BindTextureUnit(0, waveImage);
Gl::Uniform1f(waterTime, time);
Gl::DrawArrays(GL_TRIANGLES, 0, 3);
Gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
Gl::UseProgram(postProgram);
Gl::BindTextureUnit(1, hdrImage);
Gl::DrawArrays(GL_TRIANGLES, 0, 3);
}
};
std::string RunScene(const Scene& scene, ANativeWindow* window, bool vsync) {
SceneWindow egl;
egl.Open(window, vsync);
const auto* renderer = reinterpret_cast<const char*>(Gl::GetString(GL_RENDERER));
const auto* version = reinterpret_cast<const char*>(Gl::GetString(GL_VERSION));
const auto rendererName = JsonString(renderer ? renderer : "Unknown renderer");
const bool oceanHdr = scene.kind == SceneKind::OceanHdr;
OceanHdrPasses ocean;
GLuint program = 0;
GLint timeUniform = -1;
if (oceanHdr) {
ocean.Setup(egl);
} else {
const bool es = version && std::string_view(version).starts_with("OpenGL ES");
program = BuildProgram(es ? "#version 300 es\nprecision highp float;\n" : "#version 330 core\n",
scene.fragment, kFragmentMain);
Gl::UseProgram(program);
Gl::Uniform2f(Gl::GetUniformLocation(program, "uExtent"), egl.width, egl.height);
timeUniform = Gl::GetUniformLocation(program, "uTime");
}
constexpr GLfloat triangle[] = {-1.0f, -1.0f, 3.0f, -1.0f, -1.0f, 3.0f};
GLuint vao = 0;
GLuint vbo = 0;
Gl::GenVertexArrays(1, &vao);
Gl::BindVertexArray(vao);
Gl::GenBuffers(1, &vbo);
Gl::BindBuffer(GL_ARRAY_BUFFER, vbo);
Gl::BufferData(GL_ARRAY_BUFFER, sizeof triangle, triangle, GL_STATIC_DRAW);
Gl::VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
Gl::EnableVertexAttribArray(0);
Gl::Viewport(0, 0, egl.width, egl.height);
const auto start = Clock::now();
const auto draw = [&] {
const float time = std::chrono::duration<float>(Clock::now() - start).count();
if (oceanHdr) {
ocean.Draw(time);
} else {
Gl::Uniform1f(timeUniform, time);
if (scene.kind == SceneKind::ApiChurn) IssueRedundantCalls(program, vao, vbo, timeUniform, time);
Gl::DrawArrays(GL_TRIANGLES, 0, 3);
}
if (!Egl::SwapBuffers(egl.display, egl.surface)) {
throw MobileGL::RuntimeError("eglSwapBuffers failed");
}
};
for (int i = 0; i < 8; ++i)
draw();
std::vector<double> frameTimes;
const auto sampleStart = Clock::now();
auto end = sampleStart;
do {
const auto begin = end;
draw();
end = Clock::now();
frameTimes.push_back(std::chrono::duration<double, std::milli>(end - begin).count());
} while (end - sampleStart < std::chrono::seconds(5));
const GLenum glError = Gl::GetError();
std::sort(frameTimes.begin(), frameTimes.end());
const auto count = frameTimes.size();
const double seconds = std::chrono::duration<double>(end - sampleStart).count();
std::string report = "{\"renderer\":" + rendererName + ",\"frames\":" + std::to_string(count) +
",\"fps\":" + std::to_string(count / seconds) +
",\"medianFrameMs\":" + std::to_string(frameTimes[count / 2]) +
",\"p95FrameMs\":" + std::to_string(frameTimes[(count * 95 + 99) / 100 - 1]) +
",\"glError\":" + std::to_string(glError);
if (scene.kind == SceneKind::ApiChurn) {
report += ",\"redundantCallsPerFrame\":" + std::to_string(kRedundantCallsPerFrame);
}
return report + "}";
}
} // namespace
extern "C" JNIEXPORT jstring JNICALL Java_top_mobilegl_plugin_TestActivity_nativeSampleCatalog(JNIEnv* env, jclass) {
std::string catalog = "[";
for (const auto& scene : kScenes) {
if (catalog.size() > 1) catalog += ',';
catalog += JsonString(scene.title);
}
catalog += ']';
return env->NewStringUTF(catalog.c_str());
}
extern "C" JNIEXPORT jstring JNICALL Java_top_mobilegl_plugin_TestService_nativeRunSample(JNIEnv* env, jclass,
jstring sample,
jobject surface,
jboolean vsync) {
std::unique_ptr<ANativeWindow, decltype(&ANativeWindow_release)> window(
surface ? ANativeWindow_fromSurface(env, surface) : nullptr, ANativeWindow_release);
if (!window) return env->NewStringUTF("{\"error\":\"Surface unavailable\"}");
const char* chars = env->GetStringUTFChars(sample, nullptr);
if (!chars) return nullptr;
const std::string selected(chars);
env->ReleaseStringUTFChars(sample, chars);
std::string result = Error("Unknown scene");
try {
for (const auto& scene : kScenes) {
if (selected == scene.title) {
result = RunScene(scene, window.get(), vsync == JNI_TRUE);
break;
}
}
}
catch (const std::exception& error) {
result = Error(error.what());
}
catch (...) {
result = Error("Native rendering failed");
}
return env->NewStringUTF(result.c_str());
}
#endif
+2 -1
View File
@@ -471,7 +471,8 @@ namespace MobileGL::MG_ConfigLoader {
// loads; the debug property is how a developer picks the backend for such a process
// without rebuilding it (`adb shell setprop debug.mobilegl.backend DirectVulkan`).
char property[PROP_VALUE_MAX] = {};
if (__system_property_get("debug.mobilegl.backend", property) > 0) {
if (!QueryEnvFlag("MOBILEGL_TEST_BACKEND_ENV_PRIORITY") &&
__system_property_get("debug.mobilegl.backend", property) > 0) {
MGLOG_I("Config: debug.mobilegl.backend=%s overrides MOBILEGL_BACKEND_TYPE=%s", property,
backendTypeStr.c_str());
backendTypeStr = property;
@@ -0,0 +1,54 @@
// MobileGL - MobileGL/MG_Util/SelfTest/AndroidTestApiChurn.inc
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
constexpr const char* kApiChurn = R"glsl(
vec3 scene(vec2 p, vec2 uv, float t) {
vec2 grid = p * 6.0 + 0.5;
vec2 tile = floor(grid);
vec2 local = fract(grid) - 0.5;
float wave = 0.5 + 0.5 * sin(dot(tile, vec2(0.63, 0.84)) - t * 4.0);
float glow = wave * wave;
float edge = max(abs(local.x), abs(local.y));
float aa = max(fwidth(grid.x), fwidth(grid.y));
float panel = 1.0 - smoothstep(0.44 - aa, 0.44 + aa, edge);
float rim = smoothstep(0.39 - aa, 0.39 + aa, edge) * panel;
float radius = 0.12 + 0.19 * glow;
float light = 1.0 - smoothstep(radius - aa, radius + aa, length(local));
vec3 accent = mix(vec3(0.10, 0.86, 1.0), vec3(1.0, 0.36, 0.18), uv.x);
vec3 color = vec3(0.014, 0.023, 0.046);
color += panel * (vec3(0.016, 0.024, 0.037) + accent * (0.05 + 0.14 * glow));
color += accent * (rim * (0.08 + 0.29 * glow) + light * (0.12 + 0.58 * glow));
return color;
}
)glsl";
constexpr int kApiChurnBatchesPerFrame = 96;
constexpr int kApiChurnCallsPerBatch = 16;
constexpr int kRedundantCallsPerFrame = kApiChurnBatchesPerFrame * kApiChurnCallsPerBatch;
void IssueRedundantCalls(GLuint program, GLuint vao, GLuint vbo, GLint timeUniform, float time) {
// Reapply the fullscreen draw setup, its current time, and the defaults in its fresh context.
for (int batch = 0; batch < kApiChurnBatchesPerFrame; ++batch) {
Gl::UseProgram(program);
Gl::BindVertexArray(vao);
Gl::BindBuffer(GL_ARRAY_BUFFER, vbo);
Gl::EnableVertexAttribArray(0);
Gl::ActiveTexture(GL_TEXTURE0);
Gl::BindTexture(GL_TEXTURE_2D, 0);
Gl::Uniform1f(timeUniform, time);
Gl::Disable(GL_BLEND);
Gl::BlendFunc(GL_ONE, GL_ZERO);
Gl::BlendEquation(GL_FUNC_ADD);
Gl::Disable(GL_DEPTH_TEST);
Gl::DepthFunc(GL_LESS);
Gl::DepthMask(GL_TRUE);
Gl::Disable(GL_CULL_FACE);
Gl::Disable(GL_SCISSOR_TEST);
Gl::ColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
}
}
@@ -0,0 +1,254 @@
// MobileGL - MobileGL/MG_Util/SelfTest/AndroidTestGeometricScenes.inc
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
constexpr const char* kTunnel = R"glsl(
float tunnelStripe(float phase, float width) {
float aa = max(fwidth(phase), 0.001);
float distanceToStripe = abs(fract(phase + 0.5) - 0.5);
return (1.0 - smoothstep(width, width + aa, distanceToStripe))
* (1.0 - smoothstep(0.18, 0.48, aa));
}
vec3 scene(vec2 p, vec2 uv, float t) {
p -= 0.20 * vec2(sin(t * 0.51), cos(t * 0.37));
float radius2 = dot(p, p);
// Inverse screen radius projects equal world-space rings toward the vanishing point.
float depth = 1.35 * inversesqrt(radius2 + 0.006) + t * 1.65;
float angle = atan(p.y, p.x + 0.00001) + 0.34 * depth + t * 0.11;
float crossSection = 8.0 * angle;
float spoke = abs(sin(crossSection));
float rails = 1.0 - smoothstep(0.06, 0.06 + max(fwidth(spoke), 0.01), spoke);
float railGlow = 1.0 - smoothstep(0.08, 0.56, spoke);
float rings = tunnelStripe(depth, 0.043);
float ringGlow = tunnelStripe(depth, 0.14);
float majorRings = tunnelStripe(depth * 0.25, 0.018);
float panels = 0.5 + 0.5 * sin(crossSection * 0.5 + floor(depth + 0.5) * 1.7);
vec3 walls = mix(vec3(0.026, 0.030, 0.095), vec3(0.055, 0.165, 0.223), panels);
walls += vec3(0.06, 0.32, 0.43) * (rings * 0.85 + railGlow * 0.35);
walls += vec3(0.20, 0.67, 0.79) * rails * (0.52 + 0.48 * ringGlow);
walls += vec3(0.90, 0.42, 0.13) * majorRings * (0.76 + 0.24 * panels);
float visibility = smoothstep(0.026, 0.29, radius2);
vec3 haze = mix(vec3(0.08, 0.19, 0.29), vec3(0.25, 0.66, 0.79),
1.0 - smoothstep(0.0, 0.022, radius2));
return clamp(mix(haze, walls, visibility) / (1.0 + 0.22 * radius2), 0.0, 1.0);
}
)glsl";
constexpr const char* kKaleidoscope = R"glsl(
float kaleidoscopeFill(float distanceToEdge) {
float aa = max(fwidth(distanceToEdge), 0.002);
return 1.0 - smoothstep(-aa, aa, distanceToEdge);
}
vec3 scene(vec2 p, vec2 uv, float t) {
const float wedge = 0.62831853;
float radius = length(p);
float angle = atan(p.y, p.x + 0.00001) + t * 0.23;
angle += 0.12 * sin(4.0 * radius - t * 1.25);
float folded = abs(mod(angle + 0.5 * wedge, wedge) - 0.5 * wedge);
vec2 q = radius * vec2(sin(folded), cos(folded));
float pulse = sin(t * 1.35);
float petal = abs(q.x - 0.063) * 3.1 + abs(q.y - (0.50 + 0.07 * pulse)) - 0.30;
float leaf = abs(q.x - 0.21 + 0.15 * (q.y - 0.86)) * 2.8
+ abs(q.y - 0.90 + 0.045 * pulse) - 0.25;
float jewel = q.x * 2.6 + abs(q.y - 0.17) - 0.107;
float ribbon = abs(q.x - 0.25 * q.y + 0.038 + 0.023 * sin(q.y * 7.0 + t * 1.8));
float lattice = abs(fract(q.y * 3.9 + q.x * 7.5 - t * 0.33) - 0.5);
vec3 color = mix(vec3(0.035, 0.010, 0.086), vec3(0.15, 0.027, 0.23),
1.0 - smoothstep(0.0, 1.36, radius));
float leafFill = kaleidoscopeFill(leaf);
float petalFill = kaleidoscopeFill(petal);
color += vec3(0.15, 0.27, 0.54) * leafFill * (0.7 + 0.3 * q.y);
color += vec3(0.55, 0.065, 0.23) * petalFill * (1.0 - 0.78 * lattice);
color += vec3(0.77, 0.27, 0.38) * kaleidoscopeFill(abs(petal) - 0.014);
color += vec3(0.28, 0.58, 0.88) * kaleidoscopeFill(abs(leaf) - 0.011);
color += vec3(0.94, 0.55, 0.19) * kaleidoscopeFill(jewel);
color += vec3(0.73, 0.33, 0.13) * kaleidoscopeFill(ribbon - 0.008)
* (1.0 - smoothstep(0.80, 1.47, q.y));
color += vec3(0.28, 0.11, 0.28) * smoothstep(0.26, 0.48, lattice)
* (1.0 - smoothstep(0.65, 1.62, radius));
return clamp(color / (1.0 + 0.43 * radius * radius), 0.0, 1.0);
}
)glsl";
constexpr const char* kParticles = R"glsl(
vec3 particleHash(vec2 cell) {
vec3 hash = fract(cell.xyx * vec3(0.1031, 0.11369, 0.13787));
hash += dot(hash, hash.yzx + 19.19);
return fract((hash.xxy + hash.yzz) * hash.zyx);
}
vec3 particleLayer(vec2 p, float t, float size, float density, float sparkle, vec3 tint) {
vec3 seed = particleHash(floor(p));
// The widest halo stays within its cell, so only one cell needs sampling.
vec2 local = fract(p) - mix(vec2(0.23), vec2(0.77), seed.xy);
float radius2 = dot(local, local);
float core = 1.0 - smoothstep(size * size * 0.15, size * size, radius2);
float halo = max(1.0 - radius2 * 25.0, 0.0);
vec2 axis = abs(local);
float rays = (1.0 - smoothstep(0.001, 0.027, min(axis.x, axis.y)))
* (1.0 - smoothstep(0.025, 0.21, max(axis.x, axis.y)));
float twinkle = 1.0 - abs(fract(t * (0.33 + seed.x * 0.31) + seed.y) * 2.0 - 1.0);
float intensity = core + halo * halo * 0.19 + rays * sparkle * twinkle * 0.60;
return mix(tint, vec3(0.98, 0.81, 0.59), twinkle * seed.y * sparkle)
* intensity * step(1.0 - density, seed.z) * (0.38 + 0.62 * twinkle);
}
vec3 scene(vec2 p, vec2 uv, float t) {
float band = p.y + 0.28 * p.x + 0.18 * sin(p.x * 2.8 + t * 0.19);
float cloud = 1.0 - smoothstep(0.03, 0.69, abs(band));
vec3 color = vec3(0.015, 0.022, 0.063);
color += cloud * mix(vec3(0.073, 0.040, 0.12), vec3(0.027, 0.099, 0.15), uv.x);
vec2 drift = t * vec2(0.11, -0.066);
color += particleLayer(31.0 * (p + 0.29 * drift) + vec2(11.0, 7.0), t, 0.061, 0.27, 0.0,
vec3(0.26, 0.39, 0.56));
color += particleLayer(18.0 * (p + 0.64 * drift) + vec2(3.0, 19.0), t, 0.060, 0.25, 0.23,
vec3(0.48, 0.73, 0.90));
color += particleLayer(9.0 * (p + drift), t, 0.087, 0.17, 1.0, vec3(0.69, 0.83, 0.95));
return clamp(color / (1.0 + 0.20 * dot(p, p)), 0.0, 1.0);
}
)glsl";
constexpr const char* kMetaballs = R"glsl(
void metaballField(vec2 offset, float inverseRadius2, inout float field, inout vec2 slope) {
float falloff = max(1.0 - dot(offset, offset) * inverseRadius2, 0.0);
float falloff2 = falloff * falloff;
field += falloff2 * falloff;
slope -= offset * (6.0 * inverseRadius2 * falloff2);
}
vec3 scene(vec2 p, vec2 uv, float t) {
float phase = t * 0.89;
vec2 orbit = vec2(cos(phase), sin(phase));
vec2 inner = vec2(cos(phase * 1.72), sin(phase * 1.72));
vec2 swing = vec2(cos(phase * 0.66), sin(phase * 0.66));
float field = 0.0;
vec2 slope = vec2(0.0);
metaballField(p - orbit * vec2(0.90, 0.46), 2.20, field, slope);
metaballField(p + orbit.yx * vec2(0.55, 0.58), 2.61, field, slope);
metaballField(p + orbit * vec2(0.85, 0.37) - vec2(0.03, 0.18), 3.25, field, slope);
metaballField(p - inner * vec2(0.69, 0.56), 3.56, field, slope);
metaballField(p - swing.yx * vec2(1.10, 0.64) + vec2(0.14, 0.21), 4.53, field, slope);
const float iso = 0.35;
float aa = max(fwidth(field), 0.002);
float surface = smoothstep(iso - aa, iso + aa, field);
// The analytic gradient gives a steep rim and a rounded interior.
vec3 normal = normalize(vec3(-0.17 * slope, sqrt(max(field - iso + 0.018, 0.018))));
vec3 lightDir = vec3(-0.42, 0.56, 0.714);
vec3 halfwayDir = vec3(-0.227, 0.302, 0.926);
float diffuse = max(dot(normal, lightDir), 0.0);
float gloss = pow(max(dot(normal, halfwayDir), 0.0), 34.0);
float rim = 1.0 - normal.z;
vec3 liquid = mix(vec3(0.025, 0.24, 0.36), vec3(0.52, 0.83, 0.19), diffuse);
liquid += vec3(0.72, 0.93, 0.70) * gloss * 0.77;
liquid += vec3(0.06, 0.60, 0.41) * rim * rim;
float ripple = 0.5 + 0.5 * sin(13.0 * field - t * 1.55 + 4.0 * dot(p, p));
float halo = smoothstep(0.0, iso, field);
vec3 background = vec3(0.024, 0.046, 0.085) + vec3(0.035, 0.19, 0.20) * halo * ripple;
background /= 1.0 + 0.18 * dot(p, p);
return clamp(mix(background, liquid, surface), 0.0, 1.0);
}
)glsl";
constexpr const char* kPrism = R"glsl(
vec3 prismToLocal(vec3 v, vec2 spin, vec2 tilt, vec2 pitch) {
vec2 yz = mat2(pitch.x, pitch.y, -pitch.y, pitch.x) * v.yz;
vec2 xy = mat2(tilt.x, tilt.y, -tilt.y, tilt.x) * vec2(v.x, yz.x);
vec2 xz = mat2(spin.x, spin.y, -spin.y, spin.x) * vec2(xy.x, yz.y);
return vec3(xz.x, xy.y, xz.y);
}
vec4 prismProjections(vec3 v) {
return vec4(v.x, 0.5 * v.x + 0.8660254 * v.z, -0.5 * v.x + 0.8660254 * v.z, v.y);
}
vec3 scene(vec2 p, vec2 uv, float t) {
vec3 camera = vec3(0.0, 0.13, 3.74);
vec3 ray = normalize(vec3(p.x, p.y - 0.08, -1.87));
float skyGlow = 1.0 - smoothstep(0.08, 2.46, dot(p - vec2(0.0, 0.26), p - vec2(0.0, 0.26)));
vec3 background = mix(vec3(0.048, 0.022, 0.035), vec3(0.19, 0.10, 0.13), skyGlow);
// Fade the projected floor grid before it reaches the horizon.
float floorDistance = (camera.y + 1.20) / max(-ray.y, 0.001);
vec2 floorPosition = camera.xz + floorDistance * ray.xz;
vec2 grid = abs(fract(floorPosition * 1.5 + 0.5) - 0.5);
vec2 gridAA = max(fwidth(floorPosition * 1.5), vec2(0.001));
vec2 lines = 1.0 - smoothstep(vec2(0.015), gridAA + 0.015, grid);
vec2 shadowOffset = floorPosition * vec2(0.86, 0.97);
float shadow = 1.0 - smoothstep(0.08, 1.04, dot(shadowOffset, shadowOffset));
vec3 floorColor = vec3(0.102, 0.061, 0.086) + vec3(0.12, 0.066, 0.064) * max(lines.x, lines.y);
floorColor *= 1.0 - 0.70 * shadow;
background = mix(background, floorColor, 1.0 - smoothstep(4.6, 13.0, floorDistance));
float spinAngle = t * 0.83 + 0.28;
float tiltAngle = 0.28 + 0.30 * sin(t * 0.76 + 0.13);
float pitchAngle = 0.52 * sin(t * 0.98 - 0.22);
vec2 spin = vec2(cos(spinAngle), sin(spinAngle));
vec2 tilt = vec2(cos(tiltAngle), sin(tiltAngle));
vec2 pitch = vec2(cos(pitchAngle), sin(pitchAngle));
vec3 localCamera = prismToLocal(camera, spin, tilt, pitch);
vec3 localRay = prismToLocal(ray, spin, tilt, pitch);
// A hexagonal prism is the intersection of three side slabs and one cap slab.
const vec4 extent = vec4(0.66, 0.66, 0.66, 0.79);
vec4 origin = prismProjections(localCamera);
vec4 direction = prismProjections(localRay);
vec4 directionSign = mix(vec4(-1.0), vec4(1.0), step(vec4(0.0), direction));
vec4 inverseDirection = directionSign / max(abs(direction), vec4(0.00001));
vec4 nearPlane = (-extent * directionSign - origin) * inverseDirection;
vec4 farPlane = (extent * directionSign - origin) * inverseDirection;
float enter = max(max(nearPlane.x, nearPlane.y), max(nearPlane.z, nearPlane.w));
float leave = min(min(farPlane.x, farPlane.y), min(farPlane.z, farPlane.w));
if (enter <= 0.0 || leave < enter) {
return background;
}
vec3 hit = localCamera + localRay * enter;
vec4 clearance = extent - abs(prismProjections(hit));
vec3 normal;
if (enter == nearPlane.x) {
normal = vec3(-directionSign.x, 0.0, 0.0);
clearance.x = 1.0;
} else if (enter == nearPlane.y) {
normal = -directionSign.y * vec3(0.5, 0.0, 0.8660254);
clearance.y = 1.0;
} else if (enter == nearPlane.z) {
normal = -directionSign.z * vec3(-0.5, 0.0, 0.8660254);
clearance.z = 1.0;
} else {
normal = vec3(0.0, -directionSign.w, 0.0);
clearance.w = 1.0;
}
float edge = min(min(clearance.x, clearance.y), min(clearance.z, clearance.w));
float frame = 1.0 - smoothstep(0.069, 0.078, edge);
float border = 1.0 - smoothstep(0.015, 0.027, edge);
float inlay = 1.0 - smoothstep(0.004, 0.012, abs(edge - 0.107));
float capInlay = abs(normal.y) * (1.0 - smoothstep(0.005, 0.014, abs(edge - 0.30)));
vec3 lightDir = prismToLocal(vec3(-0.38, 0.60, 0.7068), spin, tilt, pitch);
float diffuse = max(dot(normal, lightDir), 0.0);
float specular = pow(max(dot(normal, normalize(lightDir - localRay)), 0.0), 24.0);
float fresnel = 1.0 - max(dot(normal, -localRay), 0.0);
float faceHue = 0.5 + dot(normal, vec3(0.30, 0.12, 0.26));
vec3 enamel = mix(vec3(0.19, 0.17, 0.36), vec3(0.13, 0.43, 0.45), faceHue);
enamel *= 1.0 + 0.28 * hit.y;
vec3 brass = mix(vec3(0.57, 0.24, 0.08), vec3(1.0, 0.66, 0.27), border);
vec3 material = mix(enamel, brass, max(frame, 0.74 * max(inlay, capInlay)));
vec3 color = material * (0.28 + diffuse * 0.76) + vec3(0.42, 0.31, 0.19) * specular;
color += vec3(0.13, 0.075, 0.048) * fresnel * fresnel;
return clamp(mix(background, color, smoothstep(0.0, 0.013, leave - enter)), 0.0, 1.0);
}
)glsl";
@@ -0,0 +1,358 @@
// MobileGL - MobileGL/MG_Util/SelfTest/AndroidTestLandscapeScenes.inc
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
constexpr const char* kAurora = R"glsl(
float auroraHash(vec2 cell) {
vec3 v = fract(vec3(cell.xyx) * vec3(0.1031, 0.1030, 0.0973));
v += dot(v, v.yzx + 33.33);
return fract((v.x + v.y) * v.z);
}
vec3 auroraCurtain(vec2 p, float t, float height, float phase, vec3 tint) {
float x = p.x;
float fold = sin(2.6 * x - phase + 0.52 * t);
float hem = height + 0.14 * fold + 0.075 * sin(5.4 * x + phase - 0.31 * t);
float rise = p.y - hem;
float ray = 0.62 + 0.24 * sin(34.0 * x + 4.0 * fold - 1.6 * t + phase)
+ 0.14 * sin(59.0 * x - 8.0 * p.y + 1.2 * t);
float veil = smoothstep(-0.050, 0.022, rise)
* (1.0 - smoothstep(0.045, 0.40 + 0.08 * fold, rise));
float edge = 1.0 - smoothstep(0.0, 0.040, abs(rise));
vec3 high = mix(tint, vec3(0.37, 0.21, 0.72), smoothstep(0.08, 0.32, rise));
return high * veil * ray + 0.22 * tint * edge;
}
float auroraRidge(float x, float phase) {
return 0.095 * abs(sin(3.0 * x + phase))
+ 0.042 * abs(sin(8.0 * x - phase))
+ 0.018 * abs(sin(16.0 * x + phase));
}
vec3 scene(vec2 p, vec2 uv, float t) {
const float shore = -0.48;
float aa = fwidth(p.y);
bool reflection = p.y < shore;
float depth = max(shore - p.y, 0.0);
vec2 q = p;
if (reflection) {
float ripple = sin(103.0 * depth - 4.2 * t + 6.0 * p.x);
q = vec2(p.x + (0.011 + 0.05 * depth) * ripple, shore + 2.3 * depth);
}
vec3 sky = mix(vec3(0.080, 0.145, 0.233), vec3(0.017, 0.023, 0.087),
smoothstep(shore, 1.0, q.y));
if (!reflection) {
vec2 grid = q * 49.0;
vec2 cell = floor(grid);
float seed = auroraHash(cell);
vec2 offset = 0.48 * (vec2(seed, auroraHash(cell + 9.0)) - 0.5);
float star = 1.0 - smoothstep(0.021, 0.021 + 36.0 * aa,
length(fract(grid) - 0.5 - offset));
sky += vec3(0.60, 0.74, 1.0) * star * step(0.88, seed)
* (0.68 + 0.32 * sin(1.8 * t + 77.0 * seed));
vec2 moon = q - vec2(0.96, 0.65);
float rim = 1.0 - smoothstep(0.096 - aa, 0.096 + aa, length(moon));
float shadow = smoothstep(0.088 - aa, 0.088 + aa, length(moon - vec2(-0.035, 0.024)));
sky += vec3(0.55, 0.66, 0.84) * rim * shadow;
sky += vec3(0.05, 0.071, 0.12) * (1.0 - smoothstep(0.08, 0.26, length(moon)));
}
sky += auroraCurtain(q, t, 0.26, 3.8, vec3(0.28, 0.19, 0.53));
sky += auroraCurtain(q, t, 0.12, 1.7, vec3(0.13, 0.57, 0.43));
sky += auroraCurtain(q, t, -0.06, 0.3, vec3(0.20, 0.83, 0.62));
float farPeaks = shore + 0.09 + 1.45 * auroraRidge(q.x, 1.0);
float nearPeaks = shore + 0.024 + auroraRidge(q.x + 0.43, 2.7);
sky = mix(sky, vec3(0.10, 0.15, 0.23), 1.0 - smoothstep(farPeaks - aa, farPeaks + aa, q.y));
sky = mix(sky, vec3(0.035, 0.051, 0.10), 1.0 - smoothstep(nearPeaks - aa, nearPeaks + aa, q.y));
if (reflection) {
float crest = sin(170.0 * depth - 5.0 * t + 5.0 * p.x);
sky = mix(vec3(0.023, 0.050, 0.094), sky, (0.64 + 0.10 * crest) * (1.0 - 0.9 * depth));
}
return clamp(sky * (0.85 + 0.15 * sin(3.14159 * uv.x)), 0.0, 1.0);
}
)glsl";
constexpr const char* kOcean = R"glsl(
float oceanCloud(vec2 p, float t, float height, float phase) {
float x = 3.3 * p.x - 0.11 * t + phase;
float fold = sin(x) + 0.41 * sin(2.8 * x - phase);
float center = height + 0.038 * fold;
float body = 1.0 - smoothstep(0.012, 0.083, abs(p.y - center));
return body * smoothstep(-0.55, 0.95, fold);
}
vec3 scene(vec2 p, vec2 uv, float t) {
const float horizon = -0.20;
const vec2 sunCenter = vec2(-0.38, 0.044);
const float sunRadius = 0.23;
float aa = fwidth(p.y);
vec2 sun = p - sunCenter;
if (p.y >= horizon) {
vec3 sky = mix(vec3(0.99, 0.34, 0.22), vec3(0.14, 0.085, 0.30),
smoothstep(horizon, 0.97, p.y));
sky += vec3(0.24, 0.14, 0.023) * (1.0 - smoothstep(0.19, 1.06, length(sun)));
float disc = 1.0 - smoothstep(sunRadius - aa, sunRadius + aa, length(sun));
vec3 sunlight = mix(vec3(1.0, 0.54, 0.20), vec3(1.0, 0.95, 0.65),
smoothstep(-sunRadius, 0.17, sun.y));
sky = mix(sky, sunlight, disc);
float lowerCloud = oceanCloud(p, t, -0.075, 2.0);
float upperCloud = oceanCloud(p, t, 0.52, 0.1)
+ 0.60 * oceanCloud(p, t, 0.66, 2.9);
sky = mix(sky, vec3(0.54, 0.21, 0.29), 0.60 * lowerCloud);
sky = mix(sky, vec3(0.30, 0.13, 0.32), 0.62 * upperCloud);
return clamp(sky, 0.0, 1.0);
}
// Inverse depth compresses the crests toward the horizon.
float depth = horizon - p.y;
float along = p.x / (depth + 0.16);
float distance = 1.0 / (depth + 0.090);
float swell = sin(6.1 * distance + 0.9 * sin(0.85 * along) - 2.8 * t);
float chop = sin(19.0 * distance - 1.5 * along + 3.6 * t);
float crossing = sin(9.5 * distance + 2.4 * along - 1.8 * t);
float crest = 0.56 * swell + 0.29 * chop + 0.15 * crossing;
float visibility = smoothstep(0.016, 0.15, depth);
vec3 water = mix(vec3(0.31, 0.16, 0.30), vec3(0.054, 0.115, 0.245),
smoothstep(0.0, 0.66, depth));
water += vec3(0.19, 0.15, 0.28) * (0.5 + 0.5 * crest) * visibility;
water += vec3(0.33, 0.19, 0.25) * smoothstep(0.61, 0.94, crest) * visibility;
float gold = abs(sun.x + (0.025 + 0.20 * depth) * (chop + 0.55 * crossing));
float spread = 0.13 + 0.52 * depth;
float trail = (1.0 - smoothstep(0.025, spread, gold))
* mix(0.30, 0.82 * smoothstep(-0.17, 0.79, crest), visibility);
water += vec3(1.0, 0.52, 0.19) * trail;
water = mix(water, vec3(0.67, 0.31, 0.31), 0.31 * (1.0 - smoothstep(0.0, 0.021, depth)));
return clamp(water, 0.0, 1.0);
}
)glsl";
constexpr const char* kDunes = R"glsl(
float duneProfile(float x, float phase) {
return 0.14 * sin(2.2 * x + phase) + 0.066 * sin(4.8 * x - phase)
+ 0.021 * sin(8.1 * x + 0.7 * phase);
}
vec3 scene(vec2 p, vec2 uv, float t) {
float aa = fwidth(p.y);
vec3 color = mix(vec3(0.93, 0.78, 0.60), vec3(0.23, 0.60, 0.66),
smoothstep(-0.28, 0.98, p.y));
vec2 toSun = p - vec2(0.76, 0.48);
float sunDistance = length(toSun);
color += vec3(0.17, 0.11, 0.03) * (1.0 - smoothstep(0.08, 0.57, sunDistance));
color = mix(color, vec3(1.0, 0.89, 0.64),
1.0 - smoothstep(0.101 - aa, 0.101 + aa, sunDistance));
float highCloud = p.y - 0.67 - 0.055 * sin(2.3 * p.x - 0.12 * t);
float cloud = (1.0 - smoothstep(0.012, 0.056, abs(highCloud)))
* smoothstep(0.2, 0.95, sin(2.3 * p.x + 1.0 - 0.10 * t));
color = mix(color, vec3(0.98, 0.83, 0.70), 0.19 * cloud);
float farDune = -0.15 + duneProfile(0.86 * p.x, 3.4);
float middleDune = -0.34 + 1.3 * duneProfile(p.x, 1.7);
float closeDune = -0.59 + 1.12 * duneProfile(p.x + 0.25, -0.2);
float foreground = -0.81 + 1.28 * duneProfile(p.x + 0.16, 3.0);
color = mix(color, vec3(0.75, 0.42, 0.31),
1.0 - smoothstep(farDune - aa, farDune + aa, p.y));
color = mix(color, mix(vec3(0.94, 0.64, 0.34), vec3(0.70, 0.35, 0.25),
smoothstep(0.0, 0.22, middleDune - p.y)),
1.0 - smoothstep(middleDune - aa, middleDune + aa, p.y));
// A dark slip face follows the lee side of the close ridge.
float depth = max(closeDune - p.y, 0.0);
float lee = smoothstep(0.0, 0.064, depth) * smoothstep(-0.34, 0.10, p.x + 1.26 * depth);
vec3 nearSand = mix(vec3(0.95, 0.52, 0.24), vec3(0.57, 0.245, 0.175), lee);
float ripples = sin(101.0 * depth + 16.0 * p.x + 2.7 * sin(5.1 * p.x));
nearSand += vec3(0.060, 0.035, 0.020) * ripples * smoothstep(0.011, 0.11, depth);
color = mix(color, nearSand, 1.0 - smoothstep(closeDune - aa, closeDune + aa, p.y));
float frontDepth = max(foreground - p.y, 0.0);
float sandWave = max(sin(88.0 * frontDepth + 18.0 * p.x + 1.1 * sin(7.9 * p.x)), 0.0);
vec3 front = mix(vec3(0.95, 0.60, 0.30), vec3(0.63, 0.29, 0.18),
smoothstep(0.0, 0.24, frontDepth));
front += vec3(0.10, 0.064, 0.035) * sandWave * smoothstep(0.010, 0.09, frontDepth);
color = mix(color, front, 1.0 - smoothstep(foreground - aa, foreground + aa, p.y));
// Broad plumes lift above the ridge while thin streamers race along the sand.
float wind = p.x - 0.54 * t;
float gust = sin(5.7 * wind);
float dustCenter = closeDune + 0.058 + 0.036 * gust;
float dust = (1.0 - smoothstep(0.009, 0.098, abs(p.y - dustCenter)))
* smoothstep(-0.32, 0.95, gust + 0.32 * sin(13.0 * wind));
float stream = 0.030 * sin(7.0 * wind) + 0.016 * sin(17.0 * wind);
float drift = (1.0 - smoothstep(0.010, 0.082, abs(p.y - foreground + 0.045 - stream)))
* smoothstep(0.08, 0.95, sin(8.0 * wind + 0.4) + 0.24 * sin(23.0 * wind));
color = mix(color, vec3(1.0, 0.81, 0.55), 0.50 * dust + 0.44 * drift);
return clamp(color * (0.92 + 0.08 * uv.x), 0.0, 1.0);
}
)glsl";
constexpr const char* kCity = R"glsl(
float cityHash(vec2 cell) {
vec3 v = fract(vec3(cell.xyx) * vec3(0.1031, 0.1030, 0.0973));
v += dot(v, v.yzx + 33.33);
return fract((v.x + v.y) * v.z);
}
vec3 cityBlock(vec3 sky, vec2 p, float t, float aa, float row) {
float pitch = mix(6.1, 10.3, row);
float block = p.x * pitch + row * 5.68;
float id = floor(block);
float seed = cityHash(vec2(id, row));
float local = fract(block) - 0.5;
float width = 0.29 + 0.19 * cityHash(vec2(id, row + 11.7));
float height = mix(0.15, 0.80, seed) + 0.14 * row;
float crown = mix(0.042, 0.12, seed);
float tint = cityHash(vec2(id, row + 24.1));
vec3 neon = mix(vec3(0.11, 0.81, 0.96), vec3(0.99, 0.20, 0.55), step(0.58, tint));
vec3 wall = mix(vec3(0.024, 0.031, 0.089), vec3(0.069, 0.046, 0.143), row);
// The setback and a narrow service face give the tower an uneven outline.
float side = (abs(local) - width) / pitch;
float body = max(side, p.y - height);
float roof = max((abs(local + 0.054) - width * 0.56) / pitch, p.y - height - crown);
float silhouette = min(body, roof);
float building = 1.0 - smoothstep(-aa, aa, silhouette);
float service = smoothstep(width * 0.27, width * 0.52, local);
wall *= 1.0 - 0.45 * service;
vec2 panes = vec2((local + 0.5) * 5.0, p.y * mix(23.0, 31.0, row));
vec2 pane = abs(fract(panes) - 0.5);
float window = (1.0 - smoothstep(0.26, 0.41, pane.x))
* (1.0 - smoothstep(0.15, 0.32, pane.y));
float occupancy = cityHash(floor(panes) + vec2(5.0 * id, 13.0 * row));
float blink = 0.76 + 0.24 * sin(0.9 * t + 31.0 * occupancy);
wall += neon * step(0.49 + 0.12 * row, occupancy) * window * blink * (0.43 - 0.20 * service);
float edge = 1.0 - smoothstep(aa, aa + 0.009, abs(silhouette));
float sign = (1.0 - smoothstep(0.07, 0.10, abs(local + 0.16)))
* (1.0 - smoothstep(0.042, 0.050, abs(p.y - height + 0.13)));
wall += neon * (0.54 * edge + 0.71 * sign * step(0.78, tint));
sky = mix(sky, wall, building);
float antenna = max(abs(local + 0.054) / pitch, abs(p.y - height - crown - 0.059) - 0.059);
float antennaLight = length(vec2((local + 0.054) / pitch, p.y - height - crown - 0.119));
sky += neon * step(0.64, seed) * (0.59 * (1.0 - smoothstep(aa, aa + 0.003, antenna))
+ (0.54 + 0.40 * sin(2.8 * t + 11.0 * seed)) * (1.0 - smoothstep(0.003, 0.013, antennaLight)));
return sky;
}
vec3 scene(vec2 p, vec2 uv, float t) {
const float shore = -0.43;
float aa = fwidth(p.y);
float depth = max(shore - p.y, 0.0);
float ripple = sin(94.0 * depth - 4.8 * t + 4.1 * p.x);
vec2 q = vec2(p.x + 0.10 * depth * ripple, abs(p.y - shore));
q.y += 0.56 * depth;
vec3 color = mix(vec3(0.47, 0.19, 0.40), vec3(0.033, 0.030, 0.14),
smoothstep(0.0, 1.15, q.y));
vec2 moon = q - vec2(0.87, 1.07);
float moonDistance = length(moon);
color += vec3(0.21, 0.13, 0.30) * (1.0 - smoothstep(0.14, 0.76, moonDistance));
color = mix(color, vec3(0.82, 0.62, 0.85),
1.0 - smoothstep(0.154 - aa, 0.154 + aa, moonDistance));
if (q.y < 1.21) {
color = cityBlock(color, q - vec2(0.0, 0.12), t, aa, 1.0);
color = cityBlock(color, q, t, aa, 0.0);
}
if (depth > 0.0) {
float shimmer = 0.55 + 0.22 * ripple + 0.12 * sin(167.0 * depth + 3.9 * t);
color = mix(vec3(0.031, 0.045, 0.13), color, shimmer * (1.0 - 1.23 * depth));
}
float road = abs(p.y - shore);
float lane = 1.0 - smoothstep(aa, 0.007 + aa, road);
float traffic = smoothstep(0.857, 0.97, fract(1.89 * p.x - 0.62 * t + 0.07 * sin(11.0 * p.x)));
float headlights = smoothstep(0.92, 0.99, fract(2.8 * p.x + 0.82 * t));
color += lane * (vec3(0.13, 0.43, 0.58) + vec3(0.63, 0.10, 0.30) * traffic
+ vec3(0.41, 0.50, 0.43) * headlights);
return clamp(color * (0.92 + 0.08 * sin(3.14159 * uv.x)), 0.0, 1.0);
}
)glsl";
constexpr const char* kOrbit = R"glsl(
float orbitHash(vec2 cell) {
vec3 v = fract(vec3(cell.xyx) * vec3(0.1031, 0.1030, 0.0973));
v += dot(v, v.yzx + 33.33);
return fract((v.x + v.y) * v.z);
}
vec3 scene(vec2 p, vec2 uv, float t) {
const vec2 center = vec2(-0.62, -0.22);
const float radius = 0.79;
const vec3 light = vec3(0.86, 0.41, 0.30);
float aa = fwidth(p.y);
vec2 q = p - center;
float orb = length(q);
float galaxy = p.y - 0.38 * p.x - 0.50;
vec3 color = vec3(0.019, 0.019, 0.061);
color += vec3(0.15, 0.09, 0.19) * (1.0 - smoothstep(0.0, 0.46, abs(galaxy)))
* (0.61 + 0.39 * sin(3.7 * p.x + 0.7 * sin(7.0 * galaxy)));
if (orb > radius - aa) {
vec2 grid = p * 42.0;
vec2 cell = floor(grid);
float seed = orbitHash(cell);
vec2 shift = 0.49 * (vec2(seed, orbitHash(cell + 21.0)) - 0.5);
float size = 0.024 + 0.095 * smoothstep(0.94, 1.0, seed);
float star = 1.0 - smoothstep(size, size + 29.0 * aa, length(fract(grid) - 0.5 - shift));
vec3 starlight = mix(vec3(0.43, 0.64, 0.94), vec3(1.0, 0.77, 0.55), orbitHash(cell - 33.0));
color += starlight * star * step(0.83, seed) * (0.71 + 0.29 * sin(2.2 * t + 54.0 * seed));
}
// Draw the back half of the ring before the globe and the front half afterward.
vec2 ring = vec2(dot(q, vec2(0.9659, 0.2588)), dot(q, vec2(-0.2588, 0.9659)));
float ringRadius = length(vec2(ring.x, ring.y * 3.8));
float ringMask = smoothstep(0.98, 1.014, ringRadius) * (1.0 - smoothstep(1.35, 1.40, ringRadius));
float ringDivision = 1.0 - smoothstep(0.014, 0.024, abs(ringRadius - 1.25));
float ringBand = 0.65 + 0.21 * sin(110.0 * ringRadius) + 0.14 * sin(183.0 * ringRadius);
vec3 ringColor = mix(vec3(0.33, 0.33, 0.63), vec3(0.89, 0.65, 0.47),
smoothstep(-1.2, 0.86, ring.x));
float ringAlpha = ringMask * (0.36 + 0.60 * ringBand) * (1.0 - 0.78 * ringDivision);
if (ring.y >= 0.0) color = mix(color, ringColor, ringAlpha);
float limbLight = smoothstep(-0.24, 0.77, dot(q, light.xy));
float halo = 1.0 - smoothstep(0.0, 0.117, abs(orb - radius));
color += vec3(0.25, 0.51, 0.88) * halo * halo * limbLight;
if (orb < radius + aa) {
vec2 disk = q / radius;
float face = sqrt(max(1.0 - dot(disk, disk), 0.0));
vec3 normal = vec3(disk, face);
float lit = max(0.0, dot(normal, light));
float latitude = dot(normal, vec3(-0.21, 0.91, 0.34));
float current = 0.49 * sin(19.0 * latitude + 3.2 * disk.x + 1.1 * face - 0.84 * t);
float belts = sin(31.0 * latitude + current) + 0.32 * sin(61.0 * latitude + 2.0 * current);
float filaments = sin(92.0 * latitude + 3.7 * current + 1.8 * disk.x + 0.52 * t);
vec3 gas = mix(vec3(0.079, 0.26, 0.52), vec3(0.38, 0.78, 0.82), smoothstep(-0.8, 1.0, belts));
gas += vec3(0.25, 0.26, 0.19) * smoothstep(0.47, 1.15, belts + 0.25 * filaments);
gas *= 0.13 + 0.86 * sqrt(lit);
float rim = 1.0 - smoothstep(0.0, 0.22, face);
gas += vec3(0.35, 0.58, 0.96) * rim * limbLight;
color = mix(color, gas, 1.0 - smoothstep(radius - aa, radius + aa, orb));
}
if (ring.y < 0.0) color = mix(color, ringColor, ringAlpha);
vec2 moonCenter = vec2(0.94 + 0.13 * sin(0.41 * t), 0.46 + 0.08 * sin(0.41 * t + 1.2));
vec2 moon = (p - moonCenter) / 0.174;
float moonDisk = dot(moon, moon);
if (moonDisk < 1.0 + 12.0 * aa) {
float face = sqrt(max(1.0 - moonDisk, 0.0));
float illumination = max(0.0, dot(vec3(moon, face), vec3(0.67, 0.45, 0.55)));
float craters = (1.0 - smoothstep(0.22, 0.42, length(moon - vec2(0.30, 0.25))))
+ (1.0 - smoothstep(0.14, 0.28, length(moon - vec2(-0.43, -0.26))))
+ (1.0 - smoothstep(0.10, 0.22, length(moon - vec2(0.62, -0.37))));
vec3 surface = vec3(0.65, 0.57, 0.69) * (0.12 + 0.88 * illumination) * (1.0 - 0.39 * craters);
color = mix(color, surface, 1.0 - smoothstep(1.0 - 12.0 * aa, 1.0 + 12.0 * aa, moonDisk));
}
return clamp(color * (0.94 + 0.06 * sin(3.14159 * uv.x)), 0.0, 1.0);
}
)glsl";
@@ -0,0 +1,86 @@
// MobileGL - MobileGL/MG_Util/SelfTest/AndroidTestOceanHdr.inc
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
constexpr const char* kOceanSpectrum = R"glsl(
layout(local_size_x = 32) in;
layout(std430, binding = 0) writeonly buffer Spectrum { vec4 waves[]; };
uniform float uTime;
void main() {
uint index = gl_GlobalInvocationID.x;
if (index >= 24u) return;
float band = float(index);
float angle = band * 2.399963;
vec2 mode = round(vec2(cos(angle), sin(angle)) * (3.0 + band * 0.85));
float frequency = length(mode) * 0.196350;
float phase = band * 1.618034 - sqrt(frequency * 9.81) * uTime;
waves[index] = vec4(mode, phase, 0.045 * exp(-band * 0.081));
}
)glsl";
constexpr const char* kOceanSynthesis = R"glsl(
layout(local_size_x = 8, local_size_y = 8) in;
layout(std430, binding = 0) readonly buffer Spectrum { vec4 waves[]; };
layout(rgba32f, binding = 0) uniform writeonly image2D uWaveField;
void main() {
ivec2 cell = ivec2(gl_GlobalInvocationID.xy);
ivec2 size = imageSize(uWaveField);
if (any(greaterThanEqual(cell, size))) return;
vec2 angle = (vec2(cell) + 0.5) * 6.2831853 / vec2(size);
float displacement = 0.0;
vec2 slope = vec2(0.0);
float compression = 0.0;
for (int i = 0; i < 24; ++i) {
vec4 wave = waves[i];
float phase = dot(angle, wave.xy) + wave.z;
float crest = sin(phase) * wave.w;
displacement += crest;
slope += cos(phase) * wave.w * wave.xy * 0.196350;
compression += crest * dot(wave.xy, wave.xy) * 0.006;
}
imageStore(uWaveField, cell, vec4(displacement, slope, max(compression, 0.0)));
}
)glsl";
constexpr const char* kOceanHdrMain = R"glsl(
void main() {
vec2 uv = gl_FragCoord.xy / uExtent;
vec2 p = (2.0 * gl_FragCoord.xy - uExtent) / uExtent.y;
outColor = vec4(scene(p, uv, uTime), 1.0);
}
)glsl";
constexpr const char* kOceanPost = R"glsl(
layout(binding = 1) uniform sampler2D uRadiance;
vec3 oceanHighlight(vec3 light) {
float luminance = dot(light, vec3(0.2126, 0.7152, 0.0722));
return light * smoothstep(0.75, 3.5, luminance);
}
void main() {
vec2 uv = gl_FragCoord.xy / uExtent;
vec2 texel = 1.0 / uExtent;
vec3 radiance = texture(uRadiance, uv).rgb;
vec3 glare = vec3(0.0);
const vec2 axes[4] = vec2[4](vec2(1, 0), vec2(0, 1), vec2(0.707, 0.707), vec2(-0.707, 0.707));
for (int i = 0; i < 4; ++i) {
vec2 offset = axes[i] * texel;
glare += 0.04 * oceanHighlight(texture(uRadiance, uv + offset * 5.0).rgb);
glare += 0.04 * oceanHighlight(texture(uRadiance, uv - offset * 5.0).rgb);
glare += 0.025 * oceanHighlight(texture(uRadiance, uv + offset * 17.0).rgb);
glare += 0.025 * oceanHighlight(texture(uRadiance, uv - offset * 17.0).rgb);
glare += 0.014 * oceanHighlight(texture(uRadiance, uv + offset * 42.0).rgb);
glare += 0.014 * oceanHighlight(texture(uRadiance, uv - offset * 42.0).rgb);
}
vec3 hdr = max(vec3(0.0), 1.09 * radiance + 0.54 * glare * vec3(1.0, 0.82, 0.62));
vec3 mapped = (hdr * (2.51 * hdr + 0.03)) / (hdr * (2.43 * hdr + 0.59) + 0.14);
outColor = vec4(pow(clamp(mapped, 0.0, 1.0), vec3(1.0 / 2.2)), 1.0);
}
)glsl";
@@ -0,0 +1,195 @@
// MobileGL - MobileGL/MG_Util/SelfTest/AndroidTestOceanSunrise.inc
// Copyright (c) 2025-2026 MobileGL-Dev
// Licensed under the GNU Lesser General Public License v3.0:
// https://www.gnu.org/licenses/gpl-3.0.txt
// https://www.gnu.org/licenses/lgpl-3.0.txt
// SPDX-License-Identifier: LGPL-3.0-only
// End of Source File Header
constexpr const char* kOceanSunrise = R"glsl(
const vec3 sunriseSun = vec3(-0.1432, 0.0678, 0.9874);
const vec3 sunriseLight = vec3(1.0, 0.54, 0.23);
#ifdef MOBILEGL_OCEAN_HDR
layout(binding = 0) uniform sampler2D uCapillaryWaves;
#endif
float sunriseHash(vec3 cell) {
vec3 p = fract(cell * vec3(0.1031, 0.11369, 0.13787));
p += dot(p, p.yzx + 19.19);
return fract((p.x + p.y) * p.z);
}
float sunriseNoise(vec3 p) {
vec3 cell = floor(p);
vec3 f = fract(p);
vec3 u = f * f * (3.0 - 2.0 * f);
float a = mix(sunriseHash(cell), sunriseHash(cell + vec3(1, 0, 0)), u.x);
float b = mix(sunriseHash(cell + vec3(0, 1, 0)), sunriseHash(cell + vec3(1, 1, 0)), u.x);
float c = mix(sunriseHash(cell + vec3(0, 0, 1)), sunriseHash(cell + vec3(1, 0, 1)), u.x);
float d = mix(sunriseHash(cell + vec3(0, 1, 1)), sunriseHash(cell + vec3(1, 1, 1)), u.x);
return mix(mix(a, b, u.y), mix(c, d, u.y), u.z);
}
float sunriseCloudDensity(vec3 point, float time) {
float height = clamp((point.y - 40.0) / 58.0, 0.0, 1.0);
float profile = smoothstep(0.0, 0.24, height) * (1.0 - smoothstep(0.48, 1.0, height));
vec3 p = point * vec3(0.017, 0.032, 0.017) + vec3(8.3 - 0.045 * time, -2.0, 3.7);
float cover = sunriseNoise(vec3(p.xz * 0.61, 3.5));
float billow = 0.60 * sunriseNoise(p) + 0.26 * sunriseNoise(p * 2.03 + 5.1)
+ 0.10 * sunriseNoise(p * 4.13 - 2.7) + 0.04 * sunriseNoise(p * 8.23 + 7.4);
return max(0.0, billow - mix(0.64, 0.37, cover)) * profile * 2.6;
}
vec3 sunriseAtmosphere(vec3 ray, bool sunDisk) {
float elevation = max(0.0, ray.y);
float alignment = clamp(dot(ray, sunriseSun), 0.0, 1.0);
float horizon = exp(-elevation * 7.0);
vec3 zenith = mix(vec3(0.045, 0.18, 0.36), vec3(0.16, 0.30, 0.49), horizon);
vec3 dawn = mix(vec3(0.39, 0.20, 0.18), vec3(1.14, 0.46, 0.16), pow(alignment, 5.0));
vec3 sky = mix(zenith, dawn, horizon * 0.73);
sky += sunriseLight * (0.37 * pow(alignment, 24.0) + 0.95 * pow(alignment, 162.0));
if (sunDisk) {
float sunMask = smoothstep(0.99963, 0.99971, alignment);
sky += vec3(9.2, 5.2, 2.45) * sunMask;
}
return sky;
}
vec3 sunriseClouds(vec3 sky, vec3 origin, vec3 ray, float time, int steps) {
if (ray.y < 0.012) return sky;
float entry = max(0.0, (40.0 - origin.y) / ray.y);
float exit = min(1500.0, (98.0 - origin.y) / ray.y);
if (exit <= entry) return sky;
float stepLength = (exit - entry) / float(steps);
float transmission = 1.0;
vec3 cloud = vec3(0.0);
float jitter = 0.32 + 0.36 * sunriseHash(vec3(gl_FragCoord.xy, 17.0));
for (int i = 0; i < 36; ++i) {
if (i >= steps || transmission < 0.014) break;
float distanceToSample = entry + (float(i) + jitter) * stepLength;
vec3 point = origin + ray * distanceToSample;
float density = sunriseCloudDensity(point, time);
if (density < 0.008) continue;
float lightDensity = sunriseCloudDensity(point + 11.0 * sunriseSun + vec3(0, 4, 0), time);
float lightDepth = sunriseCloudDensity(point + 26.0 * sunriseSun + vec3(0, 8, 0), time);
float light = exp(-4.8 * lightDensity - 2.5 * lightDepth);
float edge = clamp((density - lightDensity) * 2.6, 0.0, 1.0);
float phase = pow(max(0.0, dot(ray, sunriseSun)), 7.0);
vec3 ambient = vec3(0.17, 0.23, 0.35);
vec3 scatter = ambient + sunriseLight * (light * (0.45 + 1.65 * phase) + edge * 0.32);
scatter = mix(sky * 0.76, scatter, exp(-distanceToSample * 0.0011));
float opacity = 1.0 - exp(-0.086 * density * stepLength);
cloud += transmission * opacity * scatter;
transmission *= 1.0 - opacity;
}
return sky * transmission + cloud;
}
// The same spectrum drives the intersection and the analytic surface normal.
vec3 sunriseWave(vec2 position, float time, int bands, float detail) {
const mat2 turn = mat2(0.7648, 0.6442, -0.6442, 0.7648);
vec2 direction = vec2(0.270, 0.963);
float frequency = 0.47;
float amplitude = 0.55;
vec3 field = vec3(0.0);
for (int i = 0; i < 14; ++i) {
if (i >= bands) break;
float phase = frequency * dot(position, direction) - sqrt(9.81 * frequency) * time
+ float(i * i) * 0.82;
float wave = sin(phase);
float harmonic = cos(2.0 * phase);
float fade = i < 8 ? 1.0 : detail;
field.x += fade * amplitude * (wave - 0.20 * harmonic);
field.yz += fade * amplitude * frequency * direction * (cos(phase) + 0.40 * sin(2.0 * phase));
direction = turn * direction;
frequency *= 1.56;
amplitude *= 0.53;
}
return field;
}
float sunriseSurfaceDistance(vec3 origin, vec3 ray, float time) {
float entry = (origin.y - 1.45) / -ray.y;
if (entry > 190.0) return origin.y / -ray.y;
float lo = max(0.0, entry);
float hi = lo;
for (int i = 0; i < 32; ++i) {
vec3 point = origin + ray * hi;
float gap = point.y - sunriseWave(point.xz, time, 8, 0.0).x;
if (gap <= 0.0) {
for (int refine = 0; refine < 7; ++refine) {
float mid = 0.5 * (lo + hi);
vec3 probe = origin + ray * mid;
if (probe.y > sunriseWave(probe.xz, time, 8, 0.0).x) lo = mid;
else hi = mid;
}
return 0.5 * (lo + hi);
}
lo = hi;
hi += max(0.045, gap / (-ray.y + 0.84));
}
return origin.y / -ray.y;
}
vec3 sunriseWater(vec3 origin, vec3 ray, float time) {
float distanceToSurface = sunriseSurfaceDistance(origin, ray, time);
vec3 point = origin + ray * distanceToSurface;
float detail = 1.0 - smoothstep(35.0, 195.0, distanceToSurface);
vec3 wave = sunriseWave(point.xz, time, 14, detail);
#ifdef MOBILEGL_OCEAN_HDR
vec4 ripples = texture(uCapillaryWaves, fract(point.xz / 32.0));
wave.x += ripples.x * 0.18 * detail;
wave.yz += ripples.yz * 0.25 * detail;
#endif
float swell = 1.0 - smoothstep(75.0, 470.0, distanceToSurface);
vec3 normal = normalize(vec3(-wave.y * swell, 1.0, -wave.z * swell));
float facing = clamp(dot(-ray, normal), 0.0, 1.0);
vec3 reflection = reflect(ray, normal);
reflection.y = max(reflection.y, 0.007);
reflection = normalize(reflection);
vec3 sky = sunriseAtmosphere(reflection, false);
sky = sunriseClouds(sky, point, reflection, time, 16);
float fresnel = 0.02 + 0.98 * pow(1.0 - facing, 5.0);
float waveLight = max(0.0, dot(normal, sunriseSun));
vec3 body = vec3(0.012, 0.062, 0.082) + vec3(0.024, 0.26, 0.23)
* (0.22 + 0.78 * waveLight) * clamp(wave.x + 0.58, 0.0, 1.0);
vec3 halfVector = normalize(sunriseSun - ray);
float sunDot = clamp(dot(normal, halfVector), 0.0, 1.0);
float streak = 1.5 * pow(sunDot, 98.0) + 7.4 * pow(sunDot, 570.0);
streak *= (0.19 + 0.81 * smoothstep(0.0, 0.14, waveLight))
* (1.0 - 0.65 * smoothstep(65.0, 350.0, distanceToSurface));
float crest = smoothstep(0.76, 1.12, wave.x) * smoothstep(0.20, 0.70, length(wave.yz));
float bubbles = sunriseNoise(vec3(point.xz * 2.9, time * 0.65));
float foam = crest * smoothstep(0.44, 0.67, bubbles) * detail;
vec3 color = mix(body, 0.83 * sky, fresnel) + sunriseLight * streak;
#ifdef MOBILEGL_OCEAN_HDR
float subsurface = pow(max(dot(ray, sunriseSun), 0.0), 5.0) * (1.0 - facing);
color += vec3(0.035, 0.32, 0.22) * subsurface * smoothstep(0.08, 0.88, wave.x);
foam = max(foam, smoothstep(0.65, 0.94, wave.x + ripples.w * 0.24) * detail * 0.45);
#endif
color = mix(color, vec3(0.58, 0.72, 0.72) * (0.55 + 0.45 * waveLight), foam * 0.63);
vec3 mist = sunriseAtmosphere(normalize(vec3(ray.x, 0.008, ray.z)), false) * 0.84;
return mix(mist, color, exp(-distanceToSurface * 0.0027));
}
vec3 scene(vec2 p, vec2 uv, float t) {
float time = t + 4.0;
vec3 origin = vec3(0.22 * sin(time * 0.31), 2.55 + 0.14 * sin(time * 0.69), time * 0.23);
vec3 ray = normalize(vec3(p.x * 0.72, p.y * 0.72 - 0.18, 1.32));
vec3 radiance;
if (ray.y < -0.004) {
radiance = sunriseWater(origin, ray, time);
} else {
radiance = sunriseAtmosphere(ray, true);
radiance = sunriseClouds(radiance, origin, ray, time, 36);
}
float vignette = 1.0 - 0.23 * smoothstep(0.20, 0.72, length(uv - 0.5));
vec3 exposed = max(vec3(0.0), radiance * 1.12 * vignette);
#ifdef MOBILEGL_OCEAN_HDR
return exposed;
#else
vec3 mapped = (exposed * (2.51 * exposed + 0.03)) / (exposed * (2.43 * exposed + 0.59) + 0.14);
return pow(clamp(mapped, 0.0, 1.0), vec3(1.0 / 2.2));
#endif
}
)glsl";
+27 -20
View File
@@ -1,19 +1,26 @@
# MobileGL trace replay APK
# MobileGL trace replay on Android
The Android plugin app has two flavor dimensions:
## Replay from the Test page
- `backend`: `espryt` uses `DirectGLES`, `magma` uses `DirectVulkan`.
- `profile`: `plugin` keeps the original FCL plugin APK behavior, `trace` adds the standalone trace runner Activity.
In the Android app, open **Test**, set any **Environment** overrides, and tap **Replay trace…**.
Choose an apitrace file from Android’s file picker. Replay starts after the app copies the document
into its private cache. The Test page shows the snapshot from the last frame boundary, or from
the last call if the trace has no frame boundary. Tap **Cancel trace replay** to stop importing or
replaying. The app keeps the latest trace result and snapshot in its cache.
Useful debug builds:
Both the standard plugin and the trace APK include the replay library. Supply your own trace file.
## Run with adb
The `trace` profile exposes a standalone runner for adb and CI. It uses the `.trace` application
ID suffix. From the repository root, build either debug variant with the installed Gradle:
```sh
./gradlew -p MobileGL/android-plugin :app:assembleEsprytPluginDebug
./gradlew -p MobileGL/android-plugin :app:assembleEsprytTraceDebug
./gradlew -p MobileGL/android-plugin :app:assembleMagmaTraceDebug
gradle -p android-plugin :app:assemblePluginDebug
gradle -p android-plugin :app:assembleTraceDebug
```
The trace profile keeps the existing plugin manifest metadata and adds:
The trace profile exposes the following activity:
```text
action: top.mobilegl.plugin.TRACE_REPLAY
@@ -27,7 +34,7 @@ trace_path absolute path to the apitrace file
golden_path optional absolute path to a golden PNG
output_dir directory for result.json and actual.png
diff_path optional absolute path for a golden-difference PNG
backend DirectGLES or DirectVulkan; defaults to the backend flavor
backend DirectGLES (the default) or DirectVulkan
target_frame target frame index, or -1
target_call target call number, or -1
width optional replay surface width override
@@ -50,7 +57,7 @@ Implementation notes:
- The runner uses a MobileGL-backed EGL window-system shim. GLX calls in PC traces are consumed by apitrace's GLX retrace frontend and mapped onto this EGL shim; the Android runner does not require or call a MobileGL GLX implementation.
- `DirectGLES` and `DirectVulkan` replay on the Activity `SurfaceView` by default. DirectGLES can still use the old offscreen EGL pbuffer path by passing `use_pbuffer=true`.
- Golden comparison is implemented in native C++ with libpng RGBA decode and SSIM validation. The Java Activity only passes arguments and displays the native result, so the replay/compare core is not tied to Android UI or Bitmap APIs and can be ported to Linux.
- The plugin profile still excludes `libtrace_replay_runner.so`; normal plugin APK behavior is preserved.
- The standard plugin exposes replay through its private Test service.
- Set `MOBILEGL_ESPRYT_USE_ANGLE=1` and `MOBILEGL_TRACE_ANGLE_VARIANT=<short-hash>` when running `trace-replay-ci.sh` for DirectGLES. The trace APK contains both allowlisted ANGLE builds with short-hash filenames and SONAMEs; MobileGL resolves its signed native library directory and loads the selected pair by absolute path. Set `MOBILEGL_RETRACE_USE_PBUFFER=1` or pass `--use-pbuffer` to keep DirectGLES offscreen.
Example core-profile trace smoke command for a debug trace APK:
@@ -58,21 +65,21 @@ Example core-profile trace smoke command for a debug trace APK:
```sh
adb push app.trace /data/local/tmp/mobilegl_app.trace
adb push app.golden.png /data/local/tmp/mobilegl_app_ref.png
adb shell run-as top.mobilegl.plugin.espryt.trace mkdir -p files/trace-replay/input files/trace-replay/output
adb shell run-as top.mobilegl.plugin.espryt.trace cp /data/local/tmp/mobilegl_app.trace files/trace-replay/input/app.trace
adb shell run-as top.mobilegl.plugin.espryt.trace cp /data/local/tmp/mobilegl_app_ref.png files/trace-replay/input/app.golden.png
adb shell run-as top.mobilegl.plugin.trace mkdir -p files/trace-replay/input files/trace-replay/output
adb shell run-as top.mobilegl.plugin.trace cp /data/local/tmp/mobilegl_app.trace files/trace-replay/input/app.trace
adb shell run-as top.mobilegl.plugin.trace cp /data/local/tmp/mobilegl_app_ref.png files/trace-replay/input/app.golden.png
adb shell am start -a top.mobilegl.plugin.TRACE_REPLAY \
-n top.mobilegl.plugin.espryt.trace/top.mobilegl.plugin.trace.TraceReplayActivity \
--es trace_path /data/user/0/top.mobilegl.plugin.espryt.trace/files/trace-replay/input/app.trace \
--es golden_path /data/user/0/top.mobilegl.plugin.espryt.trace/files/trace-replay/input/app.golden.png \
--es output_dir /data/user/0/top.mobilegl.plugin.espryt.trace/files/trace-replay/output \
--es diff_path /data/user/0/top.mobilegl.plugin.espryt.trace/files/trace-replay/output/app-diff.png \
-n top.mobilegl.plugin.trace/top.mobilegl.plugin.trace.TraceReplayActivity \
--es trace_path /data/user/0/top.mobilegl.plugin.trace/files/trace-replay/input/app.trace \
--es golden_path /data/user/0/top.mobilegl.plugin.trace/files/trace-replay/input/app.golden.png \
--es output_dir /data/user/0/top.mobilegl.plugin.trace/files/trace-replay/output \
--es diff_path /data/user/0/top.mobilegl.plugin.trace/files/trace-replay/output/app-diff.png \
--es backend DirectGLES \
--ez use_angle true \
--es angle_variant ec889e6ea831 \
--el target_call 31249 \
--es ssim_threshold 0.99
adb shell run-as top.mobilegl.plugin.espryt.trace cat files/trace-replay/output/result.json
adb shell run-as top.mobilegl.plugin.trace cat files/trace-replay/output/result.json
```
## Emulator shards in CI
+43 -6
View File
@@ -126,7 +126,50 @@ val pluginRendererConfig = buildJsonValue {
)
}
val environmentSources = fileTree("../../MobileGL") {
include("**/*.cpp", "**/*.h", "**/*.inc", "**/*.hpp", "**/*.c")
exclude("MG_Test/**", "MG_IntegrationTest/**", "MG_Benchmark/**")
}
val environmentAssets = layout.buildDirectory.dir("generated/testEnvironment/assets")
val generateTestEnvironment = tasks.register("generateTestEnvironment") {
inputs.files(environmentSources)
outputs.dir(environmentAssets)
doLast {
val names = sortedSetOf("LIBGL_ES", "POJAV_RENDERER", "VK_ICD_FILENAMES", "VK_DRIVER_FILES", "VK_LAYER_PATH")
val types = mutableMapOf<String, String>()
val name = Regex(""""(MOBILEGL_[A-Z0-9_]+)"""")
val query = Regex("""QueryEnv(Flag|QuirkOverride|Uint32|MultiDrawMode|GLESMultiDrawMode)\s*\(\s*"(MOBILEGL_[A-Z0-9_]+)"""")
val choices = mapOf(
"Flag" to "Off=0|On=1",
"QuirkOverride" to "Auto|ForceOn|ForceOff",
"Uint32" to "number",
"MultiDrawMode" to "auto|ext|indirect|unroll",
"GLESMultiDrawMode" to "auto|ext|multiindirect|indirect|basevertex|drawelements|compute",
)
environmentSources.forEach { source ->
val text = source.readText()
name.findAll(text).forEach { names.add(it.groupValues[1]) }
query.findAll(text).forEach { types[it.groupValues[2]] = choices.getValue(it.groupValues[1]) }
}
types.putAll(mapOf(
"MOBILEGL_BACKEND_TYPE" to "DirectGLES|DirectVulkan",
"MOBILEGL_TRANSPORT" to "monolith|inproc|spawn",
"MOBILEGL_IPC_DATA" to "auto|shm|stream",
"MOBILEGL_IPC_SURFACE" to "offscreen|server",
"MOBILEGL_IPC_RECOVER" to choices.getValue("Flag"),
"MOBILEGL_FPS_LOG" to choices.getValue("Flag"),
"MOBILEGL_ES_CONTEXT_IDENTITY" to choices.getValue("Flag"),
))
names.remove("MOBILEGL_TEST_BACKEND_ENV_PRIORITY")
val asset = environmentAssets.get().file("test-environment.tsv").asFile
asset.parentFile.mkdirs()
asset.writeText(names.joinToString("\n", postfix = "\n") { "$it\t${types[it].orEmpty()}" })
}
}
tasks.named("preBuild").configure { dependsOn(generateTestEnvironment) }
android {
sourceSets.getByName("main").assets.srcDir(environmentAssets)
namespace = "top.mobilegl.plugin"
compileSdk = 34
ndkVersion = "27.3.13750724"
@@ -260,12 +303,6 @@ android.applicationVariants.configureEach {
}
}
androidComponents {
onVariants(selector().withFlavor("profile" to "plugin")) { variant ->
variant.packaging.jniLibs.excludes.add("**/libtrace_replay_runner.so")
}
}
dependencies {
implementation(project(":MobileGL"))
}
@@ -86,6 +86,15 @@
android:exported="false"
android:process=":bench" />
<activity
android:name=".TestActivity"
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|uiMode"
android:exported="false" />
<service
android:name=".TestService"
android:exported="false"
android:process=":test" />
<meta-data
android:name="fclPlugin_V2"
android:resource="@string/config" />
@@ -0,0 +1,176 @@
package top.mobilegl.plugin;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
final class EnvironmentOptions {
private static final String INHERIT = "Inherit";
private static final String UNSET = "Unset";
private static final String CUSTOM = "Custom value…";
private final Activity activity;
private final Runnable changed;
private final List<Option> catalog = new ArrayList<>();
private final Bundle overrides = new Bundle();
EnvironmentOptions(Activity activity, Runnable changed) {
this.activity = activity;
this.changed = changed;
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
activity.getAssets().open("test-environment.tsv"), StandardCharsets.UTF_8))) {
for (String line; (line = reader.readLine()) != null;) {
int tab = line.indexOf(' ');
if (tab >= 0) catalog.add(new Option(line.substring(0, tab), line.substring(tab + 1)));
}
} catch (IOException ignored) {
catalog.clear();
}
}
Bundle snapshot() {
return new Bundle(overrides);
}
void restore(Bundle state) {
if (state != null) overrides.putAll(state);
}
void show() {
if (catalog.isEmpty()) {
new AlertDialog.Builder(activity).setMessage("Environment options unavailable")
.setPositiveButton("Close", null).show();
return;
}
LinearLayout panel = new LinearLayout(activity);
panel.setOrientation(LinearLayout.VERTICAL);
SearchView search = new SearchView(activity);
search.setQueryHint("Search variables");
panel.addView(search);
ListView list = new ListView(activity);
int listHeight = activity.getResources().getDisplayMetrics().heightPixels / 2;
panel.addView(list, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, listHeight));
List<Option> visible = new ArrayList<>();
ArrayAdapter<String> adapter = new ArrayAdapter<>(activity, android.R.layout.simple_list_item_1);
list.setAdapter(adapter);
Runnable refresh = () -> {
String query = search.getQuery().toString().trim().toUpperCase(Locale.ROOT);
visible.clear();
adapter.setNotifyOnChange(false);
adapter.clear();
for (Option option : catalog) {
if (!option.name.contains(query)) continue;
visible.add(option);
adapter.add(option.name + "\n" + state(option));
}
adapter.notifyDataSetChanged();
};
search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override public boolean onQueryTextSubmit(String query) { return false; }
@Override public boolean onQueryTextChange(String query) {
refresh.run();
return true;
}
});
list.setOnItemClickListener((parent, view, position, id) -> edit(visible.get(position), refresh));
refresh.run();
new AlertDialog.Builder(activity).setTitle("Environment").setView(panel)
.setPositiveButton("Done", null).show();
}
private String state(Option option) {
if (!overrides.containsKey(option.name)) return INHERIT;
String value = overrides.getString(option.name);
if (value == null) return UNSET;
if (option.name.endsWith("_TOKEN")) return "Set";
if (value.isEmpty()) return "Empty value";
int index = option.values.indexOf(value);
return index < 0 ? value : option.labels.get(index);
}
private void edit(Option option, Runnable refresh) {
List<String> labels = new ArrayList<>();
labels.add(INHERIT);
labels.add(UNSET);
labels.addAll(option.labels);
labels.add(CUSTOM);
String value = overrides.getString(option.name);
int current = !overrides.containsKey(option.name) ? 0 : value == null ? 1 : option.values.indexOf(value) + 2;
if (current == 1 && value != null) current = labels.size() - 1;
new AlertDialog.Builder(activity).setTitle(option.name)
.setSingleChoiceItems(labels.toArray(new String[0]), current, (dialog, position) -> {
dialog.dismiss();
if (position == 0) overrides.remove(option.name);
else if (position == 1) overrides.putString(option.name, null);
else if (position == labels.size() - 1) {
editValue(option, refresh, value);
return;
} else overrides.putString(option.name, option.values.get(position - 2));
updated(refresh);
}).setNegativeButton("Cancel", null).show();
}
private void editValue(Option option, Runnable refresh, String current) {
EditText value = new EditText(activity);
value.setSingleLine();
value.setHint("Value");
value.setInputType(option.numeric ? InputType.TYPE_CLASS_NUMBER
: InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
value.setText(current);
AlertDialog dialog = new AlertDialog.Builder(activity).setTitle(option.name).setView(value)
.setNegativeButton("Cancel", null).setPositiveButton("Set", (ignored, position) -> {
overrides.putString(option.name, value.getText().toString());
updated(refresh);
}).show();
Runnable validate = () -> {
String text = value.getText().toString();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(text.length() <= 4096 && text.indexOf(0) < 0);
};
value.addTextChangedListener(new TextWatcher() {
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) { validate.run(); }
@Override public void afterTextChanged(Editable s) {}
});
validate.run();
}
private void updated(Runnable refresh) {
refresh.run();
changed.run();
}
private static final class Option {
final String name;
final boolean numeric;
final List<String> labels = new ArrayList<>();
final List<String> values = new ArrayList<>();
Option(String name, String type) {
this.name = name;
numeric = type.equals("number");
if (type.isEmpty() || numeric) return;
for (String choice : type.split("[|]")) {
int equals = choice.indexOf('=');
labels.add(equals < 0 ? choice : choice.substring(0, equals));
values.add(equals < 0 ? choice : choice.substring(equals + 1));
}
}
}
}
@@ -10,13 +10,12 @@ import android.widget.LinearLayout;
import android.widget.TextView;
/**
* Bottom navigation bar switching between the POST screen and the render server
* control screen. Tabs switch by reordering the other activity to the front, so each
* screen keeps its state while the other is open.
* Bottom navigation bar. Tabs reorder their activities to the front to preserve screen state.
*/
public final class NavBar {
public static final int TAB_POST = 0;
public static final int TAB_SERVER = 1;
public static final int TAB_TEST = 2;
private static final int COLOR_BAR = 0xFF1E1E1E;
private static final int COLOR_TAB_ACTIVE = 0xFFEEEEEE;
@@ -37,6 +36,7 @@ public final class NavBar {
bar.setBackgroundColor(COLOR_BAR);
addTab(activity, bar, "Diagnostics", PostActivity.class, currentTab == TAB_POST);
addTab(activity, bar, "Server", ServerControlActivity.class, currentTab == TAB_SERVER);
addTab(activity, bar, "Test", TestActivity.class, currentTab == TAB_TEST);
root.addView(bar, new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, dp(activity, BAR_HEIGHT_DP)));
return root;
@@ -0,0 +1,418 @@
package top.mobilegl.plugin;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public final class TestActivity extends Activity {
private static final int PICK_TRACE = 1;
private static native String nativeSampleCatalog();
private final Handler main = new Handler(Looper.getMainLooper());
private final ArrayList<String> samples = new ArrayList<>();
private Spinner sample;
private Button environment;
private EnvironmentOptions environmentOptions;
private Button run;
private Button replayTrace;
private Switch vsync;
private SurfaceView preview;
private ImageView snapshot;
private String snapshotPath;
private static final int FRAME_WIDTH = 1280;
private static final int FRAME_HEIGHT = 720;
private TextView report;
private String result;
private Run active;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
ScrollView scroll = new ScrollView(this);
scroll.setBackgroundColor(0xFF121212);
LinearLayout content = new LinearLayout(this);
content.setOrientation(LinearLayout.VERTICAL);
int padding = dp(16);
content.setPadding(padding, padding, padding, padding);
scroll.addView(content);
setContentView(NavBar.wrap(this, scroll, NavBar.TAB_TEST));
TextView title = text("MobileGL Test", 20);
title.setTypeface(null, Typeface.BOLD);
content.addView(title);
content.addView(text("Scene", 14));
sample = new Spinner(this);
sample.setContentDescription("Scene");
content.addView(sample);
environment = new Button(this);
environmentOptions = new EnvironmentOptions(this, this::updateEnvironmentLabel);
environment.setOnClickListener(view -> environmentOptions.show());
if (state != null) environmentOptions.restore(state.getBundle("environmentOptions"));
updateEnvironmentLabel();
content.addView(environment);
vsync = new Switch(this);
vsync.setText("VSync");
vsync.setChecked(state == null || state.getBoolean("vsync", true));
content.addView(vsync);
run = new Button(this);
run.setText("Run");
run.setOnClickListener(view -> {
if (active == null) startRun();
else active.cancel();
});
content.addView(run);
replayTrace = new Button(this);
replayTrace.setText("Replay trace…");
replayTrace.setOnClickListener(view -> {
if (active == null) chooseTrace();
else if (active.isTrace()) active.cancel();
});
content.addView(replayTrace);
FrameLayout frame = new FrameLayout(this);
content.addView(frame);
preview = new SurfaceView(this) {
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
int width = MeasureSpec.getSize(widthSpec);
setMeasuredDimension(width, width * FRAME_HEIGHT / FRAME_WIDTH);
}
};
preview.setContentDescription("Live sample surface");
frame.addView(preview, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT));
snapshot = new ImageView(this);
snapshot.setScaleType(ImageView.ScaleType.FIT_CENTER);
snapshot.setBackgroundColor(0xFF121212);
snapshot.setContentDescription("Trace snapshot");
frame.addView(snapshot, new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
showSnapshot(state == null ? null : state.getString("snapshotPath"));
preview.getHolder().setFixedSize(FRAME_WIDTH, FRAME_HEIGHT);
preview.getHolder().addCallback(new SurfaceHolder.Callback() {
@Override public void surfaceCreated(SurfaceHolder holder) {}
@Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
@Override public void surfaceDestroyed(SurfaceHolder holder) {
if (active != null && !active.isTrace() && !active.received) active.cancel();
}
});
report = text("", 14);
report.setTextIsSelectable(true);
content.addView(report);
try {
System.loadLibrary("MobileGL");
JSONArray catalog = new JSONArray(nativeSampleCatalog());
for (int i = 0; i < catalog.length(); i++) samples.add(catalog.getString(i));
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, samples);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sample.setAdapter(adapter);
if (state != null) {
sample.setSelection(Math.max(0, samples.indexOf(state.getString("sample"))));
result = state.getString("result");
report.setText(result);
}
} catch (LinkageError | JSONException failure) {
showResult("Samples unavailable: " + failure.getMessage());
}
run.setEnabled(!samples.isEmpty());
}
@Override
protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putString("sample", (String) sample.getSelectedItem());
state.putBundle("environmentOptions", environmentOptions.snapshot());
state.putString("result", result);
state.putString("snapshotPath", snapshotPath);
state.putBoolean("vsync", vsync.isChecked());
}
@Override
protected void onDestroy() {
if (active != null) active.complete();
super.onDestroy();
}
private void chooseTrace() {
Intent picker = new Intent(Intent.ACTION_OPEN_DOCUMENT)
.addCategory(Intent.CATEGORY_OPENABLE).setType("*/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
try {
startActivityForResult(picker, PICK_TRACE);
} catch (ActivityNotFoundException error) {
showResult("No file picker is available");
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode != PICK_TRACE || resultCode != RESULT_OK || active != null) return;
Uri trace = data == null ? null : data.getData();
if (trace == null) {
showResult("No trace file was selected");
return;
}
start(new Run("Trace replay", trace, environmentOptions.snapshot(), false));
}
private void startRun() {
Surface surface = preview.getHolder().getSurface();
if (!surface.isValid()) {
showResult("Surface unavailable");
return;
}
start(new Run((String) sample.getSelectedItem(), null, environmentOptions.snapshot(), vsync.isChecked()));
}
private void start(Run request) {
showSnapshot(null);
active = request;
if (active.bind()) {
setRunning(true);
showResult(request.isTrace() ? "Importing and replaying trace…" : "Running…");
} else {
active = null;
showResult("Test process unavailable");
}
}
private void updateEnvironmentLabel() {
int count = environmentOptions.snapshot().size();
environment.setText(count == 0 ? "Environment" : "Environment (" + count + ")");
}
private void setRunning(boolean running) {
sample.setEnabled(!running);
environment.setEnabled(!running);
vsync.setEnabled(!running);
boolean replaying = running && active.isTrace();
run.setText(running && !replaying ? "Cancel" : "Run");
run.setEnabled(replaying ? false : running || !samples.isEmpty());
replayTrace.setText(replaying ? "Cancel trace replay" : "Replay trace…");
replayTrace.setEnabled(!running || replaying);
}
private final class Run implements ServiceConnection {
private final String name;
private final Uri trace;
private final Bundle overrides;
private final boolean useVsync;
private Messenger worker;
private boolean bound;
private boolean cancelled;
private boolean received;
private final Runnable unavailable = () -> fail("Test process unavailable");
Run(String name, Uri trace, Bundle overrides, boolean useVsync) {
this.name = name;
this.trace = trace;
this.overrides = overrides;
this.useVsync = useVsync;
}
boolean isTrace() {
return trace != null;
}
private Button cancelButton() {
return isTrace() ? replayTrace : run;
}
boolean bind() {
bound = bindService(new Intent(TestActivity.this, TestService.class), this, Context.BIND_AUTO_CREATE);
if (bound) main.postDelayed(unavailable, 10_000);
return bound;
}
@Override
public void onServiceConnected(ComponentName component, IBinder binder) {
if (active != this || worker != null) return;
main.removeCallbacks(unavailable);
worker = new Messenger(binder);
Message request = Message.obtain(null, TestService.RUN);
request.getData().putBundle(TestService.ENVIRONMENT, overrides);
if (isTrace()) {
request.getData().putParcelable(TestService.TRACE_URI, trace);
} else {
Surface surface = preview.getHolder().getSurface();
if (!surface.isValid()) {
fail("Surface unavailable");
return;
}
request.getData().putString(TestService.SAMPLE, name);
request.getData().putBoolean(TestService.VSYNC, useVsync);
request.getData().putParcelable(TestService.SURFACE, surface);
}
request.replyTo = new Messenger(new Handler(Looper.getMainLooper(), this::onResult));
try {
worker.send(request);
} catch (RemoteException error) {
fail("Test process unavailable");
}
}
private boolean onResult(Message message) {
if (message.what != TestService.RESULT || active != this || cancelled) return false;
received = true;
String json = message.getData().getString(TestService.REPORT, "");
if (isTrace()) showTraceReport(json);
else showResult(formatReport(name, json));
cancelButton().setEnabled(false);
return true;
}
@Override
public void onServiceDisconnected(ComponentName component) {
if (active != this) return;
if (!received && !cancelled) showResult(name + "\nTest process exited");
complete();
}
@Override
public void onBindingDied(ComponentName component) {
onServiceDisconnected(component);
}
@Override
public void onNullBinding(ComponentName component) {
fail("Test process unavailable");
}
void cancel() {
cancelled = true;
showResult("Canceled");
if (worker == null) {
complete();
return;
}
cancelButton().setEnabled(false);
try {
worker.send(Message.obtain(null, TestService.CANCEL));
} catch (RemoteException ignored) {
complete();
}
}
private void fail(String detail) {
if (active != this) return;
showResult(detail);
complete();
}
void complete() {
main.removeCallbacks(unavailable);
if (bound) unbindService(this);
bound = false;
if (active != this) return;
active = null;
setRunning(false);
}
}
private static String formatReport(String name, String json) {
try {
JSONObject data = new JSONObject(json);
if (data.has("error")) return name + "\n" + data.getString("error");
String report = String.format(Locale.ROOT, "%s%n%s%n%d frames · %.1f FPS%nMedian %.3f ms · P95 %.3f ms%nGL error 0x%04X",
name, data.getString("renderer"), data.getInt("frames"), data.getDouble("fps"),
data.getDouble("medianFrameMs"), data.getDouble("p95FrameMs"), data.getInt("glError"));
int redundantCalls = data.optInt("redundantCallsPerFrame", -1);
if (redundantCalls >= 0) report += "\nRedundant calls per frame: " + redundantCalls;
return report;
} catch (JSONException error) {
return name + "\nInvalid test report";
}
}
private void showTraceReport(String json) {
try {
JSONObject data = new JSONObject(json);
if (data.has("error")) {
showResult("Trace replay\n" + data.getString("error"));
return;
}
String summary = data.getString("name") + "\n"
+ (data.getBoolean("passed") ? "Replay complete" : "Replay failed")
+ "\n" + data.getString("message");
String resultFile = data.getString("resultPath");
if (!resultFile.isEmpty()) summary += "\nResult: " + resultFile;
showResult(summary);
showSnapshot(data.getString("actualPath"));
} catch (JSONException error) {
showResult("Invalid trace replay report");
}
}
private void showSnapshot(String path) {
Bitmap image = null;
if (path != null && !path.isEmpty()) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inJustDecodeBounds = false;
options.inSampleSize = 1;
while (Math.max(options.outWidth, options.outHeight) / options.inSampleSize > FRAME_WIDTH) {
options.inSampleSize *= 2;
}
image = BitmapFactory.decodeFile(path, options);
}
snapshotPath = image == null ? null : path;
snapshot.setImageBitmap(image);
snapshot.setVisibility(image == null ? View.GONE : View.VISIBLE);
}
private void showResult(String text) {
result = text;
report.setText(text);
}
private TextView text(String value, int size) {
TextView view = new TextView(this);
view.setText(value);
view.setTextSize(size);
view.setPadding(0, dp(8), 0, dp(4));
return view;
}
private int dp(int value) {
return Math.round(value * getResources().getDisplayMetrics().density);
}
}
@@ -0,0 +1,123 @@
package top.mobilegl.plugin;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.os.Process;
import android.os.RemoteException;
import android.system.Os;
import android.view.Surface;
import org.json.JSONObject;
public final class TestService extends Service {
static final int RUN = 1;
static final int RESULT = 2;
static final int CANCEL = 3;
static final String SAMPLE = "sample";
static final String ENVIRONMENT = "environment";
static final String TRACE_URI = "traceUri";
static final String REPORT = "report";
static final String SURFACE = "surface";
static final String VSYNC = "vsync";
private static final long TIMEOUT_MS = 90_000;
static final String BACKEND_ENV_PRIORITY = "MOBILEGL_TEST_BACKEND_ENV_PRIORITY";
private static native String nativeRunSample(String sample, Surface surface, boolean vsync);
private final Handler main = new Handler(Looper.getMainLooper());
private final Messenger requests = new Messenger(new Handler(Looper.getMainLooper(), this::onRequest));
private boolean started;
private boolean finished;
@Override
public IBinder onBind(Intent intent) {
return requests.getBinder();
}
@Override
public boolean onUnbind(Intent intent) {
if (started) exit();
return false;
}
private boolean onRequest(Message message) {
if (message.what == CANCEL) {
exit();
return true;
}
if (message.what != RUN || started || message.replyTo == null) return false;
started = true;
Messenger reply = message.replyTo;
Bundle args = message.getData();
Uri trace = args.getParcelable(TRACE_URI);
if (trace == null) main.postDelayed(() -> finish(reply, error("Timed out")), TIMEOUT_MS);
new Thread(() -> {
String result;
Surface surface = args.getParcelable(SURFACE);
try {
result = trace == null ? runSample(args, surface)
: TraceTest.run(this, trace, args.getBundle(ENVIRONMENT));
} catch (Exception | LinkageError failure) {
String detail = failure.getMessage();
result = error(detail == null ? failure.getClass().getSimpleName() : detail);
} finally {
if (surface != null) surface.release();
}
String report = result == null ? error("No result") : result;
main.post(() -> finish(reply, report));
}, "MobileGLTest").start();
return true;
}
private static String runSample(Bundle args, Surface surface) throws Exception {
String sample = args.getString(SAMPLE);
if (sample == null || sample.isEmpty()) throw new IllegalArgumentException("Select a sample");
Bundle overrides = args.getBundle(ENVIRONMENT);
if (overrides != null) {
for (String name : overrides.keySet()) {
String value = overrides.getString(name);
if (value == null) Os.unsetenv(name);
else Os.setenv(name, value, true);
}
if (overrides.containsKey(ServerEnvironment.BACKEND)) {
// A Test selection also applies to a renderer process it spawns.
Os.setenv(BACKEND_ENV_PRIORITY, "1", true);
}
}
System.loadLibrary("MobileGL");
if (surface == null || !surface.isValid()) throw new IllegalStateException("Surface unavailable");
return nativeRunSample(sample, surface, args.getBoolean(VSYNC, true));
}
private static String error(String detail) {
return "{\"error\":" + JSONObject.quote(detail) + "}";
}
private void finish(Messenger reply, String report) {
if (finished) return;
finished = true;
main.removeCallbacksAndMessages(null);
Message result = Message.obtain(null, RESULT);
result.getData().putString(REPORT, report);
try {
reply.send(result);
} catch (RemoteException ignored) {
exit();
return;
}
// The client unbinds after reading the report. Exit even if it stops responding.
main.postDelayed(this::exit, 1_000);
}
private void exit() {
TraceTest.discardInput(this);
Process.killProcess(Process.myPid());
}
}
@@ -0,0 +1,118 @@
package top.mobilegl.plugin;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.OpenableColumns;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import org.json.JSONObject;
final class TraceTest {
private static final String OUTPUT_DIRECTORY = "test-trace-replay";
private static final String INPUT_FILENAME = "input.trace";
private static final String TRANSPORT = "MOBILEGL_TRANSPORT";
private static final String SERVER_PATH = "MOBILEGL_IPC_SERVER_PATH";
private TraceTest() {}
static String run(Context context, Uri source, Bundle overrides) throws Exception {
if (!"content".equals(source.getScheme())) throw new IOException("Select a document from the file picker");
File output = outputDirectory(context);
Files.createDirectories(output.toPath());
File[] files = output.listFiles();
if (files == null) throw new IOException("Trace output directory unavailable");
for (File file : files) Files.deleteIfExists(file.toPath());
File input = new File(output, INPUT_FILENAME);
try {
copyDocument(context, source, input);
if (overrides == null) overrides = new Bundle();
String backend = overrides.getString(ServerEnvironment.BACKEND);
if (backend == null) backend = context.getString(R.string.mobilegl_default_backend);
System.loadLibrary("trace_replay_runner");
Result result = nativeReplay(input.getAbsolutePath(), output.getAbsolutePath(), backend,
environment(context, overrides));
if (result == null) throw new IOException("Trace replay returned no result");
return new JSONObject().put("name", displayName(context, source)).put("passed", result.passed)
.put("message", result.message).put("actualPath", existingPath(result.actualPath))
.put("resultPath", existingPath(result.resultPath)).toString();
} finally {
discardInput(context);
}
}
private static File outputDirectory(Context context) {
return new File(context.getCacheDir(), OUTPUT_DIRECTORY);
}
static void discardInput(Context context) {
new File(outputDirectory(context), INPUT_FILENAME).delete();
}
private static String existingPath(String path) {
return new File(path).isFile() ? path : "";
}
private static String displayName(Context context, Uri source) {
try (Cursor cursor = context.getContentResolver().query(source,
new String[]{OpenableColumns.DISPLAY_NAME}, null, null, null)) {
if (cursor != null && cursor.moveToFirst()) {
String name = cursor.getString(0);
if (name != null && !name.isEmpty()) return name.substring(0, Math.min(name.length(), 256));
}
} catch (RuntimeException ignored) {
}
return "Trace replay";
}
private static void copyDocument(Context context, Uri source, File input) throws IOException {
// The native parser opens a regular file twice. A document provider can return a pipe.
try (FileOutputStream output = new FileOutputStream(input);
InputStream stream = context.getContentResolver().openInputStream(source)) {
if (stream == null) throw new IOException("Document provider did not open the file");
byte[] buffer = new byte[128 * 1024];
for (int count; (count = stream.read(buffer)) != -1;) output.write(buffer, 0, count);
} catch (IOException | SecurityException failure) {
throw new IOException("Unable to read the selected trace: " + failure.getMessage(), failure);
}
if (input.length() == 0) throw new IOException("The selected trace is empty");
}
private static String[] environment(Context context, Bundle overrides) {
ArrayList<String> entries = new ArrayList<>();
for (String name : overrides.keySet()) {
String value = overrides.getString(name);
entries.add(value == null ? name : name + "=" + value);
}
if (overrides.containsKey(ServerEnvironment.BACKEND)) entries.add(TestService.BACKEND_ENV_PRIORITY + "=1");
if ("spawn".equalsIgnoreCase(overrides.getString(TRANSPORT)) && !overrides.containsKey(SERVER_PATH)) {
File server = new File(context.getApplicationInfo().nativeLibraryDir, "libMobileGLServer.so");
entries.add(SERVER_PATH + "=" + server.getAbsolutePath());
}
return entries.toArray(new String[0]);
}
private static native Result nativeReplay(String input, String output, String backend, String[] environment);
private static final class Result {
final boolean passed;
final String message;
final String actualPath;
final String resultPath;
Result(boolean passed, String message, String actualPath, String resultPath) {
this.passed = passed;
this.message = message;
this.actualPath = actualPath;
this.resultPath = resultPath;
}
}
}
@@ -1,7 +1,9 @@
#include "trace_replay_core.hpp"
#include "apitrace_exit.hpp"
#include "spawn_spike.hpp"
#include "trace_env_overrides.hpp"
#include "trace_parser.hpp"
#include "trace_replay_lease.hpp"
#include <android/native_window.h>
@@ -9,6 +11,7 @@
#include <jni.h>
#include <exception>
#include <memory>
#include <string>
#include <vector>
#include <sys/stat.h>
@@ -84,6 +87,44 @@ public:
}
};
jobject MakeTestResult(JNIEnv* env, const mobilegl_trace::Result& result) {
jclass clazz = env->FindClass("top/mobilegl/plugin/TraceTest$Result");
if (clazz == nullptr) {
return nullptr;
}
jmethodID ctor = env->GetMethodID(clazz, "<init>", "(ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
if (ctor == nullptr) {
return nullptr;
}
jstring message = env->NewStringUTF(result.message.c_str());
jstring actualPath = env->NewStringUTF(result.actualPath.c_str());
jstring resultPath = env->NewStringUTF(result.resultPath.c_str());
return env->NewObject(clazz, ctor, result.passed ? JNI_TRUE : JNI_FALSE, message, actualPath, resultPath);
}
mobilegl_trace::Result RunTestReplay(mobilegl_trace::Request& request) {
long long lastCall = -1;
long long lastFrameEnd = -1;
{
trace::Parser parser;
if (!parser.open(request.tracePath.c_str())) {
return MakeFailureResult(request, mobilegl_trace::STATUS_INVALID_ARGUMENT, "Could not open the trace");
}
while (std::unique_ptr<trace::Call> call{parser.scan_call()}) {
lastCall = call->no;
if (call->flags & trace::CALL_FLAG_END_FRAME) {
lastFrameEnd = call->no;
}
}
}
// Capture before the final presentation. Cleanup calls can destroy the drawable.
request.targetCall = lastFrameEnd >= 0 ? lastFrameEnd : lastCall;
if (request.targetCall < 0) {
return MakeFailureResult(request, mobilegl_trace::STATUS_INVALID_ARGUMENT, "The trace contains no calls");
}
return mobilegl_trace::RunTraceReplay(request);
}
} // namespace
extern "C" JNIEXPORT jobject JNICALL
@@ -216,6 +257,44 @@ Java_top_mobilegl_plugin_trace_TraceReplayActivity_nativeRunTraceReplay(JNIEnv*
return MakeResult(env, result);
}
extern "C" JNIEXPORT jobject JNICALL
Java_top_mobilegl_plugin_TraceTest_nativeReplay(JNIEnv* env, jclass, jstring input, jstring output, jstring backend,
jobjectArray environment) {
mobilegl_trace::TraceReplayLease lease;
if (!lease) {
mobilegl_trace::Result result;
result.message = "Another trace replay is already running in this process";
return MakeTestResult(env, result);
}
mobilegl_trace::Request request;
request.tracePath = ToString(env, input);
request.outputDir = ToString(env, output);
request.backend = ToString(env, backend);
request.usePbuffer = true;
for (jsize i = 0; i < env->GetArrayLength(environment); ++i) {
auto entry = static_cast<jstring>(env->GetObjectArrayElement(environment, i));
request.envOverrides.push_back(ToString(env, entry));
env->DeleteLocalRef(entry);
}
mobilegl_trace::Result result;
try {
result = RunTestReplay(request);
} catch (const MobileGLRetraceExit&) {
result = MakeFailureResult(request, mobilegl_trace::STATUS_RETRACE_FAILED, "Could not read the trace");
} catch (const std::exception& failure) {
result = MakeFailureResult(request, mobilegl_trace::STATUS_RETRACE_FAILED, failure.what());
} catch (...) {
result = MakeFailureResult(request, mobilegl_trace::STATUS_RETRACE_FAILED, "Unexpected trace replay failure");
}
if (!mobilegl_trace::WriteResultJson(request, result) && result.passed) {
result.passed = false;
result.message = "Replay completed but the result could not be written";
}
return MakeTestResult(env, result);
}
// P0 spike A: exec the packaged MobileGLServer stub from this app process and report what
// happened. Deliberately a separate entry point rather than another parameter on the
// replay call - it shares nothing with a replay, and the trace lane must be able to run