[Chore] (MG_Backend, MG_Backend/DirectGLES, MG_Backend/DirectVulkan, MG_Backend/MGPipe, MG_Backend/Record, MG_Benchmark/Buffer, MG_Benchmark/Container, MG_Benchmark/Driver, MG_Benchmark/Program, MG_Benchmark/ShaderCache, MG_Benchmark/Transpile, MG_Gbm, MG_Impl, MG_Impl/CGLImpl, MG_Impl/DyldInterpose, MG_Impl/EGLImpl, MG_Impl/GLImpl, MG_Impl/GLXImpl, MG_Impl/NSOpenGLImpl, MG_Impl/Pipe, MG_Impl/WGLImpl, MG_IntegrationTest, MG_IntegrationTest/Harness, MG_IntegrationTest/Scenarios, MG_Pipe, MG_Remote, MG_Remote/Client, MG_Remote/Protocol, MG_Remote/Server, MG_Remote/Transport, MG_Remote/Wire, MG_State/EGLState, MG_State/GLState, MG_Test, MG_Test/Backend, MG_Test/BackendLoader, MG_Test/Buffer, MG_Test/EGLState, MG_Test/Framebuffer, MG_Test/Gbm, MG_Test/Pipe, MG_Test/Pipeline, MG_Test/Program, MG_Test/Query, MG_Test/SelfTest, MG_Test/ShaderTranspiler, MG_Test/State, MG_Test/Swapchain, MG_Test/Texture, MG_Test/Util, MG_Test/VertexArray, MG_Test/Wire, MG_Util/Async, MG_Util/BackendLoaders, MG_Util/Converters, MG_Util/Damage, MG_Util/Debug, MG_Util/Math, MG_Util/Metrics, MG_Util/SelfTest, MG_Util/ShaderTranspiler, MG_Util/Texture, MG_Util/X11, MobileGL, scripts/data, tools/cts, tools/device_bench, tools/spikes, tools/trace_replay, tools/wgl-smoke): clang-format every C and C++ source

- Layout only: token streams match up to split literals, continuations and using order
- The size totals fall, so the structure baseline is lowered
This commit is contained in:
2026-10-16 06:30:38 -04:00
parent 76b10cc35b
commit f4994ee36e
747 changed files with 35842 additions and 36261 deletions
@@ -37,7 +37,7 @@ namespace {
// The capability block is a process-global the backend fills in at init; restore whatever
// was there so ordering between this suite and any other that touches it cannot matter.
struct ScopedGLESCapabilitiesOverride {
ScopedGLESCapabilitiesOverride(): saved(g_GLESCapabilities) {}
ScopedGLESCapabilitiesOverride() : saved(g_GLESCapabilities) {}
~ScopedGLESCapabilitiesOverride() { g_GLESCapabilities = saved; }
ScopedGLESCapabilitiesOverride(const ScopedGLESCapabilitiesOverride&) = delete;
ScopedGLESCapabilitiesOverride& operator=(const ScopedGLESCapabilitiesOverride&) = delete;
@@ -80,8 +80,7 @@ TEST(BaseInstanceInjectionGate, DriverWithVertexStorageBlocksGetsTheIndirectView
g_GLESCapabilities.MaxShaderStorageBufferBindings = 13;
g_GLESCapabilities.MaxVertexShaderStorageBlocks = 1;
const String rewritten =
PromoteDrawParameterGlobalsToUniforms(kLoweredBaseInstanceVertexShader, GL_VERTEX_SHADER);
const String rewritten = PromoteDrawParameterGlobalsToUniforms(kLoweredBaseInstanceVertexShader, GL_VERTEX_SHADER);
EXPECT_TRUE(Contains(rewritten, "layout(std430, binding = 12) readonly buffer mg_IndirectParams"));
EXPECT_TRUE(Contains(rewritten, "uniform highp int mg_BaseInstanceWordIndex;"));
@@ -99,8 +98,7 @@ TEST(BaseInstanceInjectionGate, DriverWithoutVertexStorageBlocksDeclaresNoBlockA
g_GLESCapabilities.MaxShaderStorageBufferBindings = 13;
g_GLESCapabilities.MaxVertexShaderStorageBlocks = 0;
const String rewritten =
PromoteDrawParameterGlobalsToUniforms(kLoweredBaseInstanceVertexShader, GL_VERTEX_SHADER);
const String rewritten = PromoteDrawParameterGlobalsToUniforms(kLoweredBaseInstanceVertexShader, GL_VERTEX_SHADER);
EXPECT_FALSE(Contains(rewritten, "mg_IndirectParams")) << rewritten;
EXPECT_FALSE(Contains(rewritten, "buffer"));
@@ -118,8 +116,7 @@ TEST(BaseInstanceInjectionGate, WithoutTheBlockBaseInstanceFallsBackToThePlainUn
g_GLESCapabilities.MaxShaderStorageBufferBindings = 13;
g_GLESCapabilities.MaxVertexShaderStorageBlocks = 0;
const String rewritten =
PromoteDrawParameterGlobalsToUniforms(kLoweredBaseInstanceVertexShader, GL_VERTEX_SHADER);
const String rewritten = PromoteDrawParameterGlobalsToUniforms(kLoweredBaseInstanceVertexShader, GL_VERTEX_SHADER);
EXPECT_TRUE(Contains(rewritten, "uniform highp int mg_BaseInstance;")) << rewritten;
EXPECT_TRUE(Contains(rewritten, "#define mg_BaseInstanceLowered (mg_BaseInstance)")) << rewritten;
@@ -136,8 +133,7 @@ TEST(BaseInstanceInjectionGate, WithoutTheBlockInstanceIdRebaseCollapsesToIdenti
g_GLESCapabilities.MaxShaderStorageBufferBindings = 13;
g_GLESCapabilities.MaxVertexShaderStorageBlocks = 0;
const String rewritten =
PromoteDrawParameterGlobalsToUniforms(kLoweredBaseInstanceVertexShader, GL_VERTEX_SHADER);
const String rewritten = PromoteDrawParameterGlobalsToUniforms(kLoweredBaseInstanceVertexShader, GL_VERTEX_SHADER);
EXPECT_TRUE(Contains(rewritten, "#define mg_ZeroBasedInstanceID gl_InstanceID")) << rewritten;
EXPECT_FALSE(Contains(rewritten, "gl_InstanceID - ("));
@@ -21,7 +21,7 @@
namespace MobileGL::MG_Backend::DirectGLES {
SamplerImpl::BackendSamplerObject* GetRawDepthFetchSampler();
}
} // namespace MobileGL::MG_Backend::DirectGLES
#endif
using namespace MobileGL;
@@ -31,11 +31,21 @@ namespace {
#if MOBILEGL_BUILD_DISAGGREGATED
Uint unpackCalls = 0, samplerParameters = 0, nextNativeId = 100, boundXfb = 0;
Vector<GLenum> unpackNames;
void GL_APIENTRY PixelStore(GLenum name, GLint) { ++unpackCalls; unpackNames.push_back(name); }
void GL_APIENTRY GenNames(GLsizei count, GLuint* names) { while (count-- > 0) *names++ = ++nextNativeId; }
void GL_APIENTRY PixelStore(GLenum name, GLint) {
++unpackCalls;
unpackNames.push_back(name);
}
void GL_APIENTRY GenNames(GLsizei count, GLuint* names) {
while (count-- > 0)
*names++ = ++nextNativeId;
}
void GL_APIENTRY DeleteNames(GLsizei, const GLuint*) {}
void GL_APIENTRY SamplerParam(GLuint, GLenum, GLint) { ++samplerParameters; }
void GL_APIENTRY BindXfb(GLenum, GLuint id) { boundXfb = id; }
void GL_APIENTRY SamplerParam(GLuint, GLenum, GLint) {
++samplerParameters;
}
void GL_APIENTRY BindXfb(GLenum, GLuint id) {
boundXfb = id;
}
void GL_APIENTRY NoArgs() {}
void GL_APIENTRY BeginXfb(GLenum) {}
void GL_APIENTRY XfbVaryings(GLuint, GLsizei, const GLchar* const*, GLenum) {}
@@ -66,7 +76,7 @@ namespace {
}
};
#endif
}
} // namespace
TEST(ContextEpochTest, UnpackDefaultIsRepublishedForANewNativeContextOrRole) {
#if MOBILEGL_BUILD_DISAGGREGATED
@@ -110,7 +120,6 @@ TEST(ContextEpochTest, RawDepthSamplerOwnsANativeIdForEachContextGeneration) {
#endif
}
TEST(ContextEpochTest, SameXfbNameInTwoServedContextsDoesNotAliasThePausedSpan) {
#if MOBILEGL_BUILD_DISAGGREGATED
DriverScope scope;
@@ -187,10 +196,12 @@ TEST(ContextEpochTest, DualBlockApplierDiagnosticIsRoleLocalWhileSharedControlRe
Session::NoteApplyThreadEnteredApplier();
serverSawItself = Session::ApplyThreadIsInsideApplier();
entered.store(true, std::memory_order_release);
while (!leave.load(std::memory_order_acquire)) std::this_thread::yield();
while (!leave.load(std::memory_order_acquire))
std::this_thread::yield();
Session::NoteApplyThreadLeftApplier();
});
while (!entered.load(std::memory_order_acquire)) std::this_thread::yield();
while (!entered.load(std::memory_order_acquire))
std::this_thread::yield();
const Bool clientSawServer = Session::ApplyThreadIsInsideApplier();
leave.store(true, std::memory_order_release);
server.join();
@@ -215,8 +226,12 @@ TEST(ContextEpochTest, DualBlockApplierDiagnosticIsRoleLocalWhileSharedControlRe
namespace {
Bool fakeScissor = false;
Uint isEnabledCalls = 0;
void GL_APIENTRY FakeEnable(GLenum cap) { if (cap == GL_SCISSOR_TEST) fakeScissor = true; }
void GL_APIENTRY FakeDisable(GLenum cap) { if (cap == GL_SCISSOR_TEST) fakeScissor = false; }
void GL_APIENTRY FakeEnable(GLenum cap) {
if (cap == GL_SCISSOR_TEST) fakeScissor = true;
}
void GL_APIENTRY FakeDisable(GLenum cap) {
if (cap == GL_SCISSOR_TEST) fakeScissor = false;
}
GLboolean GL_APIENTRY FakeIsEnabled(GLenum cap) {
++isEnabledCalls;
return cap == GL_SCISSOR_TEST && fakeScissor ? GL_TRUE : GL_FALSE;
@@ -233,8 +248,7 @@ namespace {
// The driver's scissor as the copy inside the guard sees it.
Bool ScissorDuringGuard() {
Bool seen = true;
RenderStateImpl::RunScissorDisabledForTesting([](void* out) { *static_cast<Bool*>(out) = fakeScissor; },
&seen);
RenderStateImpl::RunScissorDisabledForTesting([](void* out) { *static_cast<Bool*>(out) = fakeScissor; }, &seen);
return seen;
}
} // namespace
@@ -35,14 +35,14 @@ using MobileGL::MG_Backend::DirectGLES::PrgramImpl::IMAGE_WRITE_ALIAS_PREFIX;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::IMAGE_WRITEONLY_ALIAS_PREFIX;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::ImageArrayUnitPlan;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::LowerZeroGradCubeArrayShadowLookups;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RedeclareClipCullDistancesInPerVertexBlock;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RedeclareClipCullDistanceInputsInPerVertexBlock;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RemapImageArrayElementUnits;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::PointSizeExtensionName;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RedeclareClipCullDistanceInputsInPerVertexBlock;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RedeclareClipCullDistancesInPerVertexBlock;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RemapImageArrayElementUnits;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RemoveLayoutBinding;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RequestPointSizeExtension;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RequestClipCullDistanceExtension;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RequestExtendedImageFormats;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RequestPointSizeExtension;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RequestViewportArrayExtension;
using MobileGL::MG_Backend::DirectGLES::PrgramImpl::SplitReadWriteImageUniforms;
@@ -61,12 +61,22 @@ namespace {
// The pass tags the name of every declaration it rewrites with the REPAIR it applied, so the
// expectations have to spell the tag that matches how the fixture uses the image.
String RoAlias(const String& name) { return String(IMAGE_READONLY_ALIAS_PREFIX) + name; }
String WoAlias(const String& name) { return String(IMAGE_WRITEONLY_ALIAS_PREFIX) + name; }
String RwAlias(const String& name) { return String(IMAGE_SPLIT_READ_ALIAS_PREFIX) + name; }
String RoAlias(const String& name) {
return String(IMAGE_READONLY_ALIAS_PREFIX) + name;
}
String WoAlias(const String& name) {
return String(IMAGE_WRITEONLY_ALIAS_PREFIX) + name;
}
String RwAlias(const String& name) {
return String(IMAGE_SPLIT_READ_ALIAS_PREFIX) + name;
}
// The writeonly half is minted from the ALREADY access-tagged name, so it carries both.
String WriteAlias(const String& name) { return String(IMAGE_WRITE_ALIAS_PREFIX) + name; }
String SplitWriteAlias(const String& name) { return WriteAlias(RwAlias(name)); }
String WriteAlias(const String& name) {
return String(IMAGE_WRITE_ALIAS_PREFIX) + name;
}
String SplitWriteAlias(const String& name) {
return WriteAlias(RwAlias(name));
}
// The scalar RemapImageArrayElementUnits declares for one element of a split image array.
String Elem(const String& name, Int element) {
return String(IMAGE_ARRAY_ELEMENT_PREFIX) + name + "_" + std::to_string(element);
@@ -94,8 +104,8 @@ void main()
// Both halves: same binding, same format, same type - which is what makes two image
// variables on one image unit legal - and both `coherent`, which is what makes the store
// through one of them visible to the load through the other.
EXPECT_TRUE(Contains(out, "layout(binding = 2, rgba8) uniform coherent readonly highp image2D " +
RwAlias("goku") + ";"))
EXPECT_TRUE(
Contains(out, "layout(binding = 2, rgba8) uniform coherent readonly highp image2D " + RwAlias("goku") + ";"))
<< out;
EXPECT_TRUE(Contains(out, "layout(binding = 2, rgba8) uniform coherent writeonly highp image2D " +
SplitWriteAlias("goku") + ";"))
@@ -136,8 +146,8 @@ void main()
}
)";
const String out = SplitReadWriteImageUniforms(source);
EXPECT_TRUE(Contains(out, "layout(binding = 1, rgba16f) uniform readonly highp image2DArray " +
RoAlias("trunks") + ";"))
EXPECT_TRUE(
Contains(out, "layout(binding = 1, rgba16f) uniform readonly highp image2DArray " + RoAlias("trunks") + ";"))
<< out;
EXPECT_TRUE(Contains(out, "imageLoad(" + RoAlias("trunks") + ","));
EXPECT_FALSE(Contains(out, "writeonly"));
@@ -154,8 +164,7 @@ void main()
}
)";
const String out = SplitReadWriteImageUniforms(source);
EXPECT_TRUE(
Contains(out, "layout(binding = 3, rgba8) uniform writeonly highp image2D " + WoAlias("gohan") + ";"))
EXPECT_TRUE(Contains(out, "layout(binding = 3, rgba8) uniform writeonly highp image2D " + WoAlias("gohan") + ";"))
<< out;
EXPECT_TRUE(Contains(out, "imageStore(" + WoAlias("gohan") + ","));
EXPECT_FALSE(Contains(out, "readonly"));
@@ -189,11 +198,9 @@ void main()
}
)";
const String out = SplitReadWriteImageUniforms(source);
EXPECT_TRUE(Contains(out, "layout(binding = 0, rgba8) uniform readonly highp image2D " +
RoAlias("reader") + ";"))
EXPECT_TRUE(Contains(out, "layout(binding = 0, rgba8) uniform readonly highp image2D " + RoAlias("reader") + ";"))
<< out;
EXPECT_TRUE(Contains(out, "layout(binding = 1, rgba8) uniform writeonly highp image2D " +
WoAlias("writer") + ";"))
EXPECT_TRUE(Contains(out, "layout(binding = 1, rgba8) uniform writeonly highp image2D " + WoAlias("writer") + ";"))
<< out;
EXPECT_TRUE(Contains(out, "imageStore(" + WoAlias("writer") + ",")) << out;
EXPECT_TRUE(Contains(out, "imageLoad(" + RoAlias("reader") + ",")) << out;
@@ -229,8 +236,8 @@ void main()
}
)";
const String out = SplitReadWriteImageUniforms(source);
EXPECT_TRUE(Contains(out, "layout(binding = 6, rgba8) uniform coherent readonly highp image2D " +
RwAlias("gohan") + "[3];"))
EXPECT_TRUE(Contains(out, "layout(binding = 6, rgba8) uniform coherent readonly highp image2D " + RwAlias("gohan") +
"[3];"))
<< out;
EXPECT_TRUE(Contains(out, "layout(binding = 6, rgba8) uniform coherent writeonly highp image2D " +
SplitWriteAlias("gohan") + "[3];"))
@@ -256,14 +263,13 @@ void main()
// goku is read+write -> split (and coherent with it); goku_hd is write-only -> qualified in
// place, not split, and left non-coherent because nothing aliases it. Both are renamed.
EXPECT_TRUE(Contains(out, "layout(binding = 1, rgba8) uniform coherent readonly highp image2D " +
RwAlias("goku") + ";"))
EXPECT_TRUE(
Contains(out, "layout(binding = 1, rgba8) uniform coherent readonly highp image2D " + RwAlias("goku") + ";"))
<< out;
EXPECT_TRUE(Contains(out, "layout(binding = 1, rgba8) uniform coherent writeonly highp image2D " +
SplitWriteAlias("goku") + ";"))
<< out;
EXPECT_TRUE(Contains(out, "layout(binding = 2, rgba8) uniform writeonly highp image2D " +
WoAlias("goku_hd") + ";"))
EXPECT_TRUE(Contains(out, "layout(binding = 2, rgba8) uniform writeonly highp image2D " + WoAlias("goku_hd") + ";"))
<< out;
EXPECT_TRUE(Contains(out, "imageStore(" + WoAlias("goku_hd") + ","));
EXPECT_FALSE(Contains(out, SplitWriteAlias("goku") + "_hd"));
@@ -281,10 +287,8 @@ void main()
}
)";
const String out = SplitReadWriteImageUniforms(source);
EXPECT_TRUE(Contains(out, "uniform readonly coherent restrict highp image2D " + RwAlias("goku") + ";"))
<< out;
EXPECT_TRUE(
Contains(out, "uniform writeonly coherent restrict highp image2D " + SplitWriteAlias("goku") + ";"))
EXPECT_TRUE(Contains(out, "uniform readonly coherent restrict highp image2D " + RwAlias("goku") + ";")) << out;
EXPECT_TRUE(Contains(out, "uniform writeonly coherent restrict highp image2D " + SplitWriteAlias("goku") + ";"))
<< out;
// ...and the coherent the split adds is not a SECOND one: a repeated memory qualifier is a
// compile error in ESSL, so the source's own has to be recognized.
@@ -311,8 +315,7 @@ void main()
)";
const String out = SplitReadWriteImageUniforms(source);
EXPECT_TRUE(Contains(out, "uniform coherent readonly highp image2D " + RwAlias("goku") + ";")) << out;
EXPECT_TRUE(Contains(out, "uniform coherent writeonly highp image2D " + SplitWriteAlias("goku") + ";"))
<< out;
EXPECT_TRUE(Contains(out, "uniform coherent writeonly highp image2D " + SplitWriteAlias("goku") + ";")) << out;
// Exactly the two halves of the pair, and nothing else: the store-only image is repaired in
// place, has no alias to stay visible to, and must not pay for uncached access.
EXPECT_EQ(CountOf(out, "coherent"), 2u);
@@ -377,8 +380,8 @@ void main()
}
)";
const String out = SplitReadWriteImageUniforms(source);
EXPECT_TRUE(Contains(out, "max(imageLoad(" + RwAlias("gohan") +
"[2], ivec2(0)), vec4(0.5))); memoryBarrierImage();"))
EXPECT_TRUE(
Contains(out, "max(imageLoad(" + RwAlias("gohan") + "[2], ivec2(0)), vec4(0.5))); memoryBarrierImage();"))
<< out;
EXPECT_EQ(CountOf(out, "memoryBarrierImage();"), 1u) << out;
}
@@ -430,8 +433,8 @@ void main()
}
)";
const String out = SplitReadWriteImageUniforms(source);
EXPECT_TRUE(Contains(out, "layout(binding = 8, rgba8ui) uniform readonly highp uimage2D " +
RoAlias("sizeOnly") + ";"))
EXPECT_TRUE(
Contains(out, "layout(binding = 8, rgba8ui) uniform readonly highp uimage2D " + RoAlias("sizeOnly") + ";"))
<< out;
// The rename has to reach imageSize too, or the declaration and its only use stop agreeing.
EXPECT_TRUE(Contains(out, "imageSize(" + RoAlias("sizeOnly") + ")")) << out;
@@ -593,8 +596,7 @@ void main()
const String first = SplitReadWriteImageUniforms(stage);
const String second = SplitReadWriteImageUniforms(stage);
EXPECT_EQ(first, second);
EXPECT_TRUE(Contains(first, "uniform coherent readonly highp image2D " + RoAlias("g_image") + ";"))
<< first;
EXPECT_TRUE(Contains(first, "uniform coherent readonly highp image2D " + RoAlias("g_image") + ";")) << first;
}
// The other side of that coin, and the one a per-STAGE tag got wrong. Two stages that use the
@@ -630,8 +632,7 @@ void main()
// back into the single image uniform the application declared.
for (const String& out : {vsOut, fsOut}) {
EXPECT_TRUE(Contains(out, "uniform coherent readonly highp image2D " + RwAlias("goku") + ";")) << out;
EXPECT_TRUE(Contains(out, "uniform coherent writeonly highp image2D " + SplitWriteAlias("goku") + ";"))
<< out;
EXPECT_TRUE(Contains(out, "uniform coherent writeonly highp image2D " + SplitWriteAlias("goku") + ";")) << out;
EXPECT_TRUE(Contains(out, "imageLoad(" + RwAlias("goku") + ",")) << out;
EXPECT_TRUE(Contains(out, "imageStore(" + SplitWriteAlias("goku") + ",")) << out;
}
@@ -693,8 +694,7 @@ void main()
// units 0, 1, 2, 3.
TEST(RemapImageArrayElementUnitsTest, NonConsecutiveUnitsSplitIntoOneScalarPerElement) {
Vector<String> declined;
const String out =
RemapImageArrayElementUnits(kSsoImageArrayFS, {Plan("g_image", {0, 2, 4, 6})}, &declined);
const String out = RemapImageArrayElementUnits(kSsoImageArrayFS, {Plan("g_image", {0, 2, 4, 6})}, &declined);
EXPECT_TRUE(declined.empty()) << (declined.empty() ? String() : declined[0]);
const Int units[4] = {0, 2, 4, 6};
@@ -702,8 +702,7 @@ TEST(RemapImageArrayElementUnitsTest, NonConsecutiveUnitsSplitIntoOneScalarPerEl
EXPECT_TRUE(Contains(out, "layout(rgba32f, binding = " + std::to_string(units[element]) +
") uniform writeonly highp image2D " + Elem("g_image", element) + ";"))
<< out;
EXPECT_TRUE(Contains(out, "imageStore(" + Elem("g_image", element) + ", ivec2(gl_FragCoord.xy)"))
<< out;
EXPECT_TRUE(Contains(out, "imageStore(" + Elem("g_image", element) + ", ivec2(gl_FragCoord.xy)")) << out;
}
// The array is gone entirely; nothing may still address units 0,1,2,3 through it.
EXPECT_FALSE(Contains(out, "image2D g_image[4];")) << out;
@@ -727,8 +726,8 @@ void main()
const String out = RemapImageArrayElementUnits(source, {Plan("g_image", {3, 1, 7, 5})});
const Int units[4] = {3, 1, 7, 5};
for (Int element = 0; element < 4; ++element) {
EXPECT_TRUE(Contains(out, "binding = " + std::to_string(units[element]) +
") uniform writeonly highp image2D " + Elem("g_image", element) + ";"))
EXPECT_TRUE(Contains(out, "binding = " + std::to_string(units[element]) + ") uniform writeonly highp image2D " +
Elem("g_image", element) + ";"))
<< out;
}
// Only elements 0 and 3 are ever accessed; elements 1 and 2 are declared and unused, because
@@ -783,8 +782,7 @@ void main()
}
)";
Vector<String> outOfRangeDeclined;
EXPECT_EQ(RemapImageArrayElementUnits(outOfRange, {Plan("g_image", {0, 5})}, &outOfRangeDeclined),
outOfRange);
EXPECT_EQ(RemapImageArrayElementUnits(outOfRange, {Plan("g_image", {0, 5})}, &outOfRangeDeclined), outOfRange);
ASSERT_EQ(outOfRangeDeclined.size(), 1u);
}
@@ -913,8 +911,7 @@ void main()
// Element 1 sits on unit 9, and both halves of its split pair say so.
EXPECT_EQ(CountOf(out, "binding = 9"), 2u) << out;
EXPECT_TRUE(Contains(out, "readonly highp image2D " + RwAlias(Elem("g_image", 1)) + ";")) << out;
EXPECT_TRUE(Contains(out, "writeonly highp image2D " + WriteAlias(RwAlias(Elem("g_image", 1))) + ";"))
<< out;
EXPECT_TRUE(Contains(out, "writeonly highp image2D " + WriteAlias(RwAlias(Elem("g_image", 1))) + ";")) << out;
EXPECT_EQ(CountOf(out, "binding = 4"), 1u) << out;
}
@@ -986,9 +983,11 @@ void main()
TEST(RetargetTextureBufferExtensionTest, OesOnlyDriverGetsTheOesDirective) {
const String out = RetargetTextureBufferExtension(kBufferTextureShader, Tier::ExtensionOES);
EXPECT_TRUE(Contains(out, "#extension GL_OES_texture_buffer : require"))
<< "the OES driver's own spelling must reach the directive:\n" << out;
<< "the OES driver's own spelling must reach the directive:\n"
<< out;
EXPECT_FALSE(Contains(out, "GL_EXT_texture_buffer"))
<< "the EXT spelling this driver does not advertise must be gone:\n" << out;
<< "the EXT spelling this driver does not advertise must be gone:\n"
<< out;
// Only the directive changes; the declaration and the fetch are identical between the two
// extensions and must not be touched.
EXPECT_TRUE(Contains(out, "uniform highp isamplerBuffer CloudFaces;"));
@@ -996,17 +995,14 @@ TEST(RetargetTextureBufferExtensionTest, OesOnlyDriverGetsTheOesDirective) {
}
TEST(RetargetTextureBufferExtensionTest, ExtDriverKeepsWhatSpirvCrossEmitted) {
EXPECT_EQ(RetargetTextureBufferExtension(kBufferTextureShader, Tier::ExtensionEXT),
kBufferTextureShader);
EXPECT_EQ(RetargetTextureBufferExtension(kBufferTextureShader, Tier::ExtensionEXT), kBufferTextureShader);
}
// ES 3.2 needs no directive at all, and SPIRV-Cross emits none at ESSL 320 - but a shader
// that arrived with one anyway must not be rewritten to a name the pass was not asked for.
TEST(RetargetTextureBufferExtensionTest, CoreAndUnsupportedTiersAreNoOps) {
EXPECT_EQ(RetargetTextureBufferExtension(kBufferTextureShader, Tier::CoreEs32),
kBufferTextureShader);
EXPECT_EQ(RetargetTextureBufferExtension(kBufferTextureShader, Tier::None),
kBufferTextureShader);
EXPECT_EQ(RetargetTextureBufferExtension(kBufferTextureShader, Tier::CoreEs32), kBufferTextureShader);
EXPECT_EQ(RetargetTextureBufferExtension(kBufferTextureShader, Tier::None), kBufferTextureShader);
}
// The name is only the subject of a rewrite where it is the subject of an #extension
@@ -1065,7 +1061,8 @@ void main() {}
const String out = RetargetTextureBufferExtension(source, Tier::ExtensionOES);
EXPECT_TRUE(Contains(out, "# extension GL_OES_texture_buffer : require")) << out;
EXPECT_TRUE(Contains(out, "#extension GL_EXT_shader_io_blocks : require"))
<< "an unrelated extension must survive untouched:\n" << out;
<< "an unrelated extension must survive untouched:\n"
<< out;
EXPECT_EQ(CountOf(out, "GL_OES_texture_buffer"), 1u);
}
@@ -1368,8 +1365,8 @@ layout(points) in;
layout(points, max_vertices = 1) out;
void main() { gl_ViewportIndex = 1; gl_PointSize = 2.0; EmitVertex(); }
)";
const String out = RequestPointSizeExtension(RequestViewportArrayExtension(source, true),
"GL_EXT_geometry_point_size");
const String out =
RequestPointSizeExtension(RequestViewportArrayExtension(source, true), "GL_EXT_geometry_point_size");
EXPECT_EQ(out.find("#version 320 es"), 0u) << out;
EXPECT_TRUE(Contains(out, "#extension GL_OES_viewport_array : require\n")) << out;
EXPECT_TRUE(Contains(out, "#extension GL_EXT_geometry_point_size : require\n")) << out;
@@ -1407,9 +1404,7 @@ TEST(PassthroughTessControlEsslTest, DeclaresThePatchSizeAndWritesEveryTessLevel
const String out = BuildPassthroughTessControlEssl(320, 4, "", "", kDefaultOuter, kDefaultInner);
EXPECT_EQ(out.find("#version 320 es"), 0u) << out;
EXPECT_TRUE(Contains(out, "layout(vertices = 4) out;")) << out;
EXPECT_TRUE(Contains(out,
"gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;"))
<< out;
EXPECT_TRUE(Contains(out, "gl_out[gl_InvocationID].gl_Position = gl_in[gl_InvocationID].gl_Position;")) << out;
// All six, unconditionally: writing a level the evaluation stage's domain does not use is
// legal and ignored, and it saves the generator from having to know the domain.
for (const char* level : {"gl_TessLevelOuter[0]", "gl_TessLevelOuter[1]", "gl_TessLevelOuter[2]",
@@ -1425,8 +1420,8 @@ TEST(PassthroughTessControlEsslTest, DeclaresThePatchSizeAndWritesEveryTessLevel
// entry point to forward it to, so a generator that ignored these arguments would tessellate every
// control-stage-less program at level 1 whatever the application asked for.
TEST(PassthroughTessControlEsslTest, BakesTheDefaultTessLevelsIn) {
const String out = BuildPassthroughTessControlEssl(320, 4, "", "", FloatVec4(2.0f, 3.0f, 4.0f, 5.0f),
FloatVec2(6.5f, 7.25f));
const String out =
BuildPassthroughTessControlEssl(320, 4, "", "", FloatVec4(2.0f, 3.0f, 4.0f, 5.0f), FloatVec2(6.5f, 7.25f));
EXPECT_TRUE(Contains(out, "gl_TessLevelOuter[0] = 2.0;")) << out;
EXPECT_TRUE(Contains(out, "gl_TessLevelOuter[1] = 3.0;")) << out;
EXPECT_TRUE(Contains(out, "gl_TessLevelOuter[2] = 4.0;")) << out;
@@ -1439,8 +1434,8 @@ TEST(PassthroughTessControlEsslTest, BakesTheDefaultTessLevelsIn) {
// `gl_TessLevelOuter[0] = 1;` as an int assigned to a float and refuses to compile the stage,
// which would take the whole program down with it.
TEST(PassthroughTessControlEsslTest, SpellsIntegralLevelsAsFloatLiterals) {
const String out = BuildPassthroughTessControlEssl(320, 4, "", "", FloatVec4(2.0f, 2.0f, 2.0f, 2.0f),
FloatVec2(2.0f, 2.0f));
const String out =
BuildPassthroughTessControlEssl(320, 4, "", "", FloatVec4(2.0f, 2.0f, 2.0f, 2.0f), FloatVec2(2.0f, 2.0f));
EXPECT_FALSE(Contains(out, "= 2;")) << out;
}
@@ -1452,8 +1447,7 @@ TEST(PassthroughTessControlEsslTest, SpellsIntegralLevelsAsFloatLiterals) {
TEST(PassthroughTessControlEsslTest, NonFiniteLevelsFollowTheDiscardRule) {
const Float notANumber = std::numeric_limits<Float>::quiet_NaN();
const Float infinity = std::numeric_limits<Float>::infinity();
const String out = BuildPassthroughTessControlEssl(320, 4, "", "",
FloatVec4(notANumber, -infinity, infinity, 1.0f),
const String out = BuildPassthroughTessControlEssl(320, 4, "", "", FloatVec4(notANumber, -infinity, infinity, 1.0f),
FloatVec2(notANumber, 1.0f));
EXPECT_TRUE(Contains(out, "gl_TessLevelOuter[0] = 0.0;")) << out;
EXPECT_TRUE(Contains(out, "gl_TessLevelOuter[1] = 0.0;")) << out;
@@ -1467,9 +1461,8 @@ TEST(PassthroughTessControlEsslTest, NonFiniteLevelsFollowTheDiscardRule) {
// A level below the old six-decimal format's resolution is still a POSITIVE level, which GL clamps
// to 1 and draws; rendering it as "0.000000" discarded the patch instead.
TEST(PassthroughTessControlEsslTest, TinyPositiveLevelsDoNotFlushToZero) {
const String out = BuildPassthroughTessControlEssl(320, 4, "", "",
FloatVec4(1e-7f, 1.0f, 1.0f, 1.0f),
FloatVec2(1.0f, 1.0f));
const String out =
BuildPassthroughTessControlEssl(320, 4, "", "", FloatVec4(1e-7f, 1.0f, 1.0f, 1.0f), FloatVec2(1.0f, 1.0f));
EXPECT_FALSE(Contains(out, "gl_TessLevelOuter[0] = 0.0;")) << out;
EXPECT_FALSE(Contains(out, "gl_TessLevelOuter[0] = 0.000000;")) << out;
}
@@ -106,30 +106,26 @@ TEST(SubsystemDepsTest, EveryRowNamesExactlyOneFamilyAndNoRowRequiresItself) {
}
// The families the rule is about. Bit 8 and bit 13 are in the table too, which is the half
// MGPipe.h's old "THREE OF THEM" comment was missing.
EXPECT_EQ(seen, kMGPipeSubsystemVertexInput | kMGPipeSubsystemFramebuffer |
kMGPipeSubsystemTextureResources | kMGPipeSubsystemSamplers |
kMGPipeSubsystemPrograms | kMGPipeSubsystemBufferBindings);
EXPECT_EQ(seen, kMGPipeSubsystemVertexInput | kMGPipeSubsystemFramebuffer | kMGPipeSubsystemTextureResources |
kMGPipeSubsystemSamplers | kMGPipeSubsystemPrograms | kMGPipeSubsystemBufferBindings);
}
TEST(SubsystemDepsTest, TheFourthRowIsPresentAndTheWithdrawnMirrorPairIsNotFine) {
// ID-14/ID-15. This is the row two comments in the tree denied existed, and the reason this
// case is written as an assertion rather than a paragraph.
EXPECT_NE(MGPipeSubsystemRequires(kMGPipeSubsystemTextureResources) & kMGPipeSubsystemSamplers,
0ull)
EXPECT_NE(MGPipeSubsystemRequires(kMGPipeSubsystemTextureResources) & kMGPipeSubsystemSamplers, 0ull)
<< "bit 10 no longer requires bit 11. If that is intended, the withdrawal recorded in "
"PipeFill.cpp and in BRIEF-P4A's amendment has been reversed and Espryt's "
"ResolveTextureResourceSubsystemArm must stop refusing 0x7ff in the same commit";
EXPECT_FALSE(MGPipeSubsystemDependenciesAreSet(kMGPipeSubsystemTextureResources, 0x7ffull));
EXPECT_FALSE(MGPipeSubsystemDependenciesAreSet(
kMGPipeSubsystemSamplers,
kMGPipeSubsystemsMigratedAtP5e & ~kMGPipeSubsystemTextureResources))
EXPECT_FALSE(MGPipeSubsystemDependenciesAreSet(kMGPipeSubsystemSamplers,
kMGPipeSubsystemsMigratedAtP5e & ~kMGPipeSubsystemTextureResources))
<< "bit 11 without bit 10 must not be live - the symmetric half of the fourth row";
// ...and the mirrors that really are fine.
EXPECT_TRUE(MGPipeSubsystemDependenciesAreSet(kMGPipeSubsystemPrograms, 0ull))
<< "bit 12 depends on nothing";
EXPECT_TRUE(MGPipeSubsystemDependenciesAreSet(
kMGPipeSubsystemTextureResources,
kMGPipeSubsystemResources | kMGPipeSubsystemSamplers | kMGPipeSubsystemTextureResources))
EXPECT_TRUE(MGPipeSubsystemDependenciesAreSet(kMGPipeSubsystemPrograms, 0ull)) << "bit 12 depends on nothing";
EXPECT_TRUE(MGPipeSubsystemDependenciesAreSet(kMGPipeSubsystemTextureResources,
kMGPipeSubsystemResources | kMGPipeSubsystemSamplers |
kMGPipeSubsystemTextureResources))
<< "bit 10 with 7 and 11 and WITHOUT bit 9 is fine and is not a row";
}
@@ -148,16 +144,15 @@ TEST(SubsystemDepsTest, TheFourthRowIsPresentAndTheWithdrawnMirrorPairIsNotFine)
// disagreement means records crossing to a server whose matching handle arm did not come up.
// ---------------------------------------------------------------------------------------------
TEST(SubsystemDepsTest, TheClientNeverEmitsAFamilyTheTableRefuses) {
const Uint64 families[] = {kMGPipeSubsystemFramebuffer, kMGPipeSubsystemTextureResources,
kMGPipeSubsystemSamplers, kMGPipeSubsystemPrograms};
const Uint64 families[] = {kMGPipeSubsystemFramebuffer, kMGPipeSubsystemTextureResources, kMGPipeSubsystemSamplers,
kMGPipeSubsystemPrograms};
int emitted = 0;
for (const Uint64 mask : InterestingMasks()) {
for (const Uint64 family : families) {
if (!MGPipeP4aFamilyEmits(family, mask)) continue;
++emitted;
EXPECT_TRUE(MGPipeSubsystemDependenciesAreSet(family, mask))
<< "at MOBILEGL_PIPE_PUSH=" << Describe(mask) << " the CLIENT emits family "
<< Describe(family)
<< "at MOBILEGL_PIPE_PUSH=" << Describe(mask) << " the CLIENT emits family " << Describe(family)
<< " while MG_Pipe/SubsystemDeps.def says its dependency bits are not all set. "
"Those records reach a server whose matching handle arm refused to come up - "
"the half-run subsystem D-K2 exists to make impossible. The two statements of "
@@ -172,6 +167,3 @@ TEST(SubsystemDepsTest, TheClientNeverEmitsAFamilyTheTableRefuses) {
// to have pulled in a consumer registration.
RecordProperty("client_emitting_combinations", emitted);
}
@@ -39,9 +39,8 @@ TEST(DirectVulkanSanity, ExtensionEnumeration) {
std::vector<VkExtensionProperties> extensions(extensionCount);
vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, extensions.data());
for(const auto& extension : extensions) {
std::cout << extension.extensionName
<< " (r." << extension.specVersion << ")\n";
for (const auto& extension : extensions) {
std::cout << extension.extensionName << " (r." << extension.specVersion << ")\n";
}
}
@@ -52,7 +51,7 @@ TEST(DirectVulkanSanity, WindowCreation) {
glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API);
GLFWwindow* window = glfwCreateWindow(800, 600, "MobileGL WindowCreation", nullptr, nullptr);
while(!glfwWindowShouldClose(window)) {
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
}
@@ -64,11 +63,11 @@ TEST(DirectVulkanSanity, WindowCreation) {
#define EGLAPI
#include <EGL/egl.h>
#ifdef _WIN32
#define GLFW_EXPOSE_NATIVE_WIN32
#define GLFW_EXPOSE_NATIVE_WIN32
#elif defined(__linux__)
#define GLFW_EXPOSE_NATIVE_X11
#define GLFW_EXPOSE_NATIVE_X11
#elif defined(__APPLE__)
#define GLFW_EXPOSE_NATIVE_COCOA
#define GLFW_EXPOSE_NATIVE_COCOA
#endif
#include <GLFW/glfw3native.h>
#ifdef __APPLE__
@@ -79,12 +78,7 @@ TEST(DirectVulkanSanity, WindowCreation) {
TEST(DirectVulkanSanity, ContextCreation) {
glfwInit();
static EGLint const attribute_list[] = {
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_NONE
};
static EGLint const attribute_list[] = {EGL_RED_SIZE, 8, EGL_GREEN_SIZE, 8, EGL_BLUE_SIZE, 8, EGL_NONE};
EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
eglInitialize(display, nullptr, nullptr);
@@ -122,7 +116,7 @@ TEST(DirectVulkanSanity, ContextCreation) {
EGLSurface surface = eglCreateWindowSurface(display, config, nativewindow, nullptr);
eglMakeCurrent(display, surface, surface, context);
while(!glfwWindowShouldClose(window)) {
while (!glfwWindowShouldClose(window)) {
glfwPollEvents();
eglSwapBuffers(display, surface);
}
@@ -83,7 +83,8 @@ TEST(GpuHangDetectorTest, TheBudgetRunsFromTheFirstSampleThatSawItRunning) {
TEST(GpuHangDetectorTest, AZeroBudgetNamesNothing) {
Watch::Detector detector(0);
for (Uint64 now = 0; now <= 60000; now += 1000) EXPECT_EQ(detector.Observe(One(1, true, false), now), 0u);
for (Uint64 now = 0; now <= 60000; now += 1000)
EXPECT_EQ(detector.Observe(One(1, true, false), now), 0u);
}
namespace {
@@ -137,7 +138,7 @@ TEST(GpuHangWatchThreadTest, TheHangingDeviceIsNamedOnceAndTheOneWaitingBehindIt
const ScopedWatchTiming timing(20, 200);
FakeDevice guilty;
FakeDevice innocent;
guilty.started = true; // the GPU runs it and it never ends
guilty.started = true; // the GPU runs it and it never ends
innocent.started = false; // queued behind it for the whole stall
const Uint64 a = Watch::Register(&guilty, &FakeDevice::Sample, &FakeDevice::Hung);
const Uint64 b = Watch::Register(&innocent, &FakeDevice::Sample, &FakeDevice::Hung);
@@ -145,7 +146,8 @@ TEST(GpuHangWatchThreadTest, TheHangingDeviceIsNamedOnceAndTheOneWaitingBehindIt
ASSERT_NE(b, 0u);
const auto start = std::chrono::steady_clock::now();
EXPECT_TRUE(PollUntil([&] { return guilty.named.load() > 0; }, 3000));
const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
const auto ms =
std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - start).count();
EXPECT_GE(ms, 180) << "named before the budget ran out";
EXPECT_LE(ms, 1500) << "named far past budget + interval";
EXPECT_EQ(guilty.namedId.load(), 42u);
@@ -147,7 +147,9 @@ namespace {
FakeDriverState g_fake;
void ResetFakeDriver() { g_fake = FakeDriverState{}; }
void ResetFakeDriver() {
g_fake = FakeDriverState{};
}
std::vector<unsigned char>* StoreOfBufferBoundTo(GLenum target) {
const auto boundIt = g_fake.boundBuffers.find(target);
@@ -473,7 +475,8 @@ namespace {
funcs.glIsEnabled = [](GLenum) -> GLboolean { return GL_FALSE; };
funcs.glGetBooleanv = [](GLenum, GLboolean* data) {
if (data == nullptr) return;
for (int i = 0; i < 4; ++i) data[i] = GL_TRUE;
for (int i = 0; i < 4; ++i)
data[i] = GL_TRUE;
};
funcs.glGetIntegeri_v = [](GLenum pname, GLuint index, GLint* data) {
if (data == nullptr) return;
@@ -506,9 +509,8 @@ namespace {
auto* out = static_cast<unsigned char*>(pixels);
if (out == nullptr) return;
const std::size_t index = g_fake.ioBlockReads++;
const bool arrives = index < g_fake.ioBlockPayloadArrives.size()
? g_fake.ioBlockPayloadArrives[index]
: true;
const bool arrives =
index < g_fake.ioBlockPayloadArrives.size() ? g_fake.ioBlockPayloadArrives[index] : true;
// 0.25 and 0.5 as the probe's vertex stage wrote them; zeroes are what a stage that
// received nothing reads.
out[0] = arrives ? 0x40 : 0x00;
@@ -539,18 +541,18 @@ namespace {
// Buffer-texture entry points, each present only when its knob says so. A real loader
// resolves the suffixed names only on a driver whose support is that extension.
funcs.glTexBuffer = g_fake.hasCoreTexBufferEntryPoint
? static_cast<MobileGL::MG_External::GLES::glTexBuffer_PTR>(
[](GLenum, GLenum, GLuint) {})
: nullptr;
funcs.glTexBufferEXT = g_fake.hasExtTexBufferEntryPoint
? static_cast<MobileGL::MG_External::GLES::glTexBufferEXT_PTR>(
[](GLenum, GLenum, GLuint) {})
: nullptr;
funcs.glTexBufferOES = g_fake.hasOesTexBufferEntryPoint
? static_cast<MobileGL::MG_External::GLES::glTexBufferOES_PTR>(
[](GLenum, GLenum, GLuint) {})
: nullptr;
funcs.glTexBuffer =
g_fake.hasCoreTexBufferEntryPoint
? static_cast<MobileGL::MG_External::GLES::glTexBuffer_PTR>([](GLenum, GLenum, GLuint) {})
: nullptr;
funcs.glTexBufferEXT =
g_fake.hasExtTexBufferEntryPoint
? static_cast<MobileGL::MG_External::GLES::glTexBufferEXT_PTR>([](GLenum, GLenum, GLuint) {})
: nullptr;
funcs.glTexBufferOES =
g_fake.hasOesTexBufferEntryPoint
? static_cast<MobileGL::MG_External::GLES::glTexBufferOES_PTR>([](GLenum, GLenum, GLuint) {})
: nullptr;
// The probe's vertex shader writes the gl_InstanceID it observed into the
// result SSBO at binding 0. A conforming driver observes 0; a leaking one
@@ -1169,21 +1171,23 @@ TEST(FragmentInterpolationCapabilities, QueryErrorIsDrainedAndFallsBackToCoreMin
// The extension string is what apps gate on (LWJGL builds GLCapabilities from it), so advertising
// it on a driver that cannot filter anisotropically would leave them silently on trilinear.
TEST(TextureAnisotropyCapabilities, ExtensionIsAdvertisedOnlyWhenTheHostDriverSupportsIt) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions,
MobileGL::GLExtension wanted) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions, MobileGL::GLExtension wanted) {
return std::find(extensions.begin(), extensions.end(), wanted) != extensions.end();
};
const auto without = MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false);
const auto without =
MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false);
EXPECT_FALSE(contains(without, MobileGL::E_GL_EXT_texture_filter_anisotropic));
EXPECT_FALSE(contains(without, MobileGL::E_GL_ARB_texture_filter_anisotropic));
const auto with = MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, true, false, false, false, false);
const auto with =
MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, true, false, false, false, false);
EXPECT_TRUE(contains(with, MobileGL::E_GL_EXT_texture_filter_anisotropic));
EXPECT_TRUE(contains(with, MobileGL::E_GL_ARB_texture_filter_anisotropic));
// Same rule on the Vulkan backend, where the gate is the samplerAnisotropy device feature.
const auto vkWithout = MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false);
const auto vkWithout =
MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false);
EXPECT_FALSE(contains(vkWithout, MobileGL::E_GL_EXT_texture_filter_anisotropic));
const auto vkWith = MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, true, false, false);
EXPECT_TRUE(contains(vkWith, MobileGL::E_GL_EXT_texture_filter_anisotropic));
@@ -1196,8 +1200,7 @@ TEST(TextureAnisotropyCapabilities, ExtensionIsAdvertisedOnlyWhenTheHostDriverSu
// and it has to BE there when the capability is, because KHR-GL4*.texture_gather.*-cube-array
// gates on the string with no core-version fallback.
TEST(CubeMapArrayAdvertisement, FollowsTheHostCapabilityOnBothBackends) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions,
MobileGL::GLExtension wanted) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions, MobileGL::GLExtension wanted) {
return std::find(extensions.begin(), extensions.end(), wanted) != extensions.end();
};
@@ -1208,8 +1211,8 @@ TEST(CubeMapArrayAdvertisement, FollowsTheHostCapabilityOnBothBackends) {
MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, true);
EXPECT_TRUE(contains(esWith, MobileGL::E_GL_ARB_texture_cube_map_array));
const auto vkWithout = MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false,
false);
const auto vkWithout =
MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false);
EXPECT_FALSE(contains(vkWithout, MobileGL::E_GL_ARB_texture_cube_map_array));
const auto vkWith = MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, true);
EXPECT_TRUE(contains(vkWith, MobileGL::E_GL_ARB_texture_cube_map_array));
@@ -1221,22 +1224,26 @@ TEST(CubeMapArrayAdvertisement, FollowsTheHostCapabilityOnBothBackends) {
// together so a future edit cannot quietly drop one, and pinned on BOTH backends so the two
// cannot disagree about what MobileGL is.
TEST(CorePlumbingAdvertisement, IsUnconditionalAndIdenticalOnBothBackends) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions,
MobileGL::GLExtension wanted) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions, MobileGL::GLExtension wanted) {
return std::find(extensions.begin(), extensions.end(), wanted) != extensions.end();
};
const MobileGL::GLExtension expected[] = {
MobileGL::E_GL_ARB_sync, MobileGL::E_GL_ARB_shader_atomic_counters,
MobileGL::E_GL_ARB_vertex_array_object, MobileGL::E_GL_ARB_sampler_objects,
MobileGL::E_GL_ARB_map_buffer_range, MobileGL::E_GL_ARB_copy_buffer,
MobileGL::E_GL_ARB_copy_image, MobileGL::E_GL_ARB_texture_swizzle,
MobileGL::E_GL_ARB_vertex_type_2_10_10_10_rev, MobileGL::E_GL_ARB_texture_rg,
MobileGL::E_GL_ARB_depth_buffer_float, MobileGL::E_GL_ARB_texture_float,
MobileGL::E_GL_ARB_viewport_array};
const MobileGL::GLExtension expected[] = {MobileGL::E_GL_ARB_sync,
MobileGL::E_GL_ARB_shader_atomic_counters,
MobileGL::E_GL_ARB_vertex_array_object,
MobileGL::E_GL_ARB_sampler_objects,
MobileGL::E_GL_ARB_map_buffer_range,
MobileGL::E_GL_ARB_copy_buffer,
MobileGL::E_GL_ARB_copy_image,
MobileGL::E_GL_ARB_texture_swizzle,
MobileGL::E_GL_ARB_vertex_type_2_10_10_10_rev,
MobileGL::E_GL_ARB_texture_rg,
MobileGL::E_GL_ARB_depth_buffer_float,
MobileGL::E_GL_ARB_texture_float,
MobileGL::E_GL_ARB_viewport_array};
// Every gate off: none of these may depend on one.
const auto es = MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false,
false);
const auto es =
MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false);
const auto vk = MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false);
for (const auto extension : expected) {
EXPECT_TRUE(contains(es, extension)) << "DirectGLES stopped advertising extension " << extension;
@@ -1249,18 +1256,17 @@ TEST(CorePlumbingAdvertisement, IsUnconditionalAndIdenticalOnBothBackends) {
// the same surface. Unconditional on both backends; only the tessellation string follows a probed
// device capability.
TEST(CoreSurfaceAdvertisement, BatchIsUnconditionalAndTessellationFollowsTheDevice) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions,
MobileGL::GLExtension wanted) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions, MobileGL::GLExtension wanted) {
return std::find(extensions.begin(), extensions.end(), wanted) != extensions.end();
};
const MobileGL::GLExtension expected[] = {
MobileGL::E_GL_ARB_transform_feedback2, MobileGL::E_GL_ARB_transform_feedback3,
MobileGL::E_GL_ARB_texture_rgb10_a2ui, MobileGL::E_GL_EXT_texture_shared_exponent,
MobileGL::E_GL_EXT_texture_integer, MobileGL::E_GL_ARB_pipeline_statistics_query,
MobileGL::E_GL_ARB_transform_feedback2, MobileGL::E_GL_ARB_transform_feedback3,
MobileGL::E_GL_ARB_texture_rgb10_a2ui, MobileGL::E_GL_EXT_texture_shared_exponent,
MobileGL::E_GL_EXT_texture_integer, MobileGL::E_GL_ARB_pipeline_statistics_query,
MobileGL::E_GL_EXT_shader_integer_mix};
const auto es = MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false,
false);
const auto es =
MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false);
const auto vk = MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false);
for (const auto extension : expected) {
EXPECT_TRUE(contains(es, extension)) << "DirectGLES does not advertise extension " << extension;
@@ -1273,33 +1279,32 @@ TEST(CoreSurfaceAdvertisement, BatchIsUnconditionalAndTessellationFollowsTheDevi
EXPECT_FALSE(contains(es, MobileGL::E_GL_ARB_tessellation_shader));
EXPECT_FALSE(contains(vk, MobileGL::E_GL_ARB_tessellation_shader));
const MobileGL::MG_Backend::AdvertisedFeatureSupport tessellation{.TessellationShader = true};
EXPECT_TRUE(contains(MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false,
false, false, tessellation),
MobileGL::E_GL_ARB_tessellation_shader));
EXPECT_TRUE(contains(MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false,
false, tessellation),
EXPECT_TRUE(contains(MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false,
false, tessellation),
MobileGL::E_GL_ARB_tessellation_shader));
EXPECT_TRUE(contains(
MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false, tessellation),
MobileGL::E_GL_ARB_tessellation_shader));
}
// ARB_cull_distance follows the backend's cull-distance capability, never the context version.
TEST(CoreSurfaceAdvertisement, CullDistanceFollowsTheDevice) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions,
MobileGL::GLExtension wanted) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions, MobileGL::GLExtension wanted) {
return std::find(extensions.begin(), extensions.end(), wanted) != extensions.end();
};
EXPECT_FALSE(contains(MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false,
false, false),
MobileGL::E_GL_ARB_cull_distance));
EXPECT_FALSE(contains(MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false,
false),
MobileGL::E_GL_ARB_cull_distance));
EXPECT_FALSE(
contains(MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false),
MobileGL::E_GL_ARB_cull_distance));
EXPECT_FALSE(
contains(MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false),
MobileGL::E_GL_ARB_cull_distance));
const MobileGL::MG_Backend::AdvertisedFeatureSupport cull{.CullDistance = true};
EXPECT_TRUE(contains(MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false,
false, false, cull),
MobileGL::E_GL_ARB_cull_distance));
EXPECT_TRUE(contains(MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false,
false, cull),
MobileGL::E_GL_ARB_cull_distance));
EXPECT_TRUE(contains(
MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false, cull),
MobileGL::E_GL_ARB_cull_distance));
EXPECT_TRUE(
contains(MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false, cull),
MobileGL::E_GL_ARB_cull_distance));
}
// ES 3.2 has tessellation in core; ES 3.1 only through GL_EXT_tessellation_shader. Either way the
@@ -1367,28 +1372,26 @@ TEST(ClipControlCapabilities, NeedTheExtensionAndTheEntryPoint) {
// DirectGLES advertises ARB_clip_control on the driver's extension; DirectVulkan always, since it
// applies clip control in its own position fixup.
TEST(CoreSurfaceAdvertisement, ClipControlFollowsTheBackendsRoute) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions,
MobileGL::GLExtension wanted) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions, MobileGL::GLExtension wanted) {
return std::find(extensions.begin(), extensions.end(), wanted) != extensions.end();
};
EXPECT_FALSE(contains(MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false,
false, false),
MobileGL::E_GL_ARB_clip_control));
EXPECT_FALSE(
contains(MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false),
MobileGL::E_GL_ARB_clip_control));
const MobileGL::MG_Backend::AdvertisedFeatureSupport clipControl{.ClipControl = true};
EXPECT_TRUE(contains(MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false,
false, false, clipControl),
MobileGL::E_GL_ARB_clip_control));
EXPECT_TRUE(contains(MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false,
false),
EXPECT_TRUE(contains(MobileGL::MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false,
false, clipControl),
MobileGL::E_GL_ARB_clip_control));
EXPECT_TRUE(
contains(MobileGL::MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false),
MobileGL::E_GL_ARB_clip_control));
}
// Minecraft 26.3 checks ARB_draw_indirect before it considers the already-advertised
// ARB_multi_draw_indirect, then separately requires ARB_base_instance before enabling its terrain
// indirect path. Pin both strings and, just as importantly, the non-zero firstInstance gate.
TEST(IndirectDrawAdvertisement, MatchesEachBackendsUsableCommandSemantics) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions,
MobileGL::GLExtension wanted) {
const auto contains = [](const MobileGL::Vector<MobileGL::GLExtension>& extensions, MobileGL::GLExtension wanted) {
return std::find(extensions.begin(), extensions.end(), wanted) != extensions.end();
};
@@ -1467,8 +1470,8 @@ TEST(MultiDrawCapabilities, PointerAloneNeverCountsAsSupport) {
// Simulate the stub hazard: every pointer resolved, no extension advertised.
funcs.glMultiDrawArraysIndirectEXT = [](GLenum, const void*, GLsizei, GLsizei) {};
funcs.glMultiDrawElementsIndirectEXT = [](GLenum, GLenum, const void*, GLsizei, GLsizei) {};
funcs.glMultiDrawElementsBaseVertexEXT = [](GLenum, const GLsizei*, GLenum, const void* const*,
GLsizei, const GLint*) {};
funcs.glMultiDrawElementsBaseVertexEXT = [](GLenum, const GLsizei*, GLenum, const void* const*, GLsizei,
const GLint*) {};
MobileGL::MG_External::GLESCapabilities stubCaps;
ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(stubCaps, funcs));
@@ -1537,8 +1540,7 @@ TEST(DrawIndirectCapabilities, RequiresEs31AndBothCoreEntryPoints) {
g_fake.maxVertexSsboBlocks = 0;
const auto missingElements = MakeFakeGLESFunctions();
MobileGL::MG_External::GLESCapabilities missingEntryPointCaps;
ASSERT_TRUE(
MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(missingEntryPointCaps, missingElements));
ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(missingEntryPointCaps, missingElements));
EXPECT_FALSE(missingEntryPointCaps.SupportsDrawIndirect);
}
@@ -1547,10 +1549,9 @@ TEST(BaseInstanceCapabilities, RequiresTheExtensionAndAllThreeEntryPoints) {
g_fake.maxVertexSsboBlocks = 0;
auto funcs = MakeFakeGLESFunctions();
funcs.glDrawArraysInstancedBaseInstanceEXT = [](GLenum, GLint, GLsizei, GLsizei, GLuint) {};
funcs.glDrawElementsInstancedBaseInstanceEXT =
[](GLenum, GLsizei, GLenum, const void*, GLsizei, GLuint) {};
funcs.glDrawElementsInstancedBaseVertexBaseInstanceEXT =
[](GLenum, GLsizei, GLenum, const void*, GLsizei, GLint, GLuint) {};
funcs.glDrawElementsInstancedBaseInstanceEXT = [](GLenum, GLsizei, GLenum, const void*, GLsizei, GLuint) {};
funcs.glDrawElementsInstancedBaseVertexBaseInstanceEXT = [](GLenum, GLsizei, GLenum, const void*, GLsizei, GLint,
GLuint) {};
// Resolved stubs alone must never make the capability true.
MobileGL::MG_External::GLESCapabilities pointersOnlyCaps;
@@ -1569,8 +1570,7 @@ TEST(BaseInstanceCapabilities, RequiresTheExtensionAndAllThreeEntryPoints) {
g_fake.extensions.emplace_back("GL_EXT_base_instance");
funcs.glDrawElementsInstancedBaseInstanceEXT = nullptr;
MobileGL::MG_External::GLESCapabilities missingEntryPointCaps;
ASSERT_TRUE(
MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(missingEntryPointCaps, funcs));
ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(missingEntryPointCaps, funcs));
EXPECT_FALSE(missingEntryPointCaps.SupportsBaseInstance);
}
@@ -1749,7 +1749,9 @@ namespace {
bool g_damageKhrAvailable = false;
std::vector<std::string> g_damageQueries;
EGLDisplay FakeDamageDisplay() { return g_damageDisplay; }
EGLDisplay FakeDamageDisplay() {
return g_damageDisplay;
}
const char* FakeDamageQueryString(EGLDisplay display, EGLint name) {
EXPECT_EQ(display, g_damageDisplay);
EXPECT_EQ(name, EGL_EXTENSIONS);
@@ -1766,8 +1768,8 @@ namespace {
__eglMustCastToProperFunctionPointerType FakeDamageGetProcAddress(const char* name) {
g_damageQueries.emplace_back(name);
const bool available = std::string(name) == "eglSwapBuffersWithDamageEXT"
? g_damageExtAvailable : g_damageKhrAvailable;
const bool available =
std::string(name) == "eglSwapBuffersWithDamageEXT" ? g_damageExtAvailable : g_damageKhrAvailable;
return available ? reinterpret_cast<__eglMustCastToProperFunctionPointerType>(&FakeSwapBuffersWithDamage)
: nullptr;
}
@@ -1797,7 +1799,8 @@ TEST(SwapBuffersWithDamageResolution, PrefersExtThenKhrThenAnswersNothing) {
g_damageExtAvailable = false;
g_damageQueries.clear();
EXPECT_EQ(MG_Util::BackendLoader::ResolveSwapBuffersWithDamage(funcs), &FakeSwapBuffersWithDamage);
EXPECT_EQ(g_damageQueries, (std::vector<std::string>{"eglSwapBuffersWithDamageEXT", "eglSwapBuffersWithDamageKHR"}));
EXPECT_EQ(g_damageQueries,
(std::vector<std::string>{"eglSwapBuffersWithDamageEXT", "eglSwapBuffersWithDamageKHR"}));
g_damageExtensions = "EGL_KHR_swap_buffers_with_damage";
g_damageQueries.clear();
+108 -103
View File
@@ -23,15 +23,13 @@
using namespace MobileGL;
class BufferTest : public ::testing::Test {
protected:
// GL error flags are sticky per error code and the context outlives an individual test in this
// binary, so drain whatever an earlier test left pending - otherwise an error-code assertion
// here reads someone else's error. Bounded: one flag per code, so this cannot hang the suite.
static void DrainPendingGlErrors() {
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {}
}
// The call under test must raise exactly the expected error and nothing more: a second pending
@@ -300,7 +298,8 @@ TEST_F(BufferTest, MappedPointersHonourTheAdvertisedMapBufferAlignment) {
const SizeT offset = alignment - 1;
bufObj->Resize(bufferSize);
Vector<Uint8> initData(bufferSize);
for (SizeT i = 0; i < bufferSize; ++i) initData[i] = static_cast<Uint8>(i);
for (SizeT i = 0; i < bufferSize; ++i)
initData[i] = static_cast<Uint8>(i);
bufObj->UploadData(DataPtr{.data = initData.data(), .size = bufferSize}, 0);
const auto addressOf = [](const void* pointer) { return reinterpret_cast<std::uintptr_t>(pointer); };
@@ -366,8 +365,8 @@ TEST_F(BufferTest, ExplicitFlushOfARangeMapFollowsTheAlignmentBias) {
bufObj->UploadData(DataPtr{.data = initData.data(), .size = bufferSize}, 0);
const Range1D mapRange{.start = offset, .end = bufferSize};
Uint8* mapped = static_cast<Uint8*>(bufObj->AcquireMemoryRange(
mapRange, BufferMappingAccessBit::Write | BufferMappingAccessBit::FlushExplicit));
Uint8* mapped = static_cast<Uint8*>(
bufObj->AcquireMemoryRange(mapRange, BufferMappingAccessBit::Write | BufferMappingAccessBit::FlushExplicit));
ASSERT_NE(mapped, nullptr);
mapped[4] = 0x5A;
mapped[5] = 0x5B;
@@ -724,9 +723,9 @@ TEST_F(BufferTest, ClearNamedBufferSubDataAcceptsSignedNormalizedIntPattern) {
MobileGL::MG_Impl::GLImpl::CreateBuffers(1, &buffer);
const Vector<Uint8> initial(24, 0x7F);
MobileGL::MG_Impl::GLImpl::NamedBufferStorage(
buffer, initial.size(), initial.data(),
GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_DYNAMIC_STORAGE_BIT | GL_MAP_PERSISTENT_BIT);
MobileGL::MG_Impl::GLImpl::NamedBufferStorage(buffer, initial.size(), initial.data(),
GL_MAP_READ_BIT | GL_MAP_WRITE_BIT | GL_DYNAMIC_STORAGE_BIT |
GL_MAP_PERSISTENT_BIT);
ASSERT_EQ(MobileGL::MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
const GLint zero = 0;
@@ -738,7 +737,8 @@ TEST_F(BufferTest, ClearNamedBufferSubDataAcceptsSignedNormalizedIntPattern) {
ASSERT_NE(bufferObject, nullptr);
Memcpy(actual.data(), bufferObject->AcquireMemory(false, true, false), actual.size());
Vector<Uint8> expected(initial);
for (SizeT i = 0; i < sizeof(GLint); ++i) expected[i] = 0;
for (SizeT i = 0; i < sizeof(GLint); ++i)
expected[i] = 0;
EXPECT_EQ(actual, expected);
MobileGL::MG_Impl::GLImpl::DeleteBuffers(1, &buffer);
@@ -776,11 +776,10 @@ TEST_F(BufferTest, ClearBufferSubDataInitializesIrisStaticSsboRange) {
MobileGL::MG_Impl::GLImpl::BindBuffer(GL_SHADER_STORAGE_BUFFER, buffer);
Vector<Uint8> initial(32, 0x7F);
MobileGL::MG_Impl::GLImpl::BufferData(
GL_SHADER_STORAGE_BUFFER, initial.size(), initial.data(), GL_STATIC_DRAW);
MobileGL::MG_Impl::GLImpl::BufferData(GL_SHADER_STORAGE_BUFFER, initial.size(), initial.data(), GL_STATIC_DRAW);
const GLbyte zero = 0;
const auto clear = reinterpret_cast<PFNGLCLEARBUFFERSUBDATAPROC>(
MobileGL::MG_Impl::GetProcAddress("glClearBufferSubData"));
const auto clear =
reinterpret_cast<PFNGLCLEARBUFFERSUBDATAPROC>(MobileGL::MG_Impl::GetProcAddress("glClearBufferSubData"));
ASSERT_NE(clear, nullptr);
clear(GL_SHADER_STORAGE_BUFFER, GL_R8, 4, 24, GL_RED, GL_BYTE, &zero);
@@ -788,10 +787,8 @@ TEST_F(BufferTest, ClearBufferSubDataInitializesIrisStaticSsboRange) {
auto bufferObject = MobileGL::MG_State::pGLContext->GetBufferObject(buffer);
ASSERT_NE(bufferObject, nullptr);
Memcpy(actual.data(), bufferObject->AcquireMemory(false, true, false), actual.size());
EXPECT_EQ(actual, (Vector<Uint8>{0x7F, 0x7F, 0x7F, 0x7F,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0x7F, 0x7F, 0x7F, 0x7F}));
EXPECT_EQ(actual, (Vector<Uint8>{0x7F, 0x7F, 0x7F, 0x7F, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7F, 0x7F, 0x7F, 0x7F}));
EXPECT_EQ(MobileGL::MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
MobileGL::MG_Impl::GLImpl::BindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
@@ -806,11 +803,10 @@ TEST_F(BufferTest, ClearBufferSubDataInitializesCompleteIrisStaticSsbo) {
MobileGL::MG_Impl::GLImpl::BindBuffer(GL_SHADER_STORAGE_BUFFER, buffer);
Vector<Uint8> initial(irisStaticSsboSize, 0x7F);
MobileGL::MG_Impl::GLImpl::BufferData(
GL_SHADER_STORAGE_BUFFER, initial.size(), initial.data(), GL_STATIC_DRAW);
MobileGL::MG_Impl::GLImpl::BufferData(GL_SHADER_STORAGE_BUFFER, initial.size(), initial.data(), GL_STATIC_DRAW);
const GLbyte zero = 0;
MobileGL::MG_Impl::GLImpl::ClearBufferSubData(
GL_SHADER_STORAGE_BUFFER, GL_R8, 0, irisStaticSsboSize, GL_RED, GL_BYTE, &zero);
MobileGL::MG_Impl::GLImpl::ClearBufferSubData(GL_SHADER_STORAGE_BUFFER, GL_R8, 0, irisStaticSsboSize, GL_RED,
GL_BYTE, &zero);
Vector<Uint8> actual(irisStaticSsboSize);
auto bufferObject = MobileGL::MG_State::pGLContext->GetBufferObject(buffer);
@@ -831,10 +827,9 @@ TEST_F(BufferTest, ClearBufferDataConvertsOneClientPixelBeforeRepeatingIt) {
Vector<Uint32> initial(4, 0u);
MobileGL::MG_Impl::GLImpl::BufferData(GL_ARRAY_BUFFER, initial.size() * sizeof(Uint32), initial.data(),
GL_STATIC_DRAW);
GL_STATIC_DRAW);
const Uint8 value = 0xAB;
MobileGL::MG_Impl::GLImpl::ClearBufferData(
GL_ARRAY_BUFFER, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE, &value);
MobileGL::MG_Impl::GLImpl::ClearBufferData(GL_ARRAY_BUFFER, GL_R32UI, GL_RED_INTEGER, GL_UNSIGNED_BYTE, &value);
Vector<Uint32> actual(initial.size());
auto bufferObject = MobileGL::MG_State::pGLContext->GetBufferObject(buffer);
@@ -851,8 +846,7 @@ TEST_F(BufferTest, ClearBufferDataConvertsOneClientPixelBeforeRepeatingIt) {
TEST_F(BufferTest, ClearBufferSubDataRejectsUnboundTarget) {
MobileGL::MG_Impl::GLImpl::BindBuffer(GL_SHADER_STORAGE_BUFFER, 0);
const GLbyte zero = 0;
MobileGL::MG_Impl::GLImpl::ClearBufferSubData(
GL_SHADER_STORAGE_BUFFER, GL_R8, 0, 1, GL_RED, GL_BYTE, &zero);
MobileGL::MG_Impl::GLImpl::ClearBufferSubData(GL_SHADER_STORAGE_BUFFER, GL_R8, 0, 1, GL_RED, GL_BYTE, &zero);
ExpectSingleGlError(GL_INVALID_OPERATION);
}
@@ -864,11 +858,9 @@ TEST_F(BufferTest, ClearBufferDataRejectsInvalidPixelFormatTypePairs) {
const Vector<Uint8> initial{0x7F, 0x7F};
MobileGL::MG_Impl::GLImpl::BufferData(GL_ARRAY_BUFFER, initial.size(), initial.data(), GL_STATIC_DRAW);
const Uint16 packed = 0;
MobileGL::MG_Impl::GLImpl::ClearBufferData(
GL_ARRAY_BUFFER, GL_R16, GL_RED, GL_UNSIGNED_SHORT_5_6_5, &packed);
MobileGL::MG_Impl::GLImpl::ClearBufferData(GL_ARRAY_BUFFER, GL_R16, GL_RED, GL_UNSIGNED_SHORT_5_6_5, &packed);
ExpectSingleGlError(GL_INVALID_VALUE);
MobileGL::MG_Impl::GLImpl::ClearBufferData(
GL_ARRAY_BUFFER, GL_R16, GL_RED, GL_UNSIGNED_SHORT_5_6_5, nullptr);
MobileGL::MG_Impl::GLImpl::ClearBufferData(GL_ARRAY_BUFFER, GL_R16, GL_RED, GL_UNSIGNED_SHORT_5_6_5, nullptr);
ExpectSingleGlError(GL_INVALID_VALUE);
Vector<Uint8> actual(initial.size());
@@ -882,7 +874,6 @@ TEST_F(BufferTest, ClearBufferDataRejectsInvalidPixelFormatTypePairs) {
DrainPendingGlErrors();
}
// GL 4.6 core 6.5: glBufferSubData fails only when the written range OVERLAPS the mapped range.
// A second, wrong test used to sit next to the correct one and reject any write whose end reached
// the start of the mapping - which killed every legal disjoint update in front of a mapped tail.
@@ -1117,8 +1108,7 @@ TEST_F(BufferTest, BindBufferRangeEnforcesUniformAndTransformFeedbackAlignment)
// Transform feedback captures 32-bit components: offset and size are both constrained, and the
// size half has no analogue on any other target.
auto& feedbackPoint =
MobileGL::MG_State::pGLContext->GetBufferBindingPoint(BufferTarget::TransformFeedback, 0);
auto& feedbackPoint = MobileGL::MG_State::pGLContext->GetBufferBindingPoint(BufferTarget::TransformFeedback, 0);
MobileGL::MG_Impl::GLImpl::BindBufferRange(GL_TRANSFORM_FEEDBACK_BUFFER, 0, buffer, 2, 4);
ExpectSingleGlError(GL_INVALID_VALUE);
EXPECT_EQ(feedbackPoint.GetBoundObject(), nullptr);
@@ -1394,9 +1384,8 @@ TEST_F(GeneralBufferTest, General_PersistentCoherentWriteDirtyWithoutUnmap) {
ASSERT_NE(bufferObject, nullptr);
const Uint64 baseSerial = bufferObject->GetChangeSerial();
auto* mapped = static_cast<GLint*>(
MapBufferRange(GL_ARRAY_BUFFER, 0, sizeof(initial),
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT));
auto* mapped = static_cast<GLint*>(MapBufferRange(GL_ARRAY_BUFFER, 0, sizeof(initial),
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT));
ASSERT_NE(mapped, nullptr);
mapped[2] = 1234;
@@ -1422,9 +1411,8 @@ TEST_F(GeneralBufferTest, General_PersistentExplicitFlushOnlyDirtiesFlushedRange
ASSERT_NE(bufferObject, nullptr);
const Uint64 baseSerial = bufferObject->GetChangeSerial();
auto* mapped = static_cast<GLint*>(
MapBufferRange(GL_ARRAY_BUFFER, 0, sizeof(initial),
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_FLUSH_EXPLICIT_BIT));
auto* mapped = static_cast<GLint*>(MapBufferRange(
GL_ARRAY_BUFFER, 0, sizeof(initial), GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_FLUSH_EXPLICIT_BIT));
ASSERT_NE(mapped, nullptr);
mapped[1] = 200;
mapped[3] = 400;
@@ -1456,9 +1444,8 @@ TEST_F(GeneralBufferTest, General_NamedBufferStorageMappingWrappers) {
ASSERT_NE(bufferObject, nullptr);
const Uint64 baseSerial = bufferObject->GetChangeSerial();
auto* mapped = static_cast<GLint*>(
MapNamedBufferRange(buffer, 0, sizeof(initial),
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_FLUSH_EXPLICIT_BIT));
auto* mapped = static_cast<GLint*>(MapNamedBufferRange(
buffer, 0, sizeof(initial), GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_FLUSH_EXPLICIT_BIT));
ASSERT_NE(mapped, nullptr);
mapped[0] = 99;
@@ -1671,8 +1658,6 @@ namespace {
};
} // namespace
// ---------------------------------------------------------------------------
// MOBILEGL_COHERENT_AS_FLUSH: persistent FLUSH_EXPLICIT mapping requests are
// rewritten to coherent semantics, so apps that bind mapped ranges for GPU reads
@@ -1817,9 +1802,9 @@ TEST_F(GeneralBufferTest, General_CoherentAsFlush_PersistentMapAdoptsZeroCopyBac
// Flywheel-style map: FLUSH_EXPLICIT and never flushed. Under the feature it becomes
// coherent-persistent and takes the zero-copy path: the app writes straight into the
// backend's GPU storage, so nothing depends on flush calls.
auto* mapped = static_cast<GLint*>(
MapBufferRange(GL_ARRAY_BUFFER, 0, static_cast<GLsizeiptr>(kCount * sizeof(GLint)),
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_FLUSH_EXPLICIT_BIT));
auto* mapped =
static_cast<GLint*>(MapBufferRange(GL_ARRAY_BUFFER, 0, static_cast<GLsizeiptr>(kCount * sizeof(GLint)),
GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_FLUSH_EXPLICIT_BIT));
ASSERT_NE(mapped, nullptr);
EXPECT_EQ(mock.acquireMapCalls, 1);
@@ -1877,8 +1862,7 @@ TEST_F(BufferTest, RedefiningAnAdoptedBufferHandsTheMappingBack) {
// The backend adopts the bytes, exactly as a capture target or an SSBO binding does.
ASSERT_TRUE(bufferObject->EnsureGpuResidentStorage());
ASSERT_TRUE(bufferObject->IsBackendPersistentMapped());
ASSERT_EQ(static_cast<const void*>(bufferObject->MappedData()),
static_cast<const void*>(mock.gpu.data()));
ASSERT_EQ(static_cast<const void*>(bufferObject->MappedData()), static_cast<const void*>(mock.gpu.data()));
mock.respecifyCalls = 0;
const GLint after[4] = {10, 20, 30, 40};
@@ -1886,8 +1870,7 @@ TEST_F(BufferTest, RedefiningAnAdoptedBufferHandsTheMappingBack) {
ASSERT_EQ(GetError(), GL_NO_ERROR);
EXPECT_FALSE(bufferObject->IsBackendPersistentMapped());
EXPECT_NE(static_cast<const void*>(bufferObject->MappedData()),
static_cast<const void*>(mock.gpu.data()));
EXPECT_NE(static_cast<const void*>(bufferObject->MappedData()), static_cast<const void*>(mock.gpu.data()));
EXPECT_EQ(std::memcmp(bufferObject->MappedData(), after, sizeof(after)), 0);
// The backend has a separate copy again, so it must have been told to refresh it.
EXPECT_EQ(mock.respecifyCalls, 1);
@@ -2052,9 +2035,9 @@ namespace {
GenBuffers(1, &buffer);
BindBuffer(target, buffer);
Vector<GLint> initial(kAdoptedInts);
for (SizeT i = 0; i < kAdoptedInts; ++i) initial[i] = static_cast<GLint>(i);
BufferData(target, static_cast<GLsizeiptr>(kAdoptedInts * sizeof(GLint)), initial.data(),
GL_DYNAMIC_DRAW);
for (SizeT i = 0; i < kAdoptedInts; ++i)
initial[i] = static_cast<GLint>(i);
BufferData(target, static_cast<GLsizeiptr>(kAdoptedInts * sizeof(GLint)), initial.data(), GL_DYNAMIC_DRAW);
EXPECT_EQ(GetError(), GL_NO_ERROR);
auto bufferObject = MG_State::pGLContext->GetBufferObject(buffer);
EXPECT_NE(bufferObject, nullptr);
@@ -2088,8 +2071,10 @@ TEST_F(BufferTest, ANonPersistentReadWriteRangeMapOfAnAdoptedStoreLandsAtUnmap)
ASSERT_NE(mapped, nullptr);
// A non-persistent map is a staging copy, seeded from the adopted store...
EXPECT_NE(static_cast<void*>(mapped), static_cast<void*>(mock.gpu.data()));
for (SizeT i = 0; i < kAdoptedInts; ++i) EXPECT_EQ(mapped[i], static_cast<GLint>(i));
for (SizeT i = 0; i < kAdoptedInts; ++i) mapped[i] = 1000 + static_cast<GLint>(i);
for (SizeT i = 0; i < kAdoptedInts; ++i)
EXPECT_EQ(mapped[i], static_cast<GLint>(i));
for (SizeT i = 0; i < kAdoptedInts; ++i)
mapped[i] = 1000 + static_cast<GLint>(i);
// ...that the store does not see until the unmap.
EXPECT_EQ(GpuInts(mock)[0], 0);
bufferObject->ReleaseMemory();
@@ -2170,7 +2155,8 @@ TEST_F(BufferTest, AWriteMapInvalidatingAnAdoptedStoreLandsTheWholeRangeAtUnmap)
ASSERT_NE(mapped, nullptr);
EXPECT_NE(static_cast<void*>(mapped), static_cast<void*>(mock.gpu.data()));
// The whole range is undefined by contract, so the application rewrites all of it.
for (SizeT i = 0; i < kAdoptedInts; ++i) mapped[i] = -static_cast<GLint>(i) - 1;
for (SizeT i = 0; i < kAdoptedInts; ++i)
mapped[i] = -static_cast<GLint>(i) - 1;
bufferObject->ReleaseMemory();
for (SizeT i = 0; i < kAdoptedInts; ++i) {
@@ -2204,14 +2190,16 @@ TEST_F(BufferTest, ARangeMapAtAnUnalignedOffsetOfAnAdoptedStoreLandsInPlace) {
auto* mapped = static_cast<GLint*>(bufferObject->AcquireMemoryRange(range, BufferMappingAccessBit::Write));
ASSERT_NE(mapped, nullptr);
// Seeded from the right place...
for (SizeT i = 0; i < kCount; ++i) EXPECT_EQ(mapped[i], static_cast<GLint>(kFirst + i));
for (SizeT i = 0; i < kCount; ++i) mapped[i] = 500 + static_cast<GLint>(i);
for (SizeT i = 0; i < kCount; ++i)
EXPECT_EQ(mapped[i], static_cast<GLint>(kFirst + i));
for (SizeT i = 0; i < kCount; ++i)
mapped[i] = 500 + static_cast<GLint>(i);
bufferObject->ReleaseMemory();
// ...and landed in the right place, with everything outside the range untouched.
for (SizeT i = 0; i < kAdoptedInts; ++i) {
const GLint expected = (i >= kFirst && i < kFirst + kCount) ? 500 + static_cast<GLint>(i - kFirst)
: static_cast<GLint>(i);
const GLint expected =
(i >= kFirst && i < kFirst + kCount) ? 500 + static_cast<GLint>(i - kFirst) : static_cast<GLint>(i);
EXPECT_EQ(GpuInts(mock)[i], expected) << "int " << i;
}
EXPECT_GT(bufferObject->GetChangeSerial(), baseSerial);
@@ -2237,10 +2225,11 @@ TEST_F(BufferTest, AnExplicitFlushOfAWriteMapOfAnAdoptedStoreLandsOnlyTheFlushed
constexpr SizeT kFirst = 2;
constexpr SizeT kCount = 12;
const Range1D range{kFirst * sizeof(GLint), (kFirst + kCount) * sizeof(GLint)};
auto* mapped = static_cast<GLint*>(bufferObject->AcquireMemoryRange(
range, BufferMappingAccessBit::Write | BufferMappingAccessBit::FlushExplicit));
auto* mapped = static_cast<GLint*>(
bufferObject->AcquireMemoryRange(range, BufferMappingAccessBit::Write | BufferMappingAccessBit::FlushExplicit));
ASSERT_NE(mapped, nullptr);
for (SizeT i = 0; i < kCount; ++i) mapped[i] = 700 + static_cast<GLint>(i);
for (SizeT i = 0; i < kCount; ++i)
mapped[i] = 700 + static_cast<GLint>(i);
// ...but only ints 5..8 (map-relative ints 3..6) flushed.
constexpr SizeT kFlushFirst = 3;
constexpr SizeT kFlushCount = 4;
@@ -2284,10 +2273,11 @@ TEST_F(BufferTest, ABackendWithAResidentSubDataOpTakesTheUnmappedBytesForAGpuOrd
constexpr SizeT kFirst = 3;
constexpr SizeT kCount = 5;
const Range1D range{kFirst * sizeof(GLint), (kFirst + kCount) * sizeof(GLint)};
auto* mapped = static_cast<GLint*>(bufferObject->AcquireMemoryRange(
range, BufferMappingAccessBit::Read | BufferMappingAccessBit::Write));
auto* mapped = static_cast<GLint*>(
bufferObject->AcquireMemoryRange(range, BufferMappingAccessBit::Read | BufferMappingAccessBit::Write));
ASSERT_NE(mapped, nullptr);
for (SizeT i = 0; i < kCount; ++i) mapped[i] = 900 + static_cast<GLint>(i);
for (SizeT i = 0; i < kCount; ++i)
mapped[i] = 900 + static_cast<GLint>(i);
bufferObject->ReleaseMemory();
// The op got exactly the mapped range's bytes at the mapped offset...
@@ -2295,9 +2285,11 @@ TEST_F(BufferTest, ABackendWithAResidentSubDataOpTakesTheUnmappedBytesForAGpuOrd
EXPECT_EQ(mock.residentWrites[0].offset, range.start);
ASSERT_EQ(mock.residentWrites[0].bytes.size(), kCount * sizeof(GLint));
const auto* handed = reinterpret_cast<const GLint*>(mock.residentWrites[0].bytes.data());
for (SizeT i = 0; i < kCount; ++i) EXPECT_EQ(handed[i], 900 + static_cast<GLint>(i)) << "int " << i;
for (SizeT i = 0; i < kCount; ++i)
EXPECT_EQ(handed[i], 900 + static_cast<GLint>(i)) << "int " << i;
// ...the mapping itself was not written through...
for (SizeT i = 0; i < kAdoptedInts; ++i) EXPECT_EQ(GpuInts(mock)[i], static_cast<GLint>(i)) << "int " << i;
for (SizeT i = 0; i < kAdoptedInts; ++i)
EXPECT_EQ(GpuInts(mock)[i], static_cast<GLint>(i)) << "int " << i;
EXPECT_GT(bufferObject->GetChangeSerial(), baseSerial);
EXPECT_EQ(mock.flushCalls, 0);
EXPECT_EQ(mock.subDataCalls, 0);
@@ -2308,8 +2300,8 @@ TEST_F(BufferTest, ABackendWithAResidentSubDataOpTakesTheUnmappedBytesForAGpuOrd
EXPECT_EQ(mock.readbackCalls, 1);
EXPECT_TRUE(mock.residentWrites.empty());
for (SizeT i = 0; i < kAdoptedInts; ++i) {
const GLint expected = (i >= kFirst && i < kFirst + kCount) ? 900 + static_cast<GLint>(i - kFirst)
: static_cast<GLint>(i);
const GLint expected =
(i >= kFirst && i < kFirst + kCount) ? 900 + static_cast<GLint>(i - kFirst) : static_cast<GLint>(i);
EXPECT_EQ(readBack[i], expected) << "int " << i;
}
// A second read has nothing outstanding to reconcile.
@@ -2331,10 +2323,11 @@ TEST_F(BufferTest, ABackendWithAResidentSubDataOpTakesAnExplicitlyFlushedRangeTh
constexpr SizeT kFirst = 2;
constexpr SizeT kCount = 8;
const Range1D range{kFirst * sizeof(GLint), (kFirst + kCount) * sizeof(GLint)};
auto* mapped = static_cast<GLint*>(bufferObject->AcquireMemoryRange(
range, BufferMappingAccessBit::Write | BufferMappingAccessBit::FlushExplicit));
auto* mapped = static_cast<GLint*>(
bufferObject->AcquireMemoryRange(range, BufferMappingAccessBit::Write | BufferMappingAccessBit::FlushExplicit));
ASSERT_NE(mapped, nullptr);
for (SizeT i = 0; i < kCount; ++i) mapped[i] = 800 + static_cast<GLint>(i);
for (SizeT i = 0; i < kCount; ++i)
mapped[i] = 800 + static_cast<GLint>(i);
constexpr SizeT kFlushFirst = 5;
constexpr SizeT kFlushCount = 2;
bufferObject->FlushMemoryRange(kFlushFirst * sizeof(GLint), kFlushCount * sizeof(GLint));
@@ -2368,12 +2361,13 @@ TEST_F(BufferTest, MapBufferRangeAndUnmapBufferReseedAnAdoptedShaderStorageBuffe
ASSERT_NE(bufferObject, nullptr);
for (GLint pass = 1; pass <= 3; ++pass) {
auto* mapped = static_cast<GLint*>(
MapBufferRange(GL_SHADER_STORAGE_BUFFER, 0, static_cast<GLsizeiptr>(kAdoptedInts * sizeof(GLint)),
GL_MAP_READ_BIT | GL_MAP_WRITE_BIT));
auto* mapped = static_cast<GLint*>(MapBufferRange(GL_SHADER_STORAGE_BUFFER, 0,
static_cast<GLsizeiptr>(kAdoptedInts * sizeof(GLint)),
GL_MAP_READ_BIT | GL_MAP_WRITE_BIT));
ASSERT_NE(mapped, nullptr);
ASSERT_EQ(GetError(), GL_NO_ERROR);
for (SizeT i = 0; i < kAdoptedInts; ++i) mapped[i] = pass * 100 + static_cast<GLint>(i);
for (SizeT i = 0; i < kAdoptedInts; ++i)
mapped[i] = pass * 100 + static_cast<GLint>(i);
EXPECT_TRUE(UnmapBuffer(GL_SHADER_STORAGE_BUFFER));
ASSERT_EQ(GetError(), GL_NO_ERROR);
for (SizeT i = 0; i < kAdoptedInts; ++i) {
@@ -2436,7 +2430,8 @@ TEST_F(BufferTest, ABackendWithAResidentSubDataOpTakesAGlBufferSubDataAtItsOffse
ASSERT_EQ(mock.residentWrites[0].bytes.size(), sizeof(updated));
EXPECT_EQ(std::memcmp(mock.residentWrites[0].bytes.data(), updated, sizeof(updated)), 0);
// The mapping itself is left alone until the backend's ordered copy runs.
for (SizeT i = 0; i < kAdoptedInts; ++i) EXPECT_EQ(GpuInts(mock)[i], static_cast<GLint>(i)) << "int " << i;
for (SizeT i = 0; i < kAdoptedInts; ++i)
EXPECT_EQ(GpuInts(mock)[i], static_cast<GLint>(i)) << "int " << i;
const auto* readBack = static_cast<const GLint*>(bufferObject->AcquireMemory(false, true, false));
EXPECT_EQ(mock.readbackCalls, 1);
@@ -2497,8 +2492,10 @@ TEST_F(BufferTest, ABackendWithAResidentSubDataOpTakesTheExpandedClearPattern) {
EXPECT_EQ(mock.residentWrites[0].offset, kFirst * sizeof(GLint));
ASSERT_EQ(mock.residentWrites[0].bytes.size(), kCount * sizeof(GLint));
const auto* handed = reinterpret_cast<const GLint*>(mock.residentWrites[0].bytes.data());
for (SizeT i = 0; i < kCount; ++i) EXPECT_EQ(handed[i], value) << "int " << i;
for (SizeT i = 0; i < kAdoptedInts; ++i) EXPECT_EQ(GpuInts(mock)[i], static_cast<GLint>(i)) << "int " << i;
for (SizeT i = 0; i < kCount; ++i)
EXPECT_EQ(handed[i], value) << "int " << i;
for (SizeT i = 0; i < kAdoptedInts; ++i)
EXPECT_EQ(GpuInts(mock)[i], static_cast<GLint>(i)) << "int " << i;
const auto* readBack = static_cast<const GLint*>(bufferObject->AcquireMemory(false, true, false));
EXPECT_EQ(mock.readbackCalls, 1);
@@ -2519,7 +2516,8 @@ namespace {
GenBuffers(1, &buffer);
BindBuffer(target, buffer);
Vector<GLint> bytes(kAdoptedInts);
for (SizeT i = 0; i < kAdoptedInts; ++i) bytes[i] = bias + static_cast<GLint>(i);
for (SizeT i = 0; i < kAdoptedInts; ++i)
bytes[i] = bias + static_cast<GLint>(i);
BufferData(target, static_cast<GLsizeiptr>(kAdoptedInts * sizeof(GLint)), bytes.data(), GL_STATIC_DRAW);
EXPECT_EQ(GetError(), GL_NO_ERROR);
return buffer;
@@ -2547,8 +2545,8 @@ TEST_F(BufferTest, GlCopyBufferSubDataIntoAnAdoptedStoreLandsAtTheDestinationOff
for (SizeT i = 0; i < kAdoptedInts; ++i) {
const GLint expected = (i >= kDstFirst && i < kDstFirst + kCount)
? 900 + static_cast<GLint>(kSrcFirst + i - kDstFirst)
: static_cast<GLint>(i);
? 900 + static_cast<GLint>(kSrcFirst + i - kDstFirst)
: static_cast<GLint>(i);
EXPECT_EQ(GpuInts(mock)[i], expected) << "int " << i;
}
EXPECT_EQ(mock.subDataCalls, 0);
@@ -2583,7 +2581,8 @@ TEST_F(BufferTest, ABackendWithAResidentSubDataOpTakesACopyAtTheDestinationOffse
for (SizeT i = 0; i < kCount; ++i) {
EXPECT_EQ(handed[i], 900 + static_cast<GLint>(kSrcFirst + i)) << "int " << i;
}
for (SizeT i = 0; i < kAdoptedInts; ++i) EXPECT_EQ(GpuInts(mock)[i], static_cast<GLint>(i)) << "int " << i;
for (SizeT i = 0; i < kAdoptedInts; ++i)
EXPECT_EQ(GpuInts(mock)[i], static_cast<GLint>(i)) << "int " << i;
GLuint toDelete[] = {destination, source};
DeleteBuffers(2, toDelete);
@@ -2606,13 +2605,14 @@ TEST_F(BufferTest, AnExplicitFlushOfAPersistentMapOfAnAdoptedStoreOnlyPublishesT
constexpr SizeT kFirst = 2;
constexpr SizeT kCount = 8;
const Range1D range{kFirst * sizeof(GLint), (kFirst + kCount) * sizeof(GLint)};
auto* mapped = static_cast<GLint*>(bufferObject->AcquireMemoryRange(
range, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent |
BufferMappingAccessBit::FlushExplicit));
auto* mapped = static_cast<GLint*>(
bufferObject->AcquireMemoryRange(range, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent |
BufferMappingAccessBit::FlushExplicit));
ASSERT_NE(mapped, nullptr);
// The application writes the store itself: the map IS the adopted memory.
EXPECT_EQ(static_cast<void*>(mapped), static_cast<void*>(mock.gpu.data() + range.start));
for (SizeT i = 0; i < kCount; ++i) mapped[i] = 400 + static_cast<GLint>(i);
for (SizeT i = 0; i < kCount; ++i)
mapped[i] = 400 + static_cast<GLint>(i);
constexpr SizeT kFlushFirst = 3;
constexpr SizeT kFlushCount = 2;
@@ -2658,8 +2658,7 @@ TEST_F(BufferTest, AZeroLengthExplicitFlushOfAnAdoptedStoreLeavesItUndefined) {
const Uint64 baseSerial = bufferObject->GetChangeSerial();
auto* mapped = bufferObject->AcquireMemoryRange({0, kAdoptedInts * sizeof(GLint)},
BufferMappingAccessBit::Write |
BufferMappingAccessBit::Persistent |
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent |
BufferMappingAccessBit::FlushExplicit);
ASSERT_NE(mapped, nullptr);
bufferObject->FlushMemoryRange(0, 0);
@@ -2701,7 +2700,8 @@ TEST_F(BufferTest, AWriteMapThatDiscardsWhatItMapsDoesNotReconcileAnAdoptedStore
range, BufferMappingAccessBit::Write | BufferMappingAccessBit::InvalidateRange));
ASSERT_NE(mapped, nullptr);
EXPECT_EQ(mock.readbackCalls, 0);
for (SizeT i = 0; i < kCount; ++i) mapped[i] = 300 + static_cast<GLint>(i);
for (SizeT i = 0; i < kCount; ++i)
mapped[i] = 300 + static_cast<GLint>(i);
bufferObject->ReleaseMemory();
ASSERT_EQ(mock.residentWrites.size(), 2u);
@@ -2709,7 +2709,8 @@ TEST_F(BufferTest, AWriteMapThatDiscardsWhatItMapsDoesNotReconcileAnAdoptedStore
const auto* readBack = static_cast<const GLint*>(bufferObject->AcquireMemory(false, true, false));
EXPECT_EQ(mock.readbackCalls, 1);
EXPECT_EQ(readBack[0], firstInt);
for (SizeT i = 0; i < kCount; ++i) EXPECT_EQ(readBack[kFirst + i], 300 + static_cast<GLint>(i)) << "int " << i;
for (SizeT i = 0; i < kCount; ++i)
EXPECT_EQ(readBack[kFirst + i], 300 + static_cast<GLint>(i)) << "int " << i;
// The control: a map that keeps what it maps still reconciles before seeding.
BufferSubData(GL_ARRAY_BUFFER, 0, sizeof(firstInt), &firstInt);
@@ -2718,7 +2719,8 @@ TEST_F(BufferTest, AWriteMapThatDiscardsWhatItMapsDoesNotReconcileAnAdoptedStore
bufferObject->AcquireMemoryRange(range, BufferMappingAccessBit::Read | BufferMappingAccessBit::Write));
ASSERT_NE(seeded, nullptr);
EXPECT_EQ(mock.readbackCalls, 2);
for (SizeT i = 0; i < kCount; ++i) EXPECT_EQ(seeded[i], 300 + static_cast<GLint>(i)) << "int " << i;
for (SizeT i = 0; i < kCount; ++i)
EXPECT_EQ(seeded[i], 300 + static_cast<GLint>(i)) << "int " << i;
bufferObject->ReleaseMemory();
DeleteBuffers(1, &buffer);
@@ -2738,7 +2740,8 @@ TEST_F(BufferTest, AStorageBindingDoesNotAdoptTheStoreWhileTheApplicationHoldsAM
GenBuffers(1, &buffer);
BindBuffer(GL_SHADER_STORAGE_BUFFER, buffer);
Vector<GLint> initial(kAdoptedInts);
for (SizeT i = 0; i < kAdoptedInts; ++i) initial[i] = static_cast<GLint>(i);
for (SizeT i = 0; i < kAdoptedInts; ++i)
initial[i] = static_cast<GLint>(i);
BufferData(GL_SHADER_STORAGE_BUFFER, static_cast<GLsizeiptr>(kAdoptedInts * sizeof(GLint)), initial.data(),
GL_DYNAMIC_DRAW);
ASSERT_EQ(GetError(), GL_NO_ERROR);
@@ -2749,9 +2752,9 @@ TEST_F(BufferTest, AStorageBindingDoesNotAdoptTheStoreWhileTheApplicationHoldsAM
constexpr SizeT kFirst = 2;
constexpr SizeT kCount = 4;
const Range1D range{kFirst * sizeof(GLint), (kFirst + kCount) * sizeof(GLint)};
auto* mapped = static_cast<GLint*>(bufferObject->AcquireMemoryRange(
range, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent |
BufferMappingAccessBit::FlushExplicit));
auto* mapped = static_cast<GLint*>(
bufferObject->AcquireMemoryRange(range, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent |
BufferMappingAccessBit::FlushExplicit));
ASSERT_NE(mapped, nullptr);
ASSERT_EQ(static_cast<const void*>(mapped), static_cast<const void*>(shadowBase + range.start));
@@ -2760,11 +2763,13 @@ TEST_F(BufferTest, AStorageBindingDoesNotAdoptTheStoreWhileTheApplicationHoldsAM
EXPECT_EQ(mock.acquireMapCalls, 0);
// The application's pointer is still the store's: it survived the binding.
EXPECT_EQ(static_cast<const void*>(bufferObject->MappedData()), static_cast<const void*>(shadowBase));
for (SizeT i = 0; i < kCount; ++i) mapped[i] = 250 + static_cast<GLint>(i);
for (SizeT i = 0; i < kCount; ++i)
mapped[i] = 250 + static_cast<GLint>(i);
bufferObject->FlushMemoryRange(0, kCount * sizeof(GLint));
EXPECT_EQ(mock.flushCalls, 1);
const auto* shadowInts = reinterpret_cast<const GLint*>(bufferObject->MappedData());
for (SizeT i = 0; i < kCount; ++i) EXPECT_EQ(shadowInts[kFirst + i], 250 + static_cast<GLint>(i));
for (SizeT i = 0; i < kCount; ++i)
EXPECT_EQ(shadowInts[kFirst + i], 250 + static_cast<GLint>(i));
// Unmapped, the next binding adopts as usual.
bufferObject->ReleaseMemory();
@@ -2789,7 +2794,8 @@ TEST_F(BufferTest, RespecifyingAStoreWhileItIsMappedDoesNotLandTheStagedBytesInt
auto* mapped = static_cast<GLint*>(
bufferObject->AcquireMemoryRange({0, kAdoptedInts * sizeof(GLint)}, BufferMappingAccessBit::Write));
ASSERT_NE(mapped, nullptr);
for (SizeT i = 0; i < kAdoptedInts; ++i) mapped[i] = 1234;
for (SizeT i = 0; i < kAdoptedInts; ++i)
mapped[i] = 1234;
bufferObject->Respecify(kAdoptedInts * sizeof(GLint), nullptr);
EXPECT_TRUE(mock.residentWrites.empty());
@@ -2803,4 +2809,3 @@ TEST_F(BufferTest, RespecifyingAStoreWhileItIsMappedDoesNotLandTheStagedBytesInt
DeleteBuffers(1, &buffer);
g_zeroCopyMock = nullptr;
}
+80 -52
View File
@@ -38,9 +38,9 @@ using namespace MobileGL;
namespace {
#if MOBILEGL_BUILD_DISAGGREGATED
using MG_State::GLState::BufferObject;
using MG_Record::GpuWriteProducer;
using MG_Record::PersistentMapTracker;
using MG_State::GLState::BufferObject;
// A backend that MINTS a persistent mapping, for the one case that needs the adopted arm
// (TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo): a resource op table (P13: the
@@ -48,7 +48,9 @@ namespace {
// CASE's, not this table's - AdoptPersistentMap keeps the pointer and never owns it - so the
// base travels through a file-scope variable the case sets and clears.
void* g_mintedPersistentBase = nullptr;
void* MintPersistentMap(MG_Pipe::MGPipeHandle, Uint64, const void*) { return g_mintedPersistentBase; }
void* MintPersistentMap(MG_Pipe::MGPipeHandle, Uint64, const void*) {
return g_mintedPersistentBase;
}
const MG_Pipe::MGPipeResourceOps g_mintingResourceOps = [] {
MG_Pipe::MGPipeResourceOps ops{};
ops.MapPersistent = &MintPersistentMap;
@@ -126,10 +128,10 @@ namespace {
};
#endif
#define MGL_SPLIT_ONLY_OR_SKIP() \
do { \
GTEST_SKIP() << "the client-side GPU-write set and the persistent-map push exist only in " \
"a MOBILEGL_BUILD_DISAGGREGATED build"; \
#define MGL_SPLIT_ONLY_OR_SKIP() \
do { \
GTEST_SKIP() << "the client-side GPU-write set and the persistent-map push exist only in " \
"a MOBILEGL_BUILD_DISAGGREGATED build"; \
} while (0)
} // namespace
@@ -170,8 +172,7 @@ TEST_F(SplitBufferSet, Row1EveryBoundAtomicCounterIsMarkedByADraw) {
// a byte of it.
TEST_F(SplitBufferSet, Row2OnlyAWritableImageBufferTextureCounts) {
MG_State::GLState::ImageTextureBinding empty{};
EXPECT_FALSE(MG_Record::ImageUnitIsAWritableBufferTexture(empty))
<< "an unbound image unit is not a GPU write";
EXPECT_FALSE(MG_Record::ImageUnitIsAWritableBufferTexture(empty)) << "an unbound image unit is not a GPU write";
auto texture = MakeShared<MG_State::GLState::TextureObjectBuffer>(7u);
auto backing = MakeBuffer(13u, 128);
@@ -286,7 +287,6 @@ TEST_F(SplitBufferSet, Row5EndTransformFeedbackMarksTheCaptureTargets) {
EXPECT_EQ(MG_Record::ProducerMarkCount(GpuWriteProducer::EndTransformFeedbackCapture), 1u);
}
// =====================================================================================
// The persistent-map push
// =====================================================================================
@@ -298,8 +298,7 @@ TEST_F(SplitBufferSet, MembershipIsSyncPersistentMappedRangesOwnEarlyOutChain) {
auto buffer = MakeBuffer(20u, 4096);
EXPECT_FALSE(PersistentMapTracker::IsLivePersistentMap(*buffer)) << "not mapped";
buffer->AcquireMemoryRange(Range1D{0, 4096},
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
buffer->AcquireMemoryRange(Range1D{0, 4096}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
ASSERT_FALSE(buffer->IsBackendPersistentMapped())
<< "the acquisition was minted, so this is the adopted arm and not the one under test";
EXPECT_TRUE(PersistentMapTracker::IsLivePersistentMap(*buffer));
@@ -311,8 +310,7 @@ TEST_F(SplitBufferSet, MembershipIsSyncPersistentMappedRangesOwnEarlyOutChain) {
// FLUSH_EXPLICIT is the early-out that is easiest to lose: the application announces its
// own writes with glFlushMappedBufferRange, which already crosses as resource_flush_range.
buffer->AcquireMemoryRange(Range1D{0, 4096}, BufferMappingAccessBit::Write |
BufferMappingAccessBit::Persistent |
buffer->AcquireMemoryRange(Range1D{0, 4096}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent |
BufferMappingAccessBit::FlushExplicit);
EXPECT_FALSE(PersistentMapTracker::IsLivePersistentMap(*buffer));
EXPECT_EQ(PersistentMapTracker::Instance().MemberCount(), 0u);
@@ -353,8 +351,7 @@ TEST_F(SplitBufferSet, TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo) {
auto declined = MakeBuffer(28u, kSize);
// The declined twin first, with no backend ops at all: same flags, same size, same call.
declined->AcquireMemoryRange(Range1D{0, kSize},
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
declined->AcquireMemoryRange(Range1D{0, kSize}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
ASSERT_FALSE(declined->IsBackendPersistentMapped());
ASSERT_TRUE(PersistentMapTracker::IsLivePersistentMap(*declined))
<< "the emulated arm IS a member - if this fails the two halves are not comparable and the "
@@ -413,8 +410,7 @@ TEST_F(SplitBufferSet, TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo) {
TEST_F(SplitBufferSet, ThePushCutsTheMappedSpanIntoBlocksAndMovesPmap) {
constexpr SizeT kSize = 4u * 64u * 1024u; // exactly four 64 KiB blocks
auto buffer = MakeBuffer(21u, kSize);
buffer->AcquireMemoryRange(Range1D{0, kSize},
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
buffer->AcquireMemoryRange(Range1D{0, kSize}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
ASSERT_TRUE(PersistentMapTracker::IsLivePersistentMap(*buffer));
const Uint64 before = MG_Util::PipeStats::TotalBytes(MG_Util::PipeStats::ByteClass::PersistentMapPush);
@@ -435,8 +431,7 @@ TEST_F(SplitBufferSet, ThePushCutsTheMappedSpanIntoBlocksAndMovesPmap) {
TEST_F(SplitBufferSet, TheLastBlockIsTheRemainderAndNotAWholeBlock) {
constexpr SizeT kSize = 64u * 1024u + 7u;
auto buffer = MakeBuffer(22u, kSize);
buffer->AcquireMemoryRange(Range1D{0, kSize},
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
buffer->AcquireMemoryRange(Range1D{0, kSize}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
MG_Record::PushPersistentMapsBeforeVerb();
EXPECT_EQ(PersistentMapTracker::Instance().BlocksPushed(), 2u);
EXPECT_EQ(PersistentMapTracker::Instance().BytesPushed(), static_cast<Uint64>(kSize));
@@ -454,8 +449,7 @@ TEST_F(SplitBufferSet, BothEdgesOfAWriteMapPublishOneStateRecord) {
EXPECT_FALSE(buffer->HasLiveHostWritesForWire());
const Uint64 beforeMap = buffer->GetChangeSerial();
buffer->AcquireMemoryRange(Range1D{0, kSize},
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
buffer->AcquireMemoryRange(Range1D{0, kSize}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
EXPECT_TRUE(buffer->HasLiveHostWritesForWire());
EXPECT_EQ(buffer->GetChangeSerial(), beforeMap + 1)
<< "the rising edge published nothing, so the server cannot know a host writer is live "
@@ -479,11 +473,9 @@ TEST_F(SplitBufferSet, AZeroBlockSizeTurnsThePushOffRatherThanMakingItUnlimited)
auto buffer = MakeBuffer(23u, kSize);
const Uint64 beforeMap = buffer->GetChangeSerial();
buffer->AcquireMemoryRange(Range1D{0, kSize},
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
buffer->AcquireMemoryRange(Range1D{0, kSize}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
ASSERT_TRUE(PersistentMapTracker::IsLivePersistentMap(*buffer));
EXPECT_EQ(buffer->GetChangeSerial(), beforeMap)
<< "the rising-edge state record went out with the push disabled";
EXPECT_EQ(buffer->GetChangeSerial(), beforeMap) << "the rising-edge state record went out with the push disabled";
const Uint64 before = MG_Util::PipeStats::TotalBytes(MG_Util::PipeStats::ByteClass::PersistentMapPush);
MG_Record::PushPersistentMapsBeforeVerb();
@@ -788,10 +780,9 @@ TEST_F(SplitBufferSet, AFaultedMapTheDrawDidNotBindStillShipsBeforeTheDrawThatDo
constexpr SizeT kSize = 4096; // one page, one block each
auto a = MakeBuffer(29u, kSize);
auto b = MakeBuffer(30u, kSize);
auto* aMapped = static_cast<Uint8*>(a->AcquireMemoryRange(
Range1D{0, kSize}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent));
b->AcquireMemoryRange(Range1D{0, kSize},
BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
auto* aMapped = static_cast<Uint8*>(
a->AcquireMemoryRange(Range1D{0, kSize}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent));
b->AcquireMemoryRange(Range1D{0, kSize}, BufferMappingAccessBit::Write | BufferMappingAccessBit::Persistent);
ASSERT_NE(aMapped, nullptr);
ASSERT_NE(PersistentMapTracker::TrackedSlotForTest(*a), nullptr)
<< "both maps must be on the mprotect arm, or the epoch is not what decides";
@@ -840,32 +831,70 @@ TEST_F(SplitBufferSet, AFaultedMapTheDrawDidNotBindStillShipsBeforeTheDrawThatDo
// pull and push name lists line for line and G14 allows build-split to ADD names but never to
// remove one, so a case that exists only where it can run would break both gates for a reason
// that has nothing to do with what it tests. It skips instead, and says why.
TEST(SplitBufferSet, Row0EverySsboBindingPointIsMarkedByADraw) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, Row1EveryBoundAtomicCounterIsMarkedByADraw) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, Row2OnlyAWritableImageBufferTextureCounts) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, Row2AWritableImageBufferTextureIsMarkedByADraw) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, Row2TheSweepIsBoundedByTheImageUnitHighWaterMark) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, Row0EverySsboBindingPointIsMarkedByADraw) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, Row1EveryBoundAtomicCounterIsMarkedByADraw) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, Row2OnlyAWritableImageBufferTextureCounts) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, Row2AWritableImageBufferTextureIsMarkedByADraw) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, Row2TheSweepIsBoundedByTheImageUnitHighWaterMark) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, Row3TransformFeedbackTargetsAreOnlyMarkedWhileACaptureIsActive) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, Row4AReadPixelsIntoAPackPboMarksThePbo) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, Row5EndTransformFeedbackMarksTheCaptureTargets) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, Row4AReadPixelsIntoAPackPboMarksThePbo) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, Row5EndTransformFeedbackMarksTheCaptureTargets) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, MembershipIsSyncPersistentMappedRangesOwnEarlyOutChain) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, ThePushCutsTheMappedSpanIntoBlocksAndMovesPmap) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, TheLastBlockIsTheRemainderAndNotAWholeBlock) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, BothEdgesOfAWriteMapPublishOneStateRecord) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, AZeroBlockSizeTurnsThePushOffRatherThanMakingItUnlimited) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, ADestroyedBufferLeavesTheSet) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, UnderSplitTheWritebackClearsThePendingFlagAndNotTheRequest) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, AnOlderWritebackCannotRetireANewerGpuWriteMark) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, TheAdoptTierIsSettledAtTheHandshakeAndNeverFatal) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, ASubPageMapIsOneProtectedPageAndAWriteThroughItFaults) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, MembershipIsSyncPersistentMappedRangesOwnEarlyOutChain) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, TheAdoptedArmIsNotAMemberAndItIsTheChainRowThatSaysSo) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, ThePushCutsTheMappedSpanIntoBlocksAndMovesPmap) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, TheLastBlockIsTheRemainderAndNotAWholeBlock) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, BothEdgesOfAWriteMapPublishOneStateRecord) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, AZeroBlockSizeTurnsThePushOffRatherThanMakingItUnlimited) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, ADestroyedBufferLeavesTheSet) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, UnderSplitTheWritebackClearsThePendingFlagAndNotTheRequest) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, AnOlderWritebackCannotRetireANewerGpuWriteMark) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, TheAdoptTierIsSettledAtTheHandshakeAndNeverFatal) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, ASubPageMapIsOneProtectedPageAndAWriteThroughItFaults) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, AShadowThatFailsThePageGranularTestKeepsTheInwardAlignmentAndItsEdges) {
MGL_SPLIT_ONLY_OR_SKIP();
}
TEST(SplitBufferSet, AFaultedMapTheDrawDidNotBindStillShipsBeforeTheDrawThatDoes) { MGL_SPLIT_ONLY_OR_SKIP(); }
TEST(SplitBufferSet, AFaultedMapTheDrawDidNotBindStillShipsBeforeTheDrawThatDoes) {
MGL_SPLIT_ONLY_OR_SKIP();
}
#endif // MOBILEGL_BUILD_DISAGGREGATED
@@ -916,8 +945,7 @@ TEST(EsprytFlushLadder, AMapWiderThanTheQueuedRangeRefusesTierOne) {
"rewrite, and overwrites whatever the GPU put there";
// And narrower, which is the same corruption read the other way round: bytes left
// unwritten inside a range that has just been declared dead.
EXPECT_EQ(InvalidateFlushAccessFor(queuedStart, queuedEnd, queuedStart, queuedEnd - 8, kStore, kStore, false),
0u);
EXPECT_EQ(InvalidateFlushAccessFor(queuedStart, queuedEnd, queuedStart, queuedEnd - 8, kStore, kStore, false), 0u);
}
TEST(EsprytFlushLadder, AnEmptyRangeIsNeverTierOne) {
@@ -965,8 +993,8 @@ TEST(EsprytFlushLadder, ARenameThatWouldMoveTooManyUnaskedBytesKeepsItsQueuedRan
// The 1.21.5 trace's other shape: 128 bytes into a 53 KiB index store.
EXPECT_FALSE(WholeStoreRenameApplies(53824, 53824, 128, true, false, true))
<< "rewriting 53 KiB for a 128-byte write moves more bytes than the copy job it saves";
EXPECT_FALSE(WholeStoreRenameApplies(16384, 16384, 16384 - kEsprytWholeStoreRenameMaxExtraBytes - 1, true,
false, true));
EXPECT_FALSE(
WholeStoreRenameApplies(16384, 16384, 16384 - kEsprytWholeStoreRenameMaxExtraBytes - 1, true, false, true));
EXPECT_FALSE(WholeStoreRenameApplies(0, 0, 0, true, false, true));
EXPECT_FALSE(WholeStoreRenameApplies(288, 288, 0, true, false, true)) << "nothing queued, nothing to rename";
}
+40 -22
View File
@@ -45,7 +45,7 @@ namespace {
EXPECT_NE(fixture->Context, EGL_NO_CONTEXT);
return fixture;
}
}
} // namespace
TEST(EGLStateMakeCurrent, ContextCannotBeCurrentOnTwoThreadsAtOnce) {
auto fixture = CreateFixture();
@@ -66,19 +66,18 @@ TEST(EGLStateMakeCurrent, ContextCannotBeCurrentOnTwoThreadsAtOnce) {
EGLint threadBAttachAfterReleaseError = EGL_SUCCESS;
std::thread threadA([&] {
threadAAttachOk = fixture->State.MakeCurrent(fixture->Display, fixture->Surface, fixture->Surface,
fixture->Context);
threadAAttachOk =
fixture->State.MakeCurrent(fixture->Display, fixture->Surface, fixture->Surface, fixture->Context);
threadAReady.set_value();
threadBAttemptedFuture.wait();
threadAReleaseOk =
fixture->State.MakeCurrent(fixture->Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
threadAReleaseOk = fixture->State.MakeCurrent(fixture->Display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
threadAReleased.set_value();
});
std::thread threadB([&] {
threadAReadyFuture.wait();
threadBDenied = fixture->State.MakeCurrent(fixture->Display, fixture->Surface, fixture->Surface,
fixture->Context);
threadBDenied =
fixture->State.MakeCurrent(fixture->Display, fixture->Surface, fixture->Surface, fixture->Context);
threadBDeniedError = fixture->State.ConsumeError();
threadBAttempted.set_value();
threadAReleasedFuture.wait();
@@ -276,9 +275,9 @@ TEST(EGLStateCreateContext, NoConfigContextIsAcceptedAndReportsConfigIdZero) {
EXPECT_TRUE(fixture->State.MakeCurrent(fixture->Display, EGL_NO_SURFACE, EGL_NO_SURFACE, context));
EXPECT_TRUE(fixture->State.MakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT));
// A non-null handle that names no config is still EGL_BAD_CONFIG.
EXPECT_EQ(fixture->State.CreateContext(fixture->Display, reinterpret_cast<EGLConfig>(0xdead), EGL_NO_CONTEXT,
esAttribs),
EGL_NO_CONTEXT);
EXPECT_EQ(
fixture->State.CreateContext(fixture->Display, reinterpret_cast<EGLConfig>(0xdead), EGL_NO_CONTEXT, esAttribs),
EGL_NO_CONTEXT);
EXPECT_EQ(fixture->State.ConsumeError(), EGL_BAD_CONFIG);
}
@@ -291,8 +290,19 @@ namespace {
// A complete single-plane import, as a compositor builds it for a linux-dmabuf wl_buffer.
std::vector<EGLAttrib> DmaBufAttribs(EGLAttrib fourcc = kAbgr8888) {
return {EGL_WIDTH, 64, EGL_HEIGHT, 32, EGL_LINUX_DRM_FOURCC_EXT, fourcc, EGL_DMA_BUF_PLANE0_FD_EXT, 7,
EGL_DMA_BUF_PLANE0_OFFSET_EXT, 0, EGL_DMA_BUF_PLANE0_PITCH_EXT, 256, EGL_NONE};
return {EGL_WIDTH,
64,
EGL_HEIGHT,
32,
EGL_LINUX_DRM_FOURCC_EXT,
fourcc,
EGL_DMA_BUF_PLANE0_FD_EXT,
7,
EGL_DMA_BUF_PLANE0_OFFSET_EXT,
0,
EGL_DMA_BUF_PLANE0_PITCH_EXT,
256,
EGL_NONE};
}
std::vector<EGLAttrib> WithAttrib(std::vector<EGLAttrib> attribs, EGLAttrib name, EGLAttrib value) {
@@ -321,9 +331,9 @@ namespace {
TEST(EGLStateDmaBufImport, ParsesACompleteSinglePlaneImport) {
auto fixture = CreateFixture();
const auto attribs = WithAttrib(WithAttrib(DmaBufAttribs(kXbgr8888), EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT,
static_cast<EGLAttrib>(0xffffffffu)),
EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, 0x00ffffff);
const auto attribs = WithAttrib(
WithAttrib(DmaBufAttribs(kXbgr8888), EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, static_cast<EGLAttrib>(0xffffffffu)),
EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, 0x00ffffff);
StateContext::DmaBufImportAttribs parsed;
ASSERT_TRUE(fixture->State.PrepareDmaBufImport(fixture->Display, EGL_NO_CONTEXT, nullptr, attribs.data(), &parsed));
EXPECT_EQ(fixture->State.ConsumeError(), EGL_SUCCESS);
@@ -377,7 +387,8 @@ TEST(EGLStateDmaBufImport, RefusesWhatTheExtensionRefuses) {
TEST(EGLStateDmaBufImport, SharedImageLifetime) {
auto fixture = CreateFixture();
const StateContext::SharedImageInfo info{.Id = 42, .Width = 64, .Height = 32, .Fourcc = StateContext::kDrmFourccAbgr8888};
const StateContext::SharedImageInfo info{
.Id = 42, .Width = 64, .Height = 32, .Fourcc = StateContext::kDrmFourccAbgr8888};
const EGLImage image = fixture->State.CreateSharedImage(fixture->Display, info);
ASSERT_NE(image, EGL_NO_IMAGE);
@@ -498,7 +509,8 @@ TEST(EGLStateDmaBufImport, ParsesATwoPlaneYuvImportWithItsHints) {
auto linear = WithAttrib(WithAttrib(Nv12Attribs(), EGL_DMA_BUF_PLANE0_MODIFIER_LO_EXT, 0),
EGL_DMA_BUF_PLANE0_MODIFIER_HI_EXT, 0);
EXPECT_EQ(PrepareError(*fixture, linear), EGL_BAD_PARAMETER);
linear = WithAttrib(WithAttrib(linear, EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT, 0), EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT, 0);
linear =
WithAttrib(WithAttrib(linear, EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT, 0), EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT, 0);
EXPECT_EQ(PrepareError(*fixture, linear), EGL_SUCCESS);
auto mixed = WithAttrib(WithAttrib(WithoutAttrib(WithoutAttrib(linear, EGL_DMA_BUF_PLANE1_MODIFIER_LO_EXT),
EGL_DMA_BUF_PLANE1_MODIFIER_HI_EXT),
@@ -516,7 +528,8 @@ TEST(EGLStateDmaBufImport, RefusesAnIncompleteYuvImport) {
}
// NV12 has two planes, not three.
EXPECT_EQ(PrepareError(*fixture, WithAttrib(Nv12Attribs(), EGL_DMA_BUF_PLANE2_FD_EXT, 7)), EGL_BAD_ATTRIBUTE);
auto badPitch = WithAttrib(WithoutAttrib(Nv12Attribs(), EGL_DMA_BUF_PLANE1_PITCH_EXT), EGL_DMA_BUF_PLANE1_PITCH_EXT, 0);
auto badPitch =
WithAttrib(WithoutAttrib(Nv12Attribs(), EGL_DMA_BUF_PLANE1_PITCH_EXT), EGL_DMA_BUF_PLANE1_PITCH_EXT, 0);
EXPECT_EQ(PrepareError(*fixture, badPitch), EGL_BAD_ACCESS);
}
@@ -575,8 +588,13 @@ TEST(EGLStateRobustness, ResetNotificationStrategyIsRecordedValidatedAndMatchedA
EXPECT_EQ(strategyOf(robustExt), EGL_LOSE_CONTEXT_ON_RESET);
// ANGLE's shape: an ES 3.2 request with the EGL 1.5 name.
const EGLint loseCore[] = {EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 2,
EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY, EGL_LOSE_CONTEXT_ON_RESET, EGL_NONE};
const EGLint loseCore[] = {EGL_CONTEXT_MAJOR_VERSION,
3,
EGL_CONTEXT_MINOR_VERSION,
2,
EGL_CONTEXT_OPENGL_RESET_NOTIFICATION_STRATEGY,
EGL_LOSE_CONTEXT_ON_RESET,
EGL_NONE};
const auto robustCore = state.CreateContext(fixture->Display, fixture->Config, EGL_NO_CONTEXT, loseCore);
ASSERT_NE(robustCore, EGL_NO_CONTEXT);
EXPECT_EQ(strategyOf(robustCore), EGL_LOSE_CONTEXT_ON_RESET);
@@ -630,8 +648,8 @@ TEST(EGLStateRobustness, RobustAccessIsARequestAndNeverAGLContextFlagByItself) {
EXPECT_TRUE(requestOf(core, &flags));
EXPECT_EQ(flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT, 0);
// KWin's desktop candidate: the KHR flag bit, next to the debug bit that IS a GL flag.
const EGLint khr[] = {EGL_CONTEXT_FLAGS_KHR, EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR | EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR,
EGL_NONE};
const EGLint khr[] = {EGL_CONTEXT_FLAGS_KHR,
EGL_CONTEXT_OPENGL_ROBUST_ACCESS_BIT_KHR | EGL_CONTEXT_OPENGL_DEBUG_BIT_KHR, EGL_NONE};
EXPECT_TRUE(requestOf(khr, &flags));
EXPECT_EQ(flags & GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT, 0);
EXPECT_NE(flags & GL_CONTEXT_FLAG_DEBUG_BIT, 0);
@@ -44,8 +44,8 @@ namespace {
GLenum g_lastReadPixelsType = GL_NONE;
void RecordBlitNamedFramebuffer(const SharedPtr<MG_State::GLState::FramebufferObject>& readFramebuffer,
const SharedPtr<MG_State::GLState::FramebufferObject>& drawFramebuffer,
GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) {
const SharedPtr<MG_State::GLState::FramebufferObject>& drawFramebuffer, GLint,
GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) {
g_lastBlitReadFramebuffer = readFramebuffer;
g_lastBlitDrawFramebuffer = drawFramebuffer;
++g_blitNamedFramebufferCallCount;
@@ -89,8 +89,7 @@ protected:
// binary, so drain whatever an earlier test left pending - otherwise an error-code assertion
// here reads someone else's error. Bounded: one flag per code, so this cannot hang the suite.
static void DrainPendingGlErrors() {
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {}
}
// The call under test must raise exactly the expected error and nothing more: a second pending
@@ -250,10 +249,8 @@ TEST_F(FramebufferTest, NamedFramebufferTextureAttachesWithoutChangingBindings)
MG_State::pGLContext->GenTextureNames(1, textureNames);
MG_State::pGLContext->CreateTextureObject(textureNames[0], TextureTarget::Texture2D);
const auto originalDraw =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto originalRead =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const auto originalDraw = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto originalRead = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
MG_Impl::GLImpl::NamedFramebufferTexture(framebuffer, GL_COLOR_ATTACHMENT0, textureNames[0], 3);
@@ -273,10 +270,8 @@ TEST_F(FramebufferTest, NamedDepthFramebufferTextureStorageIsCompleteWithoutBind
MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer);
MG_Impl::GLImpl::CreateTextures(GL_TEXTURE_2D, 1, &texture);
const auto originalDraw =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto originalRead =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const auto originalDraw = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto originalRead = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
MG_Impl::GLImpl::TextureStorage2D(texture, 1, GL_DEPTH_COMPONENT24, 64, 32);
MG_Impl::GLImpl::NamedFramebufferTexture(framebuffer, GL_DEPTH_ATTACHMENT, texture, 0);
@@ -321,11 +316,10 @@ TEST_F(FramebufferTest, ReadPixelsAllowsPersistentMappedPixelPackBuffer) {
MG_Impl::GLImpl::BindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
MG_Impl::GLImpl::BindBuffer(GL_PIXEL_PACK_BUFFER, pixelPackBuffer);
MG_Impl::GLImpl::BufferStorage(GL_PIXEL_PACK_BUFFER, 4 * 4 * 4, nullptr,
GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
ASSERT_NE(MG_Impl::GLImpl::MapBufferRange(GL_PIXEL_PACK_BUFFER, 0, 4 * 4 * 4,
GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT),
nullptr);
MG_Impl::GLImpl::BufferStorage(GL_PIXEL_PACK_BUFFER, 4 * 4 * 4, nullptr, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT);
ASSERT_NE(
MG_Impl::GLImpl::MapBufferRange(GL_PIXEL_PACK_BUFFER, 0, 4 * 4 * 4, GL_MAP_READ_BIT | GL_MAP_PERSISTENT_BIT),
nullptr);
MG_Backend::gBackendFunctionsTable.GL.ReadPixels = RecordReadPixels;
MG_Impl::GLImpl::ReadPixels(0, 0, 4, 4, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
@@ -411,10 +405,8 @@ TEST_F(FramebufferTest, NamedRenderbufferStorageAndFramebufferAttachDoNotChangeB
MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer);
MG_Impl::GLImpl::CreateRenderbuffers(1, &renderbuffer);
const auto originalDraw =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto originalRead =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const auto originalDraw = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto originalRead = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const auto originalRenderbuffer =
MG_State::pGLContext->GetRenderbufferBindingSlot(RenderbufferTarget::Renderbuffer).GetBoundObject();
@@ -448,10 +440,8 @@ TEST_F(FramebufferTest, NamedFramebufferDrawBuffersDoNotModifyDefaultFramebuffer
GLuint framebuffer = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer);
const auto defaultDraw =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto defaultRead =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const auto defaultDraw = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto defaultRead = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const auto defaultDrawBuffer = defaultDraw->GetDrawBuffers()[0];
const auto defaultReadBuffer = defaultRead->GetReadBuffer();
@@ -471,8 +461,7 @@ TEST_F(FramebufferTest, NamedFramebufferDrawBuffersDoNotModifyDefaultFramebuffer
}
TEST_F(FramebufferTest, DefaultFramebufferReadBufferAcceptsGLBackAlias) {
const auto defaultRead =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const auto defaultRead = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
MG_Impl::GLImpl::ReadBuffer(GL_BACK);
@@ -481,8 +470,7 @@ TEST_F(FramebufferTest, DefaultFramebufferReadBufferAcceptsGLBackAlias) {
}
TEST_F(FramebufferTest, DefaultFramebufferDrawBufferAcceptsGLFrontAlias) {
const auto defaultDraw =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto defaultDraw = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
MG_Impl::GLImpl::DrawBuffer(GL_FRONT);
@@ -514,10 +502,8 @@ TEST_F(FramebufferTest, ClearNamedFramebufferfvUsesNamedObjectWithoutChangingBin
GLuint framebuffer = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer);
const auto defaultDraw =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto defaultRead =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const auto defaultDraw = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto defaultRead = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const GLfloat depth[] = {0.25f};
MG_Backend::gBackendFunctionsTable.GL.ClearNamedFramebufferfv = RecordClearNamedFramebufferfv;
@@ -538,10 +524,8 @@ TEST_F(FramebufferTest, ClearNamedFramebufferfiAllowsDefaultFramebufferZero) {
GLuint framebuffer = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer);
const auto defaultDraw =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto defaultRead =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const auto defaultDraw = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto defaultRead = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
MG_Backend::gBackendFunctionsTable.GL.ClearNamedFramebufferfi = RecordClearNamedFramebufferfi;
MG_Impl::GLImpl::ClearNamedFramebufferfi(0, GL_DEPTH_STENCIL, 0, 0.5f, 7);
@@ -569,12 +553,12 @@ TEST_F(FramebufferTest, GetNamedFramebufferAttachmentParameterivReadsTargetObjec
GLint objectType = 0;
GLint objectName = 0;
GLint textureLevel = 0;
MG_Impl::GLImpl::GetNamedFramebufferAttachmentParameteriv(
framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &objectType);
MG_Impl::GLImpl::GetNamedFramebufferAttachmentParameteriv(
framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &objectName);
MG_Impl::GLImpl::GetNamedFramebufferAttachmentParameteriv(
framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &textureLevel);
MG_Impl::GLImpl::GetNamedFramebufferAttachmentParameteriv(framebuffer, GL_COLOR_ATTACHMENT0,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, &objectType);
MG_Impl::GLImpl::GetNamedFramebufferAttachmentParameteriv(framebuffer, GL_COLOR_ATTACHMENT0,
GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, &objectName);
MG_Impl::GLImpl::GetNamedFramebufferAttachmentParameteriv(framebuffer, GL_COLOR_ATTACHMENT0,
GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL, &textureLevel);
EXPECT_EQ(objectType, GL_TEXTURE);
EXPECT_EQ(objectName, static_cast<GLint>(textureNames[0]));
@@ -586,14 +570,11 @@ TEST_F(FramebufferTest, BlitNamedFramebufferAllowsDefaultFramebufferZero) {
GLuint framebuffer = 0;
MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer);
const auto defaultDraw =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto defaultRead =
MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
const auto defaultDraw = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject();
const auto defaultRead = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject();
MG_Backend::gBackendFunctionsTable.GL.BlitNamedFramebuffer = RecordBlitNamedFramebuffer;
MG_Impl::GLImpl::BlitNamedFramebuffer(framebuffer, 0, 0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT,
GL_NEAREST);
MG_Impl::GLImpl::BlitNamedFramebuffer(framebuffer, 0, 0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT, GL_NEAREST);
const auto framebufferObject = MG_State::pGLContext->GetFramebufferObject(framebuffer);
EXPECT_EQ(g_blitNamedFramebufferCallCount, 1);
@@ -616,8 +597,7 @@ namespace {
// Converts a row of wide pixels (4 components of wideType each) into `format`/`type` words.
template <typename WordT, typename SrcT>
Vector<WordT> ConvertWideRowToPackedWords(const Vector<SrcT>& wide, GLenum wideType, GLenum format,
GLenum type) {
Vector<WordT> ConvertWideRowToPackedWords(const Vector<SrcT>& wide, GLenum wideType, GLenum format, GLenum type) {
ClientReadback::ReadbackChannelMapping mapping{};
EXPECT_TRUE(ClientReadback::GetReadbackChannelMapping(format, mapping));
EXPECT_EQ(ClientReadback::GetReadbackDstPixelSize(mapping, type), sizeof(WordT));
@@ -637,9 +617,9 @@ namespace {
// Wide RGBA8 pattern shared by the normalized-encode tests. Expected fields below are
// round(v / 255 * (2^bits - 1)), computed by hand per pixel.
// R G B A
const Vector<Uint8> kRGBA8Row{255, 0, 128, 64, // P0
10, 250, 33, 200, // P1
85, 170, 255, 0}; // P2
const Vector<Uint8> kRGBA8Row{255, 0, 128, 64, // P0
10, 250, 33, 200, // P1
85, 170, 255, 0}; // P2
} // namespace
TEST(PackedReadbackEncodeTest, EncodesUnsignedShort565) {
@@ -926,8 +906,8 @@ namespace {
class ScopedBackendOverride {
public:
explicit ScopedBackendOverride(UniquePtr<MG_Backend::BackendObject> backend):
m_previous(Move(MG_Backend::pActiveBackendObject)) {
explicit ScopedBackendOverride(UniquePtr<MG_Backend::BackendObject> backend)
: m_previous(Move(MG_Backend::pActiveBackendObject)) {
MG_Backend::pActiveBackendObject = Move(backend);
}
@@ -1020,7 +1000,8 @@ namespace {
RecordedColorMask g_driverUniformColorMask;
void ResetRecordedColorMasks() {
for (auto& recorded : g_driverIndexedColorMasks) recorded = {};
for (auto& recorded : g_driverIndexedColorMasks)
recorded = {};
g_driverUniformColorMask = {};
}
@@ -1028,7 +1009,8 @@ namespace {
g_driverUniformColorMask = {true, r, g, b, a};
// The non-indexed call sets every draw buffer, so record it as such: a later assertion
// about draw buffer 1 must not read a stale indexed record the uniform push overwrote.
for (auto& recorded : g_driverIndexedColorMasks) recorded = {true, r, g, b, a};
for (auto& recorded : g_driverIndexedColorMasks)
recorded = {true, r, g, b, a};
}
void StubColorMaski(GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a) {
@@ -1047,7 +1029,8 @@ namespace {
RecordedBlend g_driverBlend[kRecordedDrawBuffers];
void ResetRecordedBlend() {
for (auto& recorded : g_driverBlend) recorded = {};
for (auto& recorded : g_driverBlend)
recorded = {};
}
void RecordBlendEnable(Bool enabled) {
@@ -1138,8 +1121,8 @@ namespace {
public:
// dualSourceBlendSupported models GL_EXT_blend_func_extended on the ES driver, which is
// the one capability in here that a real device is commonly WITHOUT.
explicit ScopedRenderStateDriverStubs(Bool dualSourceBlendSupported = true):
m_funcs(MG_Backend::DirectGLES::g_GLESFuncs), m_caps(MG_Backend::DirectGLES::g_GLESCapabilities) {
explicit ScopedRenderStateDriverStubs(Bool dualSourceBlendSupported = true)
: m_funcs(MG_Backend::DirectGLES::g_GLESFuncs), m_caps(MG_Backend::DirectGLES::g_GLESCapabilities) {
auto& gl = MG_Backend::DirectGLES::g_GLESFuncs;
gl = MG_External::GLESFunctionsTable{};
gl.glViewport = StubViewport;
@@ -1541,21 +1524,21 @@ TEST_F(FramebufferTest, FramebufferTextureRejectsAColourAttachmentPastTheLimit)
// The same limit ValidateColorAttachmentInRange reads, so the test cannot disagree with the
// implementation about where the boundary is.
const GLint limit = MG_Backend::pActiveBackendObject
? static_cast<GLint>(
MG_Backend::pActiveBackendObject->GetDynamicParameters().MaxColorAttachments)
: static_cast<GLint>(MG_State::GLState::FramebufferObject::MAX_DRAW_BUFFERS);
const GLint limit =
MG_Backend::pActiveBackendObject
? static_cast<GLint>(MG_Backend::pActiveBackendObject->GetDynamicParameters().MaxColorAttachments)
: static_cast<GLint>(MG_State::GLState::FramebufferObject::MAX_DRAW_BUFFERS);
ASSERT_GT(limit, 0);
ASSERT_LT(limit, 32) << "the test needs a colour attachment enum past the limit to exist";
MG_Impl::GLImpl::FramebufferTexture(GL_DRAW_FRAMEBUFFER,
static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + limit), texture, 0);
MG_Impl::GLImpl::FramebufferTexture(GL_DRAW_FRAMEBUFFER, static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + limit), texture,
0);
EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_INVALID_OPERATION);
DrainPendingGlErrors();
// The last legal one still attaches, so the boundary is off-by-none.
MG_Impl::GLImpl::FramebufferTexture(GL_DRAW_FRAMEBUFFER,
static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + limit - 1), texture, 0);
MG_Impl::GLImpl::FramebufferTexture(GL_DRAW_FRAMEBUFFER, static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + limit - 1),
texture, 0);
EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
}
@@ -1631,13 +1614,12 @@ TEST_F(FramebufferTest, FramebufferTexture2DRejectsTheDefaultFramebufferAndBadAt
MG_Impl::GLImpl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, framebuffer);
ASSERT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR);
const GLint limit = MG_Backend::pActiveBackendObject
? static_cast<GLint>(
MG_Backend::pActiveBackendObject->GetDynamicParameters().MaxColorAttachments)
: static_cast<GLint>(MG_State::GLState::FramebufferObject::MAX_DRAW_BUFFERS);
MG_Impl::GLImpl::FramebufferTexture2D(GL_DRAW_FRAMEBUFFER,
static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + limit), GL_TEXTURE_2D,
texture, 0);
const GLint limit =
MG_Backend::pActiveBackendObject
? static_cast<GLint>(MG_Backend::pActiveBackendObject->GetDynamicParameters().MaxColorAttachments)
: static_cast<GLint>(MG_State::GLState::FramebufferObject::MAX_DRAW_BUFFERS);
MG_Impl::GLImpl::FramebufferTexture2D(GL_DRAW_FRAMEBUFFER, static_cast<GLenum>(GL_COLOR_ATTACHMENT0 + limit),
GL_TEXTURE_2D, texture, 0);
EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_INVALID_OPERATION);
DrainPendingGlErrors();
@@ -41,15 +41,20 @@ namespace {
}
} // namespace
FAKE_EXPORT uint32_t mobilegl_shared_image_abi_version(void) { return MOBILEGL_SHARED_IMAGE_ABI_VERSION; }
FAKE_EXPORT uint32_t mobilegl_shared_image_abi_version(void) {
return MOBILEGL_SHARED_IMAGE_ABI_VERSION;
}
FAKE_EXPORT int mobilegl_server_available(void) { return 1; }
FAKE_EXPORT int mobilegl_server_available(void) {
return 1;
}
FAKE_EXPORT int mobilegl_shared_image_formats(uint32_t* formats, uint32_t capacity) {
const uint32_t all[] = {MOBILEGL_SHARED_IMAGE_FOURCC_ABGR8888, MOBILEGL_SHARED_IMAGE_FOURCC_XBGR8888,
MOBILEGL_SHARED_IMAGE_FOURCC_ARGB8888, MOBILEGL_SHARED_IMAGE_FOURCC_XRGB8888,
MOBILEGL_SHARED_IMAGE_FOURCC_NV12};
for (uint32_t i = 0; i < 5 && i < capacity; ++i) formats[i] = all[i];
for (uint32_t i = 0; i < 5 && i < capacity; ++i)
formats[i] = all[i];
return 5;
}
@@ -58,7 +63,7 @@ FAKE_EXPORT int mobilegl_shared_image_allocate(uint32_t width, uint32_t height,
if (width == 0 || height == 0 || !Supported(fourcc) || out == nullptr) return -EINVAL;
const int fd = ::memfd_create("fake-shared-image", MFD_CLOEXEC);
if (fd < 0 || ::ftruncate(fd, static_cast<off_t>(width) * height * 4) != 0) return -EIO;
struct stat st {};
struct stat st{};
::fstat(fd, &st);
const std::lock_guard<std::mutex> lock(g_mutex);
const uint64_t id = g_nextId++;
@@ -81,7 +86,7 @@ FAKE_EXPORT int mobilegl_shared_image_allocate(uint32_t width, uint32_t height,
FAKE_EXPORT int mobilegl_shared_image_import(int fd, uint32_t width, uint32_t height, uint32_t fourcc,
uint64_t* out_id) {
struct stat st {};
struct stat st{};
if (fd < 0 || ::fstat(fd, &st) != 0 || !Supported(fourcc)) return -EINVAL;
const std::lock_guard<std::mutex> lock(g_mutex);
for (auto& [id, image] : g_images) {
@@ -118,7 +123,8 @@ FAKE_EXPORT int fake_shared_image_imports(void) {
// A YUV import names an image by its descriptor as an RGBA one does; the planes are not looked at.
FAKE_EXPORT int mobilegl_shared_image_import_planes(int fd, uint32_t width, uint32_t height, uint32_t fourcc,
const struct mobilegl_shared_image_planes* planes, uint64_t* out_id) {
const struct mobilegl_shared_image_planes* planes,
uint64_t* out_id) {
if (planes == nullptr || planes->plane_count != 2 || fourcc != MOBILEGL_SHARED_IMAGE_FOURCC_NV12) return -EINVAL;
return mobilegl_shared_image_import(fd, width, height, fourcc, out_id);
}
+2 -2
View File
@@ -94,7 +94,7 @@ TEST_F(GbmGlamor, AWindowPixmapIsASharedImageWithOneExportablePlane) {
EXPECT_EQ(gbm_bo_get_offset(bo, 0), 0u);
// Exports are duplicates of one dma-buf: the same inode every time.
const int again = gbm_bo_get_fd(bo);
struct stat a {}, b {};
struct stat a{}, b{};
ASSERT_EQ(::fstat(fd, &a), 0);
ASSERT_EQ(::fstat(again, &b), 0);
EXPECT_EQ(a.st_ino, b.st_ino);
@@ -137,7 +137,7 @@ TEST_F(GbmGlamor, ADri3ClientsBufferImportsBackAsTheSameImage) {
EXPECT_EQ(m_imports(), importsBefore + 1);
// ...and re-exported for EGL_LINUX_DMA_BUF_EXT: still that image.
const int reexport = gbm_bo_get_fd_for_plane(imported, 0);
struct stat a {}, b {};
struct stat a{}, b{};
::fstat(fd, &a);
::fstat(reexport, &b);
EXPECT_EQ(a.st_ino, b.st_ino);
@@ -148,7 +148,9 @@ namespace {
return result;
}
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
Bool DiedOfAbort(const ChildResult& r) {
return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT;
}
std::string DescribeStatus(const ChildResult& r) {
if (r.Status < 0) return "fork/waitpid failed";
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
@@ -356,7 +358,6 @@ TEST(CompositeResolver, ASlotAtTheShaderCsoLimitIsRefusedWhileTheLastBandSlotIsN
<< "an ordinary slot below the band resolved against a record nobody created";
}
namespace {
namespace GL = MobileGL::MG_Impl::GLImpl;
using GLContext = MG_State::GLState::GLContext;
@@ -380,7 +381,9 @@ namespace {
}
};
GLContext& Ctx() { return *MG_State::pGLContext; }
GLContext& Ctx() {
return *MG_State::pGLContext;
}
const char* kVs = R"(#version 430 core
out gl_PerVertex { vec4 gl_Position; };
@@ -589,8 +592,7 @@ void main() { o_color = vec4(0.5); }
EXPECT_EQ(MGPipeProgramEmitterInstance().DrawCso(), first)
<< "the same stage set is the same composite and the same handle";
EXPECT_GE(MGPipeCompositeResolverInstance().GetCounters().Reuses, 1u);
EXPECT_EQ(MGPipeCompositeResolverInstance().GetCounters().Releases, 0u)
<< "a reuse releases nothing";
EXPECT_EQ(MGPipeCompositeResolverInstance().GetCounters().Releases, 0u) << "a reuse releases nothing";
// NOW THE STAGE SET REALLY MOVES: a different fragment stage program is a different
// lifetime id, so ComputeDrawProgramSignature moves and the frontend builds a second
@@ -712,8 +714,7 @@ void main() { o_color = vec4(0.5); }
EXPECT_FALSE(MGPipeHandleIsPublished(MGPipeKind::ShaderCso, handle))
<< "and it took the publication latch with the delete";
EXPECT_EQ(MGPipeSlots().LiveCount(MGPipeKind::ShaderCso), liveBefore) << "exactly once";
EXPECT_EQ(resolver.GetCounters().Releases, releasesBefore)
<< "the resolver spoke no release of its own for it";
EXPECT_EQ(resolver.GetCounters().Releases, releasesBefore) << "the resolver spoke no release of its own for it";
// THE NEXT CONTEXT's FIRST VERB. The stranded entry is dropped, not released.
MGPipeProgramEmitterInstance().Reset();
@@ -742,8 +743,7 @@ int main(int argc, char** argv) {
// raised by the encoder on THIS thread - the client role. So g_logPath, which is the read
// path from here on, becomes the client-derived name; the env keeps the base. The rule is
// the library's own, not a copy.
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(), MobileGL::MG_Util::Debug::LogRole::Client);
MobileGL::Initialize();
::testing::InitGoogleTest(&argc, argv);
const int rc = RUN_ALL_TESTS();
+2 -1
View File
@@ -55,7 +55,8 @@ namespace {
Uint64 bytes = 0;
const RenderStateParameters params = PipelineState(7);
const MGPipeHandle first = cache.Acquire(params, bytes);
for (int i = 0; i < 16; ++i) EXPECT_TRUE(cache.Acquire(params, bytes) == first);
for (int i = 0; i < 16; ++i)
EXPECT_TRUE(cache.Acquire(params, bytes) == first);
EXPECT_EQ(cache.GetCounters().Mints, 1u);
EXPECT_EQ(cache.GetCounters().Hits, 16u);
EXPECT_EQ(cache.Size(), 1u);
+73 -92
View File
@@ -110,7 +110,9 @@ namespace {
SharedPtr<GLContext> m_previous;
};
SizeT Index(MGPipeInputField field) { return static_cast<SizeT>(field); }
SizeT Index(MGPipeInputField field) {
return static_cast<SizeT>(field);
}
#if MGTEST_HAVE_FORK
struct ChildResult {
@@ -139,8 +141,12 @@ namespace {
return result;
}
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
Bool ExitedWith(const ChildResult& r, int code) { return WIFEXITED(r.Status) && WEXITSTATUS(r.Status) == code; }
Bool DiedOfAbort(const ChildResult& r) {
return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT;
}
Bool ExitedWith(const ChildResult& r, int code) {
return WIFEXITED(r.Status) && WEXITSTATUS(r.Status) == code;
}
std::string DescribeStatus(const ChildResult& r) {
if (r.Status < 0) return "fork/waitpid failed";
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
@@ -150,7 +156,6 @@ namespace {
#endif // MGTEST_HAVE_FORK
} // namespace
// ---------------------------------------------------------------------------------------
// The arithmetic: the table partitions the field set. Runs in push, verify and split.
// ---------------------------------------------------------------------------------------
@@ -172,12 +177,9 @@ TEST_F(FieldOwnershipTest, TheClassSizesPartitionTheFieldSet) {
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
++counted[static_cast<SizeT>(kMGPipeFieldOwnership[i])];
}
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kRecordSupplied)],
kMGPipeRecordSuppliedFieldCount);
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kApplierDerived)],
kMGPipeApplierDerivedFieldCount);
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kBarrierPulled)],
kMGPipeBarrierPulledFieldCount);
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kRecordSupplied)], kMGPipeRecordSuppliedFieldCount);
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kApplierDerived)], kMGPipeApplierDerivedFieldCount);
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kBarrierPulled)], kMGPipeBarrierPulledFieldCount);
EXPECT_EQ(counted[static_cast<SizeT>(MGPipeFieldOwnership::kFatal)], kMGPipeFatalFieldCount);
// The census's own arithmetic (scout-unmigrated-census section 2.1), updated by P5c rv
// (CONTRACT-P5C.md §5.3): rv moved the NINE value-class rows to RECORD-SUPPLIED through
@@ -186,8 +188,7 @@ TEST_F(FieldOwnershipTest, TheClassSizesPartitionTheFieldSet) {
// 15 BARRIER-PULLED (the object class: nine non-sticky rows plus six of the seven sticky
// forwards), four APPLIER-DERIVED and three FATAL - and 41 are.
EXPECT_EQ(kMGPipeRecordSuppliedFieldCount, SizeT{41});
EXPECT_EQ(kMGPipeApplierDerivedFieldCount + kMGPipeBarrierPulledFieldCount + kMGPipeFatalFieldCount,
SizeT{22});
EXPECT_EQ(kMGPipeApplierDerivedFieldCount + kMGPipeBarrierPulledFieldCount + kMGPipeFatalFieldCount, SizeT{22});
}
TEST_F(FieldOwnershipTest, EveryBarrierPulledRowNamesTheRetiringPhase) {
@@ -207,12 +208,18 @@ TEST_F(FieldOwnershipTest, EveryBarrierPulledRowNamesTheRetiringPhase) {
TEST_F(FieldOwnershipTest, TheReducedPathsUnmigratedFieldsAreAllAccountedFor) {
// Historical name retained for G14. These are retired legacy getters, not records.
const MGPipeInputField retired[] = {
MGPipeInputField::GetBoundVertexArray, MGPipeInputField::GetBufferBindingSlot,
MGPipeInputField::GetBufferBindingPoint, MGPipeInputField::GetFramebufferBindingSlot,
MGPipeInputField::GetImageTextureBinding, MGPipeInputField::GetTextureUnitObject,
MGPipeInputField::GetProgramForDraw, MGPipeInputField::GetProgramForDispatch,
MGPipeInputField::GetTransformFeedbackProgram, MGPipeInputField::GetProgramObject,
MGPipeInputField::GetTextureObject, MGPipeInputField::ValidateProgramName,
MGPipeInputField::GetBoundVertexArray,
MGPipeInputField::GetBufferBindingSlot,
MGPipeInputField::GetBufferBindingPoint,
MGPipeInputField::GetFramebufferBindingSlot,
MGPipeInputField::GetImageTextureBinding,
MGPipeInputField::GetTextureUnitObject,
MGPipeInputField::GetProgramForDraw,
MGPipeInputField::GetProgramForDispatch,
MGPipeInputField::GetTransformFeedbackProgram,
MGPipeInputField::GetProgramObject,
MGPipeInputField::GetTextureObject,
MGPipeInputField::ValidateProgramName,
MGPipeInputField::RecordError,
};
for (const auto field : retired)
@@ -222,23 +229,17 @@ TEST_F(FieldOwnershipTest, TheReducedPathsUnmigratedFieldsAreAllAccountedFor) {
EXPECT_EQ(kMGPipeAdmittedPullPairCount, SizeT{0});
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetPixelStoreParameters, 0),
MGPipeFieldOwnership::kApplierDerived);
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetPixelStoreParameters, 1),
MGPipeFieldOwnership::kFatal);
EXPECT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetPixelStoreParameters, 1), MGPipeFieldOwnership::kFatal);
for (const auto field : {MGPipeInputField::GetBufferBindingPointCount,
MGPipeInputField::HasOpenTransformFeedbackSpan,
MGPipeInputField::GetTextureBindGeneration,
MGPipeInputField::GetSamplingResolutionGeneration,
MGPipeInputField::GetTextureContextId})
MGPipeInputField::HasOpenTransformFeedbackSpan, MGPipeInputField::GetTextureBindGeneration,
MGPipeInputField::GetSamplingResolutionGeneration, MGPipeInputField::GetTextureContextId})
EXPECT_EQ(MGPipeFieldOwnershipOf(field), MGPipeFieldOwnership::kApplierDerived);
for (const auto field : {MGPipeInputField::GetActiveTextureUnit,
MGPipeInputField::GetMaxTouchedTextureUnit,
MGPipeInputField::GetTouchedBufferBindingPointCount,
MGPipeInputField::IsTransformFeedbackActive,
MGPipeInputField::IsTransformFeedbackPaused,
MGPipeInputField::GetTransformFeedbackGeneration,
MGPipeInputField::GetBoundTransformFeedbackLifetimeId,
MGPipeInputField::GetTransformFeedbackCapturedVertices,
MGPipeInputField::GetCurrentVertexAttribute})
for (const auto field :
{MGPipeInputField::GetActiveTextureUnit, MGPipeInputField::GetMaxTouchedTextureUnit,
MGPipeInputField::GetTouchedBufferBindingPointCount, MGPipeInputField::IsTransformFeedbackActive,
MGPipeInputField::IsTransformFeedbackPaused, MGPipeInputField::GetTransformFeedbackGeneration,
MGPipeInputField::GetBoundTransformFeedbackLifetimeId, MGPipeInputField::GetTransformFeedbackCapturedVertices,
MGPipeInputField::GetCurrentVertexAttribute})
EXPECT_EQ(MGPipeFieldOwnershipOf(field), MGPipeFieldOwnership::kRecordSupplied);
}
@@ -271,7 +272,8 @@ TEST_F(FieldOwnershipTest, EveryVerbsRecordOpIsStampedAsAVerbOfTheSameFillClass)
const MGPipeVerb stamped = MGPipeVerbForWireOp(op);
ASSERT_NE(stamped, MGPipeVerb::kVerbCount) << kMGPipeVerbNames[i] << ": its record op stamps no verb";
EXPECT_EQ(kMGPipeVerbClass[static_cast<SizeT>(stamped)], kMGPipeVerbClass[i])
<< kMGPipeVerbNames[i] << " publishes a record stamped as " << kMGPipeVerbNames[static_cast<SizeT>(stamped)];
<< kMGPipeVerbNames[i] << " publishes a record stamped as "
<< kMGPipeVerbNames[static_cast<SizeT>(stamped)];
}
// GetIntegeri_v and IsTimerQuerySupported, answered from the caps mirror.
EXPECT_EQ(noRecord, 2u);
@@ -306,8 +308,7 @@ TEST_F(FieldOwnershipTest, VerbBoundaryOpsCoverEveryVerbShapedCall) {
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::BindShaderImage), MGPipeVerb::BindImageTexture);
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::PatchParameter), MGPipeVerb::PatchParameteri);
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::BindStreamOutput), MGPipeVerb::BindTransformFeedback);
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::SetStorageBlockBinding),
MGPipeVerb::ShaderStorageBlockBinding);
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::SetStorageBlockBinding), MGPipeVerb::ShaderStorageBlockBinding);
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::CopyFramebufferToTexture), MGPipeVerb::CopyTexImage2D);
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::FenceCreate), MGPipeVerb::FenceSync);
EXPECT_EQ(MGPipeVerbForWireOp(MGPWireOp::FenceStatus), MGPipeVerb::GetSyncStatus);
@@ -352,11 +353,9 @@ TEST_F(FieldOwnershipTest, TheAdmittedPullTableIsID84sDerivationAndNotAList) {
EXPECT_EQ(kMGPipeAdmittedPullPairCount, SizeT{0});
for (SizeT v = 0; v < kMGPipeVerbCount; ++v)
for (SizeT f = 0; f < kMGPipeInputFieldCount; ++f)
EXPECT_FALSE(MGPipeBarrierPullAdmitted(static_cast<MGPipeInputField>(f),
static_cast<MGPipeVerb>(v)))
EXPECT_FALSE(MGPipeBarrierPullAdmitted(static_cast<MGPipeInputField>(f), static_cast<MGPipeVerb>(v)))
<< kMGPipeInputFieldNames[f] << "@" << kMGPipeVerbNames[v];
EXPECT_FALSE(MGPipeBarrierPullAdmitted(MGPipeInputField::GetFramebufferBindingSlot,
MGPipeVerb::kVerbCount));
EXPECT_FALSE(MGPipeBarrierPullAdmitted(MGPipeInputField::GetFramebufferBindingSlot, MGPipeVerb::kVerbCount));
}
// ---------------------------------------------------------------------------------------
@@ -395,31 +394,27 @@ TEST_F(FieldOwnershipTest, TheResidualFillsSuppliedMemoReKeysOnEveryInputThatMov
// applier writes it without deriving, so at a mask that carries the render-state bit the
// fill skips it - and at 0, which is what a unit lane runs at (Features.PipePush defaults
// to 0), nothing is emitted and every field is pulled.
EXPECT_FALSE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetRenderStateParameters,
kNoSubsystems, true, false));
EXPECT_TRUE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetRenderStateParameters,
kEverySubsystem, true, false));
EXPECT_FALSE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetRenderStateParameters,
kNoSubsystems, true, false))
EXPECT_FALSE(
MGPipeResidualFillSuppliesField(MGPipeInputField::GetRenderStateParameters, kNoSubsystems, true, false));
EXPECT_TRUE(
MGPipeResidualFillSuppliesField(MGPipeInputField::GetRenderStateParameters, kEverySubsystem, true, false));
EXPECT_FALSE(
MGPipeResidualFillSuppliesField(MGPipeInputField::GetRenderStateParameters, kNoSubsystems, true, false))
<< "the memo answered the previous mask: MOBILEGL_PIPE_PUSH is not in its key, and a "
"per-subsystem A/B would then fill from the wrong subsystem set";
// 2. THE DERIVATION LATCH. GetViewport reaches PipeInputs only through
// MGPipeDeriveRenderStateFields, so a build whose derivation is a stub must keep PULLING
// it - skipping it there leaves the mirror unwritten and the backend reading a default.
EXPECT_TRUE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetViewport, kEverySubsystem,
true, false));
EXPECT_FALSE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetViewport, kEverySubsystem,
false, false))
EXPECT_TRUE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetViewport, kEverySubsystem, true, false));
EXPECT_FALSE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetViewport, kEverySubsystem, false, false))
<< "the memo answered the previous latch: ApplierDerivesRenderStateFields is not in its key";
// 3. P5c rv's WIRE GATE (CONTRACT-P5C.md §5.3). set_context_values has no producer without a
// live wire, so its eight value-class fields keep being pulled under monolith - G1's
// byte-for-byte rule - and are skipped only when the record really crosses.
EXPECT_FALSE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetActiveTextureUnit,
kEverySubsystem, true, false));
EXPECT_TRUE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetActiveTextureUnit,
kEverySubsystem, true, true))
EXPECT_FALSE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetActiveTextureUnit, kEverySubsystem, true, false));
EXPECT_TRUE(MGPipeResidualFillSuppliesField(MGPipeInputField::GetActiveTextureUnit, kEverySubsystem, true, true))
<< "the memo answered the previous wire state: contextValuesWireLive is not in its key, "
"and the emission's half of the gate and the fill's half would then disagree";
@@ -441,8 +436,7 @@ TEST_F(FieldOwnershipTest, TheResidualFillsSuppliedMemoReKeysOnEveryInputThatMov
ASSERT_NE(MGPipeGetResourceOps(), nullptr)
<< "the fixture did not move the signal it names, so this step observes nothing";
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
if (MGPipeResidualFillSuppliesField(static_cast<MGPipeInputField>(i), kEverySubsystem,
true, true)) {
if (MGPipeResidualFillSuppliesField(static_cast<MGPipeInputField>(i), kEverySubsystem, true, true)) {
withConsumer.Words[i / 64] |= (Uint64{1} << (i % 64));
}
}
@@ -450,8 +444,7 @@ TEST_F(FieldOwnershipTest, TheResidualFillsSuppliedMemoReKeysOnEveryInputThatMov
MGPipeSetResourceOps(nullptr);
ASSERT_EQ(MGPipeGetResourceOps(), nullptr);
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
if (MGPipeResidualFillSuppliesField(static_cast<MGPipeInputField>(i), kEverySubsystem,
true, true)) {
if (MGPipeResidualFillSuppliesField(static_cast<MGPipeInputField>(i), kEverySubsystem, true, true)) {
withoutConsumer.Words[i / 64] |= (Uint64{1} << (i % 64));
}
}
@@ -461,13 +454,11 @@ TEST_F(FieldOwnershipTest, TheResidualFillsSuppliedMemoReKeysOnEveryInputThatMov
// and so rides the framebuffer family's consumer gate - and is pulled regardless, because
// its storage is a BindingSlot<FramebufferObject> no payload can carry.
EXPECT_FALSE(MGPipeFieldMaskHas(withConsumer, MGPipeInputField::GetFramebufferBindingSlot));
EXPECT_FALSE(
MGPipeFieldMaskHas(withoutConsumer, MGPipeInputField::GetFramebufferBindingSlot));
EXPECT_FALSE(MGPipeFieldMaskHas(withoutConsumer, MGPipeInputField::GetFramebufferBindingSlot));
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
const auto field = static_cast<MGPipeInputField>(i);
EXPECT_EQ(MGPipeFieldMaskHas(withConsumer, field),
MGPipeFieldMaskHas(withoutConsumer, field))
EXPECT_EQ(MGPipeFieldMaskHas(withConsumer, field), MGPipeFieldMaskHas(withoutConsumer, field))
<< kMGPipeInputFieldNames[i]
<< "'s supplied answer moved with the P4a consumer signal. That is CORRECT "
"behaviour and this assertion is a trip wire, not a defect report: the "
@@ -488,8 +479,8 @@ TEST_F(FieldOwnershipTest, AServerStampMakesRecordSuppliedFieldsFreshAndWithdraw
MGPipeServerStampVerbBoundary(MGPipeVerb::Clear);
EXPECT_TRUE(gPipeInputs->ServerStampedVerb());
EXPECT_EQ(gPipeInputs->CurrentVerb(), MGPipeVerb::Clear);
const MGPipeFieldMask& mask = kMGPipeClassFieldMask[static_cast<SizeT>(
kMGPipeVerbClass[static_cast<SizeT>(MGPipeVerb::Clear)])];
const MGPipeFieldMask& mask =
kMGPipeClassFieldMask[static_cast<SizeT>(kMGPipeVerbClass[static_cast<SizeT>(MGPipeVerb::Clear)])];
SizeT stamped = 0;
for (SizeT i = 0; i < kMGPipeInputFieldCount; ++i) {
const auto field = static_cast<MGPipeInputField>(i);
@@ -497,12 +488,12 @@ TEST_F(FieldOwnershipTest, AServerStampMakesRecordSuppliedFieldsFreshAndWithdraw
// The stamp respects the verb's own may-read table for the client fill's reason: a
// field outside the class was never copied for this verb, so answering it would hand
// the server the previous verb's value.
const Bool answerable = MGPipeFieldMaskHas(mask, field) &&
(kMGPipeFieldOwnership[i] == MGPipeFieldOwnership::kRecordSupplied ||
kMGPipeFieldOwnership[i] == MGPipeFieldOwnership::kApplierDerived);
EXPECT_EQ(fresh, answerable)
<< kMGPipeInputFieldNames[i] << " is " << MGPipeFieldOwnershipName(kMGPipeFieldOwnership[i])
<< " and the stamp answered " << (fresh ? "fresh" : "stale");
const Bool answerable =
MGPipeFieldMaskHas(mask, field) && (kMGPipeFieldOwnership[i] == MGPipeFieldOwnership::kRecordSupplied ||
kMGPipeFieldOwnership[i] == MGPipeFieldOwnership::kApplierDerived);
EXPECT_EQ(fresh, answerable) << kMGPipeInputFieldNames[i] << " is "
<< MGPipeFieldOwnershipName(kMGPipeFieldOwnership[i]) << " and the stamp answered "
<< (fresh ? "fresh" : "stale");
stamped += fresh ? 1 : 0;
}
// Not vacuous: kClear really does have record-supplied fields to stamp.
@@ -513,10 +504,10 @@ TEST_F(FieldOwnershipTest, AServerStampMakesRecordSuppliedFieldsFreshAndWithdraw
// with the table - never a table that is wrong. These four say what the stamp must do for
// four fields whose class is an argument of this package rather than a lookup.
const MGPipeFilledState& filled = gPipeInputs->FilledState();
EXPECT_TRUE(MGPipeInputFieldIsFresh(filled, MGPipeInputField::GetClearColor)); // supplied
EXPECT_TRUE(MGPipeInputFieldIsFresh(filled, MGPipeInputField::GetClearColor)); // supplied
EXPECT_TRUE(MGPipeInputFieldIsFresh(filled, MGPipeInputField::GetRenderStateParameters));
EXPECT_FALSE(MGPipeInputFieldIsFresh(filled, MGPipeInputField::GetFramebufferBindingSlot)); // pulled
EXPECT_FALSE(MGPipeInputFieldIsFresh(filled, MGPipeInputField::RecordError)); // sticky
EXPECT_FALSE(MGPipeInputFieldIsFresh(filled, MGPipeInputField::RecordError)); // sticky
}
// THE STICKY EXEMPTION, CANCELLED. generated/PipeFilled.inc answers "fresh" for a sticky field
@@ -540,8 +531,7 @@ TEST_F(FieldOwnershipTest, TheStickyExemptionIsCancelledByTheServerStamp) {
// E4's NEGATIVE CONTROL. Move one field from RECORD-SUPPLIED to FATAL in FieldOwnership.def
// and this case goes red by name: the read below aborts instead of completing.
TEST_F(FieldOwnershipTest, ARecordSuppliedFieldIsReadableAfterAServerStamp) {
ASSERT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetClearColor),
MGPipeFieldOwnership::kRecordSupplied);
ASSERT_EQ(MGPipeFieldOwnershipOf(MGPipeInputField::GetClearColor), MGPipeFieldOwnership::kRecordSupplied);
MGPipeServerStampVerbBoundary(MGPipeVerb::Clear);
(void)gPipeInputs->GetClearColor();
(void)gPipeInputs->GetRenderStateParameters();
@@ -610,7 +600,6 @@ TEST_F(FieldOwnershipTest, ABarrierPulledReadAfterAServerStampIsCountedNotFatal)
#if MGTEST_HAVE_FORK
// Historical name retained for G14: the formerly admitted read is now forbidden.
const ChildResult r = RunInChild([] {
MGPipeServerStampVerbBoundary(MGPipeVerb::DrawArrays);
(void)gPipeInputs->GetBoundVertexArray();
});
@@ -627,7 +616,6 @@ TEST_F(FieldOwnershipTest, AStickyForwardIsCountedAsAResidualPull) {
#if MGTEST_HAVE_FORK
// Historical name retained for G14: the formerly admitted read is now forbidden.
const ChildResult r = RunInChild([] {
MGPipeServerStampVerbBoundary(MGPipeVerb::Clear);
(void)gPipeInputs->ValidateProgramName(1u);
});
@@ -680,8 +668,7 @@ TEST_F(FieldOwnershipTest, ABarrierPulledFieldOutsideTheVerbsClassIsStillFatal)
(void)gPipeInputs->GetProgramForDraw(); // retired accessor, outside kClear too
});
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetProgramForDraw@Clear\"}"), std::string::npos)
<< r.Log;
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetProgramForDraw@Clear\"}"), std::string::npos) << r.Log;
EXPECT_EQ(r.Log.find("BARRIER-PULLED"), std::string::npos) << r.Log;
#else
GTEST_SKIP() << "needs fork";
@@ -730,8 +717,7 @@ namespace {
}
void Arm(Bool arm) {
MG_Config::Ipc.RoleSplitState = arm;
MG_Config::Transport = arm ? MG_Config::TransportMode::InProcess
: MG_Config::TransportMode::Monolith;
MG_Config::Transport = arm ? MG_Config::TransportMode::InProcess : MG_Config::TransportMode::Monolith;
}
MG_Config::TransportMode m_previousTransport;
Bool m_previousKnob;
@@ -872,8 +858,7 @@ TEST_F(FieldOwnershipTest, RoleSplitGivesTheFillSideADistinctBlockTheStampNeverT
// which is CONTRACT-P5E §3.2's "the server's stamp is server-private" as a fact rather
// than as a comment.
MGPipeClientClearVerbBoundary();
EXPECT_TRUE(gPipeInputs->ServerStampedVerb())
<< "the client-role clear withdrew the SERVER's stamp";
EXPECT_TRUE(gPipeInputs->ServerStampedVerb()) << "the client-role clear withdrew the SERVER's stamp";
MGPipeServerClearVerbBoundary();
EXPECT_FALSE(gPipeInputs->ServerStampedVerb());
@@ -914,8 +899,7 @@ TEST_F(FieldOwnershipTest, AClientFreshStampCannotReviveARetiredServerGetter) {
(void)gPipeInputs->GetBoundVertexArray();
});
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetBoundVertexArray@DrawArrays\"}"),
std::string::npos) << r.Log;
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetBoundVertexArray@DrawArrays\"}"), std::string::npos) << r.Log;
}
TEST_F(FieldOwnershipTest, StrictErrorsTurnsABarrierPulledReadIntoANamedAbort) {
@@ -1000,12 +984,12 @@ TEST_F(FieldOwnershipTest, AFatalClassReadAbortsEvenWithoutStrictErrors) {
TEST_F(FieldOwnershipTest, TheComputeProgramIsServedUnderADispatchStampFromP5bOn) {
// Historical name retained for G14: the formerly admitted read is now forbidden.
const ChildResult r = RunInChild([] {
MGPipeServerStampVerbBoundary(MGPipeVerb::DispatchCompute);
(void)gPipeInputs->GetProgramForDispatch();
});
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetProgramForDispatch@DispatchCompute\"}"), std::string::npos) << r.Log;
EXPECT_NE(r.Log.find("Fatal{UnmigratedPipeInput, \"GetProgramForDispatch@DispatchCompute\"}"), std::string::npos)
<< r.Log;
EXPECT_EQ(r.Log.find("Admitted{"), std::string::npos) << r.Log;
}
@@ -1019,15 +1003,13 @@ TEST_F(FieldOwnershipTest, TheUnpackHalfOfThePixelStoreAbortsWhileThePackHalfDoe
(void)gPipeInputs->GetPixelStoreParameters(true);
});
ASSERT_TRUE(DiedOfAbort(fatal)) << DescribeStatus(fatal) << "\n" << fatal.Log;
EXPECT_NE(fatal.Log.find("Fatal{UnmigratedPipeInput, \"GetPixelStoreParameters@ReadPixels\"}"),
std::string::npos)
EXPECT_NE(fatal.Log.find("Fatal{UnmigratedPipeInput, \"GetPixelStoreParameters@ReadPixels\"}"), std::string::npos)
<< fatal.Log;
// The line must say WHICH HALF. Without this the message is byte-identical to what a
// genuinely stale read of the pack half would print, and the whole case for narrowing by
// argument instead of by a second field id is that the reader is told which half they
// asked for.
EXPECT_NE(fatal.Log.find("argument 0 = 1 is FATAL while the field is APPLIER-DERIVED"),
std::string::npos)
EXPECT_NE(fatal.Log.find("argument 0 = 1 is FATAL while the field is APPLIER-DERIVED"), std::string::npos)
<< fatal.Log;
const ChildResult ok = RunInChild([] {
@@ -1055,8 +1037,7 @@ TEST_F(FieldOwnershipTest, AnUnmigratedEmulationIsFatalUnderARealTransportAndIne
MGPipeUnmigratedEmulation("get-tex-image-shadow");
});
ASSERT_TRUE(DiedOfAbort(split)) << DescribeStatus(split) << "\n" << split.Log;
EXPECT_NE(split.Log.find("Fatal{UnmigratedEmulation, \"get-tex-image-shadow\"}"), std::string::npos)
<< split.Log;
EXPECT_NE(split.Log.find("Fatal{UnmigratedEmulation, \"get-tex-image-shadow\"}"), std::string::npos) << split.Log;
}
// P5f terminal contract; the historical registration name is retained for G14.
+51 -68
View File
@@ -137,7 +137,9 @@ namespace {
return result;
}
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
Bool DiedOfAbort(const ChildResult& r) {
return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT;
}
std::string DescribeStatus(const ChildResult& r) {
if (r.Status < 0) return "fork/waitpid failed";
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
@@ -242,10 +244,8 @@ namespace {
// content-addressed cache) and bit 10 requires bit 7 (a buffer texture's
// BufferForTexBuffer names a Buffer handle, D-D1). Bit 7 changes nothing else here:
// this file constructs no BufferObject.
MG_Config::Features.PipePush |= kMGPipeSubsystemResources |
kMGPipeSubsystemFramebuffer |
kMGPipeSubsystemTextureResources |
kMGPipeSubsystemSamplers;
MG_Config::Features.PipePush |= kMGPipeSubsystemResources | kMGPipeSubsystemFramebuffer |
kMGPipeSubsystemTextureResources | kMGPipeSubsystemSamplers;
m_previousContext = MG_State::pGLContext.Take();
MG_State::pGLContext = MakeUnique<GLContext>();
MGPipeFramebufferEmitterInstance().ResetForTest();
@@ -275,17 +275,21 @@ namespace {
Uint64 m_previousPush = 0;
};
MGPipeFramebufferEmitter& Framebuffers() { return MGPipeFramebufferEmitterInstance(); }
GLContext& Ctx() { return *MG_State::pGLContext; }
MGPipeFramebufferEmitter& Framebuffers() {
return MGPipeFramebufferEmitterInstance();
}
GLContext& Ctx() {
return *MG_State::pGLContext;
}
SharedPtr<TextureObject2D> MakeColorTexture(Uint name, Int size, Uint levels = 1) {
auto texture = MakeShared<TextureObject2D>(name);
texture->SetInternalFormat(TextureInternalFormat::RGBA8);
for (Uint level = 0; level < levels; ++level) {
const Int extent = std::max<Int>(size >> level, 1);
texture->AllocateStorage(TextureUploadTarget::Texture2D, level,
MipmapInput{IntVec3{extent, extent, 1},
static_cast<SizeT>(extent) * static_cast<SizeT>(extent) * 4});
texture->AllocateStorage(
TextureUploadTarget::Texture2D, level,
MipmapInput{IntVec3{extent, extent, 1}, static_cast<SizeT>(extent) * static_cast<SizeT>(extent) * 4});
}
return texture;
}
@@ -362,8 +366,7 @@ TEST(FramebufferEmit, OneObjectBoundToBothTargetsEmitsOneRecordWithTargetBoth) {
Framebuffers().EmitFramebufferState(Ctx());
EXPECT_EQ(Framebuffers().EmissionCount(), 1u) << "one object on both targets is ONE record";
EXPECT_EQ(Framebuffers().LastDraw().Target, static_cast<Uint8>(MGPipeFramebufferTarget::Both));
const MGPipeHandle color1Handle =
MGPipeSlots().FindByLifetimeId(MGPipeKind::Texture, color1->GetLifetimeId());
const MGPipeHandle color1Handle = MGPipeSlots().FindByLifetimeId(MGPipeKind::Texture, color1->GetLifetimeId());
EXPECT_TRUE(Framebuffers().LastDraw().ReadSurface.Res == color1Handle)
<< "the shared-FBO record's ReadSurface is not that object's own read buffer";
}
@@ -445,10 +448,10 @@ TEST(FramebufferEmit, EveryAttachmentFieldSurvivesTheSurfaceConversion) {
colors.push_back(MakeColorTexture(static_cast<Uint>(20 + i), 32, 2));
// Distinct level, layer and layered flag per point, so a conversion that dropped one
// field could not be masked by another point's value.
fbo->AttachTexture(static_cast<FramebufferAttachmentType>(
static_cast<Int>(FramebufferAttachmentType::Color0) + static_cast<Int>(i)),
colors.back(), TextureUploadTarget::Texture2D,
static_cast<int>(i % 2), static_cast<int>(i), (i % 2) == 0);
fbo->AttachTexture(static_cast<FramebufferAttachmentType>(static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(i)),
colors.back(), TextureUploadTarget::Texture2D, static_cast<int>(i % 2), static_cast<int>(i),
(i % 2) == 0);
}
const auto depth = MakeShared<RenderbufferObject>(2);
depth->SetInternalFormat(TextureInternalFormat::Depth24Stencil8);
@@ -463,8 +466,8 @@ TEST(FramebufferEmit, EveryAttachmentFieldSurvivesTheSurfaceConversion) {
const MGPFramebufferState& record = Framebuffers().LastDraw();
for (SizeT i = 0; i < kMGPipeMaxColorAttachments; ++i) {
const auto type = static_cast<FramebufferAttachmentType>(
static_cast<Int>(FramebufferAttachmentType::Color0) + static_cast<Int>(i));
const auto type = static_cast<FramebufferAttachmentType>(static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(i));
const auto& attachment = fbo->GetAttachment(type);
const MGPSurface& surface = record.Color[i];
const MGPipeHandle expected =
@@ -477,29 +480,25 @@ TEST(FramebufferEmit, EveryAttachmentFieldSurvivesTheSurfaceConversion) {
<< "MGPSurface::Level at colour point " << i;
EXPECT_EQ(surface.Layer, static_cast<Uint32>(attachment.GetTextureLayer()))
<< "MGPSurface::Layer at colour point " << i;
EXPECT_EQ(surface.Layered, attachment.IsLayered() ? 1 : 0)
<< "MGPSurface::Layered at colour point " << i;
EXPECT_EQ(surface.Layered, attachment.IsLayered() ? 1 : 0) << "MGPSurface::Layered at colour point " << i;
EXPECT_EQ(surface.UploadTarget, static_cast<Uint16>(TextureUploadTarget::Texture2D))
<< "MGPSurface::UploadTarget at colour point " << i;
// ID-12 DV-5: three of the four cross-object masks reduce to (format, TEXTURE TARGET)
// and no TextureUploadTarget -> TextureTarget inverse exists anywhere in the tree.
EXPECT_EQ(surface.TextureTarget,
static_cast<Uint16>(attachment.GetTexture()->GetTarget()))
EXPECT_EQ(surface.TextureTarget, static_cast<Uint16>(attachment.GetTexture()->GetTarget()))
<< "MGPSurface::TextureTarget at colour point " << i;
}
EXPECT_EQ(record.Depth.Kind, kMGPipeSurfaceKindRenderbuffer) << "MGPSurface::Kind on the depth point";
EXPECT_EQ(record.Depth.InternalFormat, static_cast<Uint32>(depth->GetInternalFormat()))
<< "MGPSurface::InternalFormat on the depth point";
EXPECT_TRUE(record.Depth.Res ==
MGPipeSlots().FindByLifetimeId(MGPipeKind::Renderbuffer, depth->GetLifetimeId()))
EXPECT_TRUE(record.Depth.Res == MGPipeSlots().FindByLifetimeId(MGPipeKind::Renderbuffer, depth->GetLifetimeId()))
<< "MGPSurface::Res on the depth point";
EXPECT_EQ(record.Depth.Layered, 0) << "MGPSurface::Layered on the depth point";
EXPECT_EQ(record.Depth.TextureTarget, kMGPipeSurfaceNoTextureTarget)
<< "MGPSurface::TextureTarget on the RENDERBUFFER point must be the Unknown sentinel";
EXPECT_EQ(record.Stencil.Kind, kMGPipeSurfaceKindTexture) << "MGPSurface::Kind on the stencil point";
EXPECT_TRUE(record.Stencil.Res ==
MGPipeSlots().FindByLifetimeId(MGPipeKind::Texture, stencil->GetLifetimeId()))
EXPECT_TRUE(record.Stencil.Res == MGPipeSlots().FindByLifetimeId(MGPipeKind::Texture, stencil->GetLifetimeId()))
<< "MGPSurface::Res on the stencil point";
EXPECT_EQ(record.Width, 32u) << "MGPFramebufferState::Width";
@@ -520,8 +519,7 @@ TEST(FramebufferEmit, EveryAttachmentFieldSurvivesTheSurfaceConversion) {
// BOTH TARGET FIELDS CARRY THE SENTINEL, not 0 (m6 / ID-12 DV-5): a Uint16 zero is
// TextureUploadTarget::Texture1D and TextureTarget::Texture1D, so a reader that forgot to
// gate on Kind would read a plausible wrong answer instead of a nonsense one.
EXPECT_EQ(Framebuffers().LastDraw().Color[1].UploadTarget,
static_cast<Uint16>(TextureUploadTarget::Unknown));
EXPECT_EQ(Framebuffers().LastDraw().Color[1].UploadTarget, static_cast<Uint16>(TextureUploadTarget::Unknown));
EXPECT_EQ(Framebuffers().LastDraw().Color[1].TextureTarget, kMGPipeSurfaceNoTextureTarget);
}
@@ -540,9 +538,8 @@ TEST(FramebufferEmit, AnAttachmentPointAboveTheWireWidthIsRefusedNotTruncated) {
// MGPFramebufferState::Color[] is eight wide and MaxColorAttachments is the driver's raw ES
// cap, not clamped to eight on the GLES path. Truncating silently is the bug class this
// phase is closing, so the record is REFUSED and the legacy arm runs.
fbo->AttachTexture(static_cast<FramebufferAttachmentType>(
static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(kMGPipeMaxColorAttachments)),
fbo->AttachTexture(static_cast<FramebufferAttachmentType>(static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(kMGPipeMaxColorAttachments)),
beyond, TextureUploadTarget::Texture2D);
Framebuffers().EmitFramebufferState(Ctx());
EXPECT_EQ(Framebuffers().EmissionCount(), 1u)
@@ -576,8 +573,8 @@ TEST(FramebufferEmit, TheRecordsElevenSurfacesAreTheWholePointSetTheServerReads)
Vector<SharedPtr<TextureObject2D>> colors;
for (Uint i = 0; i < kMGPipeMaxColorAttachments; ++i) {
colors.push_back(MakeColorTexture(70 + i, 32));
fbo->AttachTexture(static_cast<FramebufferAttachmentType>(
static_cast<Int>(FramebufferAttachmentType::Color0) + static_cast<Int>(i)),
fbo->AttachTexture(static_cast<FramebufferAttachmentType>(static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(i)),
colors.back(), TextureUploadTarget::Texture2D);
}
const auto depth = MakeShared<RenderbufferObject>(21);
@@ -599,11 +596,9 @@ TEST(FramebufferEmit, TheRecordsElevenSurfacesAreTheWholePointSetTheServerReads)
const MGPFramebufferState* const applied = MGPipeApplier().DrawFramebuffer();
ASSERT_NE(applied, nullptr);
for (Uint i = 0; i < kMGPipeMaxColorAttachments; ++i) {
const MGPipeHandle expected =
MGPipeSlots().FindByLifetimeId(MGPipeKind::Texture, colors[i]->GetLifetimeId());
const MGPipeHandle expected = MGPipeSlots().FindByLifetimeId(MGPipeKind::Texture, colors[i]->GetLifetimeId());
EXPECT_FALSE(MGPipeHandleIsNull(expected)) << "colour point " << i << " minted no handle";
EXPECT_TRUE(applied->Color[i].Res == expected)
<< "colour point " << i << " did not reach the server's record";
EXPECT_TRUE(applied->Color[i].Res == expected) << "colour point " << i << " did not reach the server's record";
EXPECT_EQ(applied->Color[i].Kind, kMGPipeSurfaceKindTexture) << "at colour point " << i;
}
EXPECT_EQ(applied->Depth.Kind, kMGPipeSurfaceKindRenderbuffer) << "the Depth point";
@@ -614,9 +609,8 @@ TEST(FramebufferEmit, TheRecordsElevenSurfacesAreTheWholePointSetTheServerReads)
const Uint64 hashBefore = applied->ContentHash;
const Uint64 serialBefore = MGPipeApplier().FramebufferSerial;
const auto beyond = MakeColorTexture(90, 32);
fbo->AttachTexture(static_cast<FramebufferAttachmentType>(
static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(kMGPipeMaxColorAttachments)),
fbo->AttachTexture(static_cast<FramebufferAttachmentType>(static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(kMGPipeMaxColorAttachments)),
beyond, TextureUploadTarget::Texture2D);
Framebuffers().EmitFramebufferState(Ctx());
EXPECT_GE(Framebuffers().RefusedCount(), 1u) << "the over-wide framebuffer was not refused";
@@ -730,8 +724,7 @@ TEST(FramebufferEmit, ARestoragedAttachedRenderbufferPublishesItsNewExtent) {
BindDrawAndRead(fbo, fbo);
Framebuffers().EmitFramebufferState(Ctx());
const MGPipeHandle handle =
MGPipeSlots().FindByLifetimeId(MGPipeKind::Renderbuffer, renderbuffer->GetLifetimeId());
const MGPipeHandle handle = MGPipeSlots().FindByLifetimeId(MGPipeKind::Renderbuffer, renderbuffer->GetLifetimeId());
ASSERT_FALSE(MGPipeHandleIsNull(handle));
const Uint64 respecifiesBefore = MGPipeTextureEmitterInstance().RespecifyCount();
@@ -785,18 +778,15 @@ TEST(FramebufferEmit, AFramebufferHandedOverByNameGetsANamedRecordWithoutMovingA
EXPECT_EQ(Framebuffers().LastNamed().Target, static_cast<Uint8>(MGPipeFramebufferTarget::Named));
EXPECT_GT(MGPipeApplier().FramebufferSerial, serialBefore) << "a Named record must publish";
const MGPFramebufferState* stored =
MGPipeApplier().FramebufferRecordFor(Framebuffers().LastNamed().Fbo);
const MGPFramebufferState* stored = MGPipeApplier().FramebufferRecordFor(Framebuffers().LastNamed().Fbo);
ASSERT_NE(stored, nullptr) << "the framebuffer the server is about to receive by name has no record";
EXPECT_EQ(stored->Width, 16u) << "the Named record does not describe the object it names";
// AND IT MOVED NEITHER BINDING.
ASSERT_NE(MGPipeApplier().DrawFramebuffer(), nullptr);
EXPECT_TRUE(MGPipeApplier().DrawFramebuffer()->Fbo == boundHandle)
<< "a Named record took the draw binding";
EXPECT_TRUE(MGPipeApplier().DrawFramebuffer()->Fbo == boundHandle) << "a Named record took the draw binding";
ASSERT_NE(MGPipeApplier().ReadFramebuffer(), nullptr);
EXPECT_TRUE(MGPipeApplier().ReadFramebuffer()->Fbo == boundHandle)
<< "a Named record took the read binding";
EXPECT_TRUE(MGPipeApplier().ReadFramebuffer()->Fbo == boundHandle) << "a Named record took the read binding";
}
TEST(FramebufferEmit, ANamedRecordIsSuppressedPerObjectAndNeverAgainstABoundRecord) {
@@ -842,9 +832,8 @@ TEST(FramebufferEmit, ADrawBufferTokenAboveTheWireWidthIsRefusedNotTruncated) {
// A LEGAL STATE THE ATTACHMENT SCAN CANNOT SEE: nothing is attached at the point the token
// names, so D-C3's attachment loop passes, and MGPipeDrawBufferIndex would write an index of
// 8 or more into an 8-wide array.
fbo->SetDrawBuffer(0, static_cast<FramebufferAttachmentType>(
static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(kMGPipeMaxColorAttachments) + 2));
fbo->SetDrawBuffer(0, static_cast<FramebufferAttachmentType>(static_cast<Int>(FramebufferAttachmentType::Color0) +
static_cast<Int>(kMGPipeMaxColorAttachments) + 2));
Framebuffers().EmitFramebufferState(Ctx());
EXPECT_EQ(Framebuffers().EmissionCount(), 1u)
<< "a draw-buffer token naming a colour point at or above the wire width was truncated "
@@ -873,12 +862,10 @@ TEST(FramebufferEmit, ALayeredCubeAttachmentDoesNotAssertAFaceItCannotKnow) {
Framebuffers().EmitFramebufferState(Ctx());
ASSERT_EQ(Framebuffers().EmissionCount(), 1u);
EXPECT_EQ(Framebuffers().LastDraw().Color[0].Layered, 1);
EXPECT_EQ(Framebuffers().LastDraw().Color[0].UploadTarget,
static_cast<Uint16>(TextureUploadTarget::Unknown))
EXPECT_EQ(Framebuffers().LastDraw().Color[0].UploadTarget, static_cast<Uint16>(TextureUploadTarget::Unknown))
<< "a layered cube attachment resolved to one face, so the record asserts a face the "
"attachment does not name";
EXPECT_EQ(Framebuffers().LastDraw().Color[0].TextureTarget,
static_cast<Uint16>(TextureTarget::TextureCubeMap))
EXPECT_EQ(Framebuffers().LastDraw().Color[0].TextureTarget, static_cast<Uint16>(TextureTarget::TextureCubeMap))
<< "MGPSurface::TextureTarget is what a cross-object mask reads instead";
}
@@ -958,8 +945,7 @@ TEST(FramebufferEmit, ADrawRecordAndAReadRecordAreKeptApartAndBothWritesBoth) {
EXPECT_EQ(MGPipeApplier().DrawFramebuffer()->Width, 100u);
EXPECT_EQ(MGPipeApplier().DrawFramebuffer()->Color[0].InternalFormat, 0x8058u);
EXPECT_EQ(MGPipeApplier().DrawFramebuffer()->DrawBuffers[0], 0);
EXPECT_EQ(MGPipeApplier().ReadFramebuffer(), nullptr)
<< "a Draw record landed in the read binding as well";
EXPECT_EQ(MGPipeApplier().ReadFramebuffer(), nullptr) << "a Draw record landed in the read binding as well";
const Uint64 afterDraw = MGPipeApplier().FramebufferSerial;
EXPECT_GT(afterDraw, serialAtStart) << "an applied record must move the serial the twin memoises";
@@ -1011,8 +997,7 @@ TEST(FramebufferEmit, ATargetOutsideTheThreeBindingsIsRefusedNamingTheRecord) {
EXPECT_EQ(MGPipeApplier().ReadFramebuffer(), nullptr);
EXPECT_EQ(MGPipeApplier().FramebufferRecordFor(MGPipeHandle{7, 4}), nullptr)
<< "a refused record was written into the per-object table anyway";
EXPECT_EQ(MGPipeApplier().FramebufferSerial, serialBefore)
<< "a refused record must not move the serial";
EXPECT_EQ(MGPipeApplier().FramebufferSerial, serialBefore) << "a refused record must not move the serial";
}
// The draw-buffer array is an INDEX into this record's own Color[], and -1 is NONE. An entry
@@ -1163,7 +1148,8 @@ TEST(FramebufferEmit, ANamedRecordDescribesTheFramebufferItNamesWithoutMovingEit
"clears into a driver framebuffer with no attachments";
EXPECT_EQ(MGPipeApplier().FramebufferRecordFor(MGPipeHandle{6, 3})->Width, 300u);
EXPECT_EQ(MGPipeApplier().FramebufferRecordFor(MGPipeHandle{6, 3})->Color[0].Res, (MGPipeHandle{21, 1}));
EXPECT_EQ(MGPipeApplier().FramebufferRecordFor(MGPipeHandle{6, 3})->Target, static_cast<Uint8>(MGPipeFramebufferTarget::Named));
EXPECT_EQ(MGPipeApplier().FramebufferRecordFor(MGPipeHandle{6, 3})->Target,
static_cast<Uint8>(MGPipeFramebufferTarget::Named));
// (b) AND NEITHER BINDING MOVED.
ASSERT_NE(MGPipeApplier().DrawFramebuffer(), nullptr);
@@ -1236,8 +1222,7 @@ TEST(FramebufferEmit, AFramebufferRecordThatNamesNoUsableHandleIsRefusedRatherTh
ApplierGuard guard;
// The positive control first: the DEFAULT framebuffer is slot 0 at generation 1 and is
// perfectly legal, so what follows refuses the null handle and not slot 0.
MGPipeApplySetFramebufferState(
FramebufferRecord(kMGPipeDefaultFramebuffer, MGPipeFramebufferTarget::Both, 128));
MGPipeApplySetFramebufferState(FramebufferRecord(kMGPipeDefaultFramebuffer, MGPipeFramebufferTarget::Both, 128));
ASSERT_NE(MGPipeApplier().FramebufferRecordFor(kMGPipeDefaultFramebuffer), nullptr);
EXPECT_EQ(MGPipeApplier().FramebufferRecordFor(kMGPipeDefaultFramebuffer)->Width, 128u);
const Uint64 serialBefore = MGPipeApplier().FramebufferSerial;
@@ -1247,20 +1232,18 @@ TEST(FramebufferEmit, AFramebufferRecordThatNamesNoUsableHandleIsRefusedRatherTh
"framebuffer handle",
[&nullHandle]() { MGPipeApplySetFramebufferState(nullHandle); });
MGPFramebufferState pastTheBound = FramebufferRecord(
MGPipeHandle{kMGPipeMaxFramebufferSlots, 1}, MGPipeFramebufferTarget::Draw, 400);
MGPFramebufferState pastTheBound =
FramebufferRecord(MGPipeHandle{kMGPipeMaxFramebufferSlots, 1}, MGPipeFramebufferTarget::Draw, 400);
ExpectRefusedNaming("set_framebuffer_state {slot=65536, gen=1, target=0}: the framebuffer slot is "
"outside the record table's bound",
[&pastTheBound]() { MGPipeApplySetFramebufferState(pastTheBound); });
static_assert(kMGPipeMaxFramebufferSlots == 65536u,
"the refusal line above names the bound; move both together");
static_assert(kMGPipeMaxFramebufferSlots == 65536u, "the refusal line above names the bound; move both together");
EXPECT_EQ(MGPipeApplier().FramebufferSerial, serialBefore) << "a refused record moved the serial";
ASSERT_NE(MGPipeApplier().DrawFramebuffer(), nullptr);
EXPECT_EQ(MGPipeApplier().DrawFramebuffer()->Fbo, kMGPipeDefaultFramebuffer)
<< "a refused record took the draw binding";
EXPECT_LT(MGPipeApplier().FramebufferRecords.size(),
static_cast<SizeT>(kMGPipeMaxFramebufferSlots))
EXPECT_LT(MGPipeApplier().FramebufferRecords.size(), static_cast<SizeT>(kMGPipeMaxFramebufferSlots))
<< "an out-of-range slot resized the table instead of being refused";
}
+16 -15
View File
@@ -140,7 +140,9 @@ namespace {
return result;
}
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
Bool DiedOfAbort(const ChildResult& r) {
return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT;
}
std::string DescribeStatus(const ChildResult& r) {
if (r.Status < 0) return "fork/waitpid failed";
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
@@ -324,7 +326,6 @@ TEST(ImageEmit, AMakeCurrentClearsTheImageSetAndAdvancesItsSerial) {
EXPECT_GT(MGPipeApplier().ShaderImagesSerial, serialBefore);
}
namespace {
namespace GL = MobileGL::MG_Impl::GLImpl;
using GLContext = MG_State::GLState::GLContext;
@@ -343,8 +344,12 @@ namespace {
}
};
GLContext& Ctx() { return *MG_State::pGLContext; }
MGPipeImageEmitter& Emitter() { return MGPipeImageEmitterInstance(); }
GLContext& Ctx() {
return *MG_State::pGLContext;
}
MGPipeImageEmitter& Emitter() {
return MGPipeImageEmitterInstance();
}
GLuint MakeComputeProgram(const char* source) {
const GLuint shader = GL::CreateShader(GL_COMPUTE_SHADER);
@@ -425,8 +430,7 @@ void main() { imageStore(img, ivec2(0), vec4(1.0)); }
const auto& resolution = MGPipeProgramOpaqueUnitsShared().For(object.get());
ASSERT_EQ(resolution.MaxImageUnit, 1)
<< "maxUniformLocation=" << object->GetMaxUniformLocation()
<< " unit@0=" << object->GetUniformSamplerOrImageUnitIndex(0)
<< " linked=" << object->GetLinkStatus();
<< " unit@0=" << object->GetUniformSamplerOrImageUnitIndex(0) << " linked=" << object->GetLinkStatus();
// ASSERTED ON THE COUNTER, NOT ON THIS CALL'S RETURN VALUE, and the reason is worth
// writing down because it surprised this suite: the glBindImageTexture above ALREADY
@@ -518,9 +522,8 @@ void main() { imageStore(img, ivec2(0), vec4(1.0)); }
ASSERT_GE(Emitter().ImageSetCount(), 1u);
ASSERT_GE(Emitter().LastShaderImages().Count, 2u);
const MGPImageView& view = Emitter().LastImageViews()[1];
EXPECT_EQ(view.Access, c.encoded)
<< "glBindImageTexture(access=0x" << std::hex << static_cast<Uint>(c.gl) << std::dec
<< ") did not travel as the shared constant";
EXPECT_EQ(view.Access, c.encoded) << "glBindImageTexture(access=0x" << std::hex << static_cast<Uint>(c.gl)
<< std::dec << ") did not travel as the shared constant";
ASSERT_TRUE(MGPipeImageAccessIsValid(view.Access));
EXPECT_EQ(MGPipeDecodeImageAccess(view.Access), c.decoded)
<< "the server's decode does not invert the client's encode";
@@ -632,8 +635,7 @@ void main() { imageStore(img, ivec2(0, 0), vec4(1.0)); }
GL::BindImageTexture(1, name, 0, GL_FALSE, 0, GL_READ_WRITE, GL_RGBA8);
Emitter().EmitShaderImages(Ctx());
EXPECT_EQ(Emitter().LastImageViews()[1].Level, 0u)
<< "the base level is base-complete and must stay bound";
EXPECT_EQ(Emitter().LastImageViews()[1].Level, 0u) << "the base level is base-complete and must stay bound";
GL::UseProgram(0);
GL::BindImageTexture(1, 0, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA8);
}
@@ -662,8 +664,8 @@ void main() { imageStore(img, ivec2(0, 0), vec4(1.0)); }
// And the bind is checked before the mark is, so a REFUSED bind says so rather than
// reading as a missing NoteImageUnitTouched.
ASSERT_TRUE(Ctx().GetImageTextureBinding(kUnit).Texture != nullptr)
<< "glBindImageTexture did not take: this lane's backend advertises fewer than "
<< (kUnit + 1) << " image units, so the case cannot observe the mark at all";
<< "glBindImageTexture did not take: this lane's backend advertises fewer than " << (kUnit + 1)
<< " image units, so the case cannot observe the mark at all";
EXPECT_GE(Ctx().GetMaxTouchedImageUnit(), kUnit)
<< "glBindImageTexture did not move the image-unit high-water mark, so every reader "
"that bounds a per-draw walk with it now walks past this binding";
@@ -692,8 +694,7 @@ int main(int argc, char** argv) {
// raised by the encoder on THIS thread - the client role. So g_logPath, which is the read
// path from here on, becomes the client-derived name; the env keeps the base. The rule is
// the library's own, not a copy.
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(), MobileGL::MG_Util::Debug::LogRole::Client);
MobileGL::Initialize();
::testing::InitGoogleTest(&argc, argv);
const int rc = RUN_ALL_TESTS();
@@ -18,49 +18,49 @@
#include <vector>
namespace {
using MobileGL::MG_Backend::DirectVulkan::CollectSubmitFencePrefix;
using MobileGL::MG_Backend::DirectVulkan::CollectSubmitFencePrefix;
struct Submit {
std::uint64_t submitIndex;
std::uint64_t frameSerial;
int fence;
};
struct Submit {
std::uint64_t submitIndex;
std::uint64_t frameSerial;
int fence;
};
bool SerialComplete(std::uint64_t serial, const std::vector<Submit>& pending) {
return std::none_of(pending.begin(), pending.end(), [serial](const Submit& submit) {
return submit.frameSerial == serial;
});
}
bool SerialComplete(std::uint64_t serial, const std::vector<Submit>& pending) {
return std::none_of(pending.begin(), pending.end(),
[serial](const Submit& submit) { return submit.frameSerial == serial; });
}
TEST(MagmaAggregateWaitTest, MissingTargetAfterAnEarlierPrefixIsRejected) {
const std::vector<Submit> gap{{10, 42, 101}, {12, 43, 103}};
std::vector<int> fences;
TEST(MagmaAggregateWaitTest, MissingTargetAfterAnEarlierPrefixIsRejected) {
const std::vector<Submit> gap{{10, 42, 101}, {12, 43, 103}};
std::vector<int> fences;
EXPECT_FALSE(CollectSubmitFencePrefix(gap, 11, 0, fences));
EXPECT_TRUE(fences.empty());
}
EXPECT_FALSE(CollectSubmitFencePrefix(gap, 11, 0, fences));
EXPECT_TRUE(fences.empty());
}
TEST(MagmaAggregateWaitTest, SingleFenceControlLeavesTheTargetFrameInFlight) {
const std::vector<Submit> pending{{10, 42, 101}, {11, 42, 102}, {12, 43, 103}};
TEST(MagmaAggregateWaitTest, SingleFenceControlLeavesTheTargetFrameInFlight) {
const std::vector<Submit> pending{{10, 42, 101}, {11, 42, 102}, {12, 43, 103}};
// The old control waits only the first matching fence. The second submit still carries 42.
auto singleFenceControl = pending;
singleFenceControl.erase(singleFenceControl.begin());
EXPECT_FALSE(SerialComplete(42, singleFenceControl));
// The old control waits only the first matching fence. The second submit still carries 42.
auto singleFenceControl = pending;
singleFenceControl.erase(singleFenceControl.begin());
EXPECT_FALSE(SerialComplete(42, singleFenceControl));
// The production selector includes both submissions through index 11, but not frame 43.
std::vector<int> fences;
ASSERT_TRUE(CollectSubmitFencePrefix(pending, 11, 0, fences));
ASSERT_EQ(fences, (std::vector<int>{101, 102}));
// The production selector includes both submissions through index 11, but not frame 43.
std::vector<int> fences;
ASSERT_TRUE(CollectSubmitFencePrefix(pending, 11, 0, fences));
ASSERT_EQ(fences, (std::vector<int>{101, 102}));
auto aggregateWait = pending;
aggregateWait.erase(
std::remove_if(aggregateWait.begin(), aggregateWait.end(), [&fences](const Submit& submit) {
return std::find(fences.begin(), fences.end(), submit.fence) != fences.end();
}),
aggregateWait.end());
EXPECT_TRUE(SerialComplete(42, aggregateWait));
ASSERT_EQ(aggregateWait.size(), 1u);
EXPECT_EQ(aggregateWait.front().frameSerial, 43u);
}
auto aggregateWait = pending;
aggregateWait.erase(std::remove_if(aggregateWait.begin(), aggregateWait.end(),
[&fences](const Submit& submit) {
return std::find(fences.begin(), fences.end(), submit.fence) !=
fences.end();
}),
aggregateWait.end());
EXPECT_TRUE(SerialComplete(42, aggregateWait));
ASSERT_EQ(aggregateWait.size(), 1u);
EXPECT_EQ(aggregateWait.front().frameSerial, 43u);
}
} // namespace
+98 -78
View File
@@ -75,7 +75,7 @@ namespace {
// Every payload named in the catalogue must be a memcpy-able POD, and so must every
// payload the verify comparator knows about.
#define MGP_ASSERT_CALL_PAYLOAD_POD(Name, Payload, Class, Flags, Wait) \
#define MGP_ASSERT_CALL_PAYLOAD_POD(Name, Payload, Class, Flags, Wait) \
static_assert(std::is_trivially_copyable_v<Payload>, #Name "'s payload " #Payload " is not trivially copyable");
MGP_CALL_LIST(MGP_ASSERT_CALL_PAYLOAD_POD)
@@ -87,19 +87,14 @@ namespace {
// of these and MG_Pipe may not reach it (MG_Remote is above this layer), so the table is
// expanded from the catalogue here rather than a name being duplicated per EXPECT.
#define MGP_CATALOGUE_NAME_ROW(Name, Payload, Class, Flags, Wait) #Name,
constexpr const char* kCatalogueOpNames[] = {
"<kInvalid>",
MGP_CALL_LIST(MGP_CATALOGUE_NAME_ROW)
};
constexpr const char* kCatalogueOpNames[] = {"<kInvalid>", MGP_CALL_LIST(MGP_CATALOGUE_NAME_ROW)};
#undef MGP_CATALOGUE_NAME_ROW
static_assert(sizeof(kCatalogueOpNames) / sizeof(kCatalogueOpNames[0]) ==
static_cast<SizeT>(MGPWireOp::kOpCount),
static_assert(sizeof(kCatalogueOpNames) / sizeof(kCatalogueOpNames[0]) == static_cast<SizeT>(MGPWireOp::kOpCount),
"the diagnostic name table and the opcode space disagree");
const char* WireOpNameForDiag(MGPWireOp op) {
const SizeT index = static_cast<SizeT>(op);
return index < static_cast<SizeT>(MGPWireOp::kOpCount) ? kCatalogueOpNames[index]
: "<opcode out of range>";
return index < static_cast<SizeT>(MGPWireOp::kOpCount) ? kCatalogueOpNames[index] : "<opcode out of range>";
}
} // namespace
@@ -130,8 +125,8 @@ TEST(PipeCatalogue, EntryCountMatchesTheDocumentedCount) {
TEST(PipeCatalogue, GeneratedTablesHoldTheWholeCatalogue) {
static_assert(ClassCount<kScreen>() == kMGPipeScreenCallCount);
static_assert(ClassCount<kScreen>() + ClassCount<kCtxCso>() + ClassCount<kCtxState>() +
ClassCount<kCtxObject>() + ClassCount<kCtxVerb>() + ClassCount<kCtxQuery>() ==
static_assert(ClassCount<kScreen>() + ClassCount<kCtxCso>() + ClassCount<kCtxState>() + ClassCount<kCtxObject>() +
ClassCount<kCtxVerb>() + ClassCount<kCtxQuery>() ==
kMGPipeCallCount);
// The tables ARE their function pointers: a struct that is bigger than its call count
// has grown a member no generator knows about.
@@ -228,10 +223,16 @@ TEST(PipeCatalogue, ExactlyTheRoutedRowsAreInstalledAndTheRestAreStillNull) {
MGPipeInstallMonolithTables();
for (SizeT i = 0; i < kMGPipeScreenCallCount; ++i) {
if (screen[i] != nullptr) ++installed; else ++nulls;
if (screen[i] != nullptr)
++installed;
else
++nulls;
}
for (SizeT i = 0; i < kMGPipeContextCallCount; ++i) {
if (context[i] != nullptr) ++installed; else ++nulls;
if (context[i] != nullptr)
++installed;
else
++nulls;
}
EXPECT_EQ(installed + nulls, static_cast<SizeT>(kMGPipeCallCount));
@@ -407,8 +408,7 @@ TEST(PipeCatalogue, EveryTextureTargetMapsToItsOwnResourceTarget) {
const auto target = static_cast<TextureTarget>(i);
EXPECT_NE(MGPipeResourceTargetForTextureTarget(target), kMGPipeResourceTargetUnmapped)
<< "TextureTarget " << i << " has no MGPResourceDesc::Target row";
EXPECT_LT(MGPipeResourceTargetForTextureTarget(target),
static_cast<Uint32>(MGPipeResourceTarget::Count));
EXPECT_LT(MGPipeResourceTargetForTextureTarget(target), static_cast<Uint32>(MGPipeResourceTarget::Count));
}
// Buffer is 0 and stays 0: P3a's constant is what a zero-initialised record already says,
// and the narrowed ack predicate below compares against it.
@@ -451,8 +451,7 @@ TEST(PipeCatalogue, SubDataTargetPacksAResourceTargetAndAnUploadTarget) {
static_cast<Uint32>(TextureUploadTarget::CubeMapNegativeZ),
static_cast<Uint32>(TextureUploadTarget::TextureUploadTargetCount) - 1u,
};
for (Uint32 resource = 0; resource < static_cast<Uint32>(MGPipeResourceTarget::Count);
++resource) {
for (Uint32 resource = 0; resource < static_cast<Uint32>(MGPipeResourceTarget::Count); ++resource) {
for (const Uint32 upload : uploadTargets) {
const Uint16 packed = MGPipePackSubDataTarget(resource, upload);
EXPECT_EQ(MGPipeSubDataResourceTargetOf(packed), static_cast<Uint8>(resource))
@@ -465,11 +464,9 @@ TEST(PipeCatalogue, SubDataTargetPacksAResourceTargetAndAnUploadTarget) {
// THE BUFFER INVARIANT, at compile time in MGPipeTypes.h and again here so a failure names
// itself: a buffer record's Target is exactly kMGPipeResourceTargetBuffer, whole field,
// upload byte and all, so P3a's records are unchanged on the wire.
static_assert(MGPipePackSubDataTarget(kMGPipeResourceTargetBuffer, 0u) ==
kMGPipeResourceTargetBuffer);
static_assert(MGPipePackSubDataTarget(kMGPipeResourceTargetBuffer, 0u) == kMGPipeResourceTargetBuffer);
EXPECT_EQ(MGPipePackSubDataTarget(kMGPipeResourceTargetBuffer, 0u), kMGPipeResourceTargetBuffer);
EXPECT_EQ(MGPipePackSubDataTarget(kMGPipeResourceTargetBuffer,
static_cast<Uint32>(TextureUploadTarget::Texture1D)),
EXPECT_EQ(MGPipePackSubDataTarget(kMGPipeResourceTargetBuffer, static_cast<Uint32>(TextureUploadTarget::Texture1D)),
kMGPipeResourceTargetBuffer);
MGPSubData zeroed{};
EXPECT_EQ(zeroed.Target, kMGPipeResourceTargetBuffer);
@@ -477,8 +474,7 @@ TEST(PipeCatalogue, SubDataTargetPacksAResourceTargetAndAnUploadTarget) {
// ...and the other side of it: a 1D texture's upload target IS 0, and packed it still
// cannot be mistaken for a buffer, because no texture's resource target is 0.
EXPECT_EQ(static_cast<Uint32>(TextureUploadTarget::Texture1D), 0u);
for (Uint32 resource = 1; resource < static_cast<Uint32>(MGPipeResourceTarget::Count);
++resource) {
for (Uint32 resource = 1; resource < static_cast<Uint32>(MGPipeResourceTarget::Count); ++resource) {
EXPECT_NE(MGPipePackSubDataTarget(resource, 0u), kMGPipeResourceTargetBuffer)
<< "resource target " << resource << " collides with a buffer record";
}
@@ -488,13 +484,10 @@ TEST(PipeCatalogue, SubDataTargetPacksAResourceTargetAndAnUploadTarget) {
// What a real cube-face record reads back as, through the field rather than a local.
MGPSubData record{};
record.Target =
MGPipePackSubDataTarget(MGPipeResourceTargetForTextureTarget(TextureTarget::TextureCubeMap),
static_cast<Uint32>(TextureUploadTarget::CubeMapNegativeY));
EXPECT_EQ(MGPipeSubDataResourceTargetOf(record.Target),
static_cast<Uint8>(MGPipeResourceTarget::TexCube));
EXPECT_EQ(MGPipeSubDataUploadTargetOf(record.Target),
static_cast<Uint8>(TextureUploadTarget::CubeMapNegativeY));
record.Target = MGPipePackSubDataTarget(MGPipeResourceTargetForTextureTarget(TextureTarget::TextureCubeMap),
static_cast<Uint32>(TextureUploadTarget::CubeMapNegativeY));
EXPECT_EQ(MGPipeSubDataResourceTargetOf(record.Target), static_cast<Uint8>(MGPipeResourceTarget::TexCube));
EXPECT_EQ(MGPipeSubDataUploadTargetOf(record.Target), static_cast<Uint8>(TextureUploadTarget::CubeMapNegativeY));
// Six faces share one resource target: the high byte is the only thing that tells them
// apart, which is why it cannot be dropped.
EXPECT_EQ(MGPipeSubDataResourceTargetOf(
@@ -640,8 +633,7 @@ TEST(PipeCatalogue, LateArrivalsAreAppendedWithoutRenumbering) {
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::ReadPixelsToBuffer), static_cast<Uint32>(kNone));
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::GetTextureImageToBuffer), static_cast<Uint32>(kNone));
EXPECT_EQ(sizeof(MGPReadbackToBuffer), 104u);
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::SetProgramBindings),
static_cast<Uint32>(kVarTail | kHostSpan));
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::SetProgramBindings), static_cast<Uint32>(kVarTail | kHostSpan));
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::ApplierReset), static_cast<Uint32>(kNone));
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::ObjectDeath), static_cast<Uint32>(kNone));
EXPECT_EQ(MGPipeCallFlagsFor(MGPWireOp::SetContextValues), static_cast<Uint32>(kNone));
@@ -723,9 +715,8 @@ TEST(PipeCatalogue, LateArrivalsAreAppendedWithoutRenumbering) {
// P5e's draw flag: the next free bit, and disjoint from all five before it.
EXPECT_EQ(static_cast<Uint32>(kDrawClientArrays), 1u << 6);
EXPECT_EQ(static_cast<Uint32>(kDrawClientArrays) &
static_cast<Uint32>(kDrawHasUserIndices | kDrawPrimitiveRestart |
kDrawIndicesAreClient | kDrawHasIndexRange |
kDrawHasXfbCount | kDrawIsIndirect),
static_cast<Uint32>(kDrawHasUserIndices | kDrawPrimitiveRestart | kDrawIndicesAreClient |
kDrawHasIndexRange | kDrawHasXfbCount | kDrawIsIndirect),
0u);
// ... and it still fits the one byte MGPDrawInfo::Flags is, which is why the record did not
// grow: MGPDrawInfo stays 56 bytes.
@@ -757,16 +748,15 @@ TEST(PipeCatalogue, EveryRowCarriesTheWaitClassTheContractGivesIt) {
// kWaitReply: every row whose answer is not derivable (R-5). Named, all fourteen, because
// the flag-to-class agreement is what keeps a waiter from hanging on a slot nobody posts.
const MGPWireOp replyRows[] = {
MGPWireOp::GetCaps, MGPWireOp::ResourceCreate, MGPWireOp::ResourceRespecify,
MGPWireOp::MapPersistent, MGPWireOp::FenceStatus, MGPWireOp::FenceWait,
MGPWireOp::QueryAvailable, MGPWireOp::QueryResult, MGPWireOp::QueryTimestamp,
MGPWireOp::GetCaps, MGPWireOp::ResourceCreate, MGPWireOp::ResourceRespecify,
MGPWireOp::MapPersistent, MGPWireOp::FenceStatus, MGPWireOp::FenceWait,
MGPWireOp::QueryAvailable, MGPWireOp::QueryResult, MGPWireOp::QueryTimestamp,
MGPWireOp::SetTextureParams, MGPWireOp::ResourceSubData, MGPWireOp::ResourceReadback,
MGPWireOp::GetTextureImage, MGPWireOp::ReadPixels,
MGPWireOp::GetTextureImage, MGPWireOp::ReadPixels,
};
for (const MGPWireOp op : replyRows) {
EXPECT_EQ(MGPipeWaitClassFor(op), kWaitReply) << WireOpNameForDiag(op);
EXPECT_NE(MGPipeCallFlagsFor(op) & static_cast<Uint32>(kReplySlot), 0u)
<< WireOpNameForDiag(op);
EXPECT_NE(MGPipeCallFlagsFor(op) & static_cast<Uint32>(kReplySlot), 0u) << WireOpNameForDiag(op);
}
// kWaitApplied: only applier_reset is left. P15 (user decision: everything fire-and-forget
@@ -788,22 +778,46 @@ TEST(PipeCatalogue, EveryRowCarriesTheWaitClassTheContractGivesIt) {
// the rows the phase exists for, and then counted for the rest, so a new row cannot join
// the set unnoticed.
const MGPWireOp noneRows[] = {
MGPWireOp::DrawVbo, MGPWireOp::LaunchGrid, MGPWireOp::Clear,
MGPWireOp::Blit, MGPWireOp::MemoryBarrier, MGPWireOp::Flush,
MGPWireOp::SetSwapInterval, MGPWireOp::BindShaderImage, MGPWireOp::PatchParameter,
MGPWireOp::ObjectDeath, MGPWireOp::ResourceDestroy, MGPWireOp::UnmapPersistent,
MGPWireOp::FenceCreate, MGPWireOp::FenceDestroy, MGPWireOp::FenceWaitServer,
MGPWireOp::QueryCreate, MGPWireOp::QueryBegin, MGPWireOp::QueryEnd,
MGPWireOp::QueryDestroy, MGPWireOp::QueryCounter, MGPWireOp::SetContextValues,
MGPWireOp::SetProgramBindings, MGPWireOp::SetShaderBuffers,
MGPWireOp::SetVertexBuffers, MGPWireOp::SetFramebufferState,
MGPWireOp::CreateShaderState, MGPWireOp::SetDrawProgram,
MGPWireOp::DrawVbo,
MGPWireOp::LaunchGrid,
MGPWireOp::Clear,
MGPWireOp::Blit,
MGPWireOp::MemoryBarrier,
MGPWireOp::Flush,
MGPWireOp::SetSwapInterval,
MGPWireOp::BindShaderImage,
MGPWireOp::PatchParameter,
MGPWireOp::ObjectDeath,
MGPWireOp::ResourceDestroy,
MGPWireOp::UnmapPersistent,
MGPWireOp::FenceCreate,
MGPWireOp::FenceDestroy,
MGPWireOp::FenceWaitServer,
MGPWireOp::QueryCreate,
MGPWireOp::QueryBegin,
MGPWireOp::QueryEnd,
MGPWireOp::QueryDestroy,
MGPWireOp::QueryCounter,
MGPWireOp::SetContextValues,
MGPWireOp::SetProgramBindings,
MGPWireOp::SetShaderBuffers,
MGPWireOp::SetVertexBuffers,
MGPWireOp::SetFramebufferState,
MGPWireOp::CreateShaderState,
MGPWireOp::SetDrawProgram,
// P9: the pack-buffer readbacks - the point of the two rows is that nothing waits.
MGPWireOp::ReadPixelsToBuffer, MGPWireOp::GetTextureImageToBuffer,
MGPWireOp::ReadPixelsToBuffer,
MGPWireOp::GetTextureImageToBuffer,
// P15: fire-and-forget.
MGPWireOp::GenerateMipmap, MGPWireOp::ResourceCopyRegion, MGPWireOp::CopyFramebufferToTexture,
MGPWireOp::SetStorageBlockBinding, MGPWireOp::BeginStreamOutput, MGPWireOp::EndStreamOutput,
MGPWireOp::PauseStreamOutput, MGPWireOp::ResumeStreamOutput, MGPWireOp::BindStreamOutput,
MGPWireOp::GenerateMipmap,
MGPWireOp::ResourceCopyRegion,
MGPWireOp::CopyFramebufferToTexture,
MGPWireOp::SetStorageBlockBinding,
MGPWireOp::BeginStreamOutput,
MGPWireOp::EndStreamOutput,
MGPWireOp::PauseStreamOutput,
MGPWireOp::ResumeStreamOutput,
MGPWireOp::BindStreamOutput,
};
for (const MGPWireOp op : noneRows) {
EXPECT_EQ(MGPipeWaitClassFor(op), kWaitNone) << WireOpNameForDiag(op);
@@ -817,11 +831,21 @@ TEST(PipeCatalogue, EveryRowCarriesTheWaitClassTheContractGivesIt) {
SizeT reply = 0, applied = 0, present = 0, none = 0, other = 0;
for (SizeT i = 1; i < static_cast<SizeT>(MGPWireOp::kOpCount); ++i) {
switch (MGPipeWaitClassFor(static_cast<MGPWireOp>(i))) {
case kWaitReply: ++reply; break;
case kWaitApplied: ++applied; break;
case kWaitPresent: ++present; break;
case kWaitNone: ++none; break;
default: ++other; break;
case kWaitReply:
++reply;
break;
case kWaitApplied:
++applied;
break;
case kWaitPresent:
++present;
break;
case kWaitNone:
++none;
break;
default:
++other;
break;
}
}
EXPECT_EQ(reply, 15u);
@@ -888,9 +912,8 @@ TEST(PipeCatalogue, VerifyComparatorNamesTheDifferingField) {
TEST(PipeCatalogue, CoverageAccountsForEveryInventoryRow) {
EXPECT_EQ(kMGPipeInventoryReadPoints, 477u);
EXPECT_EQ(kMGPipeInventoryUnmapped, 0u);
EXPECT_EQ(kMGPipeInventoryMappedToCall + kMGPipeInventoryClientResolved +
kMGPipeInventoryReverseChannel + kMGPipeInventoryStructuralHandle +
kMGPipeInventoryUnmapped,
EXPECT_EQ(kMGPipeInventoryMappedToCall + kMGPipeInventoryClientResolved + kMGPipeInventoryReverseChannel +
kMGPipeInventoryStructuralHandle + kMGPipeInventoryUnmapped,
kMGPipeInventoryReadPoints);
EXPECT_GT(kMGPipeCoverageEntryCount, 0u);
}
@@ -947,9 +970,9 @@ TEST(PipeCatalogue, VerbTableIsTheFunctionTable) {
// The sticky set is exactly the seven forwarded, argument-keyed accessors (P1 brief D6); no
// version or generation accessor is among them.
TEST(PipeCatalogue, StickyFieldsAreExactlyTheSeven) {
const char* const expected[] = {"GetBufferBindingPointCount", "GetProgramObject", "GetTextureObject",
"HasOpenTransformFeedbackSpan", "InvalidateCompileEnv", "ValidateProgramName",
"RecordError"};
const char* const expected[] = {
"GetBufferBindingPointCount", "GetProgramObject", "GetTextureObject", "HasOpenTransformFeedbackSpan",
"InvalidateCompileEnv", "ValidateProgramName", "RecordError"};
SizeT count = 0;
for (SizeT f = 0; f < kMGPipeInputFieldCount; ++f) {
Bool listed = false;
@@ -1104,8 +1127,7 @@ TEST(PipeCatalogue, PipelineSubsetMembersArePinned) {
// and its two combiner ops.
EXPECT_EQ(kMGPipePipelineStateMemberCount, 47u);
EXPECT_STREQ(kMGPipePipelineStateMembers[0], "PatchVertices");
EXPECT_STREQ(kMGPipePipelineStateMembers[kMGPipePipelineStateMemberCount - 1],
"ScissorTestEnabledMask");
EXPECT_STREQ(kMGPipePipelineStateMembers[kMGPipePipelineStateMemberCount - 1], "ScissorTestEnabledMask");
}
// The reverse channel is exactly SEVEN callbacks: plan B's section 7.1 wrote ten, and the tenth
@@ -1163,7 +1185,7 @@ TEST(PipeCatalogue, BufferRangeCarriesNoInlineHostSpan) {
// The call still declares the span it may carry, so the transport lays the tail out.
Uint32 flags = 0;
#define MGP_FLAGS_OF_SET_SHADER_BUFFERS(Name, Payload, Class, Flags, Wait) \
#define MGP_FLAGS_OF_SET_SHADER_BUFFERS(Name, Payload, Class, Flags, Wait) \
if (std::strcmp(#Name, "SetShaderBuffers") == 0) flags = static_cast<Uint32>(Flags);
MGP_CALL_LIST(MGP_FLAGS_OF_SET_SHADER_BUFFERS)
#undef MGP_FLAGS_OF_SET_SHADER_BUFFERS
@@ -1301,7 +1323,7 @@ TEST(PipeCatalogue, VertexWireViewsAreFlatAndCarryIsLongSeparately) {
// inherits this pin rather than the guess.
TEST(PipeCatalogue, ResourceRespecifyAcksOnlyImmutableStorage) {
Uint32 flags = 0;
#define MGP_FLAGS_OF_RESOURCE_RESPECIFY(Name, Payload, Class, Flags, Wait) \
#define MGP_FLAGS_OF_RESOURCE_RESPECIFY(Name, Payload, Class, Flags, Wait) \
if (std::strcmp(#Name, "ResourceRespecify") == 0) flags = static_cast<Uint32>(Flags);
MGP_CALL_LIST(MGP_FLAGS_OF_RESOURCE_RESPECIFY)
#undef MGP_FLAGS_OF_RESOURCE_RESPECIFY
@@ -1309,7 +1331,7 @@ TEST(PipeCatalogue, ResourceRespecifyAcksOnlyImmutableStorage) {
// And it is the ONLY call that carries it: a second one would be a second decision, and
// this predicate answers for exactly one call.
Uint32 ackingCalls = 0;
#define MGP_COUNT_ACKING_CALLS(Name, Payload, Class, Flags, Wait) \
#define MGP_COUNT_ACKING_CALLS(Name, Payload, Class, Flags, Wait) \
if ((static_cast<Uint32>(Flags) & static_cast<Uint32>(kNeedsAck)) != 0) ++ackingCalls;
MGP_CALL_LIST(MGP_COUNT_ACKING_CALLS)
#undef MGP_COUNT_ACKING_CALLS
@@ -1325,7 +1347,7 @@ TEST(PipeCatalogue, ResourceRespecifyAcksOnlyImmutableStorage) {
// carried no flag because in monolith that answer is a direct call's return value. FIFTEEN since
// shared_image, whose every operation is answered.
Uint32 replySlotCalls = 0;
#define MGP_COUNT_REPLY_SLOT_CALLS(Name, Payload, Class, Flags, Wait) \
#define MGP_COUNT_REPLY_SLOT_CALLS(Name, Payload, Class, Flags, Wait) \
if ((static_cast<Uint32>(Flags) & static_cast<Uint32>(kReplySlot)) != 0) ++replySlotCalls;
MGP_CALL_LIST(MGP_COUNT_REPLY_SLOT_CALLS)
#undef MGP_COUNT_REPLY_SLOT_CALLS
@@ -1336,8 +1358,8 @@ TEST(PipeCatalogue, ResourceRespecifyAcksOnlyImmutableStorage) {
// (ResourceCreate, ResourceRespecify, ResourceSubData, SetTextureParams in PipeApply.h);
// map_persistent's void* is the fifth answer and was already declared.
Uint32 acceptanceWithSlot = 0;
#define MGP_COUNT_ACCEPTANCE_ROWS(Name, Payload, Class, Flags, Wait) \
if ((std::strcmp(#Name, "ResourceCreate") == 0 || std::strcmp(#Name, "ResourceRespecify") == 0 || \
#define MGP_COUNT_ACCEPTANCE_ROWS(Name, Payload, Class, Flags, Wait) \
if ((std::strcmp(#Name, "ResourceCreate") == 0 || std::strcmp(#Name, "ResourceRespecify") == 0 || \
std::strcmp(#Name, "ResourceSubData") == 0 || std::strcmp(#Name, "SetTextureParams") == 0) && \
(static_cast<Uint32>(Flags) & static_cast<Uint32>(kReplySlot)) != 0) { \
++acceptanceWithSlot; \
@@ -1374,8 +1396,7 @@ TEST(PipeCatalogue, ResourceRespecifyAcksOnlyImmutableStorage) {
// stopped naming the buffer target would turn these two green-and-wrong.
MGPResourceDesc immutableTexture{};
immutableTexture.Immutable = 1; // glTexStorage2D
immutableTexture.Target =
static_cast<Uint8>(MGPipeResourceTargetForTextureTarget(TextureTarget::Texture2D));
immutableTexture.Target = static_cast<Uint8>(MGPipeResourceTargetForTextureTarget(TextureTarget::Texture2D));
immutableTexture.Width = 256;
immutableTexture.Height = 256;
immutableTexture.Levels = 9;
@@ -1411,8 +1432,7 @@ TEST(PipeCatalogue, ResourceRespecifyAcksOnlyImmutableStorage) {
// of the line: glBufferData(size, NULL) at an unchanged size is an orphaning
// reallocation, so a record that moves only it must still clear, and must never be read
// as a mask change.
EXPECT_NE(offsetof(MGPResourceDesc, HasDefinedContent),
offsetof(MGPResourceDesc, ImageBindableHint));
EXPECT_NE(offsetof(MGPResourceDesc, HasDefinedContent), offsetof(MGPResourceDesc, ImageBindableHint));
}
// G13b, D-M: "emulation 在 split 下显式 Fatal 直到 P8" costs P4a a NAMED, GREPPABLE call site
+26 -18
View File
@@ -85,16 +85,19 @@ namespace {
};
#if MOBILEGL_PIPE_POISON
Bool Fresh(MGPipeInputField field) { return MGPipeInputFieldIsFresh(gPipeInputs->FilledState(), field); }
Bool Fresh(MGPipeInputField field) {
return MGPipeInputFieldIsFresh(gPipeInputs->FilledState(), field);
}
#endif
[[maybe_unused]] constexpr const char* kOmittedFatal ="Fatal{UnmigratedPipeInput, \"GetActiveTextureUnit@GenerateMipmap\"}";
[[maybe_unused]] constexpr const char* kOmittedFatal =
"Fatal{UnmigratedPipeInput, \"GetActiveTextureUnit@GenerateMipmap\"}";
[[maybe_unused]] constexpr const char* kOmissionKnob = "GenerateMipmap:GetActiveTextureUnit";
#if MGTEST_HAVE_FORK
struct ChildResult {
int Status = -1; // waitpid's status; -1 when fork or waitpid failed
std::string Log; // the lines the child appended to the log file
int Status = -1; // waitpid's status; -1 when fork or waitpid failed
std::string Log; // the lines the child appended to the log file
};
// Runs `body` in a forked child and returns its wait status and log delta. The child
@@ -118,8 +121,12 @@ namespace {
return result;
}
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
Bool ExitedWith(const ChildResult& r, int code) { return WIFEXITED(r.Status) && WEXITSTATUS(r.Status) == code; }
Bool DiedOfAbort(const ChildResult& r) {
return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT;
}
Bool ExitedWith(const ChildResult& r, int code) {
return WIFEXITED(r.Status) && WEXITSTATUS(r.Status) == code;
}
std::string DescribeStatus(const ChildResult& r) {
if (r.Status < 0) return "fork/waitpid failed";
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
@@ -129,7 +136,6 @@ namespace {
#endif // MGTEST_HAVE_FORK
} // namespace
// Negative control B, layer 1 (P1 brief D6 / G5): the omitted (verb, field) pair is the
// ONLY thing that goes stale - every other bit of the verb class's mask is fresh, every
// field outside it is not, and the verb after it neither heals the field (not in kDraw's
@@ -190,7 +196,7 @@ TEST_F(PipeInputsTest, ReadingAnOmittedFieldAbortsNamingTheVerb) {
MGPipeValidateForVerb(MGPipeVerb::GenerateMipmap);
(void)gPipeInputs->GetTextureUnitObject(0); // the sibling field: filled, must not abort
(void)gPipeInputs->GetActiveTextureUnit(); // the omitted field: Fatal
::_exit(3); // reached only if the poison failed
::_exit(3); // reached only if the poison failed
});
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_NE(r.Log.find(kOmittedFatal), std::string::npos) << r.Log;
@@ -357,8 +363,8 @@ TEST_F(PipeInputsTest, MutatedFieldIsNamedAtRead) {
EXPECT_NE(r.Log.find("MGPipe: verify read of GetLineWidth (index 0, 0) differs from the live context"),
std::string::npos)
<< r.Log;
const std::string expected = "Fatal{PipeVerifyDiffer, \"GetLineWidth@DrawArrays\", verb=" + std::to_string(serial) +
", where=read}";
const std::string expected =
"Fatal{PipeVerifyDiffer, \"GetLineWidth@DrawArrays\", verb=" + std::to_string(serial) + ", where=read}";
EXPECT_NE(r.Log.find(expected), std::string::npos) << "expected " << expected << " in\n" << r.Log;
EXPECT_EQ(r.Log.find("where=entry"), std::string::npos) << r.Log;
#endif
@@ -385,8 +391,9 @@ TEST_F(PipeInputsTest, VerifyCorruptKnobNamesTheFieldAtEntry) {
ASSERT_TRUE(DiedOfAbort(r)) << DescribeStatus(r) << "\n" << r.Log;
EXPECT_NE(r.Log.find("MGPipe: verify armed - 63 fields, 69 verbs, fatal=1"), std::string::npos) << r.Log;
EXPECT_NE(r.Log.find("MGPipe: verify corruption armed - GetRenderStateParameters"), std::string::npos) << r.Log;
const std::string expected = "Fatal{PipeVerifyDiffer, \"GetRenderStateParameters@DrawArrays\", verb=" +
std::to_string(serial) + ", where=entry}";
const std::string expected =
"Fatal{PipeVerifyDiffer, \"GetRenderStateParameters@DrawArrays\", verb=" + std::to_string(serial) +
", where=entry}";
EXPECT_NE(r.Log.find(expected), std::string::npos) << "expected " << expected << " in\n" << r.Log;
#endif
}
@@ -442,10 +449,12 @@ TEST_F(PipeInputsTest, VerifyFatalOffLogsTheDivergenceAndContinues) {
EXPECT_NE(r.Log.find("MGPipe: verify summary - 2 divergence(s) survived MOBILEGL_PIPE_VERIFY_FATAL=0"),
std::string::npos)
<< r.Log;
const std::string first = "Fatal{PipeVerifyDiffer, \"GetRenderStateParameters@DrawArrays\", verb=" +
std::to_string(serial) + ", where=entry}";
const std::string second = "Fatal{PipeVerifyDiffer, \"GetRenderStateParameters@DrawElements\", verb=" +
std::to_string(serial + 1) + ", where=entry}";
const std::string first =
"Fatal{PipeVerifyDiffer, \"GetRenderStateParameters@DrawArrays\", verb=" + std::to_string(serial) +
", where=entry}";
const std::string second =
"Fatal{PipeVerifyDiffer, \"GetRenderStateParameters@DrawElements\", verb=" + std::to_string(serial + 1) +
", where=entry}";
EXPECT_NE(r.Log.find(first), std::string::npos) << "expected " << first << " in\n" << r.Log;
EXPECT_NE(r.Log.find(second), std::string::npos) << "expected " << second << " in\n" << r.Log;
#endif
@@ -490,7 +499,7 @@ TEST_F(PipeInputsTest, AFrontendMutationInsideAVerbRefreshesThePushedField) {
const Uint64 samplingBefore = ctx.GetSamplingResolutionGeneration();
auto sampler = MakeShared<MG_State::GLState::SamplerObject>(0u);
sampler->SetMinFilter(sampler->GetMinFilter() == SamplerFilterMode::Nearest ? SamplerFilterMode::Linear
: SamplerFilterMode::Nearest);
: SamplerFilterMode::Nearest);
ASSERT_NE(ctx.GetSamplingResolutionGeneration(), samplingBefore) << "the mutation did not move the counter";
EXPECT_EQ(gPipeInputs->GetSamplingResolutionGeneration(), ctx.GetSamplingResolutionGeneration());
@@ -568,7 +577,6 @@ TEST_F(PipeInputsTest, AFrontendMutationInsideAVerbDoesNotDivergeAtRead) {
#endif
}
int main(int argc, char** argv) {
// Before anything logs: MG_Util::Debug::InitFile() reads the variable once, on the first
// write, and caches the FILE*. The name carries this process's pid (see the file header),
+30 -32
View File
@@ -150,7 +150,9 @@ namespace {
return result;
}
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
Bool DiedOfAbort(const ChildResult& r) {
return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT;
}
std::string DescribeStatus(const ChildResult& r) {
if (r.Status < 0) return "fork/waitpid failed";
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
@@ -190,8 +192,7 @@ namespace {
// See FramebufferEmitTest's twin for why this is a shape pin rather than a placeholder.
TEST(ProgramEmit, TheEmitterIsOneNeverDestroyedProcessSingleton) {
EXPECT_EQ(&MGPipeProgramEmitterInstance(), &MGPipeProgramEmitterInstance());
EXPECT_TRUE(kMGPipeWiredProgramSubsystem == 0 ||
kMGPipeWiredProgramSubsystem == kMGPipeSubsystemPrograms);
EXPECT_TRUE(kMGPipeWiredProgramSubsystem == 0 || kMGPipeWiredProgramSubsystem == kMGPipeSubsystemPrograms);
}
// =========================================================================================
@@ -305,11 +306,10 @@ TEST(ProgramEmit, ACreateWithNoArtefactsAnOversizedBlockOrACorruptSlotIsRefusedN
EXPECT_TRUE(MGPipeApplier().ShaderCsos.empty()) << "the table was grown by a refused record";
const MGPProgramDesc pastTheBound = ProgramDesc(MGPipeHandle{kMGPipeMaxShaderCsoSlots, 1}, 0x3u, 0);
ExpectRefusedNaming("create_shader_state {slot=1048576, gen=1}: the slot is outside the record table's "
"bound",
[&pastTheBound, &link, &spirv]() {
MGPipeApplyCreateShaderState(pastTheBound, &link, &spirv, nullptr);
});
ExpectRefusedNaming(
"create_shader_state {slot=1048576, gen=1}: the slot is outside the record table's "
"bound",
[&pastTheBound, &link, &spirv]() { MGPipeApplyCreateShaderState(pastTheBound, &link, &spirv, nullptr); });
EXPECT_TRUE(MGPipeApplier().ShaderCsos.empty());
EXPECT_TRUE(MGPipeApplier().CompositeShaderCsos.empty());
}
@@ -469,7 +469,6 @@ TEST(ProgramEmit, TheProgramRecordSurvivesAMakeCurrentWhileTheThreeBindingsDoNot
EXPECT_TRUE(MGPipeApplier().ShaderCsos.empty());
}
namespace {
namespace GL = MobileGL::MG_Impl::GLImpl;
using GLContext = MG_State::GLState::GLContext;
@@ -490,8 +489,12 @@ namespace {
}
};
GLContext& Ctx() { return *MG_State::pGLContext; }
MGPipeProgramEmitter& Emitter() { return MGPipeProgramEmitterInstance(); }
GLContext& Ctx() {
return *MG_State::pGLContext;
}
MGPipeProgramEmitter& Emitter() {
return MGPipeProgramEmitterInstance();
}
const char* kVs = R"(#version 430 core
uniform vec4 u_value;
@@ -525,7 +528,9 @@ void main() { gl_Position = vec4(0.0); EmitVertex(); }
return program;
}
constexpr Uint32 StageBit(ShaderStage stage) { return Uint32{1} << static_cast<Uint32>(stage); }
constexpr Uint32 StageBit(ShaderStage stage) {
return Uint32{1} << static_cast<Uint32>(stage);
}
// ProgramObject.h says it in as many words and this is the case that holds it: a stage mask
// built from the ATTACH list would describe a program that does not exist yet, because
@@ -702,8 +707,7 @@ void main() { gl_Position = vec4(0.0); EmitVertex(); }
// Driven to the fixed point rather than assumed to settle in one call: the first
// EmitGlobalConstants reads GetUBOContentVersion() BEFORE GetUBOSize() joins phase B,
// and that join bumps the counter, so the first key is one behind by construction.
for (int i = 0; i < 8 && Emitter().EmitGlobalConstants(Ctx()) > 0u; ++i) {
}
for (int i = 0; i < 8 && Emitter().EmitGlobalConstants(Ctx()) > 0u; ++i) {}
const Uint64 setsBefore = Emitter().GlobalConstantsSetCount();
ASSERT_GT(setsBefore, 0u) << "this program declares a uniform, so a block must have gone out";
const MGPipeHandle cso = Emitter().GlobalConstantsCso();
@@ -731,8 +735,7 @@ void main() { gl_Position = vec4(0.0); EmitVertex(); }
EXPECT_EQ(Emitter().GlobalConstantsVersion(), kMGPipeGlobalConstantsNeverUploaded);
// And the block really is sent again.
for (int i = 0; i < 8 && Emitter().EmitGlobalConstants(Ctx()) > 0u; ++i) {
}
for (int i = 0; i < 8 && Emitter().EmitGlobalConstants(Ctx()) > 0u; ++i) {}
EXPECT_GT(Emitter().GlobalConstantsSetCount(), setsBefore);
}
// A default uniform block wide enough that one vec4 is less than half of it, so a write to
@@ -761,8 +764,7 @@ void main() { gl_Position = u_a + u_b + u_c + u_d; }
void DrawWith(GLuint name) {
GL::UseProgram(name);
Emitter().EmitShaderState(Ctx());
for (int i = 0; i < 8 && Emitter().EmitGlobalConstants(Ctx()) > 0u; ++i) {
}
for (int i = 0; i < 8 && Emitter().EmitGlobalConstants(Ctx()) > 0u; ++i) {}
}
// THE set_global_constants KEY IS PER HANDLE, because the applier keeps one block per shader
@@ -899,8 +901,7 @@ void main() { gl_Position = u_a + u_b + u_c + u_d; }
// is what keeps a program-pipeline composite's per-draw uniform mirror free.
const Uint64 latched = Emitter().ProgramBindingsSetCount();
Emitter().EmitProgramBindings(*program, cso);
EXPECT_EQ(Emitter().ProgramBindingsSetCount(), latched)
<< "an unchanged binding set was re-sent";
EXPECT_EQ(Emitter().ProgramBindingsSetCount(), latched) << "an unchanged binding set was re-sent";
// A REAL glUniformBlockBinding, after the link, on a program that declares no block:
// the frontend's setter bails out on an out-of-range index, so this drives the other
@@ -914,8 +915,7 @@ void main() { gl_Position = u_a + u_b + u_c + u_d; }
<< "a post-link unit assignment did not move the latch, so it never travels";
const auto& hdr = Emitter().LastProgramBindings();
EXPECT_EQ(hdr.Cso, cso);
EXPECT_GE(hdr.SamplerUnitCount, 1u)
<< "the assigned unit is not in the record's second tail";
EXPECT_GE(hdr.SamplerUnitCount, 1u) << "the assigned unit is not in the record's second tail";
}
}
@@ -934,8 +934,10 @@ void main() { gl_Position = u_a + u_b + u_c + u_d; }
EXPECT_TRUE(program->HasUniformLocationTables(0)) << "a linked program must own its tables";
Vector<GLuint> attached;
for (const auto& shader : program->GetAttachedShaders()) attached.push_back(shader->GetExternalIndex());
for (const GLuint shader : attached) GL::DetachShader(name, shader);
for (const auto& shader : program->GetAttachedShaders())
attached.push_back(shader->GetExternalIndex());
for (const GLuint shader : attached)
GL::DetachShader(name, shader);
GL::LinkProgram(name);
GLint linked = GL_TRUE;
GL::GetProgramiv(name, GL_LINK_STATUS, &linked);
@@ -1046,8 +1048,7 @@ void main() { gl_Position = u_a + u_b + u_c + u_d; }
EXPECT_EQ(Emitter().CreateCount(), creates + 1)
<< "the failed relink did not re-issue, so the server keeps drawing an executable "
"the frontend reports unlinked";
EXPECT_EQ(Emitter().LastProgramDesc().LinkStatus, 0u)
<< "the re-issue claims the program linked";
EXPECT_EQ(Emitter().LastProgramDesc().LinkStatus, 0u) << "the re-issue claims the program linked";
EXPECT_TRUE(MGPipeSlots().IsLive(MGPipeKind::ShaderCso, cso))
<< "a failed relink must never be modelled as an object_death";
}
@@ -1064,8 +1065,7 @@ void main() { gl_Position = u_a + u_b + u_c + u_d; }
spirv.generatedSpirv.resize(2);
spirv.generatedSpirv[0].assign(3, 0x07230203u);
spirv.generatedSpirv[1].assign(5, 0x07230204u);
const Vector<Uint32> stages{static_cast<Uint32>(ShaderStage::Vertex),
static_cast<Uint32>(ShaderStage::Vertex)};
const Vector<Uint32> stages{static_cast<Uint32>(ShaderStage::Vertex), static_cast<Uint32>(ShaderStage::Vertex)};
Vector<Uint8> framed;
MG_State::GLState::EncodeProgramArchive(link, spirv, stages, framed);
@@ -1082,8 +1082,7 @@ void main() { gl_Position = u_a + u_b + u_c + u_d; }
// A TRUNCATED FRAME IS REFUSED, not guessed, and both outputs come back defined.
MG_State::GLState::ProgramArchive refused;
EXPECT_FALSE(
MG_State::GLState::DecodeProgramArchive(framed.data(), framed.size() - 1, refused));
EXPECT_FALSE(MG_State::GLState::DecodeProgramArchive(framed.data(), framed.size() - 1, refused));
EXPECT_TRUE(refused.LinkedStages.empty());
EXPECT_TRUE(refused.Spirv.generatedSpirv.empty());
}
@@ -1106,8 +1105,7 @@ int main(int argc, char** argv) {
// raised by the encoder on THIS thread - the client role. So g_logPath, which is the read
// path from here on, becomes the client-derived name; the env keeps the base. The rule is
// the library's own, not a copy.
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(), MobileGL::MG_Util::Debug::LogRole::Client);
MobileGL::Initialize();
::testing::InitGoogleTest(&argc, argv);
const int rc = RUN_ALL_TESTS();
+3 -1
View File
@@ -62,7 +62,9 @@ namespace {
g_seenLine = line;
return false;
}
bool AlwaysLatched() { return true; }
bool AlwaysLatched() {
return true;
}
} // namespace
// An installed latch hook gets the family and the FORMATTED line, and its answer is the call's.
+52 -22
View File
@@ -118,24 +118,41 @@ namespace {
Scrub(p.RendererInfo);
}
template <>
void Normalize(MGPRenderStateDesc& p) { Scrub(p.Blob); }
void Normalize(MGPRenderStateDesc& p) {
Scrub(p.Blob);
}
template <>
void Normalize(MGPDynamicState& p) { Scrub(p.Blob); }
void Normalize(MGPDynamicState& p) {
Scrub(p.Blob);
}
template <>
void Normalize(MGPVertexElements& p) { Scrub(p.Blob); }
void Normalize(MGPVertexElements& p) {
Scrub(p.Blob);
}
template <>
void Normalize(MGPSamplerDesc& p) { Scrub(p.Parameters); }
void Normalize(MGPSamplerDesc& p) {
Scrub(p.Parameters);
}
template <>
void Normalize(MGPGlobalConstants& p) { Scrub(p.Blob); }
void Normalize(MGPGlobalConstants& p) {
Scrub(p.Blob);
}
template <>
void Normalize(MGPResidualValueState& p) { Scrub(p.Blob); }
void Normalize(MGPResidualValueState& p) {
Scrub(p.Blob);
}
template <>
void Normalize(MGPSubData& p) { Scrub(p.Blob); }
void Normalize(MGPSubData& p) {
Scrub(p.Blob);
}
template <>
void Normalize(MGPStorageBlockBinding& p) { Scrub(p.Name); }
void Normalize(MGPStorageBlockBinding& p) {
Scrub(p.Name);
}
template <>
void Normalize(MGPProgramDesc& p) {
for (auto& stage : p.Spirv) Scrub(stage);
for (auto& stage : p.Spirv)
Scrub(stage);
Scrub(p.Reflection);
}
@@ -168,8 +185,12 @@ namespace {
}
// The six argument shapes PipeTables.inc generates after the payload.
Uint64 HashRest(Fnv&, const char*) { return 0; }
Uint64 HashRest(Fnv&, const char*, MGPReplySlot*) { return 0; }
Uint64 HashRest(Fnv&, const char*) {
return 0;
}
Uint64 HashRest(Fnv&, const char*, MGPReplySlot*) {
return 0;
}
Uint64 HashRest(Fnv& hash, const char*, const void* blob, Uint64 blobBytes) {
hash.AddU64(blobBytes);
if (blob != nullptr && blobBytes != 0) hash.Add(blob, static_cast<SizeT>(blobBytes));
@@ -226,13 +247,13 @@ namespace {
#undef MGL_REC_NAME
void InstallTableRecorders() {
#define MGL_REC_INSTALL(Name, Payload, Class, Flags, Wait) \
#define MGL_REC_INSTALL(Name, Payload, Class, Flags, Wait) \
Wrap<kRecName_##Name, decltype(MGL_REC_TABLE_##Class.Name)>::Install(MGL_REC_TABLE_##Class.Name);
MGP_CALL_LIST(MGL_REC_INSTALL)
#undef MGL_REC_INSTALL
}
void UninstallTableRecorders() {
#define MGL_REC_UNINSTALL(Name, Payload, Class, Flags, Wait) \
#define MGL_REC_UNINSTALL(Name, Payload, Class, Flags, Wait) \
Wrap<kRecName_##Name, decltype(MGL_REC_TABLE_##Class.Name)>::Uninstall(MGL_REC_TABLE_##Class.Name);
MGP_CALL_LIST(MGL_REC_UNINSTALL)
#undef MGL_REC_UNINSTALL
@@ -299,8 +320,8 @@ namespace {
const char* WireOpName(MGPWireOp op) {
switch (op) {
#define MGL_REC_OP_NAME(Name, Payload, Class, Flags, Wait) \
case MGPWireOp::Name: \
#define MGL_REC_OP_NAME(Name, Payload, Class, Flags, Wait) \
case MGPWireOp::Name: \
return #Name;
MGP_CALL_LIST(MGL_REC_OP_NAME)
#undef MGL_REC_OP_NAME
@@ -326,7 +347,8 @@ namespace {
Uint64 bytes = payloadBytes;
for (Uint32 i = 0; i < tailCount; ++i) {
hash.AddU64(tails[i].Size);
if (tails[i].Bytes != nullptr && tails[i].Size != 0) hash.Add(tails[i].Bytes, static_cast<SizeT>(tails[i].Size));
if (tails[i].Bytes != nullptr && tails[i].Size != 0)
hash.Add(tails[i].Bytes, static_cast<SizeT>(tails[i].Size));
bytes += tails[i].Size;
}
Note(WireOpName(op), hash, bytes);
@@ -363,7 +385,9 @@ namespace {
};
RecordingVerbSession* g_session = nullptr;
MG_Record::VerbSession& ResolveRecordingSession(const char*) { return *g_session; }
MG_Record::VerbSession& ResolveRecordingSession(const char*) {
return *g_session;
}
// ---- the scope a fixture runs in -------------------------------------------------------------
@@ -599,7 +623,9 @@ void main() { o_color = texture(u_texture, vec2(0.5)); }
return stream;
}
Bool FirstCaptureInProcess() { return g_captures == 0; }
Bool FirstCaptureInProcess() {
return g_captures == 0;
}
// Index of the first record whose op is `op` in a golden, or -1.
Int64 FirstGoldenRecordOf(const char* fixture, const char* op) {
@@ -617,13 +643,15 @@ void main() { o_color = texture(u_texture, vec2(0.5)); }
} // namespace
TEST(RecorderGolden, BufferVertexArrayDraw) {
if (!FirstCaptureInProcess()) GTEST_SKIP() << "compare the first capture of a process only (ctest runs each case alone)";
if (!FirstCaptureInProcess())
GTEST_SKIP() << "compare the first capture of a process only (ctest runs each case alone)";
const std::vector<Record> stream = Capture([] { RunBufferVertexArrayDraw(); });
CheckAgainstGolden("BufferVertexArrayDraw", stream);
}
TEST(RecorderGolden, TextureFramebufferClearBlit) {
if (!FirstCaptureInProcess()) GTEST_SKIP() << "compare the first capture of a process only (ctest runs each case alone)";
if (!FirstCaptureInProcess())
GTEST_SKIP() << "compare the first capture of a process only (ctest runs each case alone)";
const std::vector<Record> stream = Capture(&RunTextureFramebufferClearBlit);
CheckAgainstGolden("TextureFramebufferClearBlit", stream);
}
@@ -644,7 +672,8 @@ TEST(RecorderGolden, TheSameCallsRecordTheSameStreamTwice) {
// differently produces - must turn the comparison red AT that record, and nowhere before it.
TEST(RecorderGolden, APerturbedRecordFieldIsCaughtAtThatRecord) {
if (WriteRequested()) GTEST_SKIP() << "goldens are being rewritten";
if (!FirstCaptureInProcess()) GTEST_SKIP() << "compare the first capture of a process only (ctest runs each case alone)";
if (!FirstCaptureInProcess())
GTEST_SKIP() << "compare the first capture of a process only (ctest runs each case alone)";
// The first draw: a verb record, i.e. the session half of the recorder rather than the tables.
const Int64 victim = FirstGoldenRecordOf("BufferVertexArrayDraw", "DrawVbo");
ASSERT_GE(victim, 0) << "the golden has no DrawVbo record to perturb";
@@ -661,7 +690,8 @@ TEST(RecorderGolden, APerturbedRecordFieldIsCaughtAtThatRecord) {
// enters the stream.
TEST(RecorderGolden, AChangedGlInputChangesTheStream) {
if (WriteRequested()) GTEST_SKIP() << "goldens are being rewritten";
if (!FirstCaptureInProcess()) GTEST_SKIP() << "compare the first capture of a process only (ctest runs each case alone)";
if (!FirstCaptureInProcess())
GTEST_SKIP() << "compare the first capture of a process only (ctest runs each case alone)";
const std::vector<Record> stream = Capture([] { RunBufferVertexArrayDraw(4); });
const String difference = Compare("BufferVertexArrayDraw", stream);
ASSERT_FALSE(difference.empty())
+79 -76
View File
@@ -108,7 +108,7 @@ namespace {
SizeT Size;
};
#define MGP_RS_MEMBER_ROW(name) \
#define MGP_RS_MEMBER_ROW(name) \
Member{#name, offsetof(RenderStateParameters, name), sizeof(RenderStateParameters::name)},
constexpr Member kMembers[] = {MGP_FIELDS_RenderStateParameters(MGP_RS_MEMBER_ROW)};
#undef MGP_RS_MEMBER_ROW
@@ -134,7 +134,9 @@ namespace {
return OverlapWith(kMGPipeDynamicChunks, kMGPipeDynamicChunkCount, offset, size) == size;
}
Bool IsWhollyPipeline(SizeT offset, SizeT size) { return PipelineBytesOf(offset, size) == size; }
Bool IsWhollyPipeline(SizeT offset, SizeT size) {
return PipelineBytesOf(offset, size) == size;
}
// ---------------------------------------------------------------------------------
// D5's 25 kDraw derivations against the frontend getters they were transcribed from.
@@ -280,12 +282,12 @@ namespace {
}
EXPECT_TRUE(IsWhollyPipeline(member.Offset, member.Size))
<< member.Name << " is named as pipeline state but only " << pipelineBytes << " of its "
<< member.Size << " bytes are in the pipeline half - the rest have silently left the "
"CSO's identity";
<< member.Size
<< " bytes are in the pipeline half - the rest have silently left the "
"CSO's identity";
} else {
EXPECT_EQ(pipelineBytes, SizeT{0})
<< member.Name << " is not named as pipeline state but " << pipelineBytes
<< " of its bytes are in the pipeline half";
EXPECT_EQ(pipelineBytes, SizeT{0}) << member.Name << " is not named as pipeline state but "
<< pipelineBytes << " of its bytes are in the pipeline half";
EXPECT_TRUE(IsWhollyDynamic(member.Offset, member.Size))
<< member.Name << " is neither wholly pipeline nor wholly dynamic";
}
@@ -378,7 +380,7 @@ namespace {
// ---- Capabilities: every SET_CAPABILITY name, D3's three new ones included ----
#define MGP_CHECK_CAPABILITY(cap) \
check("SetCapability(" #cap ")", [](RenderState& s) { \
s.SetCapability(CapabilityInput::cap, !s.IsCapabilityEnabled(CapabilityInput::cap)); \
s.SetCapability(CapabilityInput::cap, !s.IsCapabilityEnabled(CapabilityInput::cap)); \
});
MGP_CHECK_CAPABILITY(ColorLogicOp)
MGP_CHECK_CAPABILITY(DebugOutput)
@@ -451,8 +453,8 @@ namespace {
BlendFactor::SrcAlpha);
});
check("SetBlendFuncIndexed(0)", [](RenderState& s) {
s.SetBlendFuncIndexed(0, BlendFactor::ConstantColor, BlendFactor::ConstantAlpha, BlendFactor::OneMinusDstColor,
BlendFactor::OneMinusDstAlpha);
s.SetBlendFuncIndexed(0, BlendFactor::ConstantColor, BlendFactor::ConstantAlpha,
BlendFactor::OneMinusDstColor, BlendFactor::OneMinusDstAlpha);
});
check("SetBlendEquation",
[](RenderState& s) { s.SetBlendEquation(BlendEquation::Subtract, BlendEquation::Min); });
@@ -503,7 +505,8 @@ namespace {
// ---- Colour mask, clear state, sampling ----
check("SetColorMask", [](RenderState& s) { s.SetColorMask(BoolVec4(true, false, true, false)); });
check("SetColorMaskIndexed", [](RenderState& s) { s.SetColorMaskIndexed(6, BoolVec4(false, false, true, true)); });
check("SetColorMaskIndexed",
[](RenderState& s) { s.SetColorMaskIndexed(6, BoolVec4(false, false, true, true)); });
check("SetColorMaskIndexed(0)",
[](RenderState& s) { s.SetColorMaskIndexed(0, BoolVec4(false, true, false, true)); });
check("SetClearColor", [](RenderState& s) { s.SetClearColor(FloatVec4(0.1f, 0.2f, 0.3f, 0.4f)); });
@@ -609,68 +612,68 @@ namespace {
// below is driven afterwards, so a field that still agrees with the context at the
// end can only have got there through the applier's derivation.
{
MG_Test::ScopedPipeVerb verb(MGPipeVerb::DrawArrays);
MG_Test::ScopedPipeVerb verb(MGPipeVerb::DrawArrays);
ctx.SetViewportIndexed(0, FloatVec4(1.5f, 2.5f, 63.5f, 32.25f));
ctx.SetViewportIndexed(7, FloatVec4(8.f, 9.f, 10.f, 11.f));
ctx.SetLineWidth(3.5f);
ctx.SetPatchVertices(4);
ctx.SetPatchDefaultOuterLevel(FloatVec4(2.f, 3.f, 4.f, 5.f));
ctx.SetPatchDefaultInnerLevel(FloatVec2(6.f, 7.f));
ctx.SetPolygonOffsetClamped(1.5f, 2.5f, 0.25f);
ctx.SetClampReadColor(GL_TRUE);
ctx.SetPolygonMode(GL_LINE, GL_POINT);
ctx.SetPrimitiveRestartIndex(0xabcdu);
ctx.SetBlendFuncIndexed(2, BlendFactor::DstColor, BlendFactor::SrcColor, BlendFactor::DstAlpha,
BlendFactor::SrcAlpha);
ctx.SetBlendEquationIndexed(4, BlendEquation::ReverseSubtract, BlendEquation::Max);
ctx.SetCapabilityIndexed(CapabilityInput::Blend, 3, true);
ctx.SetCapabilityIndexed(CapabilityInput::ScissorTest, 5, true);
ctx.SetLogicOp(LogicOperation::Xor);
ctx.SetDepthFunc(DepthTestFunc::GreaterEqual);
ctx.SetDepthMask(false);
ctx.SetStencilFunc(StencilFace::Front, DepthTestFunc::Equal, 7, 0xf0u);
ctx.SetStencilOp(StencilFace::Back, StencilOperation::Replace, StencilOperation::IncrementClamp,
StencilOperation::DecrementWrap);
ctx.SetStencilMask(StencilFace::Back, 0x0fu);
ctx.SetColorMaskIndexed(6, BoolVec4(false, false, true, true));
ctx.SetClearColor(FloatVec4(0.1f, 0.2f, 0.3f, 0.4f));
ctx.SetClearDepth(0.75f);
ctx.SetClearStencil(9);
ctx.SetBlendColor(FloatVec4(0.5f, 0.6f, 0.7f, 0.8f));
ctx.SetDepthRangeIndexed(9, FloatVec2(0.1f, 0.9f));
ctx.SetMinSampleShadingValue(0.625f);
ctx.SetCullFaceMode(CullFaceMode::Front);
ctx.SetProvokingVertexMode(ProvokingVertexMode::FirstVertex);
ctx.SetScissorBox(IntVec4(1, 2, 3, 4));
// One capability out of every arm of the 35-way switch: plain bools (the three D3
// gave storage to among them), the two indexed ones through their non-indexed entry
// point, and a clip distance.
ctx.SetCapability(CapabilityInput::DepthTest, true);
ctx.SetCapability(CapabilityInput::FramebufferSrgb, true);
ctx.SetCapability(CapabilityInput::DepthClamp, true);
ctx.SetCapability(CapabilityInput::TextureCubeMapSeamless, true);
ctx.SetCapability(CapabilityInput::Blend, true);
ctx.SetCapability(CapabilityInput::ClipDistance3, true);
ctx.SetViewportIndexed(0, FloatVec4(1.5f, 2.5f, 63.5f, 32.25f));
ctx.SetViewportIndexed(7, FloatVec4(8.f, 9.f, 10.f, 11.f));
ctx.SetLineWidth(3.5f);
ctx.SetPatchVertices(4);
ctx.SetPatchDefaultOuterLevel(FloatVec4(2.f, 3.f, 4.f, 5.f));
ctx.SetPatchDefaultInnerLevel(FloatVec2(6.f, 7.f));
ctx.SetPolygonOffsetClamped(1.5f, 2.5f, 0.25f);
ctx.SetClampReadColor(GL_TRUE);
ctx.SetPolygonMode(GL_LINE, GL_POINT);
ctx.SetPrimitiveRestartIndex(0xabcdu);
ctx.SetBlendFuncIndexed(2, BlendFactor::DstColor, BlendFactor::SrcColor, BlendFactor::DstAlpha,
BlendFactor::SrcAlpha);
ctx.SetBlendEquationIndexed(4, BlendEquation::ReverseSubtract, BlendEquation::Max);
ctx.SetCapabilityIndexed(CapabilityInput::Blend, 3, true);
ctx.SetCapabilityIndexed(CapabilityInput::ScissorTest, 5, true);
ctx.SetLogicOp(LogicOperation::Xor);
ctx.SetDepthFunc(DepthTestFunc::GreaterEqual);
ctx.SetDepthMask(false);
ctx.SetStencilFunc(StencilFace::Front, DepthTestFunc::Equal, 7, 0xf0u);
ctx.SetStencilOp(StencilFace::Back, StencilOperation::Replace, StencilOperation::IncrementClamp,
StencilOperation::DecrementWrap);
ctx.SetStencilMask(StencilFace::Back, 0x0fu);
ctx.SetColorMaskIndexed(6, BoolVec4(false, false, true, true));
ctx.SetClearColor(FloatVec4(0.1f, 0.2f, 0.3f, 0.4f));
ctx.SetClearDepth(0.75f);
ctx.SetClearStencil(9);
ctx.SetBlendColor(FloatVec4(0.5f, 0.6f, 0.7f, 0.8f));
ctx.SetDepthRangeIndexed(9, FloatVec2(0.1f, 0.9f));
ctx.SetMinSampleShadingValue(0.625f);
ctx.SetCullFaceMode(CullFaceMode::Front);
ctx.SetProvokingVertexMode(ProvokingVertexMode::FirstVertex);
ctx.SetScissorBox(IntVec4(1, 2, 3, 4));
// One capability out of every arm of the 35-way switch: plain bools (the three D3
// gave storage to among them), the two indexed ones through their non-indexed entry
// point, and a clip distance.
ctx.SetCapability(CapabilityInput::DepthTest, true);
ctx.SetCapability(CapabilityInput::FramebufferSrgb, true);
ctx.SetCapability(CapabilityInput::DepthClamp, true);
ctx.SetCapability(CapabilityInput::TextureCubeMapSeamless, true);
ctx.SetCapability(CapabilityInput::Blend, true);
ctx.SetCapability(CapabilityInput::ClipDistance3, true);
// The vacuity guard: the block still holds what the fill copied out of the DEFAULT
// context, so it must currently DISAGREE with the live one. If this ever passes, the
// comparisons below would be checking the filler against itself.
ASSERT_NE(gPipeInputs->GetLineWidth(), ctx.GetLineWidth());
// The vacuity guard: the block still holds what the fill copied out of the DEFAULT
// context, so it must currently DISAGREE with the live one. If this ever passes, the
// comparisons below would be checking the filler against itself.
ASSERT_NE(gPipeInputs->GetLineWidth(), ctx.GetLineWidth());
applyWholeBlock();
applyWholeBlock();
// ---- the 25 kDraw fields ----
ExpectDerivedDrawFieldsMatch(ctx, "whole block, kDraw");
// ...and the ~25 members that have NO derived field, which only a byte compare of the
// whole block reaches.
ExpectAssembledBlockIsTheLiveBlock(ctx, "whole block, kDraw");
// The rounding half of GetViewport, exercised on purpose: viewport 0 is
// (1.5, 2.5, 63.5, 32.25), so a transcription that truncated instead of rounding
// would hand the backends a 63-wide rectangle where 64 was asked for. The literal
// is std::lround's answer - round half AWAY FROM ZERO, so 1.5 -> 2 and 2.5 -> 3,
// not the banker's rounding a nearbyint() transcription would give.
EXPECT_EQ(gPipeInputs->GetViewport(), IntVec4(2, 3, 64, 32));
// ---- the 25 kDraw fields ----
ExpectDerivedDrawFieldsMatch(ctx, "whole block, kDraw");
// ...and the ~25 members that have NO derived field, which only a byte compare of the
// whole block reaches.
ExpectAssembledBlockIsTheLiveBlock(ctx, "whole block, kDraw");
// The rounding half of GetViewport, exercised on purpose: viewport 0 is
// (1.5, 2.5, 63.5, 32.25), so a transcription that truncated instead of rounding
// would hand the backends a 63-wide rectangle where 64 was asked for. The literal
// is std::lround's answer - round half AWAY FROM ZERO, so 1.5 -> 2 and 2.5 -> 3,
// not the banker's rounding a nearbyint() transcription would give.
EXPECT_EQ(gPipeInputs->GetViewport(), IntVec4(2, 3, 64, 32));
} // phase 1, kDraw
// Phase 2, kClear: the three clear values. The verb's own fill runs FIRST and copies
@@ -792,12 +795,10 @@ namespace {
const auto push = [&](const char* tag) {
const RenderStateParameters& live = ctx.GetRenderStateParameters();
const Uint32 movedPipeline =
firstPush ? static_cast<Uint32>((Uint64{1} << kMGPipePipelineChunkCount) - 1)
: MGPipePipelineChunksThatMoved(staged, live);
const Uint32 movedDynamic =
firstPush ? static_cast<Uint32>((Uint64{1} << kMGPipeDynamicChunkCount) - 1)
: MGPipeDynamicChunksThatMoved(staged, live);
const Uint32 movedPipeline = firstPush ? static_cast<Uint32>((Uint64{1} << kMGPipePipelineChunkCount) - 1)
: MGPipePipelineChunksThatMoved(staged, live);
const Uint32 movedDynamic = firstPush ? static_cast<Uint32>((Uint64{1} << kMGPipeDynamicChunkCount) - 1)
: MGPipeDynamicChunksThatMoved(staged, live);
if (movedPipeline != 0) {
Vector<Uint8> blob(MGPipePipelineChunkBlobBytes(movedPipeline));
@@ -1018,7 +1019,9 @@ namespace {
return result;
}
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
Bool DiedOfAbort(const ChildResult& r) {
return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT;
}
std::string DescribeStatus(const ChildResult& r) {
if (r.Status < 0) return "fork/waitpid failed";
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
+61 -67
View File
@@ -110,8 +110,7 @@ namespace {
// It is also the negative control for the registration itself. A Set that did not stick
// would leave the family permanently dark, and nothing else in the tree would say so.
TEST(ResourceEmit, TheResourceOpTableIsUnregisteredUntilABackendInstallsOne) {
ASSERT_EQ(MGPipeGetResourceOps(), nullptr)
<< "something registered a resource op table in a unit-test process";
ASSERT_EQ(MGPipeGetResourceOps(), nullptr) << "something registered a resource op table in a unit-test process";
static const MGPipeResourceOps ops{};
MGPipeSetResourceOps(&ops);
@@ -272,8 +271,8 @@ namespace {
g_spy.LastHandle = res;
}
const MGPipeResourceOps kSpyOps{SpyCreate, SpyRespecify, SpySubData, SpyResident, SpyFlush,
SpyReadback, SpyDestroy, SpyMap, SpyUnmap};
const MGPipeResourceOps kSpyOps{SpyCreate, SpyRespecify, SpySubData, SpyResident, SpyFlush,
SpyReadback, SpyDestroy, SpyMap, SpyUnmap};
#if MGTEST_HAVE_FORK
struct ChildResult {
@@ -304,7 +303,9 @@ namespace {
return result;
}
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
Bool DiedOfAbort(const ChildResult& r) {
return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT;
}
std::string DescribeStatus(const ChildResult& r) {
if (r.Status < 0) return "fork/waitpid failed";
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
@@ -579,7 +580,8 @@ namespace {
"acquisition";
// Three declines still cost three answers.
for (Uint32 i = 0; i < 3; ++i) EXPECT_EQ(MGPipeApplyMapPersistent(BufferHandle(res), 256, bytes), nullptr);
for (Uint32 i = 0; i < 3; ++i)
EXPECT_EQ(MGPipeApplyMapPersistent(BufferHandle(res), 256, bytes), nullptr);
EXPECT_EQ(MGPipeApplier().MapPersistentRoundtrips, 3u);
// A mint costs the same one.
@@ -643,8 +645,10 @@ namespace {
const std::string before = ReadLog();
MGPipeApplyResourceSubData(pastTheEnd, bytes);
EXPECT_EQ(RecordOf(res.Slot).Serial, 2u) << "a refused write must not move the serial";
EXPECT_NE(ReadLog().substr(before.size()).find("ProtocolCorruption resource_subdata {slot=7, gen=3, "
"glName=41}"),
EXPECT_NE(ReadLog()
.substr(before.size())
.find("ProtocolCorruption resource_subdata {slot=7, gen=3, "
"glName=41}"),
std::string::npos)
<< "the gate refused the write without saying which record it was";
#endif
@@ -1002,7 +1006,8 @@ namespace {
EXPECT_EQ(ElementsOf(cso.Slot).ContentSerial, 2u) << "a re-create on the same handle counts up";
EXPECT_EQ(ElementsOf(cso.Slot).AttributeCount, 2u);
EXPECT_EQ(ElementsOf(cso.Slot).BindingPointCount, 1u);
for (Uint32 i = 0; i < 2; ++i) ExpectAttribEq(ElementsOf(cso.Slot).Attributes[i], AttribAt(i), i);
for (Uint32 i = 0; i < 2; ++i)
ExpectAttribEq(ElementsOf(cso.Slot).Attributes[i], AttribAt(i), i);
ExpectBindingEq(ElementsOf(cso.Slot).BindingPoints[0], BindingAt(0), 0);
const MGPVertexAttribWire zeroAttrib{};
const MGPVertexBindingPointWire zeroBinding{};
@@ -1054,18 +1059,16 @@ namespace {
// And a count above the destination it would be unpacked into.
MGPVertexElements tooManyAttributes = declared.Desc;
tooManyAttributes.AttributeCount = kMGPipeMaxVertexAttribs + 1;
ExpectRefusedNaming("create_vertex_elements {slot=5, gen=2}: the declared attribute count is above "
"GL's attribute limit",
[&tooManyAttributes, blobBytes]() {
MGPipeApplyCreateVertexElements(tooManyAttributes, blobBytes);
});
ExpectRefusedNaming(
"create_vertex_elements {slot=5, gen=2}: the declared attribute count is above "
"GL's attribute limit",
[&tooManyAttributes, blobBytes]() { MGPipeApplyCreateVertexElements(tooManyAttributes, blobBytes); });
MGPVertexElements tooManyBindings = declared.Desc;
tooManyBindings.BindingPointCount = kMGPipeMaxVertexAttribs + 1;
ExpectRefusedNaming("create_vertex_elements {slot=5, gen=2}: the declared binding-point count is "
"above GL's attribute limit",
[&tooManyBindings, blobBytes]() {
MGPipeApplyCreateVertexElements(tooManyBindings, blobBytes);
});
ExpectRefusedNaming(
"create_vertex_elements {slot=5, gen=2}: the declared binding-point count is "
"above GL's attribute limit",
[&tooManyBindings, blobBytes]() { MGPipeApplyCreateVertexElements(tooManyBindings, blobBytes); });
EXPECT_EQ(ElementsOf(cso.Slot).ContentSerial, 2u);
EXPECT_EQ(ElementsOf(cso.Slot).AttributeCount, 3u);
}
@@ -1301,9 +1304,8 @@ namespace {
// The packed (resource target, upload target) pair a Tex2D level's records carry. 0x0102 -
// and it is the very number the split bring-up's Fatal printed, which is how this case is
// known to be about the same shape.
const Uint16 kTex2DUpload = MGPipePackSubDataTarget(
static_cast<Uint32>(MGPipeResourceTarget::Tex2D),
static_cast<Uint32>(TextureUploadTarget::Texture2D));
const Uint16 kTex2DUpload = MGPipePackSubDataTarget(static_cast<Uint32>(MGPipeResourceTarget::Tex2D),
static_cast<Uint32>(TextureUploadTarget::Texture2D));
MGPSubData TextureWrite(MGPipeHandle res, Uint16 uploadTarget, Uint16 level, Uint32 extent) {
MGPSubData record{};
@@ -1397,18 +1399,15 @@ namespace {
const ChildResult child = RunInChild([&res, &drive]() {
MGPResourceDesc perLevel = Tex2DDesc(res, 4, 2, 92);
MGPipeSetRespecifiedLevel(perLevel, kTex2DUpload, 1, 2, 2, 1);
const MGPRespecifiedLevel named = MGPipeMakeRespecifiedLevel(drive.PointerTarget, drive.PointerLevel, 2, 2, 1);
MGPipeApplyResourceRespecify(perLevel, nullptr,
drive.HasPointer ? &named : nullptr);
const MGPRespecifiedLevel named =
MGPipeMakeRespecifiedLevel(drive.PointerTarget, drive.PointerLevel, 2, 2, 1);
MGPipeApplyResourceRespecify(perLevel, nullptr, drive.HasPointer ? &named : nullptr);
});
EXPECT_TRUE(DiedOfAbort(child))
<< drive.What << ": " << DescribeStatus(child) << "; log: " << child.Log;
const std::string named =
"Fatal{PipeRespecifyScope} resource_respecify {slot=13, gen=2}";
EXPECT_TRUE(DiedOfAbort(child)) << drive.What << ": " << DescribeStatus(child) << "; log: " << child.Log;
const std::string named = "Fatal{PipeRespecifyScope} resource_respecify {slot=13, gen=2}";
EXPECT_NE(child.Log.find(named), std::string::npos)
<< drive.What << ": wanted \"" << named << "\"; log: " << child.Log;
EXPECT_NE(child.Log.find("declares a per-level respecify scope (target=258, level=1)"),
std::string::npos)
EXPECT_NE(child.Log.find("declares a per-level respecify scope (target=258, level=1)"), std::string::npos)
<< drive.What << ": the refusal must print the DECLARED range; log: " << child.Log;
EXPECT_NE(child.Log.find(drive.Wanted), std::string::npos)
<< drive.What << ": wanted \"" << drive.Wanted << "\"; log: " << child.Log;
@@ -1504,8 +1503,7 @@ namespace {
// A renderbuffer restorage is the publication D-D2 asks for: the frontend raises no
// version for it, so the emission IS the notice, and the applier holds the new extent.
MGPipeApplyResourceRespecify(TargetedDesc(shared, MGPipeResourceTarget::Renderbuffer, 1024, 33),
nullptr);
MGPipeApplyResourceRespecify(TargetedDesc(shared, MGPipeResourceTarget::Renderbuffer, 1024, 33), nullptr);
EXPECT_EQ(MGPipeApplier().RenderbufferResources[7].Desc.Width, 1024u);
EXPECT_EQ(MGPipeApplier().RenderbufferResources[7].Serial, 1u);
@@ -1586,8 +1584,7 @@ namespace {
// ---- with no consumer: every one of them declines, and NOTHING is stored ----
EXPECT_FALSE(MGPipeApplyResourceCreate(TargetedDesc(texture, MGPipeResourceTarget::Tex2D, 0, 22)));
EXPECT_FALSE(
MGPipeApplyResourceRespecify(TargetedDesc(texture, MGPipeResourceTarget::Tex2D, 64, 22), nullptr));
EXPECT_FALSE(MGPipeApplyResourceRespecify(TargetedDesc(texture, MGPipeResourceTarget::Tex2D, 64, 22), nullptr));
EXPECT_FALSE(MGPipeApplyResourceSubData(upload, nullptr));
MGPipeApplySetTextureParams(params);
MGPipeApplySetFramebufferState(fboState);
@@ -1638,18 +1635,17 @@ namespace {
EXPECT_TRUE(MGPipeHandleIsNull(MGPipeApplier().BoundShaderCso));
EXPECT_TRUE(MGPipeHandleIsNull(MGPipeApplier().DrawProgram));
EXPECT_TRUE(MGPipeHandleIsNull(MGPipeApplier().DispatchProgram));
EXPECT_TRUE(MGPipeHandleIsNull(
MGPipeApplier().BoundFramebuffer[static_cast<SizeT>(MGPipeFramebufferTarget::Draw)]));
EXPECT_TRUE(
MGPipeHandleIsNull(MGPipeApplier().BoundFramebuffer[static_cast<SizeT>(MGPipeFramebufferTarget::Draw)]));
// ---- and with one, every one of them lands. Same records, same order ----
{
ScopedResourceOps consumer;
const Uint64 refusalsBefore = MGPipeApplier().RefusedNoConsumer;
EXPECT_TRUE(MGPipeApplyResourceCreate(TargetedDesc(texture, MGPipeResourceTarget::Tex2D, 0, 22)));
EXPECT_TRUE(
MGPipeApplyResourceCreate(TargetedDesc(texture, MGPipeResourceTarget::Tex2D, 0, 22)));
EXPECT_TRUE(MGPipeApplyResourceRespecify(
TargetedDesc(texture, MGPipeResourceTarget::Tex2D, 64, 22), nullptr));
MGPipeApplyResourceRespecify(TargetedDesc(texture, MGPipeResourceTarget::Tex2D, 64, 22), nullptr));
MGPipeApplySetTextureParams(params);
MGPipeApplySetFramebufferState(fboState);
MGPipeApplyCreateSamplerState(samplerDesc, &samplerParams);
@@ -1670,8 +1666,7 @@ namespace {
EXPECT_EQ(MGPipeApplier().TextureResources[7].Params.BuiltinSampler, cso);
ASSERT_GT(MGPipeApplier().FramebufferRecords.size(), 4u);
EXPECT_TRUE(MGPipeApplier().FramebufferRecords[4].Live);
EXPECT_EQ(MGPipeApplier().BoundFramebuffer[static_cast<SizeT>(MGPipeFramebufferTarget::Draw)],
fbo);
EXPECT_EQ(MGPipeApplier().BoundFramebuffer[static_cast<SizeT>(MGPipeFramebufferTarget::Draw)], fbo);
ASSERT_GT(MGPipeApplier().SamplerCsos.size(), 9u);
EXPECT_TRUE(MGPipeApplier().SamplerCsos[9].Live);
ASSERT_GT(MGPipeApplier().SamplerViewCsos.size(), 9u);
@@ -1760,8 +1755,7 @@ namespace {
MGPipeApplyResourceCreate(TargetedDesc(texture, MGPipeResourceTarget::Tex2D, 0, 55));
MGPipeApplyResourceRespecify(TargetedDesc(texture, MGPipeResourceTarget::Tex2D, 8, 55), nullptr);
MGPipeApplyResourceCreate(TargetedDesc(renderbuffer, MGPipeResourceTarget::Renderbuffer, 0, 66));
MGPipeApplyResourceRespecify(TargetedDesc(renderbuffer, MGPipeResourceTarget::Renderbuffer, 8, 66),
nullptr);
MGPipeApplyResourceRespecify(TargetedDesc(renderbuffer, MGPipeResourceTarget::Renderbuffer, 8, 66), nullptr);
MGPSubData upload{};
upload.Res = texture;
upload.Target = static_cast<Uint16>(MGPipeResourceTarget::Tex2D);
@@ -1827,9 +1821,13 @@ namespace {
SharedPtr<GLContext> m_previousContext;
};
GLContext& Ctx() { return *MG_State::pGLContext; }
GLContext& Ctx() {
return *MG_State::pGLContext;
}
const SharedPtr<BufferObject>& MakeBuffer(Uint name) { return Ctx().CreateBufferObject(name); }
const SharedPtr<BufferObject>& MakeBuffer(Uint name) {
return Ctx().CreateBufferObject(name);
}
// Bind `buffer` to `target` the way the GL entry point for that target does. The index
// target is the BOUND VAO's element slot, not one of BufferState's, which is why it
@@ -1863,23 +1861,23 @@ namespace {
Uint32 LiteralBindMaskFor(BufferTarget target) {
switch (target) {
case BufferTarget::Vertex:
return 1u << 0; // VERTEX
return 1u << 0; // VERTEX
case BufferTarget::Index:
return (1u << 1) | (1u << 11); // INDEX | ELEMENT_ARRAY
return (1u << 1) | (1u << 11); // INDEX | ELEMENT_ARRAY
case BufferTarget::Uniform:
return 1u << 2; // CONSTANT
return 1u << 2; // CONSTANT
case BufferTarget::ShaderStorage:
return 1u << 3; // SHADER_BUFFER
return 1u << 3; // SHADER_BUFFER
case BufferTarget::DispatchIndirect:
case BufferTarget::DrawIndirect:
case BufferTarget::Parameter:
return 1u << 4; // INDIRECT
return 1u << 4; // INDIRECT
case BufferTarget::Texture:
return 1u << 5; // SAMPLER
return 1u << 5; // SAMPLER
case BufferTarget::TransformFeedback:
return 1u << 9; // STREAM_OUTPUT
return 1u << 9; // STREAM_OUTPUT
case BufferTarget::AtomicCounter:
return 1u << 10; // ATOMIC
return 1u << 10; // ATOMIC
case BufferTarget::CopyRead:
case BufferTarget::CopyWrite:
case BufferTarget::PixelPack:
@@ -1887,7 +1885,7 @@ namespace {
case BufferTarget::Query:
case BufferTarget::BufferTargetCount:
case BufferTarget::Unknown:
return 0u; // transfer and query targets bind nothing
return 0u; // transfer and query targets bind nothing
}
return 0xFFFFFFFFu;
}
@@ -2112,8 +2110,8 @@ namespace {
// The same refusal through the reachable cap, which is what a transport will hit
// first: a range whose later pieces cross the offset cap is refused whole.
pieces.clear();
EXPECT_FALSE(MGPipeForEachSubDataRecordRange(kMGPipeSubDataMaxRecordOffset - kSegment,
kSegment * 4, collect, kSegment));
EXPECT_FALSE(
MGPipeForEachSubDataRecordRange(kMGPipeSubDataMaxRecordOffset - kSegment, kSegment * 4, collect, kSegment));
EXPECT_TRUE(pieces.empty());
}
@@ -2152,8 +2150,7 @@ namespace {
std::vector<std::pair<Uint64, Uint64>> pieces;
const auto collect = [&](Uint64 at, Uint64 length) { pieces.emplace_back(at, length); };
const auto checkCoverage = [&](Uint64 whole, Uint64 cap) {
EXPECT_GE(pieces.size(), 4u) << "a range of " << whole << " bytes was not cut at a "
<< cap << " byte cap";
EXPECT_GE(pieces.size(), 4u) << "a range of " << whole << " bytes was not cut at a " << cap << " byte cap";
Uint64 covered = 0;
Uint64 expectedAt = 0;
for (const auto& piece : pieces) {
@@ -2165,8 +2162,8 @@ namespace {
// And every piece the walk produced has to be encodable by the record builder -
// a piece the box refuses is a record the applier's bounds gate would abort on.
MGPSubData record{};
EXPECT_TRUE(MGPipeBuildSubDataRecord(MGPipeHandle{1, 1}, piece.first, piece.second,
record, /*verbatimShadow=*/true))
EXPECT_TRUE(MGPipeBuildSubDataRecord(MGPipeHandle{1, 1}, piece.first, piece.second, record,
/*verbatimShadow=*/true))
<< "a piece the splitter produced does not fit one record";
EXPECT_EQ(MGPipeSubDataBufferOffset(record), piece.first);
EXPECT_EQ(MGPipeSubDataBufferSize(record), piece.second);
@@ -2250,8 +2247,7 @@ namespace {
MG_Pipe::MGPCaps caps{};
caps.CallMask = MG_Remote::MGCapsConsumerBits(MG_Pipe::kMGPipeSubsystemResources);
MG_Remote::Client::CapsMirrorInstance().Adopt(caps, MG_Backend::FormatCapabilityCache{},
MobileGL::RendererInfo{}, String{},
BackendType::DirectGLES);
MobileGL::RendererInfo{}, String{}, BackendType::DirectGLES);
// The spy IS the applier's consumer here, so "no resource_subdata followed" is
// counted rather than inferred from a missing log line.
g_spy = SpyState{};
@@ -2331,8 +2327,7 @@ namespace {
<< "the first write after a make-current moved no serial - it was dropped";
EXPECT_EQ(MGPipeApplier().RefusedResourceCalls, 0u)
<< "the write was refused because the applier had no record for it";
EXPECT_EQ(tracker.CreateCount(), 1u)
<< "the client re-published a create for a record the applier still had";
EXPECT_EQ(tracker.CreateCount(), 1u) << "the client re-published a create for a record the applier still had";
}
// THE DSA HOLE, which is what makes the sampled mask insufficient on its own: an element
@@ -2355,8 +2350,7 @@ namespace {
// The negative control FIRST, so the assertion below cannot pass because the bit is
// set for everything: a respecify with nothing bound publishes an empty mask.
indices->Respecify(64, nullptr);
ASSERT_EQ(tracker.LastDesc().BindMask, 0u)
<< "a respecify with no binding at all published one";
ASSERT_EQ(tracker.LastDesc().BindMask, 0u) << "a respecify with no binding at all published one";
// Bind, draw, unbind - the transient the sampler cannot see afterwards.
Ctx().GetBoundVertexArray()->GetIndexBufferBindingSlot().Bind(indices);
+24 -21
View File
@@ -151,7 +151,9 @@ namespace {
return result;
}
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
Bool DiedOfAbort(const ChildResult& r) {
return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT;
}
std::string DescribeStatus(const ChildResult& r) {
if (r.Status < 0) return "fork/waitpid failed";
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
@@ -194,8 +196,7 @@ TEST(SamplerEmit, TheEmitterIsOneNeverDestroyedProcessSingleton) {
// One bit for the whole sampler family - the CSO, the view and all three unit sets,
// including set_shader_images, whose emitter lives in ImageEmit.h. An operator switching
// samplers off has to get the whole family's legacy arm, not two thirds of it.
EXPECT_TRUE(kMGPipeWiredSamplerSubsystem == 0 ||
kMGPipeWiredSamplerSubsystem == kMGPipeSubsystemSamplers);
EXPECT_TRUE(kMGPipeWiredSamplerSubsystem == 0 || kMGPipeWiredSamplerSubsystem == kMGPipeSubsystemSamplers);
}
// =========================================================================================
@@ -520,7 +521,6 @@ TEST(SamplerEmit, AMakeCurrentTakesTheUnitSetsAndLeavesTheCsoAndViewRecordsStand
EXPECT_GT(MGPipeApplier().SamplerStatesSerial, statesSerial);
}
namespace {
using GLContext = MG_State::GLState::GLContext;
using MG_State::GLState::ITextureObject;
@@ -549,9 +549,15 @@ namespace {
}
};
GLContext& Ctx() { return *MG_State::pGLContext; }
MGPipeSamplerEmitter& Emitter() { return MGPipeSamplerEmitterInstance(); }
MGPipeSamplerCsoCache& Cache() { return MGPipeSamplerCsoCacheInstance(); }
GLContext& Ctx() {
return *MG_State::pGLContext;
}
MGPipeSamplerEmitter& Emitter() {
return MGPipeSamplerEmitterInstance();
}
MGPipeSamplerCsoCache& Cache() {
return MGPipeSamplerCsoCacheInstance();
}
// Every field of SamplerParameters set to a value that is not its default, so a conversion
// that dropped one is caught by the field's own EXPECT rather than by a count.
@@ -591,9 +597,7 @@ namespace {
}
void BindTextureToUnit(Uint32 unit, const SharedPtr<ITextureObject>& texture) {
Ctx().GetTextureUnitObject(static_cast<Int>(unit))
.GetBindingSlot(TextureTarget::Texture2D)
.Bind(texture);
Ctx().GetTextureUnitObject(static_cast<Int>(unit)).GetBindingSlot(TextureTarget::Texture2D).Bind(texture);
Ctx().NoteTextureUnitTouched(static_cast<Int>(unit));
}
@@ -641,7 +645,8 @@ namespace {
auto* bytes = reinterpret_cast<Uint8*>(&dirty);
// Written THROUGH A BYTE POINTER, past the last member and inside the object, which is
// the only way to make the difference this case is about.
for (SizeT i = 97; i < sizeof(SamplerParameters); ++i) bytes[i] = static_cast<Uint8>(0xA5 + i);
for (SizeT i = 97; i < sizeof(SamplerParameters); ++i)
bytes[i] = static_cast<Uint8>(0xA5 + i);
SamplerParameters canonClean;
SamplerParameters canonDirty;
@@ -821,7 +826,8 @@ namespace {
EXPECT_EQ(Cache().GetCounters().GroupPublishes, 1u);
EXPECT_NE(BoundGroupSamplerRecord(back), nullptr);
for (const MGPipeHandle held : {first, second, again, back}) Cache().Release(held);
for (const MGPipeHandle held : {first, second, again, back})
Cache().Release(held);
EXPECT_EQ(Cache().GetCounters().UnknownReleases + Cache().GetCounters().UnderflowedReleases, 0u);
}
@@ -934,11 +940,10 @@ namespace {
Uint MakeSamplerProgram() {
namespace GL = MobileGL::MG_Impl::GLImpl;
static const char* kVs = "#version 330 core\nvoid main(){ gl_Position = vec4(0.0); }\n";
static const char* kFs =
"#version 330 core\n"
"uniform sampler2D sampled;\n"
"out vec4 color;\n"
"void main(){ color = texture(sampled, vec2(0.0)); }\n";
static const char* kFs = "#version 330 core\n"
"uniform sampler2D sampled;\n"
"out vec4 color;\n"
"void main(){ color = texture(sampled, vec2(0.0)); }\n";
const Uint program = GL::CreateProgram();
const Uint vs = GL::CreateShader(GL_VERTEX_SHADER);
GL::ShaderSource(vs, 1, &kVs, nullptr);
@@ -1098,8 +1103,7 @@ namespace {
EXPECT_EQ(Cache().GetCounters().OverCapacityMints, 0u)
<< "there were unreferenced entries to take, so nothing had to grow";
EXPECT_TRUE(Cache().RecordIsPublished(pinned))
<< "a handle a standing record names is not the LRU's to take";
EXPECT_TRUE(Cache().RecordIsPublished(pinned)) << "a handle a standing record names is not the LRU's to take";
Uint64 second = 0;
EXPECT_EQ(Cache().Acquire(pinnedParams, second), pinned);
EXPECT_EQ(second, 0u) << "and it was a hit, not a re-mint under the same value";
@@ -1239,8 +1243,7 @@ int main(int argc, char** argv) {
// raised by the encoder on THIS thread - the client role. So g_logPath, which is the read
// path from here on, becomes the client-derived name; the env keeps the base. The rule is
// the library's own, not a copy.
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(), MobileGL::MG_Util::Debug::LogRole::Client);
// ONE process-wide context for the whole suite, because half these cases need a really
// linked program and glslang lives behind this call. Each case uses GL names of its own.
MobileGL::Initialize();
+24 -31
View File
@@ -81,7 +81,6 @@ namespace {
}
} // namespace
namespace {
namespace GL = MobileGL::MG_Impl::GLImpl;
using GLContext = MG_State::GLState::GLContext;
@@ -111,8 +110,12 @@ namespace {
}
};
GLContext& Ctx() { return *MG_State::pGLContext; }
MGPipeShaderBufferEmitter& Emitter() { return MGPipeShaderBufferEmitterInstance(); }
GLContext& Ctx() {
return *MG_State::pGLContext;
}
MGPipeShaderBufferEmitter& Emitter() {
return MGPipeShaderBufferEmitterInstance();
}
// ---- driving a refusal, in ImageEmitTest's shape and for its reason ------------------
//
@@ -181,8 +184,7 @@ namespace {
const ChildResult child = RunInChild(body);
EXPECT_TRUE(DiedOfAbort(child)) << DescribeStatus(child) << "; log: " << child.Log;
EXPECT_NE(child.Log.find(tagged), std::string::npos)
<< "the gate fired without naming what it refused; wanted \"" << tagged
<< "\"; log: " << child.Log;
<< "the gate fired without naming what it refused; wanted \"" << tagged << "\"; log: " << child.Log;
#else
(void)needle;
(void)body; // no fork on this platform; the verdict here is std::abort()
@@ -262,8 +264,7 @@ namespace {
// And the record reached the applier through the monolith adapter this route installs.
EXPECT_EQ(MGPipeApplier().ShaderBufferCount[kMGPipeShaderBufferClassUniform], header.Count);
EXPECT_EQ(MGPipeApplier().BoundShaderBuffers[kMGPipeShaderBufferClassUniform][0].Size,
kMGPipeWholeBuffer);
EXPECT_EQ(MGPipeApplier().BoundShaderBuffers[kMGPipeShaderBufferClassUniform][0].Size, kMGPipeWholeBuffer);
}
// ID-104's case. The mask is what replaces the backend's own GPU-write walk, and until this
@@ -288,8 +289,7 @@ namespace {
GL::BindBufferBase(GL_UNIFORM_BUFFER, 0, uniform);
ASSERT_NE(Emitter().EmitShaderBuffers(Ctx()), 0u);
const MGPShaderBuffers& storageHeader =
Emitter().LastHeader(kMGPipeShaderBufferClassShaderStorage);
const MGPShaderBuffers& storageHeader = Emitter().LastHeader(kMGPipeShaderBufferClassShaderStorage);
ASSERT_EQ(storageHeader.Count, top + 1u)
<< "the window is the touched high-water mark, so binding the top point describes "
"every point below it too";
@@ -299,8 +299,7 @@ namespace {
<< "nothing is bound at storage point 0, so nothing is writable there";
ASSERT_NE(Emitter().EmitConstBuffers(Ctx()), 0u);
const MGPShaderBuffers& uniformHeader =
Emitter().LastHeader(kMGPipeShaderBufferClassUniform);
const MGPShaderBuffers& uniformHeader = Emitter().LastHeader(kMGPipeShaderBufferClassUniform);
for (Uint32 w = 0; w < kMGPipeShaderBufferWritableMaskWords; ++w) {
EXPECT_EQ(uniformHeader.WritableMask[w], 0u)
<< "a UBO is read-only to the shader by definition (word " << w << ")";
@@ -308,8 +307,8 @@ namespace {
// And the applier carries the mask by class, not by record.
EXPECT_TRUE(MGPipeShaderBufferMaskHas(
MGPipeApplier().ShaderBufferWritableMask[kMGPipeShaderBufferClassShaderStorage], top));
EXPECT_FALSE(MGPipeShaderBufferMaskHas(
MGPipeApplier().ShaderBufferWritableMask[kMGPipeShaderBufferClassUniform], top));
EXPECT_FALSE(
MGPipeShaderBufferMaskHas(MGPipeApplier().ShaderBufferWritableMask[kMGPipeShaderBufferClassUniform], top));
// THE WIRE FIELD's OWN HALF (ID-104): a mask bit at the LAST point the window may
// describe survives the record and the applier. A Uint32 field could not have carried
@@ -345,8 +344,7 @@ namespace {
ASSERT_NE(Emitter().EmitConstBuffers(Ctx()), 0u);
ASSERT_NE(Emitter().EmitShaderBuffers(Ctx()), 0u);
const Uint64 uniformEmissions = Emitter().EmissionCount(kMGPipeShaderBufferClassUniform);
const Uint64 storageEmissions =
Emitter().EmissionCount(kMGPipeShaderBufferClassShaderStorage);
const Uint64 storageEmissions = Emitter().EmissionCount(kMGPipeShaderBufferClassShaderStorage);
// Nothing moved: both classes must be suppressed, and each on its OWN latch.
EXPECT_EQ(Emitter().EmitConstBuffers(Ctx()), 0u);
@@ -358,8 +356,7 @@ namespace {
// re-sent, and the case would pass for the wrong reason if it only asserted the mover.
GL::BindBufferBase(GL_SHADER_STORAGE_BUFFER, 2, 0);
EXPECT_NE(Emitter().EmitShaderBuffers(Ctx()), 0u);
EXPECT_EQ(Emitter().EmissionCount(kMGPipeShaderBufferClassShaderStorage),
storageEmissions + 1u);
EXPECT_EQ(Emitter().EmissionCount(kMGPipeShaderBufferClassShaderStorage), storageEmissions + 1u);
EXPECT_EQ(Emitter().EmitConstBuffers(Ctx()), 0u)
<< "the uniform class did not move and must not be re-sent on the storage class's "
"account";
@@ -386,8 +383,7 @@ namespace {
MGPipeApplySetShaderBuffers(header, ranges);
EXPECT_EQ(MGPipeApplier().ShaderBufferCount[kMGPipeShaderBufferClassShaderStorage], 2u);
EXPECT_EQ(MGPipeApplier().BoundShaderBuffers[kMGPipeShaderBufferClassShaderStorage][1].Offset,
64u);
EXPECT_EQ(MGPipeApplier().BoundShaderBuffers[kMGPipeShaderBufferClassShaderStorage][1].Offset, 64u);
EXPECT_EQ(MGPipeApplier().ShaderBuffersSerial, before + 1u);
// THE OTHER TWO CLASSES ARE UNTOUCHED, which is the whole reason Class is a field: one
// record describes one array and says nothing about the other two.
@@ -446,19 +442,17 @@ namespace {
applier.ShaderBufferStart[kMGPipeShaderBufferClassUniform] = 0;
applier.ShaderBufferCount[kMGPipeShaderBufferClassUniform] = 7;
applier.BoundShaderBuffers[kMGPipeShaderBufferClassUniform][0].Res = MGPipeHandle{31, 1};
MGPipeShaderBufferMaskSet(
applier.ShaderBufferWritableMask[kMGPipeShaderBufferClassShaderStorage],
kMGPipeMaxBufferBindingPoints - 1);
MGPipeShaderBufferMaskSet(applier.ShaderBufferWritableMask[kMGPipeShaderBufferClassShaderStorage],
kMGPipeMaxBufferBindingPoints - 1);
applier.ShaderBuffersSerial = 99;
MGPipeApplierReset();
EXPECT_EQ(MGPipeApplier().ShaderBufferCount[kMGPipeShaderBufferClassUniform], 0u);
EXPECT_TRUE(MGPipeHandleIsNull(
MGPipeApplier().BoundShaderBuffers[kMGPipeShaderBufferClassUniform][0].Res));
EXPECT_FALSE(MGPipeShaderBufferMaskHas(
MGPipeApplier().ShaderBufferWritableMask[kMGPipeShaderBufferClassShaderStorage],
kMGPipeMaxBufferBindingPoints - 1));
EXPECT_TRUE(MGPipeHandleIsNull(MGPipeApplier().BoundShaderBuffers[kMGPipeShaderBufferClassUniform][0].Res));
EXPECT_FALSE(
MGPipeShaderBufferMaskHas(MGPipeApplier().ShaderBufferWritableMask[kMGPipeShaderBufferClassShaderStorage],
kMGPipeMaxBufferBindingPoints - 1));
EXPECT_EQ(MGPipeApplier().ShaderBuffersSerial, 100u);
EXPECT_GT(MGPipeApplier().ShaderBuffersSerial, 99u)
<< "ADVANCED, never zeroed: no value this counter has handed a twin may come back";
@@ -467,8 +461,8 @@ namespace {
int main(int argc, char** argv) {
namespace fs = std::filesystem;
const fs::path path = fs::temp_directory_path() /
("mobilegl-shaderbufferemit-test-" + std::to_string(ProcessId()) + ".log");
const fs::path path =
fs::temp_directory_path() / ("mobilegl-shaderbufferemit-test-" + std::to_string(ProcessId()) + ".log");
std::error_code ec;
fs::remove(path, ec);
g_logPath = path.string();
@@ -482,8 +476,7 @@ int main(int argc, char** argv) {
// raised by the encoder on THIS thread - the client role. So g_logPath, which is the read
// path from here on, becomes the client-derived name; the env keeps the base. The rule is
// the library's own, not a copy.
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(), MobileGL::MG_Util::Debug::LogRole::Client);
MobileGL::Initialize();
::testing::InitGoogleTest(&argc, argv);
const int rc = RUN_ALL_TESTS();
+8 -7
View File
@@ -118,7 +118,7 @@ namespace {
Uint64 staleHint = MGPipePackHandleHint(minted);
const MGPipeHandle successor = allocator.AcquireHinted(MGPipeKind::Buffer, kSecond, staleHint);
EXPECT_EQ(successor.Slot, minted.Slot) << "the free list did not hand the slot back";
Uint64 forged = MGPipePackHandleHint(successor); // the successor's exact slot and generation
Uint64 forged = MGPipePackHandleHint(successor); // the successor's exact slot and generation
EXPECT_TRUE(MGPipeHandleIsNull(allocator.FindByLifetimeIdHinted(MGPipeKind::Buffer, kFirst, forged)))
<< "a hint naming another object's live slot answered for the dead object";
@@ -133,7 +133,8 @@ namespace {
MGPipeSlotAllocator allocator;
MGPipeHandle handles[8];
for (MGPipeHandle& handle : handles) handle = allocator.Allocate(MGPipeKind::Framebuffer);
for (MGPipeHandle& handle : handles)
handle = allocator.Allocate(MGPipeKind::Framebuffer);
const Uint32 highWater = allocator.HighWater(MGPipeKind::Framebuffer);
EXPECT_EQ(allocator.LiveCount(MGPipeKind::Framebuffer), 8u);
EXPECT_EQ(allocator.FreeCount(MGPipeKind::Framebuffer), 0u);
@@ -148,7 +149,7 @@ namespace {
const MGPipeHandle a = allocator.Allocate(MGPipeKind::Framebuffer);
const MGPipeHandle b = allocator.Allocate(MGPipeKind::Framebuffer);
EXPECT_EQ(allocator.HighWater(MGPipeKind::Framebuffer), highWater) << "the high-water mark grew with two "
"slots waiting on the free list";
"slots waiting on the free list";
EXPECT_TRUE((a.Slot == handles[2].Slot && b.Slot == handles[5].Slot) ||
(a.Slot == handles[5].Slot && b.Slot == handles[2].Slot))
<< "the reused slots are not the two that were freed";
@@ -247,10 +248,10 @@ namespace {
EXPECT_FALSE(MGPipeHandleIsNull(first));
sharp.Free(MGPipeKind::VertexElementsCso, first);
const MGPipeHandle second = sharp.Acquire(MGPipeKind::VertexElementsCso, repeatedLifetimeId);
EXPECT_FALSE(second == first)
<< "re-acquiring the SAME lifetime id after a free reproduced handle {slot=" << first.Slot
<< ", gen=" << first.Gen << "}; an address-keyed or name-keyed memo would then serve the dead "
"object's entry to the live one";
EXPECT_FALSE(second == first) << "re-acquiring the SAME lifetime id after a free reproduced handle {slot="
<< first.Slot << ", gen=" << first.Gen
<< "}; an address-keyed or name-keyed memo would then serve the dead "
"object's entry to the live one";
EXPECT_EQ(second.Slot, first.Slot) << "the freed slot was not the one handed back";
EXPECT_EQ(second.Gen, first.Gen + 1) << "a reused slot must carry a new generation";
// And the dead handle stays dead, which is what makes the ABA detectable rather than
+88 -133
View File
@@ -144,7 +144,9 @@ namespace {
return result;
}
Bool DiedOfAbort(const ChildResult& r) { return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT; }
Bool DiedOfAbort(const ChildResult& r) {
return WIFSIGNALED(r.Status) && WTERMSIG(r.Status) == SIGABRT;
}
std::string DescribeStatus(const ChildResult& r) {
if (r.Status < 0) return "fork/waitpid failed";
if (WIFEXITED(r.Status)) return "exited " + std::to_string(WEXITSTATUS(r.Status));
@@ -186,8 +188,7 @@ namespace {
// use-after-free this design closed once already.
TEST(TextureEmit, TheEmitterIsOneNeverDestroyedProcessSingleton) {
EXPECT_EQ(&MGPipeTextureEmitterInstance(), &MGPipeTextureEmitterInstance());
EXPECT_TRUE(kMGPipeWiredTextureSubsystem == 0 ||
kMGPipeWiredTextureSubsystem == kMGPipeSubsystemTextureResources);
EXPECT_TRUE(kMGPipeWiredTextureSubsystem == 0 || kMGPipeWiredTextureSubsystem == kMGPipeSubsystemTextureResources);
}
// ============================================================================
@@ -228,9 +229,8 @@ namespace {
// resource hook has anything to fire on.
// Without all three the family gate is FALSE and every case below would be green for
// the wrong reason - which is what the dependency cases at the end of this file pin.
MG_Config::Features.PipePush |= kMGPipeSubsystemResources |
kMGPipeSubsystemTextureResources |
kMGPipeSubsystemSamplers;
MG_Config::Features.PipePush |=
kMGPipeSubsystemResources | kMGPipeSubsystemTextureResources | kMGPipeSubsystemSamplers;
m_previousContext = MG_State::pGLContext.Take();
MG_State::pGLContext = MakeUnique<GLContext>();
MGPipeTextureEmitterInstance().ResetForTest();
@@ -273,8 +273,12 @@ namespace {
const MGPipeResourceOps* m_saved;
};
MGPipeTextureEmitter& Textures() { return MGPipeTextureEmitterInstance(); }
GLContext& Ctx() { return *MG_State::pGLContext; }
MGPipeTextureEmitter& Textures() {
return MGPipeTextureEmitterInstance();
}
GLContext& Ctx() {
return *MG_State::pGLContext;
}
// The APPLIER's own view of what this emitter sent. With the family's wired constant flipped
// the calls actually land, so a case can read the record rather than the emitter's staging
@@ -288,8 +292,8 @@ namespace {
return &record;
}
const MGPipeResourceRecord::PendingUpload* AppliedUpload(const MGPipeResourceRecord& record,
Uint16 target, Uint16 level) {
const MGPipeResourceRecord::PendingUpload* AppliedUpload(const MGPipeResourceRecord& record, Uint16 target,
Uint16 level) {
for (const auto& pending : record.PendingUploads) {
if (pending.UploadTarget == target && pending.Level == level) return &pending;
}
@@ -304,9 +308,9 @@ namespace {
texture->SetInternalFormat(TextureInternalFormat::RGBA8);
for (Uint level = 0; level < levels; ++level) {
const Int extent = std::max<Int>(size >> level, 1);
texture->AllocateStorage(TextureUploadTarget::Texture2D, level,
MipmapInput{IntVec3{extent, extent, 1},
static_cast<SizeT>(extent) * static_cast<SizeT>(extent) * 4});
texture->AllocateStorage(
TextureUploadTarget::Texture2D, level,
MipmapInput{IntVec3{extent, extent, 1}, static_cast<SizeT>(extent) * static_cast<SizeT>(extent) * 4});
}
return texture;
}
@@ -373,8 +377,7 @@ TEST(TextureEmit, ABindMaskBitIsStickyAcrossARespecify) {
Textures().NoteTextureBoundAs(handle, kMGPipeBindRenderTarget);
// A storage definition REPUBLISHES the mask; it does not rebuild it.
texture->AllocateStorage(TextureUploadTarget::Texture2D, 0,
MipmapInput{IntVec3{16, 16, 1}, 16 * 16 * 4});
texture->AllocateStorage(TextureUploadTarget::Texture2D, 0, MipmapInput{IntVec3{16, 16, 1}, 16 * 16 * 4});
EXPECT_TRUE(Textures().LastDesc().Resource == handle);
EXPECT_NE(Textures().LastDesc().BindMask & kMGPipeBindRenderTarget, 0)
<< "MGPResourceDesc::BindMask lost the RENDER_TARGET bit across a respecify";
@@ -437,8 +440,7 @@ TEST(TextureEmit, TheUnionBoxAndTheRegionListDescribeTheSameTexels) {
TextureScope scope;
const auto texture = MakeTexture2D(4, 256);
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0}, IntVec3{1, 1, 1});
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{255, 255, 0},
IntVec3{1, 1, 1});
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{255, 255, 0}, IntVec3{1, 1, 1});
ASSERT_EQ(Textures().DrainListSize(), 1u);
Textures().DrainTextureSubData(Ctx());
@@ -454,11 +456,9 @@ TEST(TextureEmit, TheUnionBoxAndTheRegionListDescribeTheSameTexels) {
for (const MGPSubRegion& region : regions) {
EXPECT_GE(region.X, record.UnionBox.X) << "a rect starts left of the union box";
EXPECT_GE(region.Y, record.UnionBox.Y) << "a rect starts above the union box";
EXPECT_LE(region.X + static_cast<Int32>(region.W),
record.UnionBox.X + static_cast<Int32>(record.UnionBox.W))
EXPECT_LE(region.X + static_cast<Int32>(region.W), record.UnionBox.X + static_cast<Int32>(record.UnionBox.W))
<< "a rect ends right of the union box";
EXPECT_LE(region.Y + static_cast<Int32>(region.H),
record.UnionBox.Y + static_cast<Int32>(record.UnionBox.H))
EXPECT_LE(region.Y + static_cast<Int32>(region.H), record.UnionBox.Y + static_cast<Int32>(record.UnionBox.H))
<< "a rect ends below the union box";
loX = std::min(loX, region.X);
loY = std::min(loY, region.Y);
@@ -475,8 +475,7 @@ TEST(TextureEmit, AScatteredUploadCarriesTheLevelShadowsStridesAndNotZero) {
TextureScope scope;
const auto texture = MakeTexture2D(5, 256);
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{4, 8, 0}, IntVec3{2, 2, 1});
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{200, 220, 0},
IntVec3{2, 2, 1});
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{200, 220, 0}, IntVec3{2, 2, 1});
Textures().DrainTextureSubData(Ctx());
const Vector<MGPSubRegion> regions = Textures().LastRegions();
const auto& record = Textures().LastSubData();
@@ -488,10 +487,8 @@ TEST(TextureEmit, AScatteredUploadCarriesTheLevelShadowsStridesAndNotZero) {
// not its own width - or the staging planner on the far side repacks the wrong bytes.
for (const MGPSubRegion& region : regions) {
EXPECT_EQ(region.SrcRowStride, 256u * 4u) << "SrcRowStride is not the LEVEL's row pitch";
EXPECT_EQ(region.SrcSliceStride, 256u * 4u * 256u)
<< "SrcSliceStride is not the LEVEL's slice pitch";
const Uint64 expectedOffset =
static_cast<Uint64>(region.Y) * 256u * 4u + static_cast<Uint64>(region.X) * 4u;
EXPECT_EQ(region.SrcSliceStride, 256u * 4u * 256u) << "SrcSliceStride is not the LEVEL's slice pitch";
const Uint64 expectedOffset = static_cast<Uint64>(region.Y) * 256u * 4u + static_cast<Uint64>(region.X) * 4u;
EXPECT_EQ(region.SrcOffset, expectedOffset) << "SrcOffset is not the first texel's byte offset";
}
}
@@ -499,8 +496,7 @@ TEST(TextureEmit, AScatteredUploadCarriesTheLevelShadowsStridesAndNotZero) {
TEST(TextureEmit, AWholeLevelUploadCarriesZeroStrides) {
TextureScope scope;
const auto texture = MakeTexture2D(6, 64);
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0},
IntVec3{64, 64, 1});
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0}, IntVec3{64, 64, 1});
Textures().DrainTextureSubData(Ctx());
const MGPSubData record = Textures().LastSubData();
EXPECT_EQ(record.RegionCount, 0u) << "a single whole-level rect IS the union box, not a list";
@@ -519,10 +515,8 @@ TEST(TextureEmit, AWholeLevelUploadCarriesZeroStrides) {
"whole-level shape stays what it always was";
// The upload target rides in the record's Target byte beside the resource target, which is
// the only place a cube face could ever be carried.
EXPECT_EQ(MGPipeSubDataResourceTargetOf(record.Target),
static_cast<Uint8>(MGPipeResourceTarget::Tex2D));
EXPECT_EQ(MGPipeSubDataUploadTargetOf(record.Target),
static_cast<Uint8>(TextureUploadTarget::Texture2D));
EXPECT_EQ(MGPipeSubDataResourceTargetOf(record.Target), static_cast<Uint8>(MGPipeResourceTarget::Tex2D));
EXPECT_EQ(MGPipeSubDataUploadTargetOf(record.Target), static_cast<Uint8>(TextureUploadTarget::Texture2D));
// And the whole-level builder really does say TIGHTLY PACKED.
const MGPipeLevelPitch pitch = MGPipeLevelPitchOf(IntVec3{64, 64, 1}, 64 * 64 * 4);
const MGPSubRegion whole = MGPipeBuildSubRegion(record.UnionBox, IntVec3{64, 64, 1}, pitch);
@@ -543,8 +537,7 @@ TEST(TextureEmit, MoreWritesThanTheRectListKeepsCrossAsTheExactFootprint) {
for (Int i = 0; i < 4 * static_cast<Int>(MipmapStorage::kMaxDirtyRects); ++i) {
const Int x = (i * 7) % 120;
const Int y = (i * 11) % 120;
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{x, y, 0},
IntVec3{2, 2, 1});
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{x, y, 0}, IntVec3{2, 2, 1});
}
Vector<MipmapDirtyRegion> oracle;
texture->GetStorageDirtyFootprint(TextureUploadTarget::Texture2D, 0, oracle);
@@ -558,8 +551,8 @@ TEST(TextureEmit, MoreWritesThanTheRectListKeepsCrossAsTheExactFootprint) {
ASSERT_EQ(regions.size(), oracle.size());
for (SizeT i = 0; i < oracle.size(); ++i) {
const MGPBox box = MGPipeBoxOfDirtyRegion(oracle[i]);
EXPECT_TRUE(regions[i].X == box.X && regions[i].Y == box.Y && regions[i].Z == box.Z &&
regions[i].W == box.W && regions[i].H == box.H && regions[i].D == box.D)
EXPECT_TRUE(regions[i].X == box.X && regions[i].Y == box.Y && regions[i].Z == box.Z && regions[i].W == box.W &&
regions[i].H == box.H && regions[i].D == box.D)
<< "region " << i << " is not footprint box " << i;
}
}
@@ -575,8 +568,7 @@ TEST(TextureEmit, MoreThanKMaxDirtyRectsCollapsesToTheBoxWithRegionCountZero) {
const auto texture = MakeTexture2D(91, 256);
for (Int y = 0; y < 256; y += 2) {
for (Int x = 0; x < 256; x += 2) {
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{x, y, 0},
IntVec3{1, 1, 1});
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{x, y, 0}, IntVec3{1, 1, 1});
}
}
Vector<MipmapDirtyRegion> footprint;
@@ -584,8 +576,8 @@ TEST(TextureEmit, MoreThanKMaxDirtyRectsCollapsesToTheBoxWithRegionCountZero) {
ASSERT_GT(footprint.size(), static_cast<SizeT>(kMGPipeMaxPendingUploadRegions))
<< "the writes must outgrow one record, or this case pins the footprint path instead";
MipmapDirtyRegion oracle[MipmapStorage::kMaxDirtyRects];
const SizeT oracleCount = texture->GetStorageDirtyRects(TextureUploadTarget::Texture2D, 0, oracle,
MipmapStorage::kMaxDirtyRects);
const SizeT oracleCount =
texture->GetStorageDirtyRects(TextureUploadTarget::Texture2D, 0, oracle, MipmapStorage::kMaxDirtyRects);
EXPECT_LE(oracleCount, MipmapStorage::kMaxDirtyRects);
Textures().DrainTextureSubData(Ctx());
EXPECT_EQ(Textures().LastSubData().RegionCount, static_cast<Uint32>(oracleCount))
@@ -648,28 +640,23 @@ TEST(TextureEmit, ALevelTooLargeForTheStageChunkIsCutIntoSlabs) {
// exactly once, in order, each within the cap and each exactly its own box's byte extent.
const auto cut = [&](const IntVec3& levelSize, Uint64 levelBytes, SizeT chunk) {
std::vector<MGPipeTextureSlab> slabs;
const MGPipeLevelPitch pitch =
MGPipeLevelPitchOf(levelSize, static_cast<SizeT>(levelBytes));
const MGPipeLevelPitch pitch = MGPipeLevelPitchOf(levelSize, static_cast<SizeT>(levelBytes));
EXPECT_TRUE(MGPipeForEachTextureSlab(levelSize, pitch, levelBytes, chunk,
[&](const MGPipeTextureSlab& slab) {
slabs.push_back(slab);
}));
EXPECT_GE(slabs.size(), 2u) << "a level of " << levelBytes << " bytes was not cut at a "
<< chunk << " byte cap";
[&](const MGPipeTextureSlab& slab) { slabs.push_back(slab); }));
EXPECT_GE(slabs.size(), 2u) << "a level of " << levelBytes << " bytes was not cut at a " << chunk
<< " byte cap";
Uint64 expectedOffset = 0;
Uint64 covered = 0;
for (const MGPipeTextureSlab& slab : slabs) {
EXPECT_GT(slab.RunBytes, 0u);
EXPECT_LE(slab.RunBytes, static_cast<Uint64>(chunk)) << "a piece is bigger than the cap";
EXPECT_EQ(slab.RunOffset, expectedOffset)
<< "the pieces are not contiguous and ascending";
EXPECT_EQ(slab.RunOffset, expectedOffset) << "the pieces are not contiguous and ascending";
expectedOffset += slab.RunBytes;
covered += slab.RunBytes;
const Uint64 boxBytes = static_cast<Uint64>(slab.Box.D - 1) * pitch.SliceStride +
static_cast<Uint64>(slab.Box.H - 1) * pitch.RowStride +
static_cast<Uint64>(slab.Box.W) * pitch.BytesPerTexel;
EXPECT_EQ(boxBytes, slab.RunBytes)
<< "the box does not describe the run, so the far side cannot place it";
EXPECT_EQ(boxBytes, slab.RunBytes) << "the box does not describe the run, so the far side cannot place it";
}
EXPECT_EQ(covered, levelBytes) << "the pieces do not cover the level exactly once";
return slabs;
@@ -735,15 +722,11 @@ TEST(TextureEmit, ALevelTooLargeForTheStageChunkIsCutIntoSlabs) {
// split existed: no cap at all, a pitch that does not tile the level's bytes exactly, and a cap
// below one texel.
std::vector<MGPipeTextureSlab> refusals;
const auto refuses = [&](const IntVec3& levelSize, const MGPipeLevelPitch& pitch,
Uint64 levelBytes, SizeT chunk) {
const auto refuses = [&](const IntVec3& levelSize, const MGPipeLevelPitch& pitch, Uint64 levelBytes, SizeT chunk) {
return !MGPipeForEachTextureSlab(levelSize, pitch, levelBytes, chunk,
[&](const MGPipeTextureSlab& slab) {
refusals.push_back(slab);
});
[&](const MGPipeTextureSlab& slab) { refusals.push_back(slab); });
};
const MGPipeLevelPitch volumePitch =
MGPipeLevelPitchOf(volume, static_cast<SizeT>(volumeBytes));
const MGPipeLevelPitch volumePitch = MGPipeLevelPitchOf(volume, static_cast<SizeT>(volumeBytes));
const MGPipeLevelPitch linePitch = MGPipeLevelPitchOf(line, static_cast<SizeT>(lineBytes));
EXPECT_TRUE(refuses(volume, volumePitch, volumeBytes, 0));
EXPECT_TRUE(refuses(volume, volumePitch, volumeBytes + 1, cap))
@@ -755,11 +738,11 @@ TEST(TextureEmit, ALevelTooLargeForTheStageChunkIsCutIntoSlabs) {
// the piece's own run (MGPipeTypes.h: SrcOffset is "into the blob") and the LEVEL's pitches
// kept. A slab the dirty set does not reach still carries its own box as ONE region.
const MGPBox dirty[5] = {
{0, 0, 0, 512, 128, 1}, // the whole first slice, inside slab 0
{0, 0, 4, 64, 64, 1}, // a small rect in the middle of slab 0
{10, 20, 8, 64, 64, 2}, // a rect spanning the first two slices of slab 1
{460, 100, 7, 64, 64, 3}, // clipped on X, Y and the slab-0/slab-1 boundary
{0, 0, 32, 512, 128, 1}, // the last slice, inside slab 4
{0, 0, 0, 512, 128, 1}, // the whole first slice, inside slab 0
{0, 0, 4, 64, 64, 1}, // a small rect in the middle of slab 0
{10, 20, 8, 64, 64, 2}, // a rect spanning the first two slices of slab 1
{460, 100, 7, 64, 64, 3}, // clipped on X, Y and the slab-0/slab-1 boundary
{0, 0, 32, 512, 128, 1}, // the last slice, inside slab 4
};
SizeT regionCounts[5] = {0, 0, 0, 0, 0};
for (SizeT i = 0; i < volumeSlabs.size(); ++i) {
@@ -772,21 +755,17 @@ TEST(TextureEmit, ALevelTooLargeForTheStageChunkIsCutIntoSlabs) {
const MGPSubRegion& region = regions[r];
EXPECT_EQ(region.SrcRowStride, volumePitch.RowStride);
EXPECT_EQ(region.SrcSliceStride, volumePitch.SliceStride);
EXPECT_EQ(region.SrcOffset,
static_cast<Uint64>(region.Z - slab.Box.Z) * volumePitch.SliceStride +
static_cast<Uint64>(region.Y - slab.Box.Y) * volumePitch.RowStride +
static_cast<Uint64>(region.X - slab.Box.X) * volumePitch.BytesPerTexel)
EXPECT_EQ(region.SrcOffset, static_cast<Uint64>(region.Z - slab.Box.Z) * volumePitch.SliceStride +
static_cast<Uint64>(region.Y - slab.Box.Y) * volumePitch.RowStride +
static_cast<Uint64>(region.X - slab.Box.X) * volumePitch.BytesPerTexel)
<< "SrcOffset is not relative to the piece's own run";
EXPECT_GE(region.X, slab.Box.X);
EXPECT_GE(region.Y, slab.Box.Y);
EXPECT_GE(region.Z, slab.Box.Z);
EXPECT_LE(region.X + static_cast<Int32>(region.W),
slab.Box.X + static_cast<Int32>(slab.Box.W))
EXPECT_LE(region.X + static_cast<Int32>(region.W), slab.Box.X + static_cast<Int32>(slab.Box.W))
<< "a clipped rect reaches outside the piece's box";
EXPECT_LE(region.Y + static_cast<Int32>(region.H),
slab.Box.Y + static_cast<Int32>(slab.Box.H));
EXPECT_LE(region.Z + static_cast<Int32>(region.D),
slab.Box.Z + static_cast<Int32>(slab.Box.D));
EXPECT_LE(region.Y + static_cast<Int32>(region.H), slab.Box.Y + static_cast<Int32>(slab.Box.H));
EXPECT_LE(region.Z + static_cast<Int32>(region.D), slab.Box.Z + static_cast<Int32>(slab.Box.D));
}
}
// Slab 0 sees three rects (one of them clipped at its own z end), slab 1 two, slabs 2 and 3
@@ -819,10 +798,9 @@ TEST(TextureEmit, ALevelTooLargeForTheStageChunkIsCutIntoSlabs) {
EXPECT_EQ(regions[i].H, 28u);
EXPECT_EQ(regions[i].Z, 7);
EXPECT_EQ(regions[i].D, 1u);
EXPECT_EQ(regions[i].SrcOffset,
static_cast<Uint64>(7) * volumePitch.SliceStride +
static_cast<Uint64>(100) * volumePitch.RowStride +
static_cast<Uint64>(460) * volumePitch.BytesPerTexel);
EXPECT_EQ(regions[i].SrcOffset, static_cast<Uint64>(7) * volumePitch.SliceStride +
static_cast<Uint64>(100) * volumePitch.RowStride +
static_cast<Uint64>(460) * volumePitch.BytesPerTexel);
}
}
EXPECT_TRUE(sawClippedRect) << "a rect wider than the level was not clipped to the piece";
@@ -841,8 +819,7 @@ TEST(TextureEmit, AnUploadThroughAViewKeysOnTheStorageOwner) {
ASSERT_FALSE(ownerHandle == viewHandle);
// ViewOf names the storage owner, and ONE HOP always reaches storage.
EXPECT_TRUE(Textures().LastDesc().Resource == viewHandle);
EXPECT_TRUE(Textures().LastDesc().ViewOf == ownerHandle)
<< "the view's descriptor does not name its storage owner";
EXPECT_TRUE(Textures().LastDesc().ViewOf == ownerHandle) << "the view's descriptor does not name its storage owner";
// An upload through the VIEW: TextureObjectView forwards the mark to the OWNER's method
// after remapping the level, so the drain list holds exactly one entry and it is the
@@ -862,10 +839,8 @@ TEST(TextureEmit, EveryTexturesParamsNameItsBuiltinSamplerCso) {
TextureScope scope;
const auto texture = MakeTexture2D(10, 8);
const MGPipeHandle handle = Textures().FindTexture(*texture);
texture->SetSwizzleParamRGBA(Vec4<TextureSwizzleParam>{TextureSwizzleParam::Alpha,
TextureSwizzleParam::Blue,
TextureSwizzleParam::Green,
TextureSwizzleParam::Red});
texture->SetSwizzleParamRGBA(Vec4<TextureSwizzleParam>{TextureSwizzleParam::Alpha, TextureSwizzleParam::Blue,
TextureSwizzleParam::Green, TextureSwizzleParam::Red});
const MGPTextureParams params = Textures().LastParams();
EXPECT_TRUE(params.Res == handle);
// kMGPipeNullHandle is ILLEGAL here: every texture object owns a sampler object, so a null
@@ -883,8 +858,8 @@ TEST(TextureEmit, EveryTexturesParamsNameItsBuiltinSamplerCso) {
EXPECT_GE(MGPipeSamplerCsoCacheInstance().RefCountOf(params.BuiltinSampler), 1u)
<< "the texture holds no reference on its built-in sampler, so an LRU eviction could take "
"the handle out from under a standing set_texture_params record";
EXPECT_TRUE(MGPipeHandleIsNull(MGPipeSlots().FindByLifetimeId(
MGPipeKind::SamplerCso, texture->GetSamplerObject()->GetLifetimeId())))
EXPECT_TRUE(MGPipeHandleIsNull(
MGPipeSlots().FindByLifetimeId(MGPipeKind::SamplerCso, texture->GetSamplerObject()->GetLifetimeId())))
<< "a SamplerCso slot was minted against the SamplerObject's lifetime id; the cache "
"deliberately allocates without one, so ~SamplerObject frees nothing for this kind";
EXPECT_EQ(params.Swizzle[0], static_cast<Uint8>(TextureSwizzleParam::Alpha));
@@ -1037,18 +1012,15 @@ TEST(TextureEmit, TheApplierStoresTheRegionListTheEmitterBuiltAndNotAnEmptyOne)
const MGPipeResourceRecord* stored = AppliedTexture(handle);
ASSERT_NE(stored, nullptr);
const MGPipeResourceRecord::PendingUpload* pending =
AppliedUpload(*stored, Textures().LastSubData().Target, 0);
const MGPipeResourceRecord::PendingUpload* pending = AppliedUpload(*stored, Textures().LastSubData().Target, 0);
ASSERT_NE(pending, nullptr) << "the applier accumulated no pending upload for the level";
ASSERT_EQ(pending->Regions.size(), emitted.size())
<< "the applier's stored region count is not the emitted one";
ASSERT_EQ(pending->Regions.size(), emitted.size()) << "the applier's stored region count is not the emitted one";
for (SizeT i = 0; i < pending->Regions.size(); ++i) {
EXPECT_EQ(pending->Regions[i].X, emitted[i].X) << "MGPSubRegion::X at region " << i;
EXPECT_EQ(pending->Regions[i].Y, emitted[i].Y) << "MGPSubRegion::Y at region " << i;
EXPECT_EQ(pending->Regions[i].W, emitted[i].W) << "MGPSubRegion::W at region " << i;
EXPECT_EQ(pending->Regions[i].H, emitted[i].H) << "MGPSubRegion::H at region " << i;
EXPECT_EQ(pending->Regions[i].SrcOffset, emitted[i].SrcOffset)
<< "MGPSubRegion::SrcOffset at region " << i;
EXPECT_EQ(pending->Regions[i].SrcOffset, emitted[i].SrcOffset) << "MGPSubRegion::SrcOffset at region " << i;
EXPECT_EQ(pending->Regions[i].SrcRowStride, emitted[i].SrcRowStride)
<< "MGPSubRegion::SrcRowStride at region " << i;
EXPECT_EQ(pending->Regions[i].SrcSliceStride, emitted[i].SrcSliceStride)
@@ -1126,8 +1098,7 @@ TEST(TextureEmit, WithNoBackendConsumerTheFamilyGateIsFalseAndNothingReachesTheA
// All four families, because all four ride the one signal (D-D1: a texture and a
// renderbuffer ARE resource rows, and the other three name texture handles).
EXPECT_FALSE(
MGPipeP4aFamilyEmits(kMGPipeSubsystemTextureResources, kMGPipeWiredTextureSubsystem));
EXPECT_FALSE(MGPipeP4aFamilyEmits(kMGPipeSubsystemTextureResources, kMGPipeWiredTextureSubsystem));
EXPECT_FALSE(MGPipeP4aFamilyEmits(kMGPipeSubsystemFramebuffer, kMGPipeSubsystemFramebuffer));
EXPECT_FALSE(MGPipeP4aFamilyEmits(kMGPipeSubsystemSamplers, kMGPipeSubsystemSamplers));
EXPECT_FALSE(MGPipeP4aFamilyEmits(kMGPipeSubsystemPrograms, kMGPipeSubsystemPrograms));
@@ -1154,8 +1125,7 @@ TEST(TextureEmit, WithNoBackendConsumerTheFamilyGateIsFalseAndNothingReachesTheA
EXPECT_EQ(Textures().RespecifyCount(), 0u);
EXPECT_TRUE(MGPipeApplier().TextureResources.empty());
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0},
IntVec3{8, 8, 1});
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0}, IntVec3{8, 8, 1});
EXPECT_EQ(Textures().DrainListSize(), 0u) << "a level was queued for a drain that has no consumer";
EXPECT_EQ(Textures().SubDataCount(), 0u);
// THE ONE THAT MATTERED. The frontend's flag is what Magma's legacy path uploads from,
@@ -1176,8 +1146,7 @@ TEST(TextureEmit, WithNoBackendConsumerTheFamilyGateIsFalseAndNothingReachesTheA
ASSERT_FALSE(MGPipeHandleIsNull(live));
EXPECT_TRUE(MGPipeHandleIsPublished(MGPipeKind::Texture, live));
EXPECT_GT(Textures().CreateCount(), 0u);
consumed->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0},
IntVec3{8, 8, 1});
consumed->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0}, IntVec3{8, 8, 1});
EXPECT_EQ(Textures().DrainListSize(), 1u);
Textures().DrainTextureSubData(Ctx());
EXPECT_EQ(Textures().SubDataCount(), 1u);
@@ -1223,8 +1192,7 @@ TEST(TextureEmit, WithTheSamplerBitClearTheTextureFamilyGateIsFalseAndNothingRea
EXPECT_EQ(Textures().RespecifyCount(), 0u);
EXPECT_TRUE(MGPipeApplier().TextureResources.empty());
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0},
IntVec3{8, 8, 1});
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0}, IntVec3{8, 8, 1});
EXPECT_EQ(Textures().DrainListSize(), 0u);
Textures().DrainTextureSubData(Ctx());
EXPECT_EQ(Textures().SubDataCount(), 0u);
@@ -1244,8 +1212,7 @@ TEST(TextureEmit, WithTheSamplerBitClearTheTextureFamilyGateIsFalseAndNothingRea
const MGPipeHandle liveHandle = Textures().FindTexture(*live);
ASSERT_FALSE(MGPipeHandleIsNull(liveHandle));
EXPECT_TRUE(MGPipeHandleIsPublished(MGPipeKind::Texture, liveHandle));
live->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0},
IntVec3{8, 8, 1});
live->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0}, IntVec3{8, 8, 1});
EXPECT_EQ(Textures().DrainListSize(), 1u);
Textures().DrainTextureSubData(Ctx());
EXPECT_EQ(Textures().SubDataCount(), 1u);
@@ -1273,8 +1240,7 @@ TEST(TextureEmit, WithTheBufferResourceBitClearTheTextureFamilyGateIsFalseAndNot
EXPECT_EQ(Textures().RespecifyCount(), 0u);
EXPECT_TRUE(MGPipeApplier().TextureResources.empty());
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0},
IntVec3{8, 8, 1});
texture->MarkStorageDirtyRegion(TextureUploadTarget::Texture2D, 0, IntVec3{0, 0, 0}, IntVec3{8, 8, 1});
EXPECT_EQ(Textures().DrainListSize(), 0u);
Textures().DrainTextureSubData(Ctx());
EXPECT_EQ(Textures().SubDataCount(), 0u);
@@ -1298,9 +1264,8 @@ TEST(TextureEmit, WithTheBufferResourceBitClearTheTextureFamilyGateIsFalseAndNot
TEST(TextureEmit, EveryDKTwoDependencyRowGatesItsOwnFamilyAndTheMirrorPairsStayLive) {
TextureScope scope;
const auto emits = [](Uint64 family) { return MGPipeP4aFamilyEmits(family, family); };
const Uint64 kAll = kMGPipeSubsystemResources | kMGPipeSubsystemFramebuffer |
kMGPipeSubsystemTextureResources | kMGPipeSubsystemSamplers |
kMGPipeSubsystemPrograms;
const Uint64 kAll = kMGPipeSubsystemResources | kMGPipeSubsystemFramebuffer | kMGPipeSubsystemTextureResources |
kMGPipeSubsystemSamplers | kMGPipeSubsystemPrograms;
// ---- every dependency satisfied: all four families live ----
MG_Config::Features.PipePush = kAll;
@@ -1420,8 +1385,7 @@ TEST(TextureEmit, ALodWriteOnTheBuiltinSamplerRepublishesTheParams) {
// NOTHING MOVED: the version-first skip reads both counters and emits nothing.
MG_Pipe::MGPipeEmitTextureParams(*texture);
EXPECT_EQ(Textures().ParamCount(), paramsBefore)
<< "an unchanged texture re-emitted its parameters";
EXPECT_EQ(Textures().ParamCount(), paramsBefore) << "an unchanged texture re-emitted its parameters";
// A WRITE THAT ONLY THE SAMPLER OBJECT SEES.
const Uint16 textureVersionBefore = texture->GetTextureParamsVersion();
@@ -1533,8 +1497,7 @@ TEST(TextureEmit, ALevelMarkedCleanIsCollectedAtTheNextDrain) {
EXPECT_EQ(Textures().DrainListSize(), 1u) << "the entry is collected at the drain, not here";
const Uint64 emissionsBefore = Textures().SubDataCount();
Textures().DrainTextureSubData(Ctx());
EXPECT_EQ(Textures().SubDataCount(), emissionsBefore)
<< "a level that is no longer dirty was uploaded anyway";
EXPECT_EQ(Textures().SubDataCount(), emissionsBefore) << "a level that is no longer dirty was uploaded anyway";
EXPECT_EQ(Textures().DrainListSize(), 0u) << "the clean level was never collected";
// And the key really was dropped from the per-slot list, so a later write re-appends.
@@ -1578,7 +1541,8 @@ TEST(TextureEmit, ALevelDefinedAfterAnEmittedButUnconsumedUploadKeepsThatUpload)
EXPECT_TRUE(levelZeroPending)
<< "defining level 1 dropped level 0's accepted-but-unconsumed pending upload (PendingUploads.size()="
<< record->PendingUploads.size() << ") while level 0's client dirty flag is "
<< (texture->IsStorageDirty(TextureUploadTarget::Texture2D, 0) ? "set" : "CLEAR - the texels are owed by nobody");
<< (texture->IsStorageDirty(TextureUploadTarget::Texture2D, 0) ? "set"
: "CLEAR - the texels are owed by nobody");
// And after the next drain both levels stand in the set.
Textures().DrainTextureSubData(Ctx());
record = AppliedTexture(handle);
@@ -1913,9 +1877,8 @@ TEST(TextureEmit, ATextureInASecondShareGroupNamesABuiltinSamplerItsOwnGroupHold
const MGPipeHandle sampler = record->Params.BuiltinSampler;
const auto& samplers = MGPipeApplier().SamplerCsos;
ASSERT_FALSE(MGPipeHandleIsNull(sampler));
ASSERT_LT(sampler.Slot, samplers.size())
<< "the texture names built-in sampler {" << sampler.Slot << ", " << sampler.Gen
<< "}, which its share group's applier was never sent";
ASSERT_LT(sampler.Slot, samplers.size()) << "the texture names built-in sampler {" << sampler.Slot << ", "
<< sampler.Gen << "}, which its share group's applier was never sent";
EXPECT_TRUE(samplers[sampler.Slot].Live && samplers[sampler.Slot].Gen == sampler.Gen)
<< "the texture names built-in sampler {" << sampler.Slot << ", " << sampler.Gen
<< "}, which its share group's applier was never sent";
@@ -1927,7 +1890,6 @@ TEST(TextureEmit, ATextureInASecondShareGroupNamesABuiltinSamplerItsOwnGroupHold
first.reset();
}
// =========================================================================================
// The APPLIER's half of the texture family (the wire commits'): set_texture_params on the
// texture's own record, and the sub-data validator plus the pending-upload set that replaces
@@ -2158,16 +2120,13 @@ TEST(TextureEmit, TheSubDataValidatorRefusesALevelABoxAndARegionTheRecordCannotD
const MGPSubData escapes = TextureUpload(texture, 0, MGPBox{0, 0, 0, 8, 8, 1}, 1);
ExpectRefusedNaming("resource_subdata {slot=5, gen=2, glName=99}: a sub-region is not inside the union "
"box the record declares",
[&escapes, &texels, &outside]() {
MGPipeApplyResourceSubData(escapes, texels, outside);
});
[&escapes, &texels, &outside]() { MGPipeApplyResourceSubData(escapes, texels, outside); });
const MGPSubData nothing = TextureUpload(texture, 0, MGPBox{0, 0, 0, 0, 0, 0}, 0);
ExpectRefusedNaming("resource_subdata {slot=5, gen=2, glName=99}: the record describes no texels at all",
[&nothing, &texels]() { MGPipeApplyResourceSubData(nothing, texels); });
EXPECT_EQ(TextureRecordOf(5).PendingUploads.size(), 1u)
<< "a refused record was accumulated anyway";
EXPECT_EQ(TextureRecordOf(5).PendingUploads.size(), 1u) << "a refused record was accumulated anyway";
EXPECT_EQ(TextureRecordOf(5).Serial, serialBefore) << "not one refusal may move the serial";
}
@@ -2188,8 +2147,7 @@ TEST(TextureEmit, ARespecifyDropsThePendingUploadsAgainstTheStorageItReplaces) {
ASSERT_EQ(TextureRecordOf(3).PendingUploads.size(), 2u);
MGPipeApplyResourceRespecify(TextureDesc(texture, 8, 55), nullptr);
EXPECT_TRUE(TextureRecordOf(3).PendingUploads.empty())
<< "a 64-wide box survived onto an 8-wide store";
EXPECT_TRUE(TextureRecordOf(3).PendingUploads.empty()) << "a 64-wide box survived onto an 8-wide store";
EXPECT_EQ(TextureRecordOf(3).Desc.Width, 8u);
}
@@ -2301,10 +2259,10 @@ TEST(TextureEmit, ARespecifyOfOneCubeFaceKeepsTheOtherFacesUploadOfTheSameLevel)
// The packed Target's two bytes (ID-12): low = the RESOURCE target, high = the per-call
// UPLOAD target, which for a cube map is the FACE. Both faces below name the same resource
// target and the same level and differ only in the face, which is the whole point.
const Uint16 positiveX = MGPipePackSubDataTarget(
kTexCube, static_cast<Uint32>(TextureUploadTarget::CubeMapPositiveX));
const Uint16 negativeX = MGPipePackSubDataTarget(
kTexCube, static_cast<Uint32>(TextureUploadTarget::CubeMapNegativeX));
const Uint16 positiveX =
MGPipePackSubDataTarget(kTexCube, static_cast<Uint32>(TextureUploadTarget::CubeMapPositiveX));
const Uint16 negativeX =
MGPipePackSubDataTarget(kTexCube, static_cast<Uint32>(TextureUploadTarget::CubeMapNegativeX));
ASSERT_NE(positiveX, negativeX);
ASSERT_EQ(MGPipeSubDataResourceTargetOf(positiveX), MGPipeSubDataResourceTargetOf(negativeX))
<< "the two faces must differ in the UPLOAD byte alone, or this case would be measuring "
@@ -2388,8 +2346,7 @@ TEST(TextureEmit, TheSubDataCallAnswersWhetherTheRecordWasAcceptedSoTheClientCan
// A stale generation is the refusal that is NOT a Fatal, so it is the one the answer has to
// carry: the record is gone, the texels were never taken, and the flag may not be cleared.
const Uint64 refusedBefore = MGPipeApplier().RefusedResourceCalls;
EXPECT_FALSE(
MGPipeApplyResourceSubData(TextureUpload(MGPipeHandle{8, 2}, 0, MGPBox{0, 0, 0, 8, 8, 1}, 0), texels))
EXPECT_FALSE(MGPipeApplyResourceSubData(TextureUpload(MGPipeHandle{8, 2}, 0, MGPBox{0, 0, 0, 8, 8, 1}, 0), texels))
<< "a refused upload answered 'accepted' and the client would clear a flag nothing owes";
EXPECT_EQ(MGPipeApplier().RefusedResourceCalls, refusedBefore + 1);
EXPECT_EQ(TextureRecordOf(8).PendingUploads.size(), 1u);
@@ -2442,9 +2399,7 @@ TEST(TextureEmit, ASubDataRecordWhoseResourceTargetNamesNoTextureIsRefusedRather
pastTheCatalogue.Target = static_cast<Uint16>(MGPipeResourceTarget::Count);
ExpectRefusedNaming("resource_subdata {slot=9, gen=1}: the record's resource target names no texture "
"to upload into",
[&pastTheCatalogue, &texels]() {
MGPipeApplyResourceSubData(pastTheCatalogue, texels);
});
[&pastTheCatalogue, &texels]() { MGPipeApplyResourceSubData(pastTheCatalogue, texels); });
MGPSubData packedBuffer = renderbuffer;
packedBuffer.Target = static_cast<Uint16>(0x0100u | kMGPipeResourceTargetBuffer);
@@ -2508,7 +2463,7 @@ TEST(TextureEmit, ARespecifyThatRedefinesNoStorageCarriesTheStickyMaskAndKeepsTh
// glTexStorage2D: an IMMUTABLE store, which is the whole reason this arm exists.
MGPResourceDesc allocated = TextureDesc(texture, 64, 151);
allocated.Immutable = 1;
allocated.Levels = 2; // level 1 exists for the named-level clause below
allocated.Levels = 2; // level 1 exists for the named-level clause below
allocated.InternalFormat = 0x8058u; // GL_RGBA8
allocated.BindMask = static_cast<Uint16>(kMGPipeBindSampler);
ASSERT_TRUE(MGPipeApplyResourceRespecify(allocated, nullptr));
+37 -50
View File
@@ -71,7 +71,7 @@ namespace {
}
using GLContext = MG_State::GLState::GLContext;
using MG_State::GLState::TextureObjectBase;
using MobileGL::TextureTarget;
@@ -128,7 +128,8 @@ namespace {
TEST_F(TrackerAggregates, EveryAggregateStartsAtZero) {
const Snapshot s = Snap();
for (SizeT i = 0; i < kAggregateCount; ++i) EXPECT_EQ(s.Values[i], 0ull);
for (SizeT i = 0; i < kAggregateCount; ++i)
EXPECT_EQ(s.Values[i], 0ull);
}
TEST_F(TrackerAggregates, AVertexArrayAttributeMovesOnlyTheVaoAggregate) {
@@ -295,12 +296,10 @@ namespace {
++m_binds;
}
if (dirty & MGPipeDirtyBit(MGPipeDirty::NewRenderState)) {
m_lastDynamicMask = m_tracker.FreshlyPrimed()
? ~0u
: MGPipeDynamicChunksThatMoved(live, m_tracker.Staged());
m_lastDynamicMask =
m_tracker.FreshlyPrimed() ? ~0u : MGPipeDynamicChunksThatMoved(live, m_tracker.Staged());
}
if (dirty & (MGPipeDirtyBit(MGPipeDirty::NewPipelineState) |
MGPipeDirtyBit(MGPipeDirty::NewRenderState))) {
if (dirty & (MGPipeDirtyBit(MGPipeDirty::NewPipelineState) | MGPipeDirtyBit(MGPipeDirty::NewRenderState))) {
m_tracker.Staged() = live;
}
return dirty;
@@ -356,22 +355,17 @@ namespace {
// escalation, docs/archive/contracts/CONTRACT-P5E.md §5.7) and still names the subsystem, for the
// same reason: the bit answers "which A/B switch owns this family's legacy arm", not
// "is there a record on the wire for me today".
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewConstBuffers),
kMGPipeSubsystemBufferBindings);
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewShaderBuffers),
kMGPipeSubsystemBufferBindings);
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewSoTargets),
kMGPipeSubsystemBufferBindings);
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewConstBuffers), kMGPipeSubsystemBufferBindings);
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewShaderBuffers), kMGPipeSubsystemBufferBindings);
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewSoTargets), kMGPipeSubsystemBufferBindings);
// AND THE PHASE CONSTANT IS NOW THE WHOLE BIT SET: after P5e every dirty bit names a
// subsystem, so the loop above has no "names none" case left to exercise, and this is
// what says so rather than leaving the loop looking stronger than it is.
EXPECT_EQ(kMGPipeDirtyEmittedAtP5e,
static_cast<Uint32>((Uint64{1} << kMGPipeDirtyCount) - 1u));
EXPECT_EQ(kMGPipeDirtyEmittedAtP5e, static_cast<Uint32>((Uint64{1} << kMGPipeDirtyCount) - 1u));
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewRenderState), kMGPipeSubsystemRenderState);
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewPixelPack), kMGPipeSubsystemPixelPack);
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewPatchState), kMGPipeSubsystemPatchState);
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewVertexAttribDefaults),
kMGPipeSubsystemVertexAttribDefaults);
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewVertexAttribDefaults), kMGPipeSubsystemVertexAttribDefaults);
// P3a's three, one subsystem: an operator who clears bit 8 gets the whole legacy
// vertex-input arm rather than two thirds of it.
EXPECT_EQ(MGPipeSubsystemForDirty(MGPipeDirty::NewVertexElements), kMGPipeSubsystemVertexInput);
@@ -393,8 +387,7 @@ namespace {
// that started naming it would gate the emission twice and the two gates would
// disagree the first time one of them was edited.
for (SizeT i = 0; i < kMGPipeDirtyCount; ++i) {
EXPECT_NE(MGPipeSubsystemForDirty(static_cast<MGPipeDirty>(i)),
kMGPipeSubsystemTextureResources)
EXPECT_NE(MGPipeSubsystemForDirty(static_cast<MGPipeDirty>(i)), kMGPipeSubsystemTextureResources)
<< kMGPipeDirtyNames[i];
}
}
@@ -414,7 +407,8 @@ namespace {
Walk();
const Uint64 mintsAfterFirst = m_cache.GetCounters().Mints;
const Uint64 bindsAfterFirst = m_binds;
for (int i = 0; i < 8; ++i) EXPECT_EQ(Walk(), 0u) << "walk " << i << " fired with nothing moved";
for (int i = 0; i < 8; ++i)
EXPECT_EQ(Walk(), 0u) << "walk " << i << " fired with nothing moved";
EXPECT_EQ(m_cache.GetCounters().Mints, mintsAfterFirst);
EXPECT_EQ(m_binds, bindsAfterFirst);
}
@@ -466,7 +460,7 @@ namespace {
// RenderState's two shutters are Uint16 and the tracker widens them in its OWN state,
// never in MG_State. A wrap must cost an extra re-push at worst and never a missed one.
TEST_F(TrackerWalk, WrapAroundRePushesButNeverMisses) {
Walk(); // prime
Walk(); // prime
constexpr int kMoves = 70000; // past 65535 with room to spare
Uint64 fired = 0;
for (int i = 0; i < kMoves; ++i) {
@@ -475,8 +469,7 @@ namespace {
Ctx().SetLineWidth((i & 1) ? 2.0f : 3.0f);
if (Walk() & MGPipeDirtyBit(MGPipeDirty::NewRenderState)) ++fired;
}
EXPECT_EQ(fired, static_cast<Uint64>(kMoves))
<< "a Uint16 wrap swallowed a render-state change";
EXPECT_EQ(fired, static_cast<Uint64>(kMoves)) << "a Uint16 wrap swallowed a render-state change";
m_cache.Reset();
}
@@ -502,8 +495,7 @@ namespace {
// itself, which float equality does not do and a byte compare does.
TEST_F(TrackerWalk, ANaNPatchLevelEqualsItselfAndDoesNotFireForever) {
Walk(); // prime
Ctx().SetPatchDefaultOuterLevel(
FloatVec4(std::numeric_limits<Float>::quiet_NaN(), 1.0f, 1.0f, 1.0f));
Ctx().SetPatchDefaultOuterLevel(FloatVec4(std::numeric_limits<Float>::quiet_NaN(), 1.0f, 1.0f, 1.0f));
EXPECT_NE(Walk() & MGPipeDirtyBit(MGPipeDirty::NewPatchState), 0u);
EXPECT_EQ(Walk() & MGPipeDirtyBit(MGPipeDirty::NewPatchState), 0u)
<< "a NaN patch level re-fired against itself";
@@ -518,8 +510,7 @@ namespace {
EXPECT_EQ(Walk() & MGPipeDirtyBit(MGPipeDirty::NewPixelPack), 0u);
// The UNPACK half has no carrier at all, so it must not move the pack shutter.
Ctx().SetPixelStoreParam(PixelStoreParam::UnpackAlignment, 8);
EXPECT_EQ(Walk() & MGPipeDirtyBit(MGPipeDirty::NewPixelPack), 0u)
<< "an unpack write moved the PACK shutter";
EXPECT_EQ(Walk() & MGPipeDirtyBit(MGPipeDirty::NewPixelPack), 0u) << "an unpack write moved the PACK shutter";
m_cache.Reset();
}
@@ -600,8 +591,7 @@ namespace {
Walk();
Walk();
const Uint32 family = MGPipeDirtyBit(MGPipeDirty::NewConstBuffers) |
MGPipeDirtyBit(MGPipeDirty::NewShaderBuffers) |
MGPipeDirtyBit(MGPipeDirty::NewSoTargets);
MGPipeDirtyBit(MGPipeDirty::NewShaderBuffers) | MGPipeDirtyBit(MGPipeDirty::NewSoTargets);
ASSERT_EQ(m_tracker.LastDirty() & family, 0u)
<< "the steady state must be quiet before the interesting half of this case";
@@ -656,7 +646,8 @@ namespace {
TEST_F(TrackerWalk, TheIndexBufferBitFiresWhenTheSlotVersionWrapsOntoADifferentBuffer) {
const SharedPtr<MG_State::GLState::BufferObject> objects[3] = {
Ctx().CreateBufferObject(1), Ctx().CreateBufferObject(2), Ctx().CreateBufferObject(3)};
for (const auto& object : objects) object->Respecify(64, nullptr);
for (const auto& object : objects)
object->Respecify(64, nullptr);
auto& slot = Ctx().GetBoundVertexArray()->GetIndexBufferBindingSlot();
slot.Bind(objects[0]);
@@ -673,7 +664,8 @@ namespace {
// the version and the bound object share a parity - 65536 changes always land back on
// the object they started from, and the wrap is unobservable. Cycling three lands on
// objects[65536 % 3] == objects[1] at exactly the same raw version.
for (Uint32 i = 1; i <= 65536u; ++i) slot.Bind(objects[i % 3]);
for (Uint32 i = 1; i <= 65536u; ++i)
slot.Bind(objects[i % 3]);
ASSERT_EQ(slot.GetVersion(), versionAtStart) << "the version did not come back round";
ASSERT_EQ(slot.GetBoundObject(), objects[1]) << "the binding did not land on a different buffer";
@@ -962,8 +954,7 @@ namespace {
// frontend's converted int view travels too - 1.5f's int VIEW is 1, and the carrier
// that used to send the float bits into all three views would be sending 0x3FC00000
// where the frontend holds 1.
EXPECT_EQ(value.IntView[0],
static_cast<Uint32>(Ctx().GetCurrentVertexAttribute(3).intValue[0]));
EXPECT_EQ(value.IntView[0], static_cast<Uint32>(Ctx().GetCurrentVertexAttribute(3).intValue[0]));
EXPECT_NE(value.FloatView[0], value.IntView[0]);
}
@@ -1039,16 +1030,16 @@ namespace {
};
TEST_F(TrackerShippedEmitter, CollidingVaoShuttersStillPublishTheCurrentElementsAndBufferWindow) {
MG_Config::Features.PipePush = kMGPipeSubsystemsMigratedAtP2 | kMGPipeSubsystemResources |
kMGPipeSubsystemVertexInput;
MG_Config::Features.PipePush =
kMGPipeSubsystemsMigratedAtP2 | kMGPipeSubsystemResources | kMGPipeSubsystemVertexInput;
using MG_State::GLState::VertexArrayObject;
const SharedPtr<VertexArrayObject> a = Ctx().CreateVertexArrayObject(1);
const SharedPtr<VertexArrayObject> b = Ctx().CreateVertexArrayObject(2);
const auto buffer = Ctx().CreateBufferObject(1);
buffer->Respecify(256, nullptr);
for (Uint location : {0u, 1u}) {
a->SetAttributeFormat(location, location == 0 ? 3 : 2, DataType::Float32, false, 20,
location == 0 ? 0 : 12, false);
a->SetAttributeFormat(location, location == 0 ? 3 : 2, DataType::Float32, false, 20, location == 0 ? 0 : 12,
false);
a->BindAttributeBuffer(location, buffer);
a->EnableAttribute(location);
}
@@ -1070,8 +1061,8 @@ namespace {
const Uint32 firstB = b->GetConfigVersion() + 1;
for (Uint32 candidate = firstA; candidate < firstA + 4096; ++candidate) {
const Uint64 hash = oldMix(a->GetLifetimeId(), candidate);
const Uint64 other = (hash ^ b->GetLifetimeId()) - kCombine -
(b->GetLifetimeId() << 6) - (b->GetLifetimeId() >> 2);
const Uint64 other =
(hash ^ b->GetLifetimeId()) - kCombine - (b->GetLifetimeId() << 6) - (b->GetLifetimeId() >> 2);
if (other < firstB || other >= firstB + 4096) continue;
versionA = candidate;
versionB = static_cast<Uint32>(other);
@@ -1082,8 +1073,7 @@ namespace {
// Change a disabled attribute, leaving the enabled 0/1 versus 0
// windows intact. No private lifetime/version field is overwritten.
while (vao.GetConfigVersion() < version) {
vao.SetAttributeFormat(31, 4, DataType::Float32, !vao.GetAttribute(31).Normalized,
16, 0, false);
vao.SetAttributeFormat(31, 4, DataType::Float32, !vao.GetAttribute(31).Normalized, 16, 0, false);
}
};
advanceConfig(*a, versionA);
@@ -1099,8 +1089,7 @@ namespace {
// shutter leaves A bound with attribute 1 still enabled: the phone's
// exact "buffer-window location=1 window=0+1" mismatch.
advanceConfig(*b, versionB);
ASSERT_EQ(oldMix(a->GetLifetimeId(), a->GetConfigVersion()),
oldMix(b->GetLifetimeId(), b->GetConfigVersion()));
ASSERT_EQ(oldMix(a->GetLifetimeId(), a->GetConfigVersion()), oldMix(b->GetLifetimeId(), b->GetConfigVersion()));
Ctx().BindVertexArray(2);
Draw();
const MGPipeHandle handleB = MGPipeApplier().BoundVertexElements;
@@ -1225,9 +1214,8 @@ namespace {
MG_State::pGLContext = MakeUnique<GLContext>();
Draw();
const MGPVertexAttribDefaults header = MGPipeVertexAttribDefaultsLastHeader();
EXPECT_EQ(header.Count, 32u)
<< "a fresh context published " << header.Count
<< " attribute defaults; the server's mirror still holds the previous context's";
EXPECT_EQ(header.Count, 32u) << "a fresh context published " << header.Count
<< " attribute defaults; the server's mirror still holds the previous context's";
EXPECT_EQ(header.Mask, 0xFFFFFFFFu);
}
@@ -1273,8 +1261,8 @@ namespace {
// BaseInstance in, or the SECOND draw at a different base instance over the same buffer
// set would be suppressed as unchanged and the server would keep the first one's shift.
TEST_F(TrackerShippedEmitter, ABaseInstancedDrawAfterAMakeCurrentPublishesItsOwnBaseInstance) {
MG_Config::Features.PipePush = kMGPipeSubsystemsMigratedAtP2 | kMGPipeSubsystemResources |
kMGPipeSubsystemVertexInput;
MG_Config::Features.PipePush =
kMGPipeSubsystemsMigratedAtP2 | kMGPipeSubsystemResources | kMGPipeSubsystemVertexInput;
Draw(); // prime this context, so the switch below is a real make-current
ASSERT_EQ(MGPipeApplier().VertexFetchBaseInstance, 0u);
@@ -1296,8 +1284,7 @@ namespace {
EXPECT_EQ(MGPipeApplier().VertexBufferCount, 1u);
const Uint64 hashAtSeven = MGPipeVertexInputEmitterInstance().LastVertexBuffers().ContentHash;
EXPECT_EQ(hashAtSeven,
MGPipeVertexBufferSetContentHash(MGPipeVertexInputEmitterInstance().LastEntries().data(), 0,
1, 7))
MGPipeVertexBufferSetContentHash(MGPipeVertexInputEmitterInstance().LastEntries().data(), 0, 1, 7))
<< "the emitted set's ContentHash does not include the base instance it went out with";
// CONSUMED by the verb that carried it: the next plain draw sees 0 again, and the
+19 -18
View File
@@ -151,8 +151,12 @@ namespace {
SharedPtr<GLContext> m_previousContext;
};
GLContext& Ctx() { return *MG_State::pGLContext; }
MGPipeVertexInputEmitter& Emitter() { return MGPipeVertexInputEmitterInstance(); }
GLContext& Ctx() {
return *MG_State::pGLContext;
}
MGPipeVertexInputEmitter& Emitter() {
return MGPipeVertexInputEmitterInstance();
}
const SharedPtr<VertexArrayObject>& MakeVao(Uint name) {
Ctx().CreateVertexArrayObject(name);
@@ -423,14 +427,12 @@ namespace {
ASSERT_GT(Emitter().EmitVertexBuffers(Ctx(), 3), 0u);
ASSERT_EQ(Emitter().VertexBufferSetCount(), 1u);
const Uint64 latched =
MGPipeSetHashSuppressorInstance().LastEmitted(MGPipeSuppressorSlot::SetVertexBuffers);
const Uint64 latched = MGPipeSetHashSuppressorInstance().LastEmitted(MGPipeSuppressorSlot::SetVertexBuffers);
EXPECT_NE(latched, 0u) << "0 is reserved for 'never emitted'";
EXPECT_EQ(Emitter().EmitVertexBuffers(Ctx(), 3), 0u) << "an unchanged set went out again";
EXPECT_EQ(Emitter().VertexBufferSetCount(), 1u);
EXPECT_EQ(MGPipeSetHashSuppressorInstance().LastEmitted(MGPipeSuppressorSlot::SetVertexBuffers),
latched);
EXPECT_EQ(MGPipeSetHashSuppressorInstance().LastEmitted(MGPipeSuppressorSlot::SetVertexBuffers), latched);
// A real change to the SET still goes out with the same base instance, so the
// suppression above is not simply "this slot is stuck".
@@ -487,20 +489,18 @@ namespace {
if (!declared[i].Enabled) continue;
++covered;
SCOPED_TRACE(::testing::Message() << "attribute " << i);
EXPECT_GE(i, window.Start)
<< "create_vertex_elements declares attribute " << i
<< " ENABLED but set_vertex_buffers' window starts at " << window.Start
<< ". The backend resolves no binding for it and SKIPS it, leaving the driver "
"array enabled over whatever it last pointed at (ID-95 / ruling 19)";
EXPECT_GE(i, window.Start) << "create_vertex_elements declares attribute " << i
<< " ENABLED but set_vertex_buffers' window starts at " << window.Start
<< ". The backend resolves no binding for it and SKIPS it, leaving the driver "
"array enabled over whatever it last pointed at (ID-95 / ruling 19)";
EXPECT_LT(i, window.Start + window.Count)
<< "create_vertex_elements declares attribute " << i
<< " ENABLED but set_vertex_buffers' window ends at " << (window.Start + window.Count)
<< " - the same skip, at the other end. A narrower window is the sink's "
"Fatal{ProtocolCorruption, \"SetVertexBuffers.Count\"}";
}
ASSERT_EQ(covered, 2u)
<< "the record did not declare the two attributes this case enabled, so the window "
"check above had nothing to be about";
ASSERT_EQ(covered, 2u) << "the record did not declare the two attributes this case enabled, so the window "
"check above had nothing to be about";
// And the window's own entries agree with the record about WHICH attribute each is, so
// "covered" cannot be satisfied by a window of the right LENGTH over the wrong indices.
@@ -696,10 +696,11 @@ namespace {
}
EXPECT_EQ(slots.LiveCount(MGPipeKind::VertexElementsCso), liveBefore)
<< kChurn << " vertex arrays were created and destroyed and the client kept their "
"CSO slots; under a backend that installs no death notice consumer "
"that is one SlotState, one map node and a ~1.3 KB applier record per "
"VAO, for the life of the process";
<< kChurn
<< " vertex arrays were created and destroyed and the client kept their "
"CSO slots; under a backend that installs no death notice consumer "
"that is one SlotState, one map node and a ~1.3 KB applier record per "
"VAO, for the life of the process";
// The default VAO plus one recycled slot, i.e. the churn recycles instead of growing.
EXPECT_LE(slots.HighWater(MGPipeKind::VertexElementsCso) - highWaterBefore, 3u)
<< "the CSO slot space grew with the churn instead of being recycled";
@@ -39,38 +39,36 @@ namespace {
// Shared by both modules: a fragment shader whose default uniform block holds a vec4 and,
// in the invalid one, a sampler2D next to it.
String UniformBlockFragment(Bool withSampler) {
String text =
"OpCapability Shader\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Fragment %main \"main\" %out\n"
"OpExecutionMode %main OriginUpperLeft\n"
"OpDecorate %out Location 0\n"
"OpDecorate %Block Block\n"
"OpMemberDecorate %Block 0 Offset 0\n"
"OpDecorate %ubo DescriptorSet 0\n"
"OpDecorate %ubo Binding 0\n"
"%void = OpTypeVoid\n"
"%fn = OpTypeFunction %void\n"
"%float = OpTypeFloat 32\n"
"%v4 = OpTypeVector %float 4\n"
"%int = OpTypeInt 32 1\n"
"%zero = OpConstant %int 0\n"
"%img = OpTypeImage %float 2D 0 0 0 1 Unknown\n"
"%simg = OpTypeSampledImage %img\n";
String text = "OpCapability Shader\n"
"OpMemoryModel Logical GLSL450\n"
"OpEntryPoint Fragment %main \"main\" %out\n"
"OpExecutionMode %main OriginUpperLeft\n"
"OpDecorate %out Location 0\n"
"OpDecorate %Block Block\n"
"OpMemberDecorate %Block 0 Offset 0\n"
"OpDecorate %ubo DescriptorSet 0\n"
"OpDecorate %ubo Binding 0\n"
"%void = OpTypeVoid\n"
"%fn = OpTypeFunction %void\n"
"%float = OpTypeFloat 32\n"
"%v4 = OpTypeVector %float 4\n"
"%int = OpTypeInt 32 1\n"
"%zero = OpConstant %int 0\n"
"%img = OpTypeImage %float 2D 0 0 0 1 Unknown\n"
"%simg = OpTypeSampledImage %img\n";
text += withSampler ? "%Block = OpTypeStruct %v4 %simg\n" : "%Block = OpTypeStruct %v4\n";
text +=
"%pBlock = OpTypePointer Uniform %Block\n"
"%ubo = OpVariable %pBlock Uniform\n"
"%pv4u = OpTypePointer Uniform %v4\n"
"%pv4o = OpTypePointer Output %v4\n"
"%out = OpVariable %pv4o Output\n"
"%main = OpFunction %void None %fn\n"
"%entry = OpLabel\n"
"%ptr = OpAccessChain %pv4u %ubo %zero\n"
"%color = OpLoad %v4 %ptr\n"
"OpStore %out %color\n"
"OpReturn\n"
"OpFunctionEnd\n";
text += "%pBlock = OpTypePointer Uniform %Block\n"
"%ubo = OpVariable %pBlock Uniform\n"
"%pv4u = OpTypePointer Uniform %v4\n"
"%pv4o = OpTypePointer Output %v4\n"
"%out = OpVariable %pv4o Output\n"
"%main = OpFunction %void None %fn\n"
"%entry = OpLabel\n"
"%ptr = OpAccessChain %pv4u %ubo %zero\n"
"%color = OpLoad %v4 %ptr\n"
"OpStore %out %color\n"
"OpReturn\n"
"OpFunctionEnd\n";
return text;
}
@@ -120,8 +120,7 @@ namespace {
EXPECT_TRUE(programResult) << (programResult ? String{} : programResult.error().log);
if (!programResult) return {};
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_TESS_CONTROL_SHADER},
.program = *programResult.value()};
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_TESS_CONTROL_SHADER}, .program = *programResult.value()};
auto binaryResult = ShaderCompiler::GetSpirvBinaryFromProgram(binaryAttrib);
EXPECT_TRUE(binaryResult) << (binaryResult ? String{} : binaryResult.error().log);
if (!binaryResult || binaryResult->empty()) return {};
@@ -143,8 +142,7 @@ TEST_F(PassthroughTessControlTest, DeclaresTheRequestedPatchSize) {
for (const Uint32 patchVertices : {1u, 2u, 3u, 4u, 16u, 32u}) {
const Vector<Uint32> spirv = CompileGeneratedSource(patchVertices);
ASSERT_FALSE(spirv.empty()) << "patchVertices=" << patchVertices;
EXPECT_EQ(DeclaredOutputVertices(spirv), static_cast<Int>(patchVertices))
<< "patchVertices=" << patchVertices;
EXPECT_EQ(DeclaredOutputVertices(spirv), static_cast<Int>(patchVertices)) << "patchVertices=" << patchVertices;
}
}
@@ -167,8 +165,8 @@ TEST_F(PassthroughTessControlTest, ForwardsPositionAndWritesBothLevelArrays) {
// user-defined varying, ReflectPassthroughTessControlNeed's "built-ins only" refusal stops being
// the right gate and both have to move together.
TEST_F(PassthroughTessControlTest, InterfaceIsBuiltInsOnly) {
const String source = ProgramFactory::BuildPassthroughTessControlSource(
4, kDefaultOuter, kDefaultInner, ProgramFactory::kDefaultPerVertexMembers);
const String source = ProgramFactory::BuildPassthroughTessControlSource(4, kDefaultOuter, kDefaultInner,
ProgramFactory::kDefaultPerVertexMembers);
EXPECT_EQ(source.find("layout(location"), String::npos) << source;
EXPECT_NE(source.find("layout(vertices = 4) out;"), String::npos) << source;
}
@@ -181,8 +179,8 @@ TEST_F(PassthroughTessControlTest, BakesTheDefaultTessLevelsInAndKeysOnThem) {
constexpr Uint32 kMembers = ProgramFactory::kDefaultPerVertexMembers;
const FloatVec4 outer(2.0f, 3.0f, 4.0f, 5.0f);
const FloatVec2 inner(6.5f, 7.25f);
const String source = ProgramFactory::BuildPassthroughTessControlSource(4, outer, inner,
ProgramFactory::kDefaultPerVertexMembers);
const String source =
ProgramFactory::BuildPassthroughTessControlSource(4, outer, inner, ProgramFactory::kDefaultPerVertexMembers);
EXPECT_NE(source.find("gl_TessLevelOuter[0] = 2.0;"), String::npos) << source;
EXPECT_NE(source.find("gl_TessLevelOuter[3] = 5.0;"), String::npos) << source;
EXPECT_NE(source.find("gl_TessLevelInner[0] = 6.5;"), String::npos) << source;
@@ -197,9 +195,8 @@ TEST_F(PassthroughTessControlTest, BakesTheDefaultTessLevelsInAndKeysOnThem) {
// ...and the gl_PerVertex member set is in the same key, for the same reason: two programs at
// different GLSL versions need differently-shaped modules, and a pipeline memoised against one
// shape must not be handed back for the other.
constexpr Uint32 kMembersWithCull =
ProgramFactory::kDefaultPerVertexMembers |
static_cast<Uint32>(ProgramFactory::PerVertexMemberBit::CullDistance);
constexpr Uint32 kMembersWithCull = ProgramFactory::kDefaultPerVertexMembers |
static_cast<Uint32>(ProgramFactory::PerVertexMemberBit::CullDistance);
EXPECT_NE(ProgramFactory::ComputePassthroughTessControlKey(4, kDefaultOuter, kDefaultInner, kMembersWithCull),
defaultKey);
}
@@ -208,10 +205,8 @@ TEST_F(PassthroughTessControlTest, BakesTheDefaultTessLevelsInAndKeysOnThem) {
// without a decimal point is an int literal, and `gl_TessLevelOuter[0] = 2;` does not compile.
TEST_F(PassthroughTessControlTest, CompilesWithNonDefaultLevels) {
using namespace MG_Util::ShaderTranspiler;
const String source =
ProgramFactory::BuildPassthroughTessControlSource(4, FloatVec4(2.0f, 2.0f, 2.0f, 2.0f),
FloatVec2(2.0f, 2.0f),
ProgramFactory::kDefaultPerVertexMembers);
const String source = ProgramFactory::BuildPassthroughTessControlSource(
4, FloatVec4(2.0f, 2.0f, 2.0f, 2.0f), FloatVec2(2.0f, 2.0f), ProgramFactory::kDefaultPerVertexMembers);
ShaderAttrib shaderAttrib{.shaderType = GL_TESS_CONTROL_SHADER, .sourceStr = source};
auto shaderResult = ShaderCompiler::CompileShader(shaderAttrib);
EXPECT_TRUE(shaderResult) << (shaderResult ? String{} : shaderResult.error().log) << source;
+134 -176
View File
@@ -28,18 +28,15 @@ namespace {
constexpr Uint32 kVendorIdArm = 0x13B5;
constexpr VkColorComponentFlags kFullColorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
// Builds non-separate blend state: the alpha channel repeats the color factors/op, which
// is what glBlendFunc/glBlendEquation (as opposed to their *Separate forms) produce.
// ShouldSuppressDepthWrite deliberately decides on the color channel alone, so these
// cases cover its whole input space; SeparateAlphaAccumulationIsNotStripped below pins
// the separate-alpha contract.
VkPipelineColorBlendAttachmentState MakeBlendAttachment(Bool blendEnable,
VkBlendFactor srcColor,
VkBlendFactor dstColor,
VkBlendOp colorOp,
VkPipelineColorBlendAttachmentState MakeBlendAttachment(Bool blendEnable, VkBlendFactor srcColor,
VkBlendFactor dstColor, VkBlendOp colorOp,
VkColorComponentFlags colorWriteMask) {
VkPipelineColorBlendAttachmentState attachment{};
attachment.blendEnable = blendEnable ? VK_TRUE : VK_FALSE;
@@ -59,130 +56,103 @@ namespace {
// void main() { outColor = vec4(1.0); gl_FragDepth = 0.5; }
// Assigning gl_FragDepth makes glslang emit OpExecutionMode ... DepthReplacing.
constexpr Uint32 kFragDepthWriterSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000000fu, 0x00000000u, 0x00020011u,
0x00000001u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu,
0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, 0x0007000fu, 0x00000004u,
0x00000004u, 0x6e69616du, 0x00000000u, 0x00000009u, 0x0000000du, 0x00030010u,
0x00000004u, 0x00000007u, 0x00030010u, 0x00000004u, 0x0000000cu, 0x00030003u,
0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u,
0x00050005u, 0x00000009u, 0x4374756fu, 0x726f6c6fu, 0x00000000u, 0x00060005u,
0x0000000du, 0x465f6c67u, 0x44676172u, 0x68747065u, 0x00000000u, 0x00040047u,
0x00000009u, 0x0000001eu, 0x00000000u, 0x00040047u, 0x0000000du, 0x0000000bu,
0x00000016u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u,
0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u,
0x00000004u, 0x00040020u, 0x00000008u, 0x00000003u, 0x00000007u, 0x0004003bu,
0x00000008u, 0x00000009u, 0x00000003u, 0x0004002bu, 0x00000006u, 0x0000000au,
0x3f800000u, 0x0007002cu, 0x00000007u, 0x0000000bu, 0x0000000au, 0x0000000au,
0x0000000au, 0x0000000au, 0x00040020u, 0x0000000cu, 0x00000003u, 0x00000006u,
0x0004003bu, 0x0000000cu, 0x0000000du, 0x00000003u, 0x0004002bu, 0x00000006u,
0x0000000eu, 0x3f000000u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u,
0x00000003u, 0x000200f8u, 0x00000005u, 0x0003003eu, 0x00000009u, 0x0000000bu,
0x0003003eu, 0x0000000du, 0x0000000eu, 0x000100fdu, 0x00010038u,
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000000fu, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0007000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000009u, 0x0000000du, 0x00030010u,
0x00000004u, 0x00000007u, 0x00030010u, 0x00000004u, 0x0000000cu, 0x00030003u, 0x00000002u, 0x000001c2u,
0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00050005u, 0x00000009u, 0x4374756fu, 0x726f6c6fu,
0x00000000u, 0x00060005u, 0x0000000du, 0x465f6c67u, 0x44676172u, 0x68747065u, 0x00000000u, 0x00040047u,
0x00000009u, 0x0000001eu, 0x00000000u, 0x00040047u, 0x0000000du, 0x0000000bu, 0x00000016u, 0x00020013u,
0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u,
0x00000007u, 0x00000006u, 0x00000004u, 0x00040020u, 0x00000008u, 0x00000003u, 0x00000007u, 0x0004003bu,
0x00000008u, 0x00000009u, 0x00000003u, 0x0004002bu, 0x00000006u, 0x0000000au, 0x3f800000u, 0x0007002cu,
0x00000007u, 0x0000000bu, 0x0000000au, 0x0000000au, 0x0000000au, 0x0000000au, 0x00040020u, 0x0000000cu,
0x00000003u, 0x00000006u, 0x0004003bu, 0x0000000cu, 0x0000000du, 0x00000003u, 0x0004002bu, 0x00000006u,
0x0000000eu, 0x3f000000u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u,
0x00000005u, 0x0003003eu, 0x00000009u, 0x0000000bu, 0x0003003eu, 0x0000000du, 0x0000000eu, 0x000100fdu,
0x00010038u,
};
// Same shader without the gl_FragDepth assignment.
constexpr Uint32 kPlainFragmentSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000000cu, 0x00000000u, 0x00020011u,
0x00000001u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu,
0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, 0x0006000fu, 0x00000004u,
0x00000004u, 0x6e69616du, 0x00000000u, 0x00000009u, 0x00030010u, 0x00000004u,
0x00000007u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u,
0x6e69616du, 0x00000000u, 0x00050005u, 0x00000009u, 0x4374756fu, 0x726f6c6fu,
0x00000000u, 0x00040047u, 0x00000009u, 0x0000001eu, 0x00000000u, 0x00020013u,
0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u,
0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000004u, 0x00040020u,
0x00000008u, 0x00000003u, 0x00000007u, 0x0004003bu, 0x00000008u, 0x00000009u,
0x00000003u, 0x0004002bu, 0x00000006u, 0x0000000au, 0x3f800000u, 0x0007002cu,
0x00000007u, 0x0000000bu, 0x0000000au, 0x0000000au, 0x0000000au, 0x0000000au,
0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u,
0x00000005u, 0x0003003eu, 0x00000009u, 0x0000000bu, 0x000100fdu, 0x00010038u,
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000000cu, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0006000fu, 0x00000004u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00000009u, 0x00030010u, 0x00000004u,
0x00000007u, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u,
0x00050005u, 0x00000009u, 0x4374756fu, 0x726f6c6fu, 0x00000000u, 0x00040047u, 0x00000009u, 0x0000001eu,
0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u,
0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000004u, 0x00040020u, 0x00000008u, 0x00000003u,
0x00000007u, 0x0004003bu, 0x00000008u, 0x00000009u, 0x00000003u, 0x0004002bu, 0x00000006u, 0x0000000au,
0x3f800000u, 0x0007002cu, 0x00000007u, 0x0000000bu, 0x0000000au, 0x0000000au, 0x0000000au, 0x0000000au,
0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0003003eu,
0x00000009u, 0x0000000bu, 0x000100fdu, 0x00010038u,
};
// glslangValidator -V output for a vertex shader reading gl_InstanceIndex:
// #version 450
// layout(location = 0) in vec4 inPos;
// void main() { gl_Position = inPos + vec4(float(gl_InstanceIndex)); }
constexpr Uint32 kInstanceIndexVertexSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000001bu, 0x00000000u, 0x00020011u,
0x00000001u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu,
0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, 0x0008000fu, 0x00000000u,
0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x00000011u, 0x00000014u,
0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du,
0x00000000u, 0x00060005u, 0x0000000bu, 0x505f6c67u, 0x65567265u, 0x78657472u,
0x00000000u, 0x00060006u, 0x0000000bu, 0x00000000u, 0x505f6c67u, 0x7469736fu,
0x006e6f69u, 0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u, 0x746e696fu,
0x657a6953u, 0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u,
0x4470696cu, 0x61747369u, 0x0065636eu, 0x00070006u, 0x0000000bu, 0x00000003u,
0x435f6c67u, 0x446c6c75u, 0x61747369u, 0x0065636eu, 0x00030005u, 0x0000000du,
0x00000000u, 0x00040005u, 0x00000011u, 0x6f506e69u, 0x00000073u, 0x00070005u,
0x00000014u, 0x495f6c67u, 0x6174736eu, 0x4965636eu, 0x7865646eu, 0x00000000u,
0x00030047u, 0x0000000bu, 0x00000002u, 0x00050048u, 0x0000000bu, 0x00000000u,
0x0000000bu, 0x00000000u, 0x00050048u, 0x0000000bu, 0x00000001u, 0x0000000bu,
0x00000001u, 0x00050048u, 0x0000000bu, 0x00000002u, 0x0000000bu, 0x00000003u,
0x00050048u, 0x0000000bu, 0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u,
0x00000011u, 0x0000001eu, 0x00000000u, 0x00040047u, 0x00000014u, 0x0000000bu,
0x0000002bu, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u,
0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u,
0x00000004u, 0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u, 0x0004002bu,
0x00000008u, 0x00000009u, 0x00000001u, 0x0004001cu, 0x0000000au, 0x00000006u,
0x00000009u, 0x0006001eu, 0x0000000bu, 0x00000007u, 0x00000006u, 0x0000000au,
0x0000000au, 0x00040020u, 0x0000000cu, 0x00000003u, 0x0000000bu, 0x0004003bu,
0x0000000cu, 0x0000000du, 0x00000003u, 0x00040015u, 0x0000000eu, 0x00000020u,
0x00000001u, 0x0004002bu, 0x0000000eu, 0x0000000fu, 0x00000000u, 0x00040020u,
0x00000010u, 0x00000001u, 0x00000007u, 0x0004003bu, 0x00000010u, 0x00000011u,
0x00000001u, 0x00040020u, 0x00000013u, 0x00000001u, 0x0000000eu, 0x0004003bu,
0x00000013u, 0x00000014u, 0x00000001u, 0x00040020u, 0x00000019u, 0x00000003u,
0x00000007u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u,
0x000200f8u, 0x00000005u, 0x0004003du, 0x00000007u, 0x00000012u, 0x00000011u,
0x0004003du, 0x0000000eu, 0x00000015u, 0x00000014u, 0x0004006fu, 0x00000006u,
0x00000016u, 0x00000015u, 0x00070050u, 0x00000007u, 0x00000017u, 0x00000016u,
0x00000016u, 0x00000016u, 0x00000016u, 0x00050081u, 0x00000007u, 0x00000018u,
0x00000012u, 0x00000017u, 0x00050041u, 0x00000019u, 0x0000001au, 0x0000000du,
0x0000000fu, 0x0003003eu, 0x0000001au, 0x00000018u, 0x000100fdu, 0x00010038u,
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000001bu, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0008000fu, 0x00000000u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x00000011u, 0x00000014u,
0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00060005u,
0x0000000bu, 0x505f6c67u, 0x65567265u, 0x78657472u, 0x00000000u, 0x00060006u, 0x0000000bu, 0x00000000u,
0x505f6c67u, 0x7469736fu, 0x006e6f69u, 0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u, 0x746e696fu,
0x657a6953u, 0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u, 0x4470696cu, 0x61747369u,
0x0065636eu, 0x00070006u, 0x0000000bu, 0x00000003u, 0x435f6c67u, 0x446c6c75u, 0x61747369u, 0x0065636eu,
0x00030005u, 0x0000000du, 0x00000000u, 0x00040005u, 0x00000011u, 0x6f506e69u, 0x00000073u, 0x00070005u,
0x00000014u, 0x495f6c67u, 0x6174736eu, 0x4965636eu, 0x7865646eu, 0x00000000u, 0x00030047u, 0x0000000bu,
0x00000002u, 0x00050048u, 0x0000000bu, 0x00000000u, 0x0000000bu, 0x00000000u, 0x00050048u, 0x0000000bu,
0x00000001u, 0x0000000bu, 0x00000001u, 0x00050048u, 0x0000000bu, 0x00000002u, 0x0000000bu, 0x00000003u,
0x00050048u, 0x0000000bu, 0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u, 0x00000011u, 0x0000001eu,
0x00000000u, 0x00040047u, 0x00000014u, 0x0000000bu, 0x0000002bu, 0x00020013u, 0x00000002u, 0x00030021u,
0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u,
0x00000004u, 0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u, 0x0004002bu, 0x00000008u, 0x00000009u,
0x00000001u, 0x0004001cu, 0x0000000au, 0x00000006u, 0x00000009u, 0x0006001eu, 0x0000000bu, 0x00000007u,
0x00000006u, 0x0000000au, 0x0000000au, 0x00040020u, 0x0000000cu, 0x00000003u, 0x0000000bu, 0x0004003bu,
0x0000000cu, 0x0000000du, 0x00000003u, 0x00040015u, 0x0000000eu, 0x00000020u, 0x00000001u, 0x0004002bu,
0x0000000eu, 0x0000000fu, 0x00000000u, 0x00040020u, 0x00000010u, 0x00000001u, 0x00000007u, 0x0004003bu,
0x00000010u, 0x00000011u, 0x00000001u, 0x00040020u, 0x00000013u, 0x00000001u, 0x0000000eu, 0x0004003bu,
0x00000013u, 0x00000014u, 0x00000001u, 0x00040020u, 0x00000019u, 0x00000003u, 0x00000007u, 0x00050036u,
0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003du, 0x00000007u,
0x00000012u, 0x00000011u, 0x0004003du, 0x0000000eu, 0x00000015u, 0x00000014u, 0x0004006fu, 0x00000006u,
0x00000016u, 0x00000015u, 0x00070050u, 0x00000007u, 0x00000017u, 0x00000016u, 0x00000016u, 0x00000016u,
0x00000016u, 0x00050081u, 0x00000007u, 0x00000018u, 0x00000012u, 0x00000017u, 0x00050041u, 0x00000019u,
0x0000001au, 0x0000000du, 0x0000000fu, 0x0003003eu, 0x0000001au, 0x00000018u, 0x000100fdu, 0x00010038u,
};
// Same, but reading gl_VertexIndex instead: a DIFFERENT input builtin. glslang emits
// this for GL's gl_VertexID, so nearly every real vertex shader has one - it is what
// separates "declares some builtin" from "declares the InstanceIndex builtin".
constexpr Uint32 kVertexIndexVertexSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000001bu, 0x00000000u, 0x00020011u,
0x00000001u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu,
0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, 0x0008000fu, 0x00000000u,
0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x00000011u, 0x00000014u,
0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du,
0x00000000u, 0x00060005u, 0x0000000bu, 0x505f6c67u, 0x65567265u, 0x78657472u,
0x00000000u, 0x00060006u, 0x0000000bu, 0x00000000u, 0x505f6c67u, 0x7469736fu,
0x006e6f69u, 0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u, 0x746e696fu,
0x657a6953u, 0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u,
0x4470696cu, 0x61747369u, 0x0065636eu, 0x00070006u, 0x0000000bu, 0x00000003u,
0x435f6c67u, 0x446c6c75u, 0x61747369u, 0x0065636eu, 0x00030005u, 0x0000000du,
0x00000000u, 0x00040005u, 0x00000011u, 0x6f506e69u, 0x00000073u, 0x00060005u,
0x00000014u, 0x565f6c67u, 0x65747265u, 0x646e4978u, 0x00007865u, 0x00030047u,
0x0000000bu, 0x00000002u, 0x00050048u, 0x0000000bu, 0x00000000u, 0x0000000bu,
0x00000000u, 0x00050048u, 0x0000000bu, 0x00000001u, 0x0000000bu, 0x00000001u,
0x00050048u, 0x0000000bu, 0x00000002u, 0x0000000bu, 0x00000003u, 0x00050048u,
0x0000000bu, 0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u, 0x00000011u,
0x0000001eu, 0x00000000u, 0x00040047u, 0x00000014u, 0x0000000bu, 0x0000002au,
0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u,
0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000004u,
0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u, 0x0004002bu, 0x00000008u,
0x00000009u, 0x00000001u, 0x0004001cu, 0x0000000au, 0x00000006u, 0x00000009u,
0x0006001eu, 0x0000000bu, 0x00000007u, 0x00000006u, 0x0000000au, 0x0000000au,
0x00040020u, 0x0000000cu, 0x00000003u, 0x0000000bu, 0x0004003bu, 0x0000000cu,
0x0000000du, 0x00000003u, 0x00040015u, 0x0000000eu, 0x00000020u, 0x00000001u,
0x0004002bu, 0x0000000eu, 0x0000000fu, 0x00000000u, 0x00040020u, 0x00000010u,
0x00000001u, 0x00000007u, 0x0004003bu, 0x00000010u, 0x00000011u, 0x00000001u,
0x00040020u, 0x00000013u, 0x00000001u, 0x0000000eu, 0x0004003bu, 0x00000013u,
0x00000014u, 0x00000001u, 0x00040020u, 0x00000019u, 0x00000003u, 0x00000007u,
0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u,
0x00000005u, 0x0004003du, 0x00000007u, 0x00000012u, 0x00000011u, 0x0004003du,
0x0000000eu, 0x00000015u, 0x00000014u, 0x0004006fu, 0x00000006u, 0x00000016u,
0x00000015u, 0x00070050u, 0x00000007u, 0x00000017u, 0x00000016u, 0x00000016u,
0x00000016u, 0x00000016u, 0x00050081u, 0x00000007u, 0x00000018u, 0x00000012u,
0x00000017u, 0x00050041u, 0x00000019u, 0x0000001au, 0x0000000du, 0x0000000fu,
0x0003003eu, 0x0000001au, 0x00000018u, 0x000100fdu, 0x00010038u,
0x07230203u, 0x00010000u, 0x0008000bu, 0x0000001bu, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0008000fu, 0x00000000u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x00000011u, 0x00000014u,
0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00060005u,
0x0000000bu, 0x505f6c67u, 0x65567265u, 0x78657472u, 0x00000000u, 0x00060006u, 0x0000000bu, 0x00000000u,
0x505f6c67u, 0x7469736fu, 0x006e6f69u, 0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u, 0x746e696fu,
0x657a6953u, 0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u, 0x4470696cu, 0x61747369u,
0x0065636eu, 0x00070006u, 0x0000000bu, 0x00000003u, 0x435f6c67u, 0x446c6c75u, 0x61747369u, 0x0065636eu,
0x00030005u, 0x0000000du, 0x00000000u, 0x00040005u, 0x00000011u, 0x6f506e69u, 0x00000073u, 0x00060005u,
0x00000014u, 0x565f6c67u, 0x65747265u, 0x646e4978u, 0x00007865u, 0x00030047u, 0x0000000bu, 0x00000002u,
0x00050048u, 0x0000000bu, 0x00000000u, 0x0000000bu, 0x00000000u, 0x00050048u, 0x0000000bu, 0x00000001u,
0x0000000bu, 0x00000001u, 0x00050048u, 0x0000000bu, 0x00000002u, 0x0000000bu, 0x00000003u, 0x00050048u,
0x0000000bu, 0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u, 0x00000011u, 0x0000001eu, 0x00000000u,
0x00040047u, 0x00000014u, 0x0000000bu, 0x0000002au, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u,
0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000004u,
0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u, 0x0004002bu, 0x00000008u, 0x00000009u, 0x00000001u,
0x0004001cu, 0x0000000au, 0x00000006u, 0x00000009u, 0x0006001eu, 0x0000000bu, 0x00000007u, 0x00000006u,
0x0000000au, 0x0000000au, 0x00040020u, 0x0000000cu, 0x00000003u, 0x0000000bu, 0x0004003bu, 0x0000000cu,
0x0000000du, 0x00000003u, 0x00040015u, 0x0000000eu, 0x00000020u, 0x00000001u, 0x0004002bu, 0x0000000eu,
0x0000000fu, 0x00000000u, 0x00040020u, 0x00000010u, 0x00000001u, 0x00000007u, 0x0004003bu, 0x00000010u,
0x00000011u, 0x00000001u, 0x00040020u, 0x00000013u, 0x00000001u, 0x0000000eu, 0x0004003bu, 0x00000013u,
0x00000014u, 0x00000001u, 0x00040020u, 0x00000019u, 0x00000003u, 0x00000007u, 0x00050036u, 0x00000002u,
0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003du, 0x00000007u, 0x00000012u,
0x00000011u, 0x0004003du, 0x0000000eu, 0x00000015u, 0x00000014u, 0x0004006fu, 0x00000006u, 0x00000016u,
0x00000015u, 0x00070050u, 0x00000007u, 0x00000017u, 0x00000016u, 0x00000016u, 0x00000016u, 0x00000016u,
0x00050081u, 0x00000007u, 0x00000018u, 0x00000012u, 0x00000017u, 0x00050041u, 0x00000019u, 0x0000001au,
0x0000000du, 0x0000000fu, 0x0003003eu, 0x0000001au, 0x00000018u, 0x000100fdu, 0x00010038u,
};
// Owns the reflection module so each test case cleans up after itself.
@@ -190,8 +160,7 @@ namespace {
public:
template <SizeT WordCount>
explicit ReflectModule(const Uint32 (&spirv)[WordCount]) {
m_created = spvReflectCreateShaderModule(sizeof(spirv), spirv, &m_module) ==
SPV_REFLECT_RESULT_SUCCESS;
m_created = spvReflectCreateShaderModule(sizeof(spirv), spirv, &m_module) == SPV_REFLECT_RESULT_SUCCESS;
}
~ReflectModule() {
if (m_created) {
@@ -223,22 +192,17 @@ namespace {
// --- Device gate: MOBILEGL_MAGMA_DISABLE_BLENDED_DEPTH_WRITE tri-state ---
TEST(PipelineQuirkDeviceGate, ForceOnEnablesOnAnyVendor) {
EXPECT_TRUE(PipelineFactory::ShouldSuppressBlendedDepthWriteForDevice(QuirkOverride::ForceOn,
kVendorIdArm));
EXPECT_TRUE(PipelineFactory::ShouldSuppressBlendedDepthWriteForDevice(QuirkOverride::ForceOn,
kVendorIdQualcomm));
EXPECT_TRUE(PipelineFactory::ShouldSuppressBlendedDepthWriteForDevice(QuirkOverride::ForceOn, kVendorIdArm));
EXPECT_TRUE(PipelineFactory::ShouldSuppressBlendedDepthWriteForDevice(QuirkOverride::ForceOn, kVendorIdQualcomm));
}
TEST(PipelineQuirkDeviceGate, ForceOffDisablesEvenOnQualcomm) {
EXPECT_FALSE(PipelineFactory::ShouldSuppressBlendedDepthWriteForDevice(QuirkOverride::ForceOff,
kVendorIdQualcomm));
EXPECT_FALSE(PipelineFactory::ShouldSuppressBlendedDepthWriteForDevice(QuirkOverride::ForceOff, kVendorIdQualcomm));
}
TEST(PipelineQuirkDeviceGate, AutoDetectsQualcommOnly) {
EXPECT_TRUE(PipelineFactory::ShouldSuppressBlendedDepthWriteForDevice(QuirkOverride::Auto,
kVendorIdQualcomm));
EXPECT_FALSE(PipelineFactory::ShouldSuppressBlendedDepthWriteForDevice(QuirkOverride::Auto,
kVendorIdArm));
EXPECT_TRUE(PipelineFactory::ShouldSuppressBlendedDepthWriteForDevice(QuirkOverride::Auto, kVendorIdQualcomm));
EXPECT_FALSE(PipelineFactory::ShouldSuppressBlendedDepthWriteForDevice(QuirkOverride::Auto, kVendorIdArm));
}
TEST(PipelineQuirkDeviceGate, ForceOnRoundTripsThroughTheFactoryFlag) {
@@ -253,14 +217,14 @@ TEST(PipelineQuirkDeviceGate, ForceOnRoundTripsThroughTheFactoryFlag) {
TEST(PipelineQuirkStripDecision, MaxBlendIsStripped) {
// MC 26.3 OIT depth_bounds: GL_MAX accumulation writing depth - the case the quirk fixes.
const auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_MAX, kFullColorWriteMask));
const auto payload = MakeDepthWritingPayload(
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_MAX, kFullColorWriteMask));
EXPECT_TRUE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
TEST(PipelineQuirkStripDecision, MinBlendIsStripped) {
const auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_MIN, kFullColorWriteMask));
const auto payload = MakeDepthWritingPayload(
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_MIN, kFullColorWriteMask));
EXPECT_TRUE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
@@ -269,8 +233,8 @@ TEST(PipelineQuirkStripDecision, AdditiveOnePlusOneIsNotStripped) {
// fixture sweep (transmittance/accumulate disable depth writes themselves); the only
// real content with this shape was harmless additive glow effects (Create). A quirk
// touches as little unrelated content as possible, so the shape stays exempt.
const auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_ADD, kFullColorWriteMask));
const auto payload = MakeDepthWritingPayload(
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_ADD, kFullColorWriteMask));
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
@@ -279,16 +243,15 @@ TEST(PipelineQuirkStripDecision, SortedTransparencyOverBlendIsNotStripped) {
// draws each surface once and depends on its depth writes to occlude particles, rain,
// and clouds drawn later - it must keep them.
const auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD,
kFullColorWriteMask));
true, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, kFullColorWriteMask));
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
TEST(PipelineQuirkStripDecision, EffectivelyOpaqueBlendIsNotStripped) {
// GL_BLEND left enabled with ONE/ZERO+ADD factors is opaque in effect; stripping its
// depth write would break occlusion for plainly opaque geometry.
const auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD, kFullColorWriteMask));
const auto payload = MakeDepthWritingPayload(
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD, kFullColorWriteMask));
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
@@ -296,20 +259,20 @@ TEST(PipelineQuirkStripDecision, FullyMaskedAccumulationBlendIsNotStripped) {
// Depth-prepass pattern: colorMask(0,0,0,0) with blending left enabled - blending is
// moot, and stripping would delete the entire prepass. MAX so the exemption, not the
// blend-op filter, is what keeps the depth write.
const auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, 0));
const auto payload = MakeDepthWritingPayload(
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, 0));
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
TEST(PipelineQuirkStripDecision, DisabledBlendIsNotStripped) {
const auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
false, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask));
const auto payload = MakeDepthWritingPayload(
MakeBlendAttachment(false, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask));
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
TEST(PipelineQuirkStripDecision, NoDepthWriteMeansNoStrip) {
auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask));
auto payload = MakeDepthWritingPayload(
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask));
payload.depthWriteEnable = false;
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
@@ -317,8 +280,8 @@ TEST(PipelineQuirkStripDecision, NoDepthWriteMeansNoStrip) {
TEST(PipelineQuirkStripDecision, FragDepthWriterIsExempt) {
// gl_FragDepth output does not go through per-pipeline vertex position math, so the
// cross-pipeline invariance hazard cannot affect it (e.g. the 26.3 OIT composite).
auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask));
auto payload = MakeDepthWritingPayload(
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask));
payload.fragmentReplacesDepth = true;
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
@@ -330,10 +293,10 @@ TEST(PipelineQuirkStripDecision, AccumulationOnSecondaryAttachmentIsStripped) {
payload.colorAttachmentCount = 2;
payload.depthTestEnable = true;
payload.depthWriteEnable = true;
payload.colorBlendAttachments[0] = MakeBlendAttachment(
false, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD, kFullColorWriteMask);
payload.colorBlendAttachments[1] = MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask);
payload.colorBlendAttachments[0] =
MakeBlendAttachment(false, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ZERO, VK_BLEND_OP_ADD, kFullColorWriteMask);
payload.colorBlendAttachments[1] =
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask);
EXPECT_TRUE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
@@ -349,15 +312,14 @@ TEST(PipelineQuirkStripDecision, ReverseSubtractIsNotStripped) {
// Deliberate narrowing: only the MIN/MAX extremum ops carry the depth-bounds
// signature. SUBTRACT-class ops stay outside the quirk until content demands them.
const auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_REVERSE_SUBTRACT,
kFullColorWriteMask));
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_REVERSE_SUBTRACT, kFullColorWriteMask));
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
TEST(PipelineQuirkStripDecision, PartiallyMaskedAccumulationIsStripped) {
// Only a fully masked attachment is exempt; a live alpha channel still accumulates.
const auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, VK_COLOR_COMPONENT_A_BIT));
const auto payload = MakeDepthWritingPayload(
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, VK_COLOR_COMPONENT_A_BIT));
EXPECT_TRUE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
@@ -367,8 +329,8 @@ TEST(PipelineQuirkStripDecision, NoColorAttachmentsMeansNoStrip) {
payload.colorAttachmentCount = 0;
payload.depthTestEnable = true;
payload.depthWriteEnable = true;
payload.colorBlendAttachments[0] = MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask);
payload.colorBlendAttachments[0] =
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask);
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
@@ -376,9 +338,8 @@ TEST(PipelineQuirkStripDecision, SeparateAlphaAccumulationIsNotStripped) {
// glBlendEquationSeparate(GL_FUNC_ADD, GL_MAX) over an ordinary color over-blend: the
// alpha channel accumulates but the color channel does not. Pins that the decision is
// color-channel only - widening it to alpha would re-capture sorted transparency.
auto attachment = MakeBlendAttachment(true, VK_BLEND_FACTOR_SRC_ALPHA,
VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD,
kFullColorWriteMask);
auto attachment = MakeBlendAttachment(true, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA,
VK_BLEND_OP_ADD, kFullColorWriteMask);
attachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
attachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
attachment.alphaBlendOp = VK_BLEND_OP_MAX;
@@ -391,10 +352,9 @@ TEST(PipelineQuirkStripDecision, MixedOverAndMaskedAttachmentsAreNotStripped) {
payload.depthTestEnable = true;
payload.depthWriteEnable = true;
payload.colorBlendAttachments[0] = MakeBlendAttachment(
true, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD,
kFullColorWriteMask);
payload.colorBlendAttachments[1] = MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, 0);
true, VK_BLEND_FACTOR_SRC_ALPHA, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA, VK_BLEND_OP_ADD, kFullColorWriteMask);
payload.colorBlendAttachments[1] =
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, 0);
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
@@ -426,8 +386,8 @@ TEST(ReflectedFragmentReplacesDepth, ReflectedFlagFlipsTheStripDecision) {
ASSERT_TRUE(depthWriter.Created());
ASSERT_TRUE(plain.Created());
auto payload = MakeDepthWritingPayload(MakeBlendAttachment(
true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask));
auto payload = MakeDepthWritingPayload(
MakeBlendAttachment(true, VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE, VK_BLEND_OP_MAX, kFullColorWriteMask));
payload.fragmentReplacesDepth = ProgramFactory::ReflectedFragmentReplacesDepth(plain.Get());
EXPECT_TRUE(PipelineFactory::ShouldSuppressDepthWrite(payload));
@@ -436,7 +396,6 @@ TEST(ReflectedFragmentReplacesDepth, ReflectedFlagFlipsTheStripDecision) {
EXPECT_FALSE(PipelineFactory::ShouldSuppressDepthWrite(payload));
}
// --- InstanceIndex reflection feeding the shaderDrawParameters diagnostic ---
TEST(ReflectedReadsInstanceIndexBuiltin, TrueForAShaderReadingInstanceIndex) {
@@ -464,13 +423,12 @@ TEST(ReflectedReadsInstanceIndexBuiltin, FalseForAnEmptyModule) {
EXPECT_FALSE(ProgramFactory::ReflectedReadsInstanceIndexBuiltin(emptyModule));
}
TEST(WirePipelineCompatibility, ExactCompatibilitySurvivesNativeObjectTurnover) {
#if MOBILEGL_BUILD_DISAGGREGATED
using namespace MobileGL::MG_Backend::DirectVulkan;
WireRenderPassCompatibilityTable table;
WireRenderPassCompatibilityKey a{{(Uint64(VK_FORMAT_R8G8B8A8_UNORM) << 32) | VK_SAMPLE_COUNT_1_BIT}, {0},
VK_ATTACHMENT_UNUSED};
WireRenderPassCompatibilityKey a{
{(Uint64(VK_FORMAT_R8G8B8A8_UNORM) << 32) | VK_SAMPLE_COUNT_1_BIT}, {0}, VK_ATTACHMENT_UNUSED};
const Uint64 first = table.Intern(a);
ASSERT_NE(first, 0u);
auto b = a;
@@ -606,9 +564,9 @@ TEST(PipelineQuirkTest, WireDepthResolveProbeDetectsARenderPassThatWritesNothing
wrong.formats[0].depth.renderPassSentinels = 0;
EXPECT_EQ(EvaluateWireDepthResolveProbe(wrong), WireDepthResolveProbeVerdict::RenderPassResolveBroken);
// One aspect of one format is enough: the render pass resolves every aspect in one pass.
EXPECT_EQ(EvaluateWireDepthResolveProbe(FakeMeasurement(
{FakeFormat("D24_UNORM_S8_UINT", kBothArmsResolve, kRenderPassWroteNothing),
FakeFormat("D32_SFLOAT", kBothArmsResolve, std::nullopt)})),
EXPECT_EQ(EvaluateWireDepthResolveProbe(
FakeMeasurement({FakeFormat("D24_UNORM_S8_UINT", kBothArmsResolve, kRenderPassWroteNothing),
FakeFormat("D32_SFLOAT", kBothArmsResolve, std::nullopt)})),
WireDepthResolveProbeVerdict::RenderPassResolveBroken);
EXPECT_NE(DescribeWireDepthResolveProbe(choice.measurement).find("render pass 0/16"), String::npos);
#else
@@ -849,14 +807,14 @@ TEST(PipelineQuirkTest, WirePlaceholderKeysArePrivatePerShapeAndUnitAndBounded)
using MobileGL::MG_Backend::DirectVulkan::WirePlaceholderKey;
using MobileGL::MG_Backend::DirectVulkan::WirePlaceholderKeyHash;
constexpr Uint32 kUnits = MobileGL::MG_Pipe::kMGPipeMaxImageUnits;
static_assert(kWirePrivateStoragePlaceholderCap >= kUnits,
"one shape on every image unit must stay private");
static_assert(kWirePrivateStoragePlaceholderCap >= kUnits, "one shape on every image unit must stay private");
UnorderedMap<WirePlaceholderKey, Int, WirePlaceholderKeyHash> cache;
SizeT privateCount = 0;
// What ResolveWirePlaceholderImage does with the key: find it, or make (and count) it.
const auto take = [&](Uint64 shape, Bool storage, Uint32 unit) {
const WirePlaceholderKey key = ChooseWirePlaceholderKey(shape, storage, unit, privateCount,
[&](const WirePlaceholderKey& candidate) { return cache.count(candidate) != 0; });
const WirePlaceholderKey key =
ChooseWirePlaceholderKey(shape, storage, unit, privateCount,
[&](const WirePlaceholderKey& candidate) { return cache.count(candidate) != 0; });
if (cache.emplace(key, 0).second && key.unit != WirePlaceholderKey::kShared) ++privateCount;
return key;
};
@@ -925,9 +883,9 @@ TEST(PipelineQuirkTest, WireColorBlitSamplesNearestWhereTheBlitIsACopy) {
#if MOBILEGL_BUILD_DISAGGREGATED
// create-instancing's last pass (trace call 530331): glBlitFramebuffer(0,0,854,480 -> 0,0,854,480,
// GL_COLOR_BUFFER_BIT, GL_LINEAR) into FB 0, on an identity pbuffer.
EXPECT_EQ(WireColorBlitFilterFor({0, 0, 854, 480}, {0, 0, 854, 480}, GL_LINEAR,
VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR),
VK_FILTER_NEAREST)
EXPECT_EQ(
WireColorBlitFilterFor({0, 0, 854, 480}, {0, 0, 854, 480}, GL_LINEAR, VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR),
VK_FILTER_NEAREST)
<< "a 1:1 GL_LINEAR blit is a copy (GL 4.6 core 18.3.1); linear sampling of it is not exact on Adreno";
const struct {
const char* what;
@@ -37,8 +37,7 @@ namespace {
// one mode cannot leak into the next.
class AsyncModeScope {
public:
explicit AsyncModeScope(const Bool async)
: m_saved(MG_Config::Features.AsyncShaderCompile) {
explicit AsyncModeScope(const Bool async) : m_saved(MG_Config::Features.AsyncShaderCompile) {
MG_Config::Features.AsyncShaderCompile =
async ? MG_Config::QuirkOverride::ForceOn : MG_Config::QuirkOverride::ForceOff;
}
@@ -306,8 +305,9 @@ TEST_F(AsyncCompileTest, LinkDiagnosticsQuoteTheAsyncCompileLog) {
const String programLog(buffer.data(), static_cast<size_t>(written));
const String shaderLog = QueryShaderInfoLog(fs);
ASSERT_FALSE(shaderLog.empty());
EXPECT_NE(programLog.find(shaderLog), String::npos)
<< "program log:\n" << programLog << "\nshader log:\n" << shaderLog;
EXPECT_NE(programLog.find(shaderLog), String::npos) << "program log:\n"
<< programLog << "\nshader log:\n"
<< shaderLog;
EXPECT_EQ(GetError(), GL_NO_ERROR);
}
@@ -507,8 +507,7 @@ TEST_F(AsyncCompileTest, StressCompileQueryResourceDeleteInterleaved) {
for (int i = 0; i < kPerRound; ++i) {
const GLuint shader = shaders[static_cast<SizeT>(i)];
EXPECT_EQ(QueryCompileStatus(shader), GL_TRUE) << QueryShaderInfoLog(shader);
const String expectedUniform =
"uSeed" + std::to_string(round * 1000 + (i % 2 == 0 ? 500 + i : i));
const String expectedUniform = "uSeed" + std::to_string(round * 1000 + (i % 2 == 0 ? 500 + i : i));
const GLuint vs = MakeShader(GL_VERTEX_SHADER, kVs);
CompileShader(vs);
const GLuint program = CreateProgram();
+5 -5
View File
@@ -210,8 +210,8 @@ TEST_F(AsyncLinkTest, TwoProgramsSharingAShaderGenerateIdenticalSpirv) {
const Vector<Uint64> digestA = SpirvDigest(programA);
const Vector<Uint64> digestB = SpirvDigest(programB);
ASSERT_EQ(digestA.size(), 2u) << "async=" << async;
EXPECT_EQ(digestA, digestB)
<< "the claim winner and the re-parsing loser must produce identical SPIR-V (async=" << async << ")";
EXPECT_EQ(digestA, digestB) << "the claim winner and the re-parsing loser must produce identical SPIR-V (async="
<< async << ")";
// And the two programs really are usable independently.
EXPECT_GE(GetUniformLocation(programA, "uColor"), 0);
@@ -803,13 +803,13 @@ TEST_F(AsyncLinkTest, StressLinkQueryRelinkDeleteInterleaved) {
const GLuint program = programs[static_cast<SizeT>(i)];
ASSERT_EQ(QueryLinkStatus(program), GL_TRUE)
<< "round " << round << " program " << i << ": " << QueryProgramInfoLog(program);
const String expected =
"uSeed" + std::to_string(round * 1000 + (i % 2 == 0 ? 700 + i : 300 + i));
const String expected = "uSeed" + std::to_string(round * 1000 + (i % 2 == 0 ? 700 + i : 300 + i));
EXPECT_GE(GetUniformLocation(program, expected.c_str()), 0)
<< "round " << round << " program " << i << " expected " << expected;
DeleteProgram(program);
}
for (const GLuint fs : fragmentShaders) DeleteShader(fs);
for (const GLuint fs : fragmentShaders)
DeleteShader(fs);
DeleteShader(vs);
EXPECT_EQ(GetError(), GL_NO_ERROR);
}
@@ -395,8 +395,9 @@ TEST_F(AsyncSpirvPhaseTest, ALinkedProgramWhoseSpirvJobWasCancelledDegradesInste
const GLfloat tint[3] = {1.0f, 2.0f, 3.0f};
GLfloat model[16] = {};
for (int c = 0; c < 16; ++c) model[c] = static_cast<GLfloat>(c);
ProgramUniform3fv(program, locTint, 1, tint); // dropped, not faulted
for (int c = 0; c < 16; ++c)
model[c] = static_cast<GLfloat>(c);
ProgramUniform3fv(program, locTint, 1, tint); // dropped, not faulted
ProgramUniformMatrix4fv(program, locModel, 1, GL_FALSE, model); // ditto
UseProgram(program);
Uniform3fv(locTint, 1, tint); // the glUseProgram + glUniform* entry, same verdict
@@ -410,7 +411,8 @@ TEST_F(AsyncSpirvPhaseTest, ALinkedProgramWhoseSpirvJobWasCancelledDegradesInste
// Reads leave the caller's buffer alone rather than faulting.
GLfloat readback[16] = {};
for (int c = 0; c < 16; ++c) readback[c] = -1.0f;
for (int c = 0; c < 16; ++c)
readback[c] = -1.0f;
GetUniformfv(program, locModel, readback);
for (int c = 0; c < 16; ++c) {
EXPECT_FLOAT_EQ(readback[c], -1.0f) << "a program with no shadow must not write the query buffer";
@@ -489,7 +491,8 @@ TEST_F(AsyncSpirvPhaseTest, UniformWritesInsideTheWindowReplayExactly) {
ASSERT_GE(e.locArr, 0);
ASSERT_GE(e.locTex, 0);
for (int c = 0; c < 16; ++c) e.model[c] = static_cast<GLfloat>(i) + static_cast<GLfloat>(c) * 0.25f;
for (int c = 0; c < 16; ++c)
e.model[c] = static_cast<GLfloat>(i) + static_cast<GLfloat>(c) * 0.25f;
e.tint[0] = 0.125f * static_cast<GLfloat>(i);
e.tint[1] = 0.25f * static_cast<GLfloat>(i);
e.tint[2] = 0.5f * static_cast<GLfloat>(i);
@@ -591,7 +594,8 @@ TEST_F(AsyncSpirvPhaseTest, TheBufferedWriteValveFallsThroughToADirectWriteWitho
GLfloat model[16] = {};
for (int w = 0; w < kFloodWrites; ++w) {
for (int c = 0; c < 16; ++c) model[c] = static_cast<GLfloat>(w) + static_cast<GLfloat>(c);
for (int c = 0; c < 16; ++c)
model[c] = static_cast<GLfloat>(w) + static_cast<GLfloat>(c);
ProgramUniformMatrix4fv(program, locModel, 1, GL_FALSE, model);
}
@@ -852,16 +856,15 @@ TEST_F(AsyncSpirvPhaseTest, DeletingAProgramWithAPendingSpirvJobDoesNotBlock) {
}
const auto drainEnd = std::chrono::steady_clock::now();
const auto deleteUs =
std::chrono::duration_cast<std::chrono::microseconds>(deleteEnd - deleteStart).count();
const auto deleteUs = std::chrono::duration_cast<std::chrono::microseconds>(deleteEnd - deleteStart).count();
const auto drainUs = std::chrono::duration_cast<std::chrono::microseconds>(drainEnd - drainStart).count();
EXPECT_GT(outstandingBeforeDelete, 0) << "no program was deleted inside the A->B window";
EXPECT_GT(outstandingBeforeDrain, 0) << "nothing was left to drain, so the timing bound has no calibration";
if (outstandingBeforeDelete > 0 && outstandingBeforeDrain > 0 && drainUs > 2000) {
EXPECT_LT(deleteUs, drainUs / 4)
<< "deleting " << kHalf << " programs with outstanding SPIR-V jobs took " << deleteUs
<< " us against " << drainUs << " us to drain the same number - glDeleteProgram is waiting for them";
EXPECT_LT(deleteUs, drainUs / 4) << "deleting " << kHalf << " programs with outstanding SPIR-V jobs took "
<< deleteUs << " us against " << drainUs
<< " us to drain the same number - glDeleteProgram is waiting for them";
}
EXPECT_EQ(GetError(), GL_NO_ERROR);
}
@@ -1417,7 +1420,10 @@ discard;
GLint location;
};
const BoundAttribute kIrisWeatherBindings[] = {
{"iris_Position", 0}, {"iris_Color", 1}, {"iris_UV0", 2}, {"iris_UV2", 3},
{"iris_Position", 0},
{"iris_Color", 1},
{"iris_UV0", 2},
{"iris_UV2", 3},
};
// Drives Iris's own call sequence and returns the linked program name.
@@ -1466,8 +1472,8 @@ TEST_F(AsyncSpirvPhaseTest, IrisWeatherProgramReplaysCleanlyThroughBothPhases) {
// ---- phase A: LINK_STATUS is the join, and it must be truthful ----
GLint linkStatus = GL_FALSE;
GetProgramiv(program, GL_LINK_STATUS, &linkStatus);
ASSERT_EQ(linkStatus, GL_TRUE) << QueryProgramInfoLog(program)
<< " (optimistic quirk " << (optimisticQuirk ? "on" : "off") << ")";
ASSERT_EQ(linkStatus, GL_TRUE) << QueryProgramInfoLog(program) << " (optimistic quirk "
<< (optimisticQuirk ? "on" : "off") << ")";
// Iris queries uniforms straight after the status read; these are phase-A answers.
EXPECT_GE(GetUniformLocation(program, "iris_ModelViewMatrix"), -1);
@@ -1502,15 +1508,16 @@ TEST_F(AsyncSpirvPhaseTest, IrisWeatherProgramReplaysCleanlyThroughBothPhases) {
// which is precisely what the device victim did.
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
String validatorMessages;
tools.SetMessageConsumer([&validatorMessages](spv_message_level_t, const char*, const spv_position_t&,
const char* message) {
if (message != nullptr) validatorMessages += String(message) + "\n";
});
tools.SetMessageConsumer(
[&validatorMessages](spv_message_level_t, const char*, const spv_position_t&, const char* message) {
if (message != nullptr) validatorMessages += String(message) + "\n";
});
for (SizeT i = 0; i < modules.size(); ++i) {
validatorMessages.clear();
EXPECT_TRUE(tools.Validate(modules[i]))
<< "module " << i << " is not valid SPIR-V - Adreno rejects the pipeline for this while "
<< "lavapipe tolerates it:\n" << validatorMessages;
<< "lavapipe tolerates it:\n"
<< validatorMessages;
}
// ---- every vertex input carries a unique Location ----
@@ -1545,8 +1552,7 @@ TEST_F(AsyncSpirvPhaseTest, IrisWeatherProgramReplaysCleanlyThroughBothPhases) {
ASSERT_NE(it, locationById.end())
<< "a vertex input reached SPIR-V with no Location decoration (optimistic quirk "
<< (optimisticQuirk ? "on" : "off") << ")";
EXPECT_TRUE(usedLocations.insert(it->second).second)
<< "two vertex inputs share location " << it->second;
EXPECT_TRUE(usedLocations.insert(it->second).second) << "two vertex inputs share location " << it->second;
++checkedInputs;
}
EXPECT_GT(checkedInputs, 0u) << "no vertex inputs found; the scan proved nothing";
@@ -286,8 +286,8 @@ void main() { fragColor = thisIdentifierWasNeverDeclared; }
// then the GL_ACTIVE_UNIFORMS enumeration ProgramUniforms$Builder.buildUniforms does.
struct ProgramReflection {
GLint linkStatus = GL_FALSE;
Vector<std::pair<String, GLint>> locations; // queried name -> location
Vector<std::tuple<String, GLenum, GLint, GLint>> activeUniforms; // name, type, size, location
Vector<std::pair<String, GLint>> locations; // queried name -> location
Vector<std::tuple<String, GLenum, GLint, GLint>> activeUniforms; // name, type, size, location
};
ProgramReflection RunIrisPhaseTwo(const GLuint program, const Vector<String>& names) {
@@ -341,10 +341,10 @@ TEST_F(OptimisticStatusTest, OffByDefaultTheStatusStillJoins) {
const GLuint probe = probes[0];
EXPECT_EQ(QueryCompileStatus(probe), GL_TRUE);
EXPECT_EQ(QueryShaderCompletion(probe), GL_TRUE)
<< "GL_COMPILE_STATUS with the quirk off must have joined the job";
EXPECT_EQ(QueryShaderCompletion(probe), GL_TRUE) << "GL_COMPILE_STATUS with the quirk off must have joined the job";
for (const GLuint shader : saturation) DeleteShader(shader);
for (const GLuint shader : saturation)
DeleteShader(shader);
DeleteShader(probe);
EXPECT_EQ(GetError(), GL_NO_ERROR);
}
@@ -371,8 +371,7 @@ TEST_F(OptimisticStatusTest, PendingCompileReportsTrueAndEmptyLogWithoutJoining)
EXPECT_EQ(QueryCompileStatus(probe), GL_TRUE) << "an in-flight compile must answer GL_TRUE";
EXPECT_EQ(QueryInfoLogLength(probe), 0) << "an in-flight compile must answer an empty log length";
EXPECT_TRUE(QueryShaderInfoLog(probe).empty()) << "an in-flight compile must answer an empty log";
EXPECT_EQ(QueryShaderCompletion(probe), GL_FALSE)
<< "the three reads above must not have joined the blocked job";
EXPECT_EQ(QueryShaderCompletion(probe), GL_FALSE) << "the three reads above must not have joined the blocked job";
DeleteShader(probe);
EXPECT_EQ(GetError(), GL_NO_ERROR);
@@ -511,9 +510,8 @@ TEST_F(OptimisticStatusTest, AFailingCompileStillFailsItsLink) {
brokenSource += " fragColor = vec4(acc);\n}\n";
ASSERT_GT(brokenSource.size(), 32768u);
const GLuint vs = MakeShader(GL_VERTEX_SHADER,
"#version 460\nlayout(location = 0) in vec3 aPos;\n"
"void main() { gl_Position = vec4(aPos, 1.0); }\n");
const GLuint vs = MakeShader(GL_VERTEX_SHADER, "#version 460\nlayout(location = 0) in vec3 aPos;\n"
"void main() { gl_Position = vec4(aPos, 1.0); }\n");
const char* brokenText = brokenSource.c_str();
const GLuint fs = CreateShader(GL_FRAGMENT_SHADER);
ShaderSource(fs, 1, &brokenText, nullptr);
@@ -592,11 +590,12 @@ TEST_F(OptimisticStatusTest, IrisTwoPhaseReplayProducesIdenticalReflection) {
Vector<ProgramReflection>& out = quirkOn ? optimistic : reference;
for (int i = 0; i < kPrograms; ++i) {
const Vector<String> names = {"uModel" + std::to_string(i), "uTint",
"uSeed" + std::to_string(i), "uOffset", "uDoesNotExist"};
const Vector<String> names = {"uModel" + std::to_string(i), "uTint", "uSeed" + std::to_string(i), "uOffset",
"uDoesNotExist"};
out.push_back(RunIrisPhaseTwo(programs[(SizeT)i], names));
}
for (const GLuint program : programs) DeleteProgram(program);
for (const GLuint program : programs)
DeleteProgram(program);
ASSERT_EQ(GetError(), GL_NO_ERROR);
}
@@ -645,7 +644,8 @@ TEST_F(OptimisticStatusTest, PhaseOneIssuesNoCompileJoin) {
EXPECT_EQ(QueryShaderCompletion(shader), GL_FALSE)
<< "a phase-1 read joined a compile the blocked pool could not have run";
}
for (const GLuint shader : shaders) DeleteShader(shader);
for (const GLuint shader : shaders)
DeleteShader(shader);
}
// Quirk off: every status read joins its shader.
@@ -668,7 +668,8 @@ TEST_F(OptimisticStatusTest, PhaseOneIssuesNoCompileJoin) {
EXPECT_EQ(QueryShaderCompletion(shader), GL_TRUE)
<< "with the quirk off every per-shader status read must have joined";
}
for (const GLuint shader : shaders) DeleteShader(shader);
for (const GLuint shader : shaders)
DeleteShader(shader);
}
EXPECT_EQ(GetError(), GL_NO_ERROR);
}
@@ -412,9 +412,8 @@ TEST_F(ParallelShaderCompileTest, NonzeroCompilerThreadsRestoresAsynchronousComp
MaxShaderCompilerThreadsKHR(1);
Vector<String> sources;
const Vector<GLuint> shaders = EnqueueBacklog(64, 5000, sources);
const Bool anyOutstanding = std::any_of(shaders.begin(), shaders.end(), [](const GLuint shader) {
return QueryShaderCompletion(shader) == GL_FALSE;
});
const Bool anyOutstanding = std::any_of(
shaders.begin(), shaders.end(), [](const GLuint shader) { return QueryShaderCompletion(shader) == GL_FALSE; });
if (!anyOutstanding) {
GTEST_SKIP() << "the pool drained the backlog before the first query; asynchrony not observable here";
}
@@ -516,15 +515,17 @@ TEST_F(ParallelShaderCompileTest, MaxShaderCompilerThreadsIgnoresTheCurrentBudge
TEST_F(ParallelShaderCompileTest, BothBackendsAdvertiseTheExtensionIffAsyncIsEnabled) {
{
const AsyncModeScope async(true);
EXPECT_TRUE(Advertises(MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false),
E_GL_KHR_parallel_shader_compile));
EXPECT_TRUE(
Advertises(MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false),
E_GL_KHR_parallel_shader_compile));
EXPECT_TRUE(Advertises(MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false),
E_GL_KHR_parallel_shader_compile));
}
{
const AsyncModeScope async(false);
EXPECT_FALSE(Advertises(MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false),
E_GL_KHR_parallel_shader_compile))
EXPECT_FALSE(
Advertises(MG_Backend::DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false),
E_GL_KHR_parallel_shader_compile))
<< "MOBILEGL_ASYNC_SHADER_COMPILE=0 must withdraw the extension, not only the threading";
EXPECT_FALSE(Advertises(MG_Backend::DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false),
E_GL_KHR_parallel_shader_compile))
@@ -365,8 +365,8 @@ TEST(ProgramArtifactsCodec, ACompactArchiveOfTenEmptySpirvModulesRoundTrips) {
spirv.generatedSpirv.resize(10);
Vector<Uint8> bytes;
EncodeProgramArtifacts(LinkArtifacts{}, spirv, bytes);
const SizeT remaining = BytesAfterTheCount(bytes, spirv.generatedSpirv.size(),
Vector<Uint8>(10 * sizeof(Uint64), 0));
const SizeT remaining =
BytesAfterTheCount(bytes, spirv.generatedSpirv.size(), Vector<Uint8>(10 * sizeof(Uint64), 0));
ASSERT_LT(remaining, spirv.generatedSpirv.size() * sizeof(Vector<unsigned>))
<< "fixture: a sizeof(value_type) charge would admit this count, so the case could not go red";
@@ -375,7 +375,8 @@ TEST(ProgramArtifactsCodec, ACompactArchiveOfTenEmptySpirvModulesRoundTrips) {
ASSERT_TRUE(DecodeProgramArtifacts(bytes.data(), bytes.size(), decodedLink, decodedSpirv))
<< "a SpirvArtifacts with ten empty modules, which this encoder wrote, was refused";
ASSERT_EQ(decodedSpirv.generatedSpirv.size(), 10u);
for (const auto& module : decodedSpirv.generatedSpirv) EXPECT_TRUE(module.empty());
for (const auto& module : decodedSpirv.generatedSpirv)
EXPECT_TRUE(module.empty());
Vector<Uint8> reencoded;
EncodeProgramArtifacts(decodedLink, decodedSpirv, reencoded);
EXPECT_EQ(reencoded, bytes);
@@ -392,8 +393,7 @@ TEST(ProgramArtifactsCodec, ATruncatedStreamIsRefusedNotGuessed) {
// Cut at a spread of points rather than one: the header, a length prefix, the middle of a
// string and the last byte all fail through different branches.
for (const SizeT cut : {SizeT{0}, SizeT{4}, SizeT{9}, bytes.size() / 3, bytes.size() / 2,
bytes.size() - 1}) {
for (const SizeT cut : {SizeT{0}, SizeT{4}, SizeT{9}, bytes.size() / 3, bytes.size() / 2, bytes.size() - 1}) {
LinkArtifacts link;
SpirvArtifacts spirv;
link.infoLog = "must be cleared";
@@ -432,8 +432,7 @@ TEST(ProgramArtifactsCodec, AVectorCountCannotReservePastTheRemainingArchiveByte
ASSERT_GT(perElement, 1u);
ASSERT_LT(perElement, sizeof(UniformReflection));
const Uint64 forgedCount = static_cast<Uint64>(available / perElement) + 1;
ASSERT_LT(forgedCount, static_cast<Uint64>(available))
<< "fixture must pass the old count <= remaining check";
ASSERT_LT(forgedCount, static_cast<Uint64>(available)) << "fixture must pass the old count <= remaining check";
std::memcpy(bytes.data() + countOffset, &forgedCount, sizeof(forgedCount));
LinkArtifacts link;
@@ -121,9 +121,10 @@ namespace {
RecordProperty("sizeof_XfbVarying", static_cast<int>(sizeof(XfbVarying)));
RecordProperty("sizeof_LinkArtifacts", static_cast<int>(sizeof(LinkArtifacts)));
RecordProperty("sizeof_SpirvArtifacts", static_cast<int>(sizeof(SpirvArtifacts)));
std::printf("sizeof: TypeFacts=%zu ResourceReflection=%zu XfbVarying=%zu LinkArtifacts=%zu SpirvArtifacts=%zu\n",
sizeof(TypeFacts), sizeof(ResourceReflection), sizeof(XfbVarying), sizeof(LinkArtifacts),
sizeof(SpirvArtifacts));
std::printf(
"sizeof: TypeFacts=%zu ResourceReflection=%zu XfbVarying=%zu LinkArtifacts=%zu SpirvArtifacts=%zu\n",
sizeof(TypeFacts), sizeof(ResourceReflection), sizeof(XfbVarying), sizeof(LinkArtifacts),
sizeof(SpirvArtifacts));
#ifdef MGL_LINKARTIFACTS_SIZE // whichever STL branch the header pinned, this twin follows it
EXPECT_EQ(sizeof(ResourceReflection), static_cast<std::size_t>(MGL_RESOURCEREFLECTION_SIZE));
EXPECT_EQ(sizeof(XfbVarying), static_cast<std::size_t>(MGL_XFBVARYING_SIZE));
@@ -97,10 +97,11 @@ namespace {
return Props(program, iface, index, props);
}
GLenum TakeError() { return GetError(); }
GLenum TakeError() {
return GetError();
}
void ClearErrors() {
for (int i = 0; i < 32 && TakeError() != GL_NO_ERROR; ++i) {
}
for (int i = 0; i < 32 && TakeError() != GL_NO_ERROR; ++i) {}
}
const char* kSimpleVs = R"(#version 430
@@ -221,12 +222,9 @@ void main(void)
GL_REFERENCED_BY_VERTEX_SHADER,
GL_LOCATION,
GL_IS_PER_PATCH};
EXPECT_EQ(PropsOf(p, GL_PROGRAM_INPUT, "a", props),
(std::vector<GLint>{2, GL_FLOAT_MAT4, 1, 0, 0, 1, 0, 0}));
EXPECT_EQ(PropsOf(p, GL_PROGRAM_INPUT, "c[0]", props),
(std::vector<GLint>{5, GL_FLOAT, 2, 0, 0, 1, 5, 0}));
EXPECT_EQ(PropsOf(p, GL_PROGRAM_INPUT, "d", props),
(std::vector<GLint>{5, GL_FLOAT_MAT2x3, 2, 0, 0, 1, 7, 0}));
EXPECT_EQ(PropsOf(p, GL_PROGRAM_INPUT, "a", props), (std::vector<GLint>{2, GL_FLOAT_MAT4, 1, 0, 0, 1, 0, 0}));
EXPECT_EQ(PropsOf(p, GL_PROGRAM_INPUT, "c[0]", props), (std::vector<GLint>{5, GL_FLOAT, 2, 0, 0, 1, 5, 0}));
EXPECT_EQ(PropsOf(p, GL_PROGRAM_INPUT, "d", props), (std::vector<GLint>{5, GL_FLOAT_MAT2x3, 2, 0, 0, 1, 7, 0}));
EXPECT_EQ(TakeError(), GL_NO_ERROR);
}
@@ -271,10 +269,10 @@ void main() {
EXPECT_EQ(GetProgramResourceLocationIndex(p, GL_PROGRAM_OUTPUT, name), 0) << name;
}
const std::vector<GLenum> props = {GL_NAME_LENGTH, GL_TYPE, GL_ARRAY_SIZE, GL_REFERENCED_BY_FRAGMENT_SHADER,
GL_LOCATION, GL_IS_PER_PATCH, GL_LOCATION_INDEX};
EXPECT_EQ(PropsOf(p, GL_PROGRAM_OUTPUT, "a", props),
(std::vector<GLint>{5, GL_FLOAT_VEC3, 2, 1, 0, 0, 0}));
const std::vector<GLenum> props = {
GL_NAME_LENGTH, GL_TYPE, GL_ARRAY_SIZE, GL_REFERENCED_BY_FRAGMENT_SHADER,
GL_LOCATION, GL_IS_PER_PATCH, GL_LOCATION_INDEX};
EXPECT_EQ(PropsOf(p, GL_PROGRAM_OUTPUT, "a", props), (std::vector<GLint>{5, GL_FLOAT_VEC3, 2, 1, 0, 0, 0}));
EXPECT_EQ(PropsOf(p, GL_PROGRAM_OUTPUT, "d", props), (std::vector<GLint>{5, GL_INT, 2, 1, 5, 0, 0}));
EXPECT_EQ(TakeError(), GL_NO_ERROR);
}
@@ -299,8 +297,8 @@ void main(void) { gl_FragDepth = 0.1; gl_SampleMask[0] = 1; }
EXPECT_EQ(GetProgramResourceLocationIndex(p, GL_PROGRAM_OUTPUT, "gl_FragDepth"), -1);
EXPECT_EQ(GetProgramResourceLocationIndex(p, GL_PROGRAM_OUTPUT, "gl_SampleMask[0]"), -1);
const std::vector<GLenum> props = {GL_NAME_LENGTH, GL_TYPE, GL_ARRAY_SIZE, GL_REFERENCED_BY_FRAGMENT_SHADER,
GL_LOCATION, GL_LOCATION_INDEX};
const std::vector<GLenum> props = {
GL_NAME_LENGTH, GL_TYPE, GL_ARRAY_SIZE, GL_REFERENCED_BY_FRAGMENT_SHADER, GL_LOCATION, GL_LOCATION_INDEX};
EXPECT_EQ(PropsOf(p, GL_PROGRAM_OUTPUT, "gl_FragDepth", props),
(std::vector<GLint>{13, GL_FLOAT, 1, 1, -1, -1}));
EXPECT_EQ(PropsOf(p, GL_PROGRAM_OUTPUT, "gl_SampleMask[0]", props),
@@ -377,9 +375,9 @@ void main() { color = vec4(0, 1, 0, 1) + recolor; }
GL_REFERENCED_BY_FRAGMENT_SHADER,
GL_REFERENCED_BY_VERTEX_SHADER,
GL_LOCATION};
EXPECT_EQ(PropsOf(p, GL_UNIFORM, "repos", props),
(std::vector<GLint>{6, GL_FLOAT_VEC4, 1, -1, -1, -1, -1, 0, -1, 0, 0, 1,
GetUniformLocation(p, "repos")}));
EXPECT_EQ(
PropsOf(p, GL_UNIFORM, "repos", props),
(std::vector<GLint>{6, GL_FLOAT_VEC4, 1, -1, -1, -1, -1, 0, -1, 0, 0, 1, GetUniformLocation(p, "repos")}));
EXPECT_EQ(PropsOf(p, GL_UNIFORM, "recolor", props),
(std::vector<GLint>{8, GL_FLOAT_VEC4, 1, -1, -1, -1, -1, 0, -1, 0, 1, 0,
GetUniformLocation(p, "recolor")}));
@@ -439,9 +437,9 @@ void main(void) {
GL_ATOMIC_COUNTER_BUFFER_INDEX,
GL_REFERENCED_BY_VERTEX_SHADER,
GL_LOCATION};
EXPECT_EQ(PropsOf(p, GL_UNIFORM, "a[2][1]", props),
(std::vector<GLint>{11, GL_FLOAT_VEC4, 5, -1, -1, -1, -1, 0, -1, 1,
GetUniformLocation(p, "a[2][1]")}));
EXPECT_EQ(
PropsOf(p, GL_UNIFORM, "a[2][1]", props),
(std::vector<GLint>{11, GL_FLOAT_VEC4, 5, -1, -1, -1, -1, 0, -1, 1, GetUniformLocation(p, "a[2][1]")}));
EXPECT_EQ(TakeError(), GL_NO_ERROR);
}
@@ -1089,7 +1087,8 @@ void main() {
const std::string n = std::to_string(count);
const std::string source = std::string(R"(#version 430
out vec4 color;
layout(r32i) uniform iimage2D u_image[)") + n + R"(];
layout(r32i) uniform iimage2D u_image[)") +
n + R"(];
void main() {
int value = 1;
for (int i = 0; i < )" + n + R"(; ++i) {
@@ -1245,7 +1244,8 @@ void main() {
)";
const std::string tes = std::string(R"(#version 430
layout(triangles) in;
layout(r32i) uniform iimage2D u_tesImage[)") + n + R"(];
layout(r32i) uniform iimage2D u_tesImage[)") +
n + R"(];
void main() {
int value = 1;
for (int i = 0; i < )" + n + R"(; ++i) {
@@ -1358,8 +1358,8 @@ void main() {
for (GLuint index = 0; index < static_cast<GLuint>(bufferCount); ++index) {
const std::vector<GLint> viaInterface =
Props(p, GL_ATOMIC_COUNTER_BUFFER, index,
{GL_BUFFER_BINDING, GL_BUFFER_DATA_SIZE, GL_NUM_ACTIVE_VARIABLES,
GL_REFERENCED_BY_VERTEX_SHADER, GL_REFERENCED_BY_FRAGMENT_SHADER});
{GL_BUFFER_BINDING, GL_BUFFER_DATA_SIZE, GL_NUM_ACTIVE_VARIABLES, GL_REFERENCED_BY_VERTEX_SHADER,
GL_REFERENCED_BY_FRAGMENT_SHADER});
ASSERT_EQ(viaInterface.size(), 5u);
EXPECT_EQ(activeBufferiv(index, GL_ATOMIC_COUNTER_BUFFER_BINDING), viaInterface[0]);
EXPECT_EQ(activeBufferiv(index, GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE), viaInterface[1]);
@@ -1412,16 +1412,15 @@ void main(void) {
EXPECT_EQ(Interfaceiv(p, GL_TRANSFORM_FEEDBACK_VARYING, GL_ACTIVE_RESOURCES), 6);
EXPECT_EQ(Interfaceiv(p, GL_TRANSFORM_FEEDBACK_VARYING, GL_MAX_NAME_LENGTH), 5);
for (const char* name : varyings) ExpectResource(p, GL_TRANSFORM_FEEDBACK_VARYING, name, name);
for (const char* name : varyings)
ExpectResource(p, GL_TRANSFORM_FEEDBACK_VARYING, name, name);
const std::vector<GLenum> props = {GL_NAME_LENGTH, GL_TYPE, GL_ARRAY_SIZE};
EXPECT_EQ(PropsOf(p, GL_TRANSFORM_FEEDBACK_VARYING, "a", props),
(std::vector<GLint>{2, GL_INT_VEC4, 1}));
EXPECT_EQ(PropsOf(p, GL_TRANSFORM_FEEDBACK_VARYING, "a", props), (std::vector<GLint>{2, GL_INT_VEC4, 1}));
EXPECT_EQ(PropsOf(p, GL_TRANSFORM_FEEDBACK_VARYING, "b[0]", props), (std::vector<GLint>{5, GL_FLOAT, 1}));
EXPECT_EQ(PropsOf(p, GL_TRANSFORM_FEEDBACK_VARYING, "c", props),
(std::vector<GLint>{2, GL_UNSIGNED_INT_VEC2, 1}));
EXPECT_EQ(PropsOf(p, GL_TRANSFORM_FEEDBACK_VARYING, "e", props),
(std::vector<GLint>{2, GL_FLOAT_VEC3, 2}));
EXPECT_EQ(PropsOf(p, GL_TRANSFORM_FEEDBACK_VARYING, "e", props), (std::vector<GLint>{2, GL_FLOAT_VEC3, 2}));
EXPECT_EQ(TakeError(), GL_NO_ERROR);
}
@@ -1447,7 +1446,8 @@ void main(void) {
EXPECT_EQ(Interfaceiv(p, GL_TRANSFORM_FEEDBACK_VARYING, GL_MAX_NAME_LENGTH), 19);
std::vector<std::string> names;
for (GLuint i = 0; i < 11; ++i) names.push_back(ResourceName(p, GL_TRANSFORM_FEEDBACK_VARYING, i));
for (GLuint i = 0; i < 11; ++i)
names.push_back(ResourceName(p, GL_TRANSFORM_FEEDBACK_VARYING, i));
const auto indexOf = [&names](const std::string& name) -> GLuint {
for (GLuint i = 0; i < names.size(); ++i) {
if (names[i] == name) return i;
@@ -1608,17 +1608,16 @@ void main() {
// A non-fragment stage's outputs are varyings: no color number, so no color index.
EXPECT_EQ(PropsOf(p, GL_PROGRAM_OUTPUT, "gl_Position", {GL_LOCATION_INDEX}), (std::vector<GLint>{-1}));
const std::vector<GLenum> stageProps = {
GL_NAME_LENGTH,
GL_TYPE,
GL_ARRAY_SIZE,
GL_REFERENCED_BY_COMPUTE_SHADER,
GL_REFERENCED_BY_FRAGMENT_SHADER,
GL_REFERENCED_BY_GEOMETRY_SHADER,
GL_REFERENCED_BY_TESS_CONTROL_SHADER,
GL_REFERENCED_BY_TESS_EVALUATION_SHADER,
GL_REFERENCED_BY_VERTEX_SHADER,
GL_IS_PER_PATCH};
const std::vector<GLenum> stageProps = {GL_NAME_LENGTH,
GL_TYPE,
GL_ARRAY_SIZE,
GL_REFERENCED_BY_COMPUTE_SHADER,
GL_REFERENCED_BY_FRAGMENT_SHADER,
GL_REFERENCED_BY_GEOMETRY_SHADER,
GL_REFERENCED_BY_TESS_CONTROL_SHADER,
GL_REFERENCED_BY_TESS_EVALUATION_SHADER,
GL_REFERENCED_BY_VERTEX_SHADER,
GL_IS_PER_PATCH};
EXPECT_EQ(PropsOf(p, GL_PROGRAM_INPUT, "gl_PerVertex.gl_Position", stageProps),
(std::vector<GLint>{25, GL_FLOAT_VEC4, 1, 0, 0, 1, 0, 0, 0, 0}));
EXPECT_EQ(PropsOf(p, GL_PROGRAM_OUTPUT, "gl_Position", stageProps),
@@ -1937,9 +1936,9 @@ void main() { color = u + v; }
ASSERT_NE(neverLinked, 0u);
ClearErrors();
for (const GLenum pname : {GL_ACTIVE_ATTRIBUTES, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, GL_ACTIVE_UNIFORMS,
GL_ACTIVE_UNIFORM_MAX_LENGTH, GL_ACTIVE_UNIFORM_BLOCKS,
GL_ACTIVE_ATOMIC_COUNTER_BUFFERS}) {
for (const GLenum pname :
{GL_ACTIVE_ATTRIBUTES, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, GL_ACTIVE_UNIFORMS, GL_ACTIVE_UNIFORM_MAX_LENGTH,
GL_ACTIVE_UNIFORM_BLOCKS, GL_ACTIVE_ATOMIC_COUNTER_BUFFERS}) {
GLint value = -1;
GetProgramiv(neverLinked, pname, &value);
ClearErrors();
@@ -1967,8 +1966,8 @@ void main() { color = u + v; }
GetProgramiv(brokenSource, GL_COMPUTE_WORK_GROUP_SIZE, localSize);
const GLenum computeError = TakeError();
ClearErrors();
EXPECT_TRUE(computeError == GL_INVALID_OPERATION || (localSize[0] == 0 && localSize[1] == 0 &&
localSize[2] == 0))
EXPECT_TRUE(computeError == GL_INVALID_OPERATION ||
(localSize[0] == 0 && localSize[1] == 0 && localSize[2] == 0))
<< "either the query is refused, or it answers the initial value - never both untouched "
"and unreported";
}
@@ -1998,8 +1997,8 @@ void main() { color = u + v; }
const GLenum compatibleSubroutinesProp = GL_COMPATIBLE_SUBROUTINES;
const GLenum notAProp = GL_TEXTURE_2D;
const auto lengthAfter = [&](GLuint program, GLenum iface, GLuint index, GLsizei propCount,
const GLenum* props, GLsizei bufSize, GLint* out) {
const auto lengthAfter = [&](GLuint program, GLenum iface, GLuint index, GLsizei propCount, const GLenum* props,
GLsizei bufSize, GLint* out) {
GLsizei length = kPoison;
GetProgramResourceiv(program, iface, index, propCount, props, bufSize, &length, out);
ClearErrors();
@@ -283,8 +283,7 @@ void main() { gl_Position = u_vsOnly; }
UseProgramStages(pipeline, GL_FRAGMENT_SHADER_BIT, fs);
ASSERT_EQ(GetError(), GL_NO_ERROR);
UseProgramStages(pipeline, GL_VERTEX_SHADER_BIT, vs);
ASSERT_EQ(GetError(), GL_INVALID_OPERATION)
<< "a program not linked as separable is not a legal pipeline stage";
ASSERT_EQ(GetError(), GL_INVALID_OPERATION) << "a program not linked as separable is not a legal pipeline stage";
{
const auto& pipelineObject = MG_State::pGLContext->MaterializeProgramPipelineObject(pipeline);
ASSERT_NE(pipelineObject, nullptr);
@@ -454,8 +453,7 @@ TEST_F(ProgramPipelineCompositeTest, ASamplerWritePerDrawDoesNotRebuildTheCompos
Uniform1i(sampler, unit);
const auto composite = DrawProgram();
ASSERT_NE(composite, nullptr);
EXPECT_EQ(composite.get(), first.get())
<< "the composite was rebuilt by a sampler-unit write at unit " << unit;
EXPECT_EQ(composite.get(), first.get()) << "the composite was rebuilt by a sampler-unit write at unit " << unit;
EXPECT_EQ(composite->GetLifetimeId(), firstLifetime) << "the composite's identity changed at unit " << unit;
// The value still has to ARRIVE - the whole point is that the mirror carries it now that
// the rebuild no longer does.
@@ -555,20 +553,17 @@ void main() { gl_Position = vec4(0.0); EmitVertex(); EndPrimitive(); }
ASSERT_FALSE(composite->HasLinkedShaderStage(ShaderStage::Vertex));
DrawArrays(GL_POINTS, 0, 1);
EXPECT_EQ(GetError(), GL_INVALID_OPERATION)
<< "a geometry stage with no vertex stage must refuse the draw";
EXPECT_EQ(GetError(), GL_INVALID_OPERATION) << "a geometry stage with no vertex stage must refuse the draw";
// A dispatch shares the same "is there a program, did it link" helper and legitimately has no
// vertex stage; the rule must not have leaked onto it. There is no compute stage here, so the
// error is the compute check's own - what matters is that the draw rule did not fire first
// with a different meaning.
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {}
BindProgramPipeline(0);
DeleteProgramPipelines(1, &pipeline);
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {}
}
// GL 4.6 core 7.3: only a SEPARABLE program may have a geometry (or tessellation) stage without a
@@ -616,7 +611,8 @@ void main() { gl_Position = vec4(0.0); }
// One separable program carrying BOTH the vertex and the fragment stage.
const GLuint both = CreateProgram();
ProgramParameteri(both, GL_PROGRAM_SEPARABLE, GL_TRUE);
for (const auto& [stage, source] : {std::pair{GL_VERTEX_SHADER, kVf}, std::pair{GL_FRAGMENT_SHADER, kSharedUniformFs}}) {
for (const auto& [stage, source] :
{std::pair{GL_VERTEX_SHADER, kVf}, std::pair{GL_FRAGMENT_SHADER, kSharedUniformFs}}) {
const GLuint shader = CreateShader(stage);
ShaderSource(shader, 1, &source, nullptr);
CompileShader(shader);
@@ -669,8 +665,7 @@ void main() { gl_Position = vec4(0.0); }
BindProgramPipeline(0);
DeleteProgramPipelines(1, &pipeline);
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {}
}
// KHR-GL4x.geometry_shader.api.program_pipeline_vs_gs_capture: a vertex-only separable program
@@ -710,8 +705,7 @@ void main() { color = vec4(vertexID[0]); gl_Position = vec4(0.0); EmitVertex();
BindProgramPipeline(0);
DeleteProgramPipelines(1, &pipeline);
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {}
}
// ---------------------------------------------------------------------------------------------
+96 -119
View File
@@ -38,8 +38,7 @@ protected:
// GL error flags are sticky per code and the context outlives an individual test in this
// binary, so a pending error would be handed to whoever runs next.
static void DrainProgramTestErrors() {
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {}
}
};
@@ -474,7 +473,7 @@ namespace {
class ScopedLimitsBackend {
public:
ScopedLimitsBackend(): m_previous(Move(MG_Backend::pActiveBackendObject)) {
ScopedLimitsBackend() : m_previous(Move(MG_Backend::pActiveBackendObject)) {
MG_Backend::pActiveBackendObject = MakeUnique<StorageBlockLimitsBackend>();
}
~ScopedLimitsBackend() { MG_Backend::pActiveBackendObject = Move(m_previous); }
@@ -564,8 +563,7 @@ void main() {
ASSERT_EQ(spvReflectCreateShaderModule(spirv.size() * sizeof(Uint), spirv.data(), &module),
SPV_REFLECT_RESULT_SUCCESS);
uint32_t count = 0;
ASSERT_EQ(spvReflectEnumerateDescriptorBindings(&module, &count, nullptr),
SPV_REFLECT_RESULT_SUCCESS);
ASSERT_EQ(spvReflectEnumerateDescriptorBindings(&module, &count, nullptr), SPV_REFLECT_RESULT_SUCCESS);
std::vector<SpvReflectDescriptorBinding*> bindings(count);
if (count != 0) {
ASSERT_EQ(spvReflectEnumerateDescriptorBindings(&module, &count, bindings.data()),
@@ -579,8 +577,7 @@ void main() {
return lhs->binding < rhs->binding;
});
for (const SpvReflectDescriptorBinding* binding : bindings) {
if (binding == nullptr ||
binding->descriptor_type != SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER) {
if (binding == nullptr || binding->descriptor_type != SPV_REFLECT_DESCRIPTOR_TYPE_STORAGE_BUFFER) {
continue;
}
const String name = normalise(*binding);
@@ -613,9 +610,7 @@ void main() {
<< "the arrayed SSBO must collapse to one entry named without its subscript";
// The atomic counter is in the BACKEND's space even though GL's own enumeration excludes it.
EXPECT_NE(std::find_if(archived.begin(), archived.end(),
[](const String& name) {
return name.rfind("gl_AtomicCounterBlock", 0) == 0;
}),
[](const String& name) { return name.rfind("gl_AtomicCounterBlock", 0) == 0; }),
archived.end())
<< "the synthesized atomic-counter block is a STORAGE_BUFFER descriptor in SPIR-V, so "
"DirectVulkan's index space contains it and the archive has to as well";
@@ -741,8 +736,7 @@ TEST_F(ProgramTest, CompileAndLink) {
// glGetnUniform* (GL 4.5 / KHR_robustness): the same answers, bounded by bufSize. A
// destination too small for the uniform's components is GL_INVALID_OPERATION and untouched.
while (GetError() != GL_NO_ERROR) {
}
while (GetError() != GL_NO_ERROR) {}
float boundedRed[4] = {-1.0f, -1.0f, -1.0f, -1.0f};
GetnUniformfv(program, locRed, static_cast<GLsizei>(3 * sizeof(float)), boundedRed);
EXPECT_EQ(GetError(), static_cast<GLenum>(GL_NO_ERROR));
@@ -769,7 +763,8 @@ TEST_F(ProgramTest, CompileAndLink) {
String source;
auto& spirvCode = shaderSpirvs[index];
MG_Util::ShaderTranspiler::SpvcSession spvcSession(spirvCode, MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
MG_Util::ShaderTranspiler::SpvcSession spvcSession(spirvCode,
MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
spvc_compiler_options options;
spvcSession.CreateOptions(&options);
@@ -1613,7 +1608,8 @@ TEST_F(ProgramTest, CompileAndLinkWithExplicitVertexIn) {
char* pSrcVertIn = nullptr;
const char* needle = "layout(location = 2) in vec2 UV0;";
for (auto spirv : spirvs) {
MG_Util::ShaderTranspiler::SpvcSession spvcSession(spirv, MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
MG_Util::ShaderTranspiler::SpvcSession spvcSession(spirv,
MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
spvc_compiler_options options;
spvcSession.CreateOptions(&options);
@@ -1838,7 +1834,8 @@ TEST_F(ProgramTest, CompileAndLinkWithExplicitFragmentOut) {
char* pSrcfragOut = nullptr;
const char* needle = "layout(location = 7) out vec4 fragColor;";
// for (auto spirv: spirvs) {
MG_Util::ShaderTranspiler::SpvcSession spvcSession(fragSpirv, MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
MG_Util::ShaderTranspiler::SpvcSession spvcSession(fragSpirv,
MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
spvc_compiler_options options;
spvcSession.CreateOptions(&options);
@@ -2131,7 +2128,8 @@ TEST_F(ProgramTest, CompileShaderWithSamplerAsVarName) {
auto programObject = MG_State::pGLContext->GetCurrentProgram();
auto& spirvs = programObject->GetGeneratedSpirv();
auto& fragSpirv = spirvs[programObject->GetShaderIndexByStage(ShaderStage::Fragment)];
MG_Util::ShaderTranspiler::SpvcSession spvcSession(fragSpirv, MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
MG_Util::ShaderTranspiler::SpvcSession spvcSession(fragSpirv,
MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
spvc_compiler_options options;
spvcSession.CreateOptions(&options);
@@ -2155,17 +2153,11 @@ namespace {
const char* vsSrc = R"(#version 330 core
void main() { gl_Position = vec4(0.0); }
)";
std::string fsSrc = std::string("#version 330 core\n") +
"layout(std140" + matrixLayout + ") uniform Block {\n" +
" float uScalar;\n" +
" vec4 uArray[3];\n" +
" mat4 uMatrix;\n" +
"};\n" +
"uniform sampler2D uTex;\n" +
"out vec4 fragColor;\n" +
std::string fsSrc = std::string("#version 330 core\n") + "layout(std140" + matrixLayout +
") uniform Block {\n" + " float uScalar;\n" + " vec4 uArray[3];\n" +
" mat4 uMatrix;\n" + "};\n" + "uniform sampler2D uTex;\n" + "out vec4 fragColor;\n" +
"void main() {\n" +
" fragColor = texture(uTex, uArray[0].xy) * uScalar * uMatrix[0];\n" +
"}\n";
" fragColor = texture(uTex, uArray[0].xy) * uScalar * uMatrix[0];\n" + "}\n";
const char* fsPtr = fsSrc.c_str();
GLuint vs = CreateShader(GL_VERTEX_SHADER);
@@ -2265,8 +2257,7 @@ TEST_F(ProgramTest, GetActiveUniformsivStd140Block) {
GLint size = 0;
GLenum type = 0;
GetActiveUniform(program, m, sizeof(nameBuf), &nameLen, &size, &type, nameBuf);
EXPECT_EQ(QueryUniformiv(program, m, GL_UNIFORM_NAME_LENGTH),
static_cast<GLint>(std::strlen(nameBuf) + 1));
EXPECT_EQ(QueryUniformiv(program, m, GL_UNIFORM_NAME_LENGTH), static_cast<GLint>(std::strlen(nameBuf) + 1));
EXPECT_EQ(GetError(), GL_NO_ERROR);
}
@@ -2405,7 +2396,7 @@ void main() {
ASSERT_GE(locUiOne, 0) << "body: '" << body << "'";
UseProgram(program);
Uniform1i(locOne, 1); // crashed with a null MapUBO() before the fallback storage
Uniform1i(locOne, 1); // crashed with a null MapUBO() before the fallback storage
Uniform1i(locUiOne, 2);
EXPECT_EQ(GetError(), GL_NO_ERROR) << "body: '" << body << "'";
@@ -2458,8 +2449,7 @@ void main() {
// Distinct scalar leaves must land at distinct UBO offsets (they all aliased
// offset 0 before the fix).
const char* scalarLeaves[] = {"s[0].b[0].a", "s[0].b[1].a", "s[0].b[2].a", "s[1].a", "s[1].b[1].a",
"s[1].b[2].a"};
const char* scalarLeaves[] = {"s[0].b[0].a", "s[0].b[1].a", "s[0].b[2].a", "s[1].a", "s[1].b[1].a", "s[1].b[2].a"};
const GLfloat scalarValues[] = {0.5f, 0.25f, 0.125f, 7.0f, 3.0f, 4.0f};
for (SizeT i = 0; i < std::size(scalarLeaves); ++i) {
const GLint loc = GetUniformLocation(program, scalarLeaves[i]);
@@ -2588,8 +2578,7 @@ void main() {
Uint firstOffset = MG_State::GLState::ProgramObject::kInvalidUniformOffset;
for (int i = 0; i < outer; ++i) {
for (int j = 0; j < inner; ++j) {
const std::string name =
std::string(base) + "[" + std::to_string(i) + "][" + std::to_string(j) + "]";
const std::string name = std::string(base) + "[" + std::to_string(i) + "][" + std::to_string(j) + "]";
const GLint location = GetUniformLocation(program, name.c_str());
ASSERT_GE(location, 0) << name;
const Uint offset = programObject->GetUniformOffset(static_cast<Uint>(location));
@@ -2929,8 +2918,7 @@ TEST_F(ProgramTest, UniformBlockProgramInterfaceMatchesTheUniformBlockList) {
GetProgramInterfaceiv(program, GL_SHADER_STORAGE_BLOCK, GL_ACTIVE_RESOURCES, &storageBlocks);
EXPECT_EQ(storageBlocks, 1);
EXPECT_EQ(GetProgramResourceIndex(program, GL_UNIFORM_BLOCK, "AVeryLongStorageBlockName"), GL_INVALID_INDEX);
EXPECT_NE(GetProgramResourceIndex(program, GL_SHADER_STORAGE_BLOCK, "AVeryLongStorageBlockName"),
GL_INVALID_INDEX);
EXPECT_NE(GetProgramResourceIndex(program, GL_SHADER_STORAGE_BLOCK, "AVeryLongStorageBlockName"), GL_INVALID_INDEX);
// ... and the buffer variable by GL_BUFFER_VARIABLE, not GL_UNIFORM.
EXPECT_NE(GetProgramResourceIndex(program, GL_BUFFER_VARIABLE, "storageVec"), GL_INVALID_INDEX);
EXPECT_EQ(GetProgramResourceIndex(program, GL_UNIFORM, "storageVec"), GL_INVALID_INDEX);
@@ -2948,8 +2936,7 @@ TEST_F(ProgramTest, UniformBlockProgramInterfaceMatchesTheUniformBlockList) {
ASSERT_EQ(memberCount, 1) << blockName;
const GLenum activeVariables = GL_ACTIVE_VARIABLES;
GLint memberIndex = -1;
GetProgramResourceiv(program, GL_UNIFORM_BLOCK, interfaceIndex, 1, &activeVariables, 1, nullptr,
&memberIndex);
GetProgramResourceiv(program, GL_UNIFORM_BLOCK, interfaceIndex, 1, &activeVariables, 1, nullptr, &memberIndex);
GLint viaBlockiv = -1;
GetActiveUniformBlockiv(program, interfaceIndex, GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES, &viaBlockiv);
EXPECT_EQ(memberIndex, viaBlockiv) << blockName;
@@ -2966,8 +2953,7 @@ TEST_F(ProgramTest, ActiveUniformsExcludeBufferVariablesButKeepAtomicCounters) {
GLint activeUniforms = -1;
GetProgramiv(program, GL_ACTIVE_UNIFORMS, &activeUniforms);
ASSERT_EQ(activeUniforms, 4)
<< "uboVec, uboVec2[0], uScale and counter - storageVec is a buffer variable";
ASSERT_EQ(activeUniforms, 4) << "uboVec, uboVec2[0], uScale and counter - storageVec is a buffer variable";
// Neither spelling of the buffer variable is a uniform index.
EXPECT_EQ(UniformIndexByName(program, "storageVec"), GL_INVALID_INDEX);
@@ -2989,8 +2975,7 @@ TEST_F(ProgramTest, ActiveUniformsExcludeBufferVariablesButKeepAtomicCounters) {
// uniform block, and still points at its atomic counter BUFFER.
const GLuint counter = UniformIndexByName(program, "counter");
ASSERT_NE(counter, GL_INVALID_INDEX);
EXPECT_EQ(QueryUniformiv(program, counter, GL_UNIFORM_TYPE),
static_cast<GLint>(GL_UNSIGNED_INT_ATOMIC_COUNTER));
EXPECT_EQ(QueryUniformiv(program, counter, GL_UNIFORM_TYPE), static_cast<GLint>(GL_UNSIGNED_INT_ATOMIC_COUNTER));
EXPECT_EQ(QueryUniformiv(program, counter, GL_UNIFORM_BLOCK_INDEX), -1);
EXPECT_EQ(QueryUniformiv(program, counter, GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX), 0);
EXPECT_EQ(QueryUniformiv(program, counter, GL_UNIFORM_OFFSET), 0);
@@ -3005,8 +2990,7 @@ TEST_F(ProgramTest, ActiveUniformsExcludeBufferVariablesButKeepAtomicCounters) {
GetActiveAtomicCounterBufferiv(program, 0, GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS, &counterCount);
ASSERT_EQ(counterCount, 1);
GLint counterIndex = -1;
GetActiveAtomicCounterBufferiv(program, 0, GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES,
&counterIndex);
GetActiveAtomicCounterBufferiv(program, 0, GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES, &counterIndex);
EXPECT_EQ(static_cast<GLuint>(counterIndex), counter);
GLint counterBinding = -1;
GetActiveAtomicCounterBufferiv(program, 0, GL_ATOMIC_COUNTER_BUFFER_BINDING, &counterBinding);
@@ -3134,8 +3118,7 @@ void main() { fragColor = uUsedColor; }
GLint size = 0;
GLenum type = 0;
GetActiveUniform(program, static_cast<GLuint>(i), sizeof(nameBuf), &nameLen, &size, &type, nameBuf);
EXPECT_TRUE(std::strcmp(nameBuf, "uDeadVec") != 0 && std::strcmp(nameBuf, "uDeadFloat") != 0)
<< nameBuf;
EXPECT_TRUE(std::strcmp(nameBuf, "uDeadVec") != 0 && std::strcmp(nameBuf, "uDeadFloat") != 0) << nameBuf;
}
// No named blocks are declared, so GL must see zero uniform blocks - the global
@@ -3334,8 +3317,8 @@ namespace {
Vector<MobileGL::String> esslModules;
auto programObj = MG_State::pGLContext->GetProgramObject(program);
for (auto& spirvCode : programObj->GetGeneratedSpirv()) {
MG_Util::ShaderTranspiler::SpvcSession spvcSession(
spirvCode, MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
MG_Util::ShaderTranspiler::SpvcSession spvcSession(spirvCode,
MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
spvc_compiler_options options;
spvcSession.CreateOptions(&options);
spvc_compiler_options_set_uint(options, SPVC_COMPILER_OPTION_GLSL_VERSION, 320);
@@ -3434,8 +3417,7 @@ namespace {
const MobileGL::String needle = name + "(";
for (SizeT pos = essl.find(needle); pos != String::npos; pos = essl.find(needle, pos + 1)) {
const char before = pos == 0 ? ' ' : essl[pos - 1];
const bool isIdentifierChar =
std::isalnum(static_cast<unsigned char>(before)) != 0 || before == '_';
const bool isIdentifierChar = std::isalnum(static_cast<unsigned char>(before)) != 0 || before == '_';
if (!isIdentifierChar) return true;
}
return false;
@@ -3538,7 +3520,6 @@ void main() { fragColor = vec4(pow(uBase, 2.2), 1.0); }
EXPECT_EQ(GetError(), GL_NO_ERROR);
}
// ---------------------------------------------------------------------------
// P0b: source-hash dedupe for shader recompiles.
// Layer 1 - the same shader object re-sourced with byte-identical text keeps its
@@ -3911,8 +3892,7 @@ void main() { fragColor = vec4(1.0); }
// GL 4.6 core 7.1: shaderType is an enum, so an unrecognised one is INVALID_ENUM - it used to be
// reported as INVALID_VALUE. glCreateShaderProgramv adds a count < 0 gate ahead of everything.
TEST_F(ProgramTest, CreateShaderAndCreateShaderProgramvReportTheRightErrorClasses) {
while (GetError() != GL_NO_ERROR) {
}
while (GetError() != GL_NO_ERROR) {}
EXPECT_EQ(CreateShader(GL_FLOAT), 0u);
EXPECT_EQ(GetError(), GL_INVALID_ENUM);
@@ -3988,8 +3968,7 @@ void main() { fragColor = vec4(1.0); }
const GLuint fs = CompileShaderChecked(GL_FRAGMENT_SHADER, fsSource);
{
const String source = String("#version 430 core\nlayout(location = ") +
std::to_string(maxLocations - 1) +
const String source = String("#version 430 core\nlayout(location = ") + std::to_string(maxLocations - 1) +
") uniform vec4 uAtLimit;\nvoid main() { gl_Position = uAtLimit; }\n";
const GLuint vs = CompileShaderChecked(GL_VERTEX_SHADER, source.c_str());
const GLuint program = LinkVsFs(vs, fs, GL_TRUE);
@@ -3997,8 +3976,7 @@ void main() { fragColor = vec4(1.0); }
<< "the last location in the pool is legal and must come back verbatim";
}
{
const String source = String("#version 430 core\nlayout(location = ") +
std::to_string(maxLocations - 4) +
const String source = String("#version 430 core\nlayout(location = ") + std::to_string(maxLocations - 4) +
") uniform vec4 uSpill[8];\nvoid main() { gl_Position = uSpill[0]; }\n";
const GLuint vs = CompileShaderChecked(GL_VERTEX_SHADER, source.c_str());
(void)LinkVsFs(vs, fs, GL_FALSE);
@@ -4052,8 +4030,8 @@ void main() {
GLint arrayStride;
};
const Expectation expectations[] = {
{"ac_counter0", 1, 0, 0}, {"ac_counter1", 1, 4, 0}, {"ac_counter2", 1, 8, 0},
{"ac_counter67[0]", 2, 12, 4}, {"ac_counter3", 1, 20, 0},
{"ac_counter0", 1, 0, 0}, {"ac_counter1", 1, 4, 0}, {"ac_counter2", 1, 8, 0},
{"ac_counter67[0]", 2, 12, 4}, {"ac_counter3", 1, 20, 0},
};
for (const auto& expected : expectations) {
@@ -4171,8 +4149,8 @@ TEST_F(ProgramTest, ImplicitLocationStaysInRangeWhenABufferBlockSharesTheProgram
const GLint location = GetUniformLocation(program, implicitName.c_str());
EXPECT_EQ(location, holeBase) << "the implicit uniform must take the one free span left";
EXPECT_LT(location + implicitCount, maxLocations + 1)
<< "locations " << location << ".." << (location + implicitCount - 1)
<< " must stay inside 0.." << (maxLocations - 1);
<< "locations " << location << ".." << (location + implicitCount - 1) << " must stay inside 0.."
<< (maxLocations - 1);
EXPECT_EQ(GetUniformLocation(program, "cs_result"), -1);
};
@@ -4248,8 +4226,7 @@ void main() {
};
const auto atTheLimit = buildWith(maxPatchVertices);
EXPECT_EQ(atTheLimit.first, GL_TRUE)
<< "exactly GL_MAX_PATCH_VERTICES is legal: " << atTheLimit.second;
EXPECT_EQ(atTheLimit.first, GL_TRUE) << "exactly GL_MAX_PATCH_VERTICES is legal: " << atTheLimit.second;
const auto pastTheLimit = buildWith(maxPatchVertices + 1);
EXPECT_EQ(pastTheLimit.first, GL_FALSE) << "one past GL_MAX_PATCH_VERTICES must not link";
@@ -4459,8 +4436,7 @@ void main() { fragColorA = vec4(1.0); fragColorB = vec4(0.5); }
GetProgramInfoLog(program, sizeof(log), nullptr, log);
return std::string(log);
}();
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {
}
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {}
}
// An API colour index of ZERO is "no override", not "index 0". glBindFragDataLocation is
@@ -4510,8 +4486,7 @@ void main() { fragColor0 = vec4(1.0); fragColor1 = vec4(0.5); }
GetProgramiv(program, GL_LINK_STATUS, &linkStatus);
EXPECT_EQ(linkStatus, GL_TRUE);
EXPECT_EQ(GetFragDataIndex(program, "fragColor1"), 1);
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {
}
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {}
}
TEST_F(ProgramTest, GetProgramivReportsTheGeometryStageLinkProperties) {
@@ -4523,8 +4498,8 @@ void main() {
EndPrimitive();
}
)";
const GLuint program =
LinkStages({{GL_VERTEX_SHADER, kPassthroughVs}, {GL_GEOMETRY_SHADER, gs}, {GL_FRAGMENT_SHADER, kPassthroughFs}});
const GLuint program = LinkStages(
{{GL_VERTEX_SHADER, kPassthroughVs}, {GL_GEOMETRY_SHADER, gs}, {GL_FRAGMENT_SHADER, kPassthroughFs}});
GLint value = -1;
GetProgramiv(program, GL_GEOMETRY_INPUT_TYPE, &value);
@@ -4541,8 +4516,8 @@ void main() {
// says "a linked program object with a geometry shader", which the conformance suite checks
// from both sides.
const GLuint noGeometry = LinkStages({{GL_VERTEX_SHADER, kPassthroughVs}, {GL_FRAGMENT_SHADER, kPassthroughFs}});
for (const GLenum pname : {GL_GEOMETRY_INPUT_TYPE, GL_GEOMETRY_OUTPUT_TYPE, GL_GEOMETRY_VERTICES_OUT,
GL_GEOMETRY_SHADER_INVOCATIONS}) {
for (const GLenum pname :
{GL_GEOMETRY_INPUT_TYPE, GL_GEOMETRY_OUTPUT_TYPE, GL_GEOMETRY_VERTICES_OUT, GL_GEOMETRY_SHADER_INVOCATIONS}) {
GetProgramiv(noGeometry, pname, &value);
EXPECT_EQ(GetError(), static_cast<GLenum>(GL_INVALID_OPERATION)) << "pname " << pname;
}
@@ -4613,15 +4588,18 @@ void main() { gl_Position = gl_in[0].gl_Position; }
TEST_F(ProgramTest, ContextWideTessellationPropertiesAnswerEveryWidth) {
GLfloat outer[4] = {-1.0f, -1.0f, -1.0f, -1.0f};
GetFloatv(GL_PATCH_DEFAULT_OUTER_LEVEL, outer);
for (const GLfloat level : outer) EXPECT_FLOAT_EQ(level, 1.0f);
for (const GLfloat level : outer)
EXPECT_FLOAT_EQ(level, 1.0f);
GLfloat inner[2] = {-1.0f, -1.0f};
GetFloatv(GL_PATCH_DEFAULT_INNER_LEVEL, inner);
for (const GLfloat level : inner) EXPECT_FLOAT_EQ(level, 1.0f);
for (const GLfloat level : inner)
EXPECT_FLOAT_EQ(level, 1.0f);
GLboolean outerBools[4] = {GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE};
GetBooleanv(GL_PATCH_DEFAULT_OUTER_LEVEL, outerBools);
for (const GLboolean level : outerBools) EXPECT_EQ(level, GL_TRUE);
for (const GLboolean level : outerBools)
EXPECT_EQ(level, GL_TRUE);
GLint restart = -1;
GetIntegerv(GL_PRIMITIVE_RESTART_FOR_PATCHES_SUPPORTED, &restart);
@@ -4702,16 +4680,16 @@ TEST_F(ProgramTest, AtomicCounterBindingAtTheLimitIsRejected) {
GetIntegerv(GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS, &maxAtomicBindings);
ASSERT_GT(maxAtomicBindings, 0);
const String legal = "#version 430 core\nlayout(local_size_x = 1) in;\nlayout(binding = " +
std::to_string(maxAtomicBindings - 1) +
") uniform atomic_uint counter;\nvoid main() { atomicCounterIncrement(counter); }\n";
const String legal =
"#version 430 core\nlayout(local_size_x = 1) in;\nlayout(binding = " + std::to_string(maxAtomicBindings - 1) +
") uniform atomic_uint counter;\nvoid main() { atomicCounterIncrement(counter); }\n";
EXPECT_EQ(LinkComputeProgramStatus(legal.c_str()), GL_TRUE)
<< "the last counter binding in the range is legal and must still link";
String infoLog;
const String overRange = "#version 430 core\nlayout(local_size_x = 1) in;\nlayout(binding = " +
std::to_string(maxAtomicBindings) +
") uniform atomic_uint counter;\nvoid main() { atomicCounterIncrement(counter); }\n";
const String overRange =
"#version 430 core\nlayout(local_size_x = 1) in;\nlayout(binding = " + std::to_string(maxAtomicBindings) +
") uniform atomic_uint counter;\nvoid main() { atomicCounterIncrement(counter); }\n";
EXPECT_EQ(LinkComputeProgramStatus(overRange.c_str(), &infoLog), GL_FALSE)
<< "an atomic_uint binding at GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS must be rejected";
@@ -4754,9 +4732,9 @@ TEST_F(ProgramTest, StorageBlockBindingAtTheLimitIsStillRejected) {
GTEST_SKIP() << "no storage-buffer binding points advertised in this configuration";
}
const String overRange = "#version 430 core\nlayout(local_size_x = 1) in;\nlayout(binding = " +
std::to_string(maxStorageBindings) +
", std430) buffer Blk { vec4 v; } blk;\nvoid main() { blk.v = vec4(0.0); }\n";
const String overRange =
"#version 430 core\nlayout(local_size_x = 1) in;\nlayout(binding = " + std::to_string(maxStorageBindings) +
", std430) buffer Blk { vec4 v; } blk;\nvoid main() { blk.v = vec4(0.0); }\n";
EXPECT_EQ(LinkComputeProgramStatus(overRange.c_str()), GL_FALSE);
DrainProgramTestErrors();
@@ -4846,8 +4824,7 @@ TEST_F(ProgramTest, UniformEntryPointsRejectAnUnlinkedProgram) {
const GLfloat value = 1.0f;
ProgramUniform1fv(program, -1, 1, &value);
EXPECT_EQ(GetError(), GL_INVALID_OPERATION)
<< "the link check has to run BEFORE the location == -1 early-out";
EXPECT_EQ(GetError(), GL_INVALID_OPERATION) << "the link check has to run BEFORE the location == -1 early-out";
ProgramUniform1f(program, 0, 1.0f);
EXPECT_EQ(GetError(), GL_INVALID_OPERATION);
@@ -4925,41 +4902,41 @@ namespace {
EXPECT_EQ(GetError(), GL_NO_ERROR) << "the call recorded more than one error";
}
// 255 words
const unsigned int kVertexModule[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000020u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0009000fu, 0x00000000u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x00000012u, 0x0000001eu,
0x0000001fu, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u,
0x00060005u, 0x0000000bu, 0x505f6c67u, 0x65567265u, 0x78657472u, 0x00000000u, 0x00060006u, 0x0000000bu,
0x00000000u, 0x505f6c67u, 0x7469736fu, 0x006e6f69u, 0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u,
0x746e696fu, 0x657a6953u, 0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u, 0x4470696cu,
0x61747369u, 0x0065636eu, 0x00070006u, 0x0000000bu, 0x00000003u, 0x435f6c67u, 0x446c6c75u, 0x61747369u,
0x0065636eu, 0x00030005u, 0x0000000du, 0x00000000u, 0x00040005u, 0x00000012u, 0x736f5061u, 0x00000000u,
0x00040005u, 0x00000014u, 0x61635375u, 0x0000656cu, 0x00050005u, 0x0000001eu, 0x565f6c67u, 0x65747265u,
0x00444978u, 0x00060005u, 0x0000001fu, 0x495f6c67u, 0x6174736eu, 0x4965636eu, 0x00000044u, 0x00030047u,
0x0000000bu, 0x00000002u, 0x00050048u, 0x0000000bu, 0x00000000u, 0x0000000bu, 0x00000000u, 0x00050048u,
0x0000000bu, 0x00000001u, 0x0000000bu, 0x00000001u, 0x00050048u, 0x0000000bu, 0x00000002u, 0x0000000bu,
0x00000003u, 0x00050048u, 0x0000000bu, 0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u, 0x00000012u,
0x0000001eu, 0x00000000u, 0x00040047u, 0x00000014u, 0x00000001u, 0x00000003u, 0x00040047u, 0x0000001eu,
0x0000000bu, 0x00000005u, 0x00040047u, 0x0000001fu, 0x0000000bu, 0x00000006u, 0x00020013u, 0x00000002u,
0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u,
0x00000006u, 0x00000004u, 0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u, 0x0004002bu, 0x00000008u,
0x00000009u, 0x00000001u, 0x0004001cu, 0x0000000au, 0x00000006u, 0x00000009u, 0x0006001eu, 0x0000000bu,
0x00000007u, 0x00000006u, 0x0000000au, 0x0000000au, 0x00040020u, 0x0000000cu, 0x00000003u, 0x0000000bu,
0x0004003bu, 0x0000000cu, 0x0000000du, 0x00000003u, 0x00040015u, 0x0000000eu, 0x00000020u, 0x00000001u,
0x0004002bu, 0x0000000eu, 0x0000000fu, 0x00000000u, 0x00040017u, 0x00000010u, 0x00000006u, 0x00000002u,
0x00040020u, 0x00000011u, 0x00000001u, 0x00000010u, 0x0004003bu, 0x00000011u, 0x00000012u, 0x00000001u,
0x00040032u, 0x00000006u, 0x00000014u, 0x3f800000u, 0x0004002bu, 0x00000006u, 0x00000016u, 0x00000000u,
0x0004002bu, 0x00000006u, 0x00000017u, 0x3f800000u, 0x00040020u, 0x0000001bu, 0x00000003u, 0x00000007u,
0x00040020u, 0x0000001du, 0x00000001u, 0x0000000eu, 0x0004003bu, 0x0000001du, 0x0000001eu, 0x00000001u,
0x0004003bu, 0x0000001du, 0x0000001fu, 0x00000001u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u,
0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003du, 0x00000010u, 0x00000013u, 0x00000012u, 0x0005008eu,
0x00000010u, 0x00000015u, 0x00000013u, 0x00000014u, 0x00050051u, 0x00000006u, 0x00000018u, 0x00000015u,
0x00000000u, 0x00050051u, 0x00000006u, 0x00000019u, 0x00000015u, 0x00000001u, 0x00070050u, 0x00000007u,
0x0000001au, 0x00000018u, 0x00000019u, 0x00000016u, 0x00000017u, 0x00050041u, 0x0000001bu, 0x0000001cu,
0x0000000du, 0x0000000fu, 0x0003003eu, 0x0000001cu, 0x0000001au, 0x000100fdu, 0x00010038u,
};
// 255 words
const unsigned int kVertexModule[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000020u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0009000fu, 0x00000000u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x00000012u, 0x0000001eu,
0x0000001fu, 0x00030003u, 0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u,
0x00060005u, 0x0000000bu, 0x505f6c67u, 0x65567265u, 0x78657472u, 0x00000000u, 0x00060006u, 0x0000000bu,
0x00000000u, 0x505f6c67u, 0x7469736fu, 0x006e6f69u, 0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u,
0x746e696fu, 0x657a6953u, 0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u, 0x4470696cu,
0x61747369u, 0x0065636eu, 0x00070006u, 0x0000000bu, 0x00000003u, 0x435f6c67u, 0x446c6c75u, 0x61747369u,
0x0065636eu, 0x00030005u, 0x0000000du, 0x00000000u, 0x00040005u, 0x00000012u, 0x736f5061u, 0x00000000u,
0x00040005u, 0x00000014u, 0x61635375u, 0x0000656cu, 0x00050005u, 0x0000001eu, 0x565f6c67u, 0x65747265u,
0x00444978u, 0x00060005u, 0x0000001fu, 0x495f6c67u, 0x6174736eu, 0x4965636eu, 0x00000044u, 0x00030047u,
0x0000000bu, 0x00000002u, 0x00050048u, 0x0000000bu, 0x00000000u, 0x0000000bu, 0x00000000u, 0x00050048u,
0x0000000bu, 0x00000001u, 0x0000000bu, 0x00000001u, 0x00050048u, 0x0000000bu, 0x00000002u, 0x0000000bu,
0x00000003u, 0x00050048u, 0x0000000bu, 0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u, 0x00000012u,
0x0000001eu, 0x00000000u, 0x00040047u, 0x00000014u, 0x00000001u, 0x00000003u, 0x00040047u, 0x0000001eu,
0x0000000bu, 0x00000005u, 0x00040047u, 0x0000001fu, 0x0000000bu, 0x00000006u, 0x00020013u, 0x00000002u,
0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u,
0x00000006u, 0x00000004u, 0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u, 0x0004002bu, 0x00000008u,
0x00000009u, 0x00000001u, 0x0004001cu, 0x0000000au, 0x00000006u, 0x00000009u, 0x0006001eu, 0x0000000bu,
0x00000007u, 0x00000006u, 0x0000000au, 0x0000000au, 0x00040020u, 0x0000000cu, 0x00000003u, 0x0000000bu,
0x0004003bu, 0x0000000cu, 0x0000000du, 0x00000003u, 0x00040015u, 0x0000000eu, 0x00000020u, 0x00000001u,
0x0004002bu, 0x0000000eu, 0x0000000fu, 0x00000000u, 0x00040017u, 0x00000010u, 0x00000006u, 0x00000002u,
0x00040020u, 0x00000011u, 0x00000001u, 0x00000010u, 0x0004003bu, 0x00000011u, 0x00000012u, 0x00000001u,
0x00040032u, 0x00000006u, 0x00000014u, 0x3f800000u, 0x0004002bu, 0x00000006u, 0x00000016u, 0x00000000u,
0x0004002bu, 0x00000006u, 0x00000017u, 0x3f800000u, 0x00040020u, 0x0000001bu, 0x00000003u, 0x00000007u,
0x00040020u, 0x0000001du, 0x00000001u, 0x0000000eu, 0x0004003bu, 0x0000001du, 0x0000001eu, 0x00000001u,
0x0004003bu, 0x0000001du, 0x0000001fu, 0x00000001u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u,
0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003du, 0x00000010u, 0x00000013u, 0x00000012u, 0x0005008eu,
0x00000010u, 0x00000015u, 0x00000013u, 0x00000014u, 0x00050051u, 0x00000006u, 0x00000018u, 0x00000015u,
0x00000000u, 0x00050051u, 0x00000006u, 0x00000019u, 0x00000015u, 0x00000001u, 0x00070050u, 0x00000007u,
0x0000001au, 0x00000018u, 0x00000019u, 0x00000016u, 0x00000017u, 0x00050041u, 0x0000001bu, 0x0000001cu,
0x0000000du, 0x0000000fu, 0x0003003eu, 0x0000001cu, 0x0000001au, 0x000100fdu, 0x00010038u,
};
} // namespace
TEST_F(ProgramTest, ShaderBinaryStoresASpirvModuleAndTheStateQueryReportsIt) {
+210 -215
View File
@@ -170,16 +170,13 @@ void main() {
const auto countOccurrences = [](const String& text, const String& needle) {
SizeT count = 0;
for (SizeT offset = 0; (offset = text.find(needle, offset)) != String::npos;
offset += needle.size()) {
for (SizeT offset = 0; (offset = text.find(needle, offset)) != String::npos; offset += needle.size()) {
++count;
}
return count;
};
EXPECT_EQ(countOccurrences(outputText, "OpCapability StorageImageReadWithoutFormat"), 1u)
<< outputText;
EXPECT_EQ(countOccurrences(outputText, "OpCapability StorageImageWriteWithoutFormat"), 1u)
<< outputText;
EXPECT_EQ(countOccurrences(outputText, "OpCapability StorageImageReadWithoutFormat"), 1u) << outputText;
EXPECT_EQ(countOccurrences(outputText, "OpCapability StorageImageWriteWithoutFormat"), 1u) << outputText;
EXPECT_EQ(countOccurrences(outputText, "2D 0 0 0 2 Unknown"), 1u) << outputText;
EXPECT_NE(outputText.find("Binding 0"), String::npos) << outputText;
EXPECT_NE(outputText.find("Binding 1"), String::npos) << outputText;
@@ -296,10 +293,8 @@ TEST_F(ProgramUtilTest, UnformattedFloatStorageImagesKeepFloatAtomicImageTypesTy
EXPECT_EQ(outputText.find("StorageImageReadWithoutFormat"), String::npos) << outputText;
EXPECT_EQ(outputText.find("StorageImageWriteWithoutFormat"), String::npos) << outputText;
String validationDiagnostics;
tools.SetMessageConsumer([&validationDiagnostics](spv_message_level_t, const char*,
const spv_position_t&, const char* message) {
validationDiagnostics += message;
});
tools.SetMessageConsumer([&validationDiagnostics](spv_message_level_t, const char*, const spv_position_t&,
const char* message) { validationDiagnostics += message; });
EXPECT_TRUE(tools.Validate(outputBinary)) << validationDiagnostics;
}
@@ -506,8 +501,8 @@ void main() {
ShaderAttrib vertexAttrib{.shaderType = GL_VERTEX_SHADER, .sourceStr = vertexSource};
auto vertexResult = ShaderCompiler::CompileShader(vertexAttrib);
if (!vertexResult) {
FAIL() << "errc: " << vertexResult.error().errc << "\nlog: " << vertexResult.error().log
<< "\nsource:\n" << vertexSource;
FAIL() << "errc: " << vertexResult.error().errc << "\nlog: " << vertexResult.error().log << "\nsource:\n"
<< vertexSource;
}
String fragmentSource = R"(#version 150
@@ -527,8 +522,8 @@ void main() {
ShaderAttrib fragmentAttrib{.shaderType = GL_FRAGMENT_SHADER, .sourceStr = fragmentSource};
auto fragmentResult = ShaderCompiler::CompileShader(fragmentAttrib);
if (!fragmentResult) {
FAIL() << "errc: " << fragmentResult.error().errc << "\nlog: " << fragmentResult.error().log
<< "\nsource:\n" << fragmentSource;
FAIL() << "errc: " << fragmentResult.error().errc << "\nlog: " << fragmentResult.error().log << "\nsource:\n"
<< fragmentSource;
}
}
@@ -609,25 +604,24 @@ TEST_F(ProgramUtilTest, PreprocessRejectsMalformedVersionDirectives) {
PreprocessShaderSource(ShaderStage::Fragment, src);
ShaderAttrib attrib{.shaderType = GL_FRAGMENT_SHADER, .sourceStr = src};
auto res = ShaderCompiler::CompileShader(attrib);
return res ? false : true; // "rejects" == compile failed
return res ? false : true; // "rejects" == compile failed
};
// Silently legalized today - the five this fix must flip to rejection:
EXPECT_TRUE(rejects(String("#version 329") + body)) << "329 is not a real version";
EXPECT_TRUE(rejects(String("#version 331") + body)) << "331 is not a real version";
EXPECT_TRUE(rejects(String("#version 330 foo") + body)) << "unknown profile keyword";
EXPECT_TRUE(rejects(String("#version 330.0") + body)) << "float literal, not an int token";
EXPECT_TRUE(rejects(String("#version 329") + body)) << "329 is not a real version";
EXPECT_TRUE(rejects(String("#version 331") + body)) << "331 is not a real version";
EXPECT_TRUE(rejects(String("#version 330 foo") + body)) << "unknown profile keyword";
EXPECT_TRUE(rejects(String("#version 330.0") + body)) << "float literal, not an int token";
EXPECT_TRUE(rejects(String("#version 330 foobar") + body)) << "trailing tokens after a valid decl";
// Already rejected (no leading integer, or #version is not the first token) - pinned so a future
// change to the normalizer cannot start legalizing them either:
EXPECT_TRUE(rejects(String("#version") + body)) << "missing version number";
EXPECT_TRUE(rejects(String("#version foobar") + body)) << "identifier where the int belongs";
EXPECT_TRUE(rejects(String("#version AAA") + body)) << "identifier where the int belongs";
EXPECT_TRUE(rejects(String("#version") + body)) << "missing version number";
EXPECT_TRUE(rejects(String("#version foobar") + body)) << "identifier where the int belongs";
EXPECT_TRUE(rejects(String("#version AAA") + body)) << "identifier where the int belongs";
EXPECT_TRUE(rejects(String("precision mediump float;\n#version 330") + body))
<< "#version must be the first statement";
EXPECT_TRUE(rejects(String("#define FOO BAR\n#version 330") + body))
<< "#version must precede a #define";
EXPECT_TRUE(rejects(String("#define FOO BAR\n#version 330") + body)) << "#version must precede a #define";
}
// The PASS half of the same CTS group: a valid decl, and #version preceded only by whitespace or a
@@ -645,10 +639,8 @@ TEST_F(ProgramUtilTest, PreprocessKeepsValidVersionDirectivesCompiling) {
};
EXPECT_TRUE(compiles(String("#version 330 core") + body));
EXPECT_TRUE(compiles(String("\n#version 330 core") + body))
<< "leading whitespace is legal before #version";
EXPECT_TRUE(compiles(String("// test\n#version 330 core") + body))
<< "a leading comment is legal before #version";
EXPECT_TRUE(compiles(String("\n#version 330 core") + body)) << "leading whitespace is legal before #version";
EXPECT_TRUE(compiles(String("// test\n#version 330 core") + body)) << "a leading comment is legal before #version";
}
TEST_F(ProgramUtilTest, PreprocessUsesRealSpacedVersionDirectiveForInjectedOutput) {
@@ -921,7 +913,6 @@ void main() {
}
}
const char* vs = R"(#version 150
in vec4 Position;
@@ -1253,10 +1244,11 @@ void main() { fragColor = vColor; }
auto essl = ShaderCompiler::DecompileShader(session);
if (!essl) FAIL() << "decompile errc: " << essl.error().errc << "\nlog: " << essl.error().log;
EXPECT_NE(essl.value().find("noperspective"), String::npos)
<< "noperspective was lost before it reached SPIR-V:\n" << essl.value();
EXPECT_NE(essl.value().find("noperspective"), String::npos) << "noperspective was lost before it reached SPIR-V:\n"
<< essl.value();
EXPECT_NE(essl.value().find("GL_NV_shader_noperspective_interpolation"), String::npos)
<< "SPIRV-Cross must require the NV extension for ES noperspective:\n" << essl.value();
<< "SPIRV-Cross must require the NV extension for ES noperspective:\n"
<< essl.value();
}
// The old handling was a naked substring erase of "noperspective", so any identifier that merely
@@ -1271,8 +1263,8 @@ out vec4 fragColor;
void main() { fragColor = vec4(noperspectiveBlend); }
)";
PreprocessShaderSource(ShaderStage::Fragment, source);
EXPECT_NE(source.find("noperspectiveBlend"), String::npos)
<< "identifier was corrupted by substring stripping:\n" << source;
EXPECT_NE(source.find("noperspectiveBlend"), String::npos) << "identifier was corrupted by substring stripping:\n"
<< source;
}
// The DirectGLES fallback for devices without GL_NV_shader_noperspective_interpolation: stripping the
@@ -1315,10 +1307,10 @@ void main() { fragColor = vColor; }
SpvcSession session(stripped, SessionUsageBit::Transpile);
auto essl = ShaderCompiler::DecompileShader(session);
if (!essl) FAIL() << "decompile errc: " << essl.error().errc << "\nlog: " << essl.error().log;
EXPECT_EQ(essl.value().find("noperspective"), String::npos)
<< "the decoration should be gone:\n" << essl.value();
EXPECT_EQ(essl.value().find("noperspective"), String::npos) << "the decoration should be gone:\n" << essl.value();
EXPECT_EQ(essl.value().find("GL_NV_shader_noperspective_interpolation"), String::npos)
<< "no extension require without the decoration:\n" << essl.value();
<< "no extension require without the decoration:\n"
<< essl.value();
}
// Directly exercises BOTH decoration forms StripNoPerspectivePass handles: a plain-variable
@@ -1374,8 +1366,8 @@ TEST_F(ProgramUtilTest, StripNoPerspectivePassRemovesBothDecorateForms) {
String inputText;
ASSERT_TRUE(tools.Disassemble(inputBinary, &inputText));
ASSERT_EQ(countNoPerspective(inputText), 2u)
<< "fixture must carry both a plain and a member NoPerspective:\n" << inputText;
ASSERT_EQ(countNoPerspective(inputText), 2u) << "fixture must carry both a plain and a member NoPerspective:\n"
<< inputText;
Vector<uint32_t> outputBinary;
ASSERT_TRUE(ShaderCompiler::StripNoPerspectiveForEssl(inputBinary, outputBinary));
@@ -1384,11 +1376,10 @@ TEST_F(ProgramUtilTest, StripNoPerspectivePassRemovesBothDecorateForms) {
String outputText;
ASSERT_TRUE(tools.Disassemble(outputBinary, &outputText));
EXPECT_EQ(countNoPerspective(outputText), 0u)
<< "both NoPerspective decorations (OpDecorate and OpMemberDecorate) must be stripped:\n" << outputText;
EXPECT_NE(outputText.find("Flat"), String::npos)
<< "the unrelated Flat decoration must survive:\n" << outputText;
EXPECT_NE(outputText.find("Location"), String::npos)
<< "Location decorations must survive:\n" << outputText;
<< "both NoPerspective decorations (OpDecorate and OpMemberDecorate) must be stripped:\n"
<< outputText;
EXPECT_NE(outputText.find("Flat"), String::npos) << "the unrelated Flat decoration must survive:\n" << outputText;
EXPECT_NE(outputText.find("Location"), String::npos) << "Location decorations must survive:\n" << outputText;
}
// Phase 2 emulation - fragment side. On a device without the NV extension the NoPerspective input is
@@ -1431,7 +1422,8 @@ void main() { f = vColor; }
if (!essl) FAIL() << "decompile: " << essl.error().log;
EXPECT_EQ(essl.value().find("noperspective"), String::npos) << essl.value();
EXPECT_EQ(essl.value().find("GL_NV_shader_noperspective_interpolation"), String::npos) << essl.value();
EXPECT_NE(essl.value().find("gl_FragCoord"), String::npos) << "recovery must reference gl_FragCoord:\n" << essl.value();
EXPECT_NE(essl.value().find("gl_FragCoord"), String::npos) << "recovery must reference gl_FragCoord:\n"
<< essl.value();
}
// Phase 2 emulation - vertex side. The NoPerspective output is pre-multiplied by gl_Position.w before
@@ -1470,27 +1462,28 @@ void main() { gl_Position = pos; vColor = pos; }
auto essl = ShaderCompiler::DecompileShader(session);
if (!essl) FAIL() << "decompile: " << essl.error().log;
EXPECT_EQ(essl.value().find("noperspective"), String::npos) << essl.value();
EXPECT_NE(essl.value().find("gl_Position"), String::npos) << "pre-multiply must reference gl_Position:\n" << essl.value();
EXPECT_NE(essl.value().find("gl_Position"), String::npos) << "pre-multiply must reference gl_Position:\n"
<< essl.value();
}
namespace {
// Compiles one shader stage through the full pipeline and returns its SPIR-V, or fails the test.
MobileGL::Vector<uint32_t> CompileStageSpirv(GLenum type, const char* src) {
using namespace MG_Util::ShaderTranspiler;
ShaderAttrib attrib{.shaderType = type, .sourceStr = src};
auto res = ShaderCompiler::CompileShader(attrib);
EXPECT_TRUE(static_cast<bool>(res)) << (res ? "" : res.error().log);
if (!res) return {};
ProgramAttrib pa{.shaders = {res.value()}};
auto pr = ShaderCompiler::LinkProgram(pa);
EXPECT_TRUE(static_cast<bool>(pr)) << (pr ? "" : pr.error().log);
if (!pr) return {};
ProgramBinaryAttrib ba{.shaderTypes = {type}, .program = *pr.value()};
auto br = ShaderCompiler::GetSpirvBinaryFromProgram(ba);
EXPECT_TRUE(static_cast<bool>(br)) << (br ? "" : br.error().log);
if (!br || br.value().empty()) return {};
return br.value()[0];
}
// Compiles one shader stage through the full pipeline and returns its SPIR-V, or fails the test.
MobileGL::Vector<uint32_t> CompileStageSpirv(GLenum type, const char* src) {
using namespace MG_Util::ShaderTranspiler;
ShaderAttrib attrib{.shaderType = type, .sourceStr = src};
auto res = ShaderCompiler::CompileShader(attrib);
EXPECT_TRUE(static_cast<bool>(res)) << (res ? "" : res.error().log);
if (!res) return {};
ProgramAttrib pa{.shaders = {res.value()}};
auto pr = ShaderCompiler::LinkProgram(pa);
EXPECT_TRUE(static_cast<bool>(pr)) << (pr ? "" : pr.error().log);
if (!pr) return {};
ProgramBinaryAttrib ba{.shaderTypes = {type}, .program = *pr.value()};
auto br = ShaderCompiler::GetSpirvBinaryFromProgram(ba);
EXPECT_TRUE(static_cast<bool>(br)) << (br ? "" : br.error().log);
if (!br || br.value().empty()) return {};
return br.value()[0];
}
} // namespace
// Regression: the vertex pre-multiply must be applied exactly once (in main), not once per function.
@@ -1542,8 +1535,8 @@ void main() { f = vec4(vColor.x); }
ASSERT_TRUE(tools.Disassemble(emulated, &dis));
ASSERT_TRUE(tools.Validate(emulated)) << dis;
EXPECT_EQ(dis.find("NoPerspective"), String::npos) << dis;
EXPECT_NE(dis.find("FragCoord"), String::npos)
<< "the component read must still be recovered via gl_FragCoord.w:\n" << dis;
EXPECT_NE(dis.find("FragCoord"), String::npos) << "the component read must still be recovered via gl_FragCoord.w:\n"
<< dis;
}
// Coverage: a scalar float varying exercises the OpFMul path; a vector varying the OpVectorTimesScalar
@@ -1567,7 +1560,8 @@ void main() { f = vec4(a, b, 1.0); }
EXPECT_EQ(dis.find("NoPerspective"), String::npos) << dis;
EXPECT_NE(dis.find("OpFMul"), String::npos) << "the scalar varying must scale with OpFMul:\n" << dis;
EXPECT_NE(dis.find("OpVectorTimesScalar"), String::npos)
<< "the vector varying must scale with OpVectorTimesScalar:\n" << dis;
<< "the vector varying must scale with OpVectorTimesScalar:\n"
<< dis;
}
const char* vs_location = R"(#version 460
@@ -2032,8 +2026,7 @@ TEST_F(ProgramUtilTest, DecomposeWorkgroupVec3InSpirvPass) {
SpvcSession session(optimized, SessionUsageBit::Transpile);
auto sourceRes = ShaderCompiler::DecompileShader(session);
ASSERT_TRUE(sourceRes.has_value()) << "errc: " << sourceRes.error().errc
<< "\nlog: " << sourceRes.error().log;
ASSERT_TRUE(sourceRes.has_value()) << "errc: " << sourceRes.error().errc << "\nlog: " << sourceRes.error().log;
const String& source = sourceRes.value();
// The decomposed output must not contain a `shared vec3` declaration.
@@ -2042,9 +2035,8 @@ TEST_F(ProgramUtilTest, DecomposeWorkgroupVec3InSpirvPass) {
<< source;
// It should now use a scalar array form (shared float ...).
EXPECT_NE(source.find("shared float"), std::string::npos)
<< "Expected `shared float` in decomposed output:\n"
<< source;
EXPECT_NE(source.find("shared float"), std::string::npos) << "Expected `shared float` in decomposed output:\n"
<< source;
EXPECT_EQ(source.find("= shared_memory[0]"), std::string::npos)
<< "Decomposed output kept an invalid whole-row shared-memory load:\n"
@@ -2094,7 +2086,6 @@ void main() {
ASSERT_TRUE(ShaderCompiler::SanitizeAndOptimizeBinary(binRes->at(0), optimized));
}
TEST_F(ProgramUtilTest, PreprocessCoercesBlockPackingQualifiersToStd140) {
using namespace MG_Util::ShaderTranspiler;
@@ -2121,9 +2112,8 @@ void main() {
EXPECT_NE(source.find("layout ( std140 ) uniform SpacedBlock"), String::npos);
EXPECT_NE(source.find("layout(std140) uniform KeptBlock"), String::npos);
ShaderAttrib attrib{.shaderType = GL_VERTEX_SHADER,
.sourceStr = source,
.flags = ShaderCompileBits::CompileForOpenGL};
ShaderAttrib attrib{
.shaderType = GL_VERTEX_SHADER, .sourceStr = source, .flags = ShaderCompileBits::CompileForOpenGL};
auto res = ShaderCompiler::CompileShader(attrib);
if (!res) {
FAIL() << "errc: " << res.error().errc << "\nlog: " << res.error().log << "\nsource:\n" << source;
@@ -2378,7 +2368,6 @@ TEST_F(ProgramUtilTest, CompileEnvFingerprintTracksEveryInput) {
CompileEnv otherExtensions = base;
otherExtensions.advertisedExtensions.push_back(MobileGL::E_GL_ARB_gpu_shader_int64);
EXPECT_NE(ComputeCompileEnvFingerprint(otherExtensions), baseline);
}
// The no-backend fallback must stay exactly what the pipeline used to do inline:
@@ -2639,8 +2628,7 @@ void main() {
explicitVertexIns["a_TexCoord"] = 2;
explicitVertexIns["iris_Normal"] = 10;
explicitVertexIns["mc_Entity"] = 11;
ProgramAttrib programAttrib{.shaders = {shaderResult.value()},
.explicitVertexInLocations = explicitVertexIns};
ProgramAttrib programAttrib{.shaders = {shaderResult.value()}, .explicitVertexInLocations = explicitVertexIns};
auto programResult = ShaderCompiler::LinkProgram(programAttrib);
ASSERT_TRUE(programResult) << programResult.error().log;
@@ -2653,10 +2641,10 @@ void main() {
// The authoritative check - this is the same validator whose VUID the driver enforces.
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
String validatorMessages;
tools.SetMessageConsumer([&validatorMessages](spv_message_level_t, const char*, const spv_position_t&,
const char* message) {
if (message != nullptr) validatorMessages += String(message) + "\n";
});
tools.SetMessageConsumer(
[&validatorMessages](spv_message_level_t, const char*, const spv_position_t&, const char* message) {
if (message != nullptr) validatorMessages += String(message) + "\n";
});
EXPECT_TRUE(tools.Validate(vertexBinary))
<< "the raw vertex module is not valid SPIR-V; Adreno rejects the whole pipeline for this "
<< "while lavapipe tolerates it:\n"
@@ -2689,8 +2677,7 @@ void main() {
for (const unsigned id : inputIds) {
if (builtInIds.count(id) != 0) continue;
const auto it = locationById.find(id);
ASSERT_NE(it, locationById.end())
<< "vertex input id " << id << " reached SPIR-V with no Location decoration";
ASSERT_NE(it, locationById.end()) << "vertex input id " << id << " reached SPIR-V with no Location decoration";
EXPECT_TRUE(usedLocations.insert(it->second).second)
<< "two vertex inputs were assigned location " << it->second;
++checked;
@@ -2718,10 +2705,17 @@ namespace {
if (wordCount == 0 || i + wordCount > spirv.size()) break;
if (opcode == kOpVariable && wordCount >= 4) {
switch (spirv[i + 3]) {
case kStorageClassInput: ++census.inputCount; break;
case kStorageClassOutput: ++census.outputCount; break;
case kStorageClassPrivate: ++census.privateCount; break;
default: break;
case kStorageClassInput:
++census.inputCount;
break;
case kStorageClassOutput:
++census.outputCount;
break;
case kStorageClassPrivate:
++census.privateCount;
break;
default:
break;
}
} else if (opcode == kOpFunctionCall) {
++census.functionCallCount;
@@ -2762,12 +2756,10 @@ vec4 helperTint() { return vec4(1.0); }
ADD_FAILURE() << programResult.error().log;
return {};
}
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_VERTEX_SHADER},
.program = *programResult.value()};
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_VERTEX_SHADER}, .program = *programResult.value()};
auto binaryResult = ShaderCompiler::GetSpirvBinaryFromProgram(binaryAttrib);
if (!binaryResult || binaryResult->size() != 1u) {
ADD_FAILURE() << (binaryResult ? "unexpected module count"
: binaryResult.error().log);
ADD_FAILURE() << (binaryResult ? "unexpected module count" : binaryResult.error().log);
return {};
}
return binaryResult->front();
@@ -2802,10 +2794,10 @@ TEST_F(ProgramUtilTest, DeadPrivateChainVertexInputIsEliminatedFromOptimizedBina
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
String validatorMessages;
tools.SetMessageConsumer([&validatorMessages](spv_message_level_t, const char*,
const spv_position_t&, const char* message) {
if (message != nullptr) validatorMessages += String(message) + "\n";
});
tools.SetMessageConsumer(
[&validatorMessages](spv_message_level_t, const char*, const spv_position_t&, const char* message) {
if (message != nullptr) validatorMessages += String(message) + "\n";
});
EXPECT_TRUE(tools.Validate(optimized)) << validatorMessages;
}
@@ -3026,8 +3018,7 @@ namespace {
ADD_FAILURE() << programResult.error().log;
return {};
}
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_FRAGMENT_SHADER},
.program = *programResult.value()};
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_FRAGMENT_SHADER}, .program = *programResult.value()};
auto binaryResult = ShaderCompiler::GetSpirvBinaryFromProgram(binaryAttrib);
if (!binaryResult || binaryResult->size() != 1u) {
ADD_FAILURE() << (binaryResult ? "unexpected module count" : binaryResult.error().log);
@@ -3103,16 +3094,19 @@ void main() {
const String disassembly = DisassembleSpirv(legalized);
EXPECT_FALSE(LegalizeFragmentOutputIndexPass::BinaryHasDynamicOutputIndexing(legalized))
<< "no fragment output may be left indexed by anything but a constant:\n" << disassembly;
<< "no fragment output may be left indexed by anything but a constant:\n"
<< disassembly;
EXPECT_EQ(disassembly.find("OpSwitch"), String::npos)
<< "a loop-derived index must fold, not fall back to the switch lowering:\n" << disassembly;
<< "a loop-derived index must fold, not fall back to the switch lowering:\n"
<< disassembly;
EXPECT_EQ(ShaderCompiler::SpirvValidationFailureCount(), failuresBefore)
<< "the legalized module must stay validator-clean";
const String essl = DecompileToEssl(legalized);
ASSERT_FALSE(essl.empty());
EXPECT_TRUE(AllArrayIndicesAreLiterals(essl, "coeff"))
<< "the generated ESSL still indexes a fragment output with a non-constant:\n" << essl;
<< "the generated ESSL still indexes a fragment output with a non-constant:\n"
<< essl;
}
// Marking a loop for unrolling means marking every loop enclosing it - SPIRV-Tools only unrolls
@@ -3173,8 +3167,7 @@ void main() {
}
)");
ASSERT_FALSE(raw.empty());
ASSERT_TRUE(LegalizeFragmentOutputIndexPass::BinaryHasDynamicOutputIndexing(raw))
<< DisassembleSpirv(raw);
ASSERT_TRUE(LegalizeFragmentOutputIndexPass::BinaryHasDynamicOutputIndexing(raw)) << DisassembleSpirv(raw);
const Uint64 failuresBefore = ShaderCompiler::SpirvValidationFailureCount();
@@ -3184,18 +3177,23 @@ void main() {
const String disassembly = DisassembleSpirv(legalized);
EXPECT_FALSE(LegalizeFragmentOutputIndexPass::BinaryHasDynamicOutputIndexing(legalized))
<< "the uniform-driven index must be lowered away:\n" << disassembly;
<< "the uniform-driven index must be lowered away:\n"
<< disassembly;
EXPECT_NE(disassembly.find("OpSwitch"), String::npos)
<< "the dynamic write must become a switch over the array range:\n" << disassembly;
<< "the dynamic write must become a switch over the array range:\n"
<< disassembly;
EXPECT_NE(disassembly.find("OpSelect"), String::npos)
<< "the dynamic read must become constant-indexed loads and a select:\n" << disassembly;
<< "the dynamic read must become constant-indexed loads and a select:\n"
<< disassembly;
EXPECT_EQ(ShaderCompiler::SpirvValidationFailureCount(), failuresBefore)
<< "the lowered module must stay validator-clean:\n" << disassembly;
<< "the lowered module must stay validator-clean:\n"
<< disassembly;
const String essl = DecompileToEssl(legalized);
ASSERT_FALSE(essl.empty());
EXPECT_TRUE(AllArrayIndicesAreLiterals(essl, "coeff"))
<< "the generated ESSL still indexes a fragment output with a non-constant:\n" << essl;
<< "the generated ESSL still indexes a fragment output with a non-constant:\n"
<< essl;
}
// The bound on the folding half. The index here IS loop-derived, so unrolling would fold it -
@@ -3227,19 +3225,23 @@ void main() {
const String disassembly = DisassembleSpirv(legalized);
EXPECT_FALSE(LegalizeFragmentOutputIndexPass::BinaryHasDynamicOutputIndexing(legalized))
<< "the index must be legalized even when the loop is left standing:\n" << disassembly;
<< "the index must be legalized even when the loop is left standing:\n"
<< disassembly;
EXPECT_NE(disassembly.find("OpLoopMerge"), String::npos)
<< "a 512-trip loop must NOT be unrolled - that is the whole point of the cap:\n"
<< disassembly;
EXPECT_NE(disassembly.find("OpSwitch"), String::npos)
<< "with the loop standing, the write must go through the switch lowering:\n" << disassembly;
<< "with the loop standing, the write must go through the switch lowering:\n"
<< disassembly;
EXPECT_EQ(ShaderCompiler::SpirvValidationFailureCount(), failuresBefore)
<< "lowering inside a loop body must stay validator-clean:\n" << disassembly;
<< "lowering inside a loop body must stay validator-clean:\n"
<< disassembly;
const String essl = DecompileToEssl(legalized);
ASSERT_FALSE(essl.empty());
EXPECT_TRUE(AllArrayIndicesAreLiterals(essl, "coeff"))
<< "the generated ESSL still indexes a fragment output with a non-constant:\n" << essl;
<< "the generated ESSL still indexes a fragment output with a non-constant:\n"
<< essl;
}
// The gate: a fragment shader that never indexes an output array dynamically must come back byte
@@ -3284,7 +3286,8 @@ void main() {
)");
ASSERT_FALSE(raw.empty());
EXPECT_FALSE(LegalizeFragmentOutputIndexPass::BinaryHasDynamicOutputIndexing(raw))
<< "only fragment outputs carry the constant-index rule:\n" << DisassembleSpirv(raw);
<< "only fragment outputs carry the constant-index rule:\n"
<< DisassembleSpirv(raw);
}
// ---------------------------------------------------------------------------------------
@@ -3426,8 +3429,7 @@ void main() { fragColor = vec4(texelFetch(Data, 3)); }
const String essl310 = emitAt(310);
ASSERT_FALSE(essl310.empty()) << "ESSL 310 emission failed outright";
EXPECT_NE(essl310.find("isamplerBuffer"), String::npos)
<< "the buffer sampler must survive to ESSL:\n" << essl310;
EXPECT_NE(essl310.find("isamplerBuffer"), String::npos) << "the buffer sampler must survive to ESSL:\n" << essl310;
EXPECT_NE(essl310.find("GL_EXT_texture_buffer"), String::npos)
<< "SPIRV-Cross requires EXT_texture_buffer below ESSL 320, and hardcodes that spelling - "
"which is the whole reason an OES-only driver needs the emitted directive retargeted:\n"
@@ -3441,7 +3443,6 @@ void main() { fragColor = vec4(texelFetch(Data, 3)); }
EXPECT_EQ(essl320.find("GL_EXT_texture_buffer"), String::npos)
<< "ES 3.2 has buffer textures in core; requiring the extension there would be wrong:\n"
<< essl320;
}
namespace {
@@ -3544,18 +3545,17 @@ TEST_F(ProgramUtilTest, Lower1DArrayImagesRewritesTheTypeAndWidensTheCoordinate)
ASSERT_TRUE(ShaderCompiler::Lower1DArrayImagesForEssl(spirv, lowered, true));
ASSERT_FALSE(lowered.empty());
EXPECT_EQ(Count1DArrayStorageImageTypes(lowered), 0u)
<< "no 1D-array storage image type may survive the pass:\n"
<< DisassembleSpirv(lowered);
EXPECT_EQ(Count1DArrayStorageImageTypes(lowered), 0u) << "no 1D-array storage image type may survive the pass:\n"
<< DisassembleSpirv(lowered);
EXPECT_EQ(ShaderCompiler::SpirvValidationFailureCount(), failuresBefore)
<< "the lowered module must stay validator-clean";
const String essl = DecompileToEssl(lowered);
ASSERT_FALSE(essl.empty());
EXPECT_NE(essl.find("uimage2DArray"), String::npos)
<< "the image must be declared as the 2D array the texture is stored as:\n" << essl;
EXPECT_EQ(essl.find("ivec2(ivec2("), String::npos)
<< "the malformed constructor must be gone:\n" << essl;
<< "the image must be declared as the 2D array the texture is stored as:\n"
<< essl;
EXPECT_EQ(essl.find("ivec2(ivec2("), String::npos) << "the malformed constructor must be gone:\n" << essl;
// The ORDER is the whole point, and it is what a widening that merely appended the 0 would
// get wrong while still producing a three-component constructor that compiles. The fixture
// reads (u=2, layer=3), and the ES 2D array holds height 1 with the layers in depth
@@ -3620,7 +3620,7 @@ layout (location = 0, r32ui) readonly uniform uimage1D i0;
layout (std430, binding = 0) buffer SSB { uint sum; } ssb;
void main() { ssb.sum = imageLoad(i0, 2).r; }
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
Vector<Uint32> lowered;
@@ -3630,7 +3630,8 @@ void main() { ssb.sum = imageLoad(i0, 2).r; }
const String essl = DecompileToEssl(lowered);
ASSERT_FALSE(essl.empty());
EXPECT_NE(essl.find("uimage2D "), String::npos)
<< "SPIRV-Cross's own 1D-as-2D emulation must still be what handles this:\n" << essl;
<< "SPIRV-Cross's own 1D-as-2D emulation must still be what handles this:\n"
<< essl;
}
// The negative control for the ATOMIC half, and the reason the non-arrayed case is in scope at
@@ -3650,14 +3651,16 @@ TEST_F(ProgramUtilTest, SpirvCrossEmitsAScalarCoordinateForA1DImageAtomic) {
const String essl = DecompileToEssl(spirv);
ASSERT_FALSE(essl.empty());
EXPECT_NE(essl.find("uimage2D"), String::npos)
<< "SPIRV-Cross declares the 1D image as 2D on ES; that half it does do:\n" << essl;
<< "SPIRV-Cross declares the 1D image as 2D on ES; that half it does do:\n"
<< essl;
EXPECT_NE(essl.find("imageAtomicAdd(i0, 2"), String::npos)
<< "SPIRV-Cross is expected to pass the SCALAR coordinate straight through to the atomic. "
"If this no longer happens, the non-arrayed half of Lower1DArrayImagesForEssl may no "
"longer be needed:\n"
<< essl;
EXPECT_EQ(essl.find("ivec2("), String::npos)
<< "nothing else in this fixture builds an ivec2, so its absence is the defect:\n" << essl;
<< "nothing else in this fixture builds an ivec2, so its absence is the defect:\n"
<< essl;
}
// The fix: the type becomes a plain 2D image - which is what MobileGL stores a GL_TEXTURE_1D in,
@@ -3688,8 +3691,8 @@ TEST_F(ProgramUtilTest, Lower1DArrayImagesWidensThe1DAtomicCoordinate) {
const String essl = DecompileToEssl(lowered);
ASSERT_FALSE(essl.empty());
EXPECT_NE(essl.find("uimage2D"), String::npos)
<< "the declaration must still be the 2D one the ES texture is:\n" << essl;
EXPECT_NE(essl.find("uimage2D"), String::npos) << "the declaration must still be the 2D one the ES texture is:\n"
<< essl;
EXPECT_NE(essl.find("imageAtomicAdd(i0, ivec2(2, 0)"), String::npos)
<< "the atomic must address the image with the same (u, 0) SPIRV-Cross writes for a read "
"or a write:\n"
@@ -3708,7 +3711,7 @@ layout (r32ui) coherent uniform uimage1D i0;
layout (std430, binding = 0) buffer SSB { uint sum; } ssb;
void main() { ssb.sum = imageAtomicAdd(i0, 2, 7u) + uint(imageSize(i0)); }
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
const auto traits = Lower1DArrayImagesPass::InspectBinary(spirv);
ASSERT_TRUE(traits.declaresImage && traits.queriesImageSize)
@@ -3732,7 +3735,7 @@ in vec2 vUv;
out vec4 fragColor;
void main() { fragColor = texture(uTex, vUv); }
)",
GL_FRAGMENT_SHADER);
GL_FRAGMENT_SHADER);
ASSERT_FALSE(spirv.empty());
Vector<Uint32> lowered;
@@ -3753,7 +3756,7 @@ layout (location = 0, r32ui) readonly uniform uimage1DArray i0;
layout (std430, binding = 0) buffer SSB { uint sum; } ssb;
void main() { ssb.sum = uint(imageSize(i0).x) + imageLoad(i0, ivec2(0, 0)).r; }
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
const auto traits = Lower1DArrayImagesPass::InspectBinary(spirv);
ASSERT_TRUE(traits.declaresImage && traits.queriesImageSize)
@@ -3782,8 +3785,7 @@ namespace {
const unsigned wordCount = spirv[i] >> 16;
const unsigned opcode = spirv[i] & 0xFFFFu;
if (wordCount == 0 || i + wordCount > spirv.size()) break;
if (opcode == kOpTypeImage && wordCount >= 8 && spirv[i + 3] == kDim1D &&
spirv[i + 7] == 1u) {
if (opcode == kOpTypeImage && wordCount >= 8 && spirv[i + 3] == kDim1D && spirv[i + 7] == 1u) {
++count;
}
i += wordCount;
@@ -3816,7 +3818,8 @@ TEST_F(ProgramUtilTest, SpirvCrossEmitsAScalarOffsetFor1DSamplers) {
const String essl = DecompileToEssl(spirv);
ASSERT_FALSE(essl.empty());
EXPECT_NE(essl.find("sampler2DArray"), String::npos)
<< "SPIRV-Cross declares the 1D array sampler as 2D on ES; that half it does do:\n" << essl;
<< "SPIRV-Cross declares the 1D array sampler as 2D on ES; that half it does do:\n"
<< essl;
EXPECT_EQ(essl.find("ivec2"), String::npos)
<< "SPIRV-Cross is expected to pass the SCALAR offset straight through, so nothing in this "
"fixture builds an ivec2 - its absence IS the defect, because ESSL has no "
@@ -3848,9 +3851,8 @@ TEST_F(ProgramUtilTest, Lower1DSampledImagesWidensTheOffsetOfA1DArrayLookup) {
ASSERT_TRUE(ShaderCompiler::Lower1DSampledImagesForEssl(spirv, lowered, true));
ASSERT_FALSE(lowered.empty());
EXPECT_EQ(Count1DSampledImageTypes(lowered), 0u)
<< "no 1D sampled image type may survive the pass:\n"
<< DisassembleSpirv(lowered);
EXPECT_EQ(Count1DSampledImageTypes(lowered), 0u) << "no 1D sampled image type may survive the pass:\n"
<< DisassembleSpirv(lowered);
// The point of moving the TYPE rather than only the operand: an ivec2 offset against a type
// still declared Dim1D is an invalid module, and the validator would say so.
EXPECT_EQ(ShaderCompiler::SpirvValidationFailureCount(), failuresBefore)
@@ -3860,7 +3862,8 @@ TEST_F(ProgramUtilTest, Lower1DSampledImagesWidensTheOffsetOfA1DArrayLookup) {
const String essl = DecompileToEssl(lowered);
ASSERT_FALSE(essl.empty());
EXPECT_NE(essl.find("sampler2DArray"), String::npos)
<< "the sampler must still be declared as the 2D array the texture is stored as:\n" << essl;
<< "the sampler must still be declared as the 2D array the texture is stored as:\n"
<< essl;
EXPECT_NE(essl.find("ivec2"), String::npos)
<< "the offset must now be the two-component one ESSL's sampler2DArray overload takes:\n"
<< essl;
@@ -3883,8 +3886,7 @@ void main() { ssb.data = textureGrad(g_sampler0, 0.5, 0.25, 0.125); }
Vector<Uint32> spirv;
ASSERT_TRUE(ShaderCompiler::SanitizeAndOptimizeBinary(raw, spirv));
ASSERT_TRUE(Lower1DSampledImagesPass::BinaryHasOffsetOrGrad1DSampledImage(spirv))
<< DisassembleSpirv(spirv);
ASSERT_TRUE(Lower1DSampledImagesPass::BinaryHasOffsetOrGrad1DSampledImage(spirv)) << DisassembleSpirv(spirv);
const Uint64 failuresBefore = ShaderCompiler::SpirvValidationFailureCount();
@@ -3901,10 +3903,8 @@ void main() { ssb.data = textureGrad(g_sampler0, 0.5, 0.25, 0.125); }
ASSERT_FALSE(essl.empty());
EXPECT_NE(essl.find("textureGrad"), String::npos) << essl;
// Both derivatives have to be widened, not just the first: ESSL's overload takes two vec2s.
EXPECT_NE(essl.find("vec2(0.25, 0.0)"), String::npos)
<< "dPdx must be widened to two components:\n" << essl;
EXPECT_NE(essl.find("vec2(0.125, 0.0)"), String::npos)
<< "dPdy must be widened too:\n" << essl;
EXPECT_NE(essl.find("vec2(0.25, 0.0)"), String::npos) << "dPdx must be widened to two components:\n" << essl;
EXPECT_NE(essl.find("vec2(0.125, 0.0)"), String::npos) << "dPdy must be widened too:\n" << essl;
}
// Scope: a 1D sampler that is only SAMPLED or FETCHED is emitted correctly by the very same
@@ -3924,7 +3924,7 @@ void main() {
ssb.data = texelFetch(g_sampler0, 2, 0) + texture(g_sampler4, vec2(0.5, 1.0));
}
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
ASSERT_EQ(Count1DSampledImageTypes(spirv), 2u);
EXPECT_FALSE(Lower1DSampledImagesPass::BinaryHasOffsetOrGrad1DSampledImage(spirv))
@@ -3977,8 +3977,7 @@ void main() {
// was rewritten and the stage that was not declare the same ESSL type.
const String essl = DecompileToEssl(lowered);
ASSERT_FALSE(essl.empty());
EXPECT_EQ(essl.find("sampler1D"), String::npos)
<< "nothing may reach the driver still spelled 1D:\n" << essl;
EXPECT_EQ(essl.find("sampler1D"), String::npos) << "nothing may reach the driver still spelled 1D:\n" << essl;
}
// The shape that would emit INVALID SPIR-V without the deduplication, and the shape the
@@ -4044,8 +4043,7 @@ void main() {
Vector<Uint32> lowered;
ASSERT_TRUE(ShaderCompiler::Lower1DSampledImagesForEssl(spirv, lowered, true));
EXPECT_EQ(lowered, spirv)
<< "a declined module must be handed back untouched, not partly rewritten";
EXPECT_EQ(lowered, spirv) << "a declined module must be handed back untouched, not partly rewritten";
EXPECT_EQ(Count1DSampledImageTypes(lowered), 1u)
<< "declining means the 1D type is still there for the driver to reject";
}
@@ -4090,7 +4088,7 @@ layout (local_size_x = 1) in;
writeonly uniform uimage2D uni_image;
void main() { imageStore(uni_image, ivec2(gl_GlobalInvocationID.xy), uvec4(15u, 0u, 0u, 0u)); }
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
ASSERT_TRUE(ShaderCompiler::DeclaresFormatlessStorageImage(spirv))
<< "the fixture must reproduce the defect before the fix is asked to remove it:\n"
@@ -4111,9 +4109,11 @@ void main() { imageStore(uni_image, ivec2(gl_GlobalInvocationID.xy), uvec4(15u,
const String essl = DecompileToEssl(baked);
ASSERT_FALSE(essl.empty());
EXPECT_NE(essl.find("r32ui"), String::npos)
<< "the bound format must reach the declaration as a layout qualifier:\n" << essl;
<< "the bound format must reach the declaration as a layout qualifier:\n"
<< essl;
EXPECT_NE(essl.find("writeonly"), String::npos)
<< "the access qualifier the declaration already had must survive:\n" << essl;
<< "the access qualifier the declaration already had must survive:\n"
<< essl;
}
// SPIRV-Cross THROWS rather than printing the formats it calls desktop-only when it targets ESSL
@@ -4155,16 +4155,16 @@ layout (local_size_x = 1) in;
writeonly uniform uimage2D uni_image;
void main() { imageStore(uni_image, ivec2(0), uvec4(15u)); }
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
{ // Unprintable AND uncarriable: declined, module untouched, and the stage still transpiles.
{ // Unprintable AND uncarriable: declined, module untouched, and the stage still transpiles.
Vector<Uint32> baked;
ASSERT_TRUE(ShaderCompiler::BakeImageFormatsForEssl(spirv, {{"uni_image", kGlRgb8}}, baked));
EXPECT_EQ(baked, spirv) << "a format nothing can carry must leave the module untouched";
EXPECT_FALSE(DecompileToEssl(baked).empty());
}
{ // Unprintable but carriable: baked narrow here, then widened into the carrier, which is
{ // Unprintable but carriable: baked narrow here, then widened into the carrier, which is
// what finally gives the declaration a qualifier ES accepts.
Vector<Uint32> baked;
ASSERT_TRUE(ShaderCompiler::BakeImageFormatsForEssl(spirv, {{"uni_image", kGlR8ui}}, baked, true));
@@ -4178,8 +4178,7 @@ void main() { imageStore(uni_image, ivec2(0), uvec4(15u)); }
ASSERT_FALSE(widened.empty());
const String essl = DecompileToEssl(widened);
ASSERT_FALSE(essl.empty());
EXPECT_NE(essl.find("rgba8ui"), String::npos)
<< "the baked r8ui must come out as the core carrier:\n" << essl;
EXPECT_NE(essl.find("rgba8ui"), String::npos) << "the baked r8ui must come out as the core carrier:\n" << essl;
}
}
@@ -4194,7 +4193,7 @@ layout (local_size_x = 1) in;
layout (binding = 0, rgba32ui) writeonly uniform uimage2D uni_image;
void main() { imageStore(uni_image, ivec2(0), uvec4(1u)); }
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
ASSERT_FALSE(ShaderCompiler::DeclaresFormatlessStorageImage(spirv));
@@ -4218,7 +4217,7 @@ writeonly uniform uimage2D uni_image;
void writeIt(writeonly uimage2D img) { imageStore(img, ivec2(0), uvec4(1u)); }
void main() { writeIt(uni_image); }
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
ASSERT_TRUE(ShaderCompiler::DeclaresFormatlessStorageImage(spirv));
@@ -4244,7 +4243,7 @@ layout (local_size_x = 1) in;
writeonly uniform image2D uni_image;
void main() { imageStore(uni_image, ivec2(0), vec4(1.0)); }
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
const Uint64 failuresBefore = ShaderCompiler::SpirvValidationFailureCount();
@@ -4276,16 +4275,17 @@ void main() {
imageStore(imgB, ivec2(0), uvec4(2u));
}
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
ASSERT_EQ(CountSpirvOpcode(DisassembleSpirv(spirv), "OpTypeImage"), 1u)
<< "the fixture must have the two images sharing one type:\n" << DisassembleSpirv(spirv);
<< "the fixture must have the two images sharing one type:\n"
<< DisassembleSpirv(spirv);
const Uint64 failuresBefore = ShaderCompiler::SpirvValidationFailureCount();
Vector<Uint32> baked;
ASSERT_TRUE(ShaderCompiler::BakeImageFormatsForEssl(
spirv, {{"imgA", kGlR32ui}, {"imgB", kGlRgba32ui}}, baked, true));
ASSERT_TRUE(
ShaderCompiler::BakeImageFormatsForEssl(spirv, {{"imgA", kGlR32ui}, {"imgB", kGlRgba32ui}}, baked, true));
ASSERT_FALSE(baked.empty());
EXPECT_EQ(ShaderCompiler::SpirvValidationFailureCount(), failuresBefore)
<< "splitting the shared type must not leave a dangling or duplicate declaration:\n"
@@ -4313,10 +4313,11 @@ void main() {
imageStore(declared, ivec2(0), uvec4(2u));
}
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
ASSERT_EQ(CountSpirvOpcode(DisassembleSpirv(spirv), "OpTypeImage"), 2u)
<< "the fixture needs one Unknown-format and one r32ui image type:\n" << DisassembleSpirv(spirv);
<< "the fixture needs one Unknown-format and one r32ui image type:\n"
<< DisassembleSpirv(spirv);
const Uint64 failuresBefore = ShaderCompiler::SpirvValidationFailureCount();
@@ -4327,7 +4328,8 @@ void main() {
<< "the baked image collided with the module's own r32ui image and left a duplicate type:\n"
<< DisassembleSpirv(baked);
EXPECT_EQ(CountSpirvOpcode(DisassembleSpirv(baked), "OpTypeImage"), 1u)
<< "the two identical image types must be the same declaration:\n" << DisassembleSpirv(baked);
<< "the two identical image types must be the same declaration:\n"
<< DisassembleSpirv(baked);
}
// An ARRAY of format-less images: the variable's type is a pointer to an array, every use goes
@@ -4342,7 +4344,7 @@ void main() {
for (int i = 0; i < 2; ++i) imageStore(imgs[i], ivec2(0), uvec4(uint(i)));
}
)",
GL_COMPUTE_SHADER);
GL_COMPUTE_SHADER);
ASSERT_FALSE(spirv.empty());
ASSERT_TRUE(ShaderCompiler::DeclaresFormatlessStorageImage(spirv));
@@ -4369,10 +4371,11 @@ out uvec4 fragColor;
in vec2 vUv;
void main() { fragColor = texture(uni_sampler, vUv); }
)",
GL_FRAGMENT_SHADER);
GL_FRAGMENT_SHADER);
ASSERT_FALSE(spirv.empty());
EXPECT_FALSE(ShaderCompiler::DeclaresFormatlessStorageImage(spirv))
<< "a sampled image must not read as a format-less STORAGE image:\n" << DisassembleSpirv(spirv);
<< "a sampled image must not read as a format-less STORAGE image:\n"
<< DisassembleSpirv(spirv);
Vector<Uint32> baked;
ASSERT_TRUE(ShaderCompiler::BakeImageFormatsForEssl(spirv, {{"uni_sampler", kGlR32ui}}, baked, true));
@@ -4486,8 +4489,7 @@ TEST_F(ProgramUtilTest, StorageBlockBindingCeilingIsCheckedAtItsExactBoundary) {
EXPECT_TRUE(violation("layout(binding = 34) buffer Buffer { int x; } g_array[4];\n").has_value());
// Qualifiers and a second layout list may sit between the binding and the keyword.
EXPECT_TRUE(violation("layout(std430) layout(binding = 36) coherent restrict buffer B { int x; };\n")
.has_value());
EXPECT_TRUE(violation("layout(std430) layout(binding = 36) coherent restrict buffer B { int x; };\n").has_value());
// Things the scanner must NOT judge: a uniform block (a different ceiling), a storage block
// with no explicit binding, the bare default-qualifier form, and an instance array whose size
@@ -4497,8 +4499,7 @@ TEST_F(ProgramUtilTest, StorageBlockBindingCeilingIsCheckedAtItsExactBoundary) {
.has_value());
EXPECT_FALSE(violation("buffer Buffer { int x; };\nconst int binding = 40;\n").has_value());
EXPECT_FALSE(violation("layout(binding = 1) buffer;\nbuffer Buffer { int x; };\n").has_value());
EXPECT_FALSE(violation("const int kCount = 4;\nlayout(binding = 34) buffer B { int x; } g[kCount];\n")
.has_value());
EXPECT_FALSE(violation("const int kCount = 4;\nlayout(binding = 34) buffer B { int x; } g[kCount];\n").has_value());
// A backend that advertises no binding points has no ceiling to enforce.
EXPECT_FALSE(FindShaderStorageBindingViolation("layout(binding = 36) buffer B { int x; };\n", 0).has_value());
@@ -4560,14 +4561,21 @@ TEST_F(ProgramUtilTest, PreprocessSubroutineKeepsTheTypeNameVisibleToTheCompiler
const auto lowerAndCompile = [](const String& typeName) {
String source = "#version 400 core\n"
"out vec4 fragColor;\n"
"subroutine void " + typeName + "(void);\n"
"subroutine(" + typeName + ") void Impl(void) { fragColor = vec4(1.0); }\n"
"subroutine uniform " + typeName + " g_routine;\n"
"subroutine void " +
typeName +
"(void);\n"
"subroutine(" +
typeName +
") void Impl(void) { fragColor = vec4(1.0); }\n"
"subroutine uniform " +
typeName +
" g_routine;\n"
"void main() { g_routine(); }\n";
PreprocessShaderSource(ShaderStage::Fragment, source);
EXPECT_EQ(source.find("subroutine"), String::npos) << source;
EXPECT_NE(source.find("void " + typeName + "(void);"), String::npos)
<< "the type declaration must survive as a prototype:\n" << source;
<< "the type declaration must survive as a prototype:\n"
<< source;
ShaderAttrib attrib{.shaderType = GL_FRAGMENT_SHADER, .sourceStr = source};
return Bool(ShaderCompiler::CompileShader(attrib));
};
@@ -4671,7 +4679,6 @@ subroutine(FuncType) void Func0(int coord) { fragColor = vec4(float(coord)); }
<< "an inactive #if arm must not have an unconditional forwarding body appended for it";
}
// ---------------------------------------------------------------------------------------------
// gl_NumSamples: glslang declares the built-in only when it is NOT targeting SPIR-V, and MobileGL
// always targets SPIR-V, so every fragment shader that reads it used to die at compile time with
@@ -4797,33 +4804,25 @@ TEST_F(ProgramUtilTest, NumSamplesShimHonoursTheVersionAndExtensionGate) {
{"desktop 460 core", "#version 460 core\n", true},
{"desktop 400 core", "#version 400 core\n", true},
{"desktop 330 core, no extension", "#version 330 core\n", false},
{"desktop 330 core + ARB_sample_shading",
"#version 330 core\n#extension GL_ARB_sample_shading : require\n", true},
{"desktop 330 core + all : warn",
"#version 330 core\n#extension all : warn\n", true},
{"desktop 330 core + ARB_sample_shading", "#version 330 core\n#extension GL_ARB_sample_shading : require\n",
true},
{"desktop 330 core + all : warn", "#version 330 core\n#extension all : warn\n", true},
{"desktop 120, no extension", "#version 120\n", false},
{"desktop 120 + all : warn (below the 1.30 floor)",
"#version 120\n#extension all : warn\n", false},
{"desktop 120 + all : warn (below the 1.30 floor)", "#version 120\n#extension all : warn\n", false},
{"ESSL 320", "#version 320 es\n", true},
{"ESSL 310, no extension", "#version 310 es\n", false},
{"ESSL 310 + OES_sample_variables",
"#version 310 es\n#extension GL_OES_sample_variables : require\n", true},
{"ESSL 310 + OES_sample_variables", "#version 310 es\n#extension GL_OES_sample_variables : require\n", true},
// The AEP spellings. glslang applies the directive's behavior to all twelve AEP members,
// GL_OES_sample_variables among them, so these are legal ES 3.1 shaders.
{"ESSL 310 + AEP : require",
"#version 310 es\n#extension GL_ANDROID_extension_pack_es31a : require\n", true},
{"ESSL 310 + AEP : enable",
"#version 310 es\n#extension GL_ANDROID_extension_pack_es31a : enable\n", true},
{"ESSL 310 + AEP : warn",
"#version 310 es\n#extension GL_ANDROID_extension_pack_es31a : warn\n", true},
{"ESSL 310 + AEP : require", "#version 310 es\n#extension GL_ANDROID_extension_pack_es31a : require\n", true},
{"ESSL 310 + AEP : enable", "#version 310 es\n#extension GL_ANDROID_extension_pack_es31a : enable\n", true},
{"ESSL 310 + AEP : warn", "#version 310 es\n#extension GL_ANDROID_extension_pack_es31a : warn\n", true},
// ...but `disable` is not an opt-in, and the implication carries the behavior with it.
{"ESSL 310 + AEP : disable",
"#version 310 es\n#extension GL_ANDROID_extension_pack_es31a : disable\n", false},
{"ESSL 310 + all : warn",
"#version 310 es\n#extension all : warn\n", true},
{"ESSL 310 + AEP : disable", "#version 310 es\n#extension GL_ANDROID_extension_pack_es31a : disable\n", false},
{"ESSL 310 + all : warn", "#version 310 es\n#extension all : warn\n", true},
// An AEP member that does NOT imply sample variables must not open the gate.
{"ESSL 310 + EXT_geometry_shader only",
"#version 310 es\n#extension GL_EXT_geometry_shader : require\n", false},
{"ESSL 310 + EXT_geometry_shader only", "#version 310 es\n#extension GL_EXT_geometry_shader : require\n",
false},
{"ESSL 300", "#version 300 es\n", false},
{"ESSL 300 + AEP (below the 3.10 floor)",
"#version 300 es\n#extension GL_ANDROID_extension_pack_es31a : require\n", false},
@@ -4948,10 +4947,9 @@ TEST_F(ProgramUtilTest, RepeatedIdenticalVersionDirectiveIsElided) {
// Byte-for-byte the concatenation the CTS produces: kGLSLPrec ends without a newline, so the
// subcase's own "#version 310 es" lands mid-line.
String source =
"#version 310 es\n\nprecision highp float;\nprecision highp uimage2DArray;#version 310 es\n"
"layout(location = 0) in vec4 i_position;\n"
"void main() { gl_Position = i_position; }\n";
String source = "#version 310 es\n\nprecision highp float;\nprecision highp uimage2DArray;#version 310 es\n"
"layout(location = 0) in vec4 i_position;\n"
"void main() { gl_Position = i_position; }\n";
const SizeT lineCountBefore = static_cast<SizeT>(std::count(source.begin(), source.end(), '\n'));
PreprocessShaderSource(ShaderStage::Vertex, source);
@@ -4978,8 +4976,7 @@ TEST_F(ProgramUtilTest, OnlyAnExactVersionRepeatIsElided) {
SCOPED_TRACE("a lone non-first #version is still a lone non-first #version");
// KHR-GL33.shaders.preprocessor.directive.version_not_first_statement_1 requires this to
// fail to compile, and it only does so because the directive is left where it was.
String source =
"precision mediump float;\n#version 330\nout vec4 c;\nvoid main() { c = vec4(1.0); }\n";
String source = "precision mediump float;\n#version 330\nout vec4 c;\nvoid main() { c = vec4(1.0); }\n";
PreprocessShaderSource(ShaderStage::Fragment, source);
const SizeT versionPos = source.find("#version");
ASSERT_NE(versionPos, String::npos) << source;
@@ -4992,8 +4989,7 @@ TEST_F(ProgramUtilTest, OnlyAnExactVersionRepeatIsElided) {
{
SCOPED_TRACE("a MALFORMED repeat is left alone");
String source =
"#version 330 core\nout vec4 c;\n#version 330 foobar\nvoid main() { c = vec4(1.0); }\n";
String source = "#version 330 core\nout vec4 c;\n#version 330 foobar\nvoid main() { c = vec4(1.0); }\n";
PreprocessShaderSource(ShaderStage::Fragment, source);
EXPECT_NE(source.find("#version 330 foobar"), String::npos) << source;
}
@@ -5024,14 +5020,13 @@ void main() { fragColor = vec4(float(gl_NumSamples)); }
// Both halves of the AEP path: the built-in shim AND the restored member macros.
EXPECT_TRUE(HasNumSamplesShim(source)) << source;
const String defines = CollectEsPreambleMacroDefines(source);
for (const char* member : {"GL_ANDROID_extension_pack_es31a", "GL_OES_sample_variables",
"GL_OES_shader_image_atomic", "GL_OES_shader_multisample_interpolation",
"GL_OES_texture_storage_multisample_2d_array", "GL_EXT_geometry_shader",
"GL_EXT_gpu_shader5", "GL_EXT_primitive_bounding_box",
"GL_EXT_shader_io_blocks", "GL_EXT_tessellation_shader",
"GL_EXT_texture_buffer", "GL_EXT_texture_cube_map_array"}) {
EXPECT_NE(defines.find(String("#define ") + member + " 1\n"), String::npos)
<< member << " missing from:\n" << defines;
for (const char* member :
{"GL_ANDROID_extension_pack_es31a", "GL_OES_sample_variables", "GL_OES_shader_image_atomic",
"GL_OES_shader_multisample_interpolation", "GL_OES_texture_storage_multisample_2d_array",
"GL_EXT_geometry_shader", "GL_EXT_gpu_shader5", "GL_EXT_primitive_bounding_box", "GL_EXT_shader_io_blocks",
"GL_EXT_tessellation_shader", "GL_EXT_texture_buffer", "GL_EXT_texture_cube_map_array"}) {
EXPECT_NE(defines.find(String("#define ") + member + " 1\n"), String::npos) << member << " missing from:\n"
<< defines;
}
// GL_KHR_blend_equation_advanced is an AEP member glslang propagates to, but its macro is in
// the DESKTOP preamble too - so the rewrite never took it away and it must not be restored.
@@ -613,8 +613,7 @@ TEST_F(ShaderCompileAdoptionTest, AfterEverySharerIsGoneTheNextCompileIsStillCor
ShaderSource(c, 1, &text, nullptr);
CompileShader(c);
ASSERT_EQ(QueryCompileStatus(c), GL_TRUE)
<< "a cancelled node must never be adopted - it can only ever report GL_FALSE. "
<< QueryShaderInfoLog(c);
<< "a cancelled node must never be adopted - it can only ever report GL_FALSE. " << QueryShaderInfoLog(c);
const GLuint program = LinkWith(c);
ASSERT_EQ(QueryLinkStatus(program), GL_TRUE);
EXPECT_GE(GetUniformLocation(program, "uSeed240"), 0);
@@ -781,8 +780,7 @@ TEST_F(ShaderCompileAdoptionTest, StressSharedNodesUnderResourceAndDelete) {
<< "round " << round << " shader " << i << ": " << QueryShaderInfoLog(shader);
const GLuint program = LinkWith(shader);
ASSERT_EQ(QueryLinkStatus(program), GL_TRUE) << "round " << round << " shader " << i;
const String expected =
"uSeed" + std::to_string(i % 3 == 0 ? round * 100 + 50 : round * 100 + (i % 4));
const String expected = "uSeed" + std::to_string(i % 3 == 0 ? round * 100 + 50 : round * 100 + (i % 4));
EXPECT_GE(GetUniformLocation(program, expected.c_str()), 0)
<< "round " << round << " shader " << i << " expected " << expected;
DeleteProgram(program);
@@ -818,19 +816,17 @@ TEST(ShaderCompileAdoptionMapTest, RegisteredNodeIsAdoptedOnAnExactMatch) {
const SharedPtr<ShaderCompileTask> node = MakeNode(text, ShaderStage::Fragment, env);
map.Register(node);
EXPECT_EQ(map.FindAdoptable(ShaderStage::Fragment, ShaderPreprocessCache::HashSource(text), text,
env->fingerprint),
EXPECT_EQ(map.FindAdoptable(ShaderStage::Fragment, ShaderPreprocessCache::HashSource(text), text, env->fingerprint),
node);
EXPECT_EQ(map.GetAdoptionCount(), 1u);
// Every discriminator in the key is load-bearing.
EXPECT_EQ(map.FindAdoptable(ShaderStage::Vertex, ShaderPreprocessCache::HashSource(text), text,
env->fingerprint),
EXPECT_EQ(map.FindAdoptable(ShaderStage::Vertex, ShaderPreprocessCache::HashSource(text), text, env->fingerprint),
nullptr);
const String other = text + "\n";
EXPECT_EQ(map.FindAdoptable(ShaderStage::Fragment, ShaderPreprocessCache::HashSource(other), other,
env->fingerprint),
nullptr);
EXPECT_EQ(
map.FindAdoptable(ShaderStage::Fragment, ShaderPreprocessCache::HashSource(other), other, env->fingerprint),
nullptr);
EXPECT_EQ(map.GetAdoptionCount(), 1u) << "a miss must not count as an adoption";
}
@@ -851,9 +847,9 @@ TEST(ShaderCompileAdoptionMapTest, EnvFingerprintMismatchIsNotAdopted) {
otherEnv->fingerprint = MG_Util::ShaderTranspiler::ComputeCompileEnvFingerprint(*otherEnv);
ASSERT_NE(otherEnv->fingerprint, env->fingerprint);
EXPECT_EQ(map.FindAdoptable(ShaderStage::Fragment, ShaderPreprocessCache::HashSource(text), text,
otherEnv->fingerprint),
nullptr);
EXPECT_EQ(
map.FindAdoptable(ShaderStage::Fragment, ShaderPreprocessCache::HashSource(text), text, otherEnv->fingerprint),
nullptr);
EXPECT_EQ(map.GetAdoptionCount(), 0u);
}
@@ -871,8 +867,7 @@ TEST(ShaderCompileAdoptionMapTest, CancelledNodeIsNotAdoptedAndIsPruned) {
ASSERT_TRUE(node->IsCancelled());
ASSERT_EQ(map.GetEntryCount(), 1u);
EXPECT_EQ(map.FindAdoptable(ShaderStage::Fragment, ShaderPreprocessCache::HashSource(text), text,
env->fingerprint),
EXPECT_EQ(map.FindAdoptable(ShaderStage::Fragment, ShaderPreprocessCache::HashSource(text), text, env->fingerprint),
nullptr);
EXPECT_EQ(map.GetEntryCount(), 0u) << "the dead entry must be pruned on the lookup that found it";
EXPECT_EQ(map.GetAdoptionCount(), 0u);
@@ -884,13 +879,10 @@ TEST(ShaderCompileAdoptionMapTest, ExpiredNodeIsNotAdoptedAndIsPruned) {
const auto& env = MG_Util::ShaderTranspiler::GetDefaultCompileEnv();
ShaderCompileAdoptionMap map;
const String text = "#version 460\nvoid main() {}\n";
{
map.Register(MakeNode(text, ShaderStage::Fragment, env));
}
{ map.Register(MakeNode(text, ShaderStage::Fragment, env)); }
ASSERT_EQ(map.GetEntryCount(), 1u);
EXPECT_EQ(map.FindAdoptable(ShaderStage::Fragment, ShaderPreprocessCache::HashSource(text), text,
env->fingerprint),
EXPECT_EQ(map.FindAdoptable(ShaderStage::Fragment, ShaderPreprocessCache::HashSource(text), text, env->fingerprint),
nullptr);
EXPECT_EQ(map.GetEntryCount(), 0u);
}
@@ -43,12 +43,11 @@ using namespace MobileGL;
using namespace MobileGL::MG_Impl::GLImpl;
namespace {
class TessellationLinkTest: public ::testing::Test {
class TessellationLinkTest : public ::testing::Test {
protected:
void SetUp() override {
MobileGL::Initialize();
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {
}
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {}
}
};
@@ -77,7 +76,7 @@ namespace {
if (separable) {
ProgramParameteri(program, GL_PROGRAM_SEPARABLE, GL_TRUE);
}
for (const auto& [type, source]: stages) {
for (const auto& [type, source] : stages) {
const GLuint shader = CreateShader(type);
ShaderSource(shader, 1, &source, nullptr);
CompileShader(shader);
@@ -157,8 +156,7 @@ void main() { color = vec4(1.0); }
LinkProgram(program);
EXPECT_EQ(Programiv(program, GL_LINK_STATUS), GL_FALSE);
EXPECT_NE(LinkLog(program).find("no vertex-processing stage"), std::string::npos) << LinkLog(program);
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {
}
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {}
}
constexpr const char* kPassthroughVs = R"(#version 460 core
@@ -217,8 +215,7 @@ void main() {
LinkProgram(program);
EXPECT_EQ(Programiv(program, GL_LINK_STATUS), GL_FALSE) << LinkLog(program);
}
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {
}
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {}
}
// A patch-qualified SCALAR crosses the TCS/TES boundary today. It is the control for the
@@ -270,10 +267,9 @@ void main() {
gl_Position = gl_in[0].gl_Position;
}
)";
const GLuint program = MakeProgram({{GL_VERTEX_SHADER, kPassthroughVs},
{GL_TESS_CONTROL_SHADER, tcs},
{GL_TESS_EVALUATION_SHADER, tes}},
/*separable=*/true);
const GLuint program = MakeProgram(
{{GL_VERTEX_SHADER, kPassthroughVs}, {GL_TESS_CONTROL_SHADER, tcs}, {GL_TESS_EVALUATION_SHADER, tes}},
/*separable=*/true);
LinkProgram(program);
const std::string log = LinkLog(program);
ASSERT_EQ(Programiv(program, GL_LINK_STATUS), GL_TRUE)
@@ -82,8 +82,7 @@ namespace {
}
void ClearErrors() {
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {
}
for (int i = 0; i < 32 && GetError() != GL_NO_ERROR; ++i) {}
}
// The CTS shader, narrowed to two elements so the expectations stay readable.
@@ -73,8 +73,7 @@ namespace {
// ---------------------------------------------------------------------------------
class AsyncModeScope {
public:
explicit AsyncModeScope(const Bool async)
: m_saved(MG_Config::Features.AsyncShaderCompile) {
explicit AsyncModeScope(const Bool async) : m_saved(MG_Config::Features.AsyncShaderCompile) {
MG_Config::Features.AsyncShaderCompile =
async ? MG_Config::QuirkOverride::ForceOn : MG_Config::QuirkOverride::ForceOff;
}
@@ -98,7 +97,9 @@ namespace {
return String(version) +
"\n"
"\n"
"out float gl_ClipDistance[" + n + "];\n"
"out float gl_ClipDistance[" +
n +
"];\n"
"\n"
"float f(int i)\n"
"{\n"
@@ -109,7 +110,9 @@ namespace {
"\n"
"void main()\n"
"{\n"
" for(int i = 0; i < " + n + "; i++)\n"
" for(int i = 0; i < " +
n +
"; i++)\n"
" {\n"
" gl_ClipDistance[i] = f(i);\n"
" }\n"
@@ -119,16 +122,15 @@ namespace {
}
String ClipDistanceFs(const char* version) {
return String(version) +
"\n"
"\n"
"\n"
"out highp vec4 color;\n"
"\n"
"void main()\n"
"{\n"
" color = vec4(1.0, 0.0, 0.0, 1.0);\n"
"}\n";
return String(version) + "\n"
"\n"
"\n"
"out highp vec4 color;\n"
"\n"
"void main()\n"
"{\n"
" color = vec4(1.0, 0.0, 0.0, 1.0);\n"
"}\n";
}
// ---------------------------------------------------------------------------------
@@ -160,18 +162,25 @@ namespace {
}
String SkipComponentsFs(const char* version) {
return String(version) +
"\n"
" out vec4 fragColor;\n"
" void main (void)\n"
" {\n"
" fragColor = vec4(0.0, 0.0, 0.0, 1.0);\n"
" }\n";
return String(version) + "\n"
" out vec4 fragColor;\n"
" void main (void)\n"
" {\n"
" fragColor = vec4(0.0, 0.0, 0.0, 1.0);\n"
" }\n";
}
Vector<String> SkipComponentsVaryings() {
return {"gl_SkipComponents1", "value1", "gl_SkipComponents2", "gl_SkipComponents1", "value2",
"gl_SkipComponents3", "gl_SkipComponents2", "value3", "gl_SkipComponents4", "value4"};
return {"gl_SkipComponents1",
"value1",
"gl_SkipComponents2",
"gl_SkipComponents1",
"value2",
"gl_SkipComponents3",
"gl_SkipComponents2",
"value3",
"gl_SkipComponents4",
"value4"};
}
// ---------------------------------------------------------------------------------
@@ -187,9 +196,8 @@ namespace {
for (int i = 0; i < userVaryings; ++i) {
const String name = "result_" + std::to_string(i);
declarations += "out vec4 " + name + ";\n";
setters += " " + name + " = vec4(" + std::to_string(i * 4) + ".0, " +
std::to_string(i * 4 + 1) + ".0, " + std::to_string(i * 4 + 2) + ".0, " +
std::to_string(i * 4 + 3) + ".0);\n";
setters += " " + name + " = vec4(" + std::to_string(i * 4) + ".0, " + std::to_string(i * 4 + 1) +
".0, " + std::to_string(i * 4 + 2) + ".0, " + std::to_string(i * 4 + 3) + ".0);\n";
}
return String(version) + "\n\n" + declarations + "\n" +
"void main()\n"
@@ -219,20 +227,20 @@ namespace {
}
String CaptureInterleavedFs(const char* version) {
return String(version) +
"\n"
"\n"
"out vec4 color;\n"
"\n"
"void main()\n"
"{\n"
" color = vec4(0.5);\n"
"}\n";
return String(version) + "\n"
"\n"
"out vec4 color;\n"
"\n"
"void main()\n"
"{\n"
" color = vec4(0.5);\n"
"}\n";
}
Vector<String> CaptureInterleavedVaryings(const int userVaryings) {
Vector<String> names;
for (int i = 0; i < userVaryings; ++i) names.push_back("result_" + std::to_string(i));
for (int i = 0; i < userVaryings; ++i)
names.push_back("result_" + std::to_string(i));
names.push_back("gl_Position");
return names;
}
@@ -254,9 +262,8 @@ namespace {
for (int i = 0; i < userVaryings; ++i) {
const String name = "result_" + std::to_string(i);
declarations += "out vec4 " + name + ";\n";
setters += " " + name + " = vec4(" + std::to_string(i * 4) + ".0, " +
std::to_string(i * 4 + 1) + ".0, " + std::to_string(i * 4 + 2) + ".0, " +
std::to_string(i * 4 + 3) + ".0);\n";
setters += " " + name + " = vec4(" + std::to_string(i * 4) + ".0, " + std::to_string(i * 4 + 1) +
".0, " + std::to_string(i * 4 + 2) + ".0, " + std::to_string(i * 4 + 3) + ".0);\n";
}
String source = "#version 150\n"
"\n"
@@ -268,10 +275,9 @@ namespace {
declarations + "\n" +
"void main()\n"
"{\n";
const char* positions[] = {"vec4(-1.0 + 0.0625, 1.0 - 0.0625, 0.0, 1.0)",
"vec4( 1.0 - 0.0625, 1.0 - 0.0625, 0.0, 1.0)",
"vec4(-1.0 + 0.0625, -1.0 + 0.0625, 0.0, 1.0)",
"vec4( 1.0 - 0.0625, -1.0 + 0.0625, 0.0, 1.0)"};
const char* positions[] = {
"vec4(-1.0 + 0.0625, 1.0 - 0.0625, 0.0, 1.0)", "vec4( 1.0 - 0.0625, 1.0 - 0.0625, 0.0, 1.0)",
"vec4(-1.0 + 0.0625, -1.0 + 0.0625, 0.0, 1.0)", "vec4( 1.0 - 0.0625, -1.0 + 0.0625, 0.0, 1.0)"};
for (const char* position : positions) {
source += String("\n gl_Position = ") + position + ";\n";
source += setters;
@@ -296,29 +302,47 @@ namespace {
const char* DecorationName(const Uint32 decoration) {
switch (decoration) {
case 11: return "BuiltIn";
case 30: return "Location";
case 31: return "Component";
case 32: return "Index";
case 33: return "Binding";
case 34: return "DescriptorSet";
case 35: return "Offset";
case 36: return "XfbBuffer";
case 37: return "XfbStride";
case 38: return "FuncParamAttr";
default: return nullptr;
case 11:
return "BuiltIn";
case 30:
return "Location";
case 31:
return "Component";
case 32:
return "Index";
case 33:
return "Binding";
case 34:
return "DescriptorSet";
case 35:
return "Offset";
case 36:
return "XfbBuffer";
case 37:
return "XfbStride";
case 38:
return "FuncParamAttr";
default:
return nullptr;
}
}
const char* BuiltInName(const Uint32 builtIn) {
switch (builtIn) {
case 0: return "Position";
case 1: return "PointSize";
case 3: return "ClipDistance";
case 4: return "CullDistance";
case 5: return "VertexId";
case 42: return "VertexIndex";
default: return nullptr;
case 0:
return "Position";
case 1:
return "PointSize";
case 3:
return "ClipDistance";
case 4:
return "CullDistance";
case 5:
return "VertexId";
case 42:
return "VertexIndex";
default:
return nullptr;
}
}
@@ -401,14 +425,17 @@ namespace {
} else if (opcode == kOpEntryPoint && wordCount >= 4) {
SizeT next = 0;
(void)ReadSpirvString(words, w + 3, w + wordCount, next);
for (SizeT i = next; i < w + wordCount; ++i) interfaceIds.push_back(words[i]);
for (SizeT i = next; i < w + wordCount; ++i)
interfaceIds.push_back(words[i]);
} else if (opcode == kOpDecorate && wordCount >= 3) {
PendingDecoration entry{words[w + 1], -1, words[w + 2], {}};
for (SizeT i = w + 3; i < w + wordCount; ++i) entry.operands.push_back(words[i]);
for (SizeT i = w + 3; i < w + wordCount; ++i)
entry.operands.push_back(words[i]);
pending.push_back(Move(entry));
} else if (opcode == kOpMemberDecorate && wordCount >= 4) {
PendingDecoration entry{words[w + 1], static_cast<Int>(words[w + 2]), words[w + 3], {}};
for (SizeT i = w + 4; i < w + wordCount; ++i) entry.operands.push_back(words[i]);
for (SizeT i = w + 4; i < w + wordCount; ++i)
entry.operands.push_back(words[i]);
pending.push_back(Move(entry));
}
w += wordCount;
@@ -440,7 +467,8 @@ namespace {
}
std::sort(digest.decorations.begin(), digest.decorations.end());
for (const Uint32 id : interfaceIds) digest.interfaceNames.push_back(label(id));
for (const Uint32 id : interfaceIds)
digest.interfaceNames.push_back(label(id));
std::sort(digest.interfaceNames.begin(), digest.interfaceNames.end());
return digest;
}
@@ -508,14 +536,16 @@ namespace {
snapshot.strides.push_back(object->GetTransformFeedbackStride(static_cast<Uint32>(i)));
}
for (const auto& varying : object->GetTransformFeedbackVaryings()) {
snapshot.varyings.push_back(varying.name + " type=0x" + [&] {
char buffer[16];
std::snprintf(buffer, sizeof(buffer), "%04X", static_cast<unsigned>(varying.type));
return String(buffer);
}() + " size=" + std::to_string(varying.size) + " buf=" + std::to_string(varying.bufferIndex) +
" off=" + std::to_string(varying.offsetBytes) +
" bytes=" + std::to_string(varying.byteSize) +
" packedOff=" + std::to_string(varying.packedOffsetBytes));
snapshot.varyings.push_back(
varying.name + " type=0x" +
[&] {
char buffer[16];
std::snprintf(buffer, sizeof(buffer), "%04X", static_cast<unsigned>(varying.type));
return String(buffer);
}() +
" size=" + std::to_string(varying.size) + " buf=" + std::to_string(varying.bufferIndex) +
" off=" + std::to_string(varying.offsetBytes) + " bytes=" + std::to_string(varying.byteSize) +
" packedOff=" + std::to_string(varying.packedOffsetBytes));
}
for (const auto& module : object->GetGeneratedSpirv()) {
snapshot.spirv.push_back(DigestSpirv(module));
@@ -533,17 +563,21 @@ namespace {
text += "xfbNeedsScatter = " + std::to_string(static_cast<int>(snapshot.needsScattered)) + "\n";
text += "xfbNameMaxLength = " + std::to_string(snapshot.varyingNameMaxLength) + "\n";
text += "xfbStrides =";
for (const Uint32 stride : snapshot.strides) text += " " + std::to_string(stride);
for (const Uint32 stride : snapshot.strides)
text += " " + std::to_string(stride);
text += "\n";
text += "xfbVaryings (" + std::to_string(snapshot.varyings.size()) + "):\n";
for (const String& varying : snapshot.varyings) text += " " + varying + "\n";
for (const String& varying : snapshot.varyings)
text += " " + varying + "\n";
text += "gsInputPrimitive = " + std::to_string(snapshot.gsInputPrimitive) + "\n";
text += "gsStripFixup = " + std::to_string(static_cast<int>(snapshot.gsStripCaptureFixup)) + "\n";
text += "gsStripTriangles =";
for (const Uint32 triangle : snapshot.gsStripTriangles) text += " " + std::to_string(triangle);
for (const Uint32 triangle : snapshot.gsStripTriangles)
text += " " + std::to_string(triangle);
text += "\n";
text += "uniformBlocks = " + std::to_string(snapshot.uniformBlockCount) + " bindings:";
for (const Uint binding : snapshot.uniformBlockBindings) text += " " + std::to_string(binding);
for (const Uint binding : snapshot.uniformBlockBindings)
text += " " + std::to_string(binding);
text += "\n";
text += "maxUniformLoc = " + std::to_string(snapshot.maxUniformLocation) + "\n";
text += "activeAttribs = " + std::to_string(snapshot.activeAttributes) + "\n";
@@ -553,15 +587,16 @@ namespace {
text += "spirv[" + std::to_string(i) + "] words=" + std::to_string(digest.wordCount);
if (includeSpirvHash) {
char buffer[32];
std::snprintf(buffer, sizeof(buffer), " hash=%016llX",
static_cast<unsigned long long>(digest.hash));
std::snprintf(buffer, sizeof(buffer), " hash=%016llX", static_cast<unsigned long long>(digest.hash));
text += buffer;
}
text += "\n";
text += " interface:";
for (const String& name : digest.interfaceNames) text += " " + name;
for (const String& name : digest.interfaceNames)
text += " " + name;
text += "\n";
for (const String& decoration : digest.decorations) text += " " + decoration + "\n";
for (const String& decoration : digest.decorations)
text += " " + decoration + "\n";
}
return text;
}
@@ -569,8 +604,8 @@ namespace {
// ---------------------------------------------------------------------------------
// Program construction through the real GL entry points
// ---------------------------------------------------------------------------------
GLuint BuildProgram(const String& vertexSource, const String& fragmentSource,
const Vector<String>& xfbVaryings, const GLenum bufferMode) {
GLuint BuildProgram(const String& vertexSource, const String& fragmentSource, const Vector<String>& xfbVaryings,
const GLenum bufferMode) {
const GLuint vertexShader = CreateShader(GL_VERTEX_SHADER);
const char* vertexText = vertexSource.c_str();
ShaderSource(vertexShader, 1, &vertexText, nullptr);
@@ -587,7 +622,8 @@ namespace {
if (!xfbVaryings.empty()) {
std::vector<const GLchar*> names;
names.reserve(xfbVaryings.size());
for (const String& name : xfbVaryings) names.push_back(name.c_str());
for (const String& name : xfbVaryings)
names.push_back(name.c_str());
TransformFeedbackVaryings(program, static_cast<GLsizei>(names.size()), names.data(), bufferMode);
}
LinkProgram(program);
@@ -600,13 +636,12 @@ namespace {
// setter, clip function 0). Returns the program so the caller can keep it alive, which
// is what the CTS does too (it holds m_program across the whole case).
GLuint LinkClipDistanceProgram(const int clipCount, const char* version) {
return BuildProgram(ClipDistanceVs(clipCount, version), ClipDistanceFs(version), {},
GL_INTERLEAVED_ATTRIBS);
return BuildProgram(ClipDistanceVs(clipCount, version), ClipDistanceFs(version), {}, GL_INTERLEAVED_ATTRIBS);
}
GLuint LinkSkipComponentsProgram(const char* version, const String& salt = String()) {
return BuildProgram(SkipComponentsVs(version, salt), SkipComponentsFs(version),
SkipComponentsVaryings(), GL_INTERLEAVED_ATTRIBS);
return BuildProgram(SkipComponentsVs(version, salt), SkipComponentsFs(version), SkipComponentsVaryings(),
GL_INTERLEAVED_ATTRIBS);
}
GLuint LinkCaptureInterleavedProgram(const int userVaryings, const char* version) {
@@ -633,9 +668,9 @@ namespace {
AttachShader(program, fragmentShader);
std::vector<const GLchar*> names;
names.reserve(xfbVaryings.size());
for (const String& name : xfbVaryings) names.push_back(name.c_str());
TransformFeedbackVaryings(program, static_cast<GLsizei>(names.size()), names.data(),
GL_INTERLEAVED_ATTRIBS);
for (const String& name : xfbVaryings)
names.push_back(name.c_str());
TransformFeedbackVaryings(program, static_cast<GLsizei>(names.size()), names.data(), GL_INTERLEAVED_ATTRIBS);
LinkProgram(program);
DeleteShader(vertexShader);
DeleteShader(geometryShader);
@@ -645,13 +680,14 @@ namespace {
GLuint LinkCaptureGeometryProgram(const int userVaryings, const char* outPrimitive) {
return BuildProgramWithGeometry(kGeometryBlankVs, CaptureGeometryGs(userVaryings, outPrimitive),
CaptureInterleavedFs("#version 130"),
CaptureInterleavedVaryings(userVaryings));
CaptureInterleavedFs("#version 130"), CaptureInterleavedVaryings(userVaryings));
}
// Reinstalls pGLContext: new ProgramState, new P0b preprocess cache, new stage-6
// adoption map. glslang's process globals are untouched on purpose.
void FreshContext() { MG_State::Init(); }
void FreshContext() {
MG_State::Init();
}
class XfbFrontendOrderInvarianceTest : public ::testing::Test {
protected:
@@ -665,13 +701,25 @@ namespace {
GLuint (*link)();
};
GLuint LinkSkip150() { return LinkSkipComponentsProgram("#version 150"); }
GLuint LinkCapture130() { return LinkCaptureInterleavedProgram(15, "#version 130"); }
GLuint LinkSkip400() { return LinkSkipComponentsProgram("#version 400"); }
GLuint LinkCapture400() { return LinkCaptureInterleavedProgram(15, "#version 400"); }
GLuint LinkSkip150() {
return LinkSkipComponentsProgram("#version 150");
}
GLuint LinkCapture130() {
return LinkCaptureInterleavedProgram(15, "#version 130");
}
GLuint LinkSkip400() {
return LinkSkipComponentsProgram("#version 400");
}
GLuint LinkCapture400() {
return LinkCaptureInterleavedProgram(15, "#version 400");
}
GLuint LinkGeometryPoints() { return LinkCaptureGeometryProgram(15, "points"); }
GLuint LinkGeometryTriangleStrip() { return LinkCaptureGeometryProgram(15, "triangle_strip"); }
GLuint LinkGeometryPoints() {
return LinkCaptureGeometryProgram(15, "points");
}
GLuint LinkGeometryTriangleStrip() {
return LinkCaptureGeometryProgram(15, "triangle_strip");
}
const BCase kBCases[] = {
{"skip_components@150", &LinkSkip150},
@@ -690,8 +738,8 @@ namespace {
String poisoned;
};
AbResult RunAb(const BCase& bCase, const int clipCount, const char* clipVersion,
const Bool freshContextForControl, const Bool includeSpirvHash) {
AbResult RunAb(const BCase& bCase, const int clipCount, const char* clipVersion, const Bool freshContextForControl,
const Bool includeSpirvHash) {
AbResult result;
// CONTROL: B alone, in a context that has never seen A.
@@ -735,8 +783,7 @@ TEST_F(XfbFrontendOrderInvarianceTest, AsyncOn_ClipDistanceBeforeXfbChangesNothi
for (const char* clipVersion : {"#version 400", "#version 150", "#version 130"}) {
const AbResult result = RunAb(bCase, clipCount, clipVersion, true, true);
EXPECT_EQ(result.control, result.poisoned)
<< "async=1 B=" << bCase.label << " clipCount=" << clipCount
<< " clipVersion=" << clipVersion;
<< "async=1 B=" << bCase.label << " clipCount=" << clipCount << " clipVersion=" << clipVersion;
}
}
}
@@ -750,8 +797,7 @@ TEST_F(XfbFrontendOrderInvarianceTest, AsyncOff_ClipDistanceBeforeXfbChangesNoth
for (const char* clipVersion : {"#version 400", "#version 150", "#version 130"}) {
const AbResult result = RunAb(bCase, clipCount, clipVersion, true, true);
EXPECT_EQ(result.control, result.poisoned)
<< "async=0 B=" << bCase.label << " clipCount=" << clipCount
<< " clipVersion=" << clipVersion;
<< "async=0 B=" << bCase.label << " clipCount=" << clipCount << " clipVersion=" << clipVersion;
}
}
}
@@ -798,7 +844,8 @@ TEST_F(XfbFrontendOrderInvarianceTest, NoMemoHitPossibleForB) {
DeleteProgram(poisonedProgram);
DeleteProgram(clipProgram);
EXPECT_EQ(control, poisoned) << "async=" << async << " (SPIR-V hash excluded: the salt comment "
EXPECT_EQ(control, poisoned) << "async=" << async
<< " (SPIR-V hash excluded: the salt comment "
"is stripped by the preprocessor but ids can still renumber)";
}
}
@@ -863,7 +910,8 @@ TEST_F(XfbFrontendOrderInvarianceTest, LongCaseSequenceLikeGlcts) {
}
keepAlive.push_back(program);
}
for (const GLuint program : keepAlive) DeleteProgram(program);
for (const GLuint program : keepAlive)
DeleteProgram(program);
}
}
@@ -902,7 +950,8 @@ TEST_F(XfbFrontendOrderInvarianceTest, BLinksWhileAIsStillInFlight) {
const String poisoned = Render(Capture(program), true);
EXPECT_EQ(control, poisoned) << "repetition " << repetition;
DeleteProgram(program);
for (const GLuint clipProgram : clipPrograms) DeleteProgram(clipProgram);
for (const GLuint clipProgram : clipPrograms)
DeleteProgram(clipProgram);
}
}
@@ -953,8 +1002,7 @@ TEST_F(XfbFrontendOrderInvarianceTest, DumpBSpirvForDisassembly) {
const auto& object = MG_State::pGLContext->GetProgramObject(program);
const auto& modules = object->GetGeneratedSpirv();
for (SizeT i = 0; i < modules.size(); ++i) {
String path = String(directory) + "/" + dump.tag + "-" + bCase.label + "-" +
std::to_string(i) + ".spv";
String path = String(directory) + "/" + dump.tag + "-" + bCase.label + "-" + std::to_string(i) + ".spv";
std::replace(path.begin() + std::strlen(directory) + 1, path.end(), '@', '_');
std::FILE* file = std::fopen(path.c_str(), "wb");
ASSERT_NE(file, nullptr) << path;
+31 -21
View File
@@ -41,7 +41,7 @@ namespace {
// setting into later tests even if an assertion unwinds the test body
// early (same pattern as SanityTest's ScopedGLESCapabilitiesOverride).
struct ScopedFeaturesOverride {
ScopedFeaturesOverride(): m_snapshot(MG_Config::Features) {}
ScopedFeaturesOverride() : m_snapshot(MG_Config::Features) {}
~ScopedFeaturesOverride() { MG_Config::Features = m_snapshot; }
ScopedFeaturesOverride(const ScopedFeaturesOverride&) = delete;
ScopedFeaturesOverride& operator=(const ScopedFeaturesOverride&) = delete;
@@ -54,7 +54,7 @@ namespace {
// it on destruction, so stub timer-query pointers cannot leak into later
// tests.
struct ScopedBackendFunctionsOverride {
ScopedBackendFunctionsOverride(): m_snapshot(MG_Backend::gBackendFunctionsTable) {}
ScopedBackendFunctionsOverride() : m_snapshot(MG_Backend::gBackendFunctionsTable) {}
~ScopedBackendFunctionsOverride() { MG_Backend::gBackendFunctionsTable = m_snapshot; }
ScopedBackendFunctionsOverride(const ScopedBackendFunctionsOverride&) = delete;
ScopedBackendFunctionsOverride& operator=(const ScopedBackendFunctionsOverride&) = delete;
@@ -77,21 +77,27 @@ namespace {
Bool g_stubResultObtainable = true;
Uint64 g_stubResultNs = 0;
Bool StubIsTimerQuerySupported() { return g_stubTimerQuerySupported; }
Bool StubIsTimerQuerySupported() {
return g_stubTimerQuerySupported;
}
MG_Backend::BackendQueryHandle StubBeginTimeElapsedQuery() {
++g_stubBeginCount;
return reinterpret_cast<MG_Backend::BackendQueryHandle>(static_cast<uintptr_t>(0x51));
}
void StubEndTimeElapsedQuery(MG_Backend::BackendQueryHandle) { ++g_stubEndCount; }
void StubEndTimeElapsedQuery(MG_Backend::BackendQueryHandle) {
++g_stubEndCount;
}
MG_Backend::BackendQueryHandle StubQueryCounterTimestamp() {
++g_stubCounterCount;
return reinterpret_cast<MG_Backend::BackendQueryHandle>(static_cast<uintptr_t>(0x52));
}
Bool StubIsQueryResultAvailable(MG_Backend::BackendQueryHandle) { return g_stubResultAvailable; }
Bool StubIsQueryResultAvailable(MG_Backend::BackendQueryHandle) {
return g_stubResultAvailable;
}
Bool StubGetQueryResult64(MG_Backend::BackendQueryHandle, Bool, Uint64* outNanoseconds) {
if (!g_stubResultObtainable) {
@@ -101,7 +107,9 @@ namespace {
return true;
}
void StubDeleteBackendQuery(MG_Backend::BackendQueryHandle) { ++g_stubDeleteCount; }
void StubDeleteBackendQuery(MG_Backend::BackendQueryHandle) {
++g_stubDeleteCount;
}
void InstallStubBackendTimerQueries() {
auto& backendGL = MG_Backend::gBackendFunctionsTable.GL;
@@ -139,7 +147,9 @@ namespace {
return reinterpret_cast<MG_Backend::BackendQueryHandle>(static_cast<uintptr_t>(0x53));
}
void StubEndXfbPrimitivesQuery(MG_Backend::BackendQueryHandle) { ++g_stubXfbEndCount; }
void StubEndXfbPrimitivesQuery(MG_Backend::BackendQueryHandle) {
++g_stubXfbEndCount;
}
// Stub backend occlusion queries. The host has no ES context, and BeginQuery refuses the
// occlusion targets outright when the backend advertises no hook - so a conditional-render
@@ -203,8 +213,7 @@ protected:
// Drain errors recorded by earlier tests so assertions here are
// attributable to this test alone (GetError pops one queued error
// per call).
while (MG_Impl::GLImpl::GetError() != GL_NO_ERROR) {
}
while (MG_Impl::GLImpl::GetError() != GL_NO_ERROR) {}
}
};
@@ -830,14 +839,18 @@ TEST_F(QueryTest, PipelineStatisticsTargetsAreAcceptedAndReportZeroCounterBits)
// The NINE unconditional targets. The two tessellation ones are conditional on tessellation
// support and have their own test below.
static constexpr GLenum kTargets[] = {
GL_VERTICES_SUBMITTED, GL_PRIMITIVES_SUBMITTED,
GL_VERTEX_SHADER_INVOCATIONS, GL_GEOMETRY_SHADER_INVOCATIONS,
GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED, GL_FRAGMENT_SHADER_INVOCATIONS,
GL_COMPUTE_SHADER_INVOCATIONS, GL_CLIPPING_INPUT_PRIMITIVES,
GL_VERTICES_SUBMITTED,
GL_PRIMITIVES_SUBMITTED,
GL_VERTEX_SHADER_INVOCATIONS,
GL_GEOMETRY_SHADER_INVOCATIONS,
GL_GEOMETRY_SHADER_PRIMITIVES_EMITTED,
GL_FRAGMENT_SHADER_INVOCATIONS,
GL_COMPUTE_SHADER_INVOCATIONS,
GL_CLIPPING_INPUT_PRIMITIVES,
GL_CLIPPING_OUTPUT_PRIMITIVES,
};
for (const GLenum target: kTargets) {
for (const GLenum target : kTargets) {
GLuint id = 0;
MG_Impl::GLImpl::GenQueries(1, &id);
ASSERT_NE(id, 0u);
@@ -887,8 +900,7 @@ TEST_F(QueryTest, PipelineStatisticsTargetsAreAcceptedAndReportZeroCounterBits)
// backend starts emitting GL_ARB_tessellation_shader this test keeps passing and keeps pinning
// the coupling, and it fails loudly if only one of the two halves moves.
TEST_F(QueryTest, TessellationPipelineStatisticsTargetsFollowTheTessellationShaderAdvertisement) {
const auto* extensionsString =
reinterpret_cast<const char*>(MG_Impl::GLImpl::GetString(GL_EXTENSIONS));
const auto* extensionsString = reinterpret_cast<const char*>(MG_Impl::GLImpl::GetString(GL_EXTENSIONS));
ASSERT_NE(extensionsString, nullptr);
const Bool advertised = String(extensionsString).find("GL_ARB_tessellation_shader") != String::npos;
const GLenum expectedError = advertised ? GL_NO_ERROR : GL_INVALID_ENUM;
@@ -898,7 +910,7 @@ TEST_F(QueryTest, TessellationPipelineStatisticsTargetsFollowTheTessellationShad
GL_TESS_EVALUATION_SHADER_INVOCATIONS,
};
for (const GLenum target: kTessTargets) {
for (const GLenum target : kTessTargets) {
GLuint id = 0;
MG_Impl::GLImpl::GenQueries(1, &id);
ASSERT_NE(id, 0u);
@@ -935,8 +947,7 @@ TEST_F(QueryTest, TessellationPipelineStatisticsTargetsFollowTheTessellationShad
}
MG_Impl::GLImpl::DeleteQueries(1, &id);
while (MG_Impl::GLImpl::GetError() != GL_NO_ERROR) {
}
while (MG_Impl::GLImpl::GetError() != GL_NO_ERROR) {}
}
}
@@ -983,8 +994,7 @@ TEST_F(QueryTest, PipelineStatisticsQueryObjectRefusesASecondTargetAndTargetsAre
MG_Impl::GLImpl::EndQuery(GL_PRIMITIVES_SUBMITTED);
MG_Impl::GLImpl::DeleteQueries(1, &second);
MG_Impl::GLImpl::DeleteQueries(1, &id);
while (MG_Impl::GLImpl::GetError() != GL_NO_ERROR) {
}
while (MG_Impl::GLImpl::GetError() != GL_NO_ERROR) {}
}
// glCreateQueries keeps its own, shorter accepted-target list on purpose: it is unchanged here,
File diff suppressed because it is too large Load Diff
+2 -5
View File
@@ -40,8 +40,7 @@ namespace MobileGL::MG_Test {
// drives a helper of a DIFFERENT verb class opens a nested scope for it.
class ScopedPipeVerb {
public:
explicit ScopedPipeVerb([[maybe_unused]] MG_Pipe::MGPipeVerb verb)
: m_verb(verb) {
explicit ScopedPipeVerb([[maybe_unused]] MG_Pipe::MGPipeVerb verb) : m_verb(verb) {
MG_Pipe::MGPipeValidateForVerb(m_verb);
}
@@ -51,9 +50,7 @@ namespace MobileGL::MG_Test {
// A second verb of the same kind begins: re-fill and re-stamp, so a helper driven
// again after the test moved frontend state sees the new values, the way the next GL
// entry point's MGP_FILL would.
void Renew() {
MG_Pipe::MGPipeValidateForVerb(m_verb);
}
void Renew() { MG_Pipe::MGPipeValidateForVerb(m_verb); }
// Leaving bumps the serial and puts the current verb back to "none": every field
// this scope stamped goes stale, and a later test that forgets its own declaration
@@ -52,11 +52,11 @@
namespace {
// The two Renderer headers are written to be included inside the backend namespace, after
// the project's own type aliases; they name Uint32 and declare nothing else. Including them
// here with a local alias keeps them byte-identical to what VulkanRenderer.cpp compiles -
// the alternative, a copy of the words in this file, is precisely the drift this gate is for.
using Uint32 = std::uint32_t;
// The two Renderer headers are written to be included inside the backend namespace, after
// the project's own type aliases; they name Uint32 and declare nothing else. Including them
// here with a local alias keeps them byte-identical to what VulkanRenderer.cpp compiles -
// the alternative, a copy of the words in this file, is precisely the drift this gate is for.
using Uint32 = std::uint32_t;
#include <MG_Backend/DirectVulkan/Renderer/WireColorBlitSpirv.h>
#include <MG_Backend/DirectVulkan/Renderer/WireDepthMipmapSpirv.h>
#include <MG_Backend/DirectVulkan/Renderer/WireMultisampleResolveSpirv.h>
@@ -64,227 +64,199 @@ using Uint32 = std::uint32_t;
#include <MG_Backend/DirectVulkan/Renderer/WireE5RawCopySpirv.h>
#include <MG_Backend/DirectVulkan/Renderer/WireDiscardStateProbeSpirv.h>
struct BakedShader {
const char* name; // ctest entry name, and the bake file's stem
const char* source; // repository-relative GLSL source
const char* header; // repository-relative header the words live in
const char* symbol; // the array identifier inside that header
EShLanguage stage;
glslang::EShTargetClientVersion client;
glslang::EShTargetLanguageVersion spv;
const std::uint32_t* words;
std::size_t wordCount;
};
struct BakedShader {
const char* name; // ctest entry name, and the bake file's stem
const char* source; // repository-relative GLSL source
const char* header; // repository-relative header the words live in
const char* symbol; // the array identifier inside that header
EShLanguage stage;
glslang::EShTargetClientVersion client;
glslang::EShTargetLanguageVersion spv;
const std::uint32_t* words;
std::size_t wordCount;
};
#define MGL_BAKED_ROW(name, source, header, symbol, stage, client, spv, array) \
BakedShader{name, source, header, symbol, stage, client, spv, (array), \
sizeof(array) / sizeof((array)[0])}
#define MGL_BAKED_ROW(name, source, header, symbol, stage, client, spv, array) \
BakedShader { \
name, source, header, symbol, stage, client, spv, (array), sizeof(array) / sizeof((array)[0]) \
}
const BakedShader kBakedShaders[] = {
// The Magma wire arms' own programs: no GL program object, no registry entry, no runtime
// transpilation, so the words in the header are the only copy that exists.
MGL_BAKED_ROW("WireColorBlitVertex",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireColorBlit.vert",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireColorBlitSpirv.h",
"kWireColorBlitVertexSpirv", EShLangVertex,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireColorBlitVertexSpirv),
MGL_BAKED_ROW("WireColorBlitFragment",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireColorBlit.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireColorBlitSpirv.h",
"kWireColorBlitFragmentSpirv", EShLangFragment,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireColorBlitFragmentSpirv),
// The raw E5B9G9R9 read route (WireE5RawCopy.h): one compute program per source shape.
MGL_BAKED_ROW("WireE5RawCopy",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireE5RawCopy.comp",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireE5RawCopySpirv.h",
"kWireE5RawCopySpirv", EShLangCompute,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireE5RawCopySpirv),
MGL_BAKED_ROW("WireE5RawCopy3D",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireE5RawCopy3D.comp",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireE5RawCopySpirv.h",
"kWireE5RawCopy3DSpirv", EShLangCompute,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireE5RawCopy3DSpirv),
// The rasterizer-discard state probe (WireDiscardStateProbe.h).
MGL_BAKED_ROW("WireDiscardStateProbeVertex",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDiscardStateProbe.vert",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDiscardStateProbeSpirv.h",
"kWireDiscardStateProbeVertexSpirv", EShLangVertex,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireDiscardStateProbeVertexSpirv),
MGL_BAKED_ROW("WireDiscardStateProbeFragment",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDiscardStateProbe.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDiscardStateProbeSpirv.h",
"kWireDiscardStateProbeFragmentSpirv", EShLangFragment,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireDiscardStateProbeFragmentSpirv),
MGL_BAKED_ROW("WireYuvConvertVertex",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireYuvConvert.vert",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireYuvConvertSpirv.h",
"kWireYuvConvertVertexSpirv", EShLangVertex,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireYuvConvertVertexSpirv),
MGL_BAKED_ROW("WireYuvConvertFragment",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireYuvConvert.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireYuvConvertSpirv.h",
"kWireYuvConvertFragmentSpirv", EShLangFragment,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireYuvConvertFragmentSpirv),
MGL_BAKED_ROW("WireDepthMipmapVertex",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthMipmap.vert",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthMipmapSpirv.h",
"kWireDepthMipmapVertexSpirv", EShLangVertex,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireDepthMipmapVertexSpirv),
MGL_BAKED_ROW("WireDepthMipmapFragment",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthMipmap.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthMipmapSpirv.h",
"kWireDepthMipmapFragmentSpirv", EShLangFragment,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireDepthMipmapFragmentSpirv),
// P7 wave 2-B2: the multisample depth/stencil resolve's own pass. THREE ROWS FOR TWO
// PIPELINES - one vertex stage shared by both, and a fragment stage per aspect, because a
// fragment shader cannot write the stencil aspect without VK_EXT_shader_stencil_export and
// a device without that extension must still be able to compile the depth half.
MGL_BAKED_ROW("WireMultisampleResolveVertex",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleResolve.vert",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleResolveSpirv.h",
"kWireMultisampleResolveVertexSpirv", EShLangVertex,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireMultisampleResolveVertexSpirv),
MGL_BAKED_ROW("WireMultisampleDepthResolveFragment",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleDepthResolve.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleResolveSpirv.h",
"kWireMultisampleDepthResolveFragmentSpirv", EShLangFragment,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireMultisampleDepthResolveFragmentSpirv),
MGL_BAKED_ROW("WireMultisampleStencilResolveFragment",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleStencilResolve.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleResolveSpirv.h",
"kWireMultisampleStencilResolveFragmentSpirv", EShLangFragment,
glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireMultisampleStencilResolveFragmentSpirv),
// The two driver self-test probes. They are not Magma's, and they are in this table for
// the reason the contract names them: they are baked, so they can be stale, and one of
// them was.
MGL_BAKED_ROW("DriverPostIterationRPWitness",
"MobileGL/MG_Util/SelfTest/DriverPostIterationRPWitness.comp",
"MobileGL/MG_Util/SelfTest/DriverPostIterationRPWitnessSpv.h",
"kDriverPostIterationRPWitnessSpv", EShLangCompute,
glslang::EShTargetVulkan_1_1, glslang::EShTargetSpv_1_3,
MobileGL::MG_Util::SelfTest::kDriverPostIterationRPWitnessSpv),
MGL_BAKED_ROW("PrimitivesGeneratedNoXfbProbeVert",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbe.vert",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbeSpv.h",
"kPrimitivesGeneratedNoXfbProbeVertSpv", EShLangVertex,
glslang::EShTargetVulkan_1_1, glslang::EShTargetSpv_1_3,
MobileGL::MG_Util::SelfTest::kPrimitivesGeneratedNoXfbProbeVertSpv),
MGL_BAKED_ROW("PrimitivesGeneratedNoXfbProbeTesc",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbe.tesc",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbeSpv.h",
"kPrimitivesGeneratedNoXfbProbeTescSpv", EShLangTessControl,
glslang::EShTargetVulkan_1_1, glslang::EShTargetSpv_1_3,
MobileGL::MG_Util::SelfTest::kPrimitivesGeneratedNoXfbProbeTescSpv),
MGL_BAKED_ROW("PrimitivesGeneratedNoXfbProbeTese",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbe.tese",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbeSpv.h",
"kPrimitivesGeneratedNoXfbProbeTeseSpv", EShLangTessEvaluation,
glslang::EShTargetVulkan_1_1, glslang::EShTargetSpv_1_3,
MobileGL::MG_Util::SelfTest::kPrimitivesGeneratedNoXfbProbeTeseSpv),
};
const BakedShader kBakedShaders[] = {
// The Magma wire arms' own programs: no GL program object, no registry entry, no runtime
// transpilation, so the words in the header are the only copy that exists.
MGL_BAKED_ROW("WireColorBlitVertex", "MobileGL/MG_Backend/DirectVulkan/Renderer/WireColorBlit.vert",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireColorBlitSpirv.h", "kWireColorBlitVertexSpirv",
EShLangVertex, glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireColorBlitVertexSpirv),
MGL_BAKED_ROW("WireColorBlitFragment", "MobileGL/MG_Backend/DirectVulkan/Renderer/WireColorBlit.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireColorBlitSpirv.h", "kWireColorBlitFragmentSpirv",
EShLangFragment, glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireColorBlitFragmentSpirv),
// The raw E5B9G9R9 read route (WireE5RawCopy.h): one compute program per source shape.
MGL_BAKED_ROW("WireE5RawCopy", "MobileGL/MG_Backend/DirectVulkan/Renderer/WireE5RawCopy.comp",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireE5RawCopySpirv.h", "kWireE5RawCopySpirv",
EShLangCompute, glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0, kWireE5RawCopySpirv),
MGL_BAKED_ROW("WireE5RawCopy3D", "MobileGL/MG_Backend/DirectVulkan/Renderer/WireE5RawCopy3D.comp",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireE5RawCopySpirv.h", "kWireE5RawCopy3DSpirv",
EShLangCompute, glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0, kWireE5RawCopy3DSpirv),
// The rasterizer-discard state probe (WireDiscardStateProbe.h).
MGL_BAKED_ROW("WireDiscardStateProbeVertex",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDiscardStateProbe.vert",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDiscardStateProbeSpirv.h",
"kWireDiscardStateProbeVertexSpirv", EShLangVertex, glslang::EShTargetVulkan_1_0,
glslang::EShTargetSpv_1_0, kWireDiscardStateProbeVertexSpirv),
MGL_BAKED_ROW("WireDiscardStateProbeFragment",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDiscardStateProbe.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDiscardStateProbeSpirv.h",
"kWireDiscardStateProbeFragmentSpirv", EShLangFragment, glslang::EShTargetVulkan_1_0,
glslang::EShTargetSpv_1_0, kWireDiscardStateProbeFragmentSpirv),
MGL_BAKED_ROW("WireYuvConvertVertex", "MobileGL/MG_Backend/DirectVulkan/Renderer/WireYuvConvert.vert",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireYuvConvertSpirv.h", "kWireYuvConvertVertexSpirv",
EShLangVertex, glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireYuvConvertVertexSpirv),
MGL_BAKED_ROW("WireYuvConvertFragment", "MobileGL/MG_Backend/DirectVulkan/Renderer/WireYuvConvert.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireYuvConvertSpirv.h", "kWireYuvConvertFragmentSpirv",
EShLangFragment, glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireYuvConvertFragmentSpirv),
MGL_BAKED_ROW("WireDepthMipmapVertex", "MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthMipmap.vert",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthMipmapSpirv.h", "kWireDepthMipmapVertexSpirv",
EShLangVertex, glslang::EShTargetVulkan_1_0, glslang::EShTargetSpv_1_0,
kWireDepthMipmapVertexSpirv),
MGL_BAKED_ROW("WireDepthMipmapFragment", "MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthMipmap.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireDepthMipmapSpirv.h",
"kWireDepthMipmapFragmentSpirv", EShLangFragment, glslang::EShTargetVulkan_1_0,
glslang::EShTargetSpv_1_0, kWireDepthMipmapFragmentSpirv),
// P7 wave 2-B2: the multisample depth/stencil resolve's own pass. THREE ROWS FOR TWO
// PIPELINES - one vertex stage shared by both, and a fragment stage per aspect, because a
// fragment shader cannot write the stencil aspect without VK_EXT_shader_stencil_export and
// a device without that extension must still be able to compile the depth half.
MGL_BAKED_ROW("WireMultisampleResolveVertex",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleResolve.vert",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleResolveSpirv.h",
"kWireMultisampleResolveVertexSpirv", EShLangVertex, glslang::EShTargetVulkan_1_0,
glslang::EShTargetSpv_1_0, kWireMultisampleResolveVertexSpirv),
MGL_BAKED_ROW("WireMultisampleDepthResolveFragment",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleDepthResolve.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleResolveSpirv.h",
"kWireMultisampleDepthResolveFragmentSpirv", EShLangFragment, glslang::EShTargetVulkan_1_0,
glslang::EShTargetSpv_1_0, kWireMultisampleDepthResolveFragmentSpirv),
MGL_BAKED_ROW("WireMultisampleStencilResolveFragment",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleStencilResolve.frag",
"MobileGL/MG_Backend/DirectVulkan/Renderer/WireMultisampleResolveSpirv.h",
"kWireMultisampleStencilResolveFragmentSpirv", EShLangFragment, glslang::EShTargetVulkan_1_0,
glslang::EShTargetSpv_1_0, kWireMultisampleStencilResolveFragmentSpirv),
// The two driver self-test probes. They are not Magma's, and they are in this table for
// the reason the contract names them: they are baked, so they can be stale, and one of
// them was.
MGL_BAKED_ROW("DriverPostIterationRPWitness", "MobileGL/MG_Util/SelfTest/DriverPostIterationRPWitness.comp",
"MobileGL/MG_Util/SelfTest/DriverPostIterationRPWitnessSpv.h", "kDriverPostIterationRPWitnessSpv",
EShLangCompute, glslang::EShTargetVulkan_1_1, glslang::EShTargetSpv_1_3,
MobileGL::MG_Util::SelfTest::kDriverPostIterationRPWitnessSpv),
MGL_BAKED_ROW("PrimitivesGeneratedNoXfbProbeVert",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbe.vert",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbeSpv.h",
"kPrimitivesGeneratedNoXfbProbeVertSpv", EShLangVertex, glslang::EShTargetVulkan_1_1,
glslang::EShTargetSpv_1_3, MobileGL::MG_Util::SelfTest::kPrimitivesGeneratedNoXfbProbeVertSpv),
MGL_BAKED_ROW("PrimitivesGeneratedNoXfbProbeTesc",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbe.tesc",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbeSpv.h",
"kPrimitivesGeneratedNoXfbProbeTescSpv", EShLangTessControl, glslang::EShTargetVulkan_1_1,
glslang::EShTargetSpv_1_3, MobileGL::MG_Util::SelfTest::kPrimitivesGeneratedNoXfbProbeTescSpv),
MGL_BAKED_ROW("PrimitivesGeneratedNoXfbProbeTese",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbe.tese",
"MobileGL/MG_Util/SelfTest/PrimitivesGeneratedNoXfbProbeSpv.h",
"kPrimitivesGeneratedNoXfbProbeTeseSpv", EShLangTessEvaluation, glslang::EShTargetVulkan_1_1,
glslang::EShTargetSpv_1_3, MobileGL::MG_Util::SelfTest::kPrimitivesGeneratedNoXfbProbeTeseSpv),
};
#undef MGL_BAKED_ROW
std::string RepositoryRoot() {
std::string RepositoryRoot() {
#ifdef MOBILEGL_BAKED_SHADER_ROOT
return std::string(MOBILEGL_BAKED_SHADER_ROOT);
return std::string(MOBILEGL_BAKED_SHADER_ROOT);
#else
return std::string();
return std::string();
#endif
}
}
// glslang::InitializeProcess is process-wide and refcounted. One call for the whole binary:
// this test never runs MobileGL::Initialize, which is the other caller.
void EnsureGlslangProcess() {
static const bool ready = glslang::InitializeProcess();
ASSERT_TRUE(ready) << "glslang::InitializeProcess failed";
}
// glslang::InitializeProcess is process-wide and refcounted. One call for the whole binary:
// this test never runs MobileGL::Initialize, which is the other caller.
void EnsureGlslangProcess() {
static const bool ready = glslang::InitializeProcess();
ASSERT_TRUE(ready) << "glslang::InitializeProcess failed";
}
class BakedInternalShaders : public ::testing::TestWithParam<BakedShader> {};
class BakedInternalShaders : public ::testing::TestWithParam<BakedShader> {};
TEST_P(BakedInternalShaders, HeaderMatchesItsSource) {
const BakedShader& row = GetParam();
ASSERT_NO_FATAL_FAILURE(EnsureGlslangProcess());
TEST_P(BakedInternalShaders, HeaderMatchesItsSource) {
const BakedShader& row = GetParam();
ASSERT_NO_FATAL_FAILURE(EnsureGlslangProcess());
const std::string root = RepositoryRoot();
ASSERT_FALSE(root.empty())
<< "MOBILEGL_BAKED_SHADER_ROOT was not defined for this target: the gate cannot find "
"the GLSL sources and must not pass by default";
const std::string sourcePath = root + "/" + row.source;
std::ifstream in(sourcePath, std::ios::binary);
ASSERT_TRUE(in.good()) << "cannot open " << sourcePath;
std::ostringstream buffer;
buffer << in.rdbuf();
const std::string source = buffer.str();
ASSERT_FALSE(source.empty()) << sourcePath << " is empty";
const std::string root = RepositoryRoot();
ASSERT_FALSE(root.empty())
<< "MOBILEGL_BAKED_SHADER_ROOT was not defined for this target: the gate cannot find "
"the GLSL sources and must not pass by default";
const std::string sourcePath = root + "/" + row.source;
std::ifstream in(sourcePath, std::ios::binary);
ASSERT_TRUE(in.good()) << "cannot open " << sourcePath;
std::ostringstream buffer;
buffer << in.rdbuf();
const std::string source = buffer.str();
ASSERT_FALSE(source.empty()) << sourcePath << " is empty";
glslang::TShader shader(row.stage);
const char* strings[] = {source.c_str()};
shader.setStrings(strings, 1);
shader.setEnvInput(glslang::EShSourceGlsl, row.stage, glslang::EShClientVulkan, 100);
shader.setEnvClient(glslang::EShClientVulkan, row.client);
shader.setEnvTarget(glslang::EShTargetSpv, row.spv);
const EShMessages messages = static_cast<EShMessages>(EShMsgSpvRules | EShMsgVulkanRules);
ASSERT_TRUE(shader.parse(GetDefaultResources(), 100, false, messages))
<< row.source << " does not compile:\n" << shader.getInfoLog();
glslang::TShader shader(row.stage);
const char* strings[] = {source.c_str()};
shader.setStrings(strings, 1);
shader.setEnvInput(glslang::EShSourceGlsl, row.stage, glslang::EShClientVulkan, 100);
shader.setEnvClient(glslang::EShClientVulkan, row.client);
shader.setEnvTarget(glslang::EShTargetSpv, row.spv);
const EShMessages messages = static_cast<EShMessages>(EShMsgSpvRules | EShMsgVulkanRules);
ASSERT_TRUE(shader.parse(GetDefaultResources(), 100, false, messages)) << row.source << " does not compile:\n"
<< shader.getInfoLog();
glslang::TProgram program;
program.addShader(&shader);
ASSERT_TRUE(program.link(messages)) << row.source << " does not link:\n" << program.getInfoLog();
glslang::TIntermediate* intermediate = program.getIntermediate(row.stage);
ASSERT_NE(intermediate, nullptr);
glslang::TProgram program;
program.addShader(&shader);
ASSERT_TRUE(program.link(messages)) << row.source << " does not link:\n" << program.getInfoLog();
glslang::TIntermediate* intermediate = program.getIntermediate(row.stage);
ASSERT_NE(intermediate, nullptr);
std::vector<unsigned int> spirv;
spv::SpvBuildLogger logger;
glslang::SpvOptions options;
options.disableOptimizer = true;
glslang::GlslangToSpv(*intermediate, spirv, &logger, &options);
ASSERT_FALSE(spirv.empty()) << "GlslangToSpv produced nothing for " << row.source;
std::vector<unsigned int> spirv;
spv::SpvBuildLogger logger;
glslang::SpvOptions options;
options.disableOptimizer = true;
glslang::GlslangToSpv(*intermediate, spirv, &logger, &options);
ASSERT_FALSE(spirv.empty()) << "GlslangToSpv produced nothing for " << row.source;
// Bake mode writes what it computed and asserts nothing else: the script that sets this
// variable is about to overwrite the header, so a red here would only stop it doing so.
if (const char* bakeDir = std::getenv("MOBILEGL_BAKE_INTERNAL_SHADERS")) {
const std::string out = std::string(bakeDir) + "/" + row.symbol + ".words";
std::ofstream sink(out, std::ios::binary);
ASSERT_TRUE(sink.good()) << "cannot write " << out;
sink << row.header << "\n";
for (unsigned int word : spirv) {
char text[16];
std::snprintf(text, sizeof(text), "0x%08x\n", word);
sink << text;
// Bake mode writes what it computed and asserts nothing else: the script that sets this
// variable is about to overwrite the header, so a red here would only stop it doing so.
if (const char* bakeDir = std::getenv("MOBILEGL_BAKE_INTERNAL_SHADERS")) {
const std::string out = std::string(bakeDir) + "/" + row.symbol + ".words";
std::ofstream sink(out, std::ios::binary);
ASSERT_TRUE(sink.good()) << "cannot write " << out;
sink << row.header << "\n";
for (unsigned int word : spirv) {
char text[16];
std::snprintf(text, sizeof(text), "0x%08x\n", word);
sink << text;
}
ASSERT_TRUE(sink.good()) << "failed writing " << out;
return;
}
ASSERT_EQ(spirv.size(), row.wordCount)
<< row.header << ": " << row.symbol << " has " << row.wordCount << " words, recompiling " << row.source
<< " with the in-tree glslang produces " << spirv.size()
<< ". Regenerate with scripts/bake_internal_shaders.py.";
for (std::size_t at = 0; at < spirv.size(); ++at) {
ASSERT_EQ(spirv[at], row.words[at])
<< row.header << ": " << row.symbol << " word " << at << " is stale against " << row.source
<< ". Regenerate with scripts/bake_internal_shaders.py.";
}
ASSERT_TRUE(sink.good()) << "failed writing " << out;
return;
}
ASSERT_EQ(spirv.size(), row.wordCount)
<< row.header << ": " << row.symbol << " has " << row.wordCount << " words, recompiling "
<< row.source << " with the in-tree glslang produces " << spirv.size()
<< ". Regenerate with scripts/bake_internal_shaders.py.";
for (std::size_t at = 0; at < spirv.size(); ++at) {
ASSERT_EQ(spirv[at], row.words[at])
<< row.header << ": " << row.symbol << " word " << at << " is stale against "
<< row.source << ". Regenerate with scripts/bake_internal_shaders.py.";
}
}
INSTANTIATE_TEST_SUITE_P(BakedShaders, BakedInternalShaders,
::testing::ValuesIn(kBakedShaders),
[](const ::testing::TestParamInfo<BakedShader>& info) {
return std::string(info.param.name);
});
INSTANTIATE_TEST_SUITE_P(BakedShaders, BakedInternalShaders, ::testing::ValuesIn(kBakedShaders),
[](const ::testing::TestParamInfo<BakedShader>& info) {
return std::string(info.param.name);
});
} // namespace
@@ -21,13 +21,13 @@
using namespace MobileGL;
using MobileGL::MG_Util::SelfTest::CollectGlesKnownDriverBugs;
using MobileGL::MG_Util::SelfTest::DriverBugVerdict;
using MobileGL::MG_Util::SelfTest::ProbeBlitIgnoresDestinationArrayLayer;
using MobileGL::MG_Util::SelfTest::ProbeCopyImageMirrorsPacked16FieldOrder;
using MobileGL::MG_Util::SelfTest::ProbeCrossStageImageQualifierMergeDropsWrites;
using MobileGL::MG_Util::SelfTest::ProbeExplicitVertexInputLocationCeiling;
using MobileGL::MG_Util::SelfTest::ProbeGeometryStageSsboWriteAfterEmitDropped;
using MobileGL::MG_Util::SelfTest::ProbeImageLocationPerNameBudget;
using MobileGL::MG_Util::SelfTest::ProbeImageWriteReadCoherencyResidual;
using MobileGL::MG_Util::SelfTest::ProbeBlitIgnoresDestinationArrayLayer;
using MobileGL::MG_Util::SelfTest::ProbeCopyImageMirrorsPacked16FieldOrder;
using MobileGL::MG_Util::SelfTest::ProbeExplicitVertexInputLocationCeiling;
using MobileGL::MG_Util::SelfTest::ProbeR32FMultisampleSwizzleCorruption;
namespace {
@@ -55,7 +55,8 @@ namespace {
// link log below is: the report shows it to a human, so a probe that stopped capturing it
// would stop being useful long before it stopped detecting.
const char* const kAttributeRangeCompileLog =
"ERROR: 0:2: '' : the location is not within attribute range [0, MAX_ATTRIBUTES-1] \nERROR: 1 compilation errors. No code generated.";
"ERROR: 0:2: '' : the location is not within attribute range [0, MAX_ATTRIBUTES-1] \nERROR: 1 compilation "
"errors. No code generated.";
// The exact text an affected Adreno driver puts in the info log for this refusal.
const char* const kImageLocationLinkLog =
@@ -202,7 +203,9 @@ namespace {
FakeDriver g_fake;
void ResetFakeDriver() { g_fake = FakeDriver{}; }
void ResetFakeDriver() {
g_fake = FakeDriver{};
}
const std::string& SourceOf(GLuint shader) {
static const std::string empty;
@@ -238,7 +241,8 @@ namespace {
const std::size_t end = source.find_first_of(";,)", at);
if (end == std::string::npos) break;
std::string name = source.substr(at, end - at);
while (!name.empty() && (name.back() == ' ' || name.back() == '\t')) name.pop_back();
while (!name.empty() && (name.back() == ' ' || name.back() == '\t'))
name.pop_back();
if (std::find(names.begin(), names.end(), name) == names.end()) {
names.push_back(name);
}
@@ -362,8 +366,7 @@ namespace {
++g_fake.aliveShaders;
return g_fake.nextShaderId++;
};
funcs.glShaderSource = [](GLuint shader, GLsizei count, const GLchar* const* strings,
const GLint*) {
funcs.glShaderSource = [](GLuint shader, GLsizei count, const GLchar* const* strings, const GLint*) {
std::string source;
for (GLsizei i = 0; i < count; ++i) {
if (strings[i] != nullptr) source += strings[i];
@@ -387,8 +390,8 @@ namespace {
if (bufSize <= 0) return;
const auto it = g_fake.shaderInfoLogs.find(shader);
const std::string& log = it == g_fake.shaderInfoLogs.end() ? std::string() : it->second;
const GLsizei copied = static_cast<GLsizei>(
std::min<std::size_t>(log.size(), static_cast<std::size_t>(bufSize - 1)));
const GLsizei copied =
static_cast<GLsizei>(std::min<std::size_t>(log.size(), static_cast<std::size_t>(bufSize - 1)));
std::memcpy(infoLog, log.data(), static_cast<std::size_t>(copied));
infoLog[copied] = '\0';
};
@@ -409,9 +412,7 @@ namespace {
++g_fake.alivePrograms;
return g_fake.nextProgramId++;
};
funcs.glAttachShader = [](GLuint program, GLuint shader) {
g_fake.programShaders[program].push_back(shader);
};
funcs.glAttachShader = [](GLuint program, GLuint shader) { g_fake.programShaders[program].push_back(shader); };
funcs.glLinkProgram = [](GLuint program) {
const std::vector<std::string> names = DeclaredImageNames(program);
const bool overBudget = static_cast<int>(names.size()) > g_fake.distinctImageNameBudget;
@@ -419,8 +420,7 @@ namespace {
// refuses the LINK rather than the compile - which is the half of the vertex-input
// probe that decides whether the attribute is reachable another way at all.
bool attributeOutOfRange = false;
if (const auto it = g_fake.boundAttribLocations.find(program);
it != g_fake.boundAttribLocations.end()) {
if (const auto it = g_fake.boundAttribLocations.find(program); it != g_fake.boundAttribLocations.end()) {
for (const auto& [attributeName, location] : it->second) {
if (location >= g_fake.bindAttribLocationCeiling) attributeOutOfRange = true;
}
@@ -440,8 +440,8 @@ namespace {
if (bufSize <= 0) return;
const auto it = g_fake.programInfoLogs.find(program);
const std::string& log = it == g_fake.programInfoLogs.end() ? std::string() : it->second;
const GLsizei copied = static_cast<GLsizei>(
std::min<std::size_t>(log.size(), static_cast<std::size_t>(bufSize - 1)));
const GLsizei copied =
static_cast<GLsizei>(std::min<std::size_t>(log.size(), static_cast<std::size_t>(bufSize - 1)));
std::memcpy(infoLog, log.data(), static_cast<std::size_t>(copied));
infoLog[copied] = '\0';
};
@@ -469,8 +469,8 @@ namespace {
};
// One byte per layer: the layered-blit probe fills every texel of a layer with the same
// value and only ever asks which layer a value ended up on.
funcs.glTexSubImage3D = [](GLenum target, GLint, GLint, GLint, GLint zoffset, GLsizei, GLsizei,
GLsizei, GLenum, GLenum, const void* pixels) {
funcs.glTexSubImage3D = [](GLenum target, GLint, GLint, GLint, GLint zoffset, GLsizei, GLsizei, GLsizei, GLenum,
GLenum, const void* pixels) {
if (target != GL_TEXTURE_2D_ARRAY || pixels == nullptr) return;
auto& fill = g_fake.arrayLayerFill[g_fake.boundArrayTexture];
if (zoffset >= 0 && static_cast<std::size_t>(zoffset) < fill.size()) {
@@ -492,13 +492,11 @@ namespace {
};
funcs.glTexParameteri = [](GLenum target, GLenum pname, GLint param) {
if (target == GL_TEXTURE_2D_MULTISAMPLE && pname == GL_TEXTURE_SWIZZLE_A) {
g_fake.multisampleAlphaSwizzle[g_fake.boundMultisampleTexture] =
static_cast<GLenum>(param);
g_fake.multisampleAlphaSwizzle[g_fake.boundMultisampleTexture] = static_cast<GLenum>(param);
}
// A parameter write on a 2D array that has no uploaded level yet steers the
// driver's layout choice to the plain order (see FakeArrayAllocation).
if (target == GL_TEXTURE_2D_ARRAY &&
g_fake.packedArrayAllocations.count(g_fake.boundArrayTexture) == 0) {
if (target == GL_TEXTURE_2D_ARRAY && g_fake.packedArrayAllocations.count(g_fake.boundArrayTexture) == 0) {
g_fake.packedArrayAllocations[g_fake.boundArrayTexture].paramsTouchedBeforeUpload = true;
}
};
@@ -506,8 +504,8 @@ namespace {
// canonical (non-REV) order on every knob setting - the defect is confined to array
// mip levels, and keeping the 2D side clean is what lets the readback below decode
// with one order and still reproduce the mirror.
funcs.glTexImage2D = [](GLenum target, GLint level, GLint, GLsizei, GLsizei, GLint, GLenum,
GLenum type, const void* pixels) {
funcs.glTexImage2D = [](GLenum target, GLint level, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum type,
const void* pixels) {
if (target != GL_TEXTURE_2D || type != GL_UNSIGNED_SHORT_5_5_5_1 || pixels == nullptr) return;
GLushort word = 0;
std::memcpy(&word, pixels, sizeof(word));
@@ -516,8 +514,8 @@ namespace {
// Records the allocation shape the mirror below is gated on, and the uploaded word.
// Under the upload-corruption knob the STORED word is already wrong - the "not this
// bug" shape the probe's round-trip control must catch.
funcs.glTexImage3D = [](GLenum target, GLint level, GLint, GLsizei width, GLsizei height,
GLsizei depth, GLint, GLenum, GLenum type, const void* pixels) {
funcs.glTexImage3D = [](GLenum target, GLint level, GLint, GLsizei width, GLsizei height, GLsizei depth, GLint,
GLenum, GLenum type, const void* pixels) {
if (target != GL_TEXTURE_2D_ARRAY || type != GL_UNSIGNED_SHORT_5_5_5_1 || pixels == nullptr) return;
GLushort word = 0;
std::memcpy(&word, pixels, sizeof(word));
@@ -534,9 +532,8 @@ namespace {
// A raw texel-block move: the PHYSICAL word travels. The defect lives here - a source
// in the mirrored ALLOCATION delivers the re-encoded word from EVERY level - and it
// only exists for the allocation it was measured on: three levels of a 30x30x12 array.
funcs.glCopyImageSubData = [](GLuint srcName, GLenum, GLint srcLevel, GLint, GLint, GLint,
GLuint dstName, GLenum, GLint dstLevel, GLint, GLint, GLint,
GLsizei, GLsizei, GLsizei) {
funcs.glCopyImageSubData = [](GLuint srcName, GLenum, GLint srcLevel, GLint, GLint, GLint, GLuint dstName,
GLenum, GLint dstLevel, GLint, GLint, GLint, GLsizei, GLsizei, GLsizei) {
if (g_fake.packed16CopyDoesNothing) return;
const auto source = g_fake.packedTexelWords.find({srcName, srcLevel});
if (source == g_fake.packedTexelWords.end()) return;
@@ -544,16 +541,14 @@ namespace {
const auto allocation = g_fake.packedArrayAllocations.find(srcName);
const bool measuredShape = allocation != g_fake.packedArrayAllocations.end() &&
allocation->second.width == 30 && allocation->second.height == 30 &&
allocation->second.layers == 12 &&
allocation->second.levelMask == 0b111u &&
allocation->second.layers == 12 && allocation->second.levelMask == 0b111u &&
!allocation->second.paramsTouchedBeforeUpload;
if (measuredShape && g_fake.packed16ArrayAllocationMirrored) {
word = MirrorPacked5551(word);
}
g_fake.packedTexelWords[{dstName, dstLevel}] = word;
};
funcs.glTexSubImage2D = [](GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum,
const void*) {};
funcs.glTexSubImage2D = [](GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*) {};
funcs.glTexStorage2D = [](GLenum, GLsizei, GLenum, GLsizei, GLsizei) {};
funcs.glTexStorage2DMultisample = [](GLenum, GLsizei, GLenum, GLsizei, GLsizei, GLboolean) {};
funcs.glGenFramebuffers = [](GLsizei n, GLuint* framebuffers) {
@@ -571,13 +566,13 @@ namespace {
}
};
funcs.glFramebufferTexture2D = [](GLenum target, GLenum, GLenum, GLuint texture, GLint) {
const GLuint framebuffer = (target == GL_READ_FRAMEBUFFER) ? g_fake.boundReadFramebuffer
: g_fake.boundDrawFramebuffer;
const GLuint framebuffer =
(target == GL_READ_FRAMEBUFFER) ? g_fake.boundReadFramebuffer : g_fake.boundDrawFramebuffer;
g_fake.framebuffer2DAttachment[framebuffer] = texture;
};
funcs.glFramebufferTextureLayer = [](GLenum target, GLenum, GLuint texture, GLint level, GLint layer) {
const GLuint framebuffer = (target == GL_READ_FRAMEBUFFER) ? g_fake.boundReadFramebuffer
: g_fake.boundDrawFramebuffer;
const GLuint framebuffer =
(target == GL_READ_FRAMEBUFFER) ? g_fake.boundReadFramebuffer : g_fake.boundDrawFramebuffer;
g_fake.framebufferLayerAttachment[framebuffer] = {texture, layer};
g_fake.framebufferLayerLevel[framebuffer] = level;
};
@@ -585,8 +580,7 @@ namespace {
// The defect itself: the source layer is read from where the READ framebuffer says (unless
// that knob is on too), and the result is written to the layer the DRAW framebuffer names -
// or to layer 0 regardless, which is what an affected driver does.
funcs.glBlitFramebuffer = [](GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield,
GLenum) {
funcs.glBlitFramebuffer = [](GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) {
const auto source = g_fake.framebufferLayerAttachment.find(g_fake.boundReadFramebuffer);
const auto destination = g_fake.framebufferLayerAttachment.find(g_fake.boundDrawFramebuffer);
if (source == g_fake.framebufferLayerAttachment.end() ||
@@ -594,13 +588,11 @@ namespace {
return;
}
const GLint sourceLayer = g_fake.blitIgnoresSourceLayer ? 0 : source->second.second;
const GLint destinationLayer =
g_fake.blitIgnoresDestinationLayer ? 0 : destination->second.second;
const GLint destinationLayer = g_fake.blitIgnoresDestinationLayer ? 0 : destination->second.second;
auto& sourceFill = g_fake.arrayLayerFill[source->second.first];
auto& destinationFill = g_fake.arrayLayerFill[destination->second.first];
if (sourceLayer < 0 || static_cast<std::size_t>(sourceLayer) >= sourceFill.size()) return;
if (destinationLayer < 0 ||
static_cast<std::size_t>(destinationLayer) >= destinationFill.size()) {
if (destinationLayer < 0 || static_cast<std::size_t>(destinationLayer) >= destinationFill.size()) {
return;
}
destinationFill[static_cast<std::size_t>(destinationLayer)] =
@@ -637,8 +629,7 @@ namespace {
int sampleIndex = -1;
char component = '?';
ParseSampledFetch(sampling, sampleIndex, component);
const GLenum swizzle = g_fake.multisampleAlphaSwizzle.count(
g_fake.boundMultisampleTexture) != 0
const GLenum swizzle = g_fake.multisampleAlphaSwizzle.count(g_fake.boundMultisampleTexture) != 0
? g_fake.multisampleAlphaSwizzle[g_fake.boundMultisampleTexture]
: GL_ALPHA;
// An R32F texel filled with (1, 0, 0, -) reads 1.0 through both the ALPHA and the
@@ -679,18 +670,16 @@ namespace {
}
if (!writeStage.empty() && !readStage.empty()) {
// The qualifier-merge pair: the stores are lost when the two halves share a name.
const bool sharedName =
FirstImageNameIn(writeStage) == FirstImageNameIn(readStage) &&
!FirstImageNameIn(writeStage).empty();
const bool lost = g_fake.everyVertexImageWriteDropped ||
(g_fake.sameNameImagePairDropsWrites && sharedName);
const bool sharedName = FirstImageNameIn(writeStage) == FirstImageNameIn(readStage) &&
!FirstImageNameIn(writeStage).empty();
const bool lost =
g_fake.everyVertexImageWriteDropped || (g_fake.sameNameImagePairDropsWrites && sharedName);
g_fake.lastFailedTexelCount = lost ? 1 << 20 : 0;
return;
}
g_fake.lastFailedTexelCount = 0;
};
funcs.glReadPixels = [](GLint, GLint, GLsizei width, GLsizei height, GLenum format, GLenum type,
void* pixels) {
funcs.glReadPixels = [](GLint, GLint, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels) {
const std::size_t texels = static_cast<std::size_t>(width) * static_cast<std::size_t>(height);
// A read framebuffer naming a plain 2D texture that holds a 5551 word is the
// packed16 probe reading its copy destination. The driver decodes its OWN storage
@@ -702,9 +691,7 @@ namespace {
// Gated on the texture actually holding a 5551 word, so every OTHER probe that
// attaches a plain 2D texture keeps the pass/fail readback paths below.
const GLushort w = g_fake.packedTexelWords[{attached->second, 0}];
const auto expand5 = [](GLushort v) {
return static_cast<GLubyte>((v << 3) | (v >> 2));
};
const auto expand5 = [](GLushort v) { return static_cast<GLubyte>((v << 3) | (v >> 2)); };
GLubyte* out = static_cast<GLubyte*>(pixels);
for (std::size_t i = 0; i < texels; ++i) {
out[i * 4 + 0] = expand5((w >> 11) & 0x1F);
@@ -725,9 +712,7 @@ namespace {
if (const auto word = g_fake.packedTexelWords.find({layered->second.first, attachedLevel});
word != g_fake.packedTexelWords.end()) {
const GLushort w = word->second;
const auto expand5 = [](GLushort v) {
return static_cast<GLubyte>((v << 3) | (v >> 2));
};
const auto expand5 = [](GLushort v) { return static_cast<GLubyte>((v << 3) | (v >> 2)); };
GLubyte* out = static_cast<GLubyte*>(pixels);
for (std::size_t i = 0; i < texels; ++i) {
out[i * 4 + 0] = expand5((w >> 11) & 0x1F);
@@ -742,10 +727,9 @@ namespace {
// below share.
const auto& fill = g_fake.arrayLayerFill[layered->second.first];
const GLint layer = layered->second.second;
const GLubyte value =
(layer >= 0 && static_cast<std::size_t>(layer) < fill.size())
? fill[static_cast<std::size_t>(layer)]
: 0;
const GLubyte value = (layer >= 0 && static_cast<std::size_t>(layer) < fill.size())
? fill[static_cast<std::size_t>(layer)]
: 0;
GLubyte* out = static_cast<GLubyte*>(pixels);
for (std::size_t i = 0; i < texels; ++i) {
out[i * 4 + 0] = value;
@@ -757,7 +741,8 @@ namespace {
}
if (format == GL_RED && type == GL_FLOAT) {
GLfloat* out = static_cast<GLfloat*>(pixels);
for (std::size_t i = 0; i < texels; ++i) out[i] = g_fake.lastSampledValue;
for (std::size_t i = 0; i < texels; ++i)
out[i] = g_fake.lastSampledValue;
return;
}
GLubyte* out = static_cast<GLubyte*>(pixels);
@@ -790,8 +775,7 @@ namespace {
// section would stop meaning "this device has these bugs".
TEST(DriverBugProbes, AProbeThatCannotRunReportsNoBug) {
const MG_External::GLESFunctionsTable gl = EmptyFunctionTable();
EXPECT_FALSE(ProbeBlitIgnoresDestinationArrayLayer(gl))
<< "a probe with no entry points has measured nothing";
EXPECT_FALSE(ProbeBlitIgnoresDestinationArrayLayer(gl)) << "a probe with no entry points has measured nothing";
EXPECT_FALSE(ProbeExplicitVertexInputLocationCeiling(gl).detected)
<< "a probe with no entry points has measured nothing";
EXPECT_FALSE(ProbeGeometryStageSsboWriteAfterEmitDropped(gl))
@@ -800,8 +784,7 @@ TEST(DriverBugProbes, AProbeThatCannotRunReportsNoBug) {
EXPECT_FALSE(ProbeImageLocationPerNameBudget(gl).detected);
EXPECT_FALSE(ProbeCrossStageImageQualifierMergeDropsWrites(gl));
EXPECT_FALSE(ProbeImageWriteReadCoherencyResidual(gl).detected);
EXPECT_FALSE(ProbeCopyImageMirrorsPacked16FieldOrder(gl))
<< "a probe with no entry points has measured nothing";
EXPECT_FALSE(ProbeCopyImageMirrorsPacked16FieldOrder(gl)) << "a probe with no entry points has measured nothing";
}
// The section lists only bugs the device HAS, so a driver nothing could be probed on renders
@@ -819,8 +802,7 @@ TEST(DriverBugProbes, EveryFindingCarriesANameAndAnExplanation) {
for (const auto& finding : CollectGlesKnownDriverBugs(gl)) {
EXPECT_FALSE(finding.name.empty());
EXPECT_FALSE(finding.detail.empty()) << finding.name << " must say what MobileGL does about it";
EXPECT_TRUE(finding.verdict == DriverBugVerdict::Fixed ||
finding.verdict == DriverBugVerdict::Unfixable);
EXPECT_TRUE(finding.verdict == DriverBugVerdict::Fixed || finding.verdict == DriverBugVerdict::Unfixable);
}
}
@@ -1108,8 +1090,7 @@ TEST(DriverBugProbes, LayeredBlitDestinationReportsNothingWhenTheBlitMovesNothin
ResetFakeDriver();
const MG_External::GLESFunctionsTable gl = MakeFakeGLESFunctions();
MG_External::GLESFunctionsTable inert = gl;
inert.glBlitFramebuffer = [](GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield,
GLenum) {};
inert.glBlitFramebuffer = [](GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) {};
EXPECT_FALSE(ProbeBlitIgnoresDestinationArrayLayer(inert));
ExpectProbeReleasedEverything();
}
@@ -1181,7 +1162,7 @@ TEST(DriverBugProbes, Packed16MirrorArithmeticMatchesTheDeviceEvidence) {
#if MOBILEGL_BUILD_DISAGGREGATED
namespace {
MG_Backend::DirectVulkan::WireDepthResolveProbeMeasurement DepthResolveMeasurement(Uint32 renderPassMatches,
Uint32 shaderMatches) {
Uint32 shaderMatches) {
MG_Backend::DirectVulkan::WireDepthResolveProbeMeasurement measurement;
measurement.ran = true;
MG_Backend::DirectVulkan::WireDepthResolveFormatReading reading;
@@ -27,21 +27,33 @@ namespace {
Int channel = 0;
Vector<Uint8> staging;
};
struct Draw { GLuint fbo, buffer; Int channel; Bool late; };
struct Draw {
GLuint fbo, buffer;
Int channel;
Bool late;
};
std::map<GLuint, Buffer> buffers;
std::map<GLuint, GLuint> vaoBuffers;
std::map<GLuint, Int> colors;
Vector<Draw> draws;
std::set<GLuint> live;
std::map<GLenum, GLint> state = {
{GL_CURRENT_PROGRAM, 1}, {GL_VERTEX_ARRAY_BINDING, 2}, {GL_ARRAY_BUFFER, 3},
{GL_COPY_READ_BUFFER, 4}, {GL_COPY_WRITE_BUFFER, 5},
{GL_DRAW_FRAMEBUFFER_BINDING, 6}, {GL_READ_FRAMEBUFFER_BINDING, 7},
{GL_TEXTURE_BINDING_2D, 8}, {GL_PIXEL_PACK_BUFFER, 9},
{GL_PACK_ALIGNMENT, 8}, {GL_PACK_ROW_LENGTH, 31},
{GL_PACK_SKIP_PIXELS, 4}, {GL_PACK_SKIP_ROWS, 5}};
std::map<GLenum, GLboolean> enabled = {{GL_BLEND, GL_TRUE}, {GL_SCISSOR_TEST, GL_TRUE},
{GL_SAMPLE_MASK, GL_TRUE}, {GL_RASTERIZER_DISCARD, GL_TRUE}};
std::map<GLenum, GLint> state = {{GL_CURRENT_PROGRAM, 1},
{GL_VERTEX_ARRAY_BINDING, 2},
{GL_ARRAY_BUFFER, 3},
{GL_COPY_READ_BUFFER, 4},
{GL_COPY_WRITE_BUFFER, 5},
{GL_DRAW_FRAMEBUFFER_BINDING, 6},
{GL_READ_FRAMEBUFFER_BINDING, 7},
{GL_TEXTURE_BINDING_2D, 8},
{GL_PIXEL_PACK_BUFFER, 9},
{GL_PACK_ALIGNMENT, 8},
{GL_PACK_ROW_LENGTH, 31},
{GL_PACK_SKIP_PIXELS, 4},
{GL_PACK_SKIP_ROWS, 5}};
std::map<GLenum, GLboolean> enabled = {{GL_BLEND, GL_TRUE},
{GL_SCISSOR_TEST, GL_TRUE},
{GL_SAMPLE_MASK, GL_TRUE},
{GL_RASTERIZER_DISCARD, GL_TRUE}};
std::array<GLint, 4> viewport = {3, 4, 5, 6};
std::array<GLfloat, 4> clear = {.25f, .5f, .75f, 0};
std::array<GLboolean, 4> mask = {GL_FALSE, GL_TRUE, GL_FALSE, GL_TRUE};
@@ -54,8 +66,14 @@ namespace {
Uint arenaAllocations = 0;
Uint8 pointerSentinel = 0;
GLuint Create() { live.insert(next); return next++; }
void Generate(GLsizei count, GLuint* ids) { for (Int i = 0; i < count; ++i) ids[i] = Create(); }
GLuint Create() {
live.insert(next);
return next++;
}
void Generate(GLsizei count, GLuint* ids) {
for (Int i = 0; i < count; ++i)
ids[i] = Create();
}
void Delete(GLsizei count, const GLuint* ids) {
for (Int i = 0; i < count; ++i) {
live.erase(ids[i]);
@@ -84,13 +102,20 @@ namespace {
MG_External::GLESFunctionsTable Table() {
MG_External::GLESFunctionsTable gl{};
gl.glGetIntegerv = [](GLenum name, GLint* out) {
if (name == GL_MAJOR_VERSION) *out = 3;
else if (name == GL_MINOR_VERSION) *out = 2;
else if (name == GL_NUM_EXTENSIONS) *out = driver.extension ? 1 : 0;
else if (name == GL_VIEWPORT) std::copy(driver.viewport.begin(), driver.viewport.end(), out);
else if (name == GL_ARRAY_BUFFER_BINDING) *out = driver.Get(GL_ARRAY_BUFFER);
else if (name == GL_PIXEL_PACK_BUFFER_BINDING) *out = driver.Get(GL_PIXEL_PACK_BUFFER);
else *out = driver.Get(name);
if (name == GL_MAJOR_VERSION)
*out = 3;
else if (name == GL_MINOR_VERSION)
*out = 2;
else if (name == GL_NUM_EXTENSIONS)
*out = driver.extension ? 1 : 0;
else if (name == GL_VIEWPORT)
std::copy(driver.viewport.begin(), driver.viewport.end(), out);
else if (name == GL_ARRAY_BUFFER_BINDING)
*out = driver.Get(GL_ARRAY_BUFFER);
else if (name == GL_PIXEL_PACK_BUFFER_BINDING)
*out = driver.Get(GL_PIXEL_PACK_BUFFER);
else
*out = driver.Get(name);
};
gl.glGetBooleanv = [](GLenum, GLboolean* out) { std::copy(driver.mask.begin(), driver.mask.end(), out); };
gl.glGetFloatv = [](GLenum, GLfloat* out) { std::copy(driver.clear.begin(), driver.clear.end(), out); };
@@ -136,7 +161,8 @@ namespace {
if (buffer.arena) {
buffer.channel = FakeDriver::Channel(data);
buffer.copied = false;
} else std::memcpy(buffer.staging.data() + offset, data, size);
} else
std::memcpy(buffer.staging.data() + offset, data, size);
};
gl.glCopyBufferSubData = [](GLenum read, GLenum write, GLintptr offset, GLintptr, GLsizeiptr) {
auto& source = driver.buffers[driver.Get(read)];
@@ -173,8 +199,8 @@ namespace {
gl.glDrawArrays = [](GLenum, GLint, GLsizei) {
const GLuint id = driver.vaoBuffers.at(driver.Get(GL_VERTEX_ARRAY_BINDING));
const auto& buffer = driver.buffers.at(id);
const Bool late = buffer.mapped ? (buffer.copied ? driver.corruptCopy : driver.corruptSubData)
: driver.corruptUnmapped;
const Bool late =
buffer.mapped ? (buffer.copied ? driver.corruptCopy : driver.corruptSubData) : driver.corruptUnmapped;
driver.draws.push_back({GLuint(driver.Get(GL_DRAW_FRAMEBUFFER_BINDING)), id, buffer.channel, late});
};
gl.glFinish = []() { driver.Finish(); };
@@ -191,7 +217,8 @@ namespace {
const Int channel = driver.colors.at(driver.Get(GL_READ_FRAMEBUFFER_BINDING));
auto* pixels = static_cast<Uint8*>(data);
for (Int i = 0; i < width * height; ++i)
for (Int c = 0; c < 4; ++c) pixels[4 * i + c] = c == channel || c == 3 ? 255 : 0;
for (Int c = 0; c < 4; ++c)
pixels[4 * i + c] = c == channel || c == 3 ? 255 : 0;
};
return gl;
}
@@ -199,9 +226,12 @@ namespace {
class PersistentBufferOrderingProbeTest : public ::testing::Test {
protected:
void SetUp() override { driver = FakeDriver{}; }
void TearDown() override { EXPECT_TRUE(driver.live.empty()); EXPECT_TRUE(driver.draws.empty()); }
void TearDown() override {
EXPECT_TRUE(driver.live.empty());
EXPECT_TRUE(driver.draws.empty());
}
};
}
} // namespace
TEST_F(PersistentBufferOrderingProbeTest, RequiresExtensionAndCompleteDispatchBeforeAllocating) {
auto gl = Table();
@@ -282,7 +312,8 @@ TEST_F(PersistentBufferOrderingProbeTest, CorruptNeverMappedControlCannotAccuseP
TEST_F(PersistentBufferOrderingProbeTest, CorruptSerializedControlCannotConfirmOrderingDefect) {
driver.corruptSubData = driver.corruptCopy = driver.corruptSerialized = true;
const auto measurement = ProbePersistentBufferUpdateOrdering(Table());
for (const auto& row : measurement.uploads) EXPECT_GT(row.finishBoth.badFrames, 0u);
for (const auto& row : measurement.uploads)
EXPECT_GT(row.finishBoth.badFrames, 0u);
EXPECT_FALSE(DescribePersistentBufferOrderingBug(measurement));
}
@@ -40,8 +40,8 @@ using MobileGL::Bool;
using MobileGL::Uint32;
using MobileGL::Uint64;
using MobileGL::MG_Config::QuirkOverride;
using MobileGL::MG_Util::SelfTest::EvaluatePrimitivesGeneratedNoXfbVerdict;
using MobileGL::MG_Util::SelfTest::ChoosePrimitivesGeneratedReroute;
using MobileGL::MG_Util::SelfTest::EvaluatePrimitivesGeneratedNoXfbVerdict;
using MobileGL::MG_Util::SelfTest::PrimGenRerouteKind;
using MobileGL::MG_Util::SelfTest::PrimitivesGeneratedNoXfbMeasurement;
using MobileGL::MG_Util::SelfTest::PrimitivesGeneratedNoXfbProbeContext;
@@ -97,19 +97,16 @@ namespace {
// Controls agreeing changes nothing - health is decided by the subject.
TEST(PrimitivesGeneratedNoXfbVerdictTest, AConformingDriverReadsStreamCounts) {
const auto measurement = Measurement(Shape(kHealthy), Shape(kHealthy), Shape(kHealthy));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement),
PrimitivesGeneratedNoXfbVerdict::StreamCounts);
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement), PrimitivesGeneratedNoXfbVerdict::StreamCounts);
}
// ...and stays healthy with no tessellation stage to draw the patches shape with,
// and with no control at all - a control is only required to QUALIFY a
// substitute, never to certify health.
TEST(PrimitivesGeneratedNoXfbVerdictTest, HealthNeedsNeitherTessellationNorAControl) {
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(
Measurement(Shape(kHealthy), Shape(kHealthy), NotDrawn())),
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(Measurement(Shape(kHealthy), Shape(kHealthy), NotDrawn())),
PrimitivesGeneratedNoXfbVerdict::StreamCounts);
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(
Measurement(Shape({1}), Shape({1}), Shape({1}))),
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(Measurement(Shape({1}), Shape({1}), Shape({1}))),
PrimitivesGeneratedNoXfbVerdict::StreamCounts);
}
@@ -118,8 +115,7 @@ TEST(PrimitivesGeneratedNoXfbVerdictTest, HealthNeedsNeitherTessellationNorACont
// included), the statistics control dead under discard. The dedicated query must
// win - it is the only substitute that covers the CTS shape there.
TEST(PrimitivesGeneratedNoXfbVerdictTest, LavapipeShapedMeasurementTakesTheDedicatedQuery) {
const auto measurement =
Measurement(Shape(kLavapipePlain), Shape(kLavapipeDiscard), Shape(kLavapipeDiscard));
const auto measurement = Measurement(Shape(kLavapipePlain), Shape(kLavapipeDiscard), Shape(kLavapipeDiscard));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement),
PrimitivesGeneratedNoXfbVerdict::PrimitivesGeneratedExtSubstitute);
}
@@ -127,8 +123,8 @@ TEST(PrimitivesGeneratedNoXfbVerdictTest, LavapipeShapedMeasurementTakesTheDedic
// The affected-device hypothesis with no dedicated query: statistics exact on
// every shape, the CTS's discarded shapes included.
TEST(PrimitivesGeneratedNoXfbVerdictTest, StatisticsExactEverywhereIsTheFullStatisticsSubstitute) {
const auto measurement = Measurement(Shape({0, false, 0, true, 1}), Shape({0, false, 0, true, 1}),
Shape({0, false, 0, true, 1}));
const auto measurement =
Measurement(Shape({0, false, 0, true, 1}), Shape({0, false, 0, true, 1}), Shape({0, false, 0, true, 1}));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement),
PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitute);
}
@@ -136,8 +132,8 @@ TEST(PrimitivesGeneratedNoXfbVerdictTest, StatisticsExactEverywhereIsTheFullStat
// A dedicated query that is silent in the same way the stream query is must not
// be armed - the statistics tier decides instead.
TEST(PrimitivesGeneratedNoXfbVerdictTest, ASilentDedicatedQueryFallsThroughToStatistics) {
const auto measurement = Measurement(Shape({0, true, 0, true, 1}), Shape({0, true, 0, true, 1}),
Shape({0, true, 0, true, 1}));
const auto measurement =
Measurement(Shape({0, true, 0, true, 1}), Shape({0, true, 0, true, 1}), Shape({0, true, 0, true, 1}));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement),
PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitute);
}
@@ -146,8 +142,8 @@ TEST(PrimitivesGeneratedNoXfbVerdictTest, ASilentDedicatedQueryFallsThroughToSta
// the plain shape, dead under discard. Repairs undiscarded queries only, and the
// verdict must say so.
TEST(PrimitivesGeneratedNoXfbVerdictTest, StatisticsDeadUnderDiscardIsThePlainOnlySubstitute) {
const auto measurement = Measurement(Shape({0, false, 0, true, 1}), Shape({0, false, 0, true, 0}),
Shape({0, false, 0, true, 0}));
const auto measurement =
Measurement(Shape({0, false, 0, true, 1}), Shape({0, false, 0, true, 0}), Shape({0, false, 0, true, 0}));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement),
PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitutePlainOnly);
}
@@ -159,20 +155,18 @@ TEST(PrimitivesGeneratedNoXfbVerdictTest, StatisticsDeadUnderDiscardIsThePlainOn
// whose silence is selective) and whose statistics read 0 - rerouting would turn
// that correct 1 into a 0, so the honest verdict is that nothing may be armed.
TEST(PrimitivesGeneratedNoXfbVerdictTest, ASubstituteWorseThanTheStreamOnAnyShapeIsRefused) {
const auto measurement = Measurement(Shape({1, false, 0, true, 1}), Shape({1, false, 0, true, 0}),
Shape({0, false, 0, true, 0}));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement),
PrimitivesGeneratedNoXfbVerdict::Unfixable);
const auto measurement =
Measurement(Shape({1, false, 0, true, 1}), Shape({1, false, 0, true, 0}), Shape({0, false, 0, true, 0}));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement), PrimitivesGeneratedNoXfbVerdict::Unfixable);
// The same shape with the statistics slot MISSING on the stream-exact shape is
// the same trade: an unmeasured control cannot be assumed to answer.
const auto unmeasured = Measurement(Shape({1, false, 0, true, 1}), Shape({1, false, 0, false, 0}),
Shape({0, false, 0, true, 0}));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(unmeasured),
PrimitivesGeneratedNoXfbVerdict::Unfixable);
const auto unmeasured =
Measurement(Shape({1, false, 0, true, 1}), Shape({1, false, 0, false, 0}), Shape({0, false, 0, true, 0}));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(unmeasured), PrimitivesGeneratedNoXfbVerdict::Unfixable);
// ...while the same selective silence WITH a substitute that covers the shapes
// it must still qualifies: every shape the statistics miss read 0 anyway.
const auto dominating = Measurement(Shape({1, false, 0, true, 1}), Shape({0, false, 0, true, 1}),
Shape({0, false, 0, true, 0}));
const auto dominating =
Measurement(Shape({1, false, 0, true, 1}), Shape({0, false, 0, true, 1}), Shape({0, false, 0, true, 0}));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(dominating),
PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitutePlainOnly);
}
@@ -181,16 +175,13 @@ TEST(PrimitivesGeneratedNoXfbVerdictTest, ASubstituteWorseThanTheStreamOnAnyShap
// OVERCOUNTS the plain shape (as disqualifying as one that reads 0 - an exact
// match is what qualifies a substitute).
TEST(PrimitivesGeneratedNoXfbVerdictTest, StreamSilentWithoutAWorkingPlainControlIsUnfixable) {
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(
Measurement(Shape({0}), Shape({0}), Shape({0}))),
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(Measurement(Shape({0}), Shape({0}), Shape({0}))),
PrimitivesGeneratedNoXfbVerdict::Unfixable);
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(
Measurement(Shape({0, true, 0, true, 0}), Shape({0, true, 0, true, 0}),
Shape({0, true, 0, true, 0}))),
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(Measurement(
Shape({0, true, 0, true, 0}), Shape({0, true, 0, true, 0}), Shape({0, true, 0, true, 0}))),
PrimitivesGeneratedNoXfbVerdict::Unfixable);
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(
Measurement(Shape({0, true, 2, true, 2}), Shape({0, true, 1, true, 1}),
Shape({0, true, 1, true, 1}))),
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(Measurement(
Shape({0, true, 2, true, 2}), Shape({0, true, 1, true, 1}), Shape({0, true, 1, true, 1}))),
PrimitivesGeneratedNoXfbVerdict::Unfixable);
}
@@ -198,19 +189,16 @@ TEST(PrimitivesGeneratedNoXfbVerdictTest, StreamSilentWithoutAWorkingPlainContro
// defect (exact silence) nor health (the exact count), whichever shape carries
// it; and a probe that never ran, or lost its mandatory shapes, says nothing.
TEST(PrimitivesGeneratedNoXfbVerdictTest, AnswersFittingNeitherHealthNorTheDefectAreInconclusive) {
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(
Measurement(Shape({2, true, 1, true, 1}), Shape({0, true, 1, true, 1}),
Shape({0, true, 1, true, 1}))),
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(Measurement(
Shape({2, true, 1, true, 1}), Shape({0, true, 1, true, 1}), Shape({0, true, 1, true, 1}))),
PrimitivesGeneratedNoXfbVerdict::Inconclusive);
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(
Measurement(Shape({0, true, 1, true, 1}), Shape({3, true, 1, true, 1}),
Shape({0, true, 1, true, 1}))),
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(Measurement(
Shape({0, true, 1, true, 1}), Shape({3, true, 1, true, 1}), Shape({0, true, 1, true, 1}))),
PrimitivesGeneratedNoXfbVerdict::Inconclusive);
PrimitivesGeneratedNoXfbMeasurement neverRan;
neverRan.ran = false;
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(neverRan),
PrimitivesGeneratedNoXfbVerdict::Inconclusive);
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(neverRan), PrimitivesGeneratedNoXfbVerdict::Inconclusive);
const auto missingMandatoryShape = Measurement(Shape({0, true, 1, true, 1}), NotDrawn(), NotDrawn());
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(missingMandatoryShape),
@@ -221,8 +209,8 @@ TEST(PrimitivesGeneratedNoXfbVerdictTest, AnswersFittingNeitherHealthNorTheDefec
// ones read 0 (a driver that gates the stream counter on rasterization rather
// than on the capture). With a whole control the substitute is whole.
TEST(PrimitivesGeneratedNoXfbVerdictTest, SilenceOnOnlyTheDiscardShapesIsStillTheDefect) {
const auto measurement = Measurement(Shape({1, true, 1, true, 1}), Shape({0, true, 1, true, 1}),
Shape({0, true, 1, true, 1}));
const auto measurement =
Measurement(Shape({1, true, 1, true, 1}), Shape({0, true, 1, true, 1}), Shape({0, true, 1, true, 1}));
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement),
PrimitivesGeneratedNoXfbVerdict::PrimitivesGeneratedExtSubstitute);
}
@@ -242,14 +230,13 @@ namespace {
PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitutePlainOnly,
PrimitivesGeneratedNoXfbVerdict::Unfixable,
};
}
} // namespace
TEST(PrimitivesGeneratedNoXfbArmingTest, ForceOffNeverReroutes) {
for (const auto verdict : kAllVerdicts) {
for (const Bool pgqUsable : {false, true}) {
for (const Bool statsUsable : {false, true}) {
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(QuirkOverride::ForceOff, verdict, pgqUsable,
statsUsable),
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(QuirkOverride::ForceOff, verdict, pgqUsable, statsUsable),
PrimGenRerouteKind::None);
}
}
@@ -274,34 +261,30 @@ TEST(PrimitivesGeneratedNoXfbArmingTest, ForceOnBypassesTheVerdictButNeverTheStr
TEST(PrimitivesGeneratedNoXfbArmingTest, AutoFollowsExactlyTheSubstituteVerdicts) {
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(
QuirkOverride::Auto, PrimitivesGeneratedNoXfbVerdict::PrimitivesGeneratedExtSubstitute,
true, true),
QuirkOverride::Auto, PrimitivesGeneratedNoXfbVerdict::PrimitivesGeneratedExtSubstitute, true, true),
PrimGenRerouteKind::PrimitivesGeneratedExt);
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(
QuirkOverride::Auto, PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitute, false, true),
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(QuirkOverride::Auto,
PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitute, false, true),
PrimGenRerouteKind::ClippingStatistics);
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(
QuirkOverride::Auto, PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitutePlainOnly,
false, true),
QuirkOverride::Auto, PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitutePlainOnly, false, true),
PrimGenRerouteKind::ClippingStatistics);
// The statistics verdicts never take the dedicated pool: that verdict only
// exists when the dedicated query did NOT qualify.
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(
QuirkOverride::Auto, PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitute, true, true),
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(QuirkOverride::Auto,
PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitute, true, true),
PrimGenRerouteKind::ClippingStatistics);
for (const auto verdict :
{PrimitivesGeneratedNoXfbVerdict::Inconclusive, PrimitivesGeneratedNoXfbVerdict::StreamCounts,
PrimitivesGeneratedNoXfbVerdict::Unfixable}) {
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(QuirkOverride::Auto, verdict, true, true),
PrimGenRerouteKind::None);
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(QuirkOverride::Auto, verdict, true, true), PrimGenRerouteKind::None);
}
// The structural checks bind Auto too.
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(
QuirkOverride::Auto, PrimitivesGeneratedNoXfbVerdict::PrimitivesGeneratedExtSubstitute,
false, true),
QuirkOverride::Auto, PrimitivesGeneratedNoXfbVerdict::PrimitivesGeneratedExtSubstitute, false, true),
PrimGenRerouteKind::None);
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(
QuirkOverride::Auto, PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitute, false, false),
EXPECT_EQ(ChoosePrimitivesGeneratedReroute(QuirkOverride::Auto,
PrimitivesGeneratedNoXfbVerdict::StatisticsSubstitute, false, false),
PrimGenRerouteKind::None);
}
@@ -358,7 +341,9 @@ namespace {
VKAPI_ATTR VkResult VKAPI_CALL FakeBeginCommandBuffer(VkCommandBuffer, const VkCommandBufferBeginInfo*) {
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeEndCommandBuffer(VkCommandBuffer) { return VK_SUCCESS; }
VKAPI_ATTR VkResult VKAPI_CALL FakeEndCommandBuffer(VkCommandBuffer) {
return VK_SUCCESS;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateQueryPool(VkDevice, const VkQueryPoolCreateInfo*,
const VkAllocationCallbacks*, VkQueryPool* out) {
*out = FakeHandle<VkQueryPool>();
@@ -370,8 +355,8 @@ namespace {
VKAPI_ATTR void VKAPI_CALL FakeCmdResetQueryPool(VkCommandBuffer, VkQueryPool, uint32_t, uint32_t) {}
VKAPI_ATTR void VKAPI_CALL FakeCmdBeginQuery(VkCommandBuffer, VkQueryPool, uint32_t, VkQueryControlFlags) {}
VKAPI_ATTR void VKAPI_CALL FakeCmdEndQuery(VkCommandBuffer, VkQueryPool, uint32_t) {}
VKAPI_ATTR void VKAPI_CALL FakeCmdBeginQueryIndexedEXT(VkCommandBuffer, VkQueryPool, uint32_t,
VkQueryControlFlags, uint32_t) {}
VKAPI_ATTR void VKAPI_CALL FakeCmdBeginQueryIndexedEXT(VkCommandBuffer, VkQueryPool, uint32_t, VkQueryControlFlags,
uint32_t) {}
VKAPI_ATTR void VKAPI_CALL FakeCmdEndQueryIndexedEXT(VkCommandBuffer, VkQueryPool, uint32_t, uint32_t) {}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateRenderPass(VkDevice, const VkRenderPassCreateInfo*,
const VkAllocationCallbacks*, VkRenderPass* out) {
@@ -401,13 +386,11 @@ namespace {
++g_fake.destroyCalls;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreatePipelineLayout(VkDevice, const VkPipelineLayoutCreateInfo*,
const VkAllocationCallbacks*,
VkPipelineLayout* out) {
const VkAllocationCallbacks*, VkPipelineLayout* out) {
*out = FakeHandle<VkPipelineLayout>();
return VK_SUCCESS;
}
VKAPI_ATTR void VKAPI_CALL FakeDestroyPipelineLayout(VkDevice, VkPipelineLayout,
const VkAllocationCallbacks*) {
VKAPI_ATTR void VKAPI_CALL FakeDestroyPipelineLayout(VkDevice, VkPipelineLayout, const VkAllocationCallbacks*) {
++g_fake.destroyCalls;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateGraphicsPipelines(VkDevice, VkPipelineCache, uint32_t count,
@@ -423,8 +406,8 @@ namespace {
}
VKAPI_ATTR void VKAPI_CALL FakeCmdBindPipeline(VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}
VKAPI_ATTR void VKAPI_CALL FakeCmdDraw(VkCommandBuffer, uint32_t, uint32_t, uint32_t, uint32_t) {}
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateFence(VkDevice, const VkFenceCreateInfo*,
const VkAllocationCallbacks*, VkFence* out) {
VKAPI_ATTR VkResult VKAPI_CALL FakeCreateFence(VkDevice, const VkFenceCreateInfo*, const VkAllocationCallbacks*,
VkFence* out) {
*out = FakeHandle<VkFence>();
return VK_SUCCESS;
}
@@ -438,9 +421,8 @@ namespace {
VKAPI_ATTR VkResult VKAPI_CALL FakeWaitForFences(VkDevice, uint32_t, const VkFence*, VkBool32, uint64_t) {
return g_fake.fenceWaitResult;
}
VKAPI_ATTR VkResult VKAPI_CALL FakeGetQueryPoolResults(VkDevice, VkQueryPool, uint32_t, uint32_t,
size_t dataSize, void* data, VkDeviceSize,
VkQueryResultFlags) {
VKAPI_ATTR VkResult VKAPI_CALL FakeGetQueryPoolResults(VkDevice, VkQueryPool, uint32_t, uint32_t, size_t dataSize,
void* data, VkDeviceSize, VkQueryResultFlags) {
// The stream pool's {primitivesWritten, primitivesNeeded} pair; the probe
// reads primitivesNeeded, and this fake device counts capture-less draws.
if (data == nullptr || dataSize < 2 * sizeof(Uint64)) {
@@ -523,8 +505,7 @@ TEST(PrimitivesGeneratedNoXfbProbeTeardownTest, AFenceTimeoutLeaksEverythingAndR
<< "vkDeviceWaitIdle on a queue that missed a 5 s deadline is the hang the bound exists to "
"prevent";
// The verdict must not read a timed-out probe as anything but "no verdict".
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement),
PrimitivesGeneratedNoXfbVerdict::Inconclusive);
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement), PrimitivesGeneratedNoXfbVerdict::Inconclusive);
}
// The control: a driver that signals normally gets the ordinary teardown - idle
@@ -541,6 +522,5 @@ TEST(PrimitivesGeneratedNoXfbProbeTeardownTest, ASignalledFenceTearsDownNormally
EXPECT_FALSE(measurement.fenceWaitTimedOut);
EXPECT_EQ(g_fake.deviceWaitIdleCalls, 1u);
EXPECT_GT(g_fake.destroyCalls, 0u);
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement),
PrimitivesGeneratedNoXfbVerdict::StreamCounts);
EXPECT_EQ(EvaluatePrimitivesGeneratedNoXfbVerdict(measurement), PrimitivesGeneratedNoXfbVerdict::StreamCounts);
}
@@ -74,8 +74,7 @@ namespace {
EXPECT_TRUE(programResult) << (programResult ? String{} : programResult.error().log);
if (!programResult) return {};
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_FRAGMENT_SHADER},
.program = *programResult.value()};
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_FRAGMENT_SHADER}, .program = *programResult.value()};
auto binaryResult = ShaderCompiler::GetSpirvBinaryFromProgram(binaryAttrib);
EXPECT_TRUE(binaryResult) << (binaryResult ? String{} : binaryResult.error().log);
if (!binaryResult || binaryResult->empty()) return {};
@@ -275,9 +274,9 @@ TEST_F(ClampMultisampleFetchTest, LeavesAModuleWithoutAMultisampledImageUntouche
ASSERT_FALSE(input.empty());
Vector<Uint32> output;
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(
input, output, /*maxColorSamples=*/4, /*maxIntegerSamples=*/1, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true));
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(input, output, /*maxColorSamples=*/4,
/*maxIntegerSamples=*/1, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true));
EXPECT_EQ(output, input) << Disassemble(output);
}
@@ -299,9 +298,9 @@ TEST_F(ClampMultisampleFetchTest, ReplacesAnOutOfRangeIntegerSampleWithZero) {
EXPECT_EQ(constantsBefore.at(sampleBefore->maskOperandIds.front()), 3u);
Vector<Uint32> output;
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(
input, output, /*maxColorSamples=*/4, /*maxIntegerSamples=*/1, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true));
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(input, output, /*maxColorSamples=*/4,
/*maxIntegerSamples=*/1, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true));
ASSERT_FALSE(output.empty());
const String dis = Disassemble(output);
ASSERT_TRUE(Validates(output)) << dis;
@@ -335,9 +334,9 @@ TEST_F(ClampMultisampleFetchTest, LeavesTheFetchAloneWhenTheCategoryReachesTheAd
ASSERT_FALSE(input.empty());
Vector<Uint32> output;
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(
input, output, /*maxColorSamples=*/4, /*maxIntegerSamples=*/4, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true));
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(input, output, /*maxColorSamples=*/4,
/*maxIntegerSamples=*/4, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true));
EXPECT_EQ(output, input) << Disassemble(output);
}
@@ -353,9 +352,9 @@ TEST_F(ClampMultisampleFetchTest, ClampsAColorSampleWithAMinimum) {
const Uint32 originalSampleId = before.front().maskOperandIds.front();
Vector<Uint32> output;
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(
input, output, /*maxColorSamples=*/2, /*maxIntegerSamples=*/4, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true));
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(input, output, /*maxColorSamples=*/2,
/*maxIntegerSamples=*/4, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true));
ASSERT_FALSE(output.empty());
const String dis = Disassemble(output);
ASSERT_TRUE(Validates(output)) << dis;
@@ -422,8 +421,8 @@ TEST_F(ClampMultisampleFetchTest, DefersADirectUnsignedFetchToTheRuntimeBound) {
Vector<Uint32> output;
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(
input, output, /*maxColorSamples=*/4, /*maxIntegerSamples=*/1, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true, /*deferDirectUnsignedFetches=*/true));
input, output, /*maxColorSamples=*/4, /*maxIntegerSamples=*/1, /*maxDepthSamples=*/4, kAdvertisedMaxSamples,
true, /*deferDirectUnsignedFetches=*/true));
ASSERT_FALSE(output.empty());
const String dis = Disassemble(output);
ASSERT_TRUE(Validates(output)) << dis;
@@ -437,9 +436,9 @@ TEST_F(ClampMultisampleFetchTest, WithoutTheRuntimeBoundEveryIntegerFetchKeepsTh
ASSERT_FALSE(input.empty());
Vector<Uint32> output;
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(
input, output, /*maxColorSamples=*/4, /*maxIntegerSamples=*/1, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true));
ASSERT_TRUE(ShaderCompiler::ClampMultisampleFetchesForEssl(input, output, /*maxColorSamples=*/4,
/*maxIntegerSamples=*/1, /*maxDepthSamples=*/4,
kAdvertisedMaxSamples, true));
ASSERT_FALSE(output.empty());
const String dis = Disassemble(output);
EXPECT_EQ(CountSampleOperandsEqualTo(output, 3u), 0u) << dis;
@@ -64,7 +64,8 @@ namespace {
SizeT Count(const String& haystack, const String& needle) {
SizeT count = 0;
for (SizeT at = haystack.find(needle); at != String::npos; at = haystack.find(needle, at + 1)) ++count;
for (SizeT at = haystack.find(needle); at != String::npos; at = haystack.find(needle, at + 1))
++count;
return count;
}
@@ -91,7 +91,8 @@ namespace {
});
Vector<Uint32> offsets;
for (const auto& [member, offset] : offsetByMember) offsets.push_back(offset);
for (const auto& [member, offset] : offsetByMember)
offsets.push_back(offset);
return offsets;
}
@@ -206,8 +207,7 @@ void main() {
ASSERT_FALSE(input.empty());
// What glslang laid out for the 64-bit members, which is what an application computing
// std140 by hand would also get.
EXPECT_EQ(CollectOffsetsOf(input, "Blk"), (Vector<Uint32>{0, 8, 16, 32, 64, 96, 224, 272}))
<< Disassemble(input);
EXPECT_EQ(CollectOffsetsOf(input, "Blk"), (Vector<Uint32>{0, 8, 16, 32, 64, 96, 224, 272})) << Disassemble(input);
Vector<Uint32> output;
ASSERT_TRUE(ShaderCompiler::DemoteFloat64ToFloat32(input, output, true));
@@ -216,8 +216,7 @@ void main() {
// vec4 at 32, mat4 at 48 with a 16-byte column stride, the array at 112 with the std140
// 16-byte element stride, and the trailing float at 160. This is what SPIRV-Cross has to be
// able to re-derive for GLSL ES, which has no member layout(offset=) to fall back on.
EXPECT_EQ(CollectOffsetsOf(output, "Blk"), (Vector<Uint32>{0, 4, 8, 16, 32, 48, 112, 160}))
<< Disassemble(output);
EXPECT_EQ(CollectOffsetsOf(output, "Blk"), (Vector<Uint32>{0, 4, 8, 16, 32, 48, 112, 160})) << Disassemble(output);
const String text = Disassemble(output);
EXPECT_NE(text.find("MatrixStride 16"), String::npos) << text;
EXPECT_NE(text.find("ArrayStride 16"), String::npos) << text;
@@ -560,11 +559,10 @@ void main() {
// one of these before demotion, so the program simply could not be transpiled at all.
class DemoteFloat64EsslTest : public DemoteFloat64Test, public ::testing::WithParamInterface<const char*> {};
INSTANTIATE_TEST_SUITE_P(
Shapes, DemoteFloat64EsslTest,
::testing::Values(
// A double that never reaches an interface: locals and literals only.
R"(#version 460 core
INSTANTIATE_TEST_SUITE_P(Shapes, DemoteFloat64EsslTest,
::testing::Values(
// A double that never reaches an interface: locals and literals only.
R"(#version 460 core
layout(location = 0) out float vOut;
void main() {
double s = 0.5lf;
@@ -573,9 +571,9 @@ void main() {
gl_Position = vec4(float(s));
}
)",
// A default-block double uniform: the glUniform*d path, and the block MobileGL lays out
// itself.
R"(#version 460 core
// A default-block double uniform: the glUniform*d path, and the block MobileGL lays out
// itself.
R"(#version 460 core
layout(location = 0) uniform double uScale;
layout(location = 1) uniform dvec3 uOffset;
layout(location = 2) uniform dmat4 uTransform;
@@ -586,8 +584,8 @@ void main() {
gl_Position = vec4(float(p.x));
}
)",
// An application-declared std140 block whose members are 64-bit.
R"(#version 460 core
// An application-declared std140 block whose members are 64-bit.
R"(#version 460 core
layout(std140, binding = 0) uniform Blk {
float a;
double d;
@@ -605,8 +603,8 @@ void main() {
gl_Position = vec4(float(s));
}
)",
// A 64-bit vertex input, which is what glVertexAttribLFormat feeds.
R"(#version 460 core
// A 64-bit vertex input, which is what glVertexAttribLFormat feeds.
R"(#version 460 core
layout(location = 0) in dvec3 inPos;
layout(location = 2) in double inWeight;
layout(location = 0) out float vOut;
@@ -615,8 +613,8 @@ void main() {
gl_Position = vec4(vOut);
}
)",
// An std430 storage block, whose double members pack differently again.
R"(#version 460 core
// An std430 storage block, whose double members pack differently again.
R"(#version 460 core
layout(std430, binding = 0) buffer Ssbo {
double head;
dvec4 wide;
@@ -697,10 +695,14 @@ namespace {
return "#version 430 core\n"
"layout(local_size_x = 1) in;\n"
"buffer Result { int g_result; };\n"
"uniform " + type + " g_0;\n"
"uniform " +
type +
" g_0;\n"
"void main() {\n"
" g_result = 0;\n"
" if (g_0 " + op + " " + literal + ") g_result = 1;\n"
" if (g_0 " +
op + " " + literal +
") g_result = 1;\n"
"}\n";
}
@@ -720,7 +722,8 @@ namespace {
Vector<String> tokens;
StringStream words(line);
String word;
while (words >> word) tokens.push_back(word);
while (words >> word)
tokens.push_back(word);
instructions.push_back(tokens);
}
return instructions;
@@ -769,15 +772,13 @@ namespace {
const String& unorderedOpcode) {
const String disassembly = OptimizedDisassembly(source);
const Vector<String> compare = FindRewrittenCompare(disassembly);
ASSERT_FALSE(compare.empty()) << "no rewritten compare in the optimized module\n"
<< disassembly;
ASSERT_FALSE(compare.empty()) << "no rewritten compare in the optimized module\n" << disassembly;
EXPECT_TRUE(compare[2] == orderedOpcode || compare[2] == unorderedOpcode)
<< "expected " << orderedOpcode << " (or its unordered twin), got " << compare[2] << "\n"
<< disassembly;
const String zeroId = FindZeroConstantId(disassembly);
ASSERT_FALSE(zeroId.empty()) << "the module has no 0.0 constant of the abs() type\n"
<< disassembly;
ASSERT_FALSE(zeroId.empty()) << "the module has no 0.0 constant of the abs() type\n" << disassembly;
EXPECT_EQ(compare.back(), zeroId)
<< "the rewrite compares against " << compare.back()
<< " instead of the module's own zero; a synthesized threshold is the epsilon bug\n"
@@ -818,8 +819,8 @@ TEST_F(DemoteFloat64Test, AComparisonAgainstASmallNonZeroLiteralIsLeftAlone) {
TEST_F(DemoteFloat64Test, TheRewriteComparesAbsAgainstTheModulesOwnZero) {
// `x == 0.0` -> `abs(x) <= 0.0`. The equality has to be INSIDE the replacement: with a strict
// `<` and no epsilon left to hide behind, +/-0 would stop comparing equal to zero.
ExpectComparedAgainstModuleZero(CompareAgainstUsing("float", "==", "0.0"),
"OpFOrdLessThanEqual", "OpFUnordLessThanEqual");
ExpectComparedAgainstModuleZero(CompareAgainstUsing("float", "==", "0.0"), "OpFOrdLessThanEqual",
"OpFUnordLessThanEqual");
// `x != 0.0` -> `abs(x) > 0.0`, the strict complement of the above.
ExpectComparedAgainstModuleZero(CompareAgainstUsing("float", "!=", "0.0"), "OpFOrdGreaterThan",
"OpFUnordGreaterThan");
@@ -245,8 +245,8 @@ TEST_F(DemotePointSizeTest, DemotesAFiveStageProgramWholesale) {
{GL_GEOMETRY_SHADER, kGeometrySource},
{GL_FRAGMENT_SHADER, kFragmentSource}});
ASSERT_EQ(modules.size(), 5u);
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER,
GL_GEOMETRY_SHADER, GL_FRAGMENT_SHADER};
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_GEOMETRY_SHADER,
GL_FRAGMENT_SHADER};
// The defect, pinned first: every tessellation/geometry stage really does declare the
// capability the device lacks - the same probe production's declines use.
@@ -321,8 +321,8 @@ TEST_F(DemotePointSizeTest, DemotesAFiveStageProgramWholesale) {
// the same modules finds nothing to arm on and must not touch a byte.
Vector<Vector<Uint32>> again = modules;
ShaderCompiler::PointSizeDemotionOutcome secondOutcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
again, types, true, true, true, secondOutcome, true, true));
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(again, types, true, true, true,
secondOutcome, true, true));
EXPECT_FALSE(secondOutcome.demoted);
EXPECT_TRUE(secondOutcome.declineDetail.empty()) << secondOutcome.declineDetail;
EXPECT_EQ(again, modules);
@@ -334,19 +334,16 @@ TEST_F(DemotePointSizeTest, WithoutAGeometryStageTheEvaluationStageOwnsTheCaptur
{GL_TESS_EVALUATION_SHADER, kTessEvalSource},
{GL_FRAGMENT_SHADER, kFragmentSource}});
ASSERT_EQ(modules.size(), 4u);
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER,
GL_FRAGMENT_SHADER};
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_FRAGMENT_SHADER};
ShaderCompiler::PointSizeDemotionOutcome outcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
modules, types, true, true, true, outcome, true, true));
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(modules, types, true, true, true, outcome,
true, true));
EXPECT_TRUE(outcome.demoted) << outcome.declineDetail;
const String tes = Disassemble(modules[2]);
EXPECT_NE(tes.find("OpName %mg_PointSizeCapture"), String::npos) << tes;
EXPECT_NE(tes.find("OpStore %mg_PointSizeCapture"), String::npos) << tes;
EXPECT_EQ(tes.find("OpName %mg_PointSizeIo2"), String::npos)
<< "no geometry stage, no Io2 boundary:\n"
<< tes;
EXPECT_EQ(tes.find("OpName %mg_PointSizeIo2"), String::npos) << "no geometry stage, no Io2 boundary:\n" << tes;
}
TEST_F(DemotePointSizeTest, AGeometryOnlyProgramReadsTheVertexBoundary) {
@@ -367,8 +364,7 @@ void main() {
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_GEOMETRY_SHADER, GL_FRAGMENT_SHADER};
ShaderCompiler::PointSizeDemotionOutcome outcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
modules, types, /*demoteTessellation=*/false, /*demoteGeometry=*/true, false, outcome, true,
true));
modules, types, /*demoteTessellation=*/false, /*demoteGeometry=*/true, false, outcome, true, true));
EXPECT_TRUE(outcome.demoted) << outcome.declineDetail;
const String gs = Disassemble(modules[1]);
@@ -406,14 +402,13 @@ in vec4 g_color;
layout(location = 0) out vec4 fragColor;
void main() { fragColor = g_color; }
)";
Vector<Vector<Uint32>> modules = CompileProgramToSpirv({{GL_VERTEX_SHADER, vsWithVarying},
{GL_GEOMETRY_SHADER, gsWithVarying},
{GL_FRAGMENT_SHADER, fsWithVarying}});
Vector<Vector<Uint32>> modules = CompileProgramToSpirv(
{{GL_VERTEX_SHADER, vsWithVarying}, {GL_GEOMETRY_SHADER, gsWithVarying}, {GL_FRAGMENT_SHADER, fsWithVarying}});
ASSERT_EQ(modules.size(), 3u);
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_GEOMETRY_SHADER, GL_FRAGMENT_SHADER};
ShaderCompiler::PointSizeDemotionOutcome outcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
modules, types, false, true, true, outcome, true, true));
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(modules, types, false, true, true,
outcome, true, true));
EXPECT_TRUE(outcome.demoted) << outcome.declineDetail;
// v_color / g_color occupy location 0, so every carrier must sit at 1 - in every stage,
@@ -426,18 +421,16 @@ void main() { fragColor = g_color; }
}
TEST_F(DemotePointSizeTest, APointSizeFreeProgramStaysByteIdentical) {
Vector<Vector<Uint32>> modules =
CompileProgramToSpirv({{GL_VERTEX_SHADER, kPlainVertexSource},
{GL_TESS_CONTROL_SHADER, kPlainTessControlSource},
{GL_TESS_EVALUATION_SHADER, kPlainTessEvalSource},
{GL_FRAGMENT_SHADER, kFragmentSource}});
Vector<Vector<Uint32>> modules = CompileProgramToSpirv({{GL_VERTEX_SHADER, kPlainVertexSource},
{GL_TESS_CONTROL_SHADER, kPlainTessControlSource},
{GL_TESS_EVALUATION_SHADER, kPlainTessEvalSource},
{GL_FRAGMENT_SHADER, kFragmentSource}});
ASSERT_EQ(modules.size(), 4u);
const Vector<Vector<Uint32>> before = modules;
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER,
GL_FRAGMENT_SHADER};
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_FRAGMENT_SHADER};
ShaderCompiler::PointSizeDemotionOutcome outcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
modules, types, true, true, false, outcome, true, true));
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(modules, types, true, true, false,
outcome, true, true));
EXPECT_FALSE(outcome.demoted);
EXPECT_TRUE(outcome.declineDetail.empty()) << outcome.declineDetail;
EXPECT_EQ(modules, before);
@@ -450,12 +443,11 @@ TEST_F(DemotePointSizeTest, AHostingDeviceStaysByteIdentical) {
{GL_FRAGMENT_SHADER, kFragmentSource}});
ASSERT_EQ(modules.size(), 4u);
const Vector<Vector<Uint32>> before = modules;
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER,
GL_FRAGMENT_SHADER};
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_FRAGMENT_SHADER};
ShaderCompiler::PointSizeDemotionOutcome outcome;
// Both verdicts say the device hosts the built-in: the un-forced lane's contract.
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
modules, types, false, false, true, outcome, true, true));
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(modules, types, false, false, true,
outcome, true, true));
EXPECT_FALSE(outcome.demoted);
EXPECT_EQ(modules, before);
EXPECT_TRUE(ShaderCompiler::ModuleDeclaresTessellationOrGeometryPointSize(modules[1]))
@@ -466,14 +458,12 @@ TEST_F(DemotePointSizeTest, ACaptureRequestForcesTheCarrierOnANonWritingCaptureS
// The control stage writes point size (arming the demotion); the evaluation stage never
// does - but a by-name capture must still find the carrier declared there, holding
// whatever an unwritten varying holds, exactly as the unwritten built-in would have.
Vector<Vector<Uint32>> modules =
CompileProgramToSpirv({{GL_VERTEX_SHADER, kVertexSource},
{GL_TESS_CONTROL_SHADER, kTessControlSource},
{GL_TESS_EVALUATION_SHADER, kPlainTessEvalSource},
{GL_FRAGMENT_SHADER, kFragmentSource}});
Vector<Vector<Uint32>> modules = CompileProgramToSpirv({{GL_VERTEX_SHADER, kVertexSource},
{GL_TESS_CONTROL_SHADER, kTessControlSource},
{GL_TESS_EVALUATION_SHADER, kPlainTessEvalSource},
{GL_FRAGMENT_SHADER, kFragmentSource}});
ASSERT_EQ(modules.size(), 4u);
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER,
GL_FRAGMENT_SHADER};
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_FRAGMENT_SHADER};
ShaderCompiler::PointSizeDemotionOutcome outcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
modules, types, true, true, /*captureRequestsPointSize=*/true, outcome, true, true));
@@ -552,8 +542,7 @@ void main() { fragColor = vec4(g_echo); }
ASSERT_EQ(unrequested.size(), 3u);
ShaderCompiler::PointSizeDemotionOutcome unrequestedOutcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
unrequested, types, false, true, /*captureRequestsPointSize=*/false, unrequestedOutcome, true,
true));
unrequested, types, false, true, /*captureRequestsPointSize=*/false, unrequestedOutcome, true, true));
EXPECT_TRUE(unrequestedOutcome.demoted) << unrequestedOutcome.declineDetail;
EXPECT_EQ(Disassemble(unrequested[1]).find("OpName %mg_PointSizeCapture"), String::npos)
<< "with no capture asking for it, the carrier must not be declared";
@@ -592,18 +581,16 @@ TEST_F(DemotePointSizeTest, ARedeclaredControlBlockPrintsAnUnaccessedPointSizeMe
// driver still rejects is strictly worse than the honest refusal, because it also flips the
// program-wide verdict and the L1 key.
TEST_F(DemotePointSizeTest, AControlStageCarryingClipDistanceDeclinesTheProgram) {
Vector<Vector<Uint32>> modules =
CompileProgramToSpirv({{GL_VERTEX_SHADER, kVertexSource},
{GL_TESS_CONTROL_SHADER, kClipDistanceTessControlSource},
{GL_TESS_EVALUATION_SHADER, kTessEvalSource},
{GL_FRAGMENT_SHADER, kFragmentSource}});
Vector<Vector<Uint32>> modules = CompileProgramToSpirv({{GL_VERTEX_SHADER, kVertexSource},
{GL_TESS_CONTROL_SHADER, kClipDistanceTessControlSource},
{GL_TESS_EVALUATION_SHADER, kTessEvalSource},
{GL_FRAGMENT_SHADER, kFragmentSource}});
ASSERT_EQ(modules.size(), 4u);
const Vector<Vector<Uint32>> before = modules;
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER,
GL_FRAGMENT_SHADER};
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_CONTROL_SHADER, GL_TESS_EVALUATION_SHADER, GL_FRAGMENT_SHADER};
ShaderCompiler::PointSizeDemotionOutcome outcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
modules, types, true, true, true, outcome, true, true));
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(modules, types, true, true, true, outcome,
true, true));
EXPECT_FALSE(outcome.demoted);
EXPECT_NE(outcome.declineDetail.find("clip/cull"), String::npos) << outcome.declineDetail;
EXPECT_EQ(modules, before) << "a decline must leave every module byte-identical";
@@ -625,16 +612,15 @@ void main() {
gl_PointSize = gl_in[0].gl_PointSize + 1.0;
}
)";
Vector<Vector<Uint32>> modules =
CompileProgramToSpirv({{GL_VERTEX_SHADER, kVertexSource},
{GL_TESS_EVALUATION_SHADER, readingTessEval},
{GL_FRAGMENT_SHADER, kFragmentSource}});
Vector<Vector<Uint32>> modules = CompileProgramToSpirv({{GL_VERTEX_SHADER, kVertexSource},
{GL_TESS_EVALUATION_SHADER, readingTessEval},
{GL_FRAGMENT_SHADER, kFragmentSource}});
ASSERT_EQ(modules.size(), 3u);
const Vector<Vector<Uint32>> before = modules;
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_TESS_EVALUATION_SHADER, GL_FRAGMENT_SHADER};
ShaderCompiler::PointSizeDemotionOutcome outcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
modules, types, true, true, true, outcome, true, true));
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(modules, types, true, true, true, outcome,
true, true));
EXPECT_FALSE(outcome.demoted);
EXPECT_NE(outcome.declineDetail.find("control stage"), String::npos) << outcome.declineDetail;
EXPECT_EQ(modules, before) << "a decline must leave every module byte-identical";
@@ -680,14 +666,13 @@ layout(location = 0) flat in i64vec4 g_wide;
layout(location = 0) out vec4 fragColor;
void main() { fragColor = vec4(float(g_wide.x)); }
)";
Vector<Vector<Uint32>> modules = CompileProgramToSpirv({{GL_VERTEX_SHADER, wideVertex},
{GL_GEOMETRY_SHADER, wideGeometry},
{GL_FRAGMENT_SHADER, wideFragment}});
Vector<Vector<Uint32>> modules = CompileProgramToSpirv(
{{GL_VERTEX_SHADER, wideVertex}, {GL_GEOMETRY_SHADER, wideGeometry}, {GL_FRAGMENT_SHADER, wideFragment}});
ASSERT_EQ(modules.size(), 3u);
const Vector<GLenum> types{GL_VERTEX_SHADER, GL_GEOMETRY_SHADER, GL_FRAGMENT_SHADER};
ShaderCompiler::PointSizeDemotionOutcome outcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
modules, types, false, true, true, outcome, true, true));
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(modules, types, false, true, true,
outcome, true, true));
EXPECT_TRUE(outcome.demoted) << outcome.declineDetail;
// v_wide / g_wide sit at location 0 and occupy 0 AND 1, so every carrier must clear 2.
@@ -709,11 +694,10 @@ TEST_F(DemotePointSizeTest, AWholeStructCopyDeclinesTheProgramByteIdentically) {
Vector<Vector<Uint32>> modules{module};
const Vector<GLenum> types{GL_TESS_EVALUATION_SHADER};
ShaderCompiler::PointSizeDemotionOutcome outcome;
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(
modules, types, true, true, false, outcome, true, true));
ASSERT_TRUE(ShaderCompiler::DemoteTessellationGeometryPointSizeForProgram(modules, types, true, true, false,
outcome, true, true));
EXPECT_FALSE(outcome.demoted);
EXPECT_FALSE(outcome.declineDetail.empty())
<< "a shape the pass cannot express must say so, not silently no-op";
EXPECT_FALSE(outcome.declineDetail.empty()) << "a shape the pass cannot express must say so, not silently no-op";
EXPECT_EQ(modules[0], module) << "a decline must not leave a half-demoted module behind";
EXPECT_TRUE(ShaderCompiler::ModuleDeclaresTessellationOrGeometryPointSize(modules[0]))
<< "the declined module must still arm the existing honest refusals";
@@ -68,8 +68,7 @@ namespace {
ForEachInstruction(spirv, [&](spv::Op opcode, const Uint32* words, Uint32 wordCount) {
if (opcode != spv::Op::OpCapability || wordCount < 2u) return;
const auto capability = static_cast<spv::Capability>(words[1]);
if (capability >= spv::Capability::GroupNonUniform &&
capability <= spv::Capability::GroupNonUniformQuad) {
if (capability >= spv::Capability::GroupNonUniform && capability <= spv::Capability::GroupNonUniformQuad) {
++count;
}
});
@@ -97,10 +96,10 @@ namespace {
bool Validates(const Vector<Uint32>& spirv) {
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
tools.SetMessageConsumer([](spv_message_level_t, const char*, const spv_position_t& position,
const char* message) {
ADD_FAILURE() << "spirv-val at word " << position.index << ": " << message;
});
tools.SetMessageConsumer(
[](spv_message_level_t, const char*, const spv_position_t& position, const char* message) {
ADD_FAILURE() << "spirv-val at word " << position.index << ": " << message;
});
return tools.Validate(spirv);
}
@@ -59,10 +59,10 @@ namespace {
// The declared lengths of every Workgroup-storage array variable, sorted.
std::vector<Uint32> WorkgroupArrayLengths(const Vector<Uint32>& spirv) {
std::map<Uint32, Uint32> constantValues; // constant id -> value
std::map<Uint32, Uint32> arrayLengthIds; // array type id -> length constant id
std::map<Uint32, Uint32> pointerPointees; // pointer type id -> pointee type id
std::vector<Uint32> workgroupPointerTypes; // type ids of Workgroup variables
std::map<Uint32, Uint32> constantValues; // constant id -> value
std::map<Uint32, Uint32> arrayLengthIds; // array type id -> length constant id
std::map<Uint32, Uint32> pointerPointees; // pointer type id -> pointee type id
std::vector<Uint32> workgroupPointerTypes; // type ids of Workgroup variables
ForEachInstruction(spirv, [&](spv::Op opcode, const Uint32* words, Uint32 wordCount) {
switch (opcode) {
case spv::Op::OpConstant:
@@ -72,14 +72,12 @@ namespace {
if (wordCount >= 4u) arrayLengthIds[words[1]] = words[3];
break;
case spv::Op::OpTypePointer:
if (wordCount >= 4u &&
static_cast<spv::StorageClass>(words[2]) == spv::StorageClass::Workgroup) {
if (wordCount >= 4u && static_cast<spv::StorageClass>(words[2]) == spv::StorageClass::Workgroup) {
pointerPointees[words[1]] = words[3];
}
break;
case spv::Op::OpVariable:
if (wordCount >= 4u &&
static_cast<spv::StorageClass>(words[3]) == spv::StorageClass::Workgroup) {
if (wordCount >= 4u && static_cast<spv::StorageClass>(words[3]) == spv::StorageClass::Workgroup) {
workgroupPointerTypes.push_back(words[1]);
}
break;
@@ -102,10 +100,10 @@ namespace {
bool Validates(const Vector<Uint32>& spirv) {
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
tools.SetMessageConsumer([](spv_message_level_t, const char*, const spv_position_t& position,
const char* message) {
ADD_FAILURE() << "spirv-val at word " << position.index << ": " << message;
});
tools.SetMessageConsumer(
[](spv_message_level_t, const char*, const spv_position_t& position, const char* message) {
ADD_FAILURE() << "spirv-val at word " << position.index << ": " << message;
});
return tools.Validate(spirv);
}
@@ -282,16 +280,16 @@ TEST(FixIterationRPSubgroupScratchPass, LeavesPackWidthAssumptionsAloneOnWideDev
ASSERT_FALSE(input.empty());
for (const Uint32 nativeSize : {16u, 32u, 64u, 128u}) {
Vector<Uint32> output;
ASSERT_TRUE(ShaderCompiler::FixIterationRPSubgroupScratchForVulkan(
input, output, nativeSize, 32768u, true));
ASSERT_TRUE(
ShaderCompiler::FixIterationRPSubgroupScratchForVulkan(input, output, nativeSize, 32768u, true));
EXPECT_EQ(output, input) << "native width " << nativeSize;
}
}
}
TEST(FixIterationRPSubgroupScratchPass, RefusesAModuleOutsideTheIdiom) {
for (const char* source : {kInvocationIndexedSource, kNonFloatScratchSource,
kSubgroupFreeSource, kMaskedSubgroupIndexSource}) {
for (const char* source :
{kInvocationIndexedSource, kNonFloatScratchSource, kSubgroupFreeSource, kMaskedSubgroupIndexSource}) {
const Vector<Uint32> input = CompileCompute(source);
ASSERT_FALSE(input.empty());
Vector<Uint32> output;
@@ -309,8 +307,7 @@ TEST(FixIterationRPSubgroupScratchPass, LeavesEveryModuleAloneAtThePacksAssumedW
ASSERT_FALSE(input.empty());
for (const Uint32 nativeSize : {16u, 32u, 64u}) {
Vector<Uint32> output;
ASSERT_TRUE(ShaderCompiler::FixIterationRPSubgroupScratchForVulkan(
input, output, nativeSize, 32768u, true));
ASSERT_TRUE(ShaderCompiler::FixIterationRPSubgroupScratchForVulkan(input, output, nativeSize, 32768u, true));
EXPECT_EQ(output, input) << "native width " << nativeSize;
}
}
@@ -158,21 +158,21 @@ void main() {
}
)";
// glslang emits constants in FIRST-USE order, so a shader that does not use the flattened
// array's length until after it has declared the counter block leaves that constant BELOW the
// block. The pass needs the length to build `uint[length]` immediately before the block (SPIR-V
// forbids forward type references), and it used to decline the whole block in that case - which
// left the offsets in place and made SPIRV-Cross refuse the stage outright:
//
// Push constant block cannot be expressed as neither std430 nor std140.
//
// That is KHR-GL43.compute_shader.pipeline-compute-chain: its first kernel declares two counters
// at offset 8 (so the flattened array is 4 elements) and first uses the value 4 after the block,
// so the kernel never reached the driver and every buffer, image and counter it writes kept its
// initial value. Here `i < 4u` is what puts `uint 4` below the block; the ordering assertion
// below is the fixture's own latch, so a future glslang that emits constants differently reports
// a stale fixture rather than silently testing nothing.
constexpr const char* kLateLengthConstantCounters = R"(#version 430 core
// glslang emits constants in FIRST-USE order, so a shader that does not use the flattened
// array's length until after it has declared the counter block leaves that constant BELOW the
// block. The pass needs the length to build `uint[length]` immediately before the block (SPIR-V
// forbids forward type references), and it used to decline the whole block in that case - which
// left the offsets in place and made SPIRV-Cross refuse the stage outright:
//
// Push constant block cannot be expressed as neither std430 nor std140.
//
// That is KHR-GL43.compute_shader.pipeline-compute-chain: its first kernel declares two counters
// at offset 8 (so the flattened array is 4 elements) and first uses the value 4 after the block,
// so the kernel never reached the driver and every buffer, image and counter it writes kept its
// initial value. Here `i < 4u` is what puts `uint 4` below the block; the ordering assertion
// below is the fixture's own latch, so a future glslang that emits constants differently reports
// a stale fixture rather than silently testing nothing.
constexpr const char* kLateLengthConstantCounters = R"(#version 430 core
layout(local_size_x = 1) in;
layout(binding = 1, offset = 8) uniform atomic_uint g_counter[2];
layout(std430, binding = 0) buffer Output { uint value[]; } g_out;
@@ -182,27 +182,26 @@ void main() {
}
)";
// Index of the first OpConstant of type uint with value |value|, and of struct |structId|, in
// the module's instruction order. -1 when absent.
std::pair<Int64, Int64> UintConstantAndStructOrder(const Vector<Uint32>& spirv, Uint32 structId,
Uint32 value) {
Int64 index = 0, constantIndex = -1, structIndex = -1;
Uint32 uintTypeId = 0;
ForEachInstruction(spirv, [&](spv::Op opcode, const Uint32* words, Uint32 wordCount) {
if (opcode == spv::Op::OpTypeInt && wordCount >= 4u && words[2] == 32u && words[3] == 0u) {
uintTypeId = words[1];
}
if (opcode == spv::Op::OpConstant && wordCount >= 4u && words[1] == uintTypeId &&
words[3] == value && constantIndex < 0) {
constantIndex = index;
}
if (opcode == spv::Op::OpTypeStruct && wordCount >= 2u && words[1] == structId) {
structIndex = index;
}
++index;
});
return {constantIndex, structIndex};
}
// Index of the first OpConstant of type uint with value |value|, and of struct |structId|, in
// the module's instruction order. -1 when absent.
std::pair<Int64, Int64> UintConstantAndStructOrder(const Vector<Uint32>& spirv, Uint32 structId, Uint32 value) {
Int64 index = 0, constantIndex = -1, structIndex = -1;
Uint32 uintTypeId = 0;
ForEachInstruction(spirv, [&](spv::Op opcode, const Uint32* words, Uint32 wordCount) {
if (opcode == spv::Op::OpTypeInt && wordCount >= 4u && words[2] == 32u && words[3] == 0u) {
uintTypeId = words[1];
}
if (opcode == spv::Op::OpConstant && wordCount >= 4u && words[1] == uintTypeId && words[3] == value &&
constantIndex < 0) {
constantIndex = index;
}
if (opcode == spv::Op::OpTypeStruct && wordCount >= 2u && words[1] == structId) {
structIndex = index;
}
++index;
});
return {constantIndex, structIndex};
}
} // namespace
@@ -296,8 +295,7 @@ TEST(FlattenAtomicCounterBlockPass, FlattensWhenTheLengthConstantIsDeclaredAfter
EXPECT_TRUE(Validates(output));
// The symptom the CTS case actually failed on: with the block declined this throws.
MG_Util::ShaderTranspiler::SpvcSession session(
output, MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
MG_Util::ShaderTranspiler::SpvcSession session(output, MG_Util::ShaderTranspiler::SessionUsageBit::Transpile);
auto essl = ShaderCompiler::DecompileShader(session);
EXPECT_TRUE(essl) << "ESSL transpile failed: " << (essl ? String{} : essl.error().log);
}
@@ -75,7 +75,8 @@ namespace {
Vector<Uint32> members;
ForEachInstruction(spirv, [&](Uint32 opcode, const Uint32* words, Uint32 wordCount) {
if (opcode != kOpTypeStruct || wordCount < 2 || words[1] != structId) return;
for (Uint32 i = 2; i < wordCount; ++i) members.push_back(words[i]);
for (Uint32 i = 2; i < wordCount; ++i)
members.push_back(words[i]);
});
return members;
}
@@ -88,7 +89,8 @@ namespace {
byMember[words[2]] = words[4];
});
Vector<Uint32> offsets;
for (const auto& [member, offset] : byMember) offsets.push_back(offset);
for (const auto& [member, offset] : byMember)
offsets.push_back(offset);
return offsets;
}
@@ -284,8 +286,7 @@ TEST_F(FlattenFloat64StorageBlockTest, AStorageBlockWithDoublesBecomesOneWordArr
// Before: seven members, at the std140 offsets the standard requires WITH the doubles.
const Uint32 inputStructId = StructIdNamed(input, "Wide");
ASSERT_NE(inputStructId, 0u) << Disassemble(input);
EXPECT_EQ(MemberOffsetsOf(input, inputStructId),
(Vector<Uint32>{0, 16, 64, 112, 128, 160, 192}))
EXPECT_EQ(MemberOffsetsOf(input, inputStructId), (Vector<Uint32>{0, 16, 64, 112, 128, 160, 192}))
<< Disassemble(input);
const Vector<Uint32> output = Sanitize(input);
@@ -294,8 +295,7 @@ TEST_F(FlattenFloat64StorageBlockTest, AStorageBlockWithDoublesBecomesOneWordArr
const Uint32 structId = StructIdNamed(output, "Wide");
ASSERT_NE(structId, 0u) << Disassemble(output);
const Vector<Uint32> members = MemberTypesOf(output, structId);
ASSERT_EQ(members.size(), 1u) << "the block should have collapsed to one member\n"
<< Disassemble(output);
ASSERT_EQ(members.size(), 1u) << "the block should have collapsed to one member\n" << Disassemble(output);
EXPECT_EQ(MemberOffsetsOf(output, structId), (Vector<Uint32>{0}));
const auto [elementTypeId, length] = ArrayShapeOf(output, members[0]);
@@ -336,8 +336,7 @@ void main() {
const Uint32 structId = StructIdNamed(output, "Plain");
ASSERT_NE(structId, 0u) << Disassemble(output);
EXPECT_EQ(MemberTypesOf(output, structId).size(), 4u) << Disassemble(output);
EXPECT_EQ(MemberOffsetsOf(output, structId), (Vector<Uint32>{0, 16, 64, 112}))
<< Disassemble(output);
EXPECT_EQ(MemberOffsetsOf(output, structId), (Vector<Uint32>{0, 16, 64, 112})) << Disassemble(output);
}
// A plain UNIFORM block is deliberately NOT flattened, however many doubles it holds: the
@@ -366,9 +365,8 @@ void main() {
const Uint32 structId = StructIdNamed(output, "Params");
ASSERT_NE(structId, 0u) << Disassemble(output);
EXPECT_EQ(MemberTypesOf(output, structId).size(), 3u)
<< "a uniform block must not be flattened\n"
<< Disassemble(output);
EXPECT_EQ(MemberTypesOf(output, structId).size(), 3u) << "a uniform block must not be flattened\n"
<< Disassemble(output);
// The demotion's re-derived std140 layout for `int, float, int`, which is what the frontend
// reflects and what glUniform*d then writes into.
EXPECT_EQ(MemberOffsetsOf(output, structId), (Vector<Uint32>{0, 4, 8})) << Disassemble(output);
@@ -689,8 +687,7 @@ void main() {
const Vector<Uint32> input = CompileToSpirv(GL_COMPUTE_SHADER, source);
ASSERT_FALSE(input.empty());
// The premise: glslang really did mark the member row-major.
EXPECT_EQ(CountLinesWith(Disassemble(input), "OpMemberDecorate %Data 0 RowMajor", ""), 1u)
<< Disassemble(input);
EXPECT_EQ(CountLinesWith(Disassemble(input), "OpMemberDecorate %Data 0 RowMajor", ""), 1u) << Disassemble(input);
const Vector<Uint32> output = Sanitize(input);
ASSERT_FALSE(output.empty());
@@ -703,9 +700,7 @@ void main() {
EXPECT_NE(DecorationValueOf(output, members[0], kDecorationArrayStride), 4u)
<< "a row-major matrix element must not have been flattened into words\n"
<< text;
EXPECT_EQ(CountLinesWith(text, "OpIMul %uint", ""), 0u)
<< "nothing should have been re-addressed\n"
<< text;
EXPECT_EQ(CountLinesWith(text, "OpIMul %uint", ""), 0u) << "nothing should have been re-addressed\n" << text;
}
TEST_F(FlattenFloat64StorageBlockTest, AColumnMajorMatrixRuntimeArrayStepsByItsColumnStride) {
@@ -805,15 +800,11 @@ TEST_F(FlattenFloat64StorageBlockTest, TheNativePathLeavesAnOpenEndedBlockAndIts
ASSERT_NE(structId, 0u) << text;
const Vector<Uint32> members = MemberTypesOf(output, structId);
ASSERT_EQ(members.size(), 1u) << text;
EXPECT_NE(RuntimeArrayElementOf(output, members[0]), 0u)
<< "the member should still be a runtime array\n"
<< text;
EXPECT_NE(RuntimeArrayElementOf(output, members[0]), 0u) << "the member should still be a runtime array\n" << text;
EXPECT_EQ(DecorationValueOf(output, members[0], kDecorationArrayStride), 8u)
<< "the array must keep the 8-byte stride the application bound\n"
<< text;
EXPECT_GT(CountFloatTypesOfWidth(output, 64), 0u)
<< "nothing narrows here, so the doubles must survive\n"
<< text;
EXPECT_GT(CountFloatTypesOfWidth(output, 64), 0u) << "nothing narrows here, so the doubles must survive\n" << text;
}
// The other backend prints the flattened module through SPIRV-Cross: an open-ended `uint[]`
@@ -980,9 +971,7 @@ TEST_F(FlattenFloat64StorageBlockTest, ARuntimeArrayThatIsNotTheBlocksLastMember
ASSERT_NE(structId, 0u) << text;
EXPECT_EQ(MemberTypesOf(output, structId).size(), 2u) << text;
EXPECT_EQ(CountFloatTypesOfWidth(output, 64), 0u) << text;
EXPECT_EQ(CountLinesWith(text, "OpIMul %uint", ""), 0u)
<< "nothing should have been re-addressed\n"
<< text;
EXPECT_EQ(CountLinesWith(text, "OpIMul %uint", ""), 0u) << "nothing should have been re-addressed\n" << text;
}
}
@@ -1036,8 +1025,7 @@ void main() {
ASSERT_NE(inputStructId, 0u);
const Uint32 inputUintId = Uint32TypeIdOf(input);
// The premise: the module's uint really is declared after the block (or not at all).
ASSERT_TRUE(inputUintId == 0 ||
DeclarationIndexOf(input, inputUintId) > DeclarationIndexOf(input, inputStructId))
ASSERT_TRUE(inputUintId == 0 || DeclarationIndexOf(input, inputUintId) > DeclarationIndexOf(input, inputStructId))
<< "this shader was meant to declare the block before any uint\n"
<< Disassemble(input);
@@ -1074,8 +1062,7 @@ void main() {
const Uint32 inputStructId = StructIdNamed(input, "Wide");
ASSERT_NE(inputStructId, 0u);
const Uint32 inputUintId = Uint32TypeIdOf(input);
ASSERT_TRUE(inputUintId == 0 ||
DeclarationIndexOf(input, inputUintId) > DeclarationIndexOf(input, inputStructId))
ASSERT_TRUE(inputUintId == 0 || DeclarationIndexOf(input, inputUintId) > DeclarationIndexOf(input, inputStructId))
<< "this shader was meant to declare the block before any uint\n"
<< Disassemble(input);
@@ -1087,7 +1074,5 @@ void main() {
EXPECT_EQ(MemberTypesOf(output, structId).size(), 2u)
<< "a bounded block in this position must keep the decline it shipped with\n"
<< text;
EXPECT_EQ(CountLinesWith(text, "OpIMul %uint", ""), 0u)
<< "nothing should have been re-addressed\n"
<< text;
EXPECT_EQ(CountLinesWith(text, "OpIMul %uint", ""), 0u) << "nothing should have been re-addressed\n" << text;
}
@@ -148,9 +148,8 @@ TEST_F(FlattenXfbInterfaceBlocksTest, TheEmittedDeclarationIsAPlainArrayNotABloc
const String after = Transpile(output);
EXPECT_NE(after.find("StageData_attrib[16]"), String::npos) << after;
EXPECT_EQ(after.find("out StageData"), String::npos)
<< "the block must not still be declared as an output block:\n"
<< after;
EXPECT_EQ(after.find("out StageData"), String::npos) << "the block must not still be declared as an output block:\n"
<< after;
}
// GL 4.6 core 11.1.2.1: consecutive members take consecutive locations, and a member takes as
@@ -182,8 +181,7 @@ TEST_F(FlattenXfbInterfaceBlocksTest, LeavesABlockNoCaptureNamesAlone) {
std::set<String> flattened;
Vector<Uint32> output;
ASSERT_TRUE(
ShaderCompiler::FlattenXfbInterfaceBlocksForEssl(input, {"SomeOtherBlock"}, flattened, output, true));
ASSERT_TRUE(ShaderCompiler::FlattenXfbInterfaceBlocksForEssl(input, {"SomeOtherBlock"}, flattened, output, true));
EXPECT_TRUE(flattened.empty());
const String after = Transpile(output);
@@ -209,16 +207,14 @@ TEST_F(FlattenXfbInterfaceBlocksTest, DeclinesAnEmptyRequestWithoutRewriting) {
// does a name with no block prefix at all (gl_Position, a plain varying).
TEST_F(FlattenXfbInterfaceBlocksTest, RewritesOnlyTheCaptureNamesOfFlattenedBlocks) {
String rewritten;
EXPECT_TRUE(ShaderCompiler::RewriteXfbCaptureNameForFlattenedBlock("StageData.attrib[0]", {"StageData"},
rewritten));
EXPECT_TRUE(
ShaderCompiler::RewriteXfbCaptureNameForFlattenedBlock("StageData.attrib[0]", {"StageData"}, rewritten));
EXPECT_EQ(rewritten, "StageData_attrib[0]");
EXPECT_TRUE(
ShaderCompiler::RewriteXfbCaptureNameForFlattenedBlock("StageData.attrib", {"StageData"}, rewritten));
EXPECT_TRUE(ShaderCompiler::RewriteXfbCaptureNameForFlattenedBlock("StageData.attrib", {"StageData"}, rewritten));
EXPECT_EQ(rewritten, "StageData_attrib");
EXPECT_FALSE(
ShaderCompiler::RewriteXfbCaptureNameForFlattenedBlock("Other.member", {"StageData"}, rewritten));
EXPECT_FALSE(ShaderCompiler::RewriteXfbCaptureNameForFlattenedBlock("Other.member", {"StageData"}, rewritten));
EXPECT_FALSE(ShaderCompiler::RewriteXfbCaptureNameForFlattenedBlock("gl_Position", {"StageData"}, rewritten));
EXPECT_FALSE(ShaderCompiler::RewriteXfbCaptureNameForFlattenedBlock("vColor", {"StageData"}, rewritten));
EXPECT_FALSE(ShaderCompiler::RewriteXfbCaptureNameForFlattenedBlock(".leading", {"StageData"}, rewritten));
@@ -29,8 +29,8 @@ namespace {
using namespace MG_Util::ShaderTranspiler;
Vector<SharedPtr<glslang::TShader>> shaders;
Vector<GLenum> types;
for (const auto& [stage, source] : Vector<Pair<GLenum, const char*>>{{GL_VERTEX_SHADER, vertex},
{GL_FRAGMENT_SHADER, fragment}}) {
for (const auto& [stage, source] :
Vector<Pair<GLenum, const char*>>{{GL_VERTEX_SHADER, vertex}, {GL_FRAGMENT_SHADER, fragment}}) {
ShaderAttrib attrib{.shaderType = stage, .sourceStr = source};
auto shader = ShaderCompiler::CompileShader(attrib);
EXPECT_TRUE(shader) << (shader ? String{} : shader.error().log);
@@ -63,8 +63,9 @@ namespace {
String ValidationError(const Vector<Uint32>& spirv) {
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
String error;
tools.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&,
const char* message) { error += message != nullptr ? message : ""; });
tools.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&, const char* message) {
error += message != nullptr ? message : "";
});
return tools.Validate(spirv) ? String{} : (error.empty() ? String{"invalid"} : error);
}
@@ -125,8 +126,7 @@ TEST(ClipControlTransformFlags, OriginTogglesTheFlipAndDepthModeDropsTheRemap) {
EXPECT_EQ(apply(fbo, GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE), fbo);
EXPECT_EQ(apply(window, GL_LOWER_LEFT, GL_NEGATIVE_ONE_TO_ONE), window);
EXPECT_EQ(apply(fbo, GL_UPPER_LEFT, GL_NEGATIVE_ONE_TO_ONE), fbo | static_cast<Uint32>(Bit::PositionYFlip));
EXPECT_EQ(apply(window, GL_UPPER_LEFT, GL_NEGATIVE_ONE_TO_ONE),
window & ~static_cast<Uint32>(Bit::PositionYFlip));
EXPECT_EQ(apply(window, GL_UPPER_LEFT, GL_NEGATIVE_ONE_TO_ONE), window & ~static_cast<Uint32>(Bit::PositionYFlip));
EXPECT_EQ(apply(fbo, GL_LOWER_LEFT, GL_ZERO_TO_ONE), 0u);
EXPECT_EQ(apply(window, GL_UPPER_LEFT, GL_ZERO_TO_ONE),
static_cast<Uint32>(Bit::FragCoordYFlip) | static_cast<Uint32>(Bit::SurfaceRotate90));
@@ -64,14 +64,16 @@ void main() { gl_Position = vec4(position, 0.0, 1.0); }
String ValidationError(const Vector<Uint32>& spirv) {
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
String error;
tools.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&,
const char* message) { error += message != nullptr ? message : ""; });
tools.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&, const char* message) {
error += message != nullptr ? message : "";
});
return tools.Validate(spirv) ? String{} : (error.empty() ? String{"invalid"} : error);
}
SizeT CountOccurrences(const String& text, const String& needle) {
SizeT count = 0;
for (SizeT at = text.find(needle); at != String::npos; at = text.find(needle, at + needle.size())) ++count;
for (SizeT at = text.find(needle); at != String::npos; at = text.find(needle, at + needle.size()))
++count;
return count;
}
@@ -204,8 +204,7 @@ void main() {
EXPECT_EQ(probed->at("probeSampler").binding, 3u);
ASSERT_TRUE(probed->contains("probeImage"));
EXPECT_TRUE(probed->at("probeImage").hasBinding)
<< "images take the same path as samplers (both are EbtSampler)";
EXPECT_TRUE(probed->at("probeImage").hasBinding) << "images take the same path as samplers (both are EbtSampler)";
EXPECT_EQ(probed->at("probeImage").binding, 5u);
// The default-block uniform is gone from the entity list entirely - it was swept into
@@ -566,8 +565,7 @@ void main() {
// A UNIFORM block is a different binding space with its own glUniformBlockBinding path, so it
// must not reach the storage-block seeder - it has a capture set of its own (see
// UnqualifiedUniformBlocksAreCapturedSeparatelyFromStorageBlocks below).
EXPECT_EQ(capture.storageBlocksWithoutBinding.count("InputBuffer"), 0u)
<< "uniform blocks belong to the other set";
EXPECT_EQ(capture.storageBlocksWithoutBinding.count("InputBuffer"), 0u) << "uniform blocks belong to the other set";
}
// The uniform-block half of the same capture, and the reason it exists: glslang packs uniform
@@ -598,8 +596,7 @@ void main() {
<< "a declared binding must never be defaulted away";
EXPECT_EQ(capture.uniformBlocksWithoutBinding.count("OutputBuffer"), 0u)
<< "storage blocks belong to the other set";
EXPECT_EQ(capture.storageBlocksWithoutBinding.count("GOKU"), 0u)
<< "the two sets must not cross-contaminate";
EXPECT_EQ(capture.storageBlocksWithoutBinding.count("GOKU"), 0u) << "the two sets must not cross-contaminate";
// The negative control every capture case here carries: with the OUT pointer left null the
// resolver must write nothing at all.
@@ -630,8 +627,7 @@ void main() { noBinding.c = afterLayout.a + beforeLayout.b + uint(texelFetch(tex
<< "a qualifier may precede the layout list too";
EXPECT_EQ(capture.storageBlocksWithoutBinding.count("NoBindingAtAll"), 1u)
<< "a memory-qualified block with no binding is still an unqualified block";
EXPECT_EQ(capture.storageBlocksWithoutBinding.count("texelSampler"), 0u)
<< "a samplerBuffer is not a buffer block";
EXPECT_EQ(capture.storageBlocksWithoutBinding.count("texelSampler"), 0u) << "a samplerBuffer is not a buffer block";
}
// THE REGRESSION THIS MIGRATION EXISTS FOR (7de7cfc6, the original capture now replayed as
@@ -722,8 +718,7 @@ out vec4 colour;
void main() { colour = vec4(float(sharedInstance.u + fragmentBound.f)); }
)";
const LinkCapture capture =
CaptureFromLink({{GL_VERTEX_SHADER, vertex}, {GL_FRAGMENT_SHADER, fragment}});
const LinkCapture capture = CaptureFromLink({{GL_VERTEX_SHADER, vertex}, {GL_FRAGMENT_SHADER, fragment}});
ASSERT_TRUE(capture.linked) << capture.log;
EXPECT_EQ(capture.storageBlocksWithoutBinding.count("SharedBlock"), 1u);
@@ -770,8 +765,7 @@ TEST_F(GlslangCaptureProbeTest, AtomicCounterOffsetRulesAreRaisedByTheParse) {
// offset spelled as a macro, are now both judged. The scanner declined both - it read
// unexpanded text and only understood integer literals.
EXPECT_FALSE(compiles("const int kCount = 4;\nlayout(binding = 0, offset = " +
std::to_string(MAX_ATOMIC_COUNTER_BUFFER_SIZE - 8) +
") uniform atomic_uint c[kCount];\n"));
std::to_string(MAX_ATOMIC_COUNTER_BUFFER_SIZE - 8) + ") uniform atomic_uint c[kCount];\n"));
EXPECT_FALSE(compiles("#define BAD_OFFSET 2\nlayout(binding = 0, offset = BAD_OFFSET) uniform atomic_uint c;\n"));
// The counterweight: `offset` as an ordinary identifier is not a layout qualifier, and an
@@ -79,19 +79,18 @@ namespace {
// at an array-of-storage-blocks variable carries a non-constant FIRST index, which is
// exactly what the Qualcomm ES compiler refuses.
bool HasDynamicBlockArrayIndex(const Vector<Uint32>& spirv) {
std::set<Uint32> blockStructs; // OpTypeStruct ids decorated Block / BufferBlock
std::set<Uint32> constants; // OpConstant / OpConstantNull result ids
std::set<Uint32> blockArrayTypes; // OpTypeArray ids whose element is such a struct
std::set<Uint32> blockArrayPointers;// OpTypePointer ids pointing at one of those arrays
std::set<Uint32> blockArrayVars; // OpVariable ids of one of those pointer types
std::set<Uint32> blockStructs; // OpTypeStruct ids decorated Block / BufferBlock
std::set<Uint32> constants; // OpConstant / OpConstantNull result ids
std::set<Uint32> blockArrayTypes; // OpTypeArray ids whose element is such a struct
std::set<Uint32> blockArrayPointers; // OpTypePointer ids pointing at one of those arrays
std::set<Uint32> blockArrayVars; // OpVariable ids of one of those pointer types
ForEachInstruction(spirv, [&](spv::Op opcode, const Uint32* words, Uint32 wordCount) {
switch (opcode) {
case spv::Op::OpDecorate:
if (wordCount >= 3u) {
const auto decoration = static_cast<spv::Decoration>(words[2]);
if (decoration == spv::Decoration::Block ||
decoration == spv::Decoration::BufferBlock) {
if (decoration == spv::Decoration::Block || decoration == spv::Decoration::BufferBlock) {
blockStructs.insert(words[1]);
}
}
@@ -31,8 +31,8 @@ layout(location = 0) in vec2 position;
void main() { gl_Position = vec4(position, 0.0, 1.0); }
)";
Vector<SharedPtr<glslang::TShader>> shaders;
for (const auto& [stage, source] : Vector<Pair<GLenum, const char*>>{{GL_VERTEX_SHADER, kVertex},
{GL_FRAGMENT_SHADER, fragment}}) {
for (const auto& [stage, source] :
Vector<Pair<GLenum, const char*>>{{GL_VERTEX_SHADER, kVertex}, {GL_FRAGMENT_SHADER, fragment}}) {
ShaderAttrib attrib{.shaderType = stage, .sourceStr = source};
auto shader = ShaderCompiler::CompileShader(attrib);
EXPECT_TRUE(shader) << (shader ? String{} : shader.error().log);
@@ -63,14 +63,16 @@ void main() { gl_Position = vec4(position, 0.0, 1.0); }
String ValidationError(const Vector<Uint32>& spirv) {
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
String error;
tools.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&,
const char* message) { error += message != nullptr ? message : ""; });
tools.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&, const char* message) {
error += message != nullptr ? message : "";
});
return tools.Validate(spirv) ? String{} : (error.empty() ? String{"invalid"} : error);
}
SizeT CountOccurrences(const String& text, const String& needle) {
SizeT count = 0;
for (SizeT at = text.find(needle); at != String::npos; at = text.find(needle, at + needle.size())) ++count;
for (SizeT at = text.find(needle); at != String::npos; at = text.find(needle, at + needle.size()))
++count;
return count;
}
} // namespace
@@ -94,8 +96,7 @@ void main() { color = texelFetch(data, ivec2(gl_FragCoord.xy), 0); }
const String text = Disassemble(output);
EXPECT_EQ(text.find("PixelCenterInteger"), String::npos) << text;
EXPECT_EQ(CountOccurrences(text, "OpFSub"), 1u) << text;
EXPECT_NE(text.find("OpConstantComposite %v4float %float_0_5 %float_0_5 %float_0 %float_0"), String::npos)
<< text;
EXPECT_NE(text.find("OpConstantComposite %v4float %float_0_5 %float_0_5 %float_0 %float_0"), String::npos) << text;
}
// Single components arrive through an access chain: x and y move, z and w keep their values.
@@ -32,8 +32,8 @@ namespace {
using namespace MG_Util::ShaderTranspiler;
Vector<SharedPtr<glslang::TShader>> shaders;
Vector<GLenum> types;
for (const auto& [stage, source] : Vector<Pair<GLenum, const char*>>{{GL_VERTEX_SHADER, vertex},
{GL_FRAGMENT_SHADER, fragment}}) {
for (const auto& [stage, source] :
Vector<Pair<GLenum, const char*>>{{GL_VERTEX_SHADER, vertex}, {GL_FRAGMENT_SHADER, fragment}}) {
ShaderAttrib attrib{.shaderType = stage, .sourceStr = source};
auto shader = ShaderCompiler::CompileShader(attrib);
EXPECT_TRUE(shader) << (shader ? String{} : shader.error().log);
@@ -60,8 +60,9 @@ namespace {
String VulkanValidationError(const Vector<Uint32>& spirv) {
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
String error;
tools.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&,
const char* message) { error += message != nullptr ? message : ""; });
tools.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&, const char* message) {
error += message != nullptr ? message : "";
});
if (tools.Validate(spirv)) return {};
String text;
tools.Disassemble(spirv, &text);
@@ -74,7 +75,8 @@ namespace {
TEST(RelaxedOpaqueStructTest, AnAnonymousUniformStructLosesItsSamplerInTheDefaultBlock) {
MobileGL::Initialize();
const auto modules = CompileProgram(kVertex,
const auto modules = CompileProgram(
kVertex,
"#version 330 core\n"
"uniform struct { vec3 size; float time; int loaded; sampler2D smp; } c0, c1, c2, c3;\n"
"uniform vec3 res; out vec4 o;\n"
@@ -85,11 +87,11 @@ TEST(RelaxedOpaqueStructTest, AnAnonymousUniformStructLosesItsSamplerInTheDefaul
TEST(RelaxedOpaqueStructTest, ANamedUniformStructLosesItsSamplerInTheDefaultBlock) {
MobileGL::Initialize();
const auto modules = CompileProgram(kVertex,
"#version 330 core\n"
"struct Channel { vec3 size; float time; int loaded; sampler2D smp; };\n"
"uniform Channel c0; uniform Channel c1; uniform vec3 res; out vec4 o;\n"
"void main() { o = texture(c1.smp, gl_FragCoord.xy / res.xy) + vec4(c0.size, c0.time); }");
const auto modules = CompileProgram(
kVertex, "#version 330 core\n"
"struct Channel { vec3 size; float time; int loaded; sampler2D smp; };\n"
"uniform Channel c0; uniform Channel c1; uniform vec3 res; out vec4 o;\n"
"void main() { o = texture(c1.smp, gl_FragCoord.xy / res.xy) + vec4(c0.size, c0.time); }");
ASSERT_EQ(modules.size(), 2u);
EXPECT_EQ(VulkanValidationError(modules[1]), String{});
}
@@ -94,7 +94,7 @@ namespace {
"}\n";
} // namespace
class ShadingRateEsslTest: public ::testing::Test {
class ShadingRateEsslTest : public ::testing::Test {
protected:
void SetUp() override { MobileGL::Initialize(); }
};
@@ -24,71 +24,56 @@ namespace {
// layout(location = 0) in vec4 inPos;
// void main() { gl_Position = inPos; }
constexpr Uint32 kPlainVertexSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000015u, 0x00000000u, 0x00020011u,
0x00000001u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu,
0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, 0x0007000fu, 0x00000000u,
0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x00000011u, 0x00030003u,
0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u,
0x00060005u, 0x0000000bu, 0x505f6c67u, 0x65567265u, 0x78657472u, 0x00000000u,
0x00060006u, 0x0000000bu, 0x00000000u, 0x505f6c67u, 0x7469736fu, 0x006e6f69u,
0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u, 0x746e696fu, 0x657a6953u,
0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u, 0x4470696cu,
0x61747369u, 0x0065636eu, 0x00070006u, 0x0000000bu, 0x00000003u, 0x435f6c67u,
0x446c6c75u, 0x61747369u, 0x0065636eu, 0x00030005u, 0x0000000du, 0x00000000u,
0x00040005u, 0x00000011u, 0x6f506e69u, 0x00000073u, 0x00030047u, 0x0000000bu,
0x00000002u, 0x00050048u, 0x0000000bu, 0x00000000u, 0x0000000bu, 0x00000000u,
0x00050048u, 0x0000000bu, 0x00000001u, 0x0000000bu, 0x00000001u, 0x00050048u,
0x0000000bu, 0x00000002u, 0x0000000bu, 0x00000003u, 0x00050048u, 0x0000000bu,
0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u, 0x00000011u, 0x0000001eu,
0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u,
0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u,
0x00000004u, 0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u, 0x0004002bu,
0x00000008u, 0x00000009u, 0x00000001u, 0x0004001cu, 0x0000000au, 0x00000006u,
0x00000009u, 0x0006001eu, 0x0000000bu, 0x00000007u, 0x00000006u, 0x0000000au,
0x0000000au, 0x00040020u, 0x0000000cu, 0x00000003u, 0x0000000bu, 0x0004003bu,
0x0000000cu, 0x0000000du, 0x00000003u, 0x00040015u, 0x0000000eu, 0x00000020u,
0x00000001u, 0x0004002bu, 0x0000000eu, 0x0000000fu, 0x00000000u, 0x00040020u,
0x00000010u, 0x00000001u, 0x00000007u, 0x0004003bu, 0x00000010u, 0x00000011u,
0x00000001u, 0x00040020u, 0x00000013u, 0x00000003u, 0x00000007u, 0x00050036u,
0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u,
0x0004003du, 0x00000007u, 0x00000012u, 0x00000011u, 0x00050041u, 0x00000013u,
0x00000014u, 0x0000000du, 0x0000000fu, 0x0003003eu, 0x00000014u, 0x00000012u,
0x000100fdu, 0x00010038u,
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000015u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0007000fu, 0x00000000u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x00000011u, 0x00030003u,
0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00060005u, 0x0000000bu,
0x505f6c67u, 0x65567265u, 0x78657472u, 0x00000000u, 0x00060006u, 0x0000000bu, 0x00000000u, 0x505f6c67u,
0x7469736fu, 0x006e6f69u, 0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u, 0x746e696fu, 0x657a6953u,
0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u, 0x4470696cu, 0x61747369u, 0x0065636eu,
0x00070006u, 0x0000000bu, 0x00000003u, 0x435f6c67u, 0x446c6c75u, 0x61747369u, 0x0065636eu, 0x00030005u,
0x0000000du, 0x00000000u, 0x00040005u, 0x00000011u, 0x6f506e69u, 0x00000073u, 0x00030047u, 0x0000000bu,
0x00000002u, 0x00050048u, 0x0000000bu, 0x00000000u, 0x0000000bu, 0x00000000u, 0x00050048u, 0x0000000bu,
0x00000001u, 0x0000000bu, 0x00000001u, 0x00050048u, 0x0000000bu, 0x00000002u, 0x0000000bu, 0x00000003u,
0x00050048u, 0x0000000bu, 0x00000003u, 0x0000000bu, 0x00000004u, 0x00040047u, 0x00000011u, 0x0000001eu,
0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u,
0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000004u, 0x00040015u, 0x00000008u, 0x00000020u,
0x00000000u, 0x0004002bu, 0x00000008u, 0x00000009u, 0x00000001u, 0x0004001cu, 0x0000000au, 0x00000006u,
0x00000009u, 0x0006001eu, 0x0000000bu, 0x00000007u, 0x00000006u, 0x0000000au, 0x0000000au, 0x00040020u,
0x0000000cu, 0x00000003u, 0x0000000bu, 0x0004003bu, 0x0000000cu, 0x0000000du, 0x00000003u, 0x00040015u,
0x0000000eu, 0x00000020u, 0x00000001u, 0x0004002bu, 0x0000000eu, 0x0000000fu, 0x00000000u, 0x00040020u,
0x00000010u, 0x00000001u, 0x00000007u, 0x0004003bu, 0x00000010u, 0x00000011u, 0x00000001u, 0x00040020u,
0x00000013u, 0x00000003u, 0x00000007u, 0x00050036u, 0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u,
0x000200f8u, 0x00000005u, 0x0004003du, 0x00000007u, 0x00000012u, 0x00000011u, 0x00050041u, 0x00000013u,
0x00000014u, 0x0000000du, 0x0000000fu, 0x0003003eu, 0x00000014u, 0x00000012u, 0x000100fdu, 0x00010038u,
};
// ... plus `invariant gl_Position;` - already carries OpMemberDecorate %gl_PerVertex 0
// Invariant, so the pass must not add a duplicate.
constexpr Uint32 kAlreadyInvariantVertexSpirv[] = {
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000015u, 0x00000000u, 0x00020011u,
0x00000001u, 0x0006000bu, 0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu,
0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u, 0x0007000fu, 0x00000000u,
0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x00000011u, 0x00030003u,
0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u,
0x00060005u, 0x0000000bu, 0x505f6c67u, 0x65567265u, 0x78657472u, 0x00000000u,
0x00060006u, 0x0000000bu, 0x00000000u, 0x505f6c67u, 0x7469736fu, 0x006e6f69u,
0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u, 0x746e696fu, 0x657a6953u,
0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u, 0x4470696cu,
0x61747369u, 0x0065636eu, 0x00070006u, 0x0000000bu, 0x00000003u, 0x435f6c67u,
0x446c6c75u, 0x61747369u, 0x0065636eu, 0x00030005u, 0x0000000du, 0x00000000u,
0x00040005u, 0x00000011u, 0x6f506e69u, 0x00000073u, 0x00030047u, 0x0000000bu,
0x00000002u, 0x00050048u, 0x0000000bu, 0x00000000u, 0x0000000bu, 0x00000000u,
0x00040048u, 0x0000000bu, 0x00000000u, 0x00000012u, 0x00050048u, 0x0000000bu,
0x00000001u, 0x0000000bu, 0x00000001u, 0x00050048u, 0x0000000bu, 0x00000002u,
0x0000000bu, 0x00000003u, 0x00050048u, 0x0000000bu, 0x00000003u, 0x0000000bu,
0x00000004u, 0x00040047u, 0x00000011u, 0x0000001eu, 0x00000000u, 0x00020013u,
0x00000002u, 0x00030021u, 0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u,
0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u, 0x00000004u, 0x00040015u,
0x00000008u, 0x00000020u, 0x00000000u, 0x0004002bu, 0x00000008u, 0x00000009u,
0x00000001u, 0x0004001cu, 0x0000000au, 0x00000006u, 0x00000009u, 0x0006001eu,
0x0000000bu, 0x00000007u, 0x00000006u, 0x0000000au, 0x0000000au, 0x00040020u,
0x0000000cu, 0x00000003u, 0x0000000bu, 0x0004003bu, 0x0000000cu, 0x0000000du,
0x00000003u, 0x00040015u, 0x0000000eu, 0x00000020u, 0x00000001u, 0x0004002bu,
0x0000000eu, 0x0000000fu, 0x00000000u, 0x00040020u, 0x00000010u, 0x00000001u,
0x00000007u, 0x0004003bu, 0x00000010u, 0x00000011u, 0x00000001u, 0x00040020u,
0x00000013u, 0x00000003u, 0x00000007u, 0x00050036u, 0x00000002u, 0x00000004u,
0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003du, 0x00000007u,
0x00000012u, 0x00000011u, 0x00050041u, 0x00000013u, 0x00000014u, 0x0000000du,
0x0000000fu, 0x0003003eu, 0x00000014u, 0x00000012u, 0x000100fdu, 0x00010038u,
0x07230203u, 0x00010000u, 0x0008000bu, 0x00000015u, 0x00000000u, 0x00020011u, 0x00000001u, 0x0006000bu,
0x00000001u, 0x4c534c47u, 0x6474732eu, 0x3035342eu, 0x00000000u, 0x0003000eu, 0x00000000u, 0x00000001u,
0x0007000fu, 0x00000000u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x0000000du, 0x00000011u, 0x00030003u,
0x00000002u, 0x000001c2u, 0x00040005u, 0x00000004u, 0x6e69616du, 0x00000000u, 0x00060005u, 0x0000000bu,
0x505f6c67u, 0x65567265u, 0x78657472u, 0x00000000u, 0x00060006u, 0x0000000bu, 0x00000000u, 0x505f6c67u,
0x7469736fu, 0x006e6f69u, 0x00070006u, 0x0000000bu, 0x00000001u, 0x505f6c67u, 0x746e696fu, 0x657a6953u,
0x00000000u, 0x00070006u, 0x0000000bu, 0x00000002u, 0x435f6c67u, 0x4470696cu, 0x61747369u, 0x0065636eu,
0x00070006u, 0x0000000bu, 0x00000003u, 0x435f6c67u, 0x446c6c75u, 0x61747369u, 0x0065636eu, 0x00030005u,
0x0000000du, 0x00000000u, 0x00040005u, 0x00000011u, 0x6f506e69u, 0x00000073u, 0x00030047u, 0x0000000bu,
0x00000002u, 0x00050048u, 0x0000000bu, 0x00000000u, 0x0000000bu, 0x00000000u, 0x00040048u, 0x0000000bu,
0x00000000u, 0x00000012u, 0x00050048u, 0x0000000bu, 0x00000001u, 0x0000000bu, 0x00000001u, 0x00050048u,
0x0000000bu, 0x00000002u, 0x0000000bu, 0x00000003u, 0x00050048u, 0x0000000bu, 0x00000003u, 0x0000000bu,
0x00000004u, 0x00040047u, 0x00000011u, 0x0000001eu, 0x00000000u, 0x00020013u, 0x00000002u, 0x00030021u,
0x00000003u, 0x00000002u, 0x00030016u, 0x00000006u, 0x00000020u, 0x00040017u, 0x00000007u, 0x00000006u,
0x00000004u, 0x00040015u, 0x00000008u, 0x00000020u, 0x00000000u, 0x0004002bu, 0x00000008u, 0x00000009u,
0x00000001u, 0x0004001cu, 0x0000000au, 0x00000006u, 0x00000009u, 0x0006001eu, 0x0000000bu, 0x00000007u,
0x00000006u, 0x0000000au, 0x0000000au, 0x00040020u, 0x0000000cu, 0x00000003u, 0x0000000bu, 0x0004003bu,
0x0000000cu, 0x0000000du, 0x00000003u, 0x00040015u, 0x0000000eu, 0x00000020u, 0x00000001u, 0x0004002bu,
0x0000000eu, 0x0000000fu, 0x00000000u, 0x00040020u, 0x00000010u, 0x00000001u, 0x00000007u, 0x0004003bu,
0x00000010u, 0x00000011u, 0x00000001u, 0x00040020u, 0x00000013u, 0x00000003u, 0x00000007u, 0x00050036u,
0x00000002u, 0x00000004u, 0x00000000u, 0x00000003u, 0x000200f8u, 0x00000005u, 0x0004003du, 0x00000007u,
0x00000012u, 0x00000011u, 0x00050041u, 0x00000013u, 0x00000014u, 0x0000000du, 0x0000000fu, 0x0003003eu,
0x00000014u, 0x00000012u, 0x000100fdu, 0x00010038u,
};
// OpMemberDecorate <struct-id> <member> <decoration>
@@ -172,9 +172,8 @@ TEST_F(StripIoBlockLocationsTest, DropsTheQualifierFromBothBlocksAndLeavesVaryin
// fragment stage's inputs and a vertex stage's attributes are matched by them.
EXPECT_NE(after.find("in vec4 tcs_tes_result"), String::npos) << after;
EXPECT_NE(after.find("out vec4 tes_gs_result"), String::npos) << after;
EXPECT_EQ(CountOf(after, "layout(location"), 2u)
<< "exactly the two plain varyings should still be located:\n"
<< after;
EXPECT_EQ(CountOf(after, "layout(location"), 2u) << "exactly the two plain varyings should still be located:\n"
<< after;
}
TEST_F(StripIoBlockLocationsTest, StripsOnlyTheDirectionTheCallerArmed) {
@@ -199,8 +198,7 @@ TEST_F(StripIoBlockLocationsTest, StripsOnlyTheDirectionTheCallerArmed) {
// And the mirror image, for a program that BEGINS at this stage.
bool strippedOutputOnly = false;
Vector<Uint32> outputOnly;
ASSERT_TRUE(
ShaderCompiler::StripIoBlockLocationsForEssl(input, false, true, strippedOutputOnly, outputOnly, true));
ASSERT_TRUE(ShaderCompiler::StripIoBlockLocationsForEssl(input, false, true, strippedOutputOnly, outputOnly, true));
ASSERT_FALSE(outputOnly.empty());
EXPECT_TRUE(strippedOutputOnly);
const String afterOutputOnly = Transpile(outputOnly);
@@ -48,8 +48,7 @@ namespace {
// AsyncSpirvPhaseTest's AsyncModeScope uses for its own toggle.
class CacheModeScope {
public:
explicit CacheModeScope(const Bool enabled)
: m_saved(MG_Config::Features.ShaderTranslationCache) {
explicit CacheModeScope(const Bool enabled) : m_saved(MG_Config::Features.ShaderTranslationCache) {
MG_Config::Features.ShaderTranslationCache =
enabled ? MG_Config::QuirkOverride::ForceOn : MG_Config::QuirkOverride::ForceOff;
}
@@ -86,7 +85,9 @@ namespace {
return MakeTranslationCacheKey(builder);
}
SizeT PayloadBytes(const TestPayload& payload) { return payload.text.size(); }
SizeT PayloadBytes(const TestPayload& payload) {
return payload.text.size();
}
// ---- L1 fixtures ----
const char* kVertexSource = R"(#version 460
@@ -112,11 +113,15 @@ void main() {
String SwizzleLikeFragment(const String& basicType) {
return "#version 460\n"
"in vec3 vPos;\n"
"layout(location = 0) out " + basicType + "vec4 fragColor;\n"
"layout(location = 0) out " +
basicType +
"vec4 fragColor;\n"
"uniform sampler2D uTex;\n"
"void main() {\n"
" vec4 s = texture(uTex, vPos.xy);\n"
" fragColor = " + basicType + "vec4(s);\n"
" fragColor = " +
basicType +
"vec4(s);\n"
"}\n";
}
@@ -148,7 +153,8 @@ void main() {
Uint64 DigestOf(const Vector<Uint32>& words) {
Uint64 hash = 1469598103934665603ull;
for (const Uint32 word : words) hash = (hash ^ static_cast<Uint64>(word)) * 1099511628211ull;
for (const Uint32 word : words)
hash = (hash ^ static_cast<Uint64>(word)) * 1099511628211ull;
return hash;
}
@@ -156,7 +162,8 @@ void main() {
Vector<Uint64> digest;
const auto& object = MG_State::pGLContext->GetProgramObject(program);
if (!object) return digest;
for (const auto& module : object->GetGeneratedSpirv()) digest.push_back(DigestOf(module));
for (const auto& module : object->GetGeneratedSpirv())
digest.push_back(DigestOf(module));
return digest;
}
@@ -403,8 +410,7 @@ TEST_F(TranslationCacheTest, TextAppendsCannotRunIntoEachOther) {
TEST_F(TranslationCacheTest, L1AndL2KeysNeverAlias) {
const Vector<Uint32> spirv{1u, 2u, 3u};
const TranslationCacheKey l2 = BuildEsslTranslationKey(BaselineEsslInputs(spirv));
const TranslationCacheKey l1 =
BuildSpirvTranslationKey(BaselineSpirvInputs({{GL_FRAGMENT_SHADER, "source"}}));
const TranslationCacheKey l1 = BuildSpirvTranslationKey(BaselineSpirvInputs({{GL_FRAGMENT_SHADER, "source"}}));
EXPECT_FALSE(l1 == l2);
}
@@ -415,8 +421,7 @@ TEST_F(TranslationCacheTest, L1AndL2KeysNeverAlias) {
TEST_F(TranslationCacheTest, L1KeyMovesWithEveryInputThatMovesTheSpirv) {
const String vs = kVertexSource;
const String fs = kFragmentSource;
const Vector<SpirvTranslationKeyInputs::Stage> baseStages{
{GL_VERTEX_SHADER, vs}, {GL_FRAGMENT_SHADER, fs}};
const Vector<SpirvTranslationKeyInputs::Stage> baseStages{{GL_VERTEX_SHADER, vs}, {GL_FRAGMENT_SHADER, fs}};
const UnorderedMap<String, Uint> attribs{{"aPos", 3u}};
const UnorderedMap<String, Uint> fragOut{{"fragColor", 1u}};
@@ -433,44 +438,41 @@ TEST_F(TranslationCacheTest, L1KeyMovesWithEveryInputThatMovesTheSpirv) {
Vector<Pair<const char*, TranslationCacheKey>> variants;
{ // the environment fingerprint (glslang resource limits, backend identity,
{ // the environment fingerprint (glslang resource limits, backend identity,
// advertised extension set, compute limits)
SpirvTranslationKeyInputs v = base;
v.frontendFingerprint ^= 1ull;
variants.emplace_back("frontendFingerprint", BuildSpirvTranslationKey(v));
}
{ // a stage's source text
{ // a stage's source text
const String otherFs = SwizzleLikeFragment("i");
SpirvTranslationKeyInputs v = BaselineSpirvInputs({{GL_VERTEX_SHADER, vs},
{GL_FRAGMENT_SHADER, otherFs}});
SpirvTranslationKeyInputs v = BaselineSpirvInputs({{GL_VERTEX_SHADER, vs}, {GL_FRAGMENT_SHADER, otherFs}});
variants.emplace_back("stage source", BuildSpirvTranslationKey(v));
}
{ // a stage's TYPE, with the text unchanged
SpirvTranslationKeyInputs v = BaselineSpirvInputs({{GL_VERTEX_SHADER, vs},
{GL_COMPUTE_SHADER, fs}});
{ // a stage's TYPE, with the text unchanged
SpirvTranslationKeyInputs v = BaselineSpirvInputs({{GL_VERTEX_SHADER, vs}, {GL_COMPUTE_SHADER, fs}});
variants.emplace_back("stage type", BuildSpirvTranslationKey(v));
}
{ // the SET of stages - mapIO resolves a fragment stage's Locations against the
{ // the SET of stages - mapIO resolves a fragment stage's Locations against the
// vertex stage's outputs, which is why this key is per PROGRAM and not per stage
SpirvTranslationKeyInputs v = BaselineSpirvInputs({{GL_FRAGMENT_SHADER, fs}});
variants.emplace_back("stage set", BuildSpirvTranslationKey(v));
}
{ // stage ORDER
SpirvTranslationKeyInputs v = BaselineSpirvInputs({{GL_FRAGMENT_SHADER, fs},
{GL_VERTEX_SHADER, vs}});
{ // stage ORDER
SpirvTranslationKeyInputs v = BaselineSpirvInputs({{GL_FRAGMENT_SHADER, fs}, {GL_VERTEX_SHADER, vs}});
variants.emplace_back("stage order", BuildSpirvTranslationKey(v));
}
{ // glBindAttribLocation
{ // glBindAttribLocation
SpirvTranslationKeyInputs v = base;
v.explicitVertexInLocations = &attribs;
variants.emplace_back("explicitVertexInLocations", BuildSpirvTranslationKey(v));
}
{ // glBindFragDataLocation
{ // glBindFragDataLocation
SpirvTranslationKeyInputs v = base;
v.explicitFragmentOutLocations = &fragOut;
variants.emplace_back("explicitFragmentOutLocations", BuildSpirvTranslationKey(v));
}
{ // glBindFragDataLocationIndexed
{ // glBindFragDataLocationIndexed
SpirvTranslationKeyInputs v = base;
v.explicitFragmentOutIndices = &fragIndex;
variants.emplace_back("explicitFragmentOutIndices", BuildSpirvTranslationKey(v));
@@ -480,18 +482,18 @@ TEST_F(TranslationCacheTest, L1KeyMovesWithEveryInputThatMovesTheSpirv) {
// pure function of the stage sources this key already carries in full. It was dropped from
// SpirvTranslationKeyInputs with the glslang-capture migration; kKeyLayoutVersion moved to
// 4 so no blob written under the old shape can be honoured.
{ // ShaderCompileBits (0 on both production parse paths; keyed so a future value
{ // ShaderCompileBits (0 on both production parse paths; keyed so a future value
// cannot alias a module parsed without it)
SpirvTranslationKeyInputs v = base;
v.shaderCompileFlags = 1u;
variants.emplace_back("shaderCompileFlags", BuildSpirvTranslationKey(v));
}
{ // MOBILEGL_ENABLE_SPIRV_VALIDATION
{ // MOBILEGL_ENABLE_SPIRV_VALIDATION
SpirvTranslationKeyInputs v = base;
v.enableSpirvValidation = true;
variants.emplace_back("enableSpirvValidation", BuildSpirvTranslationKey(v));
}
{ // CompileEnv::ConsumesFloat64Natively(): the fp64 tail of SanitizeAndOptimizeBinary is
{ // CompileEnv::ConsumesFloat64Natively(): the fp64 tail of SanitizeAndOptimizeBinary is
// skipped under it, so the SAME GLSL yields modules with real doubles under one answer
// and demoted, storage-block-flattened ones under the other. The one backend capability
// bit in this key, and the only one allowed in without changing what glslang produces.
@@ -499,14 +501,14 @@ TEST_F(TranslationCacheTest, L1KeyMovesWithEveryInputThatMovesTheSpirv) {
v.nativeFloat64 = true;
variants.emplace_back("nativeFloat64", BuildSpirvTranslationKey(v));
}
{ // CompileEnv::DemotesTessellationPointSize(): phase B rewrites the cached modules
{ // CompileEnv::DemotesTessellationPointSize(): phase B rewrites the cached modules
// under it (the point-size demotion), so one key shape would describe two module
// sets - built-in kept vs carried as a varying with the capability stripped.
SpirvTranslationKeyInputs v = base;
v.demoteTessellationPointSize = true;
variants.emplace_back("demoteTessellationPointSize", BuildSpirvTranslationKey(v));
}
{ // ... and its geometry twin, keyed separately because the ES loader really does
{ // ... and its geometry twin, keyed separately because the ES loader really does
// probe the two extension families independently.
SpirvTranslationKeyInputs v = base;
v.demoteGeometryPointSize = true;
@@ -516,22 +518,22 @@ TEST_F(TranslationCacheTest, L1KeyMovesWithEveryInputThatMovesTheSpirv) {
// They cannot move a word of the generated SPIR-V, but they do shape the reflection the
// payload now carries, so they have to split the key. This is the group that would go
// stale first if the payload ever grew again without the key following it.
{ // glTransformFeedbackVaryings: shapes xfbVaryings / xfbStrides / gsStripTriangles
{ // glTransformFeedbackVaryings: shapes xfbVaryings / xfbStrides / gsStripTriangles
SpirvTranslationKeyInputs v = base;
v.requestedXfbVaryings = &xfbVaryings;
variants.emplace_back("requestedXfbVaryings", BuildSpirvTranslationKey(v));
}
{ // ... and its ORDER, which gl_NextBuffer / gl_SkipComponentsN make load-bearing
{ // ... and its ORDER, which gl_NextBuffer / gl_SkipComponentsN make load-bearing
SpirvTranslationKeyInputs v = base;
v.requestedXfbVaryings = &xfbVaryingsReordered;
variants.emplace_back("requestedXfbVaryings order", BuildSpirvTranslationKey(v));
}
{ // GL_INTERLEAVED_ATTRIBS vs GL_SEPARATE_ATTRIBS
{ // GL_INTERLEAVED_ATTRIBS vs GL_SEPARATE_ATTRIBS
SpirvTranslationKeyInputs v = base;
v.xfbBufferMode = GL_SEPARATE_ATTRIBS;
variants.emplace_back("xfbBufferMode", BuildSpirvTranslationKey(v));
}
{ // GL_MAX_DRAW_BUFFERS: decides whether the link is REJECTED at all
{ // GL_MAX_DRAW_BUFFERS: decides whether the link is REJECTED at all
SpirvTranslationKeyInputs v = base;
v.maxFragmentOutputColorNumber = 4;
variants.emplace_back("maxFragmentOutputColorNumber", BuildSpirvTranslationKey(v));
@@ -614,8 +616,7 @@ TEST_F(TranslationCacheTest, TwoBackendsCompilingTheSameGlslShareOneL1Entry) {
const auto [a, b] = BackendOnlyDifferentEnvs();
const String vs = kVertexSource;
const String fs = kFragmentSource;
const Vector<SpirvTranslationKeyInputs::Stage> stages{{GL_VERTEX_SHADER, vs},
{GL_FRAGMENT_SHADER, fs}};
const Vector<SpirvTranslationKeyInputs::Stage> stages{{GL_VERTEX_SHADER, vs}, {GL_FRAGMENT_SHADER, fs}};
SpirvTranslationKeyInputs onA = BaselineSpirvInputs(stages);
onA.frontendFingerprint = ComputeFrontendCompileEnvFingerprint(a);
@@ -632,9 +633,9 @@ TEST_F(TranslationCacheTest, TwoBackendsCompilingTheSameGlslShareOneL1Entry) {
// payload is the module AFTER SanitizeAndOptimizeBinary and the fp64 tail of that chain is
// exactly what this bit gates.
TEST_F(TranslationCacheTest, NativeFloat64IsOutOfTheFrontendFingerprintAndInsideTheL1Key) {
CompileEnv none; // no backend at all
CompileEnv emulated; // a backend without the feature
CompileEnv nativeEnv; // a backend with it
CompileEnv none; // no backend at all
CompileEnv emulated; // a backend without the feature
CompileEnv nativeEnv; // a backend with it
emulated.backend = BackendType::DirectVulkan;
nativeEnv.backend = BackendType::DirectVulkan;
nativeEnv.params.SupportsShaderFloat64 = true;
@@ -670,9 +671,9 @@ TEST_F(TranslationCacheTest, NativeFloat64IsOutOfTheFrontendFingerprintAndInside
// accessor direction is pinned too, because it is INVERTED relative to the params field
// and a swap of the arms would disable the device repair with every rendering test green.
TEST_F(TranslationCacheTest, PointSizeDemotionBitsAreOutOfTheFrontendFingerprintAndInsideTheL1Key) {
CompileEnv none; // no backend at all: never demote, standalone compiles stay standard
CompileEnv hosting; // a backend that hosts the built-in
CompileEnv demoting; // a backend that cannot
CompileEnv none; // no backend at all: never demote, standalone compiles stay standard
CompileEnv hosting; // a backend that hosts the built-in
CompileEnv demoting; // a backend that cannot
hosting.backend = BackendType::DirectVulkan;
demoting.backend = BackendType::DirectVulkan;
demoting.params.SupportsTessellationPointSize = false;
@@ -721,8 +722,7 @@ TEST_F(TranslationCacheTest, TheFrontendFingerprintMovesWithEveryFrontendLimit)
{"params.MaxDrawBuffers", [](CompileEnv& e) { e.params.MaxDrawBuffers += 1; }},
{"params.MaxVertexImageUniforms", [](CompileEnv& e) { e.params.MaxVertexImageUniforms += 1; }},
{"params.MaxTessControlImageUniforms", [](CompileEnv& e) { e.params.MaxTessControlImageUniforms += 1; }},
{"params.MaxTessEvaluationImageUniforms",
[](CompileEnv& e) { e.params.MaxTessEvaluationImageUniforms += 1; }},
{"params.MaxTessEvaluationImageUniforms", [](CompileEnv& e) { e.params.MaxTessEvaluationImageUniforms += 1; }},
{"params.MaxGeometryImageUniforms", [](CompileEnv& e) { e.params.MaxGeometryImageUniforms += 1; }},
{"params.MaxFragmentImageUniforms", [](CompileEnv& e) { e.params.MaxFragmentImageUniforms += 1; }},
{"params.MaxComputeImageUniforms", [](CompileEnv& e) { e.params.MaxComputeImageUniforms += 1; }},
@@ -735,8 +735,7 @@ TEST_F(TranslationCacheTest, TheFrontendFingerprintMovesWithEveryFrontendLimit)
// compiles to different SPIR-V under two different values, so each must split the
// key - one case per COMPONENT, because a per-axis difference is exactly the shape
// real drivers produce (z = 64 on ES against 1024 elsewhere).
{"params.MaxComputeTextureImageUnits",
[](CompileEnv& e) { e.params.MaxComputeTextureImageUnits += 1; }},
{"params.MaxComputeTextureImageUnits", [](CompileEnv& e) { e.params.MaxComputeTextureImageUnits += 1; }},
// wave4's 4fc3531d: glslang rejects gl_ClipDistance[i] past this at parse AND expands
// gl_MaxClipDistances from it, so it is both a compile gate and a baked constant.
{"params.MaxClipDistances", [](CompileEnv& e) { e.params.MaxClipDistances += 1; }},
@@ -751,8 +750,7 @@ TEST_F(TranslationCacheTest, TheFrontendFingerprintMovesWithEveryFrontendLimit)
[](CompileEnv& e) { e.params.MaxCombinedClipAndCullDistances += 1; }},
{"params.MaxTextureImageUnits", [](CompileEnv& e) { e.params.MaxTextureImageUnits += 1; }},
{"params.MaxVertexTextureImageUnits", [](CompileEnv& e) { e.params.MaxVertexTextureImageUnits += 1; }},
{"params.MaxCombinedTextureImageUnits",
[](CompileEnv& e) { e.params.MaxCombinedTextureImageUnits += 1; }},
{"params.MaxCombinedTextureImageUnits", [](CompileEnv& e) { e.params.MaxCombinedTextureImageUnits += 1; }},
{"params.MaxSamples", [](CompileEnv& e) { e.params.MaxSamples += 1; }},
{"maxComputeWorkGroupSize[0]", [](CompileEnv& e) { e.maxComputeWorkGroupSize[0] += 1; }},
{"maxComputeWorkGroupSize[1]", [](CompileEnv& e) { e.maxComputeWorkGroupSize[1] += 1; }},
@@ -881,8 +879,7 @@ TEST_F(TranslationCacheTest, AProgramServedFromTheMemoStillAnswersGetFragDataLoc
const Int memoLocation = MG_Impl::GLImpl::GetFragDataLocation(fromMemo, "fragColor");
EXPECT_EQ(parsedLocation, 0) << "the parsed program's own answer moved; this case is testing "
"the wrong thing";
EXPECT_EQ(memoLocation, parsedLocation)
<< "a program served from the L1 memo lost its fragment output location";
EXPECT_EQ(memoLocation, parsedLocation) << "a program served from the L1 memo lost its fragment output location";
// A name that is not an output must still be -1 from both, so the case cannot pass by
// making the accessor answer everything.
@@ -929,7 +926,7 @@ TEST_F(TranslationCacheTest, TheEscapeHatchDisablesL1Entirely) {
const SyncCompileScope sync;
const String fs = SwizzleLikeFragment("");
{ // prime the cache with the switch ON, so a later hit would be available
{ // prime the cache with the switch ON, so a later hit would be available
const CacheModeScope cacheOn(true);
(void)LinkProgramFromSources(kVertexSource, fs);
}
@@ -966,60 +963,60 @@ TEST_F(TranslationCacheTest, L2KeyMovesWithEveryGateThatSteersTheEsslChain) {
Vector<Pair<const char*, TranslationCacheKey>> variants;
{ // the module itself
{ // the module itself
EsslTranslationKeyInputs v = base;
v.spirv = &otherSpirv;
variants.emplace_back("spirv", BuildEsslTranslationKey(v));
}
{ // stage: gates LowerDrawParametersForEssl and SplitArrayVertexInputsForEssl (vertex)
{ // stage: gates LowerDrawParametersForEssl and SplitArrayVertexInputsForEssl (vertex)
// and LegalizeFragmentOutputIndexingForEssl (fragment)
EsslTranslationKeyInputs v = base;
v.shaderType = GL_VERTEX_SHADER;
variants.emplace_back("shaderType", BuildEsslTranslationKey(v));
}
{ // arms LowerViewportIndexForEssl
{ // arms LowerViewportIndexForEssl
EsslTranslationKeyInputs v = base;
v.viewportIndexLoweringArmed = true;
variants.emplace_back("viewportIndexLoweringArmed", BuildEsslTranslationKey(v));
}
{ // arms EmulateSubgroupsPass on the ESSL path
{ // arms EmulateSubgroupsPass on the ESSL path
EsslTranslationKeyInputs v = base;
v.subgroupEmulationArmed = true;
variants.emplace_back("subgroupEmulationArmed", BuildEsslTranslationKey(v));
}
{ // the emulation's scratch budget decides whether it declines
{ // the emulation's scratch budget decides whether it declines
EsslTranslationKeyInputs v = base;
v.subgroupEmulationScratchBytes = 32768;
variants.emplace_back("subgroupEmulationScratchBytes", BuildEsslTranslationKey(v));
}
{ // arms FixIterationRPBarrierPass on the ESSL path
{ // arms FixIterationRPBarrierPass on the ESSL path
EsslTranslationKeyInputs v = base;
v.iterationRPBarrierFixArmed = true;
variants.emplace_back("iterationRPBarrierFixArmed", BuildEsslTranslationKey(v));
}
{ // the subgroup emulation reads its scratch through atomic loads
{ // the subgroup emulation reads its scratch through atomic loads
EsslTranslationKeyInputs v = base;
v.subgroupScratchAtomicReads = true;
variants.emplace_back("subgroupScratchAtomicReads", BuildEsslTranslationKey(v));
}
{ // arms DeferGeometryEmitsForEssl
{ // arms DeferGeometryEmitsForEssl
EsslTranslationKeyInputs v = base;
v.deferGeometryEmitsArmed = true;
variants.emplace_back("deferGeometryEmitsArmed", BuildEsslTranslationKey(v));
}
{ // arms EmulateNoPerspectiveForEssl
{ // arms EmulateNoPerspectiveForEssl
EsslTranslationKeyInputs v = base;
v.supportsNoperspectiveInterpolation = true;
variants.emplace_back("supportsNoperspectiveInterpolation", BuildEsslTranslationKey(v));
}
{ // arms WidenImageFormatsForEssl - a driver WITH GL_NV_image_formats keeps the declared
{ // arms WidenImageFormatsForEssl - a driver WITH GL_NV_image_formats keeps the declared
// rg32f/r8ui/... image formats, one without has them re-declared in a core carrier and
// every access to them masked, so the two get materially different ESSL from one module.
EsslTranslationKeyInputs v = base;
v.supportsExtendedImageFormats = true;
variants.emplace_back("supportsExtendedImageFormats", BuildEsslTranslationKey(v));
}
{ // arms AND parameterizes ClampMultisampleFetchesForEssl
{ // arms AND parameterizes ClampMultisampleFetchesForEssl
EsslTranslationKeyInputs v = base;
v.maxColorTextureSamples = 1;
variants.emplace_back("maxColorTextureSamples", BuildEsslTranslationKey(v));
@@ -1034,38 +1031,38 @@ TEST_F(TranslationCacheTest, L2KeyMovesWithEveryGateThatSteersTheEsslChain) {
v.maxDepthTextureSamples = 1;
variants.emplace_back("maxDepthTextureSamples", BuildEsslTranslationKey(v));
}
{ // the ceiling the three above are compared against
{ // the ceiling the three above are compared against
EsslTranslationKeyInputs v = base;
v.advertisedMaxSamples = 8;
variants.emplace_back("advertisedMaxSamples", BuildEsslTranslationKey(v));
}
{ // the argument to FlattenXfbInterfaceBlocksForEssl
{ // the argument to FlattenXfbInterfaceBlocksForEssl
EsslTranslationKeyInputs v = base;
v.xfbCaptureBlockNames = &xfbBlocks;
variants.emplace_back("xfbCaptureBlockNames", BuildEsslTranslationKey(v));
}
{ // the argument to BakeImageFormatsForEssl - live glBindImageTexture state
{ // the argument to BakeImageFormatsForEssl - live glBindImageTexture state
EsslTranslationKeyInputs v = base;
v.glFormatByUniformName = &imageFormats;
variants.emplace_back("glFormatByUniformName", BuildEsslTranslationKey(v));
}
{ // SpvcSession::SetShaderStorageBlockBinding
{ // SpvcSession::SetShaderStorageBlockBinding
EsslTranslationKeyInputs v = base;
v.storageBlockBindingOverrides = &storageBindings;
variants.emplace_back("storageBlockBindingOverrides", BuildEsslTranslationKey(v));
}
{ // SPVC_COMPILER_OPTION_GLSL_VERSION (ResolveBackendEsslVersion)
{ // SPVC_COMPILER_OPTION_GLSL_VERSION (ResolveBackendEsslVersion)
EsslTranslationKeyInputs v = base;
v.esslVersion = 300;
variants.emplace_back("esslVersion", BuildEsslTranslationKey(v));
}
{ // SpvcSession::SetAtomicCounterBlockBindings - printed into the layout(binding=)
{ // SpvcSession::SetAtomicCounterBlockBindings - printed into the layout(binding=)
// qualifier of every synthesized counter block, so it changes the emitted text.
EsslTranslationKeyInputs v = base;
v.atomicCounterEsslBindingTop = 6;
variants.emplace_back("atomicCounterEsslBindingTop", BuildEsslTranslationKey(v));
}
{ // the two arguments to UniquifyIoBlockNamesForEssl. Separate cases, because a stage
{ // the two arguments to UniquifyIoBlockNamesForEssl. Separate cases, because a stage
// that CONSUMES a block renames it after the previous stage while one that PRODUCES
// it renames after itself - so the same block name legitimately maps to different
// spellings in the two maps, and a key that folded them together would let a
@@ -1079,12 +1076,12 @@ TEST_F(TranslationCacheTest, L2KeyMovesWithEveryGateThatSteersTheEsslChain) {
v.outputBlockRenames = &ioBlockRenames;
variants.emplace_back("outputBlockRenames", BuildEsslTranslationKey(v));
}
{ // ...and a DIFFERENT target spelling for the same block name must not share either.
{ // ...and a DIFFERENT target spelling for the same block name must not share either.
EsslTranslationKeyInputs v = base;
v.outputBlockRenames = &otherIoBlockRenames;
variants.emplace_back("outputBlockRenames(other target)", BuildEsslTranslationKey(v));
}
{ // the two arguments to StripIoBlockLocationsForEssl, and separate cases for the same
{ // the two arguments to StripIoBlockLocationsForEssl, and separate cases for the same
// reason the rename maps are: a stage strips the blocks it CONSUMES only when the
// producer is in this program and the ones it PRODUCES only when the consumer is, so
// the two directions are independently armed and a key that folded them together
@@ -1218,7 +1215,8 @@ TEST_F(TranslationCacheTest, ConcurrentLookupsOverOverlappingKeysAgreeWithTheSer
}
});
}
for (std::thread& thread : threads) thread.join();
for (std::thread& thread : threads)
thread.join();
EXPECT_EQ(mismatches.load(), 0) << "a worker was handed a payload belonging to another key";
EXPECT_EQ(nulls.load(), 0);
@@ -1259,7 +1257,8 @@ TEST_F(TranslationCacheTest, ConcurrentLookupsStaySafeWhileEvictionChurns) {
}
});
}
for (std::thread& thread : threads) thread.join();
for (std::thread& thread : threads)
thread.join();
EXPECT_EQ(mismatches.load(), 0);
EXPECT_LE(cache.EntryCount(), 4u);
@@ -1274,7 +1273,8 @@ TEST_F(TranslationCacheTest, ConcurrentLinksOfSharedSourcesProduceIdenticalSpirv
constexpr Int kProgramsPerVariant = 8;
Vector<String> sources;
for (Int v = 0; v < kVariants; ++v) sources.push_back(SwizzleLikeFragment(v == 0 ? "" : (v == 1 ? "i" : "u")));
for (Int v = 0; v < kVariants; ++v)
sources.push_back(SwizzleLikeFragment(v == 0 ? "" : (v == 1 ? "i" : "u")));
Vector<GLuint> programs;
Vector<Int> variantOf;
@@ -1328,9 +1328,13 @@ namespace {
return "#version 460\n"
"in vec3 vPos;\n"
"layout(location = 0) out vec4 fragColor;\n"
"uniform vec3 uTint_" + tag + ";\n"
"uniform vec3 uTint_" +
tag +
";\n"
"void main() {\n"
" fragColor = vec4(uTint_" + tag + " * vPos, 1.0);\n"
" fragColor = vec4(uTint_" +
tag +
" * vPos, 1.0);\n"
"}\n";
}
@@ -1360,14 +1364,11 @@ TEST_F(TranslationCacheTest, TheParseVerdictKeyMovesWithEveryInput) {
const TranslationCacheKey baseline = BuildShaderParseVerdictKey(BaselineParseVerdictInputs(source));
const Vector<Pair<const char*, std::function<void(ShaderParseVerdictKeyInputs&, const String&)>>> mutations{
{"frontendFingerprint",
[](ShaderParseVerdictKeyInputs& i, const String&) { i.frontendFingerprint ^= 1ull; }},
{"shaderType",
[](ShaderParseVerdictKeyInputs& i, const String&) { i.shaderType = GL_VERTEX_SHADER; }},
{"frontendFingerprint", [](ShaderParseVerdictKeyInputs& i, const String&) { i.frontendFingerprint ^= 1ull; }},
{"shaderType", [](ShaderParseVerdictKeyInputs& i, const String&) { i.shaderType = GL_VERTEX_SHADER; }},
{"preprocessedSource",
[](ShaderParseVerdictKeyInputs& i, const String& other) { i.preprocessedSource = other; }},
{"shaderCompileFlags",
[](ShaderParseVerdictKeyInputs& i, const String&) { i.shaderCompileFlags = 1u; }},
{"shaderCompileFlags", [](ShaderParseVerdictKeyInputs& i, const String&) { i.shaderCompileFlags = 1u; }},
};
Vector<TranslationCacheKey> seen{baseline};
@@ -165,8 +165,7 @@ TEST_F(UniquifyIoBlockNamesTest, ProbeIgnoresAStageWhoseBlocksAlreadyHaveDistinc
}
TEST_F(UniquifyIoBlockNamesTest, ProbeNeverReportsTheBuiltinBlock) {
const Vector<Uint32> input =
CompileToSpirv(GL_TESS_EVALUATION_SHADER, kBuiltinBlockOnlyTessEvalSource);
const Vector<Uint32> input = CompileToSpirv(GL_TESS_EVALUATION_SHADER, kBuiltinBlockOnlyTessEvalSource);
ASSERT_FALSE(input.empty());
std::set<String> colliding;
@@ -196,17 +195,15 @@ TEST_F(UniquifyIoBlockNamesTest, RenamesTheTwoBlocksApartInTheEmittedEssl) {
std::set<String> renamed;
Vector<Uint32> output;
ASSERT_TRUE(ShaderCompiler::UniquifyIoBlockNamesForEssl(input, inputRenames, outputRenames, renamed,
output, true));
ASSERT_TRUE(ShaderCompiler::UniquifyIoBlockNamesForEssl(input, inputRenames, outputRenames, renamed, output, true));
ASSERT_FALSE(output.empty());
EXPECT_EQ(renamed, (std::set<String>{"TCSOutputBlock"}));
const String dis = Disassemble(output);
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
ASSERT_TRUE(tools.Validate(output)) << dis;
EXPECT_EQ(dis.find("\"TCSOutputBlock\""), String::npos)
<< "the colliding name is still on a block struct:\n"
<< dis;
EXPECT_EQ(dis.find("\"TCSOutputBlock\""), String::npos) << "the colliding name is still on a block struct:\n"
<< dis;
EXPECT_NE(dis.find("\"TCSOutputBlock_mgio1\""), String::npos) << dis;
EXPECT_NE(dis.find("\"TCSOutputBlock_mgio2\""), String::npos) << dis;
@@ -231,8 +228,7 @@ TEST_F(UniquifyIoBlockNamesTest, RenamesOnlyTheDirectionTheCallerPlanned) {
std::set<String> renamed;
Vector<Uint32> output;
ASSERT_TRUE(
ShaderCompiler::UniquifyIoBlockNamesForEssl(input, inputRenames, {}, renamed, output, true));
ASSERT_TRUE(ShaderCompiler::UniquifyIoBlockNamesForEssl(input, inputRenames, {}, renamed, output, true));
ASSERT_FALSE(output.empty());
EXPECT_EQ(renamed, (std::set<String>{"TCSOutputBlock"}));
@@ -67,8 +67,7 @@ namespace {
EXPECT_TRUE(programResult) << (programResult ? String{} : programResult.error().log);
if (!programResult) return {};
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_FRAGMENT_SHADER},
.program = *programResult.value()};
ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_FRAGMENT_SHADER}, .program = *programResult.value()};
auto binaryResult = ShaderCompiler::GetSpirvBinaryFromProgram(binaryAttrib);
EXPECT_TRUE(binaryResult) << (binaryResult ? String{} : binaryResult.error().log);
if (!binaryResult || binaryResult->empty()) return {};
@@ -396,26 +395,22 @@ TEST(WidenImageFormats, TwentySixNonCoreFormatsHaveALosslessCoreCarrier) {
{0x8F98, 0x8D76, 1, "GL_R16_SNORM -> GL_RGBA16UI"},
};
for (const Case& testCase : cases) {
EXPECT_EQ(ShaderCompiler::WidenedCoreEsslImageFormat(testCase.requested), testCase.carrier)
<< testCase.name;
EXPECT_EQ(ShaderCompiler::ImageFormatChannelCount(testCase.requested), testCase.channels)
<< testCase.name;
EXPECT_EQ(ShaderCompiler::WidenedCoreEsslImageFormat(testCase.requested), testCase.carrier) << testCase.name;
EXPECT_EQ(ShaderCompiler::ImageFormatChannelCount(testCase.requested), testCase.channels) << testCase.name;
// Every carrier is one of the thirteen ES has in core, or the widening would have moved
// the problem rather than solved it - and every carrier has four channels, or the mask
// selectors would address components that are not there.
EXPECT_TRUE(ShaderCompiler::GLInternalFormatIsCoreEsslImageFormat(testCase.carrier))
<< testCase.name;
EXPECT_TRUE(ShaderCompiler::GLInternalFormatIsCoreEsslImageFormat(testCase.carrier)) << testCase.name;
EXPECT_EQ(ShaderCompiler::ImageFormatChannelCount(testCase.carrier), 4u) << testCase.name;
}
}
TEST(WidenImageFormats, CoreFormatsAreRefused) {
// The thirteen GLSL ES already has: nothing to carry.
for (const Uint coreFormat : {0x8814u /*RGBA32F*/, 0x881Au /*RGBA16F*/, 0x822Eu /*R32F*/,
0x8058u /*RGBA8*/, 0x8F97u /*RGBA8_SNORM*/, 0x8D82u /*RGBA32I*/,
0x8D88u /*RGBA16I*/, 0x8D8Eu /*RGBA8I*/, 0x8235u /*R32I*/,
0x8D70u /*RGBA32UI*/, 0x8D76u /*RGBA16UI*/, 0x8D7Cu /*RGBA8UI*/,
0x8236u /*R32UI*/}) {
for (const Uint coreFormat :
{0x8814u /*RGBA32F*/, 0x881Au /*RGBA16F*/, 0x822Eu /*R32F*/, 0x8058u /*RGBA8*/, 0x8F97u /*RGBA8_SNORM*/,
0x8D82u /*RGBA32I*/, 0x8D88u /*RGBA16I*/, 0x8D8Eu /*RGBA8I*/, 0x8235u /*R32I*/, 0x8D70u /*RGBA32UI*/,
0x8D76u /*RGBA16UI*/, 0x8D7Cu /*RGBA8UI*/, 0x8236u /*R32UI*/}) {
EXPECT_EQ(ShaderCompiler::WidenedCoreEsslImageFormat(coreFormat), 0u)
<< "core format 0x" << std::hex << coreFormat;
}
@@ -454,8 +449,7 @@ TEST(WidenImageFormats, OnlyTheNormalizedFormatsCarryCodesAndTheirDenominatorsAr
EXPECT_TRUE(ShaderCompiler::NormalizedImageCarrierCodes(testCase.format, channelMax, isSigned))
<< testCase.name;
for (Uint channel = 0; channel < 4; ++channel) {
EXPECT_EQ(channelMax[channel], testCase.channelMax[channel])
<< testCase.name << " channel " << channel;
EXPECT_EQ(channelMax[channel], testCase.channelMax[channel]) << testCase.name << " channel " << channel;
}
EXPECT_EQ(isSigned, testCase.isSigned) << testCase.name;
}
@@ -463,9 +457,9 @@ TEST(WidenImageFormats, OnlyTheNormalizedFormatsCarryCodesAndTheirDenominatorsAr
// Everything else keeps its own component type in the carrier, so nothing is converted: an
// rg8's carrier channel really is an 8-bit unsigned normalized one, and an rgb10_a2ui's
// channel really does hold the integer the shader stored.
for (const Uint direct : {0x8230u /*RG32F*/, 0x8229u /*R8*/, 0x8F94u /*R8_SNORM*/,
0x8232u /*R8UI*/, 0x8C3Au /*R11F_G11F_B10F*/, 0x906Fu /*RGB10_A2UI*/,
0x8814u /*RGBA32F*/, 0x8051u /*RGB8, not an image format*/}) {
for (const Uint direct :
{0x8230u /*RG32F*/, 0x8229u /*R8*/, 0x8F94u /*R8_SNORM*/, 0x8232u /*R8UI*/, 0x8C3Au /*R11F_G11F_B10F*/,
0x906Fu /*RGB10_A2UI*/, 0x8814u /*RGBA32F*/, 0x8051u /*RGB8, not an image format*/}) {
Uint32 channelMax[4] = {7u, 7u, 7u, 7u};
bool isSigned = true;
EXPECT_FALSE(ShaderCompiler::NormalizedImageCarrierCodes(direct, channelMax, isSigned))
@@ -516,8 +510,7 @@ TEST(WidenImageFormats, TwoChannelFloatImageBecomesRgba32fWithBothAccessesMasked
const VectorShuffle* loadMask = FindShuffleOver(shuffles, readIds.front());
ASSERT_NE(loadMask, nullptr) << "the imageLoad result is consumed unmasked";
EXPECT_TRUE(HasComponents(*loadMask, {0u, 1u, 6u, 7u}));
EXPECT_NE(loadMask->resultId, readIds.front())
<< "the mask must be a separate value, or it would feed itself";
EXPECT_NE(loadMask->resultId, readIds.front()) << "the mask must be a separate value, or it would feed itself";
}
// The three-channel case, which no format exercised before r11f_g11f_b10f was carried: only ALPHA
@@ -600,10 +593,9 @@ TEST(WidenImageFormats, PackedFloatImageOnlyReachesEsslThroughTheCarrier) {
ASSERT_FALSE(spirv.empty());
const EsslAttempt before = EmitEssl(spirv);
EXPECT_FALSE(before.succeeded)
<< "SPIRV-Cross printed r11f_g11f_b10f for an ES target; the widening's premise has "
"changed:\n"
<< before.text;
EXPECT_FALSE(before.succeeded) << "SPIRV-Cross printed r11f_g11f_b10f for an ES target; the widening's premise has "
"changed:\n"
<< before.text;
Vector<Uint32> widened;
ASSERT_TRUE(ShaderCompiler::WidenImageFormatsForEssl(spirv, widened, /*onlyFormatsSpirvCrossRefusesToPrint=*/false,
@@ -752,8 +744,7 @@ TEST(WidenImageFormats, OnlyTheThirtyTwoBitTwoChannelFormatsSplitAsBufferImages)
{0x823C, 0x8236, "GL_RG32UI -> GL_R32UI"},
};
for (const Case& testCase : cases) {
EXPECT_EQ(ShaderCompiler::SplitCoreEsslBufferImageFormat(testCase.format), testCase.base)
<< testCase.name;
EXPECT_EQ(ShaderCompiler::SplitCoreEsslBufferImageFormat(testCase.format), testCase.base) << testCase.name;
EXPECT_TRUE(ShaderCompiler::GLInternalFormatIsCoreEsslImageFormat(testCase.base)) << testCase.name;
EXPECT_EQ(ShaderCompiler::ImageFormatChannelCount(testCase.base), 1u) << testCase.name;
}
@@ -762,8 +753,7 @@ TEST(WidenImageFormats, OnlyTheThirtyTwoBitTwoChannelFormatsSplitAsBufferImages)
0x8F95u /*RG8_SNORM*/, 0x822Cu /*RG16*/, 0x8237u /*RG8I*/, 0x8238u /*RG8UI*/,
// Already core, or four-channel, or not an image format at all.
0x8814u /*RGBA32F*/, 0x822Eu /*R32F*/, 0x8051u /*RGB8*/, 0u}) {
EXPECT_EQ(ShaderCompiler::SplitCoreEsslBufferImageFormat(refused), 0u)
<< "format 0x" << std::hex << refused;
EXPECT_EQ(ShaderCompiler::SplitCoreEsslBufferImageFormat(refused), 0u) << "format 0x" << std::hex << refused;
}
}
@@ -856,7 +846,7 @@ TEST(WidenImageFormats, TheExtensionNarrowsTheWideningToWhatSpirvCrossWillNotPri
ASSERT_TRUE(ShaderCompiler::SpirvCrossCanPrintEsslImageFormat(0x8230 /*GL_RG32F*/));
ASSERT_FALSE(ShaderCompiler::SpirvCrossCanPrintEsslImageFormat(0x8232 /*GL_R8UI*/));
{ // rg32f: printable, so the narrow mode leaves it exactly as declared.
{ // rg32f: printable, so the narrow mode leaves it exactly as declared.
const Vector<Uint32> spirv = CompileFragment(kRg32fLoadStore);
ASSERT_FALSE(spirv.empty());
EXPECT_TRUE(ShaderCompiler::DeclaresWidenableImageFormat(spirv, false));
@@ -872,15 +862,15 @@ TEST(WidenImageFormats, TheExtensionNarrowsTheWideningToWhatSpirvCrossWillNotPri
EXPECT_EQ(CollectVectorShuffles(widened).size(), CollectVectorShuffles(spirv).size());
}
}
{ // r8ui: unprintable, so the narrow mode still carries it - and must mask it exactly as
{ // r8ui: unprintable, so the narrow mode still carries it - and must mask it exactly as
// the wide mode does, because the storage and the bind widen with it either way.
const Vector<Uint32> spirv = CompileFragment(kR8uiLoadStore);
ASSERT_FALSE(spirv.empty());
EXPECT_TRUE(ShaderCompiler::DeclaresWidenableImageFormat(spirv, true));
Vector<Uint32> widened;
ASSERT_TRUE(ShaderCompiler::WidenImageFormatsForEssl(
spirv, widened, /*onlyFormatsSpirvCrossRefusesToPrint=*/true, true));
ASSERT_TRUE(ShaderCompiler::WidenImageFormatsForEssl(spirv, widened,
/*onlyFormatsSpirvCrossRefusesToPrint=*/true, true));
ASSERT_FALSE(widened.empty());
EXPECT_TRUE(Validates(widened));
const auto types = CollectStorageImageTypes(widened);
@@ -904,7 +894,7 @@ TEST(WidenImageFormats, CoreFormatModuleIsHandedBackUntouched) {
Vector<Uint32> widened;
ShaderCompiler::WidenImageFormatsForEssl(spirv, widened, /*onlyFormatsSpirvCrossRefusesToPrint=*/false,
/*enableSpirvValidation=*/true);
/*enableSpirvValidation=*/true);
if (!widened.empty()) {
EXPECT_EQ(CollectVectorShuffles(widened).size(), CollectVectorShuffles(spirv).size())
<< "a core-format module must gain no masks";
@@ -967,12 +957,10 @@ TEST(WidenImageFormats, NormalizedImageBecomesAUimageWhoseAccessesConvertItsCode
EXPECT_EQ(after.text.find("rg16"), String::npos)
<< "the token no ES driver accepts is still in the emitted source:\n"
<< after.text;
EXPECT_NE(after.text.find("65535.0"), String::npos)
<< "the unsigned-normalized denominator is 2^16 - 1:\n"
<< after.text;
EXPECT_EQ(after.text.find("32767.0"), String::npos)
<< "an unsigned format must not take the SIGNED denominator:\n"
<< after.text;
EXPECT_NE(after.text.find("65535.0"), String::npos) << "the unsigned-normalized denominator is 2^16 - 1:\n"
<< after.text;
EXPECT_EQ(after.text.find("32767.0"), String::npos) << "an unsigned format must not take the SIGNED denominator:\n"
<< after.text;
}
// The signed half, which needs two things the unsigned one does not: the code is sign-extended
@@ -1010,12 +998,9 @@ TEST(WidenImageFormats, SignedNormalizedImageSignExtendsItsCodeAndClampsAtMinusO
EXPECT_NE(after.text.find("uimage2D"), String::npos) << after.text;
EXPECT_NE(after.text.find("rgba16ui"), String::npos) << after.text;
EXPECT_EQ(after.text.find("rgba16_snorm"), String::npos) << after.text;
EXPECT_NE(after.text.find("32767.0"), String::npos)
<< "the signed-normalized denominator is 2^15 - 1:\n"
<< after.text;
EXPECT_NE(after.text.find("-1.0"), String::npos)
<< "GL clamps the signed decode at -1:\n"
<< after.text;
EXPECT_NE(after.text.find("32767.0"), String::npos) << "the signed-normalized denominator is 2^15 - 1:\n"
<< after.text;
EXPECT_NE(after.text.find("-1.0"), String::npos) << "GL clamps the signed decode at -1:\n" << after.text;
}
// rgb10_a2, whose four channels are 10, 10, 10 and 2 bits: the only entry where one denominator
@@ -1038,8 +1023,6 @@ TEST(WidenImageFormats, TenTenTenTwoImageTakesAPerChannelDenominator) {
const EsslAttempt after = EmitEssl(widened);
ASSERT_TRUE(after.succeeded) << after.error;
EXPECT_NE(after.text.find("1023.0"), String::npos) << after.text;
EXPECT_NE(after.text.find("3.0"), String::npos)
<< "the two-bit alpha saturates at 3, not at 1023:\n"
<< after.text;
EXPECT_NE(after.text.find("3.0"), String::npos) << "the two-bit alpha saturates at 3, not at 1023:\n" << after.text;
EXPECT_EQ(after.text.find("rgb10_a2)"), String::npos) << after.text;
}
@@ -68,14 +68,16 @@ void main() { color = vec4(1.0); }
String ValidationError(const Vector<Uint32>& spirv) {
spvtools::SpirvTools tools(SPV_ENV_VULKAN_1_1);
String error;
tools.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&,
const char* message) { error += message != nullptr ? message : ""; });
tools.SetMessageConsumer([&](spv_message_level_t, const char*, const spv_position_t&, const char* message) {
error += message != nullptr ? message : "";
});
return tools.Validate(spirv) ? String{} : (error.empty() ? String{"invalid"} : error);
}
SizeT CountOccurrences(const String& text, const String& needle) {
SizeT count = 0;
for (SizeT at = text.find(needle); at != String::npos; at = text.find(needle, at + needle.size())) ++count;
for (SizeT at = text.find(needle); at != String::npos; at = text.find(needle, at + needle.size()))
++count;
return count;
}
@@ -69,17 +69,14 @@ namespace {
return context;
}
void MakeCurrent(EGLContext context) {
ASSERT_TRUE(State->MakeCurrent(Display, Surface, Surface, context));
}
void MakeCurrent(EGLContext context) { ASSERT_TRUE(State->MakeCurrent(Display, Surface, Surface, context)); }
void Release() {
if (State) State->MakeCurrent(EGL_NO_DISPLAY, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
}
static void DrainErrors() {
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {}
}
EGLStateContext* State = nullptr;
+1 -2
View File
@@ -34,8 +34,7 @@ namespace {
class DebugTest : public ::testing::Test {
protected:
static void DrainPendingGlErrors() {
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {}
}
static void ExpectSingleGlError(GLenum expected) {
@@ -56,7 +56,8 @@ namespace {
storage.MarkDirtyRegion(0, offset, extent);
for (Int z = offset.z(); z < offset.z() + extent.z(); ++z)
for (Int y = offset.y(); y < offset.y() + extent.y(); ++y)
for (Int x = offset.x(); x < offset.x() + extent.x(); ++x) written[Index(x, y, z)] = true;
for (Int x = offset.x(); x < offset.x() + extent.x(); ++x)
written[Index(x, y, z)] = true;
}
void Expect(const char* what) const {
@@ -75,7 +76,8 @@ namespace {
ASSERT_LE(box.hi.z(), size.z());
for (Int z = box.lo.z(); z < box.hi.z(); ++z)
for (Int y = box.lo.y(); y < box.hi.y(); ++y)
for (Int x = box.lo.x(); x < box.hi.x(); ++x) ++covered[Index(x, y, z)];
for (Int x = box.lo.x(); x < box.hi.x(); ++x)
++covered[Index(x, y, z)];
}
SizeT missing = 0, extra = 0, twice = 0;
MipmapDirtyRegion bounds{size, IntVec3{0, 0, 0}};
@@ -149,7 +151,8 @@ namespace {
TEST(MipmapFootprintTest, MoreBoxesThanTheListKeeps) {
Level level({40, 40, 1});
for (int j = 0; j < 10; ++j)
for (int i = 0; i < 10; ++i) level.Write({4 * i + 1, 4 * j + 1, 0}, {2, 2, 1});
for (int i = 0; i < 10; ++i)
level.Write({4 * i + 1, 4 * j + 1, 0}, {2, 2, 1});
level.Expect("a hundred 2x2");
std::vector<MipmapDirtyRegion> footprint;
level.storage.GetDirtyFootprint(0, footprint);
@@ -159,7 +162,8 @@ namespace {
// Scanlines of one width merge exactly and stay one box without ever starting the log.
TEST(MipmapFootprintTest, AbuttingScanlinesStayOneBox) {
Level level({32, 32, 1});
for (int y = 4; y < 20; ++y) level.Write({3, y, 0}, {10, 1, 1});
for (int y = 4; y < 20; ++y)
level.Write({3, y, 0}, {10, 1, 1});
level.Expect("scanlines");
std::vector<MipmapDirtyRegion> footprint;
level.storage.GetDirtyFootprint(0, footprint);
@@ -59,13 +59,10 @@ namespace {
MG_State::pGLContext = MakeUnique<MG_State::GLState::GLContext>();
}
void TearDown() override {
EXPECT_EQ(GetError(), GL_NO_ERROR) << "test left an unconsumed GL error behind";
}
void TearDown() override { EXPECT_EQ(GetError(), GL_NO_ERROR) << "test left an unconsumed GL error behind"; }
static void DrainErrors() {
for (int i = 0; i < 16 && GetError() != GL_NO_ERROR; ++i) {
}
for (int i = 0; i < 16 && GetError() != GL_NO_ERROR; ++i) {}
}
static GLuint MakeBuffer(GLenum target, GLsizeiptr size) {
@@ -119,10 +116,8 @@ namespace {
{"glBindBuffersBase with a reserved-but-uncreated name",
[&] { BindBuffersBase(GL_UNIFORM_BUFFER, 0, 2, mixedBuffers); }, GL_INVALID_OPERATION},
{"glBindBuffersRange with a reserved-but-uncreated name",
[&] { BindBuffersRange(GL_UNIFORM_BUFFER, 0, 2, mixedBuffers, offsets, sizes); },
GL_INVALID_OPERATION},
{"glBindSamplers with a deleted sampler name", [&] { BindSamplers(0, 1, samplers); },
GL_INVALID_OPERATION},
[&] { BindBuffersRange(GL_UNIFORM_BUFFER, 0, 2, mixedBuffers, offsets, sizes); }, GL_INVALID_OPERATION},
{"glBindSamplers with a deleted sampler name", [&] { BindSamplers(0, 1, samplers); }, GL_INVALID_OPERATION},
});
// ARB_multi_bind defines these as a LOOP of single binds, so the bad entry costs its own
@@ -294,8 +289,8 @@ namespace {
RunRows({
{"glDispatchComputeIndirect(-2)", [] { DispatchComputeIndirect(-2); }, GL_INVALID_VALUE},
{"glDispatchComputeIndirect(3)", [] { DispatchComputeIndirect(3); }, GL_INVALID_VALUE},
{"glDispatchComputeIndirect(16) past the end of a 24-byte buffer",
[] { DispatchComputeIndirect(16); }, GL_INVALID_OPERATION},
{"glDispatchComputeIndirect(16) past the end of a 24-byte buffer", [] { DispatchComputeIndirect(16); },
GL_INVALID_OPERATION},
{"glDispatchComputeIndirect(0) with nothing bound",
[&] {
BindBuffer(GL_DISPATCH_INDIRECT_BUFFER, 0);
@@ -526,10 +521,10 @@ void main() { g_color = vec4(1); }
{"glDrawElementsInstanced with an unaccepted mode",
[] { DrawElementsInstanced(kBadMode, 3, GL_UNSIGNED_INT, nullptr, 4); }, GL_INVALID_ENUM},
{"glDrawArrays with an unaccepted mode", [] { DrawArrays(kBadMode, 0, 3); }, GL_INVALID_ENUM},
{"glDrawElements with an unaccepted mode",
[] { DrawElements(kBadMode, 3, GL_UNSIGNED_INT, nullptr); }, GL_INVALID_ENUM},
{"glMultiDrawArrays with an unaccepted mode",
[] { MultiDrawArrays(kBadMode, nullptr, nullptr, 0); }, GL_INVALID_ENUM},
{"glDrawElements with an unaccepted mode", [] { DrawElements(kBadMode, 3, GL_UNSIGNED_INT, nullptr); },
GL_INVALID_ENUM},
{"glMultiDrawArrays with an unaccepted mode", [] { MultiDrawArrays(kBadMode, nullptr, nullptr, 0); },
GL_INVALID_ENUM},
{"glDrawRangeElements with an unaccepted mode",
[] { DrawRangeElements(kBadMode, 0, 2, 3, GL_UNSIGNED_INT, nullptr); }, GL_INVALID_ENUM},
{"glDrawElementsIndirect with an unaccepted mode",
@@ -560,9 +555,7 @@ void main() { g_color = vec4(1); }
RunRows({
{"glBlitFramebuffer with a mask bit outside COLOR|DEPTH|STENCIL",
[] {
BlitFramebuffer(0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT | kForeignBit, GL_NEAREST);
},
[] { BlitFramebuffer(0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT | kForeignBit, GL_NEAREST); },
GL_INVALID_VALUE},
{"glBlitFramebuffer with a filter that is neither GL_NEAREST nor GL_LINEAR",
[] { BlitFramebuffer(0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT, GL_NONE); }, GL_INVALID_ENUM},
@@ -572,13 +565,11 @@ void main() { g_color = vec4(1); }
},
GL_INVALID_OPERATION},
{"glBlitFramebuffer of depth with GL_LINEAR",
[] { BlitFramebuffer(0, 0, 16, 16, 0, 0, 16, 16, GL_DEPTH_BUFFER_BIT, GL_LINEAR); },
GL_INVALID_OPERATION},
[] { BlitFramebuffer(0, 0, 16, 16, 0, 0, 16, 16, GL_DEPTH_BUFFER_BIT, GL_LINEAR); }, GL_INVALID_OPERATION},
// The DSA form has to answer identically.
{"glBlitNamedFramebuffer with a mask bit outside COLOR|DEPTH|STENCIL",
[] {
BlitNamedFramebuffer(0, 0, 0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT | kForeignBit,
GL_NEAREST);
BlitNamedFramebuffer(0, 0, 0, 0, 16, 16, 0, 0, 16, 16, GL_COLOR_BUFFER_BIT | kForeignBit, GL_NEAREST);
},
GL_INVALID_VALUE},
{"glBlitNamedFramebuffer with a bad filter",
@@ -586,8 +577,8 @@ void main() { g_color = vec4(1); }
GL_INVALID_ENUM},
{"glBlitNamedFramebuffer of depth+stencil with GL_LINEAR",
[] {
BlitNamedFramebuffer(0, 0, 0, 0, 16, 16, 0, 0, 16, 16,
GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT, GL_LINEAR);
BlitNamedFramebuffer(0, 0, 0, 0, 16, 16, 0, 0, 16, 16, GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT,
GL_LINEAR);
},
GL_INVALID_OPERATION},
});
+13 -11
View File
@@ -39,13 +39,12 @@
using namespace MobileGL;
namespace {
class RenderStateTest: public ::testing::Test {
class RenderStateTest : public ::testing::Test {
protected:
// GL error flags are sticky per code and the context outlives an individual test in this
// binary, so a pending error from an earlier case would be handed to the next GetError().
static void DrainPendingGlErrors() {
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {}
}
static void ExpectSingleGlError(GLenum expected) {
@@ -675,19 +674,22 @@ TEST_F(RenderStateTest, ClearColorStartsAtTransparentBlack) {
const GLenum error = MG_Impl::GLImpl::GetError();
MG_State::pGLContext = previous;
EXPECT_EQ(error, GL_NO_ERROR);
for (const GLfloat channel : clear) EXPECT_FLOAT_EQ(channel, 0.0f);
for (const GLfloat channel : clear)
EXPECT_FLOAT_EQ(channel, 0.0f);
}
TEST_F(RenderStateTest, PatchDefaultLevelsStartAtTheGLDefault) {
GLfloat outer[4] = {-1.0f, -1.0f, -1.0f, -1.0f};
MG_Impl::GLImpl::GetFloatv(GL_PATCH_DEFAULT_OUTER_LEVEL, outer);
ExpectSingleGlError(GL_NO_ERROR);
for (const GLfloat level : outer) EXPECT_FLOAT_EQ(level, 1.0f);
for (const GLfloat level : outer)
EXPECT_FLOAT_EQ(level, 1.0f);
GLfloat inner[2] = {-1.0f, -1.0f};
MG_Impl::GLImpl::GetFloatv(GL_PATCH_DEFAULT_INNER_LEVEL, inner);
ExpectSingleGlError(GL_NO_ERROR);
for (const GLfloat level : inner) EXPECT_FLOAT_EQ(level, 1.0f);
for (const GLfloat level : inner)
EXPECT_FLOAT_EQ(level, 1.0f);
}
TEST_F(RenderStateTest, PatchDefaultLevelsRoundTripThroughEveryGetter) {
@@ -820,8 +822,7 @@ TEST_F(RenderStateTest, ARedundantNaNPatchLevelWriteSettlesInsteadOfBumpingForev
const Uint afterFirst = state.GetPipelineStateVersion();
state.SetPatchDefaultOuterLevel(FloatVec4(notANumber, 1.0f, 1.0f, 1.0f));
EXPECT_EQ(state.GetPipelineStateVersion(), afterFirst)
<< "the identical NaN tuple is not a state change";
EXPECT_EQ(state.GetPipelineStateVersion(), afterFirst) << "the identical NaN tuple is not a state change";
state.SetPatchDefaultInnerLevel(FloatVec2(notANumber, 1.0f));
const Uint afterInner = state.GetPipelineStateVersion();
@@ -1100,9 +1101,10 @@ namespace {
class ScopedFragmentShadingRateBackend {
public:
ScopedFragmentShadingRateBackend(Bool primitive, Bool attachment, Bool nonTrivial):
m_previous(Move(MG_Backend::pActiveBackendObject)) {
MG_Backend::pActiveBackendObject = MakeUnique<FragmentShadingRateBackend>(primitive, attachment, nonTrivial);
ScopedFragmentShadingRateBackend(Bool primitive, Bool attachment, Bool nonTrivial)
: m_previous(Move(MG_Backend::pActiveBackendObject)) {
MG_Backend::pActiveBackendObject =
MakeUnique<FragmentShadingRateBackend>(primitive, attachment, nonTrivial);
}
~ScopedFragmentShadingRateBackend() {
// Leave the context at the extension's initial state for whichever test runs next.
@@ -17,9 +17,9 @@ namespace {
// What each surface reports. Android's loader exposes MAILBOX and FIFO (plus the shared
// modes with VK_KHR_shared_presentable_image) but never IMMEDIATE; a desktop X11 WSI has
// all four classic modes.
const Vector<VkPresentModeKHR> kAndroidModes{
VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR,
VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR};
const Vector<VkPresentModeKHR> kAndroidModes{VK_PRESENT_MODE_MAILBOX_KHR, VK_PRESENT_MODE_FIFO_KHR,
VK_PRESENT_MODE_SHARED_DEMAND_REFRESH_KHR,
VK_PRESENT_MODE_SHARED_CONTINUOUS_REFRESH_KHR};
const Vector<VkPresentModeKHR> kAllClassicModes{VK_PRESENT_MODE_IMMEDIATE_KHR, VK_PRESENT_MODE_MAILBOX_KHR,
VK_PRESENT_MODE_FIFO_KHR, VK_PRESENT_MODE_FIFO_RELAXED_KHR};
const Vector<VkPresentModeKHR> kFifoOnly{VK_PRESENT_MODE_FIFO_KHR};
File diff suppressed because it is too large Load Diff
+18 -20
View File
@@ -66,8 +66,7 @@ namespace {
class ScopedBackendOverride {
public:
explicit ScopedBackendOverride(Bool advertiseTextureView)
: m_previous(Move(MG_Backend::pActiveBackendObject)) {
explicit ScopedBackendOverride(Bool advertiseTextureView) : m_previous(Move(MG_Backend::pActiveBackendObject)) {
MG_Backend::pActiveBackendObject = MakeUnique<TextureViewCapabilityBackend>(advertiseTextureView);
}
~ScopedBackendOverride() { MG_Backend::pActiveBackendObject = Move(m_previous); }
@@ -83,8 +82,7 @@ namespace {
// GetError() call - which silently turns error-code assertions into reads of someone
// else's error. Bounded because there is one flag per code.
static void DrainPendingGlErrors() {
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {}
}
// The call under test must raise exactly the expected error and nothing more: a second
@@ -294,21 +292,21 @@ namespace {
// ============================ the error surface ============================
// KHR-GL43.texture_view.errors walks these in this order; the letters are its own.
TEST_F(TextureViewTest, ZeroTextureIsInvalidValue) { // (a)
TEST_F(TextureViewTest, ZeroTextureIsInvalidValue) { // (a)
const GLuint storage = MakeImmutable2D();
DrainPendingGlErrors();
MG_Impl::GLImpl::TextureView(0, GL_TEXTURE_2D, storage, GL_RGBA8, 0, 1, 0, 1);
ExpectSingleGlError(GL_INVALID_VALUE);
}
TEST_F(TextureViewTest, TextureThatGenTexturesNeverReturnedIsInvalidOperation) { // (b)
TEST_F(TextureViewTest, TextureThatGenTexturesNeverReturnedIsInvalidOperation) { // (b)
const GLuint storage = MakeImmutable2D();
DrainPendingGlErrors();
MG_Impl::GLImpl::TextureView(0xFFFFFFFFu, GL_TEXTURE_2D, storage, GL_RGBA8, 0, 1, 0, 1);
ExpectSingleGlError(GL_INVALID_OPERATION);
}
TEST_F(TextureViewTest, AlreadyBoundTextureIsInvalidOperation) { // (c)
TEST_F(TextureViewTest, AlreadyBoundTextureIsInvalidOperation) { // (c)
const GLuint storage = MakeImmutable2D();
const GLuint alreadyBound = GenTexture();
MG_Impl::GLImpl::BindTexture(GL_TEXTURE_2D, alreadyBound);
@@ -318,7 +316,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_OPERATION);
}
TEST_F(TextureViewTest, OrigTextureThatIsNotATextureObjectIsInvalidValue) { // (d)
TEST_F(TextureViewTest, OrigTextureThatIsNotATextureObjectIsInvalidValue) { // (d)
const GLuint view = GenTexture();
DrainPendingGlErrors();
// Note the code differs from (b): INVALID_VALUE here, INVALID_OPERATION there.
@@ -326,7 +324,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_VALUE);
}
TEST_F(TextureViewTest, MutableOrigTextureIsInvalidOperation) { // (e)
TEST_F(TextureViewTest, MutableOrigTextureIsInvalidOperation) { // (e)
const GLuint mutableTexture = GenTexture();
MG_Impl::GLImpl::BindTexture(GL_TEXTURE_2D, mutableTexture);
MG_Impl::GLImpl::TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 8, 8, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
@@ -337,7 +335,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_OPERATION);
}
TEST_F(TextureViewTest, IncompatibleTargetPairIsInvalidOperation) { // (f)
TEST_F(TextureViewTest, IncompatibleTargetPairIsInvalidOperation) { // (f)
const GLuint storage = MakeImmutable2D();
const GLuint view = GenTexture();
DrainPendingGlErrors();
@@ -346,7 +344,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_OPERATION);
}
TEST_F(TextureViewTest, LegalTargetPairsAreAccepted) { // (f), the other way round
TEST_F(TextureViewTest, LegalTargetPairsAreAccepted) { // (f), the other way round
const GLuint storage = MakeImmutable2D(1, 16, 16);
const GLuint sameTarget = GenTexture();
MG_Impl::GLImpl::TextureView(sameTarget, GL_TEXTURE_2D, storage, GL_RGBA8, 0, 1, 0, 1);
@@ -356,7 +354,7 @@ namespace {
ExpectSingleGlError(GL_NO_ERROR);
}
TEST_F(TextureViewTest, FormatFromAnotherViewClassIsInvalidOperation) { // (g)
TEST_F(TextureViewTest, FormatFromAnotherViewClassIsInvalidOperation) { // (g)
const GLuint storage = MakeImmutable2D(1, 16, 16, GL_RGBA8);
const GLuint view = GenTexture();
DrainPendingGlErrors();
@@ -365,7 +363,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_OPERATION);
}
TEST_F(TextureViewTest, FormatFromTheSameViewClassIsAccepted) { // (g), the other way round
TEST_F(TextureViewTest, FormatFromTheSameViewClassIsAccepted) { // (g), the other way round
const GLuint storage = MakeImmutable2D(1, 16, 16, GL_RGBA8);
const GLuint view = GenTexture();
// Both VIEW_CLASS_32_BITS.
@@ -379,7 +377,7 @@ namespace {
EXPECT_EQ(internalFormat, GL_R32UI) << "the view must take the format it was asked for, not its parent's";
}
TEST_F(TextureViewTest, ClasslessFormatMayOnlyBeViewedAsItself) { // (h)
TEST_F(TextureViewTest, ClasslessFormatMayOnlyBeViewedAsItself) { // (h)
// Depth, stencil and depth/stencil formats have NO entry in table 8.21, which the spec
// turns into a stricter rule than "same class": the view's format must be IDENTICAL.
// This is the rule the Better Clouds D24S8 view depends on being permissive enough.
@@ -393,7 +391,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_OPERATION);
}
TEST_F(TextureViewTest, MinLevelPastTheLastLevelIsInvalidValue) { // (i)
TEST_F(TextureViewTest, MinLevelPastTheLastLevelIsInvalidValue) { // (i)
const GLuint storage = MakeImmutable2D(2, 16, 16);
const GLuint view = GenTexture();
DrainPendingGlErrors();
@@ -401,7 +399,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_VALUE);
}
TEST_F(TextureViewTest, MinLayerPastTheLastLayerIsInvalidValue) { // (j)
TEST_F(TextureViewTest, MinLayerPastTheLastLayerIsInvalidValue) { // (j)
const GLuint storage = MakeImmutable2DArray(1, 16, 4);
const GLuint view = GenTexture();
DrainPendingGlErrors();
@@ -409,7 +407,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_VALUE);
}
TEST_F(TextureViewTest, CubeMapViewDemandsExactlySixLayers) { // (k)
TEST_F(TextureViewTest, CubeMapViewDemandsExactlySixLayers) { // (k)
const GLuint storage = MakeImmutable2DArray(1, 16, 6);
const GLuint view = GenTexture();
DrainPendingGlErrors();
@@ -417,7 +415,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_VALUE);
}
TEST_F(TextureViewTest, CubeMapArrayViewDemandsAMultipleOfSixLayers) { // (l)
TEST_F(TextureViewTest, CubeMapArrayViewDemandsAMultipleOfSixLayers) { // (l)
const GLuint storage = MakeImmutable2DArray(1, 16, 12);
const GLuint view = GenTexture();
DrainPendingGlErrors();
@@ -425,7 +423,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_VALUE);
}
TEST_F(TextureViewTest, SingleLayerTargetsRejectMoreThanOneLayer) { // (m).. (q)
TEST_F(TextureViewTest, SingleLayerTargetsRejectMoreThanOneLayer) { // (m).. (q)
const GLuint storage = MakeImmutable2DArray(1, 16, 4);
DrainPendingGlErrors();
for (const GLenum target : {GL_TEXTURE_2D}) {
@@ -444,7 +442,7 @@ namespace {
ExpectSingleGlError(GL_INVALID_VALUE);
}
TEST_F(TextureViewTest, CubeMapViewDemandsSquareLevels) { // (r)
TEST_F(TextureViewTest, CubeMapViewDemandsSquareLevels) { // (r)
const GLuint storage = GenTexture();
MG_Impl::GLImpl::BindTexture(GL_TEXTURE_2D_ARRAY, storage);
MG_Impl::GLImpl::TexStorage3D(GL_TEXTURE_2D_ARRAY, 1, GL_RGBA8, 32, 33, 6);
+10 -6
View File
@@ -33,10 +33,12 @@ namespace {
// Every variable a case touches, restored after it.
constexpr const char* kTouched[] = {
"MOBILEGL_CONFIG_FILE", "MOBILEGL_BACKEND_FILE", "MOBILEGL_BACKEND_TYPE",
"MOBILEGL_MAGMA_FRAMESINFLIGHT", "MOBILEGL_TRANSPORT", "MOBILEGL_IPC_CONTROL",
"MOBILEGL_IPC_DATA", "MOBILEGL_IPC_ROLE", "MOBILEGL_TEST_ONLY_KEY",
"MOBILEGL_FRAMES_IN_FLIGHT", "MOBILEGL_IPC_PRESENT_CREDIT",
"MOBILEGL_CONFIG_FILE", "MOBILEGL_BACKEND_FILE",
"MOBILEGL_BACKEND_TYPE", "MOBILEGL_MAGMA_FRAMESINFLIGHT",
"MOBILEGL_TRANSPORT", "MOBILEGL_IPC_CONTROL",
"MOBILEGL_IPC_DATA", "MOBILEGL_IPC_ROLE",
"MOBILEGL_TEST_ONLY_KEY", "MOBILEGL_FRAMES_IN_FLIGHT",
"MOBILEGL_IPC_PRESENT_CREDIT",
};
class ConfigFileTest : public ::testing::Test {
@@ -60,8 +62,10 @@ namespace {
}
void TearDown() override {
for (const auto& [name, had, value] : saved_) {
if (had) ::setenv(name.c_str(), value.c_str(), 1);
else ::unsetenv(name.c_str());
if (had)
::setenv(name.c_str(), value.c_str(), 1);
else
::unsetenv(name.c_str());
}
std::error_code ec;
std::filesystem::remove_all(dir_, ec);
+21 -10
View File
@@ -37,7 +37,9 @@ namespace {
return true;
}
Region Of(std::initializer_list<Rect> rects) { return Region::FromRects(rects.begin(), rects.size()); }
Region Of(std::initializer_list<Rect> rects) {
return Region::FromRects(rects.begin(), rects.size());
}
} // namespace
// EGL damage (origin bottom-left) -> wl_surface.damage_buffer / shared-image rows (origin top-left).
@@ -87,12 +89,14 @@ TEST(Damage, NormalizeClipsDropsAndPromotesToFull) {
TEST(Damage, NormalizeMergesDownToTheLimitAndStillCoversEverything) {
Vector<Rect> input;
for (Int32 i = 0; i < 40; ++i) input.push_back({(i * 37) % 900, (i * 53) % 600, 9 + i % 5, 7 + i % 3});
for (Int32 i = 0; i < 40; ++i)
input.push_back({(i * 37) % 900, (i * 53) % 600, 9 + i % 5, 7 + i % 3});
Region region = Region::FromRects(input.data(), input.size());
region.Normalize(1000, 700, kMaxRects);
ASSERT_FALSE(region.IsFull());
EXPECT_LE(region.Rects().size(), kMaxRects);
for (const Rect& r : input) EXPECT_TRUE(Covers(region, r, 1000, 700)) << r.X << "," << r.Y;
for (const Rect& r : input)
EXPECT_TRUE(Covers(region, r, 1000, 700)) << r.X << "," << r.Y;
// Two neighbours and one far away, limit 2: the neighbours merge, the far one stays apart.
Region three = Of({{0, 0, 10, 10}, {10, 0, 10, 10}, {500, 500, 10, 10}});
@@ -107,8 +111,10 @@ TEST(Damage, DisjointCoversTheSamePixelsOnce) {
for (Int32 y = 0; y < 40; ++y) {
for (Int32 x = 0; x < 40; ++x) {
Int32 inInput = 0, inOut = 0;
for (const Rect& r : input) inInput |= (x >= r.X && x < r.X + r.Width && y >= r.Y && y < r.Y + r.Height);
for (const Rect& r : out) inOut += (x >= r.X && x < r.X + r.Width && y >= r.Y && y < r.Y + r.Height);
for (const Rect& r : input)
inInput |= (x >= r.X && x < r.X + r.Width && y >= r.Y && y < r.Y + r.Height);
for (const Rect& r : out)
inOut += (x >= r.X && x < r.X + r.Width && y >= r.Y && y < r.Y + r.Height);
EXPECT_EQ(inOut, inInput) << x << "," << y;
}
}
@@ -180,11 +186,13 @@ TEST(Damage, EachBufferCopiesTheDamageItMissedSinceItsLastWrite) {
// Buffer 0 last held frame A; frames B and C went elsewhere, D comes now.
Region copy0 = tracker.TakeForWrite(0, d, W, H);
ASSERT_FALSE(copy0.IsFull());
for (const Region* r : {&b, &c, &d}) EXPECT_TRUE(Covers(copy0, r->Rects()[0], W, H));
for (const Region* r : {&b, &c, &d})
EXPECT_TRUE(Covers(copy0, r->Rects()[0], W, H));
EXPECT_FALSE(Covers(copy0, a.Rects()[0], W, H)) << "A is already in buffer 0";
Region copy1 = tracker.TakeForWrite(1, e, W, H);
for (const Region* r : {&c, &d, &e}) EXPECT_TRUE(Covers(copy1, r->Rects()[0], W, H));
for (const Region* r : {&c, &d, &e})
EXPECT_TRUE(Covers(copy1, r->Rects()[0], W, H));
EXPECT_FALSE(Covers(copy1, b.Rects()[0], W, H));
// A reallocated buffer starts over.
@@ -223,8 +231,10 @@ TEST(Damage, MissedDamageStaysBoundedAndClipped) {
const Region copy = tracker.TakeForWrite(0, Region(), 100, 100);
ASSERT_FALSE(copy.IsFull());
EXPECT_LE(copy.Rects().size(), kMaxRects);
for (const Rect& r : copy.Rects()) EXPECT_FALSE(Clip(r, 100, 100) != r) << "clipped to the surface";
for (const Rect& r : written) EXPECT_TRUE(Covers(copy, r, 100, 100));
for (const Rect& r : copy.Rects())
EXPECT_FALSE(Clip(r, 100, 100) != r) << "clipped to the surface";
for (const Rect& r : written)
EXPECT_TRUE(Covers(copy, r, 100, 100));
}
// EGL_EXT_buffer_age per swapchain image.
@@ -241,7 +251,8 @@ TEST(Damage, SwapchainAgeCountsPresentsSinceTheImageWasShown) {
// Triple buffering, in order.
ages.Reset(3);
for (SizeT i = 0; i < 3; ++i) ages.OnPresented(i, true);
for (SizeT i = 0; i < 3; ++i)
ages.OnPresented(i, true);
EXPECT_EQ(ages.AgeOf(0), 3);
ages.OnPresented(0, true);
EXPECT_EQ(ages.AgeOf(1), 3);
+13 -8
View File
@@ -209,7 +209,8 @@ TEST(JobNodeSubmit, ManyJobsAllComplete) {
pool.Post(jobs.back());
}
for (const auto& job : jobs) job->Wait();
for (const auto& job : jobs)
job->Wait();
EXPECT_EQ(completed.load(), kJobs);
for (const auto& job : jobs) {
EXPECT_TRUE(job->IsComplete());
@@ -232,15 +233,15 @@ TEST(JobNodeSubmit, ConcurrencyBudgetIsNeverExceeded) {
jobs.push_back(MakeShared<TestJob>([&](TestJob&) {
const Uint current = inFlight.fetch_add(1, std::memory_order_acq_rel) + 1;
Uint observed = peak.load(std::memory_order_acquire);
while (current > observed && !peak.compare_exchange_weak(observed, current)) {
}
while (current > observed && !peak.compare_exchange_weak(observed, current)) {}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
inFlight.fetch_sub(1, std::memory_order_acq_rel);
}));
pool.Post(jobs.back());
}
for (const auto& job : jobs) job->Wait();
for (const auto& job : jobs)
job->Wait();
// This is also the memory bound: it is what stops a 300-program pack load from putting
// 300 glslang arenas in flight at once.
EXPECT_LE(peak.load(), kBudget);
@@ -302,7 +303,8 @@ TEST(JobNodeContinuation, DependencyCounterReachesZeroExactlyOnceAndOnlyAfterEve
Vector<SharedPtr<TestJob>> deps;
deps.reserve(kDeps);
for (Uint i = 0; i < kDeps; ++i) deps.push_back(MakeShared<TestJob>());
for (Uint i = 0; i < kDeps; ++i)
deps.push_back(MakeShared<TestJob>());
std::atomic<Int> remaining{static_cast<Int>(kDeps) + 1}; // +1 guard: nothing fires mid-registration
std::atomic<Uint> released{0};
@@ -311,7 +313,8 @@ TEST(JobNodeContinuation, DependencyCounterReachesZeroExactlyOnceAndOnlyAfterEve
const auto settle = [&] {
if (remaining.fetch_sub(1, std::memory_order_acq_rel) == 1) {
Bool allTerminal = true;
for (const auto& dep : deps) allTerminal = allTerminal && dep->IsTerminal();
for (const auto& dep : deps)
allTerminal = allTerminal && dep->IsTerminal();
allDepsTerminalAtRelease.store(allTerminal, std::memory_order_release);
released.fetch_add(1, std::memory_order_acq_rel);
}
@@ -326,7 +329,8 @@ TEST(JobNodeContinuation, DependencyCounterReachesZeroExactlyOnceAndOnlyAfterEve
EXPECT_TRUE(WaitUntil([&] { return released.load() == 1u; }));
EXPECT_EQ(released.load(), 1u);
EXPECT_TRUE(allDepsTerminalAtRelease.load());
for (const auto& dep : deps) EXPECT_TRUE(dep->IsComplete());
for (const auto& dep : deps)
EXPECT_TRUE(dep->IsComplete());
}
TEST(JobNodeContinuation, AlreadyTerminalDependenciesStillSettleTheCounterExactlyOnce) {
@@ -344,7 +348,8 @@ TEST(JobNodeContinuation, AlreadyTerminalDependenciesStillSettleTheCounterExactl
const auto settle = [&] {
if (remaining.fetch_sub(1, std::memory_order_acq_rel) == 1) ++released;
};
for (const auto& dep : deps) dep->OnTerminal(settle);
for (const auto& dep : deps)
dep->OnTerminal(settle);
settle();
EXPECT_EQ(released, 1u);
+4 -5
View File
@@ -169,9 +169,9 @@ namespace {
// live" - which is checkable in whichever configuration this was built in,
// and is what makes the renumbering safe.
const Emitted e = EmitAndRead();
EXPECT_EQ(kAssertsLive, e.debug)
<< "MOBILEGL_ASSERT liveness (" << kAssertsLive << ") disagrees with MGLOG_D liveness ("
<< e.debug << "). The Defines.h assert gate and the Log.h MGLOG_D gate have drifted.";
EXPECT_EQ(kAssertsLive, e.debug) << "MOBILEGL_ASSERT liveness (" << kAssertsLive
<< ") disagrees with MGLOG_D liveness (" << e.debug
<< "). The Defines.h assert gate and the Log.h MGLOG_D gate have drifted.";
}
TEST(LogLevel, AssertIsCompiledOutOfProductionBuilds) {
@@ -218,8 +218,7 @@ int main(int argc, char** argv) {
// main thread (client role), so the read path is the client-derived one; a pull build has
// no split and keeps the base. The env keeps the base either way.
#if MOBILEGL_BUILD_DISAGGREGATED
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(),
MobileGL::MG_Util::Debug::LogRole::Client);
g_logPath = MobileGL::MG_Util::Debug::RoleLogPath(g_logPath.c_str(), MobileGL::MG_Util::Debug::LogRole::Client);
#endif
::testing::InitGoogleTest(&argc, argv);
+12 -16
View File
@@ -224,11 +224,11 @@ namespace {
// when a generator first calls it.
TEST_F(PipeStatsTest, PayloadHistogramBucketsByPowerOfTwo) {
PS::RecordDrawPayloadBytes(0);
PS::RecordDrawPayloadBytes(1); // [1, 2) -> bucket 1
PS::RecordDrawPayloadBytes(2); // [2, 4) -> bucket 2
PS::RecordDrawPayloadBytes(3); // [2, 4) -> bucket 2
PS::RecordDrawPayloadBytes(48); // [32, 64) -> bucket 6
PS::RecordDrawPayloadBytes(64); // [64, 128)-> bucket 7
PS::RecordDrawPayloadBytes(1); // [1, 2) -> bucket 1
PS::RecordDrawPayloadBytes(2); // [2, 4) -> bucket 2
PS::RecordDrawPayloadBytes(3); // [2, 4) -> bucket 2
PS::RecordDrawPayloadBytes(48); // [32, 64) -> bucket 6
PS::RecordDrawPayloadBytes(64); // [64, 128)-> bucket 7
EXPECT_EQ(PS::TotalPayloadBucket(0), 1u);
EXPECT_EQ(PS::TotalPayloadBucket(1), 1u);
@@ -340,8 +340,7 @@ namespace {
EXPECT_EQ(PS::TotalBytes(PS::ByteClass::StageSegmentBytes), 6144u);
EXPECT_EQ(PS::FrameBytes(PS::ByteClass::StageSegmentBytes), 0u) << "a Present clears the frame";
// 6144 over one frame, two decimals, in the ordinary bytes[] bracket.
EXPECT_NE(PS::FormatWindowLine().find("seg=6144.00"), String::npos)
<< PS::FormatWindowLine();
EXPECT_NE(PS::FormatWindowLine().find("seg=6144.00"), String::npos) << PS::FormatWindowLine();
PS::AdvanceSummaryWindow();
// And it obeys the file's LABEL rule, not a rule of its own: the new window has no
@@ -392,10 +391,10 @@ namespace {
// bucket rather than a byte sum: the shape is the deliverable and the bytes have their own
// counter in `seg`.
TEST_F(PipeStatsTest, StagedBlobHistogramSharesThePayloadBucketEdges) {
PS::RecordStagedBlobBytes(1); // [1, 2) -> bucket 1
PS::RecordStagedBlobBytes(4096); // [4096,8192)-> bucket 13
PS::RecordStagedBlobBytes(4096); // same bucket
PS::RecordStagedBlobBytes(8192); // [8192,...) -> bucket 14: the edge is exclusive
PS::RecordStagedBlobBytes(1); // [1, 2) -> bucket 1
PS::RecordStagedBlobBytes(4096); // [4096,8192)-> bucket 13
PS::RecordStagedBlobBytes(4096); // same bucket
PS::RecordStagedBlobBytes(8192); // [8192,...) -> bucket 14: the edge is exclusive
EXPECT_EQ(PS::TotalStagedBlobBucket(1), 1u);
EXPECT_EQ(PS::TotalStagedBlobBucket(13), 2u);
@@ -425,9 +424,7 @@ namespace {
// The ordering is the JSON document's shape, not decoration: the new array is a SIBLING
// of the draw-payload one, so a reader that walks the object finds both where the two
// comments say they are.
EXPECT_LT(json.find("\"cmd-bytes-per-draw-histogram\""),
json.find("\"staged-blob-bytes-histogram\""))
<< json;
EXPECT_LT(json.find("\"cmd-bytes-per-draw-histogram\""), json.find("\"staged-blob-bytes-histogram\"")) << json;
}
// Successive summaries report WINDOWS, not run totals: a run total over a workload that
@@ -541,8 +538,7 @@ namespace {
EXPECT_STREQ(PS::NameOf(PS::CallClass::SamplerViewEmissions), "sampler-view-emissions");
EXPECT_STREQ(PS::NameOf(PS::CallClass::SamplerStateEmissions), "sampler-state-emissions");
EXPECT_STREQ(PS::NameOf(PS::CallClass::ShaderImageEmissions), "shader-image-emissions");
EXPECT_STREQ(PS::NameOf(PS::CallClass::ClientTextureUploadEmissions),
"client-tex-upload-emissions");
EXPECT_STREQ(PS::NameOf(PS::CallClass::ClientTextureUploadEmissions), "client-tex-upload-emissions");
EXPECT_STREQ(PS::NameOf(PS::ByteClass::CsoBlobBytes), "cso-blob-bytes");
// P6 gate 8's two, under their long names - the JSON dump keys and the names the
// MEASUREMENTS.md entry will quote.
+10 -9
View File
@@ -35,14 +35,13 @@ namespace X = MobileGL::MG_Util::X11;
namespace {
// /proc/net/unix as Xwayland's process sees it under KWin: the two listening sockets KWin bound
// and handed over with -listenfd, plus connected ones.
const char* kProcNetUnix =
"Num RefCount Protocol Flags Type St Inode Path\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41001 @/tmp/.X11-unix/X0\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41002 /tmp/.X11-unix/X0\n"
"0000000000000000: 00000003 00000000 00000000 0001 03 41003 /tmp/.X11-unix/X0\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41004 /run/user/1000/wayland-0\n"
"0000000000000000: 00000003 00000000 00000000 0001 03 41005\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41006 @/tmp/.X11-unix/X1\n";
const char* kProcNetUnix = "Num RefCount Protocol Flags Type St Inode Path\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41001 @/tmp/.X11-unix/X0\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41002 /tmp/.X11-unix/X0\n"
"0000000000000000: 00000003 00000000 00000000 0001 03 41003 /tmp/.X11-unix/X0\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41004 /run/user/1000/wayland-0\n"
"0000000000000000: 00000003 00000000 00000000 0001 03 41005\n"
"0000000000000000: 00000002 00000000 00010000 0001 01 41006 @/tmp/.X11-unix/X1\n";
} // namespace
TEST(X11DisplayGuard, DisplayNamesYieldTheirNumber) {
@@ -113,7 +112,9 @@ namespace {
return fd;
}
int UnusedDisplayNumber() { return 3000 + static_cast<int>(::getpid() % 2000); }
int UnusedDisplayNumber() {
return 3000 + static_cast<int>(::getpid() % 2000);
}
} // namespace
TEST(X11DisplayGuard, ThisProcessServesADisplayWhileItListensOnItsSocket) {
+8 -4
View File
@@ -94,7 +94,8 @@ namespace {
freed.push_back(pixmap);
pixmaps.erase(pixmap);
}
Bool PresentPixmap(Uint32 pixmap, Uint32 serial, Uint32 options, Uint64 targetMsc, const Region& update) override {
Bool PresentPixmap(Uint32 pixmap, Uint32 serial, Uint32 options, Uint64 targetMsc,
const Region& update) override {
presents.push_back({pixmap, serial, options, targetMsc, update});
return true;
}
@@ -227,7 +228,8 @@ TEST(X11PresentChain, AnImageComesBackWithIdleNotifyAndIsReused) {
TEST(X11PresentChain, AllImagesHeldWaitsThenGrowsToFourThenDropsTheFrame) {
Rig rig;
for (int i = 0; i < 3; ++i) ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
for (int i = 0; i < 3; ++i)
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
const Int64 before = rig.clock.now;
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0)) << "a fourth image after the idle wait";
EXPECT_GE(rig.clock.now - before, XP::Chain::kIdleWaitMs);
@@ -310,7 +312,8 @@ TEST(X11PresentChain, AResizeRetiresOldImagesAsTheyComeBack) {
rig.x.Idle(c);
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_EQ(rig.x.pixmaps.count(b), 0u);
for (const auto& [id, size] : rig.images.live) EXPECT_EQ(size, newSize);
for (const auto& [id, size] : rig.images.live)
EXPECT_EQ(size, newSize);
}
TEST(X11PresentChain, ConfigureNotifyReportsTheNewSizeOnce) {
@@ -378,7 +381,8 @@ TEST(X11PresentChain, FailuresSendTheWindowBackToReadback) {
TEST(X11PresentChain, TheChainFreesEveryPixmapAndReleasesEveryImage) {
Rig rig;
for (int i = 0; i < 3; ++i) ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
for (int i = 0; i < 3; ++i)
ASSERT_TRUE(rig.chain->Present(Region::Full(), 0));
EXPECT_EQ(rig.images.live.size(), 3u);
rig.chain.reset();
EXPECT_TRUE(rig.images.live.empty());
@@ -41,8 +41,7 @@ protected:
// binary, so drain whatever an earlier test left pending - otherwise an error-code assertion
// here reads someone else's error. Bounded: one flag per code, so this cannot hang the suite.
static void DrainPendingGlErrors() {
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {
}
for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {}
}
// The call under test must raise exactly the expected error and nothing more: a second pending
@@ -408,8 +407,7 @@ class GeneralVertexArrayTest : public ::testing::Test {
protected:
void SetUp() override { MG_State::pGLContext = MakeUnique<MG_State::GLState::GLContext>(); }
void TearDown() override {
}
void TearDown() override {}
GLuint CreateVAO() {
GLuint vao;
@@ -1007,9 +1005,9 @@ TEST_F(GeneralVertexArrayTest, CurrentAttrib_SignedNormalizedUsesGl33Formula) {
const GLbyte extremes[4] = {-128, 127, 0, 127};
VertexAttrib4Nbv(1, extremes);
GetVertexAttribfv(1, GL_CURRENT_VERTEX_ATTRIB, out);
EXPECT_FLOAT_EQ(out[0], -1.0f); // exact, no clamp
EXPECT_FLOAT_EQ(out[1], 1.0f); // exact
EXPECT_FLOAT_EQ(out[2], 1.0f / 255.0f); // 0 -> 1/255, NOT 0.0
EXPECT_FLOAT_EQ(out[0], -1.0f); // exact, no clamp
EXPECT_FLOAT_EQ(out[1], 1.0f); // exact
EXPECT_FLOAT_EQ(out[2], 1.0f / 255.0f); // 0 -> 1/255, NOT 0.0
EXPECT_FLOAT_EQ(out[3], 1.0f);
const GLshort sExtremes[4] = {-32768, 32767, 0, 0};
@@ -1131,10 +1129,10 @@ TEST_F(GeneralVertexArrayTest, CurrentAttrib_PackedUnsigned) {
VertexAttribP4ui(1, GL_UNSIGNED_INT_2_10_10_10_REV, GL_TRUE, packed);
GetVertexAttribfv(1, GL_CURRENT_VERTEX_ATTRIB, out);
EXPECT_EQ(GetError(), GL_NO_ERROR);
EXPECT_FLOAT_EQ(out[0], 1.0f); // 1023/1023
EXPECT_FLOAT_EQ(out[1], 0.0f); // 0/1023
EXPECT_FLOAT_EQ(out[2], 512.0f / 1023.0f); // 10-bit divisor, NOT 1023 for w
EXPECT_FLOAT_EQ(out[3], 1.0f); // 3/3 (2-bit divisor)
EXPECT_FLOAT_EQ(out[0], 1.0f); // 1023/1023
EXPECT_FLOAT_EQ(out[1], 0.0f); // 0/1023
EXPECT_FLOAT_EQ(out[2], 512.0f / 1023.0f); // 10-bit divisor, NOT 1023 for w
EXPECT_FLOAT_EQ(out[3], 1.0f); // 3/3 (2-bit divisor)
// Unnormalized: the field values are cast straight to float, no scaling.
VertexAttribP4ui(1, GL_UNSIGNED_INT_2_10_10_10_REV, GL_FALSE, packed);
@@ -1156,10 +1154,10 @@ TEST_F(GeneralVertexArrayTest, CurrentAttrib_PackedSignedUsesGl33Formula) {
VertexAttribP4ui(1, GL_INT_2_10_10_10_REV, GL_TRUE, packed);
GetVertexAttribfv(1, GL_CURRENT_VERTEX_ATTRIB, out);
EXPECT_EQ(GetError(), GL_NO_ERROR);
EXPECT_FLOAT_EQ(out[0], 1.0f); // (2*511+1)/1023 = 1023/1023
EXPECT_FLOAT_EQ(out[1], -1.0f); // (2*-512+1)/1023 = -1023/1023
EXPECT_FLOAT_EQ(out[2], 1.0f / 1023.0f); // (2*0+1)/1023 -- 4.2 rule would give 0.0
EXPECT_FLOAT_EQ(out[3], 1.0f); // (2*1+1)/3 = 3/3
EXPECT_FLOAT_EQ(out[0], 1.0f); // (2*511+1)/1023 = 1023/1023
EXPECT_FLOAT_EQ(out[1], -1.0f); // (2*-512+1)/1023 = -1023/1023
EXPECT_FLOAT_EQ(out[2], 1.0f / 1023.0f); // (2*0+1)/1023 -- 4.2 rule would give 0.0
EXPECT_FLOAT_EQ(out[3], 1.0f); // (2*1+1)/3 = 3/3
// 2-bit signed minimum: w field = 0b10 = -2 -> (2*-2+1)/3 = -1.0.
VertexAttribP4ui(1, GL_INT_2_10_10_10_REV, GL_TRUE, 2u << 30);
@@ -1222,7 +1220,7 @@ TEST_F(GeneralVertexArrayTest, CurrentAttrib_PackedValidation) {
EXPECT_EQ(GetError(), GL_NO_ERROR);
GetVertexAttribfv(0, GL_CURRENT_VERTEX_ATTRIB, out);
EXPECT_EQ(GetError(), GL_NO_ERROR);
EXPECT_FLOAT_EQ(out[0], 1.0f); // x field of the packed word
EXPECT_FLOAT_EQ(out[0], 1.0f); // x field of the packed word
VertexAttrib4f(0, 0.0f, 0.0f, 0.0f, 1.0f); // restore the initial current value
EXPECT_EQ(GetError(), GL_NO_ERROR);
@@ -1331,7 +1329,6 @@ TEST_F(GeneralVertexArrayTest, ArrayFormat_IntegerPathRejectsPackedAndBgra) {
EXPECT_FALSE(a0.IsBgra);
}
// The integer path takes exactly the eight signed/unsigned integer types (GL 4.6 core 10.3.2).
// The old check was a blacklist of Unknown + the packed types, so GL_FLOAT / GL_HALF_FLOAT /
// GL_DOUBLE / GL_FIXED all converted to a valid DataType and were silently recorded as integer
@@ -171,9 +171,7 @@ namespace {
BindVertexArray(m_vao);
}
void TearDown() override {
EXPECT_EQ(GetError(), GL_NO_ERROR) << "test left an unconsumed GL error behind";
}
void TearDown() override { EXPECT_EQ(GetError(), GL_NO_ERROR) << "test left an unconsumed GL error behind"; }
GLuint CreateVbo(GLsizeiptr size) {
GLuint vbo = 0;
@@ -185,8 +183,7 @@ namespace {
}
static void DrainErrors() {
for (int i = 0; i < 16 && GetError() != GL_NO_ERROR; ++i) {
}
for (int i = 0; i < 16 && GetError() != GL_NO_ERROR; ++i) {}
}
GLuint m_vao = 0;
+17 -13
View File
@@ -47,9 +47,9 @@ namespace {
::setenv("MOBILEGL_IPC_ROLE", "server", 1);
::setenv("MOBILEGL_IPC_DIAL", "no", 1);
::setenv("MOBILEGL_IPC_ADOPT_TIER", adoptTier, 1);
for (const char* name : {"MOBILEGL_TRANSPORT", "MOBILEGL_IPC_SERVER_PATH", "MOBILEGL_IPC_RING_MB",
"MOBILEGL_IPC_STAGE_MB", "MOBILEGL_IPC_CONTROL", "MOBILEGL_IPC_SURFACE",
"MOBILEGL_BACKEND_TYPE"})
for (const char* name :
{"MOBILEGL_TRANSPORT", "MOBILEGL_IPC_SERVER_PATH", "MOBILEGL_IPC_RING_MB", "MOBILEGL_IPC_STAGE_MB",
"MOBILEGL_IPC_CONTROL", "MOBILEGL_IPC_SURFACE", "MOBILEGL_BACKEND_TYPE"})
::unsetenv(name);
sigset_t stop;
sigemptyset(&stop);
@@ -77,8 +77,8 @@ namespace {
// this process exports for the forks): a peer writes the lines the server forwards into
// `<its base>.server.log`, opened "w", so sharing one base truncates the server's own file under
// it (measured: NUL holes and the handshake's lines gone).
bool LaunchInProcessServerWithAdoptTier(const std::string& label, const char* adoptTier, const std::string& peerBase,
ServerProcess* server) {
bool LaunchInProcessServerWithAdoptTier(const std::string& label, const char* adoptTier,
const std::string& peerBase, ServerProcess* server) {
server->logBase = "/tmp/mgl-p11-" + label + "-server-" + std::to_string(::getpid()) + ".log";
::setenv("MOBILEGL_LOG_FILE_PATH", peerBase.c_str(), 1);
Debug::TruncateRoleLogs(peerBase.c_str());
@@ -136,18 +136,21 @@ TEST(AdoptTierStream, AClientNamingT0OrT1IsRefusedOnceAndItsMapPersistentIsDecli
ASSERT_TRUE(LaunchSupervisor("adopt-client", &server)) << server.Log();
for (Uint32 tier : {0u, 1u}) {
SCOPED_TRACE(tier);
const PeerReport r = RunPeer(server.endpoint, MapPersistentThenARecord, /*stopCleanly=*/true, 30000, 0,
nullptr, [tier] { MG_Config::Ipc.AdoptTier = tier; });
const PeerReport r = RunPeer(server.endpoint, MapPersistentThenARecord, /*stopCleanly=*/true, 30000, 0, nullptr,
[tier] { MG_Config::Ipc.AdoptTier = tier; });
const std::string client = ClientLog(server);
ASSERT_EQ(r.started, 1) << "the session did not come up: " << r.note << "\n" << client;
EXPECT_EQ(r.status, Remote::Wire::ReplySink::kStatusDeclined)
<< "map_persistent was not DECLINED on a stream session\n" << client;
<< "map_persistent was not DECLINED on a stream session\n"
<< client;
EXPECT_EQ(r.applied, 1) << "the session stopped applying after the map_persistent\n" << client;
EXPECT_EQ(Count(client, RefusalLine(tier)), 1u)
<< "a stream session names T" << tier << " exactly once, at the handshake\n" << client;
<< "a stream session names T" << tier << " exactly once, at the handshake\n"
<< client;
EXPECT_EQ(Count(client, "Fatal{"), 0u) << client;
EXPECT_EQ(Count(server.Log(), "AdoptTierOnStream"), 0u)
<< "the server's own knob is 2; the line is the client's\n" << server.Log();
<< "the server's own knob is 2; the line is the client's\n"
<< server.Log();
}
}
@@ -187,15 +190,16 @@ TEST(AdoptTierStream, AServerNamingT0RefusesOncePerSessionAndServesT2) {
const auto serverLog = [&server] { return Debug::ReadRoleLogs(server.logBase.c_str()); };
for (Uint32 session = 1; session <= 2; ++session) {
SCOPED_TRACE(session);
const PeerReport r = RunPeer(server.endpoint, MapPersistentThenARecord, /*stopCleanly=*/true, 30000, 0,
nullptr, [] { MG_Config::Ipc.AdoptTier = 2u; });
const PeerReport r = RunPeer(server.endpoint, MapPersistentThenARecord, /*stopCleanly=*/true, 30000, 0, nullptr,
[] { MG_Config::Ipc.AdoptTier = 2u; });
const std::string client = ReadFile(Debug::RoleLogPath(peerBase.c_str(), Debug::LogRole::Client));
ASSERT_EQ(r.started, 1) << r.note << "\n" << serverLog();
EXPECT_EQ(r.status, Remote::Wire::ReplySink::kStatusDeclined) << serverLog();
EXPECT_EQ(r.applied, 1) << serverLog();
EXPECT_EQ(Count(client, "AdoptTierOnStream"), 0u) << "the client's knob is 2\n" << client;
EXPECT_EQ(Count(serverLog(), RefusalLine(0)), session)
<< "one refusal line per server session, at its handshake\n" << serverLog();
<< "one refusal line per server session, at its handshake\n"
<< serverLog();
}
EXPECT_EQ(Count(serverLog(), "Fatal{UnimplementedAdoptTier"), 0u) << serverLog();
if (!::testing::Test::HasFailure()) {
@@ -196,8 +196,8 @@ namespace {
BindSession(kSessionA, 4);
P::MGPipeApplierState& fourth = P::MGPipeApplier();
EXPECT_NE(&third, &fourth) << "two contexts of one share group share one applier - the "
"bindings, the current program and the CSO store would all "
"overwrite each other";
"bindings, the current program and the CSO store would all "
"overwrite each other";
EXPECT_EQ(&third.Resources, &fourth.Resources)
<< "two contexts of one share group were given different object tables";
EXPECT_NE(ResourceRecord(shared), nullptr)
@@ -237,8 +237,7 @@ namespace {
P::MGPipeApplierState& inB = P::MGPipeApplier();
EXPECT_NE(&inA, &inB) << "two sessions with identical tokens resolved one applier";
EXPECT_NE(&inA.Resources, &inB.Resources);
EXPECT_EQ(ResourceRecord(handle), nullptr)
<< "session B resolved an object record session A created";
EXPECT_EQ(ResourceRecord(handle), nullptr) << "session B resolved an object record session A created";
}
// THE GROUP'S RECORDS GO WITH ITS LAST CONTEXT, NOT ITS FIRST. A context of a live group is
@@ -261,8 +260,7 @@ namespace {
EXPECT_EQ(P::MGPipeApplierShareGroupCountForTesting(kSessionA), 1u);
P::MGPipeApplierUnregisterContext(kSessionA, 6);
EXPECT_EQ(P::MGPipeApplierShareGroupCountForTesting(kSessionA), 0u)
<< "the group outlived its last context";
EXPECT_EQ(P::MGPipeApplierShareGroupCountForTesting(kSessionA), 0u) << "the group outlived its last context";
// A RECREATED CONTEXT MUST NOT INHERIT THE DEAD GROUP'S RECORDS. The frontend never
// re-uses a token, so this is the belt: a token that comes back resolves to a fresh
@@ -285,8 +283,7 @@ namespace {
t_sessionKey = 0;
t_contextToken = 0;
P::MGPipeApplierState& processWide = P::MGPipeApplier();
EXPECT_EQ(ResourceRecord(handle), nullptr)
<< "the process-wide applier resolved a record a session registered";
EXPECT_EQ(ResourceRecord(handle), nullptr) << "the process-wide applier resolved a record a session registered";
BindSession(kSessionA, 1);
EXPECT_NE(&P::MGPipeApplier(), &processWide) << "a session resolved the process-wide applier";
+15 -15
View File
@@ -38,8 +38,8 @@ namespace {
TEST(ApplyThreadPolicy, AutoKeepsEveryBigCoreAndTheConfiguredSpinForAnInProcessOrForkedPeer) {
// inproc and the same-app fork spawn: exactly the pre-B1 `auto` (A4's measured shapes).
for (const ApplyPeer peer : {ApplyPeer::InProcess, ApplyPeer::Forked}) {
const auto policy = SelectApplyThreadPolicy("auto", false, kConfigured, peer, kShm, kRedmiBig, kRedmiPrime,
kRedmiOnline);
const auto policy =
SelectApplyThreadPolicy("auto", false, kConfigured, peer, kShm, kRedmiBig, kRedmiPrime, kRedmiOnline);
EXPECT_TRUE(policy.recognised);
EXPECT_EQ(policy.requestedMask, kRedmiBig) << ApplyPeerName(peer);
EXPECT_EQ(policy.spinUs, kConfigured) << ApplyPeerName(peer);
@@ -100,9 +100,9 @@ TEST(ApplyThreadPolicy, NoAsymmetryLeavesTheApplyThreadUnpinned) {
std::string::npos);
}
// ...and the in-process / forked rows keep the whole (symmetric) big set as before.
EXPECT_EQ(SelectApplyThreadPolicy("auto", false, kConfigured, ApplyPeer::Forked, kShm, 0xff, 0xff, 0xff)
.requestedMask,
0xffu);
EXPECT_EQ(
SelectApplyThreadPolicy("auto", false, kConfigured, ApplyPeer::Forked, kShm, 0xff, 0xff, 0xff).requestedMask,
0xffu);
}
TEST(ApplyThreadPolicy, AnEmptyOrMissingAffinityIsAuto) {
@@ -117,8 +117,8 @@ TEST(ApplyThreadPolicy, AnEmptyOrMissingAffinityIsAuto) {
}
TEST(ApplyThreadPolicy, AnExplicitSpinWinsForADialledInPeer) {
const auto policy = SelectApplyThreadPolicy("auto", true, 7, ApplyPeer::Connected, kShm, kRedmiBig, kRedmiPrime,
kRedmiOnline);
const auto policy =
SelectApplyThreadPolicy("auto", true, 7, ApplyPeer::Connected, kShm, kRedmiBig, kRedmiPrime, kRedmiOnline);
EXPECT_EQ(policy.spinUs, 7u);
EXPECT_EQ(policy.requestedMask, 0x40u);
}
@@ -126,19 +126,19 @@ TEST(ApplyThreadPolicy, AnExplicitSpinWinsForADialledInPeer) {
TEST(ApplyThreadPolicy, AnExplicitMaskOrOffWinsForEveryPeerAndPlaneAndReservesNothing) {
for (const ApplyPeer peer : {ApplyPeer::InProcess, ApplyPeer::Forked, ApplyPeer::Connected}) {
for (const Bool plane : {kShm, kStream}) {
const auto off = SelectApplyThreadPolicy("off", false, kConfigured, peer, plane, kRedmiBig, kRedmiPrime,
kRedmiOnline);
const auto off =
SelectApplyThreadPolicy("off", false, kConfigured, peer, plane, kRedmiBig, kRedmiPrime, kRedmiOnline);
EXPECT_TRUE(off.recognised);
EXPECT_EQ(off.requestedMask, 0u) << ApplyPeerName(peer);
EXPECT_EQ(off.spinUs, kConfigured) << "an operator's affinity keeps the configured spin";
const auto mask = SelectApplyThreadPolicy("0x80", false, kConfigured, peer, plane, kRedmiBig,
kRedmiPrime, kRedmiOnline);
const auto mask =
SelectApplyThreadPolicy("0x80", false, kConfigured, peer, plane, kRedmiBig, kRedmiPrime, kRedmiOnline);
EXPECT_TRUE(mask.recognised);
EXPECT_EQ(mask.requestedMask, 0x80u) << ApplyPeerName(peer);
EXPECT_EQ(SelectApplyThreadPolicy("12", false, kConfigured, peer, plane, kRedmiBig, kRedmiPrime,
kRedmiOnline)
.requestedMask,
12u);
EXPECT_EQ(
SelectApplyThreadPolicy("12", false, kConfigured, peer, plane, kRedmiBig, kRedmiPrime, kRedmiOnline)
.requestedMask,
12u);
}
}
// What the supervisor announces (and the helper avoids) under an operator's affinity: nothing.
+104 -88
View File
@@ -43,46 +43,47 @@
#include <condition_variable>
#include <mutex>
extern "C" {
void glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
const GLubyte* glGetString(GLenum name);
const GLubyte* glGetStringi(GLenum name, GLuint index);
void glGetIntegerv(GLenum pname, GLint* data);
void glGetnUniformfv(GLuint program, GLint location, GLsizei bufSize, GLfloat* params);
void glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
void glClear(GLbitfield mask);
void glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels);
GLenum glGetError(void);
GLenum glGetGraphicsResetStatus(void);
void glGenTextures(GLsizei n, GLuint* textures);
void glBindTexture(GLenum target, GLuint texture);
void glActiveTexture(GLenum texture);
void glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border,
GLenum format, GLenum type, const void* pixels);
void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLenum format, GLenum type, const void* pixels);
void glTexParameteri(GLenum target, GLenum pname, GLint param);
GLboolean glIsTexture(GLuint texture);
void glGenFramebuffers(GLsizei n, GLuint* framebuffers);
void glBindFramebuffer(GLenum target, GLuint framebuffer);
void glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
GLenum glCheckFramebufferStatus(GLenum target);
GLuint glCreateShader(GLenum type);
void glShaderSource(GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length);
void glCompileShader(GLuint shader);
void glGetShaderiv(GLuint shader, GLenum pname, GLint* params);
GLuint glCreateProgram(void);
void glAttachShader(GLuint program, GLuint shader);
void glLinkProgram(GLuint program);
void glGetProgramiv(GLuint program, GLenum pname, GLint* params);
void glUseProgram(GLuint program);
GLint glGetUniformLocation(GLuint program, const GLchar* name);
void glUniform1i(GLint location, GLint v0);
void glGenVertexArrays(GLsizei n, GLuint* arrays);
void glBindVertexArray(GLuint array);
void glViewport(GLint x, GLint y, GLsizei width, GLsizei height);
void glDrawArrays(GLenum mode, GLint first, GLsizei count);
extern "C"
{
void glTexStorage2D(GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height);
const GLubyte* glGetString(GLenum name);
const GLubyte* glGetStringi(GLenum name, GLuint index);
void glGetIntegerv(GLenum pname, GLint* data);
void glGetnUniformfv(GLuint program, GLint location, GLsizei bufSize, GLfloat* params);
void glUniform4f(GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3);
void glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha);
void glClear(GLbitfield mask);
void glReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels);
GLenum glGetError(void);
GLenum glGetGraphicsResetStatus(void);
void glGenTextures(GLsizei n, GLuint* textures);
void glBindTexture(GLenum target, GLuint texture);
void glActiveTexture(GLenum texture);
void glTexImage2D(GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border,
GLenum format, GLenum type, const void* pixels);
void glTexSubImage2D(GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height,
GLenum format, GLenum type, const void* pixels);
void glTexParameteri(GLenum target, GLenum pname, GLint param);
GLboolean glIsTexture(GLuint texture);
void glGenFramebuffers(GLsizei n, GLuint* framebuffers);
void glBindFramebuffer(GLenum target, GLuint framebuffer);
void glFramebufferTexture2D(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level);
GLenum glCheckFramebufferStatus(GLenum target);
GLuint glCreateShader(GLenum type);
void glShaderSource(GLuint shader, GLsizei count, const GLchar* const* string, const GLint* length);
void glCompileShader(GLuint shader);
void glGetShaderiv(GLuint shader, GLenum pname, GLint* params);
GLuint glCreateProgram(void);
void glAttachShader(GLuint program, GLuint shader);
void glLinkProgram(GLuint program);
void glGetProgramiv(GLuint program, GLenum pname, GLint* params);
void glUseProgram(GLuint program);
GLint glGetUniformLocation(GLuint program, const GLchar* name);
void glUniform1i(GLint location, GLint v0);
void glGenVertexArrays(GLsizei n, GLuint* arrays);
void glBindVertexArray(GLuint array);
void glViewport(GLint x, GLint y, GLsizei width, GLsizei height);
void glDrawArrays(GLenum mode, GLint first, GLsizei count);
}
using namespace MobileGL;
@@ -182,9 +183,10 @@ namespace {
GLuint texture = 0;
Bool Build(RecoveryReport& r, Uint32 rgba) {
static const char* kVertex = "#version 330 core\n"
"const vec2 corners[3] = vec2[3](vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n"
"void main() { gl_Position = vec4(corners[gl_VertexID], 0.0, 1.0); }\n";
static const char* kVertex =
"#version 330 core\n"
"const vec2 corners[3] = vec2[3](vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0));\n"
"void main() { gl_Position = vec4(corners[gl_VertexID], 0.0, 1.0); }\n";
static const char* kFragment = "#version 330 core\n"
"uniform sampler2D image;\n"
"out vec4 color;\n"
@@ -469,8 +471,8 @@ namespace {
RecoveryReport built{};
if (!old.Build(built, kGreen)) return Note(r, built.note);
old.Draw();
(void)ReadPixel(); // device check #1
(void)ClearAndRead(0.0f, 0.0f, 1.0f); // device check #2: lost
(void)ReadPixel(); // device check #1
(void)ClearAndRead(0.0f, 0.0f, 1.0f); // device check #2: lost
(void)WaitFor([] { return glGetGraphicsResetStatus() != GL_NO_ERROR; }, 5000);
(void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
(void)EGL::DestroyContext(egl.dpy, working);
@@ -496,7 +498,7 @@ namespace {
if (EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, second) != EGL_TRUE)
return Note(r, "the second replacement did not go current");
r.textureSeenAcross = glIsTexture(shared.texture) == GL_TRUE ? 1 : 0;
GLuint vertexArray = 0; // a vertex array is per context
GLuint vertexArray = 0; // a vertex array is per context
glGenVertexArrays(1, &vertexArray);
shared.vertexArray = vertexArray;
shared.Draw();
@@ -593,8 +595,8 @@ namespace {
if (!old.Build(built, kGreen)) return Note(r, built.note);
r.initialized = 1;
old.Draw();
r.firstPixel = ReadPixel(); // device check #1
(void)ClearAndRead(0.0f, 0.0f, 1.0f); // device check #2: lost
r.firstPixel = ReadPixel(); // device check #1
(void)ClearAndRead(0.0f, 0.0f, 1.0f); // device check #2: lost
(void)WaitFor([] { return glGetGraphicsResetStatus() != GL_NO_ERROR; }, 5000);
});
if (!r.initialized) return;
@@ -697,8 +699,8 @@ namespace {
return Note(r, "the contexts did not go current");
r.initialized = 1;
glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY, &r.coreStrategy);
r.firstPixel = ClearAndRead(0.0f, 1.0f, 0.0f); // device check #1
(void)ClearAndRead(0.0f, 0.0f, 1.0f); // device check #2: lost
r.firstPixel = ClearAndRead(0.0f, 1.0f, 0.0f); // device check #1
(void)ClearAndRead(0.0f, 0.0f, 1.0f); // device check #2: lost
r.lossSeen = WaitFor([] { return Remote::Client::ClientSession::SessionLatchedLost(); }, 5000) ? 1 : 0;
r.coreStatus = glGetGraphicsResetStatus();
@@ -716,7 +718,8 @@ namespace {
if (r.coreAgain == EGL_TRUE) (void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
const EGLContext fresh = egl.Context();
r.freshCurrent = fresh != EGL_NO_CONTEXT && EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, fresh) == EGL_TRUE;
r.freshCurrent =
fresh != EGL_NO_CONTEXT && EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, fresh) == EGL_TRUE;
if (!r.freshCurrent) return Note(r, "no fresh context went current");
r.freshStatus = glGetGraphicsResetStatus();
r.freshPixel = ClearAndRead(0.0f, 0.0f, 1.0f);
@@ -816,7 +819,8 @@ namespace {
(void)EGL::MakeCurrent(egl.dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
const EGLContext fresh = egl.Context();
(void)EGL::DestroyContext(egl.dpy, lost);
r.freshCurrent = fresh != EGL_NO_CONTEXT && EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, fresh) == EGL_TRUE;
r.freshCurrent =
fresh != EGL_NO_CONTEXT && EGL::MakeCurrent(egl.dpy, egl.surface, egl.surface, fresh) == EGL_TRUE;
if (!r.freshCurrent) return Note(r, "no fresh context went current");
const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(500);
while (std::chrono::steady_clock::now() < until) {
@@ -979,10 +983,9 @@ namespace {
reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION)));
glGetIntegerv(GL_MAJOR_VERSION, &r.esMajor);
glGetIntegerv(GL_MINOR_VERSION, &r.esMinor);
r.bgraAdvertised = HasToken(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)),
"GL_EXT_texture_format_BGRA8888")
? 1
: 0;
r.bgraAdvertised =
HasToken(reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)), "GL_EXT_texture_format_BGRA8888") ? 1
: 0;
GLint count = 0;
glGetIntegerv(GL_NUM_EXTENSIONS, &count);
r.bgraIndexed = 0;
@@ -990,8 +993,7 @@ namespace {
const auto* name = reinterpret_cast<const char*>(glGetStringi(GL_EXTENSIONS, static_cast<GLuint>(i)));
if (name != nullptr && std::string(name) == "GL_EXT_texture_format_BGRA8888") r.bgraIndexed = 1;
}
while (glGetError() != GL_NO_ERROR) {
}
while (glGetError() != GL_NO_ERROR) {}
// BGRA as EXT_texture_format_BGRA8888 spells it: GL_BGRA_EXT as the internal format, and
// GL_BGRA8_EXT through glTexStorage2D; a BGRA texel reads back in RGBA order.
const Uint8 bgra[4] = {0x10, 0x20, 0x30, 0xFF}; // B, G, R, A
@@ -1061,8 +1063,10 @@ namespace {
// What every route has to show from the application's side, before and after the loss.
static void ExpectLossReportedAndRecovered(const RecoveryReport& r, const std::string& diagnostics) {
ASSERT_EQ(r.initialized, 1) << r.note << "\n" << diagnostics;
ASSERT_EQ(r.firstPixel, kGreen) << "the first draw (device check #1) did not read back: " << std::hex
<< r.firstPixel << "\n" << r.note << "\n" << diagnostics;
ASSERT_EQ(r.firstPixel, kGreen)
<< "the first draw (device check #1) did not read back: " << std::hex << r.firstPixel << "\n"
<< r.note << "\n"
<< diagnostics;
EXPECT_NE(r.lostPixel, kBlue) << "a read-back on the lost device returned a frame";
// What the application checked before it asked to be told (ANGLE mirrors the EGL
// extension onto its own display; Chrome checks that and GL_*_robustness), and what
@@ -1070,8 +1074,8 @@ namespace {
EXPECT_EQ(r.eglRobustnessAdvertised, 1) << "EGL_EXT_create_context_robustness is not advertised";
EXPECT_EQ(r.glRobustnessAdvertised, 1) << "GL_KHR_robustness is not in glGetString(GL_EXTENSIONS)";
EXPECT_EQ(r.glRobustnessIndexed, 1) << "GL_KHR_robustness is not in glGetStringi(GL_EXTENSIONS, i)";
EXPECT_EQ(r.strategyBefore, GL_LOSE_CONTEXT_ON_RESET) << "GL_RESET_NOTIFICATION_STRATEGY: 0x" << std::hex
<< r.strategyBefore;
EXPECT_EQ(r.strategyBefore, GL_LOSE_CONTEXT_ON_RESET)
<< "GL_RESET_NOTIFICATION_STRATEGY: 0x" << std::hex << r.strategyBefore;
EXPECT_EQ(r.robustAccess, GL_FALSE);
// The loss is reported.
EXPECT_TRUE(r.resetStatusLost == GL_UNKNOWN_CONTEXT_RESET || r.resetStatusLost == GL_GUILTY_CONTEXT_RESET)
@@ -1083,23 +1087,27 @@ namespace {
// LOSE_CONTEXT_ON_RESET: the context stays lost, so the status does not go back to
// GL_NO_ERROR (that would read as a reset that completed in place), and the KHR name
// an ES application looks up answers the same.
EXPECT_EQ(r.resetStatusRepeat, r.resetStatusLost) << "the reset status of a lost context went back to 0x"
<< std::hex << r.resetStatusRepeat;
EXPECT_EQ(r.resetStatusKhr, r.resetStatusLost) << "glGetGraphicsResetStatusKHR: 0x" << std::hex
<< r.resetStatusKhr;
EXPECT_EQ(r.resetStatusRepeat, r.resetStatusLost)
<< "the reset status of a lost context went back to 0x" << std::hex << r.resetStatusRepeat;
EXPECT_EQ(r.resetStatusKhr, r.resetStatusLost)
<< "glGetGraphicsResetStatusKHR: 0x" << std::hex << r.resetStatusKhr;
EXPECT_EQ(r.swapLost, EGL_FALSE) << "eglSwapBuffers on the lost context succeeded";
EXPECT_EQ(r.swapLostError, EGL_CONTEXT_LOST) << "eglSwapBuffers on the lost context: 0x" << std::hex
<< r.swapLostError;
EXPECT_EQ(r.swapLostError, EGL_CONTEXT_LOST)
<< "eglSwapBuffers on the lost context: 0x" << std::hex << r.swapLostError;
EXPECT_EQ(r.releaseOk, 1) << "releasing the lost context failed";
EXPECT_EQ(r.oldCurrent, EGL_FALSE) << "the lost context was made current again";
EXPECT_EQ(r.oldCurrentError, EGL_CONTEXT_LOST) << "eglMakeCurrent of the lost context: 0x" << std::hex
<< r.oldCurrentError;
EXPECT_EQ(r.oldCurrentError, EGL_CONTEXT_LOST)
<< "eglMakeCurrent of the lost context: 0x" << std::hex << r.oldCurrentError;
EXPECT_EQ(r.destroyOldOk, 1) << "the lost context could not be destroyed";
// A fresh session, and the new context renders.
ASSERT_EQ(r.newContextOk, 1) << "no context could be created after the loss (EGL error 0x" << std::hex
<< r.newContextError << ")\n" << r.note << "\n" << diagnostics;
<< r.newContextError << ")\n"
<< r.note << "\n"
<< diagnostics;
ASSERT_EQ(r.newCurrentOk, 1) << "the new context did not go current (EGL error 0x" << std::hex
<< r.newCurrentError << ")\n" << r.note << "\n" << diagnostics;
<< r.newCurrentError << ")\n"
<< r.note << "\n"
<< diagnostics;
EXPECT_EQ(r.serverPidAfter, r.serverPidBefore) << "the new session is not on the same server process";
EXPECT_EQ(r.resetStatusNew, static_cast<Uint32>(GL_NO_ERROR)) << "the new context reports a reset";
EXPECT_EQ(r.strategyNew, GL_LOSE_CONTEXT_ON_RESET) << "the replacement is not told of resets";
@@ -1114,13 +1122,15 @@ namespace {
EXPECT_EQ(r.oldTexturePublishedAfter, 0) << "the fresh session's client still believes it holds the "
"lost texture's record";
EXPECT_EQ(r.oldTextureOwedAfter, 0) << "an upload owed to the lost session is queued for the fresh one";
EXPECT_EQ(r.drawnPixel, kRed) << "the new context's textured draw did not read back: " << std::hex
<< r.drawnPixel << "\n" << r.note << "\n" << diagnostics;
EXPECT_EQ(r.secondPixel, kBlue) << "the new context's clear did not read back: " << std::hex
<< r.secondPixel;
EXPECT_EQ(r.drawnPixel, kRed)
<< "the new context's textured draw did not read back: " << std::hex << r.drawnPixel << "\n"
<< r.note << "\n"
<< diagnostics;
EXPECT_EQ(r.secondPixel, kBlue)
<< "the new context's clear did not read back: " << std::hex << r.secondPixel;
EXPECT_EQ(r.fboStatus, static_cast<Uint32>(GL_FRAMEBUFFER_COMPLETE)) << std::hex << r.fboStatus;
EXPECT_EQ(r.fboPixel, kYellow) << "the new context's texture framebuffer did not read back: " << std::hex
<< r.fboPixel;
EXPECT_EQ(r.fboPixel, kYellow)
<< "the new context's texture framebuffer did not read back: " << std::hex << r.fboPixel;
EXPECT_EQ(r.swapNew, EGL_TRUE) << "eglSwapBuffers on the new context failed";
EXPECT_EQ(r.resetStatusEnd, static_cast<Uint32>(GL_NO_ERROR)) << "the new session was lost too";
}
@@ -1129,10 +1139,12 @@ namespace {
// second session started and ended cleanly; nothing from the first reached it.
static void ExpectOneLossAndACleanSecondSession(ServerProcess& server) {
ASSERT_TRUE(WaitFor([&] { return Count(server.Log(), "in-process unix session #2 started") == 1; }, 5000))
<< "the client never opened a second session:\n" << server.Log();
<< "the client never opened a second session:\n"
<< server.Log();
// Both sessions' ends: the lost one's latched exit and the fresh one's clean one.
ASSERT_TRUE(WaitFor([&] { return Count(server.Log(), "reaped exit=") == 2; }, 10000))
<< "the second session did not end:\n" << server.Log();
<< "the second session did not end:\n"
<< server.Log();
const std::string log = server.Log();
EXPECT_NE(log.find("SessionLatch{BackendDeviceLost}"), std::string::npos) << log;
EXPECT_EQ(Count(log, "reaped exit=75"), 1u) << "the lost session did not end latched:\n" << log;
@@ -1142,7 +1154,8 @@ namespace {
// never created, a create or bind it cannot parse - each Fatal{ProtocolCorruption}.
EXPECT_EQ(Count(log, "SessionLatch{"), 1u) << "the recovered session latched too:\n" << log;
EXPECT_EQ(log.find("Fatal{ProtocolCorruption"), std::string::npos)
<< "the recovered session was sent something it never created:\n" << log;
<< "the recovered session was sent something it never created:\n"
<< log;
EXPECT_TRUE(server.pid > 0 && ::kill(server.pid, 0) == 0) << "the server died";
}
};
@@ -1245,7 +1258,8 @@ TEST_F(ClientRecovery, AThreadStillOnTheLostContextReachesNothingOfTheFreshSessi
EXPECT_EQ(r.recordsByStaleThread, 0) << "the thread on the lost context published records on the fresh session";
EXPECT_EQ(r.destroyOldOk, 1);
EXPECT_EQ(r.pixelAfterStale, kRed) << "the fresh context stopped rendering: " << std::hex << r.pixelAfterStale
<< "\n" << diagnostics;
<< "\n"
<< diagnostics;
EXPECT_EQ(r.resetStatusAfterStale, static_cast<Uint32>(GL_NO_ERROR)) << "the fresh session was lost too";
ExpectOneLossAndACleanSecondSession(server);
server.Stop();
@@ -1263,13 +1277,16 @@ TEST_F(ClientRecovery, ContextsNamingALostShareContextShareOneNewGroup) {
const std::string diagnostics = "server:\n" + server.Log() + "\nclient:\n" + client.Text();
ASSERT_EQ(r.initialized, 1) << r.note << "\n" << diagnostics;
ASSERT_EQ(r.firstOk, 1) << "eglCreateContext naming the lost share context failed (0x" << std::hex << r.firstError
<< ")\n" << r.note;
<< ")\n"
<< r.note;
ASSERT_EQ(r.secondOk, 1) << r.note;
EXPECT_EQ(r.sameGroup, 1) << "the replacements landed in separate share groups";
EXPECT_EQ(r.lostGroupReused, 0) << "a replacement joined the lost share group";
EXPECT_EQ(r.textureSeenAcross, 1) << "a texture of one replacement is not the other's";
EXPECT_EQ(r.drawnAcross, kRed) << "the shared texture did not draw on the other replacement: " << std::hex
<< r.drawnAcross << "\n" << r.note << "\n" << diagnostics;
<< r.drawnAcross << "\n"
<< r.note << "\n"
<< diagnostics;
ExpectOneLossAndACleanSecondSession(server);
server.Stop();
}
@@ -1293,11 +1310,10 @@ TEST_F(ClientRecovery, ThePidTargetedKnobLosesOnlyThatClientAndOnlyOnce) {
}
ClientLog bystanderLog("pid-bystander");
const BystanderReport bystander =
RunInClient<BystanderReport>(server, bystanderLog.base, &RunBystanderClient);
const BystanderReport bystander = RunInClient<BystanderReport>(server, bystanderLog.base, &RunBystanderClient);
const TargetedReport r = target.Release(server.endpoint);
const std::string diagnostics = "server:\n" + server.Log() + "\ntarget:\n" + targetLog.Text() +
"\nbystander:\n" + bystanderLog.Text();
const std::string diagnostics =
"server:\n" + server.Log() + "\ntarget:\n" + targetLog.Text() + "\nbystander:\n" + bystanderLog.Text();
ASSERT_EQ(bystander.initialized, 1) << bystander.note << "\n" << diagnostics;
EXPECT_GT(bystander.frames, 5);

Some files were not shown because too many files have changed in this diff Show More