From bf87d75d70b799a67ea721e43413bec9d411d524 Mon Sep 17 00:00:00 2001 From: Swung0x48 Date: Tue, 24 Nov 2026 01:37:51 -0400 Subject: [PATCH] [Feat] (...): advertise GL_OVR_multiview and GL_OVR_multiview2 on DirectGLES - Each string follows the driver's own extension; DirectVulkan advertises neither yet - The attachment's view count crosses the wire in MGPSurface, and num_views reaches the ESSL after a capability strip, outside the translation memo --- 3rdparty/glslang | 2 +- CMakeLists.txt | 1 + MobileGL/BackendCaps.h | 8 + .../DirectGLES/BackendObject_DirectGLES.cpp | 13 +- .../MG_Backend/DirectGLES/DirectGLESBlit.cpp | 3 +- MobileGL/MG_Backend/DirectGLES/Managers.h | 2 + .../DirectGLES/ManagersFramebuffers.cpp | 18 +- .../DirectGLES/ManagersPrograms.cpp | 11 + MobileGL/MG_Backend/DirectGLES/Utils.cpp | 30 +++ MobileGL/MG_Backend/DirectGLES/Utils.h | 9 + .../DirectVulkan/Renderer/WireFramebuffer.cpp | 2 +- .../MG_Impl/GLImpl/Drawing/GL_Drawing.cpp | 3 +- .../MG_Impl/GLImpl/Exporting/Definitions.cpp | 3 +- .../GLImpl/Framebuffer/GL_Framebuffer.cpp | 77 +----- .../GLImpl/Framebuffer/GL_Framebuffer.h | 23 ++ .../Framebuffer/GL_FramebufferMultiview.cpp | 223 ++++++++++++++++ .../MG_Impl/GLImpl/Framebuffer/Validators.cpp | 85 ++++++ .../MG_Impl/GLImpl/Framebuffer/Validators.h | 20 ++ MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp | 13 +- MobileGL/MG_Impl/GetProcAddress.cpp | 2 +- MobileGL/MG_Impl/Pipe/FramebufferEmit.h | 5 +- MobileGL/MG_Pipe/MGPipeTypes.h | 6 +- MobileGL/MG_Pipe/PipeFields.def | 4 +- MobileGL/MG_Pipe/generated/PipeWireLayout.inc | 2 + .../FramebufferState/FramebufferObject.cpp | 51 +++- .../FramebufferState/FramebufferObject.h | 20 +- .../GLState/ProgramState/ProgramArtifacts.h | 8 +- .../ProgramState/ProgramArtifactsCodec.h | 3 +- .../GLState/ProgramState/ProgramLinkTask.cpp | 24 ++ .../GLState/ProgramState/ProgramObject.h | 3 + .../MG_Test/Backend/DirectGLES/CMakeLists.txt | 6 + .../Backend/DirectGLES/MultiviewEsslTest.cpp | 197 ++++++++++++++ .../BackendLoader/BackendLoaderTest.cpp | 88 +++++++ MobileGL/MG_Test/Framebuffer/CMakeLists.txt | 1 + .../Framebuffer/FramebufferMultiviewTest.cpp | 246 ++++++++++++++++++ MobileGL/MG_Test/Program/CMakeLists.txt | 1 + .../Program/ProgramArtifactsCodecTest.cpp | 9 +- .../MG_Test/Program/ProgramArtifactsTest.cpp | 2 +- .../MG_Test/Program/ProgramMultiviewTest.cpp | 210 +++++++++++++++ .../MG_Util/BackendLoaders/OpenGL/Loader.cpp | 35 +++ .../MG_Util/BackendLoaders/OpenGL/Loader.h | 9 + .../ShaderTranspiler/ShaderCompiler.cpp | 36 +++ .../MG_Util/ShaderTranspiler/ShaderCompiler.h | 9 + .../ShaderSourceProcessor.cpp | 16 +- .../MachineIndependent/localintermediate.h | 12 + 45 files changed, 1450 insertions(+), 101 deletions(-) create mode 100644 MobileGL/MG_Impl/GLImpl/Framebuffer/GL_FramebufferMultiview.cpp create mode 100644 MobileGL/MG_Test/Backend/DirectGLES/MultiviewEsslTest.cpp create mode 100644 MobileGL/MG_Test/Framebuffer/FramebufferMultiviewTest.cpp create mode 100644 MobileGL/MG_Test/Program/ProgramMultiviewTest.cpp diff --git a/3rdparty/glslang b/3rdparty/glslang index d3c70bb6..892c1e3f 160000 --- a/3rdparty/glslang +++ b/3rdparty/glslang @@ -1 +1 @@ -Subproject commit d3c70bb6a167c25ff23dcdf1f5c736d760cab3b2 +Subproject commit 892c1e3fe5ee09874c885faf2fa69db2fa246c9e diff --git a/CMakeLists.txt b/CMakeLists.txt index fc7c5af3..c7d22bf2 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -480,6 +480,7 @@ set(SOURCE_FILES MobileGL/MG_Impl/GLImpl/RenderState/GL_RenderState.cpp MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.cpp MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp + MobileGL/MG_Impl/GLImpl/Framebuffer/GL_FramebufferMultiview.cpp MobileGL/MG_Impl/GLImpl/Program/GL_Program.cpp MobileGL/MG_Impl/GLImpl/Program/GL_ShaderObjectsARB.cpp MobileGL/MG_Impl/GLImpl/Program/ProgramInterface.cpp diff --git a/MobileGL/BackendCaps.h b/MobileGL/BackendCaps.h index 0d1a8902..fbd267af 100644 --- a/MobileGL/BackendCaps.h +++ b/MobileGL/BackendCaps.h @@ -103,6 +103,11 @@ namespace MobileGL { // GL_EXT_clip_control on DirectGLES. DirectVulkan applies clip control in its own // position fixup and does not read this. Bool ClipControl = false; + // GL_OVR_multiview and GL_OVR_multiview2, each only where the driver has that same + // extension (and, for the first, glFramebufferTextureMultiviewOVR). DirectGLES only: + // DirectVulkan has no multiview render pass route and leaves both false. + Bool Multiview = false; + Bool Multiview2 = false; }; // Coarse GPU vendor identity for gating device-specific quirks. Detected from the @@ -411,6 +416,9 @@ namespace MobileGL { Int MaxFragmentShadingRateAttachmentTexelHeight = 0; Int MaxFragmentShadingRateAttachmentTexelAspectRatio = 0; Int MaxFragmentShadingRateAttachmentLayers = 0; + // GL_MAX_VIEWS_OVR. Zero means no multiview, which is also why GL_OVR_multiview is not + // advertised then; a backend that has it reports at least the spec minimum of 2. + Int MaxViews = 0; static constexpr Bool IsSamplePositionCount(Int samples) { return samples >= 2 && samples <= kMaxSamplePositionCount && (samples & (samples - 1)) == 0; diff --git a/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp b/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp index a6596f88..c251a5b6 100644 --- a/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp +++ b/MobileGL/MG_Backend/DirectGLES/BackendObject_DirectGLES.cpp @@ -903,7 +903,9 @@ namespace MobileGL::MG_Backend::DirectGLES { capabilities.SupportsTextureView, capabilities.SupportsTextureCubeMapArray, AdvertisedFeatureSupport{.TessellationShader = capabilities.SupportsTessellationShader, .CullDistance = capabilities.MaxCullDistances > 0, - .ClipControl = capabilities.SupportsClipControl}); + .ClipControl = capabilities.SupportsClipControl, + .Multiview = capabilities.SupportsMultiview, + .Multiview2 = capabilities.SupportsMultiview2}); // Exactly what InitCapabilities forwards into the dynamic parameters: the base // extension and _primitive when the driver has them, _attachment not yet. auto& extensions = MutableRendererInfo().RendererGLInfo.Extensions; @@ -1585,6 +1587,14 @@ namespace MobileGL::MG_Backend::DirectGLES { if (features.ClipControl) { extensions.push_back(E_GL_ARB_clip_control); } + // Multiview attachments go to the driver's glFramebufferTextureMultiviewOVR and + // gl_ViewID_OVR to its own built-in, so each string follows the driver's. + if (features.Multiview) { + extensions.push_back(E_GL_OVR_multiview); + if (features.Multiview2) { + extensions.push_back(E_GL_OVR_multiview2); + } + } // Minecraft 26.3 checks this prerequisite before it even considers // GL_ARB_multi_draw_indirect. ES 3.1 supplies both single-draw entry points; the loader // folds the version and pointer checks into SupportsDrawIndirect. @@ -2022,6 +2032,7 @@ namespace MobileGL::MG_Backend::DirectGLES { // the device answers every query. The attachment is not forwarded yet, so it is not // claimed, whatever the driver offers. m_dynamicParameters.SupportsFragmentShadingRate = m_GLESCapabilities.SupportsFragmentShadingRate; + m_dynamicParameters.MaxViews = m_GLESCapabilities.SupportsMultiview ? m_GLESCapabilities.MaxViews : 0; m_dynamicParameters.SupportsPrimitiveFragmentShadingRate = m_GLESCapabilities.SupportsFragmentShadingRatePrimitive; m_dynamicParameters.SupportsAttachmentFragmentShadingRate = false; diff --git a/MobileGL/MG_Backend/DirectGLES/DirectGLESBlit.cpp b/MobileGL/MG_Backend/DirectGLES/DirectGLESBlit.cpp index 3075918b..cfef37ff 100644 --- a/MobileGL/MG_Backend/DirectGLES/DirectGLESBlit.cpp +++ b/MobileGL/MG_Backend/DirectGLES/DirectGLESBlit.cpp @@ -1045,7 +1045,8 @@ namespace MobileGL::MG_Backend::DirectGLES { const auto& color = record.Color[i]; if (color.Res == record.ReadSurface.Res && color.Kind == record.ReadSurface.Kind && color.Layered == record.ReadSurface.Layered && color.Level == record.ReadSurface.Level && - color.Layer == record.ReadSurface.Layer && color.UploadTarget == record.ReadSurface.UploadTarget) { + color.NumViews == record.ReadSurface.NumViews && color.Layer == record.ReadSurface.Layer && + color.UploadTarget == record.ReadSurface.UploadTarget) { return static_cast(static_cast(FramebufferAttachmentType::Color0) + static_cast(i)); } diff --git a/MobileGL/MG_Backend/DirectGLES/Managers.h b/MobileGL/MG_Backend/DirectGLES/Managers.h index b36b3121..7553934c 100644 --- a/MobileGL/MG_Backend/DirectGLES/Managers.h +++ b/MobileGL/MG_Backend/DirectGLES/Managers.h @@ -2673,6 +2673,8 @@ namespace MobileGL::MG_Backend::DirectGLES { // build's (ProgramBuildSource), so the pull build compiles the very same text // against a ProgramObject and G1's byte identity survives. Uint GetExternalIndex() const { return Identity; } + // GL_OVR_multiview's num_views of the vertex stage, 0 without one. + Int GetVertexNumViews() const { return Link ? Link->vsNumViews : 0; } Bool GetLinkStatus() const { return Linked; } Bool GetSpirvStatus() const { return SpirvUsable; } Bool GetSpirvValidationEnabled() const { return SpirvValidationEnabled; } diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp index 1a0a4692..60a40233 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersFramebuffers.cpp @@ -409,7 +409,21 @@ namespace MobileGL::MG_Backend::DirectGLES { // texture behind the staged shadow's back (the frontend arm's note, by handle). TextureImpl::NoteDriverSideTextureWriteByHandle(surface.Res); const auto uploadTarget = static_cast(surface.UploadTarget); - if (surface.Layered != 0) { + if (surface.NumViews != 0) { + // GL_OVR_multiview. The frontend only builds one where the driver has the + // extension, but the record is the untrusted half: a multiview surface on a + // driver without the entry point is refused by name, never called through. + if (!g_GLESCapabilities.SupportsMultiview) { + MGLOG_E_ONCE("MGPipe: attachment surface {%u, %u} is multiview, but this driver has no " + "GL_OVR_multiview - refusing to attach it", + surface.Res.Slot, surface.Res.Gen); + return false; + } + g_GLESFuncs.glFramebufferTextureMultiviewOVR( + glFBOTarget, glBackendAttachment, backendTextureObject->GetBackendTextureId(), + static_cast(surface.Level), static_cast(surface.Layer), + static_cast(surface.NumViews)); + } else if (surface.Layered != 0) { g_GLESFuncs.glFramebufferTexture(glFBOTarget, glBackendAttachment, backendTextureObject->GetBackendTextureId(), static_cast(surface.Level)); @@ -580,7 +594,7 @@ namespace MobileGL::MG_Backend::DirectGLES { const auto& color = record.Color[i]; if (color.Res == record.ReadSurface.Res && color.Kind == record.ReadSurface.Kind && color.Layered == record.ReadSurface.Layered && color.Level == record.ReadSurface.Level && - color.Layer == record.ReadSurface.Layer && + color.NumViews == record.ReadSurface.NumViews && color.Layer == record.ReadSurface.Layer && color.UploadTarget == record.ReadSurface.UploadTarget) { pushedReadBuf = static_cast( static_cast(FramebufferAttachmentType::Color0) + static_cast(i)); diff --git a/MobileGL/MG_Backend/DirectGLES/ManagersPrograms.cpp b/MobileGL/MG_Backend/DirectGLES/ManagersPrograms.cpp index 443e2326..0cfccd38 100644 --- a/MobileGL/MG_Backend/DirectGLES/ManagersPrograms.cpp +++ b/MobileGL/MG_Backend/DirectGLES/ManagersPrograms.cpp @@ -1371,6 +1371,14 @@ namespace MobileGL::MG_Backend::DirectGLES { } } + // After every validating pass: the module that comes back names ViewIndex without the + // capability, which only SPIRV-Cross reads (see StripMultiviewCapabilityForEssl). + Vector multiviewStrippedSpirv; + if (MG_Util::ShaderTranspiler::ShaderCompiler::StripMultiviewCapabilityForEssl(*effectiveSpirv, + multiviewStrippedSpirv)) { + effectiveSpirv = &multiviewStrippedSpirv; + } + MG_Util::ShaderTranspiler::SpvcSession spvcSession(*effectiveSpirv, MG_Util::ShaderTranspiler::SessionUsageBit::Transpile); @@ -2155,6 +2163,9 @@ namespace MobileGL::MG_Backend::DirectGLES { !(ViewportArrayEmulationEnabled() && programRoutesViewportIndex) && source.find("gl_ViewportIndex") != String::npos; source = RequestViewportArrayExtension(std::move(source), needsViewportArrayExtension); + // GL_OVR_multiview's directive and num_views, which the memoized ESSL leaves out. + source = RequestMultiviewExtension(std::move(source), glShaderType, src.GetVertexNumViews(), + g_GLESCapabilities.SupportsMultiview2); // The fourth header-level rewrite, and the same shape as the third: ESSL has no // gl_PointSize in a tessellation or geometry stage at ANY version - 320 makes the diff --git a/MobileGL/MG_Backend/DirectGLES/Utils.cpp b/MobileGL/MG_Backend/DirectGLES/Utils.cpp index 1bac044b..78dc84d4 100644 --- a/MobileGL/MG_Backend/DirectGLES/Utils.cpp +++ b/MobileGL/MG_Backend/DirectGLES/Utils.cpp @@ -741,6 +741,36 @@ namespace MobileGL::MG_Backend::DirectGLES { return glslCode; } + String RequestMultiviewExtension(String glslCode, GLenum shaderType, Int numViews, Bool driverHasMultiview2) { + const Bool declaresViews = shaderType == GL_VERTEX_SHADER && numViews > 0; + if (!declaresViews && glslCode.find("gl_ViewID_OVR") == String::npos) return glslCode; + const String directive = std::format("#extension {} : require\n", + driverHasMultiview2 ? "GL_OVR_multiview2" : "GL_OVR_multiview"); + // The directive goes right after #version; num_views is a declaration, so it goes after + // the LAST directive, where ESSL lets non-preprocessor tokens start. + const SizeT versionPos = glslCode.find("#version"); + const SizeT versionEnd = versionPos == String::npos ? String::npos : glslCode.find('\n', versionPos); + glslCode.insert(versionEnd == String::npos ? 0 : versionEnd + 1, directive); + if (!declaresViews) return glslCode; + SizeT insertAt = 0; + for (SizeT lineStart = 0; lineStart < glslCode.size();) { + const SizeT lineEnd = glslCode.find('\n', lineStart); + const SizeT next = lineEnd == String::npos ? glslCode.size() : lineEnd + 1; + const SizeT first = glslCode.find_first_not_of(" \t\r\n", lineStart); + if (first == String::npos) break; + if (first >= next) { + lineStart = next; // a blank line + continue; + } + if (glslCode[first] != '#') break; + insertAt = next; + lineStart = next; + } + if (insertAt > 0 && glslCode[insertAt - 1] != '\n') glslCode.insert(insertAt++, "\n"); + glslCode.insert(insertAt, std::format("layout(num_views = {}) in;\n", numViews)); + return glslCode; + } + String RequestViewportArrayExtension(String glslCode, Bool needed) { #ifdef TRACY_ENABLE ZoneScopedC(TRACY_ZONECOLOR_BACKEND); diff --git a/MobileGL/MG_Backend/DirectGLES/Utils.h b/MobileGL/MG_Backend/DirectGLES/Utils.h index 3a780443..3f63a06a 100644 --- a/MobileGL/MG_Backend/DirectGLES/Utils.h +++ b/MobileGL/MG_Backend/DirectGLES/Utils.h @@ -229,6 +229,15 @@ namespace MobileGL::MG_Backend::DirectGLES { // error, so this is never emitted speculatively. A no-op when not needed or already // present. String RequestViewportArrayExtension(String glslCode, Bool needed); + // GL_OVR_multiview: adds `#extension GL_OVR_multiview2 : require` (GL_OVR_multiview where + // the driver has only that one) to a stage that names gl_ViewID_OVR or, in the vertex + // stage, declares `numViews`, and `layout(num_views = numViews) in;` to that vertex stage. + // The SPIR-V reaching SPIRV-Cross carries neither (StripMultiviewCapabilityForEssl), so the + // translation it memoizes stays independent of the view count. Frontend shaders that + // declare only GL_OVR_multiview already keep gl_ViewID_OVR out of every output but + // gl_Position, so asking for the smaller extension on such a driver is honest. A no-op + // for every other stage. + String RequestMultiviewExtension(String glslCode, GLenum shaderType, Int numViews, Bool driverHasMultiview2); // Adds `#extension : require` when a TESSELLATION or GEOMETRY stage's // emitted ESSL names gl_PointSize. Desktop GL has that built-in in gl_PerVertex for every // vertex-processing stage; ESSL does NOT have it in those two at any version - not even diff --git a/MobileGL/MG_Backend/DirectVulkan/Renderer/WireFramebuffer.cpp b/MobileGL/MG_Backend/DirectVulkan/Renderer/WireFramebuffer.cpp index 331228ba..a5e4e716 100644 --- a/MobileGL/MG_Backend/DirectVulkan/Renderer/WireFramebuffer.cpp +++ b/MobileGL/MG_Backend/DirectVulkan/Renderer/WireFramebuffer.cpp @@ -2298,7 +2298,7 @@ namespace MobileGL::MG_Backend::DirectVulkan { MG_Pipe::MGPSurface surface{}; surface.Kind = MG_Pipe::kMGPipeSurfaceKindTexture; surface.Res = state.VerbCopyTexDst; - surface.Level = static_cast(level); + surface.Level = static_cast(level); WireImage source = ResolveWireImage(*read, aspect & VK_IMAGE_ASPECT_DEPTH_BIT ? read->Depth : aspect & VK_IMAGE_ASPECT_STENCIL_BIT ? read->Stencil diff --git a/MobileGL/MG_Impl/GLImpl/Drawing/GL_Drawing.cpp b/MobileGL/MG_Impl/GLImpl/Drawing/GL_Drawing.cpp index 75d6c153..3a387a71 100644 --- a/MobileGL/MG_Impl/GLImpl/Drawing/GL_Drawing.cpp +++ b/MobileGL/MG_Impl/GLImpl/Drawing/GL_Drawing.cpp @@ -21,6 +21,7 @@ // in FixupGsStripCaptureOrder - for the reason CONTRACT-P5B.md §6.5 gives. #include #include "../Getter/GL_Getter.h" +#include "../Framebuffer/GL_Framebuffer.h" namespace MobileGL::MG_Impl::GLImpl { static Bool ValidateProgramForExecution(const SharedPtr& currentProgram, @@ -87,7 +88,7 @@ namespace MobileGL::MG_Impl::GLImpl { return false; } - return true; + return ValidateMultiviewDraw(*currentProgram, functionName); } // gl_NumSamples has no SPIR-V built-in, so the source pipeline lowers it onto a reserved diff --git a/MobileGL/MG_Impl/GLImpl/Exporting/Definitions.cpp b/MobileGL/MG_Impl/GLImpl/Exporting/Definitions.cpp index 1270df39..debb3423 100644 --- a/MobileGL/MG_Impl/GLImpl/Exporting/Definitions.cpp +++ b/MobileGL/MG_Impl/GLImpl/Exporting/Definitions.cpp @@ -2041,6 +2041,8 @@ DECLARE_GL_FUNCTION_STUB_HEAD(void, GetPixelTransformParameterivEXT, GLenum targ DECLARE_GL_FUNCTION_STUB_HEAD(void, GetPixelTransformParameterfvEXT, GLenum target, GLenum pname, GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetPixelTransformParameterfvEXT, target, pname, params) DECLARE_GL_FUNCTION_STUB_HEAD(void, PointParameterfEXT, GLenum pname, GLfloat param) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, PointParameterfEXT, pname, param) DECLARE_GL_FUNCTION_STUB_HEAD(void, PointParameterfvEXT, GLenum pname, const GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, PointParameterfvEXT, pname, params) +DECLARE_GL_FUNCTION_HEAD(void, FramebufferTextureMultiviewOVR, GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) DECLARE_GL_FUNCTION_END_NO_RETURN(void, FramebufferTextureMultiviewOVR, target, attachment, texture, level, baseViewIndex, numViews) +DECLARE_GL_FUNCTION_HEAD(void, NamedFramebufferTextureMultiviewOVR, GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) DECLARE_GL_FUNCTION_END_NO_RETURN(void, NamedFramebufferTextureMultiviewOVR, framebuffer, attachment, texture, level, baseViewIndex, numViews) DECLARE_GL_FUNCTION_HEAD(void, GetFragmentShadingRatesEXT, GLsizei samples, GLsizei maxCount, GLsizei* count, GLenum* shadingRates) DECLARE_GL_FUNCTION_END_NO_RETURN(void, GetFragmentShadingRatesEXT, samples, maxCount, count, shadingRates) DECLARE_GL_FUNCTION_HEAD(void, ShadingRateEXT, GLenum rate) DECLARE_GL_FUNCTION_END_NO_RETURN(void, ShadingRateEXT, rate) DECLARE_GL_FUNCTION_HEAD(void, ShadingRateCombinerOpsEXT, GLenum combinerOp0, GLenum combinerOp1) DECLARE_GL_FUNCTION_END_NO_RETURN(void, ShadingRateCombinerOpsEXT, combinerOp0, combinerOp1) @@ -2694,7 +2696,6 @@ DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterivNV, GLuint vide DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterfvNV, GLuint video_capture_slot, GLuint stream, GLenum pname, const GLfloat* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, VideoCaptureStreamParameterfvNV, video_capture_slot, stream, pname, params) DECLARE_GL_FUNCTION_STUB_HEAD(void, VideoCaptureStreamParameterdvNV, GLuint video_capture_slot, GLuint stream, GLenum pname, const GLdouble* params) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, VideoCaptureStreamParameterdvNV, video_capture_slot, stream, pname, params) DECLARE_GL_FUNCTION_STUB_HEAD(void, ViewportSwizzleNV, GLuint index, GLenum swizzlex, GLenum swizzley, GLenum swizzlez, GLenum swizzlew) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, ViewportSwizzleNV, index, swizzlex, swizzley, swizzlez, swizzlew) -DECLARE_GL_FUNCTION_STUB_HEAD(void, FramebufferTextureMultiviewOVR, GLenum target, GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, FramebufferTextureMultiviewOVR, target, attachment, texture, level, baseViewIndex, numViews) DECLARE_GL_FUNCTION_STUB_HEAD(void, HintPGI, GLenum target, GLint mode) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, HintPGI, target, mode) DECLARE_GL_FUNCTION_STUB_HEAD(void, DetailTexFuncSGIS, GLenum target, GLsizei n, const GLfloat* points) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, DetailTexFuncSGIS, target, n, points) DECLARE_GL_FUNCTION_STUB_HEAD(void, GetDetailTexFuncSGIS, GLenum target, GLfloat* points) DECLARE_GL_FUNCTION_STUB_END_NO_RETURN(void, GetDetailTexFuncSGIS, target, points) diff --git a/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp b/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp index eba8df20..d0879325 100644 --- a/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp +++ b/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.cpp @@ -111,6 +111,7 @@ namespace MobileGL::MG_Impl::GLImpl { // property no single attachment's state explains. GLenum IncompleteFramebufferStatus(const MG_State::GLState::FramebufferObject& framebufferObject) { if (framebufferObject.HasLayerTargetMismatch()) return GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS; + if (framebufferObject.HasViewTargetMismatch()) return GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR; return HasDefinedAttachment(framebufferObject) ? GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT : GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT; } @@ -363,6 +364,9 @@ namespace MobileGL::MG_Impl::GLImpl { Bool TryAnswerAttachmentFormatQuery(const MG_State::GLState::FramebufferAttachmentObject* attachmentObject, FramebufferAttachmentType attachmentType, Bool depthStencilAlias, GLenum pname, GLint* params, const char* caller) { + // The two GL_OVR_multiview pnames take the same fallback out of both query switches. + if (FramebufferImpl::TryAnswerMultiviewAttachmentQuery(attachmentObject, pname, params, caller)) + return true; switch (pname) { case GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE: case GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE: @@ -489,72 +493,8 @@ namespace MobileGL::MG_Impl::GLImpl { } } - // GL 4.6 core 9.2.8 conditions that depend only on the framebuffer and the attachment - // point. Shared, because glFramebufferTexture / 1D / 2D / 3D / TextureLayer are aliases of - // one another in that section and a CTS case that walks the family must not get five - // different answers - which is exactly what happened when these lived in one helper that - // only two of the five went through. - Bool ValidateFramebufferTextureAttachmentPoint( - const char* functionName, const SharedPtr& framebufferObject, - FramebufferAttachmentType attachmentType) { - // "An INVALID_OPERATION error is generated if COLOR_ATTACHMENTm is used with m greater - // than or equal to MAX_COLOR_ATTACHMENTS." - if (!FramebufferImpl::ValidateColorAttachmentInRange(attachmentType, functionName)) return false; - // "An INVALID_OPERATION error is generated if zero is bound to target." MobileGL keeps - // a real FramebufferObject for framebuffer 0, so a null test can never see this - the - // object is always there, and framebuffer 0 has to be recognized by identity instead, - // the same comparison DrawBuffers_State makes. Without this an attach onto the default - // framebuffer silently REPLACED its color attachment, permanently desynchronizing it - // from what the swapchain keeps publishing. - const auto& defaultFramebufferInfo = FramebufferImpl::pDefaultFramebufferInfo; - if (!framebufferObject || - (defaultFramebufferInfo && framebufferObject == defaultFramebufferInfo->defaultFBO)) { - MG_State::pGLContext->RecordError( - ErrorCode::InvalidOperation, - MakeUnique( - "MG_Impl/GLImpl", functionName, - "No framebuffer object is bound to the target; the default framebuffer's attachments " - "cannot be named.")); - return false; - } - return true; - } - - // The other half of 9.2.8: "level must be greater than or equal to zero", and for a - // texture with immutable storage it "must be smaller than the number of levels the texture - // has". Split from the attachment-point half because the caller only has a texture object - // once the detach (texture == 0) case is behind it. - Bool ValidateFramebufferTextureLevel(const char* functionName, - const SharedPtr& textureObject, - GLint level) { - if (level < 0) { - MG_State::pGLContext->RecordError(ErrorCode::InvalidValue, - MakeUnique("MG_Impl/GLImpl", functionName, - "Texture level must be non-negative.")); - return false; - } - if (!textureObject || !textureObject->IsImmutable()) { - // A mutable texture has no level bound here: a level it has not specified yet is - // not an error, it just leaves the framebuffer incomplete. - return true; - } - // GetAddressableLevelCount(), NOT GetImmutableLevels(): for a VIEW the latter is - // deliberately the ORIGINAL texture's count (GL 4.6 core 8.18 defines - // TEXTURE_IMMUTABLE_LEVELS on a view that way), which is far too large a bound - a - // two-level view onto a ten-level texture would accept level 5 and attach an image - // nothing can draw into. - const Uint levelBound = textureObject->GetAddressableLevelCount(); - if (static_cast(level) >= levelBound) { - MG_State::pGLContext->RecordError( - ErrorCode::InvalidValue, - MakeUnique( - "MG_Impl/GLImpl", functionName, - std::format("Texture level {} is beyond the {} level(s) this texture has.", level, - levelBound))); - return false; - } - return true; - } + using FramebufferImpl::ValidateFramebufferTextureAttachmentPoint; + using FramebufferImpl::ValidateFramebufferTextureLevel; void AttachFramebufferTextureWithUploadTarget(const char* functionName, GLenum target, GLenum attachment, GLuint texture, GLint level, @@ -2650,6 +2590,8 @@ namespace MobileGL::MG_Impl::GLImpl { ? FramebufferImpl::pDefaultFramebufferInfo->defaultFBO : GetNamedFramebufferObject_State(drawFramebuffer, "BlitNamedFramebuffer_State"); if (!readObject || !drawObject) return; + if (!FramebufferImpl::ValidateReadFramebufferIsSingleView(readObject.get(), "BlitNamedFramebuffer_State")) + return; BlitNamedFramebuffer_Backend(readObject, drawObject, srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); @@ -2910,6 +2852,8 @@ namespace MobileGL::MG_Impl::GLImpl { MakeUnique("MG_Impl/GLImpl", "ReadPixels_State", "Framebuffer is incomplete")); return false; } + if (!FramebufferImpl::ValidateReadFramebufferIsSingleView(framebufferObject.get(), "ReadPixels_State")) + return false; // Check for required buffers if (textureInputFormat == TextureInputFormat::StencilIndex) { @@ -3364,6 +3308,7 @@ namespace MobileGL::MG_Impl::GLImpl { void BlitFramebuffer(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter) { if (!ValidateBlitMaskAndFilter(__func__, mask, filter)) return; + if (!FramebufferImpl::ValidateBoundReadFramebufferIsSingleView(__func__)) return; BlitFramebuffer_Backend(srcX0, srcY0, srcX1, srcY1, dstX0, dstY0, dstX1, dstY1, mask, filter); } diff --git a/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h b/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h index 7dc6954d..9978cf73 100644 --- a/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h +++ b/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h @@ -11,6 +11,10 @@ #include #include +namespace MobileGL::MG_State::GLState { + class ProgramObject; +} // namespace MobileGL::MG_State::GLState + namespace MobileGL::MG_Impl::GLImpl { /* @INSERTION_POINT:FUNCTION_DECLARATION@ */ void ReadPixels(GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void* pixels); @@ -55,6 +59,25 @@ namespace MobileGL::MG_Impl::GLImpl { void NamedFramebufferTexture3D(GLuint framebuffer, GLenum attachment, GLenum textarget, GLuint texture, GLint level, GLint zoffset); void NamedFramebufferTextureLayer(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, GLint layer); + // GL_OVR_multiview (GL_FramebufferMultiview.cpp). + void FramebufferTextureMultiviewOVR(GLenum target, GLenum attachment, GLuint texture, GLint level, + GLint baseViewIndex, GLsizei numViews); + void NamedFramebufferTextureMultiviewOVR(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, + GLint baseViewIndex, GLsizei numViews); + void FramebufferTextureMultiviewOVR_State(GLenum target, GLenum attachment, GLuint texture, GLint level, + GLint baseViewIndex, GLsizei numViews); + void NamedFramebufferTextureMultiviewOVR_State(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, + GLint baseViewIndex, GLsizei numViews); + // GL_MAX_VIEWS_OVR as the active backend reports it; zero without a backend or without multiview, + // which is exactly when GL_OVR_multiview is not advertised. + Int GetMaxViews_State(); + Bool IsMultiviewSupported_State(); + // The draw-time rules of GL_OVR_multiview for `program` against the bound draw framebuffer. + // Records INVALID_OPERATION and returns false when the draw must be dropped. + Bool ValidateMultiviewDraw(const MG_State::GLState::ProgramObject& program, const char* functionName); + // The framebuffer object a DSA entry point names, or null with INVALID_OPERATION recorded. + SharedPtr GetNamedFramebufferObject_State(GLuint framebuffer, + const char* caller); void NamedFramebufferDrawBuffer(GLuint framebuffer, GLenum buf); void NamedFramebufferDrawBuffers(GLuint framebuffer, GLsizei n, const GLenum* bufs); void NamedFramebufferReadBuffer(GLuint framebuffer, GLenum src); diff --git a/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_FramebufferMultiview.cpp b/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_FramebufferMultiview.cpp new file mode 100644 index 00000000..d5b94c95 --- /dev/null +++ b/MobileGL/MG_Impl/GLImpl/Framebuffer/GL_FramebufferMultiview.cpp @@ -0,0 +1,223 @@ +// MobileGL - MobileGL/MG_Impl/GLImpl/Framebuffer/GL_FramebufferMultiview.cpp +// Copyright (c) 2025-2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +// GL_OVR_multiview: the two attaching entry points, the attachment queries and the draw-time rules. +// A multiview attachment is a FramebufferAttachmentObject of a 2D array texture whose layer is the +// base view index and whose view count is non-zero; the rest of the framebuffer code reads it +// through FramebufferObject::GetViewCount() and HasViewTargetMismatch(). +#include "GL_Framebuffer.h" +#include "Validators.h" +#include +#include +#include +#include +#include +#include + +namespace MobileGL::MG_Impl::GLImpl { + namespace { + void RecordMultiviewError(ErrorCode code, const char* functionName, String detail) { + MG_State::pGLContext->RecordError( + code, MakeUnique("MG_Impl/GLImpl", functionName, Move(detail))); + } + + const MG_Backend::DynamicBackendParameters& ActiveBackendLimits() { + static const MG_Backend::DynamicBackendParameters kNoBackend{}; + return MG_Backend::pActiveBackendObject ? MG_Backend::pActiveBackendObject->GetDynamicParameters() + : kNoBackend; + } + + // The checks of the spec that do not depend on the framebuffer object, in its order: + // FramebufferTextureLayer's own errors other than the layer ones, then numViews against + // MAX_VIEWS_OVR, then the texture-dependent ones. Returns the texture to attach, or null + // with `ok` telling a detach (texture 0) apart from a refusal. + SharedPtr ValidateMultiviewTexture(const char* functionName, GLuint texture, + GLint level, GLint baseViewIndex, + GLsizei numViews, Bool& ok) { + ok = false; + const Int maxViews = GetMaxViews_State(); + if (numViews < 1 || numViews > maxViews) { + RecordMultiviewError( + ErrorCode::InvalidValue, functionName, + std::format("numViews {} is outside [1, GL_MAX_VIEWS_OVR = {}].", numViews, maxViews)); + return nullptr; + } + if (texture == 0) { + ok = true; + return nullptr; + } + const auto& textureObject = MG_State::pGLContext->GetTextureObject(texture); + if (!textureObject) { + RecordMultiviewError(ErrorCode::InvalidOperation, functionName, + std::format("Texture object {} is not valid.", texture)); + return nullptr; + } + if (textureObject->GetTarget() != TextureTarget::Texture2DArray) { + RecordMultiviewError(ErrorCode::InvalidOperation, functionName, + "A multiview attachment must be a two-dimensional array texture."); + return nullptr; + } + if (!FramebufferImpl::ValidateFramebufferTextureLevel(functionName, textureObject, level)) return nullptr; + if (baseViewIndex < 0) { + RecordMultiviewError(ErrorCode::InvalidValue, functionName, "baseViewIndex must be non-negative."); + return nullptr; + } + const Int maxLayers = ActiveBackendLimits().MaxArrayTextureLayers; + if (static_cast(baseViewIndex) + numViews > maxLayers) { + RecordMultiviewError(ErrorCode::InvalidValue, functionName, + std::format("baseViewIndex {} + numViews {} exceeds GL_MAX_ARRAY_TEXTURE_LAYERS " + "({}).", + baseViewIndex, numViews, maxLayers)); + return nullptr; + } + ok = true; + return textureObject; + } + + // Shared tail of both entry points once the framebuffer object is known. Returns whether + // the framebuffer changed. + Bool AttachMultiview(const char* functionName, + const SharedPtr& framebufferObject, + GLenum attachment, GLuint texture, GLint level, GLint baseViewIndex, GLsizei numViews) { + if (!IsMultiviewSupported_State()) { + RecordMultiviewError(ErrorCode::InvalidOperation, functionName, + "GL_OVR_multiview is not supported by the active backend."); + return false; + } + const Bool depthStencil = attachment == GL_DEPTH_STENCIL_ATTACHMENT; + const FramebufferAttachmentType attachmentType = + depthStencil ? FramebufferAttachmentType::Depth + : MG_Util::ConvertGLEnumToFramebufferAttachmentType(attachment); + if (!FramebufferImpl::ValidateFramebufferAttachmentType(attachmentType)) return false; + if (!FramebufferImpl::ValidateFramebufferTextureAttachmentPoint(functionName, framebufferObject, + attachmentType)) { + return false; + } + Bool ok = false; + const auto textureObject = + ValidateMultiviewTexture(functionName, texture, level, baseViewIndex, numViews, ok); + if (!ok) return false; + + const FramebufferAttachmentType stencil = FramebufferAttachmentType::Stencil; + if (!textureObject) { + framebufferObject->Detach(attachmentType); + if (depthStencil) framebufferObject->Detach(stencil); + return true; + } + const auto attach = [&](FramebufferAttachmentType type) { + framebufferObject->AttachTexture(type, textureObject, TextureUploadTarget::Texture2DArray, level, + baseViewIndex, /*layered=*/false, numViews); + }; + attach(attachmentType); + if (depthStencil) attach(stencil); + return true; + } + } // namespace + + Int GetMaxViews_State() { + return std::max(ActiveBackendLimits().MaxViews, 0); + } + + Bool IsMultiviewSupported_State() { + return MG_Backend::pActiveBackendObject != nullptr && GetMaxViews_State() > 0; + } + + void FramebufferTextureMultiviewOVR_State(GLenum target, GLenum attachment, GLuint texture, GLint level, + GLint baseViewIndex, GLsizei numViews) { + if (target == GL_FRAMEBUFFER) target = GL_DRAW_FRAMEBUFFER; + const FramebufferTarget framebufferTarget = MG_Util::ConvertGLEnumToFramebufferTarget(target); + if (!FramebufferImpl::ValidateFramebufferTarget(framebufferTarget)) return; + if (!TextureImpl::ValidateTextureName(texture, true)) return; + const auto& framebufferObject = + MG_State::pGLContext->GetFramebufferBindingSlot(framebufferTarget).GetBoundObject(); + AttachMultiview(__func__, framebufferObject, attachment, texture, level, baseViewIndex, numViews); + } + + void NamedFramebufferTextureMultiviewOVR_State(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, + GLint baseViewIndex, GLsizei numViews) { + const auto framebufferObject = GetNamedFramebufferObject_State(framebuffer, __func__); + if (!framebufferObject) return; + if (AttachMultiview(__func__, framebufferObject, attachment, texture, level, baseViewIndex, numViews)) { + // A DSA mutator has no validate point, so the record goes out now (see + // PipePublishFramebufferByName in GL_Framebuffer.cpp). + MG_Pipe::MGPipeFramebufferEmitterInstance().EmitFramebufferByName(*framebufferObject); + } + } + + Bool ValidateMultiviewDraw(const MG_State::GLState::ProgramObject& program, const char* functionName) { + // Without backend multiview no framebuffer can be multiview, so a single-view program + // needs no framebuffer walk on every draw. + if (program.GetMultiviewViewCount() == 1 && !IsMultiviewSupported_State()) return true; + const auto& drawFramebuffer = + MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).GetBoundObject(); + const Int framebufferViews = drawFramebuffer ? drawFramebuffer->GetViewCount() : 1; + const Int programViews = program.GetMultiviewViewCount(); + // GL_OVR_multiview 11.1.3.11 / 16.X: the program's num_views (1 without the qualifier) + // must be the draw framebuffer's view count. + if (framebufferViews != programViews) { + RecordMultiviewError(ErrorCode::InvalidOperation, functionName, + std::format("The program renders {} view(s) but the draw framebuffer has {}.", + programViews, framebufferViews)); + return false; + } + if (!drawFramebuffer || !drawFramebuffer->IsMultiview()) return true; + // A multiview draw framebuffer takes no geometry or tessellation stage and no active, + // unpaused transform feedback. + if (program.HasLinkedShaderStage(ShaderStage::Geometry) || + program.HasLinkedShaderStage(ShaderStage::TessControl) || + program.HasLinkedShaderStage(ShaderStage::TessEval)) { + RecordMultiviewError(ErrorCode::InvalidOperation, functionName, + "A multiview draw cannot run a geometry or tessellation stage."); + return false; + } + if (MG_State::pGLContext->IsTransformFeedbackActive() && !MG_State::pGLContext->IsTransformFeedbackPaused()) { + RecordMultiviewError(ErrorCode::InvalidOperation, functionName, + "A multiview draw cannot capture transform feedback."); + return false; + } + return true; + } + + namespace FramebufferImpl { + Bool TryAnswerMultiviewAttachmentQuery(const MG_State::GLState::FramebufferAttachmentObject* attachmentObject, + GLenum pname, GLint* params, const char* caller) { + if (pname != GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR && + pname != GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR) { + return false; + } + if (!IsMultiviewSupported_State()) return false; + const Bool nothingAttached = + attachmentObject == nullptr || attachmentObject->IsEmpty() || !attachmentObject->IsValid(); + if (!nothingAttached && !attachmentObject->IsTexture()) { + RecordMultiviewError(ErrorCode::InvalidEnum, caller, + std::format("pname {:#x} is only defined for a texture attachment.", pname)); + return true; + } + // Zero for a texture attachment that is not multiview, as the spec answers for one + // that is not a two-dimensional array texture; FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER + // already reads the base view index. + const Bool multiview = !nothingAttached && attachmentObject->IsMultiview(); + if (pname == GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR) { + *params = multiview ? static_cast(attachmentObject->GetNumViews()) : 0; + } else { + *params = multiview ? static_cast(attachmentObject->GetTextureLayer()) : 0; + } + return true; + } + } // namespace FramebufferImpl + + void FramebufferTextureMultiviewOVR(GLenum target, GLenum attachment, GLuint texture, GLint level, + GLint baseViewIndex, GLsizei numViews) { + FramebufferTextureMultiviewOVR_State(target, attachment, texture, level, baseViewIndex, numViews); + } + + void NamedFramebufferTextureMultiviewOVR(GLuint framebuffer, GLenum attachment, GLuint texture, GLint level, + GLint baseViewIndex, GLsizei numViews) { + NamedFramebufferTextureMultiviewOVR_State(framebuffer, attachment, texture, level, baseViewIndex, numViews); + } +} // namespace MobileGL::MG_Impl::GLImpl diff --git a/MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.cpp b/MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.cpp index b48b8e39..4f2ad5cd 100644 --- a/MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.cpp +++ b/MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.cpp @@ -7,6 +7,7 @@ // End of Source File Header #include "Validators.h" +#include "GL_Framebuffer.h" #include #include #include @@ -178,6 +179,7 @@ namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl { "Read framebuffer is not framebuffer complete.")); return false; } + if (!ValidateReadFramebufferIsSingleView(framebufferObject.get(), caller)) return false; const FramebufferAttachmentType readBuffer = framebufferObject->GetReadBuffer(); if (readBuffer == FramebufferAttachmentType::None || !framebufferObject->GetAttachment(readBuffer).IsValid()) { @@ -210,4 +212,87 @@ namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl { return true; } + + Bool ValidateReadFramebufferIsSingleView(const MG_State::GLState::FramebufferObject* framebufferObject, + const char* caller) { + // GL_OVR_multiview 9.3 / 18.2 / 18.3: reading, copying or blitting out of a read + // framebuffer with more than one view is INVALID_FRAMEBUFFER_OPERATION. + if (!framebufferObject || framebufferObject->GetViewCount() <= 1) return true; + MG_State::pGLContext->RecordError( + ErrorCode::InvalidFramebufferOperation, + MakeUnique("MG_Impl/GLImpl/FramebufferImpl", caller, + "The read framebuffer has more than one view (GL_OVR_multiview).")); + return false; + } + + Bool ValidateBoundReadFramebufferIsSingleView(const char* caller) { + const auto& framebufferObject = + MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).GetBoundObject(); + return ValidateReadFramebufferIsSingleView(framebufferObject.get(), caller); + } + + // GL 4.6 core 9.2.8 conditions that depend only on the framebuffer and the attachment + // point. Shared, because glFramebufferTexture / 1D / 2D / 3D / TextureLayer are aliases of + // one another in that section and a CTS case that walks the family must not get five + // different answers - which is exactly what happened when these lived in one helper that + // only two of the five went through. + Bool ValidateFramebufferTextureAttachmentPoint( + const char* functionName, const SharedPtr& framebufferObject, + FramebufferAttachmentType attachmentType) { + // "An INVALID_OPERATION error is generated if COLOR_ATTACHMENTm is used with m greater + // than or equal to MAX_COLOR_ATTACHMENTS." + if (!FramebufferImpl::ValidateColorAttachmentInRange(attachmentType, functionName)) return false; + // "An INVALID_OPERATION error is generated if zero is bound to target." MobileGL keeps + // a real FramebufferObject for framebuffer 0, so a null test can never see this - the + // object is always there, and framebuffer 0 has to be recognized by identity instead, + // the same comparison DrawBuffers_State makes. Without this an attach onto the default + // framebuffer silently REPLACED its color attachment, permanently desynchronizing it + // from what the swapchain keeps publishing. + const auto& defaultFramebufferInfo = FramebufferImpl::pDefaultFramebufferInfo; + if (!framebufferObject || (defaultFramebufferInfo && framebufferObject == defaultFramebufferInfo->defaultFBO)) { + MG_State::pGLContext->RecordError( + ErrorCode::InvalidOperation, + MakeUnique( + "MG_Impl/GLImpl", functionName, + "No framebuffer object is bound to the target; the default framebuffer's attachments " + "cannot be named.")); + return false; + } + return true; + } + + // The other half of 9.2.8: "level must be greater than or equal to zero", and for a + // texture with immutable storage it "must be smaller than the number of levels the texture + // has". Split from the attachment-point half because the caller only has a texture object + // once the detach (texture == 0) case is behind it. + Bool ValidateFramebufferTextureLevel(const char* functionName, + const SharedPtr& textureObject, + GLint level) { + if (level < 0) { + MG_State::pGLContext->RecordError( + ErrorCode::InvalidValue, + MakeUnique("MG_Impl/GLImpl", functionName, "Texture level must be non-negative.")); + return false; + } + if (!textureObject || !textureObject->IsImmutable()) { + // A mutable texture has no level bound here: a level it has not specified yet is + // not an error, it just leaves the framebuffer incomplete. + return true; + } + // GetAddressableLevelCount(), NOT GetImmutableLevels(): for a VIEW the latter is + // deliberately the ORIGINAL texture's count (GL 4.6 core 8.18 defines + // TEXTURE_IMMUTABLE_LEVELS on a view that way), which is far too large a bound - a + // two-level view onto a ten-level texture would accept level 5 and attach an image + // nothing can draw into. + const Uint levelBound = textureObject->GetAddressableLevelCount(); + if (static_cast(level) >= levelBound) { + MG_State::pGLContext->RecordError( + ErrorCode::InvalidValue, + MakeUnique( + "MG_Impl/GLImpl", functionName, + std::format("Texture level {} is beyond the {} level(s) this texture has.", level, levelBound))); + return false; + } + return true; + } } // namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl diff --git a/MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.h b/MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.h index d3e6fa06..04f98ff2 100644 --- a/MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.h +++ b/MobileGL/MG_Impl/GLImpl/Framebuffer/Validators.h @@ -30,4 +30,24 @@ namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl { // DEFAULT framebuffer does not answer INVALID_OPERATION. Testing the framebuffer kind first // would turn GL_FRAMEBUFFER_DEFAULT_WIDTH on framebuffer zero into the wrong error. Bool ValidateFramebufferParameterPname(GLenum pname, Bool isDefaultFramebuffer, Bool forSetter, const char* caller); + // GL 4.6 core 9.2.8 conditions on the framebuffer and the attachment point that every + // texture-attaching entry point shares: a color attachment beyond GL_MAX_COLOR_ATTACHMENTS, or + // the default framebuffer bound to the target, is INVALID_OPERATION. + Bool ValidateFramebufferTextureAttachmentPoint( + const char* functionName, const SharedPtr& framebufferObject, + FramebufferAttachmentType attachmentType); + // The level half of 9.2.8: negative, or past an immutable texture's levels, is INVALID_VALUE. + Bool ValidateFramebufferTextureLevel(const char* functionName, + const SharedPtr& textureObject, + GLint level); + // GL_OVR_multiview: a read framebuffer with more than one view cannot be read, copied or blitted + // from (INVALID_FRAMEBUFFER_OPERATION). A null framebuffer passes; its caller reports that. + Bool ValidateReadFramebufferIsSingleView(const MG_State::GLState::FramebufferObject* framebufferObject, + const char* caller); + Bool ValidateBoundReadFramebufferIsSingleView(const char* caller); + // GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR / _BASE_VIEW_INDEX_OVR. False when pname is + // neither or GL_OVR_multiview is not supported, so the caller's INVALID_ENUM stands; true when + // the query was answered or refused here. Defined in GL_FramebufferMultiview.cpp. + Bool TryAnswerMultiviewAttachmentQuery(const MG_State::GLState::FramebufferAttachmentObject* attachmentObject, + GLenum pname, GLint* params, const char* caller); } // namespace MobileGL::MG_Impl::GLImpl::FramebufferImpl diff --git a/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp b/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp index 473fe5e3..d0fbdb60 100644 --- a/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp +++ b/MobileGL/MG_Impl/GLImpl/Getter/GL_Getter.cpp @@ -50,6 +50,9 @@ namespace MobileGL::MG_Impl::GLImpl { // a free function named BlendEquation, which would hide the ::MobileGL::BlendEquation enum // this file's blend-state queries name unqualified. GLboolean IsEnabledi(GLenum target, GLuint index); + // GL_Framebuffer.h, declared here for the same reason. + Int GetMaxViews_State(); + Bool IsMultiviewSupported_State(); namespace { enum class IndexedBufferQueryKind { @@ -1631,6 +1634,14 @@ namespace MobileGL::MG_Impl::GLImpl { } } + // GL_MAX_VIEWS_OVR, answered only where GL_OVR_multiview is advertised; anywhere else it is an + // unknown pname like any other extension's. + static Bool TryGetMultiviewInteger(GLenum pname, GLint* params) { + if (pname != GL_MAX_VIEWS_OVR || !IsMultiviewSupported_State()) return false; + *params = GetMaxViews_State(); + return true; + } + // GL_EXT_fragment_shading_rate's state and limits (tables 23.9 / 23.53 of the extension). // Returns false for any other pname. The tokens belong to the extension, so a context whose // backend cannot back it answers them like any unknown pname, and the attachment limits the @@ -1762,7 +1773,7 @@ namespace MobileGL::MG_Impl::GLImpl { return; } - if (TryGetFragmentShadingRateInteger(pname, params)) return; + if (TryGetFragmentShadingRateInteger(pname, params) || TryGetMultiviewInteger(pname, params)) return; switch (pname) { case GL_ACTIVE_TEXTURE: diff --git a/MobileGL/MG_Impl/GetProcAddress.cpp b/MobileGL/MG_Impl/GetProcAddress.cpp index 97a95af8..a001abd2 100644 --- a/MobileGL/MG_Impl/GetProcAddress.cpp +++ b/MobileGL/MG_Impl/GetProcAddress.cpp @@ -1547,7 +1547,7 @@ namespace MobileGL::MG_Impl { GETPROC(glGetIntegerui64i_vNV, name); GETPROC(glViewportSwizzleNV, name); GETPROC(glFramebufferTextureMultiviewOVR, name); - // GETPROC(glNamedFramebufferTextureMultiviewOVR, name); + GETPROC(glNamedFramebufferTextureMultiviewOVR, name); MGLOG_D("GetProcAddress(%s) = nullptr!", name); return nullptr; diff --git a/MobileGL/MG_Impl/Pipe/FramebufferEmit.h b/MobileGL/MG_Impl/Pipe/FramebufferEmit.h index 9f5edc95..240f63fd 100644 --- a/MobileGL/MG_Impl/Pipe/FramebufferEmit.h +++ b/MobileGL/MG_Impl/Pipe/FramebufferEmit.h @@ -109,7 +109,8 @@ namespace MobileGL::MG_Pipe { surface.Kind = kMGPipeSurfaceKindTexture; surface.InternalFormat = static_cast(texture->GetFormat()); surface.Layered = attachment.IsLayered() ? 1 : 0; - surface.Level = static_cast(std::max(attachment.GetTextureLevel(), 0)); + surface.Level = static_cast(std::clamp(attachment.GetTextureLevel(), 0, 0xFF)); + surface.NumViews = static_cast(std::clamp(attachment.GetNumViews(), 0, 0xFF)); surface.Layer = static_cast(std::max(attachment.GetTextureLayer(), 0)); surface.UploadTarget = static_cast(MGPipeResolveAttachmentUploadTarget(attachment)); // ID-12 DV-5: the field that WAS Pad0, and the size did not move. The four @@ -126,6 +127,7 @@ namespace MobileGL::MG_Pipe { surface.InternalFormat = static_cast(renderbuffer->GetInternalFormat()); surface.Layered = 0; surface.Level = 0; + surface.NumViews = 0; surface.Layer = 0; return surface; } @@ -179,6 +181,7 @@ namespace MobileGL::MG_Pipe { dst.Kind = src.Kind; dst.Layered = src.Layered; dst.Level = src.Level; + dst.NumViews = src.NumViews; dst.Layer = src.Layer; dst.UploadTarget = src.UploadTarget; // MANDATORY, not optional: TextureTarget is a PipeFields.def row now, so a diff --git a/MobileGL/MG_Pipe/MGPipeTypes.h b/MobileGL/MG_Pipe/MGPipeTypes.h index bdf93da7..704b59a2 100644 --- a/MobileGL/MG_Pipe/MGPipeTypes.h +++ b/MobileGL/MG_Pipe/MGPipeTypes.h @@ -677,7 +677,11 @@ namespace MobileGL::MG_Pipe { Uint32 InternalFormat; Uint8 Kind; // kMGPipeSurfaceKind{None,Texture,Renderbuffer}, above Uint8 Layered; - Uint16 Level; + // A mip level fits a byte: GL_MAX_TEXTURE_SIZE would have to pass 2^255 for it not to. + Uint8 Level; + // GL_OVR_multiview: non-zero on a multiview attachment, which renders views + // [Layer, Layer + NumViews) of a 2D array texture. Layered is then 0. + Uint8 NumViews; Uint32 Layer; Uint16 UploadTarget; // static_cast(MobileGL::TextureUploadTarget) // static_cast(MobileGL::TextureTarget), or kMGPipeSurfaceNoTextureTarget on a diff --git a/MobileGL/MG_Pipe/PipeFields.def b/MobileGL/MG_Pipe/PipeFields.def index 1d84211b..83b2ea6e 100644 --- a/MobileGL/MG_Pipe/PipeFields.def +++ b/MobileGL/MG_Pipe/PipeFields.def @@ -100,7 +100,7 @@ // Pad, so the rename without this row is a pipe-gates failure, and the row without the // rename is one too. A meaning-carrying byte cannot enter this record silently. #define MGP_FIELDS_MGPSurface(F) \ - F(Res) F(InternalFormat) F(Kind) F(Layered) F(Level) F(Layer) F(UploadTarget) F(TextureTarget) + F(Res) F(InternalFormat) F(Kind) F(Layered) F(Level) F(NumViews) F(Layer) F(UploadTarget) F(TextureTarget) // P4a, D-C2: Pad0 became Uint8 Target, and gen_pipe.py's PADDING_MEMBER_RE only excludes a // member still NAMED Pad - so the rename without this row is a pipe-gates failure, which @@ -399,7 +399,7 @@ F(FragmentShadingRateAttachmentWithDefaultFramebuffer) F(FragmentShadingRateMasks) \ F(MinFragmentShadingRateAttachmentTexelWidth) F(MinFragmentShadingRateAttachmentTexelHeight) \ F(MaxFragmentShadingRateAttachmentTexelWidth) F(MaxFragmentShadingRateAttachmentTexelHeight) \ - F(MaxFragmentShadingRateAttachmentTexelAspectRatio) F(MaxFragmentShadingRateAttachmentLayers) + F(MaxFragmentShadingRateAttachmentTexelAspectRatio) F(MaxFragmentShadingRateAttachmentLayers) F(MaxViews) #define MGP_FIELDS_MGHostSpan(F) \ F(Ptr) F(Seg) F(Size) F(Offset) diff --git a/MobileGL/MG_Pipe/generated/PipeWireLayout.inc b/MobileGL/MG_Pipe/generated/PipeWireLayout.inc index ed45c24c..1f2912bb 100644 --- a/MobileGL/MG_Pipe/generated/PipeWireLayout.inc +++ b/MobileGL/MG_Pipe/generated/PipeWireLayout.inc @@ -142,6 +142,7 @@ inline constexpr WireLayoutMember kMGPipeWireLayoutMembers[] = { {"MGPSurface.Kind", offsetof(MGPSurface, Kind), sizeof(((MGPSurface*)nullptr)->Kind)}, {"MGPSurface.Layered", offsetof(MGPSurface, Layered), sizeof(((MGPSurface*)nullptr)->Layered)}, {"MGPSurface.Level", offsetof(MGPSurface, Level), sizeof(((MGPSurface*)nullptr)->Level)}, + {"MGPSurface.NumViews", offsetof(MGPSurface, NumViews), sizeof(((MGPSurface*)nullptr)->NumViews)}, {"MGPSurface.Layer", offsetof(MGPSurface, Layer), sizeof(((MGPSurface*)nullptr)->Layer)}, {"MGPSurface.UploadTarget", offsetof(MGPSurface, UploadTarget), sizeof(((MGPSurface*)nullptr)->UploadTarget)}, {"MGPSurface.TextureTarget", offsetof(MGPSurface, TextureTarget), sizeof(((MGPSurface*)nullptr)->TextureTarget)}, @@ -685,6 +686,7 @@ inline constexpr WireLayoutMember kMGPipeWireLayoutMembers[] = { {"DynamicBackendParameters.MaxFragmentShadingRateAttachmentTexelHeight", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentTexelHeight), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentTexelHeight)}, {"DynamicBackendParameters.MaxFragmentShadingRateAttachmentTexelAspectRatio", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentTexelAspectRatio), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentTexelAspectRatio)}, {"DynamicBackendParameters.MaxFragmentShadingRateAttachmentLayers", offsetof(DynamicBackendParameters, MaxFragmentShadingRateAttachmentLayers), sizeof(((DynamicBackendParameters*)nullptr)->MaxFragmentShadingRateAttachmentLayers)}, + {"DynamicBackendParameters.MaxViews", offsetof(DynamicBackendParameters, MaxViews), sizeof(((DynamicBackendParameters*)nullptr)->MaxViews)}, {"MGHostSpan", 0, sizeof(MGHostSpan)}, {"MGHostSpan.Ptr", offsetof(MGHostSpan, Ptr), sizeof(((MGHostSpan*)nullptr)->Ptr)}, {"MGHostSpan.Seg", offsetof(MGHostSpan, Seg), sizeof(((MGHostSpan*)nullptr)->Seg)}, diff --git a/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.cpp b/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.cpp index 9fec8201..c6b33cda 100644 --- a/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.cpp +++ b/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.cpp @@ -45,9 +45,9 @@ namespace MobileGL::MG_State::GLState { // FramebufferAttachmentObject FramebufferAttachmentObject::FramebufferAttachmentObject( const SharedPtr& texture, TextureUploadTarget textureUploadTarget, Int level, - Int layer, Bool layered) + Int layer, Bool layered, Int numViews) : m_texture(texture), m_textureUploadTarget(textureUploadTarget), m_textureLevel(level), m_textureLayer(layer), - m_layered(layered) {} + m_layered(layered), m_numViews(numViews) {} FramebufferAttachmentObject::FramebufferAttachmentObject(const SharedPtr& renderbuffer) : m_renderbuffer(renderbuffer) {} FramebufferAttachmentObject::FramebufferAttachmentObject(Bool IsValid) @@ -87,6 +87,10 @@ namespace MobileGL::MG_State::GLState { return m_layered; } + Int FramebufferAttachmentObject::GetNumViews() const { + return m_numViews; + } + TextureUploadTarget FramebufferAttachmentObject::GetTextureUploadTarget() const { return m_textureUploadTarget; } @@ -115,7 +119,9 @@ namespace MobileGL::MG_State::GLState { default: break; } - if (layerCount >= 0 && m_textureLayer >= layerCount) return false; + // GL_OVR_multiview 9.4.1: every view's layer, not only the base one. + const Int lastLayer = m_textureLayer + std::max(m_numViews, 1) - 1; + if (layerCount >= 0 && lastLayer >= layerCount) return false; } return true; } else if (IsRenderbuffer()) { @@ -163,9 +169,10 @@ namespace MobileGL::MG_State::GLState { } void FramebufferObject::AttachTexture(FramebufferAttachmentType type, const SharedPtr& texture, - TextureUploadTarget textureUploadTarget, int level, int layer, Bool layered) { + TextureUploadTarget textureUploadTarget, int level, int layer, Bool layered, + int numViews) { m_attachmentObjects[static_cast(type)] = - FramebufferAttachmentObject(texture, textureUploadTarget, level, layer, layered); + FramebufferAttachmentObject(texture, textureUploadTarget, level, layer, layered, numViews); BumpAttachmentVersion(type); } @@ -217,7 +224,39 @@ namespace MobileGL::MG_State::GLState { } if (validAttachmentCount == 0) return false; - return !HasLayerTargetMismatch(); + return !HasLayerTargetMismatch() && !HasViewTargetMismatch(); + } + + Bool FramebufferObject::HasViewTargetMismatch() const { + Bool seen = false; + Int numViews = 0; + for (const auto& attachment : m_attachmentObjects) { + if (!attachment.IsValid() || attachment.IsEmpty()) continue; + const Int views = attachment.IsTexture() ? attachment.GetNumViews() : 0; + if (seen && views != numViews) return true; + seen = true; + numViews = views; + } + return false; + } + + Bool FramebufferObject::IsMultiview() const { + for (const auto& attachment : m_attachmentObjects) { + if (attachment.IsValid() && attachment.IsTexture() && attachment.IsMultiview()) return true; + } + return false; + } + + Int FramebufferObject::GetViewCount() const { + Int numViews = 0; + for (const auto& attachment : m_attachmentObjects) { + if (!attachment.IsValid() || attachment.IsEmpty()) continue; + const Int views = attachment.IsTexture() ? attachment.GetNumViews() : 0; + if (views == 0) return 1; + if (numViews != 0 && views != numViews) return 1; + numViews = views; + } + return std::max(numViews, 1); } Bool FramebufferObject::HasLayerTargetMismatch() const { diff --git a/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.h b/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.h index 19e75155..5f81fad2 100644 --- a/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.h +++ b/MobileGL/MG_State/GLState/FramebufferState/FramebufferObject.h @@ -75,7 +75,7 @@ namespace MobileGL { public: explicit FramebufferAttachmentObject(const SharedPtr& texture, TextureUploadTarget textureUploadTarget, Int level = 0, Int layer = 0, - Bool layered = false); + Bool layered = false, Int numViews = 0); explicit FramebufferAttachmentObject(const SharedPtr& renderbuffer); explicit FramebufferAttachmentObject(Bool IsValid = true); @@ -87,6 +87,10 @@ namespace MobileGL { Int GetTextureLevel() const; Int GetTextureLayer() const; Bool IsLayered() const; + // GL_OVR_multiview: the attachment renders views [layer, layer + numViews) of a 2D + // array texture, one per view. Zero for every attachment that is not multiview. + Int GetNumViews() const; + Bool IsMultiview() const { return m_numViews > 0; } TextureUploadTarget GetTextureUploadTarget() const; Bool IsComplete() const; IntVec3 GetSize() const; @@ -99,6 +103,7 @@ namespace MobileGL { Int m_textureLevel = 0; Int m_textureLayer = 0; Bool m_layered = false; + Int m_numViews = 0; Bool m_isValid = true; }; @@ -122,7 +127,7 @@ namespace MobileGL { void AttachTexture(FramebufferAttachmentType type, const SharedPtr& texture, TextureUploadTarget textureUploadTarget = TextureUploadTarget::Unknown, int level = 0, - int layer = 0, Bool layered = false); + int layer = 0, Bool layered = false, int numViews = 0); void AttachRenderbuffer(FramebufferAttachmentType type, const SharedPtr& renderbuffer); void Detach(FramebufferAttachmentType type); const FramebufferAttachmentObject& GetAttachment(FramebufferAttachmentType type) const; @@ -132,6 +137,17 @@ namespace MobileGL { // layered while another is not, or the layered color attachments come from textures of // different targets. CheckCompleteness() includes it; this tells the status apart. Bool HasLayerTargetMismatch() const; + // GL_OVR_multiview's FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR: the populated attachments + // do not all have the same number of views. An attachment that is not multiview does + // not match a multiview one, whatever its view count. CheckCompleteness() includes it. + Bool HasViewTargetMismatch() const; + // The number of views a draw into this framebuffer renders: the multiview attachments' + // common count, or 1 when no attachment is multiview (or the counts disagree, which + // leaves the framebuffer incomplete anyway). + Int GetViewCount() const; + // Whether any populated attachment is a multiview one. A multiview framebuffer with a + // single view still takes the multiview draw rules. + Bool IsMultiview() const; // aka. `buffer` as in glDrawBuffers/glReadBuffers void SetDrawBuffer(Uint index, FramebufferAttachmentType buffer); const FramebufferAttachmentArray& GetDrawBuffers() const; diff --git a/MobileGL/MG_State/GLState/ProgramState/ProgramArtifacts.h b/MobileGL/MG_State/GLState/ProgramState/ProgramArtifacts.h index 398faabc..af3702e2 100644 --- a/MobileGL/MG_State/GLState/ProgramState/ProgramArtifacts.h +++ b/MobileGL/MG_State/GLState/ProgramState/ProgramArtifacts.h @@ -383,6 +383,9 @@ namespace MobileGL::MG_State::GLState { GLenum gsOutputPrimitive = GL_NONE; Int gsMaxVertices = 0; Int gsInvocations = 0; + // GL_OVR_multiview: the vertex stage's layout(num_views = N) in;, or 0 without one. The + // backend that emits GLSL needs it back, because SPIR-V cannot say it. + Int vsNumViews = 0; // The tessellation evaluation stage's layout: GL_QUADS / GL_TRIANGLES / GL_ISOLINES, // GL_EQUAL / GL_FRACTIONAL_EVEN / GL_FRACTIONAL_ODD, GL_CW / GL_CCW, and point mode. GLenum tessGenMode = GL_NONE; @@ -610,6 +613,7 @@ namespace MobileGL::MG_State::GLState { v("gsOutputPrimitive", a.gsOutputPrimitive); v("gsMaxVertices", a.gsMaxVertices); v("gsInvocations", a.gsInvocations); + v("vsNumViews", a.vsNumViews); v("tessGenMode", a.tessGenMode); v("tessGenSpacing", a.tessGenSpacing); v("tessGenVertexOrder", a.tessGenVertexOrder); @@ -618,7 +622,7 @@ namespace MobileGL::MG_State::GLState { v("xfbVaryingNameMaxLength", a.xfbVaryingNameMaxLength); v("xfbNeedsScatteredCapture", a.xfbNeedsScatteredCapture); v("xfbPackedStride", a.xfbPackedStride); - } // 57 fields (58 members minus `program`) + } // 58 fields (59 members minus `program`) template requires std::same_as, SpirvArtifacts> @@ -650,7 +654,7 @@ namespace MobileGL::MG_State::GLState { #define MGL_XFBVARYING_SIZE 128 // P7 OQ-8 added storageBlocks, one more Vector, in the disaggregated build ONLY. The pull // number below is the one G1 measures and it has not moved. -#define MGL_LINKARTIFACTS_SIZE 1080 +#define MGL_LINKARTIFACTS_SIZE 1088 #define MGL_SPIRVARTIFACTS_SIZE 96 #elif defined(_LIBCPP_VERSION) && (SIZE_MAX == UINT64_MAX) && defined(MGL_ARTIFACT_SIZES_LIBCXX_PINNED) // The integrator pins these from the NDK build (brief C.4); until then this branch is inert. diff --git a/MobileGL/MG_State/GLState/ProgramState/ProgramArtifactsCodec.h b/MobileGL/MG_State/GLState/ProgramState/ProgramArtifactsCodec.h index 66c6699f..e6190c85 100644 --- a/MobileGL/MG_State/GLState/ProgramState/ProgramArtifactsCodec.h +++ b/MobileGL/MG_State/GLState/ProgramState/ProgramArtifactsCodec.h @@ -67,7 +67,8 @@ namespace MobileGL::MG_State::GLState { // reader checks FIRST and what the refusal names, and CONTRACT-P7 §5.3 asks for the bump // explicitly. `wireFingerprint` moves with both, which is expected and is what makes a // mixed-version pair refuse at the handshake instead of at the first program. - inline constexpr Uint32 kProgramArtifactsCodecVersion = 3; + // 4: LinkArtifacts gained `vsNumViews` (GL_OVR_multiview), for the same reason. + inline constexpr Uint32 kProgramArtifactsCodecVersion = 4; // Derived from the actual VisitFields order/names, container element schemas and scalar // representations. No native container size/offset is included. Also checked in Hello. Uint64 ProgramArtifactsSchemaFingerprint(); diff --git a/MobileGL/MG_State/GLState/ProgramState/ProgramLinkTask.cpp b/MobileGL/MG_State/GLState/ProgramState/ProgramLinkTask.cpp index d88d3ec3..acf68597 100644 --- a/MobileGL/MG_State/GLState/ProgramState/ProgramLinkTask.cpp +++ b/MobileGL/MG_State/GLState/ProgramState/ProgramLinkTask.cpp @@ -193,6 +193,25 @@ namespace { // The offsets themselves survive that lowering (reflection and the SPIR-V generator both // honor layoutOffset), so the check belongs here, over the same model the GL queries answer // from. Returns the info-log line for an illegal layout, empty for a legal one. + // GL_OVR_multiview's layout(num_views = N) in; of the linked vertex stage into + // artifacts.vsNumViews, 0 without one. glslang already refused a non-positive count and two + // units that disagree; the upper bound is GL_MAX_VIEWS_OVR, which glslang does not know, so it + // is held here. False, with the link failed and the TProgram dropped, when the count is over it. + static MobileGL::Bool ResolveVertexNumViews(MobileGL::MG_State::GLState::ProgramObject::LinkArtifacts& artifacts, + const MobileGL::MG_Util::ShaderTranspiler::CompileEnv& env) { + artifacts.vsNumViews = 0; + const glslang::TIntermediate* vs = artifacts.program->getIntermediate(EShLangVertex); + if (vs == nullptr) return true; + artifacts.vsNumViews = std::max(vs->getNumViews(), 0); + if (!env.HasBackend() || artifacts.vsNumViews <= env.params.MaxViews) return true; + artifacts.linkStatus = false; + artifacts.program.reset(); + artifacts.infoLog = + std::format("Vertex shader declares num_views = {}, more than the {} GL_MAX_VIEWS_OVR allows.", + artifacts.vsNumViews, env.params.MaxViews); + return false; + } + static MobileGL::String ValidateAtomicCounterLayout(glslang::TProgram& reflection) { using MobileGL::Bool; using MobileGL::Int; @@ -1040,6 +1059,11 @@ namespace MobileGL::MG_State::GLState { } } + if (!ResolveVertexNumViews(artifacts, env)) { + DeferLog(std::format("ProgramObject {}: Link failed - {}", in.externalIndex, artifacts.infoLog)); + return; + } + // ---- everything below this line up to GenerateSpirv() is the GL query surface ---- // // ORDERING NOTE (rewritten 2026-08-10; the constraint it records was RETESTED, not diff --git a/MobileGL/MG_State/GLState/ProgramState/ProgramObject.h b/MobileGL/MG_State/GLState/ProgramState/ProgramObject.h index edf53899..c4de12e7 100644 --- a/MobileGL/MG_State/GLState/ProgramState/ProgramObject.h +++ b/MobileGL/MG_State/GLState/ProgramState/ProgramObject.h @@ -1320,6 +1320,9 @@ namespace MobileGL::MG_State::GLState { GLenum GetGeometryOutputType() const { return Artifacts().gsOutputPrimitive; } Int GetGeometryVerticesOut() const { return Artifacts().gsMaxVertices; } Int GetGeometryShaderInvocations() const { return Artifacts().gsInvocations; } + // GL_OVR_multiview: how many views a draw with this program renders - its vertex stage's + // num_views, or 1 without the qualifier. + Int GetMultiviewViewCount() const { return std::max(Artifacts().vsNumViews, 1); } // GL_TESS_CONTROL_OUTPUT_VERTICES of the linked tessellation control stage, or 0 when // the program has no such stage. Never greater than GL_MAX_PATCH_VERTICES: a program // that declared more does not link at all (GL 4.6 core 11.2.1.1). diff --git a/MobileGL/MG_Test/Backend/DirectGLES/CMakeLists.txt b/MobileGL/MG_Test/Backend/DirectGLES/CMakeLists.txt index 1990d78e..2435aa94 100644 --- a/MobileGL/MG_Test/Backend/DirectGLES/CMakeLists.txt +++ b/MobileGL/MG_Test/Backend/DirectGLES/CMakeLists.txt @@ -88,3 +88,9 @@ gtest_discover_tests(NarrowIntegerEsslTest DISCOVERY_TIMEOUT 30 PROPERTIES LABEL gtest_discover_tests(EsslShaderPassTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) gtest_discover_tests(BaseInstanceInjectionTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) gtest_discover_tests(ViewportIndexRoutingTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) + +# GL_OVR_multiview's ESSL: num_views through glslang, the capability strip and the text pass. +add_executable(MultiviewEsslTest MultiviewEsslTest.cpp) +target_include_directories(MultiviewEsslTest PRIVATE ${MGL_ROOT}/include ${MGL_ROOT}/MobileGL) +target_link_libraries(MultiviewEsslTest PRIVATE MobileGLTestMain glslang-default-resource-limits ${LINK_LIBRARIES}) +gtest_discover_tests(MultiviewEsslTest DISCOVERY_TIMEOUT 30 PROPERTIES LABELS unit) diff --git a/MobileGL/MG_Test/Backend/DirectGLES/MultiviewEsslTest.cpp b/MobileGL/MG_Test/Backend/DirectGLES/MultiviewEsslTest.cpp new file mode 100644 index 00000000..02359635 --- /dev/null +++ b/MobileGL/MG_Test/Backend/DirectGLES/MultiviewEsslTest.cpp @@ -0,0 +1,197 @@ +// MobileGL - MobileGL/MG_Test/Backend/DirectGLES/MultiviewEsslTest.cpp +// Copyright (c) 2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header +// +// GL_OVR_multiview through the steps DirectGLES takes: glslang keeps the vertex stage's num_views, +// the SPIR-V loses its MultiView capability so SPIRV-Cross accepts both stages without a view +// count, and the text pass puts the directive and num_views back. The result has to be ESSL 3.20 +// that a compiler accepts, in both stages. + +#include + +#include +#include +#include +#include +#include + +#include "Init.h" + +#include +#include +#include + +using namespace MobileGL; +using MobileGL::MG_Backend::DirectGLES::PrgramImpl::RequestMultiviewExtension; +using MobileGL::MG_Util::ShaderTranspiler::SessionUsageBit; +using MobileGL::MG_Util::ShaderTranspiler::ShaderCompiler; +using MobileGL::MG_Util::ShaderTranspiler::SpvcSession; + +namespace { + constexpr const char* kVertex = R"(#version 330 core +#extension GL_OVR_multiview2 : require +layout(num_views = 2) in; +layout(location = 0) in vec2 pos; +out float tint; +void main() { + tint = float(gl_ViewID_OVR); + gl_Position = vec4(pos.x + float(gl_ViewID_OVR), pos.y, 0.0, 1.0); +} +)"; + constexpr const char* kFragment = R"(#version 330 core +#extension GL_OVR_multiview2 : require +in float tint; +out vec4 color; +void main() { color = vec4(tint, float(gl_ViewID_OVR), 0.0, 1.0); } +)"; + + struct LinkedModules { + Int numViews = -1; + Vector> modules; + }; + + LinkedModules CompileAndLink(const char* vertex, const char* fragment) { + using namespace MG_Util::ShaderTranspiler; + LinkedModules out; + Vector> shaders; + for (const auto& [stage, source] : + Vector>{{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); + if (!shader) return out; + shaders.push_back(shader.value()); + } + ProgramAttrib programAttrib{.shaders = shaders}; + auto program = ShaderCompiler::LinkProgram(programAttrib); + EXPECT_TRUE(program) << (program ? String{} : program.error().log); + if (!program) return out; + out.numViews = program.value()->getIntermediate(EShLangVertex)->getNumViews(); + ProgramBinaryAttrib binaryAttrib{.shaderTypes = {GL_VERTEX_SHADER, GL_FRAGMENT_SHADER}, + .program = *program.value()}; + auto binary = ShaderCompiler::GetSpirvBinaryFromProgram(binaryAttrib); + EXPECT_TRUE(binary) << (binary ? String{} : binary.error().log); + if (!binary || binary->size() != 2) return out; + for (auto module : binary.value()) { + EXPECT_TRUE(ShaderCompiler::SanitizeAndOptimizeBinary(module, module, true, true)); + out.modules.push_back(Move(module)); + } + return out; + } + + String EmitEssl320(const Vector& spirv) { + SpvcSession session(spirv, SessionUsageBit::Transpile); + spvc_compiler_options options; + session.CreateOptions(&options); + spvc_compiler_options_set_uint(options, SPVC_COMPILER_OPTION_GLSL_VERSION, 320); + spvc_compiler_options_set_bool(options, SPVC_COMPILER_OPTION_GLSL_ES, SPVC_TRUE); + spvc_compiler_options_set_bool(options, SPVC_COMPILER_OPTION_GLSL_VULKAN_SEMANTICS, SPVC_FALSE); + session.SetOptions(options); + const char* result = nullptr; + session.Compile(&result); + EXPECT_NE(result, nullptr) << (session.GetLastErrorString() ? session.GetLastErrorString() : ""); + return result != nullptr ? String(result) : String{}; + } + + String CompileErrorAsEssl320(const String& source, EShLanguage stage) { + glslang::TShader shader(stage); + const char* strings[] = {source.c_str()}; + shader.setStrings(strings, 1); + if (shader.parse(GetDefaultResources(), 320, EEsProfile, false, false, EShMsgDefault)) return {}; + return shader.getInfoLog(); + } + + Bool DeclaresMultiviewCapability(const Vector& module) { + constexpr Uint32 kOpCapability = 17; + constexpr Uint32 kCapabilityMultiView = 4439; + for (SizeT at = 5; at < module.size();) { + const Uint32 wordCount = module[at] >> 16; + if (wordCount == 0) return false; + if ((module[at] & 0xFFFFu) == kOpCapability && module[at + 1] == kCapabilityMultiView) return true; + at += wordCount; + } + return false; + } +} // namespace + +TEST(MultiviewEssl, BothStagesComeOutAsMultiviewEsslACompilerAccepts) { + MobileGL::Initialize(); + const LinkedModules linked = CompileAndLink(kVertex, kFragment); + ASSERT_EQ(linked.modules.size(), 2u); + EXPECT_EQ(linked.numViews, 2) << "glslang dropped the vertex stage's num_views"; + + const struct { + GLenum glStage; + EShLanguage stage; + } stages[] = {{GL_VERTEX_SHADER, EShLangVertex}, {GL_FRAGMENT_SHADER, EShLangFragment}}; + for (SizeT i = 0; i < 2; ++i) { + ASSERT_TRUE(DeclaresMultiviewCapability(linked.modules[i])); + Vector stripped; + ASSERT_TRUE(ShaderCompiler::StripMultiviewCapabilityForEssl(linked.modules[i], stripped)); + EXPECT_FALSE(DeclaresMultiviewCapability(stripped)); + + const String emitted = EmitEssl320(stripped); + ASSERT_FALSE(emitted.empty()); + EXPECT_NE(emitted.find("gl_ViewID_OVR"), String::npos) << emitted; + EXPECT_EQ(emitted.find("GL_OVR_multiview"), String::npos) << "the emission must not depend on the view count"; + + const String essl = RequestMultiviewExtension(emitted, stages[i].glStage, linked.numViews, true); + EXPECT_NE(essl.find("#extension GL_OVR_multiview2 : require\n"), String::npos) << essl; + const Bool vertex = stages[i].glStage == GL_VERTEX_SHADER; + EXPECT_EQ(essl.find("layout(num_views = 2) in;") != String::npos, vertex) << essl; + EXPECT_EQ(CompileErrorAsEssl320(essl, stages[i].stage), String{}) << essl; + } +} + +TEST(MultiviewEssl, TheDirectiveFollowsTheDriversExtensionAndNumViewsFollowsTheDirectives) { + const String source = "#version 320 es\n" + "#extension GL_EXT_clip_cull_distance : require\n" + "\n" + "precision highp float;\n" + "void main() { gl_Position = vec4(float(gl_ViewID_OVR)); }\n"; + const String essl = RequestMultiviewExtension(source, GL_VERTEX_SHADER, 3, false); + EXPECT_EQ(essl, "#version 320 es\n" + "#extension GL_OVR_multiview : require\n" + "#extension GL_EXT_clip_cull_distance : require\n" + "layout(num_views = 3) in;\n" + "\n" + "precision highp float;\n" + "void main() { gl_Position = vec4(float(gl_ViewID_OVR)); }\n"); + + // Neither the built-in nor a view count: nothing to ask for. + const String plain = "#version 320 es\nvoid main() {}\n"; + EXPECT_EQ(RequestMultiviewExtension(plain, GL_VERTEX_SHADER, 0, true), plain); + EXPECT_EQ(RequestMultiviewExtension(plain, GL_FRAGMENT_SHADER, 2, true), plain); +} + +TEST(MultiviewEssl, AModuleWithoutMultiviewIsLeftAlone) { + MobileGL::Initialize(); + const LinkedModules linked = CompileAndLink("#version 330 core\nvoid main() { gl_Position = vec4(0.0); }\n", + "#version 330 core\nout vec4 c;\nvoid main() { c = vec4(1.0); }\n"); + ASSERT_EQ(linked.modules.size(), 2u); + EXPECT_LT(linked.numViews, 0) << "no num_views qualifier was declared"; + Vector stripped; + EXPECT_FALSE(ShaderCompiler::StripMultiviewCapabilityForEssl(linked.modules[0], stripped)); + EXPECT_TRUE(stripped.empty()); +} + +TEST(MultiviewEssl, NumViewsIsAVertexStageQualifierAboveZero) { + MobileGL::Initialize(); + using namespace MG_Util::ShaderTranspiler; + for (const auto& [stage, source] : Vector>{ + {GL_VERTEX_SHADER, "#version 330 core\n#extension GL_OVR_multiview : require\n" + "layout(num_views = 0) in;\nvoid main() { gl_Position = vec4(0.0); }\n"}, + {GL_FRAGMENT_SHADER, "#version 330 core\n#extension GL_OVR_multiview : require\n" + "layout(num_views = 2) in;\nout vec4 c;\nvoid main() { c = vec4(1.0); }\n"}, + {GL_VERTEX_SHADER, "#version 330 core\n#extension GL_OVR_multiview : require\n" + "layout(num_views = 2) in;\nlayout(num_views = 3) in;\n" + "void main() { gl_Position = vec4(0.0); }\n"}, + }) { + ShaderAttrib attrib{.shaderType = stage, .sourceStr = source}; + EXPECT_FALSE(ShaderCompiler::CompileShader(attrib)) << source; + } +} diff --git a/MobileGL/MG_Test/BackendLoader/BackendLoaderTest.cpp b/MobileGL/MG_Test/BackendLoader/BackendLoaderTest.cpp index e40413e3..433e9b24 100644 --- a/MobileGL/MG_Test/BackendLoader/BackendLoaderTest.cpp +++ b/MobileGL/MG_Test/BackendLoader/BackendLoaderTest.cpp @@ -96,6 +96,8 @@ namespace { // baseInstance word and exposes it through gl_InstanceID. bool drawLeaksBaseInstanceWord = false; GLenum errorRaisedByDraw = GL_NO_ERROR; + // GL_MAX_VIEWS_OVR, a GL_OVR_multiview pname. + GLint maxViews = 4; GLenum pendingError = GL_NO_ERROR; std::vector extensions; @@ -270,6 +272,9 @@ namespace { case GL_NUM_EXTENSIONS: *data = static_cast(g_fake.extensions.size()); break; + case GL_MAX_VIEWS_OVR: + *data = g_fake.maxViews; + break; default: // Leave the caller's defaults for every other capability query. break; @@ -1387,6 +1392,89 @@ TEST(CoreSurfaceAdvertisement, ClipControlFollowsTheBackendsRoute) { MobileGL::E_GL_ARB_clip_control)); } +// GL_OVR_multiview needs the driver's string and glFramebufferTextureMultiviewOVR, and a +// GL_MAX_VIEWS_OVR of at least the spec minimum; GL_OVR_multiview2 only counts on top of it. +TEST(MultiviewCapabilities, NeedTheExtensionTheEntryPointAndTwoViews) { + auto withEntryPoint = MakeFakeGLESFunctions(); + withEntryPoint.glFramebufferTextureMultiviewOVR = [](GLenum, GLenum, GLuint, GLint, GLint, GLsizei) {}; + + ResetFakeDriver(); + g_fake.maxVertexSsboBlocks = 0; + g_fake.extensions.emplace_back("GL_OVR_multiview2"); + MobileGL::MG_External::GLESCapabilities onlyTheSecond; + ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(onlyTheSecond, withEntryPoint)); + EXPECT_FALSE(onlyTheSecond.SupportsMultiview); + EXPECT_FALSE(onlyTheSecond.SupportsMultiview2); + EXPECT_EQ(onlyTheSecond.MaxViews, 0); + + ResetFakeDriver(); + g_fake.maxVertexSsboBlocks = 0; + g_fake.extensions = {"GL_OVR_multiview", "GL_OVR_multiview2"}; + MobileGL::MG_External::GLESCapabilities noEntryPoint; + ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(noEntryPoint, MakeFakeGLESFunctions())); + EXPECT_FALSE(noEntryPoint.SupportsMultiview); + EXPECT_FALSE(noEntryPoint.SupportsMultiview2); + + ResetFakeDriver(); + g_fake.maxVertexSsboBlocks = 0; + g_fake.extensions = {"GL_OVR_multiview"}; + g_fake.maxViews = 1; + MobileGL::MG_External::GLESCapabilities oneView; + ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(oneView, withEntryPoint)); + EXPECT_FALSE(oneView.SupportsMultiview); + EXPECT_EQ(oneView.MaxViews, 0); + + ResetFakeDriver(); + g_fake.maxVertexSsboBlocks = 0; + g_fake.extensions = {"GL_OVR_multiview"}; + MobileGL::MG_External::GLESCapabilities firstOnly; + ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(firstOnly, withEntryPoint)); + EXPECT_TRUE(firstOnly.SupportsMultiview); + EXPECT_FALSE(firstOnly.SupportsMultiview2); + EXPECT_EQ(firstOnly.MaxViews, 4); + + ResetFakeDriver(); + g_fake.maxVertexSsboBlocks = 0; + g_fake.extensions = {"GL_OVR_multiview", "GL_OVR_multiview2"}; + MobileGL::MG_External::GLESCapabilities both; + ASSERT_TRUE(MobileGL::MG_Util::BackendLoader::FillInGLESCapabilities(both, withEntryPoint)); + EXPECT_TRUE(both.SupportsMultiview); + EXPECT_TRUE(both.SupportsMultiview2); +} + +// Each multiview string follows the DirectGLES driver's own; DirectVulkan has no multiview route +// and never advertises either. +TEST(CoreSurfaceAdvertisement, MultiviewFollowsTheDriver) { + const auto contains = [](const MobileGL::Vector& extensions, MobileGL::GLExtension wanted) { + return std::find(extensions.begin(), extensions.end(), wanted) != extensions.end(); + }; + namespace DirectGLES = MobileGL::MG_Backend::DirectGLES; + namespace DirectVulkan = MobileGL::MG_Backend::DirectVulkan; + const auto none = DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false); + EXPECT_FALSE(contains(none, MobileGL::E_GL_OVR_multiview)); + EXPECT_FALSE(contains(none, MobileGL::E_GL_OVR_multiview2)); + + const auto first = + DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false, {.Multiview = true}); + EXPECT_TRUE(contains(first, MobileGL::E_GL_OVR_multiview)); + EXPECT_FALSE(contains(first, MobileGL::E_GL_OVR_multiview2)); + + const auto both = DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false, + {.Multiview = true, .Multiview2 = true}); + EXPECT_TRUE(contains(both, MobileGL::E_GL_OVR_multiview)); + EXPECT_TRUE(contains(both, MobileGL::E_GL_OVR_multiview2)); + + // The second string never stands without the first, whatever the flags say. + const auto secondOnly = + DirectGLES::BuildAdvertisedExtensions(false, false, false, false, false, false, {.Multiview2 = true}); + EXPECT_FALSE(contains(secondOnly, MobileGL::E_GL_OVR_multiview2)); + + const auto vulkan = DirectVulkan::BuildAdvertisedExtensions(false, false, false, false, false, + {.Multiview = true, .Multiview2 = true}); + EXPECT_FALSE(contains(vulkan, MobileGL::E_GL_OVR_multiview)); + EXPECT_FALSE(contains(vulkan, MobileGL::E_GL_OVR_multiview2)); +} + // 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. diff --git a/MobileGL/MG_Test/Framebuffer/CMakeLists.txt b/MobileGL/MG_Test/Framebuffer/CMakeLists.txt index 7d457bb0..20d2bf14 100644 --- a/MobileGL/MG_Test/Framebuffer/CMakeLists.txt +++ b/MobileGL/MG_Test/Framebuffer/CMakeLists.txt @@ -11,6 +11,7 @@ cmake_minimum_required(VERSION 3.14) add_executable( FramebufferTest FramebufferTest.cpp + FramebufferMultiviewTest.cpp ) target_include_directories(FramebufferTest PRIVATE diff --git a/MobileGL/MG_Test/Framebuffer/FramebufferMultiviewTest.cpp b/MobileGL/MG_Test/Framebuffer/FramebufferMultiviewTest.cpp new file mode 100644 index 00000000..50626e93 --- /dev/null +++ b/MobileGL/MG_Test/Framebuffer/FramebufferMultiviewTest.cpp @@ -0,0 +1,246 @@ +// MobileGL - MobileGL/MG_Test/Framebuffer/FramebufferMultiviewTest.cpp +// Copyright (c) 2025-2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +// GL_OVR_multiview on the frontend: the attach errors, both completeness rules, the attachment +// queries, GL_MAX_VIEWS_OVR and the read-side refusal, against a backend whose GL_MAX_VIEWS_OVR the +// test chooses. None of it reaches a driver. +#include + +#include "Includes.h" +#include "Init.h" +#include +#include +#include +#include +#include + +using namespace MobileGL; + +namespace { + class MultiviewLimitsBackend final : public MG_Backend::BackendObject { + public: + explicit MultiviewLimitsBackend(Int maxViews) { + m_params.MaxViews = maxViews; + m_params.MaxArrayTextureLayers = 8; + } + + void Initialize() override {} + Bool InitCapabilities() override { return true; } + Bool InitWindowSurface() override { return true; } + const RendererInfo& GetRendererInfo() const override { + static RendererInfo info = {}; + return info; + } + String GetBackendAPIVersionString() const override { return {}; } + const MG_Backend::GlobalBackendFunctionsTable& GetBackendFunctions() const override { + static MG_Backend::GlobalBackendFunctionsTable table = {}; + return table; + } + const MG_Backend::DynamicBackendParameters& GetDynamicParameters() const override { return m_params; } + BackendType GetBackendType() const override { return BackendType::Unknown; } + + private: + MG_Backend::DynamicBackendParameters m_params{}; + }; + + class ScopedMultiviewBackend { + public: + explicit ScopedMultiviewBackend(Int maxViews) : m_previous(Move(MG_Backend::pActiveBackendObject)) { + MG_Backend::pActiveBackendObject = MakeUnique(maxViews); + } + ~ScopedMultiviewBackend() { MG_Backend::pActiveBackendObject = Move(m_previous); } + + private: + UniquePtr m_previous; + }; + + GLuint MakeArrayTexture(GLsizei layers) { + GLuint texture = 0; + MG_Impl::GLImpl::CreateTextures(GL_TEXTURE_2D_ARRAY, 1, &texture); + MG_Impl::GLImpl::TextureStorage3D(texture, 1, GL_RGBA8, 4, 4, layers); + return texture; + } + + GLint AttachmentParameter(GLuint framebuffer, GLenum attachment, GLenum pname) { + GLint value = -1; + MG_Impl::GLImpl::GetNamedFramebufferAttachmentParameteriv(framebuffer, attachment, pname, &value); + return value; + } +} // namespace + +class FramebufferMultiviewTest : public ::testing::Test { +protected: + void SetUp() override { + MobileGL::Initialize(); + for (Int drained = 0; drained < 16 && MG_Impl::GLImpl::GetError() != GL_NO_ERROR; ++drained) {} + m_defaultFramebuffer = MG_State::pGLContext->GetFramebufferObject(0); + ASSERT_NE(m_defaultFramebuffer, nullptr); + } + + void TearDown() override { + MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read).Bind(m_defaultFramebuffer); + MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).Bind(m_defaultFramebuffer); + EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR) << "test left an unconsumed GL error behind"; + } + + static void ExpectSingleGlError(GLenum expected) { + EXPECT_EQ(MG_Impl::GLImpl::GetError(), expected); + EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR) << "the call recorded more than one error"; + } + + SharedPtr m_defaultFramebuffer; +}; + +TEST_F(FramebufferMultiviewTest, WithoutBackendMultiviewTheEntryPointsAndTokensAreRefused) { + ScopedMultiviewBackend backend(0); + GLuint framebuffer = 0; + MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer); + const GLuint texture = MakeArrayTexture(2); + + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, texture, 0, 0, 2); + ExpectSingleGlError(GL_INVALID_OPERATION); + EXPECT_FALSE(MG_State::pGLContext->GetFramebufferObject(framebuffer) + ->GetAttachment(FramebufferAttachmentType::Color0) + .IsTexture()); + + GLint maxViews = -1; + MG_Impl::GLImpl::GetIntegerv(GL_MAX_VIEWS_OVR, &maxViews); + ExpectSingleGlError(GL_INVALID_ENUM); + + MG_Impl::GLImpl::NamedFramebufferTextureLayer(framebuffer, GL_COLOR_ATTACHMENT0, texture, 0, 0); + EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR); + AttachmentParameter(framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR); + ExpectSingleGlError(GL_INVALID_ENUM); +} + +TEST_F(FramebufferMultiviewTest, AttachesViewsOfAnArrayTextureAndAnswersTheQueries) { + ScopedMultiviewBackend backend(4); + GLint maxViews = -1; + MG_Impl::GLImpl::GetIntegerv(GL_MAX_VIEWS_OVR, &maxViews); + EXPECT_EQ(maxViews, 4); + + GLuint framebuffer = 0; + MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer); + const GLuint texture = MakeArrayTexture(4); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, texture, 0, 1, 2); + ASSERT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR); + + const auto framebufferObject = MG_State::pGLContext->GetFramebufferObject(framebuffer); + const auto& attachment = framebufferObject->GetAttachment(FramebufferAttachmentType::Color0); + EXPECT_TRUE(attachment.IsMultiview()); + EXPECT_EQ(attachment.GetNumViews(), 2); + EXPECT_FALSE(attachment.IsLayered()); + EXPECT_EQ(framebufferObject->GetViewCount(), 2); + + EXPECT_EQ(AttachmentParameter(framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR), + 2); + EXPECT_EQ( + AttachmentParameter(framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_BASE_VIEW_INDEX_OVR), + 1); + EXPECT_EQ(AttachmentParameter(framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER), 1); + EXPECT_EQ(MG_Impl::GLImpl::CheckNamedFramebufferStatus(framebuffer, GL_DRAW_FRAMEBUFFER), + static_cast(GL_FRAMEBUFFER_COMPLETE)); + + // A plain layer attachment is not multiview, and says so. Layer 0, the one every backend backs. + MG_Impl::GLImpl::NamedFramebufferTextureLayer(framebuffer, GL_COLOR_ATTACHMENT0, texture, 0, 0); + ASSERT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR); + EXPECT_EQ(AttachmentParameter(framebuffer, GL_COLOR_ATTACHMENT0, GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_NUM_VIEWS_OVR), + 0); + EXPECT_EQ(framebufferObject->GetViewCount(), 1); + + // Texture 0 detaches. + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, 0, 0, 0, 2); + EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR); + EXPECT_FALSE(framebufferObject->GetAttachment(FramebufferAttachmentType::Color0).IsTexture()); +} + +TEST_F(FramebufferMultiviewTest, AttachRefusesWhatTheSpecRefuses) { + ScopedMultiviewBackend backend(4); + GLuint framebuffer = 0; + MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer); + const GLuint arrayTexture = MakeArrayTexture(8); + GLuint texture2D = 0; + MG_Impl::GLImpl::CreateTextures(GL_TEXTURE_2D, 1, &texture2D); + MG_Impl::GLImpl::TextureStorage2D(texture2D, 1, GL_RGBA8, 4, 4); + + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, arrayTexture, 0, 0, 0); + ExpectSingleGlError(GL_INVALID_VALUE); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, arrayTexture, 0, 0, 5); + ExpectSingleGlError(GL_INVALID_VALUE); + // The view count is checked even when detaching. + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, 0, 0, 0, 0); + ExpectSingleGlError(GL_INVALID_VALUE); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, texture2D, 0, 0, 2); + ExpectSingleGlError(GL_INVALID_OPERATION); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, arrayTexture, 0, -1, 2); + ExpectSingleGlError(GL_INVALID_VALUE); + // GL_MAX_ARRAY_TEXTURE_LAYERS is 8: views 7 and 8 do not both exist. + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, arrayTexture, 0, 7, 2); + ExpectSingleGlError(GL_INVALID_VALUE); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, arrayTexture, 0, 6, 2); + EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR); + + // The default framebuffer has no attachment points to name. + MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw).Bind(m_defaultFramebuffer); + MG_Impl::GLImpl::FramebufferTextureMultiviewOVR(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, arrayTexture, 0, 0, 2); + ExpectSingleGlError(GL_INVALID_OPERATION); +} + +TEST_F(FramebufferMultiviewTest, CompletenessNeedsEveryViewAndOneViewCount) { + ScopedMultiviewBackend backend(4); + const GLuint fourLayers = MakeArrayTexture(4); + const GLuint otherFourLayers = MakeArrayTexture(4); + + GLuint pastTheEnd = 0; + MG_Impl::GLImpl::CreateFramebuffers(1, &pastTheEnd); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(pastTheEnd, GL_COLOR_ATTACHMENT0, fourLayers, 0, 3, 2); + EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR) << "the layer count is a completeness question"; + EXPECT_EQ(MG_Impl::GLImpl::CheckNamedFramebufferStatus(pastTheEnd, GL_DRAW_FRAMEBUFFER), + static_cast(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT)); + + GLuint mixed = 0; + MG_Impl::GLImpl::CreateFramebuffers(1, &mixed); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(mixed, GL_COLOR_ATTACHMENT0, fourLayers, 0, 0, 2); + MG_Impl::GLImpl::NamedFramebufferTextureLayer(mixed, GL_COLOR_ATTACHMENT1, otherFourLayers, 0, 0); + EXPECT_EQ(MG_Impl::GLImpl::CheckNamedFramebufferStatus(mixed, GL_DRAW_FRAMEBUFFER), + static_cast(GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR)); + + GLuint differentCounts = 0; + MG_Impl::GLImpl::CreateFramebuffers(1, &differentCounts); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(differentCounts, GL_COLOR_ATTACHMENT0, fourLayers, 0, 0, 2); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(differentCounts, GL_COLOR_ATTACHMENT1, otherFourLayers, 0, 0, + 3); + EXPECT_EQ(MG_Impl::GLImpl::CheckNamedFramebufferStatus(differentCounts, GL_DRAW_FRAMEBUFFER), + static_cast(GL_FRAMEBUFFER_INCOMPLETE_VIEW_TARGETS_OVR)); + + // Matching counts with different base views are fine. + GLuint matching = 0; + MG_Impl::GLImpl::CreateFramebuffers(1, &matching); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(matching, GL_COLOR_ATTACHMENT0, fourLayers, 0, 0, 2); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(matching, GL_COLOR_ATTACHMENT1, otherFourLayers, 0, 2, 2); + EXPECT_EQ(MG_Impl::GLImpl::CheckNamedFramebufferStatus(matching, GL_DRAW_FRAMEBUFFER), + static_cast(GL_FRAMEBUFFER_COMPLETE)); + EXPECT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR); +} + +TEST_F(FramebufferMultiviewTest, AReadFramebufferWithSeveralViewsCannotBeRead) { + ScopedMultiviewBackend backend(4); + GLuint framebuffer = 0; + MG_Impl::GLImpl::CreateFramebuffers(1, &framebuffer); + MG_Impl::GLImpl::NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, MakeArrayTexture(2), 0, 0, + 2); + ASSERT_EQ(MG_Impl::GLImpl::GetError(), GL_NO_ERROR); + MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Read) + .Bind(MG_State::pGLContext->GetFramebufferObject(framebuffer)); + + Uint8 pixels[4 * 4 * 4] = {}; + MG_Impl::GLImpl::ReadPixels(0, 0, 4, 4, GL_RGBA, GL_UNSIGNED_BYTE, pixels); + ExpectSingleGlError(GL_INVALID_FRAMEBUFFER_OPERATION); + MG_Impl::GLImpl::BlitFramebuffer(0, 0, 4, 4, 0, 0, 4, 4, GL_COLOR_BUFFER_BIT, GL_NEAREST); + ExpectSingleGlError(GL_INVALID_FRAMEBUFFER_OPERATION); +} diff --git a/MobileGL/MG_Test/Program/CMakeLists.txt b/MobileGL/MG_Test/Program/CMakeLists.txt index ce34cd2e..baf50eed 100644 --- a/MobileGL/MG_Test/Program/CMakeLists.txt +++ b/MobileGL/MG_Test/Program/CMakeLists.txt @@ -45,6 +45,7 @@ endif() add_executable( ProgramTest ProgramTest.cpp + ProgramMultiviewTest.cpp ) add_executable( diff --git a/MobileGL/MG_Test/Program/ProgramArtifactsCodecTest.cpp b/MobileGL/MG_Test/Program/ProgramArtifactsCodecTest.cpp index 83ee53c8..efd3fabe 100644 --- a/MobileGL/MG_Test/Program/ProgramArtifactsCodecTest.cpp +++ b/MobileGL/MG_Test/Program/ProgramArtifactsCodecTest.cpp @@ -165,6 +165,7 @@ namespace { link.gsOutputPrimitive = GL_TRIANGLE_STRIP; link.gsMaxVertices = 12; link.gsInvocations = 2; + link.vsNumViews = 2; link.tessGenMode = GL_QUADS; link.tessGenSpacing = GL_FRACTIONAL_ODD; link.tessGenVertexOrder = GL_CW; @@ -529,9 +530,9 @@ TEST(ProgramArtifactsCodec, AVersionMismatchIsRefused) { // no archive owns. A codec arm for it would be a use-after-free waiting for a cache hit. TEST(ProgramArtifactsCodec, TheTablesVisitEveryMemberExceptTheLiveProgram) { // P7 OQ-8: 59 members, 58 visited. The 59th is still the live TProgram; the 58th is - // storageBlocks, which follows the record arm's guard (ProgramArtifacts.h). esOrigin then - // made it 60 and 59. - EXPECT_EQ(ProgramArtifactsVisitedFieldCount(), 60u); + // storageBlocks, which follows the record arm's guard (ProgramArtifacts.h). esOrigin and + // vsNumViews then made it 61 visited. + EXPECT_EQ(ProgramArtifactsVisitedFieldCount(), 61u); EXPECT_EQ(ProgramArtifactsVisitedFieldCount(), 3u); EXPECT_EQ(ProgramArtifactsVisitedFieldCount(), 10u); EXPECT_EQ(ProgramArtifactsVisitedFieldCount(), 14u); @@ -553,7 +554,7 @@ TEST(ProgramArtifactsCodec, PortableHeaderUsesWireSchemaRatherThanNativeContaine // too - it is derived from the VisitFields tables - and so did `wireFingerprint`, which is // what makes a mixed-version pair refuse at the handshake instead of at the first program. EXPECT_EQ(version, kProgramArtifactsCodecVersion); - EXPECT_EQ(version, 3u); + EXPECT_EQ(version, 4u); EXPECT_EQ(schema, ProgramArtifactsSchemaFingerprint()); EXPECT_NE(schema, 0u); EXPECT_NE(schema, sizeof(LinkArtifacts)); diff --git a/MobileGL/MG_Test/Program/ProgramArtifactsTest.cpp b/MobileGL/MG_Test/Program/ProgramArtifactsTest.cpp index 6e035952..ba8c718e 100644 --- a/MobileGL/MG_Test/Program/ProgramArtifactsTest.cpp +++ b/MobileGL/MG_Test/Program/ProgramArtifactsTest.cpp @@ -84,7 +84,7 @@ namespace { // P7 OQ-8 added LinkArtifacts::storageBlocks and its own three-field table; since P13 W5 // the member follows the record arm (ProgramArtifacts.h), which every library builds. EXPECT_EQ(CountFields(), 3u); - EXPECT_EQ(CountFields(), 60u); + EXPECT_EQ(CountFields(), 61u); EXPECT_EQ(CountFields(), 10u); } diff --git a/MobileGL/MG_Test/Program/ProgramMultiviewTest.cpp b/MobileGL/MG_Test/Program/ProgramMultiviewTest.cpp new file mode 100644 index 00000000..a965e07e --- /dev/null +++ b/MobileGL/MG_Test/Program/ProgramMultiviewTest.cpp @@ -0,0 +1,210 @@ +// MobileGL - MobileGL/MG_Test/Program/ProgramMultiviewTest.cpp +// Copyright (c) 2026 MobileGL-Dev +// Licensed under the GNU Lesser General Public License v3.0: +// https://www.gnu.org/licenses/gpl-3.0.txt +// https://www.gnu.org/licenses/lgpl-3.0.txt +// SPDX-License-Identifier: LGPL-3.0-only +// End of Source File Header + +// GL_OVR_multiview through the GL compile and link entry points: the vertex stage's num_views +// reaches the program (and survives a link memo hit), GL_MAX_VIEWS_OVR bounds it, the shading +// language extension and its macros exist only where the backend advertises the extension, and +// the draw-time rule compares the program with the draw framebuffer. +#include + +#include "Includes.h" +#include "Init.h" +#include "MG_Backend/BackendObjects.h" +#include "MG_Impl/GLImpl/Framebuffer/GL_Framebuffer.h" +#include "MG_Impl/GLImpl/Getter/GL_Getter.h" +#include "MG_Impl/GLImpl/Program/GL_Program.h" +#include "MG_Impl/GLImpl/Texture/GL_Texture.h" +#include "MG_State/GLState/Core.h" + +using namespace MobileGL; +using namespace MobileGL::MG_Impl::GLImpl; + +namespace { + // A backend that claims a type, so the compile environment gates extensions against its list. + class MultiviewProgramBackend final : public MG_Backend::BackendObject { + public: + MultiviewProgramBackend(Int maxViews, Vector extensions) { + m_params.MaxViews = maxViews; + m_params.MaxArrayTextureLayers = 8; + m_info.RendererGLInfo.Extensions = Move(extensions); + } + void Initialize() override {} + Bool InitCapabilities() override { return true; } + Bool InitWindowSurface() override { return true; } + const RendererInfo& GetRendererInfo() const override { return m_info; } + String GetBackendAPIVersionString() const override { return {}; } + const MG_Backend::GlobalBackendFunctionsTable& GetBackendFunctions() const override { + static MG_Backend::GlobalBackendFunctionsTable table = {}; + return table; + } + const MG_Backend::DynamicBackendParameters& GetDynamicParameters() const override { return m_params; } + BackendType GetBackendType() const override { return BackendType::DirectGLES; } + + private: + MG_Backend::DynamicBackendParameters m_params{}; + RendererInfo m_info{}; + }; + + class ScopedProgramBackend { + public: + ScopedProgramBackend(Int maxViews, Vector extensions) + : m_previous(Move(MG_Backend::pActiveBackendObject)) { + MG_Backend::pActiveBackendObject = MakeUnique(maxViews, Move(extensions)); + // The context re-captures its compile environment when the backend's address changes, + // and a freshly allocated mock can land on the address the previous one had. + MG_State::pGLContext->InvalidateCompileEnv(); + } + ~ScopedProgramBackend() { + MG_Backend::pActiveBackendObject = Move(m_previous); + MG_State::pGLContext->InvalidateCompileEnv(); + } + + private: + UniquePtr m_previous; + }; + + const Vector kBothExtensions = {E_GL_OVR_multiview, E_GL_OVR_multiview2}; + + GLuint CompiledShader(GLenum type, const char* source, GLint& status) { + const GLuint shader = CreateShader(type); + ShaderSource(shader, 1, &source, nullptr); + CompileShader(shader); + GetShaderiv(shader, GL_COMPILE_STATUS, &status); + return shader; + } + + Bool Compiles(GLenum type, const char* source) { + GLint status = GL_FALSE; + CompiledShader(type, source, status); + return status == GL_TRUE; + } + + // The linked program, or 0 when it did not link. + GLuint LinkedProgram(const char* vertex, const char* fragment) { + GLint status = GL_FALSE; + const GLuint vs = CompiledShader(GL_VERTEX_SHADER, vertex, status); + EXPECT_EQ(status, GL_TRUE); + const GLuint fs = CompiledShader(GL_FRAGMENT_SHADER, fragment, status); + EXPECT_EQ(status, GL_TRUE); + const GLuint program = CreateProgram(); + AttachShader(program, vs); + AttachShader(program, fs); + LinkProgram(program); + GetProgramiv(program, GL_LINK_STATUS, &status); + return status == GL_TRUE ? program : 0; + } + + String MultiviewVertex(Int numViews) { + return std::format("#version 330 core\n" + "#extension GL_OVR_multiview2 : require\n" + "layout(num_views = {}) in;\n" + "layout(location = 0) in vec2 pos;\n" + "void main() {{ gl_Position = vec4(pos.x + float(gl_ViewID_OVR), pos.y, 0.0, 1.0); }}\n", + numViews); + } + + constexpr const char* kFragment = "#version 330 core\n" + "out vec4 color;\n" + "void main() { color = vec4(1.0); }\n"; +} // namespace + +class ProgramMultiviewTest : public ::testing::Test { +protected: + void SetUp() override { + MobileGL::Initialize(); + for (Int drained = 0; drained < 16 && GetError() != GL_NO_ERROR; ++drained) {} + } + void TearDown() override { EXPECT_EQ(GetError(), GL_NO_ERROR) << "test left an unconsumed GL error behind"; } +}; + +TEST_F(ProgramMultiviewTest, TheVertexStagesNumViewsReachesTheProgramAndSurvivesAMemoHit) { + const ScopedProgramBackend backend(4, kBothExtensions); + const String vertex = MultiviewVertex(3); + for (Int link = 0; link < 2; ++link) { + const GLuint program = LinkedProgram(vertex.c_str(), kFragment); + ASSERT_NE(program, 0u) << "link " << link; + const auto programObject = MG_State::pGLContext->GetProgramObject(program); + ASSERT_NE(programObject, nullptr); + EXPECT_EQ(programObject->GetMultiviewViewCount(), 3) << "link " << link; + } + + const GLuint plain = LinkedProgram("#version 330 core\nvoid main() { gl_Position = vec4(0.0); }\n", kFragment); + ASSERT_NE(plain, 0u); + EXPECT_EQ(MG_State::pGLContext->GetProgramObject(plain)->GetMultiviewViewCount(), 1); +} + +TEST_F(ProgramMultiviewTest, MoreViewsThanTheBackendHasFailsTheLink) { + const ScopedProgramBackend backend(4, kBothExtensions); + const String vertex = MultiviewVertex(5); + EXPECT_EQ(LinkedProgram(vertex.c_str(), kFragment), 0u); +} + +TEST_F(ProgramMultiviewTest, TheShadingLanguageExtensionFollowsTheAdvertisement) { + constexpr const char* kRequireFirst = "#version 330 core\n#extension GL_OVR_multiview : require\n" + "void main() { gl_Position = vec4(float(gl_ViewID_OVR)); }\n"; + constexpr const char* kRequireSecond = "#version 330 core\n#extension GL_OVR_multiview2 : require\n" + "void main() { gl_Position = vec4(float(gl_ViewID_OVR)); }\n"; + constexpr const char* kMacroAbsent = "#version 330 core\n#if defined(GL_OVR_multiview) || " + "defined(GL_OVR_multiview2)\n#error the macro is defined\n#endif\n" + "void main() { gl_Position = vec4(0.0); }\n"; + constexpr const char* kMacroPresent = "#version 330 core\n#ifndef GL_OVR_multiview\n#error the macro is " + "missing\n#endif\nvoid main() { gl_Position = vec4(0.0); }\n"; + { + const ScopedProgramBackend backend(0, {}); + EXPECT_FALSE(Compiles(GL_VERTEX_SHADER, kRequireFirst)); + EXPECT_FALSE(Compiles(GL_VERTEX_SHADER, kRequireSecond)); + EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kMacroAbsent)); + } + { + const ScopedProgramBackend backend(4, {E_GL_OVR_multiview}); + EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kRequireFirst)); + EXPECT_FALSE(Compiles(GL_VERTEX_SHADER, kRequireSecond)); + EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kMacroPresent)); + } + { + const ScopedProgramBackend backend(4, kBothExtensions); + EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kRequireFirst)); + EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kRequireSecond)); + EXPECT_TRUE(Compiles(GL_VERTEX_SHADER, kMacroPresent)); + } +} + +TEST_F(ProgramMultiviewTest, ADrawNeedsTheProgramsViewCountInTheDrawFramebuffer) { + const ScopedProgramBackend backend(4, kBothExtensions); + const String vertex = MultiviewVertex(2); + const GLuint multiviewProgram = LinkedProgram(vertex.c_str(), kFragment); + const GLuint plainProgram = + LinkedProgram("#version 330 core\nvoid main() { gl_Position = vec4(0.0); }\n", kFragment); + ASSERT_NE(multiviewProgram, 0u); + ASSERT_NE(plainProgram, 0u); + const auto& multiview = *MG_State::pGLContext->GetProgramObject(multiviewProgram); + const auto& plain = *MG_State::pGLContext->GetProgramObject(plainProgram); + + auto& drawSlot = MG_State::pGLContext->GetFramebufferBindingSlot(FramebufferTarget::Draw); + const auto previous = drawSlot.GetBoundObject(); + + // The default framebuffer has one view. + drawSlot.Bind(MG_State::pGLContext->GetFramebufferObject(0)); + EXPECT_TRUE(ValidateMultiviewDraw(plain, "test")); + EXPECT_FALSE(ValidateMultiviewDraw(multiview, "test")); + EXPECT_EQ(GetError(), static_cast(GL_INVALID_OPERATION)); + + GLuint texture = 0; + CreateTextures(GL_TEXTURE_2D_ARRAY, 1, &texture); + TextureStorage3D(texture, 1, GL_RGBA8, 4, 4, 2); + GLuint framebuffer = 0; + CreateFramebuffers(1, &framebuffer); + NamedFramebufferTextureMultiviewOVR(framebuffer, GL_COLOR_ATTACHMENT0, texture, 0, 0, 2); + ASSERT_EQ(GetError(), static_cast(GL_NO_ERROR)); + drawSlot.Bind(MG_State::pGLContext->GetFramebufferObject(framebuffer)); + EXPECT_TRUE(ValidateMultiviewDraw(multiview, "test")); + EXPECT_FALSE(ValidateMultiviewDraw(plain, "test")); + EXPECT_EQ(GetError(), static_cast(GL_INVALID_OPERATION)); + + drawSlot.Bind(previous); +} diff --git a/MobileGL/MG_Util/BackendLoaders/OpenGL/Loader.cpp b/MobileGL/MG_Util/BackendLoaders/OpenGL/Loader.cpp index 4391f023..93d33e2d 100644 --- a/MobileGL/MG_Util/BackendLoaders/OpenGL/Loader.cpp +++ b/MobileGL/MG_Util/BackendLoaders/OpenGL/Loader.cpp @@ -665,6 +665,7 @@ namespace MobileGL::MG_Util::BackendLoader { INIT_GLES_FUNC_OPTIONAL(glPolygonModeNV) INIT_GLES_FUNC_OPTIONAL(glPolygonModeANGLE) INIT_GLES_FUNC_OPTIONAL(glClipControlEXT) + INIT_GLES_FUNC_OPTIONAL(glFramebufferTextureMultiviewOVR) INIT_GLES_FUNC_OPTIONAL(glColorMaskiEXT) INIT_GLES_FUNC_OPTIONAL(glColorMaskiOES) INIT_GLES_FUNC_OPTIONAL(glPolygonOffsetClampEXT) @@ -1000,6 +1001,39 @@ namespace MobileGL::MG_Util::BackendLoader { } } + // GL_OVR_multiview and GL_OVR_multiview2: the strings, the entry point and GL_MAX_VIEWS_OVR. The + // second extension only counts on top of the first, which is the one with the entry point. + static void FillInMultiviewCapabilities(MG_External::GLESCapabilities& caps, + const MG_External::GLESFunctionsTable& glesFuncs, GLint extCount) { + Bool hasMultiview = false; + Bool hasMultiview2 = false; + for (GLint i = 0; i < extCount; ++i) { + const char* extension = reinterpret_cast(glesFuncs.glGetStringi(GL_EXTENSIONS, i)); + if (!extension) continue; + if (std::strcmp(extension, "GL_OVR_multiview") == 0) hasMultiview = true; + if (std::strcmp(extension, "GL_OVR_multiview2") == 0) hasMultiview2 = true; + } + caps.SupportsMultiview = hasMultiview && glesFuncs.glFramebufferTextureMultiviewOVR != nullptr; + caps.MaxViews = 0; + if (caps.SupportsMultiview) { + GLint maxViews = 0; + while (glesFuncs.glGetError() != GL_NO_ERROR) {} + glesFuncs.glGetIntegerv(GL_MAX_VIEWS_OVR, &maxViews); + // The spec minimum is 2. A driver that rejects the query or answers less cannot back + // the extension, so it is reported absent rather than clamped up. + if (glesFuncs.glGetError() != GL_NO_ERROR || maxViews < 2) { + MGLOG_W("GL_OVR_multiview is advertised but GL_MAX_VIEWS_OVR answered %d; reporting no multiview", + maxViews); + caps.SupportsMultiview = false; + } else { + caps.MaxViews = maxViews; + } + } + caps.SupportsMultiview2 = caps.SupportsMultiview && hasMultiview2; + MGLOG_I(" multiview (OVR_multiview / OVR_multiview2): %s / %s, GL_MAX_VIEWS_OVR %d", + caps.SupportsMultiview ? "yes" : "no", caps.SupportsMultiview2 ? "yes" : "no", caps.MaxViews); + } + // Reads what the driver answers for GL_EXT_fragment_shading_rate once the extension strings have // been matched. The per-sample-count rate lists are folded into masks of the packed encoding // ((log2 w << 2) | log2 h), which is what crosses to the frontend. @@ -1338,6 +1372,7 @@ namespace MobileGL::MG_Util::BackendLoader { // The string AND the pointer: eglGetProcAddress may hand back a stub for a name the // driver does not implement. caps.SupportsClipControl = hasClipControlExtension && glesFuncs.glClipControlEXT != nullptr; + FillInMultiviewCapabilities(caps, glesFuncs, extCount); caps.SupportsComputeShader = esAtLeast31 && glesFuncs.glDispatchCompute != nullptr && glesFuncs.glMemoryBarrier != nullptr && glesFuncs.glCreateShader != nullptr && glesFuncs.glCreateProgram != nullptr; diff --git a/MobileGL/MG_Util/BackendLoaders/OpenGL/Loader.h b/MobileGL/MG_Util/BackendLoaders/OpenGL/Loader.h index a8b277fe..17248625 100644 --- a/MobileGL/MG_Util/BackendLoaders/OpenGL/Loader.h +++ b/MobileGL/MG_Util/BackendLoaders/OpenGL/Loader.h @@ -650,6 +650,9 @@ namespace MobileGL { GL_FUNC_TYPEDEF(void, glPolygonModeANGLE, GLenum face, GLenum mode) // GL_EXT_clip_control (ES has no core glClipControl). GL_FUNC_TYPEDEF(void, glClipControlEXT, GLenum origin, GLenum depth) + // GL_OVR_multiview. + GL_FUNC_TYPEDEF(void, glFramebufferTextureMultiviewOVR, GLenum target, GLenum attachment, GLuint texture, + GLint level, GLint baseViewIndex, GLsizei numViews) GL_FUNC_TYPEDEF(void, glColorMaskiEXT, GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a) GL_FUNC_TYPEDEF(void, glColorMaskiOES, GLuint index, GLboolean r, GLboolean g, GLboolean b, GLboolean a) // GL_EXT_polygon_offset_clamp. ES has no core spelling at any version. @@ -1069,6 +1072,7 @@ namespace MobileGL { GL_FUNC_DECL(glPolygonModeNV) GL_FUNC_DECL(glPolygonModeANGLE) GL_FUNC_DECL(glClipControlEXT) + GL_FUNC_DECL(glFramebufferTextureMultiviewOVR) GL_FUNC_DECL(glColorMaskiEXT) GL_FUNC_DECL(glColorMaskiOES) GL_FUNC_DECL(glPolygonOffsetClampEXT) @@ -1124,6 +1128,11 @@ namespace MobileGL { // GL_EXT_clip_control advertised and glClipControlEXT resolved: the driver applies a // clip-space origin and depth mode, so the application's glClipControl is forwarded. Bool SupportsClipControl = false; + // GL_OVR_multiview advertised and glFramebufferTextureMultiviewOVR resolved, with + // GL_MAX_VIEWS_OVR in MaxViews. GL_OVR_multiview2 only counts on top of it. + Bool SupportsMultiview = false; + Bool SupportsMultiview2 = false; + Int MaxViews = 0; // GL_EXT_texture_view / GL_OES_texture_view: two ES texture names sharing one // storage, i.e. the only way DirectGLES can answer glTextureView at all. ES never // made this core - not even in 3.2 - so unlike every other capability here there is diff --git a/MobileGL/MG_Util/ShaderTranspiler/ShaderCompiler.cpp b/MobileGL/MG_Util/ShaderTranspiler/ShaderCompiler.cpp index 91e83bd5..bc9a41e9 100644 --- a/MobileGL/MG_Util/ShaderTranspiler/ShaderCompiler.cpp +++ b/MobileGL/MG_Util/ShaderTranspiler/ShaderCompiler.cpp @@ -13,6 +13,7 @@ #include "ShaderCompiler.h" #include +#include #include #include @@ -1570,6 +1571,41 @@ namespace MobileGL { enableSpirvValidation); } + bool ShaderCompiler::StripMultiviewCapabilityForEssl(const Vector& inputBinary, + Vector& outputBinary) { + outputBinary.clear(); + constexpr SizeT kHeaderWords = 5; + if (inputBinary.size() <= kHeaderWords) return false; + static constexpr char kExtension[] = "SPV_KHR_multiview"; + Vector out(inputBinary.begin(), inputBinary.begin() + kHeaderWords); + out.reserve(inputBinary.size()); + Bool stripped = false; + SizeT at = kHeaderWords; + // Capabilities and extensions all precede OpMemoryModel, so the walk stops there. + while (at < inputBinary.size()) { + const Uint32 wordCount = inputBinary[at] >> 16; + const auto opcode = static_cast(inputBinary[at] & 0xFFFFu); + if (wordCount == 0 || at + wordCount > inputBinary.size()) return false; + if (opcode == spv::Op::OpMemoryModel) break; + Bool drop = false; + if (opcode == spv::Op::OpCapability && wordCount == 2) { + drop = inputBinary[at + 1] == static_cast(spv::Capability::MultiView); + } else if (opcode == spv::Op::OpExtension && (wordCount - 1) * 4 > sizeof(kExtension) - 1) { + drop = std::memcmp(&inputBinary[at + 1], kExtension, sizeof(kExtension)) == 0; + } + if (drop) { + stripped = true; + } else { + out.insert(out.end(), inputBinary.begin() + at, inputBinary.begin() + at + wordCount); + } + at += wordCount; + } + if (!stripped) return false; + out.insert(out.end(), inputBinary.begin() + at, inputBinary.end()); + outputBinary = Move(out); + return true; + } + bool ShaderCompiler::LowerViewportIndexForEssl(const Vector& inputBinary, Vector& outputBinary, const bool enableSpirvValidation) { diff --git a/MobileGL/MG_Util/ShaderTranspiler/ShaderCompiler.h b/MobileGL/MG_Util/ShaderTranspiler/ShaderCompiler.h index 4a3e6ef9..8c4b640d 100644 --- a/MobileGL/MG_Util/ShaderTranspiler/ShaderCompiler.h +++ b/MobileGL/MG_Util/ShaderTranspiler/ShaderCompiler.h @@ -56,6 +56,15 @@ namespace MobileGL { static bool LowerDrawParametersForEssl(const Vector& inputBinary, Vector& outputBinary, bool enableSpirvValidation = false); + // Drops OpCapability MultiView and OpExtension "SPV_KHR_multiview" and leaves the + // ViewIndex built-in, which SPIRV-Cross then prints as gl_ViewID_OVR. Its own route + // for the capability needs the view count, which the module does not carry, and + // refuses every stage but the vertex one, where GL_OVR_multiview also has the + // built-in in the fragment stage; DirectGLES spells the directive and num_views + // itself (RequestMultiviewExtension). True, with `outputBinary` filled, only when + // something was dropped. + static bool StripMultiviewCapabilityForEssl(const Vector& inputBinary, + Vector& outputBinary); // Demotes the gl_ViewportIndex OUTPUT builtin to a plain Private global named // mg_ViewportIndex, so SPIRV-Cross emits an ordinary declaration instead of a bare // gl_ViewportIndex that ESSL has no core spelling for. Multi-viewport routing is diff --git a/MobileGL/MG_Util/ShaderTranspiler/ShaderSourceProcessor.cpp b/MobileGL/MG_Util/ShaderTranspiler/ShaderSourceProcessor.cpp index 5d0f945b..9c7c25f8 100644 --- a/MobileGL/MG_Util/ShaderTranspiler/ShaderSourceProcessor.cpp +++ b/MobileGL/MG_Util/ShaderTranspiler/ShaderSourceProcessor.cpp @@ -967,10 +967,13 @@ namespace { // this stage is not in GL_SUBGROUP_SUPPORTED_STAGES_KHR, or when that extension's // feature is not in GL_SUBGROUP_SUPPORTED_FEATURES_KHR - the KHR spec's own terms for // where each of the eight may be used. The stage and feature tests need a backend: - // with none, every extension reads as available (CompileEnv::IsExtensionAdvertised). + // with none, every extension reads as available (CompileEnv::IsExtensionAdvertised); + // * GL_OVR_multiview / GL_OVR_multiview2 when that extension is not advertised. bool IsUnavailableShaderExtension(const MobileGL::MG_Util::ShaderTranspiler::CompileEnv& env, MobileGL::ShaderStage stage, const MobileGL::String& name) { if (name == "GL_ARB_gpu_shader_int64") return !env.IsExtensionAdvertised(MobileGL::E_GL_ARB_gpu_shader_int64); + if (name == "GL_OVR_multiview") return !env.IsExtensionAdvertised(MobileGL::E_GL_OVR_multiview); + if (name == "GL_OVR_multiview2") return !env.IsExtensionAdvertised(MobileGL::E_GL_OVR_multiview2); const GLbitfield feature = SubgroupFeatureBit(name); if (feature == 0) return false; if (!env.IsExtensionAdvertised(MobileGL::E_GL_KHR_shader_subgroup)) return true; @@ -1048,10 +1051,13 @@ namespace { source.replace(it->pos, it->len, it->replacement); } // The extension's own feature-test macro, so an `#ifdef` guard takes the fallback branch. - // int64 keeps its historical treatment: hidden whether or not the source names it. - if (IsUnavailableShaderExtension(env, stage, "GL_ARB_gpu_shader_int64") && - std::find(hiddenNames.begin(), hiddenNames.end(), "GL_ARB_gpu_shader_int64") == hiddenNames.end()) { - hiddenNames.push_back("GL_ARB_gpu_shader_int64"); + // int64 keeps its historical treatment: hidden whether or not the source names it, and the + // two multiview macros get the same, because glslang predefines them at every 300+ version. + for (const char* alwaysHidden : {"GL_ARB_gpu_shader_int64", "GL_OVR_multiview", "GL_OVR_multiview2"}) { + if (IsUnavailableShaderExtension(env, stage, alwaysHidden) && + std::find(hiddenNames.begin(), hiddenNames.end(), alwaysHidden) == hiddenNames.end()) { + hiddenNames.push_back(alwaysHidden); + } } for (const auto& name : hiddenNames) { ReplaceIdentifier(source, name, "MG_DISABLED_" + name); diff --git a/include/glslang/MachineIndependent/localintermediate.h b/include/glslang/MachineIndependent/localintermediate.h index 137ab279..7f98487e 100644 --- a/include/glslang/MachineIndependent/localintermediate.h +++ b/include/glslang/MachineIndependent/localintermediate.h @@ -324,6 +324,7 @@ public: source(EShSourceNone), useVulkanMemoryModel(false), invocations(TQualifier::layoutNotSet), vertices(TQualifier::layoutNotSet), + numViews(TQualifier::layoutNotSet), inputPrimitive(ElgNone), outputPrimitive(ElgNone), pixelCenterInteger(false), originUpperLeft(false),texCoordBuiltinRedeclared(false), vertexSpacing(EvsNone), vertexOrder(EvoNone), interlockOrdering(EioNone), pointMode(false), earlyFragmentTests(false), @@ -901,6 +902,16 @@ public: return true; } int getInvocations() const { return invocations; } + // GL_OVR_multiview's layout(num_views = N) in; of a vertex shader. SPIR-V has no way to say + // it, so a consumer that emits GLSL from the module reads it here. + bool setNumViews(int n) + { + if (numViews != TQualifier::layoutNotSet) + return numViews == n; + numViews = n; + return true; + } + int getNumViews() const { return numViews; } bool setVertices(int m) { if (vertices != TQualifier::layoutNotSet) @@ -1286,6 +1297,7 @@ protected: bool useVulkanMemoryModel; int invocations; int vertices; + int numViews; TLayoutGeometry inputPrimitive; TLayoutGeometry outputPrimitive; bool pixelCenterInteger;