From 14b6113f62af6642f2837b51855b060753fcf084 Mon Sep 17 00:00:00 2001 From: Ramses Tech User <94632088+ramses-tech-user@users.noreply.github.com> Date: Tue, 21 Nov 2023 16:21:23 +0100 Subject: [PATCH 1/5] Oss release 28.0.0-rc3 created 2023-11-21-16-21 see CHANGELOG.md for details Original commit sha: 1bf9fb3d164a60d54b2268553cbe865b4d0fdcf2 Co-authored-by: Askanaz Torosyan <46795157+nVxx@users.noreply.github.com> Co-authored-by: Daniel Haas <25718295+bojackHaasman@users.noreply.github.com> Co-authored-by: Mirko Sova <64351017+smirko-dev@users.noreply.github.com> Co-authored-by: Violin Yanev Co-authored-by: Carsten Rohn <710234+delyas@users.noreply.github.com> Co-authored-by: Tobias Hammer Co-authored-by: Bernhard Kisslinger <65217745+bkisslinger@users.noreply.github.com> Co-authored-by: Martin Veith <3490591+veithm@users.noreply.github.com> Co-authored-by: Jonathan Conrad <833168+jcsneaker@users.noreply.github.com> Co-authored-by: Mohamed Sharaf-El-Deen <769940+mohhsharaf@users.noreply.github.com> Co-authored-by: Markus Keppler <92277233+markuskeppler@users.noreply.github.com> Co-authored-by: Chan Tong Yan <4199832+imyumichan@users.noreply.github.com> --- CHANGELOG.md | 44 +- CMakeLists.txt | 31 +- README.md | 10 +- cmake/ramses/createTarget.cmake | 3 +- .../ramses-shared-libTemplate.cmake.in | 32 +- doc/sphinx/build.rst | 5 - doc/sphinx/conf.py | 3 + doc/sphinx/logic.rst | 2 +- doc/sphinx/viewer.rst | 40 +- examples/CMakeLists.txt | 6 - examples/logic/05_serialization/main.cpp | 7 +- examples/logic/CMakeLists.txt | 22 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../src/main.cpp | 38 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- .../ramses-example-minimal/CMakeLists.txt | 2 +- .../ramses-example-renderonce/CMakeLists.txt | 2 +- .../ramses-example-text-basic/CMakeLists.txt | 2 +- .../CMakeLists.txt | 2 +- include/CMakeLists.txt | 2 +- include/ramses/client/AttributeInput.h | 30 + include/ramses/client/MipLevelData.h | 87 +- include/ramses/client/SaveFileConfig.h | 9 - include/ramses/client/Scene.h | 12 +- include/ramses/client/Texture2DBuffer.h | 8 +- include/ramses/client/UniformInput.h | 29 + include/ramses/client/logic/LogicEngine.h | 15 + .../ramses/client/logic/RenderBufferBinding.h | 106 ++ include/ramses/client/ramses-utils.h | 13 +- include/ramses/framework/APIExport.h | 4 + .../ramses/framework/RamsesFrameworkConfig.h | 12 + scripts/ci/build/build.py | 6 +- scripts/ci/build/test-cmake-configurations.py | 52 +- scripts/ci/config/clang-tidy-wrapper.yaml | 2 +- scripts/ci/config/valgrind/suppressions | 19 +- .../installation-check/check-installation.py | 32 +- .../check-shared-lib-symbols.py | 12 +- .../shared-lib-check/CMakeLists.txt | 2 +- .../code_style_checker/check_deprecated.py | 5 - src/client/CMakeLists.txt | 42 +- src/client/impl/AttributeInput.cpp | 10 + src/client/impl/BlitPassImpl.cpp | 46 +- src/client/impl/BlitPassImpl.h | 3 + src/client/impl/CameraNodeImpl.cpp | 41 +- src/client/impl/CameraNodeImpl.h | 4 +- src/client/impl/EffectDescriptionImpl.cpp | 8 +- src/client/impl/EffectImpl.cpp | 12 +- src/client/impl/RamsesClientImpl.cpp | 100 +- src/client/impl/RamsesClientTypesImpl.h | 6 - src/client/impl/RenderBufferImpl.cpp | 18 +- src/client/impl/RenderBufferImpl.h | 2 + .../impl/RenderTargetDescriptionImpl.cpp | 2 +- src/client/impl/RenderTargetImpl.cpp | 22 + src/client/impl/RenderTargetImpl.h | 2 + src/client/impl/ResourceImpl.cpp | 2 +- src/client/impl/SaveFileConfig.cpp | 5 - src/client/impl/SaveFileConfigImpl.cpp | 14 - src/client/impl/SaveFileConfigImpl.h | 6 +- src/client/impl/Scene.cpp | 2 +- src/client/impl/SceneDumper.cpp | 38 +- src/client/impl/SceneDumper.h | 1 + src/client/impl/SceneFactory.cpp | 2 +- src/client/impl/SceneImpl.cpp | 139 +- src/client/impl/SceneImpl.h | 3 +- src/client/impl/SceneObjectImpl.cpp | 10 - src/client/impl/SceneObjectImpl.h | 4 - src/client/impl/SceneObjectRegistry.cpp | 55 +- src/client/impl/SceneObjectRegistry.h | 18 +- src/client/impl/SceneObjectRegistryIterator.h | 33 +- src/client/impl/SerializationHelper.h | 2 +- src/client/impl/Texture2DBuffer.cpp | 4 +- src/client/impl/TextureUtils.cpp | 79 +- src/client/impl/UniformInput.cpp | 10 + .../impl/logic/AnimationNodeConfigImpl.cpp | 32 +- src/client/impl/logic/DataArrayImpl.cpp | 2 +- src/client/impl/logic/LogicEngine.cpp | 170 +- src/client/impl/logic/LogicEngineImpl.cpp | 16 +- src/client/impl/logic/LogicEngineImpl.h | 3 + src/client/impl/logic/LogicObject.cpp | 15 - src/client/impl/logic/LuaConfigImpl.cpp | 8 +- src/client/impl/logic/NodeBindingImpl.cpp | 4 +- src/client/impl/logic/Property.cpp | 4 +- src/client/impl/logic/PropertyImpl.cpp | 18 +- src/client/impl/logic/RenderBufferBinding.cpp | 40 + .../impl/logic/RenderBufferBindingImpl.cpp | 188 +++ .../impl/logic/RenderBufferBindingImpl.h | 76 + .../logic/RenderGroupBindingElementsImpl.cpp | 6 +- src/client/impl/ramses-utils.cpp | 85 +- src/client/impl/text/FontRegistryImpl.cpp | 18 +- .../impl/text/Freetype2FontInstance.cpp | 16 +- src/client/impl/text/FreetypeFontFace.cpp | 6 +- src/client/impl/text/GlyphTexturePage.cpp | 2 +- src/client/impl/text/TextCacheImpl.cpp | 6 +- src/client/impl/text/UtfUtils.cpp | 18 +- src/client/internal/CMakeLists.txt | 50 + .../internal/ClientApplicationLogic.cpp | 4 +- .../ClientCommands/DumpSceneToFile.cpp | 8 +- .../ClientCommands/SceneCommandVisitor.cpp | 19 +- src/client/internal/RamsesVersion.cpp | 4 +- src/client/internal/logic/ApiObjects.cpp | 125 +- src/client/internal/logic/ApiObjects.h | 5 + .../logic/ApiObjectsSerializedSize.cpp | 8 + .../internal/logic/DirectedAcyclicGraph.cpp | 6 +- .../logic/LogicNodeUpdateStatistics.cpp | 14 +- .../internal/logic/LuaCompilationUtils.cpp | 6 +- .../internal/logic/LuaCustomizations.cpp | 6 +- .../flatbuffers/generated/ApiObjectsGen.h | 35 +- .../generated/RenderBufferBindingGen.h | 94 ++ .../logic/flatbuffers/schemas/ApiObjects.fbs | 2 + .../schemas/RenderBufferBinding.fbs | 11 +- src/framework/CMakeLists.txt | 105 +- src/framework/impl/APILoggingHelper.h | 31 - src/framework/impl/APILoggingMacros.h | 75 +- src/framework/impl/ErrorReporting.cpp | 4 +- src/framework/impl/ErrorReporting.h | 3 +- .../impl/FrameworkFactoryRegistry.cpp | 2 +- src/framework/impl/FrameworkFactoryRegistry.h | 7 +- src/framework/impl/RamsesFramework.cpp | 2 - src/framework/impl/RamsesFrameworkConfig.cpp | 5 + .../impl/RamsesFrameworkConfigImpl.cpp | 16 +- .../impl/RamsesFrameworkConfigImpl.h | 3 + src/framework/impl/RamsesFrameworkImpl.cpp | 23 +- src/framework/impl/RamsesFrameworkImpl.h | 3 +- src/framework/impl/RamsesObject.cpp | 73 +- src/framework/impl/RamsesObjectImpl.h | 2 - src/framework/internal/CMakeLists.txt | 115 ++ .../CommunicationSystemFactory.cpp | 6 +- .../ConnectionStatusUpdateNotifier.cpp | 4 +- .../RamsesTransportProtocolVersion.h | 2 +- .../SceneUpdateSerializationHelper.cpp | 2 +- .../SceneUpdateStreamDeserializer.cpp | 24 +- .../SingleSceneUpdateWriter.cpp | 4 +- .../TransportTCP/TCPConnectionSystem.cpp | 181 ++- .../TransportTCP/TcpDiscoveryDaemon.cpp | 2 +- .../Components/ClientSceneLogicBase.cpp | 18 +- .../Components/ClientSceneLogicDirect.cpp | 4 +- .../Components/ClientSceneLogicShadowCopy.cpp | 8 +- .../internal/Components/ResourceComponent.cpp | 8 +- .../Components/ResourcePersistation.cpp | 8 +- .../ResourceSerializationHelper.cpp | 2 +- .../internal/Components/ResourceStorage.cpp | 8 +- .../Components/ResourceTableOfContents.cpp | 2 +- .../Components/SceneGraphComponent.cpp | 84 +- .../TaskFramework/TaskExecutingThread.cpp | 2 +- .../AndroidLogger/AndroidLogAppender.cpp | 8 +- .../Core/Utils/ConsoleLogAppender.cpp | 10 +- src/framework/internal/Core/Utils/File.cpp | 16 +- src/framework/internal/Core/Utils/Image.cpp | 16 +- src/framework/internal/Core/Utils/Image.h | 1 + .../internal/Core/Utils/LogAppenderBase.h | 2 +- .../internal/Core/Utils/LogHelper.cpp | 2 +- src/framework/internal/Core/Utils/LogMacros.h | 62 +- .../internal/Core/Utils/LogMessage.h | 38 +- .../internal/Core/Utils/PeriodicLogger.cpp | 12 +- .../internal/Core/Utils/RamsesLogger.cpp | 66 +- .../internal/Core/Utils/RamsesLogger.h | 14 +- .../internal/Core/Utils/ThreadLocalLog.cpp | 39 - .../internal/Core/Utils/ThreadLocalLog.h | 125 -- .../Core/Utils/ThreadLocalLogForced.h | 64 - .../internal/Core/Utils/UserLogAppender.cpp | 2 +- .../DltAdapterImpl/DltAdapterImpl.cpp | 8 +- .../PlatformAbstraction/PlatformThread.h | 19 +- .../synchronized_clock.cpp | 4 +- src/framework/internal/Ramsh/Ramsh.cpp | 14 +- .../Ramsh/RamshCommandArgumentsDataProvider.h | 7 +- .../Ramsh/RamshCommandPrintBuildConfig.cpp | 25 +- .../Ramsh/RamshCommandPrintLogLevels.cpp | 12 +- .../Ramsh/RamshCommandSetConsoleLogLevel.cpp | 4 +- .../Ramsh/RamshCommandSetContextLogLevel.cpp | 10 +- .../RamshCommunicationChannelConsole.cpp | 2 +- ...mmunicationChannelConsoleSignalHandler.cpp | 2 +- .../Ramsh/RamshCommunicationChannelDLT.cpp | 4 +- .../Scene/ActionCollectingScene.cpp | 6 + .../SceneGraph/Scene/ActionCollectingScene.h | 1 + .../SceneGraph/Scene/ESceneActionId.h | 2 + .../Scene/ResourceChangeCollectingScene.cpp | 7 + .../Scene/ResourceChangeCollectingScene.h | 1 + .../SceneGraph/Scene/ResourceChanges.cpp | 46 - .../SceneGraph/Scene/ResourceChanges.h | 10 +- .../internal/SceneGraph/Scene/Scene.cpp | 10 + .../internal/SceneGraph/Scene/Scene.h | 177 +-- .../SceneGraph/Scene/SceneActionApplier.cpp | 60 +- .../Scene/SceneActionCollectionCreator.cpp | 32 +- .../Scene/SceneActionCollectionCreator.h | 1 + .../internal/SceneGraph/SceneAPI/IScene.h | 1 + .../SceneGraph/SceneAPI/RenderBuffer.h | 24 - .../SceneUtils/DataInstanceHelper.h | 15 +- .../internal/Watchdog/PlatformWatchdog.cpp | 2 +- src/ramses-cli/include/ramses-cli.h | 2 +- src/renderer/CMakeLists.txt | 1 + src/renderer/impl/BinaryShaderCacheImpl.cpp | 12 +- .../impl/CommandDispatchingThread.cpp | 10 +- src/renderer/impl/RamsesRendererImpl.cpp | 4 +- src/renderer/impl/RendererFactory.cpp | 3 +- .../impl/RendererSceneControlImpl.cpp | 6 +- .../Platform/Android/Window_Android.cpp | 2 +- src/renderer/internal/Platform/CMakeLists.txt | 2 +- .../Device_EGL_Extension.cpp | 12 +- .../internal/Platform/EGL/Context_EGL.cpp | 74 +- .../internal/Platform/EGL/Platform_EGL.h | 6 +- .../internal/Platform/OpenGL/DebugOutput.cpp | 19 +- .../internal/Platform/OpenGL/Device_GL.cpp | 40 +- .../Platform/OpenGL/ShaderGPUResource_GL.cpp | 8 +- .../Platform/OpenGL/ShaderUploader_GL.cpp | 12 +- .../internal/Platform/PlatformFactory.cpp | 2 +- .../EmbeddedCompositor_Wayland.cpp | 24 +- .../EmbeddedCompositor/LinuxDmabuf.cpp | 4 +- .../LinuxDmabufConnection.cpp | 8 +- .../EmbeddedCompositor/LinuxDmabufParams.cpp | 46 +- .../TextureUploadingAdapter_Wayland.cpp | 18 +- .../EmbeddedCompositor/WaylandBuffer.cpp | 4 +- .../WaylandCompositorConnection.cpp | 8 +- .../WaylandCompositorGlobal.cpp | 2 +- .../EmbeddedCompositor/WaylandDisplay.cpp | 55 +- .../WaylandIVIApplicationConnection.cpp | 13 +- .../WaylandIVIApplicationGlobal.cpp | 2 +- .../EmbeddedCompositor/WaylandIVISurface.cpp | 24 +- .../WaylandOutputConnection.cpp | 8 +- .../WaylandOutputGlobal.cpp | 2 +- .../EmbeddedCompositor/WaylandRegion.cpp | 7 +- .../WaylandShellConnection.cpp | 8 +- .../EmbeddedCompositor/WaylandShellGlobal.cpp | 2 +- .../WaylandShellSurface.cpp | 13 +- .../EmbeddedCompositor/WaylandSurface.cpp | 31 +- .../IVI/Platform_Wayland_IVI_EGL_ES_3_0.cpp | 2 +- .../IVIControllerScreen.cpp | 2 +- .../IVIControllerSurface.cpp | 35 +- ...SystemCompositorController_Wayland_IVI.cpp | 53 +- .../WaylandOutput.cpp | 9 +- .../Wayland/IVI/Window_Wayland_IVI.cpp | 4 +- .../Wayland/InputHandling_Wayland.cpp | 6 +- .../Platform/Wayland/Logger_Wayland.cpp | 6 +- .../Platform/Wayland/Platform_Wayland_EGL.cpp | 2 +- .../Wayland/WaylandEGLExtensionProcs.cpp | 4 +- .../Wayland/WaylandEnvironmentUtils.cpp | 10 +- .../Platform/Wayland/Window_Wayland.cpp | 4 +- .../Wayland/WlShell/Window_Wayland_Shell.cpp | 2 +- .../internal/Platform/Windows/Context_WGL.cpp | 24 +- .../Platform/Windows/HiddenWindow.cpp | 2 +- .../Platform/Windows/Platform_Windows_WGL.cpp | 6 +- .../Platform/Windows/WglExtensions.cpp | 2 +- .../Platform/Windows/Window_Windows.cpp | 10 +- .../internal/Platform/X11/Window_X11.cpp | 10 +- .../internal/Platform/iOS/Window_iOS.mm | 2 +- .../RendererLib/AsyncEffectUploader.cpp | 24 +- .../RendererLib/AsyncEffectUploader.h | 6 +- .../internal/RendererLib/CMakeLists.txt | 16 +- .../RendererLib/DataReferenceLinkManager.cpp | 4 +- .../RendererLib/DisplayDispatcher.cpp | 59 +- .../internal/RendererLib/DisplayDispatcher.h | 2 +- .../RendererLib/DisplayEventHandler.cpp | 11 +- .../internal/RendererLib/DisplayThread.cpp | 29 +- .../internal/RendererLib/DisplayThread.h | 2 + .../EmbeddedCompositingManager.cpp | 12 +- .../RendererLib/IRendererResourceManager.h | 3 +- .../RendererLib/IRendererSceneUpdater.h | 3 +- .../internal/RendererLib/LinkManagerBase.cpp | 8 +- .../PendingSceneResourcesUtils.cpp | 33 +- .../PlatformBase/EmbeddedCompositor_Dummy.cpp | 16 +- .../PlatformBase/Platform_Base.cpp | 18 +- .../PlatformBase/RendererLimits.cpp | 20 +- .../RendererLib/PlatformBase/Window_Base.cpp | 2 +- .../RendererLib/RamshCommands/AssignScene.cpp | 4 +- .../RamshCommands/CreateOffscreenBuffer.cpp | 6 +- .../RamshCommands/LogRendererInfo.cpp | 2 +- .../RendererLib/RamshCommands/Screenshot.cpp | 2 +- .../RamshCommands/SetClearColor.cpp | 2 +- .../RamshCommands/SetSceneState.cpp | 2 +- .../internal/RendererLib/Renderer.cpp | 10 +- .../RendererLib/RendererCommandExecutor.cpp | 90 +- .../internal/RendererLib/RendererCommands.h | 4 + .../RendererLib/RendererEventCollector.cpp | 22 +- .../RendererLib/RendererFrameworkLogic.cpp | 28 +- .../internal/RendererLib/RendererLogger.cpp | 29 +- .../internal/RendererLib/RendererLogger.h | 5 +- .../RendererPeriodicLogSupplier.cpp | 3 +- .../RendererLib/RendererResourceManager.cpp | 57 +- .../RendererLib/RendererResourceManager.h | 3 +- .../RendererLib/RendererResourceRegistry.cpp | 26 +- .../RendererLib/RendererSceneControlLogic.cpp | 44 +- .../RendererSceneResourceRegistry.cpp | 14 +- .../RendererSceneResourceRegistry.h | 58 +- .../RendererLib/RendererSceneUpdater.cpp | 117 +- .../RendererLib/RendererSceneUpdater.h | 2 +- .../RendererLib/RendererStatistics.cpp | 8 +- .../internal/RendererLib/RendererStatistics.h | 2 +- .../RendererLib/ResourceCachedScene.cpp | 2 +- .../internal/RendererLib/ResourceUploader.cpp | 6 +- .../RendererLib/ResourceUploadingManager.cpp | 22 +- .../RendererLib/SceneExpirationMonitor.cpp | 46 +- .../RendererLib/SceneLinksManager.cpp | 22 +- .../RendererLib/SceneReferenceLogic.cpp | 44 +- .../RendererLib/SceneStateExecutor.cpp | 80 +- src/shared-lib/CMakeLists.txt | 41 +- tests/benchmarks/logic/serialization.cpp | 4 +- tests/integration/CMakeLists.txt | 4 +- .../render-backend-tests/PlatformTest.cpp | 22 - .../integration/render-backend-tests/main.cpp | 4 - .../EmbeddedCompositingTestsFramework.cpp | 30 +- .../NamedPipe.h | 14 +- .../TestForkerApplication.cpp | 2 +- .../TestForkingController.cpp | 12 +- .../TestSignalHandler.cpp | 2 +- .../TestCases/SharedMemoryBufferTests.cpp | 12 +- .../TestCases/SingleStreamTextureTests.cpp | 6 +- .../TestCases/WaylandOutputTests.cpp | 50 +- .../TestWaylandApplication.cpp | 54 +- .../TestWaylandApplication/WaylandHandler.cpp | 36 +- .../ExternalWindowTests.cpp | 3 - .../RendererTestsFramework.cpp | 6 +- .../DynamicQuad_Resources.cpp | 10 +- .../DynamicQuad_SceneResources.cpp | 8 +- .../ResourceStressTests.cpp | 6 +- tests/integration/test-content/CMakeLists.txt | 2 +- .../test-content/CubeTextureScene.cpp | 57 +- .../test-content/FileLoadingScene.cpp | 4 +- .../test-content/MultiTypeLinkScene.cpp | 6 +- .../TestScenes/Texture2DFormatScene.h | 12 + ...tureCubeAnisotropicTextureFilteringScene.h | 2 +- ...ture2DAnisotropicTextureFilteringScene.cpp | 26 +- .../Texture2DCompressedMipMapScene.cpp | 10 +- .../test-content/Texture2DFormatScene.cpp | 192 +-- .../Texture2DGenerateMipMapScene.cpp | 34 +- .../test-content/Texture2DSamplingScene.cpp | 26 +- .../test-content/Texture3DScene.cpp | 52 +- .../test-content/TextureBufferScene.cpp | 73 +- ...reCubeAnisotropicTextureFilteringScene.cpp | 88 +- .../test-content/TextureLinkScene.cpp | 9 +- .../test-content/TextureSamplerScene.cpp | 24 +- .../CMakeLists.txt | 10 +- .../LogicViewerAppTest.cpp | 603 ++------ .../res/ALogicViewerApp_clearColor.png | Bin .../res/ALogicViewerApp_clearColorCmdLine.png | Bin .../res/ALogicViewerApp_red.png | Bin .../res/ALogicViewerApp_red_500x700.png | Bin .../res/ALogicViewerApp_white.png | Bin .../res/ALogicViewerApp_yellow.png | Bin tests/unittests/client/AppearanceTest.cpp | 26 +- tests/unittests/client/BlitPassTest.cpp | 46 + tests/unittests/client/CameraTest.cpp | 8 +- tests/unittests/client/CreationHelper.cpp | 16 +- tests/unittests/client/RamsesUtilsTest.cpp | 166 +- tests/unittests/client/RenderBufferTest.cpp | 29 + tests/unittests/client/RenderTargetTest.cpp | 68 + tests/unittests/client/ResourceTest.cpp | 376 ++--- .../client/ScenePersistationTest.cpp | 19 +- .../unittests/client/ScenePersistationTest.h | 5 +- .../client/ScenePersistationThreadedTest.cpp | 4 +- tests/unittests/client/SceneTest.cpp | 255 ++- .../unittests/client/Texture2DBufferTest.cpp | 42 +- .../client/logic/api/AnchorPointTest.cpp | 7 - .../client/logic/api/AnimationNodeTest.cpp | 8 +- .../AnimationNodeWithDataPropertiesTest.cpp | 4 +- .../logic/api/AppearanceBindingTest.cpp | 10 +- .../client/logic/api/CameraBindingTest.cpp | 19 +- .../client/logic/api/DataArrayTest.cpp | 4 +- .../api/LogicEngineTest_Compatibility.cpp | 8 +- .../logic/api/LogicEngineTest_Factory.cpp | 24 +- .../logic/api/LogicEngineTest_Linking.cpp | 69 +- .../api/LogicEngineTest_Serialization.cpp | 97 +- .../api/LogicEngineTest_SerializedSize.cpp | 11 +- .../logic/api/LogicEngineTest_Validation.cpp | 135 +- .../client/logic/api/LogicObjectTest.cpp | 5 +- .../client/logic/api/LuaConfigTest.cpp | 12 +- .../client/logic/api/LuaInterfaceTest.cpp | 12 +- .../client/logic/api/LuaModuleTest.cpp | 16 +- .../client/logic/api/LuaScriptTest_Debug.cpp | 12 +- .../client/logic/api/LuaScriptTest_Init.cpp | 4 +- .../logic/api/LuaScriptTest_Lifecycle.cpp | 14 +- .../logic/api/LuaScriptTest_Modules.cpp | 8 +- .../client/logic/api/MeshNodeBindingTest.cpp | 6 +- .../client/logic/api/NodeBindingTest.cpp | 22 +- .../client/logic/api/PropertyTest.cpp | 8 +- .../logic/api/RenderBufferBindingTest.cpp | 290 ++++ .../logic/api/RenderGroupBindingTest.cpp | 2 +- .../logic/api/RenderPassBindingTest.cpp | 6 +- .../client/logic/api/SaveFileConfigTest.cpp | 7 +- .../client/logic/api/TimerNodeTest.cpp | 4 +- .../client/logic/internal/ApiObjectsTest.cpp | 254 +-- .../LogicEngineTestWithCreationHelper.h | 8 +- .../logic/shared/LogicEngineTest_Base.h | 23 +- .../client/logic/shared/RamsesTestUtils.h | 4 + .../unittests/client/res/testScene_01.ramses | Bin 25459 -> 25603 bytes .../include/UnsafeTestMemoryHelpers.h | 5 + .../{test => }/BinaryFileInputStreamTest.cpp | 0 .../{test => }/BinaryFileOutputStreamTest.cpp | 0 .../{test => }/BinaryInputStreamTest.cpp | 0 .../BinaryOffsetFileInputStreamTest.cpp | 2 +- .../{test => }/BinaryOutputStreamTest.cpp | 0 .../Core/Utils/{test => }/EnumTraitsTest.cpp | 0 .../Core/Utils/{test => }/FileTest.cpp | 2 +- .../Core/Utils/{test => }/ImageTest.cpp | 4 +- .../{test => }/InplaceStringTokenizerTest.cpp | 0 .../Core/Utils/{test => }/LogHelperTest.cpp | 0 .../Core/Utils/{test => }/LogMacrosTest.cpp | 13 +- .../Utils/{test => }/LoggingUtilsTest.cpp | 0 .../{test => }/MemoryPoolExplicitTest.cpp | 0 .../{test => }/MemoryPoolIteratorTest.cpp | 0 .../Core/Utils/{test => }/MemoryPoolTest.cpp | 0 .../{test => }/PeriodicLoggerHelperTest.cpp | 0 .../{test => }/RawBinaryOutputStreamTest.cpp | 0 .../{test => }/StatisticCollectionTest.cpp | 0 .../Core/Utils/{test => }/StringUtilsTest.cpp | 0 .../Utils/{test => }/TextureMathUtilsTest.cpp | 0 .../Utils/{test => }/ThreadBarrierTest.cpp | 0 .../VectorBinaryOutputStreamTest.cpp | 0 .../Utils/{test => }/VoidOutputStreamTest.cpp | 0 .../Core/Utils/test/MessagePoolTest.cpp | 94 -- .../Core/Utils/test/ThreadLocalLogTest.cpp | 72 - .../DltLogAppender/DltAdapterTest.cpp | 16 +- .../PlatformThreadTest.cpp | 40 + tests/unittests/framework/Ramsh/RamshTest.cpp | 6 +- .../SceneGraph/Resource/ResourceTest.cpp | 8 +- .../SceneGraph/Scene/ActionTestScene.cpp | 6 + .../SceneGraph/Scene/ActionTestScene.h | 1 + .../ResourceChangeCollectingSceneTest.cpp | 15 + .../Scene/SceneTest_RenderBuffer.cpp | 15 + .../framework/SceneGraph/Scene/TestingScene.h | 3 +- .../ramses-framework/APILoggingHelperTest.cpp | 34 - .../ramses-framework/ErrorReportingTest.cpp | 4 +- .../ramses-framework/RamsesFrameworkTest.cpp | 119 +- .../EmbeddedCompositor_Wayland_Test.cpp | 4 - .../embedded-compositor-wayland/main.cpp | 4 - .../RendererSceneControlTest.cpp | 3 - .../RendererSceneControlWithRendererTest.cpp | 12 +- .../renderer/renderer-lib/CMakeLists.txt | 4 +- .../RendererLib/AsyncEffectUploaderTest.cpp | 5 +- .../DataReferenceLinkCachedSceneTest.cpp | 4 - .../DataReferenceLinkManagerTest.cpp | 4 - .../RendererLib/DisplayEventHandlerTest.cpp | 3 - .../EmbeddedCompositingManagerTest.cpp | 7 - .../RendererLib/LinkManagerBaseTest.cpp | 4 - .../PendingSceneResourcesUtilsTest.cpp | 34 +- .../renderer-lib/RendererLib/PlatformTest.cpp | 8 - .../RendererCommandExecutorTest.cpp | 18 +- .../RendererEventCollectorTest.cpp | 7 - .../RendererLib/RendererResourceManagerMock.h | 1 + .../RendererResourceManagerTest.cpp | 37 +- .../RendererResourceRegistryTest.cpp | 8 - .../RendererSceneControlLogicTest.cpp | 3 - .../RendererSceneResourceRegistryTest.cpp | 10 +- .../RendererLib/RendererSceneUpdaterMock.h | 2 +- .../RendererLib/RendererSceneUpdaterTest.h | 4 - .../RendererLib/RendererStatisticsTest.cpp | 4 +- .../renderer-lib/RendererLib/RendererTest.cpp | 4 - .../RendererLib/ResourceCachedSceneTest.cpp | 4 - .../RendererLib/ResourceUploaderTest.cpp | 6 - .../ResourceUploadingManagerTest.cpp | 7 +- .../SceneExpirationMonitorTest.cpp | 4 - .../RendererLib/SceneLinksManagerTest.cpp | 4 - .../RendererLib/SceneLinksTest.cpp | 3 - .../RendererLib/SceneReferenceLogicTest.cpp | 3 - ...ceneReferenceLogicWithSceneUpdaterTest.cpp | 3 - .../RendererLib/SceneStateExecutorTest.cpp | 3 - .../RendererLib/TextureLinkManagerTest.cpp | 4 - .../TransformationLinkCachedSceneTest.cpp | 3 - .../TransformationLinkManagerTest.cpp | 4 - .../renderer-test-common/CMakeLists.txt | 2 +- .../window-wayland-common/AWindowWayland.h | 2 - .../window-windows/Window_Window_Test.cpp | 13 - .../renderer/window-x11/Window_X11_Test.cpp | 7 - tests/unittests/tools/CMakeLists.txt | 2 +- .../CMakeLists.txt | 9 +- .../LogicViewerLuaTest.cpp | 100 +- .../LogicViewerTest.cpp | 0 .../LogicViewerTestBase.cpp | 0 .../LogicViewerTestBase.h | 2 + .../ramses-viewer/ValidationCacheTest.cpp | 134 ++ tools/CMakeLists.txt | 7 +- tools/ramses-daemon/main.cpp | 4 +- .../ramses-imgui/include/ImguiClientHelper.h | 1 + tools/ramses-imgui/src/ImguiClientHelper.cpp | 11 +- tools/ramses-imgui/src/ImguiImageCache.cpp | 4 +- tools/ramses-logic-viewer/Arguments.h | 109 -- tools/ramses-logic-viewer/CMakeLists.txt | 69 - .../ramses-logic-viewer/ImguiClientHelper.cpp | 542 ------- tools/ramses-logic-viewer/ImguiClientHelper.h | 145 -- tools/ramses-logic-viewer/LogicViewerApp.cpp | 132 -- tools/ramses-logic-viewer/LogicViewerApp.h | 99 -- tools/ramses-logic-viewer/LogicViewerGui.cpp | 1364 ----------------- tools/ramses-logic-viewer/LogicViewerGui.h | 110 -- .../ramses-logic-viewer/LogicViewerGuiApp.cpp | 225 --- tools/ramses-logic-viewer/LogicViewerGuiApp.h | 74 - .../LogicViewerHeadlessApp.cpp | 87 -- .../LogicViewerSettings.cpp | 144 -- .../ramses-logic-viewer/LogicViewerSettings.h | 41 - tools/ramses-logic-viewer/SceneSetup.h | 169 -- tools/ramses-scene-viewer/CMakeLists.txt | 17 - tools/ramses-scene-viewer/src/SceneViewer.cpp | 250 --- tools/ramses-scene-viewer/src/SceneViewer.h | 70 - tools/ramses-stream-viewer/src/main.cpp | 4 +- tools/ramses-viewer/CMakeLists.txt | 64 + .../ImguiWrapper.h | 0 tools/ramses-viewer/LogicEngineGui.cpp | 522 +++++++ tools/ramses-viewer/LogicEngineGui.h | 144 ++ .../LogicViewer.cpp | 34 +- .../LogicViewer.h | 9 +- tools/ramses-viewer/LogicViewerGui.cpp | 475 ++++++ tools/ramses-viewer/LogicViewerGui.h | 65 + .../LogicViewerLog.cpp | 7 +- .../LogicViewerLog.h | 18 +- .../LogicViewerLuaTypes.cpp | 4 +- .../LogicViewerLuaTypes.h | 3 + .../src => ramses-viewer}/ProgressMonitor.h | 0 .../src => ramses-viewer}/ResourceList.h | 0 .../Result.h | 2 +- .../src => ramses-viewer}/SceneSetup.h | 4 +- .../src => ramses-viewer}/SceneViewerGui.cpp | 379 +++-- .../src => ramses-viewer}/SceneViewerGui.h | 41 +- .../UpdateReportSummary.h | 2 +- tools/ramses-viewer/ValidationCache.h | 95 ++ tools/ramses-viewer/ViewerApp.cpp | 202 +++ tools/ramses-viewer/ViewerApp.h | 177 +++ tools/ramses-viewer/ViewerGui.cpp | 273 ++++ tools/ramses-viewer/ViewerGui.h | 71 + tools/ramses-viewer/ViewerGuiApp.cpp | 212 +++ tools/ramses-viewer/ViewerGuiApp.h | 73 + tools/ramses-viewer/ViewerHeadlessApp.cpp | 42 + .../ViewerHeadlessApp.h} | 19 +- tools/ramses-viewer/ViewerSettings.cpp | 97 ++ tools/ramses-viewer/ViewerSettings.h | 46 + .../src => ramses-viewer}/main.cpp | 6 +- .../main_headless.cpp | 12 +- tools/test-asset-producer/CMakeLists.txt | 2 +- tools/test-asset-producer/main.cpp | 20 +- 536 files changed, 8569 insertions(+), 9079 deletions(-) create mode 100644 include/ramses/client/logic/RenderBufferBinding.h create mode 100644 src/client/impl/logic/RenderBufferBinding.cpp create mode 100644 src/client/impl/logic/RenderBufferBindingImpl.cpp create mode 100644 src/client/impl/logic/RenderBufferBindingImpl.h create mode 100644 src/client/internal/CMakeLists.txt create mode 100644 src/client/internal/logic/flatbuffers/generated/RenderBufferBindingGen.h rename tools/ramses-logic-viewer/main.cpp => src/client/internal/logic/flatbuffers/schemas/RenderBufferBinding.fbs (73%) delete mode 100644 src/framework/impl/APILoggingHelper.h create mode 100644 src/framework/internal/CMakeLists.txt delete mode 100644 src/framework/internal/Core/Utils/ThreadLocalLog.cpp delete mode 100644 src/framework/internal/Core/Utils/ThreadLocalLog.h delete mode 100644 src/framework/internal/Core/Utils/ThreadLocalLogForced.h rename tests/integration/{logic-viewer-tests => viewer-tests}/CMakeLists.txt (81%) rename tests/integration/{logic-viewer-tests => viewer-tests}/LogicViewerAppTest.cpp (59%) rename tests/integration/{logic-viewer-tests => viewer-tests}/res/ALogicViewerApp_clearColor.png (100%) rename tests/integration/{logic-viewer-tests => viewer-tests}/res/ALogicViewerApp_clearColorCmdLine.png (100%) rename tests/integration/{logic-viewer-tests => viewer-tests}/res/ALogicViewerApp_red.png (100%) rename tests/integration/{logic-viewer-tests => viewer-tests}/res/ALogicViewerApp_red_500x700.png (100%) rename tests/integration/{logic-viewer-tests => viewer-tests}/res/ALogicViewerApp_white.png (100%) rename tests/integration/{logic-viewer-tests => viewer-tests}/res/ALogicViewerApp_yellow.png (100%) create mode 100644 tests/unittests/client/logic/api/RenderBufferBindingTest.cpp rename tests/unittests/framework/Core/Utils/{test => }/BinaryFileInputStreamTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/BinaryFileOutputStreamTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/BinaryInputStreamTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/BinaryOffsetFileInputStreamTest.cpp (98%) rename tests/unittests/framework/Core/Utils/{test => }/BinaryOutputStreamTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/EnumTraitsTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/FileTest.cpp (99%) rename tests/unittests/framework/Core/Utils/{test => }/ImageTest.cpp (99%) rename tests/unittests/framework/Core/Utils/{test => }/InplaceStringTokenizerTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/LogHelperTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/LogMacrosTest.cpp (78%) rename tests/unittests/framework/Core/Utils/{test => }/LoggingUtilsTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/MemoryPoolExplicitTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/MemoryPoolIteratorTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/MemoryPoolTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/PeriodicLoggerHelperTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/RawBinaryOutputStreamTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/StatisticCollectionTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/StringUtilsTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/TextureMathUtilsTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/ThreadBarrierTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/VectorBinaryOutputStreamTest.cpp (100%) rename tests/unittests/framework/Core/Utils/{test => }/VoidOutputStreamTest.cpp (100%) delete mode 100644 tests/unittests/framework/Core/Utils/test/MessagePoolTest.cpp delete mode 100644 tests/unittests/framework/Core/Utils/test/ThreadLocalLogTest.cpp delete mode 100644 tests/unittests/framework/ramses-framework/APILoggingHelperTest.cpp rename tests/unittests/tools/{ramses-logic-viewer => ramses-viewer}/CMakeLists.txt (80%) rename tests/unittests/tools/{ramses-logic-viewer => ramses-viewer}/LogicViewerLuaTest.cpp (92%) rename tests/unittests/tools/{ramses-logic-viewer => ramses-viewer}/LogicViewerTest.cpp (100%) rename tests/unittests/tools/{ramses-logic-viewer => ramses-viewer}/LogicViewerTestBase.cpp (100%) rename tests/unittests/tools/{ramses-logic-viewer => ramses-viewer}/LogicViewerTestBase.h (96%) create mode 100644 tests/unittests/tools/ramses-viewer/ValidationCacheTest.cpp delete mode 100644 tools/ramses-logic-viewer/Arguments.h delete mode 100644 tools/ramses-logic-viewer/CMakeLists.txt delete mode 100644 tools/ramses-logic-viewer/ImguiClientHelper.cpp delete mode 100644 tools/ramses-logic-viewer/ImguiClientHelper.h delete mode 100644 tools/ramses-logic-viewer/LogicViewerApp.cpp delete mode 100644 tools/ramses-logic-viewer/LogicViewerApp.h delete mode 100644 tools/ramses-logic-viewer/LogicViewerGui.cpp delete mode 100644 tools/ramses-logic-viewer/LogicViewerGui.h delete mode 100644 tools/ramses-logic-viewer/LogicViewerGuiApp.cpp delete mode 100644 tools/ramses-logic-viewer/LogicViewerGuiApp.h delete mode 100644 tools/ramses-logic-viewer/LogicViewerHeadlessApp.cpp delete mode 100644 tools/ramses-logic-viewer/LogicViewerSettings.cpp delete mode 100644 tools/ramses-logic-viewer/LogicViewerSettings.h delete mode 100644 tools/ramses-logic-viewer/SceneSetup.h delete mode 100644 tools/ramses-scene-viewer/CMakeLists.txt delete mode 100644 tools/ramses-scene-viewer/src/SceneViewer.cpp delete mode 100644 tools/ramses-scene-viewer/src/SceneViewer.h create mode 100644 tools/ramses-viewer/CMakeLists.txt rename tools/{ramses-logic-viewer => ramses-viewer}/ImguiWrapper.h (100%) create mode 100644 tools/ramses-viewer/LogicEngineGui.cpp create mode 100644 tools/ramses-viewer/LogicEngineGui.h rename tools/{ramses-logic-viewer => ramses-viewer}/LogicViewer.cpp (89%) rename tools/{ramses-logic-viewer => ramses-viewer}/LogicViewer.h (97%) create mode 100644 tools/ramses-viewer/LogicViewerGui.cpp create mode 100644 tools/ramses-viewer/LogicViewerGui.h rename tools/{ramses-logic-viewer => ramses-viewer}/LogicViewerLog.cpp (96%) rename tools/{ramses-logic-viewer => ramses-viewer}/LogicViewerLog.h (71%) rename tools/{ramses-logic-viewer => ramses-viewer}/LogicViewerLuaTypes.cpp (98%) rename tools/{ramses-logic-viewer => ramses-viewer}/LogicViewerLuaTypes.h (98%) rename tools/{ramses-scene-viewer/src => ramses-viewer}/ProgressMonitor.h (100%) rename tools/{ramses-scene-viewer/src => ramses-viewer}/ResourceList.h (100%) rename tools/{ramses-logic-viewer => ramses-viewer}/Result.h (98%) rename tools/{ramses-scene-viewer/src => ramses-viewer}/SceneSetup.h (97%) rename tools/{ramses-scene-viewer/src => ramses-viewer}/SceneViewerGui.cpp (91%) rename tools/{ramses-scene-viewer/src => ramses-viewer}/SceneViewerGui.h (88%) rename tools/{ramses-logic-viewer => ramses-viewer}/UpdateReportSummary.h (99%) create mode 100644 tools/ramses-viewer/ValidationCache.h create mode 100644 tools/ramses-viewer/ViewerApp.cpp create mode 100644 tools/ramses-viewer/ViewerApp.h create mode 100644 tools/ramses-viewer/ViewerGui.cpp create mode 100644 tools/ramses-viewer/ViewerGui.h create mode 100644 tools/ramses-viewer/ViewerGuiApp.cpp create mode 100644 tools/ramses-viewer/ViewerGuiApp.h create mode 100644 tools/ramses-viewer/ViewerHeadlessApp.cpp rename tools/{ramses-logic-viewer/LogicViewerHeadlessApp.h => ramses-viewer/ViewerHeadlessApp.h} (56%) create mode 100644 tools/ramses-viewer/ViewerSettings.cpp create mode 100644 tools/ramses-viewer/ViewerSettings.h rename tools/{ramses-scene-viewer/src => ramses-viewer}/main.cpp (83%) rename tools/{ramses-logic-viewer => ramses-viewer}/main_headless.cpp (63%) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8a093add9..3193c3c70 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,27 @@ # Ramses Changelog +28.0.0-rc3 +------------------- +### Added +- added `ramses-viewer` tool. It replaces `ramses-scene-viewer` and `ramses-logic-viewer` +- added `RenderBufferBinding` which can be used in logic to modify `RenderBuffer` properties before it is allocated on renderer +- added `RamsesFrameworkConfig::setLoggingInstanceName` to set a global instance name used as prefix in all Ramses logs + +### Changed +- Headless shared lib always gets built +- removed automatic validation when saving scene to a file (also removed the parameter from SaveFileConfig) +- Modernized `MipLevelData` and `CubeMipLevelData`. Data are no longer stored with raw pointers + - Updated `RamsesUtils::GenerateMipMapsTexture2D` and `RamsesUtils::GenerateMipMapsTextureCube` to return a pointer of vector of the respective mip level data + - Updated `RamsesUtils::DeleteGeneratedMipMaps` for deleting the vector pointers +- `Texture2DBuffer::updateData` now takes std::bytes +- `Scene::saveToFile` implicitly updates all logic engine instances and flushes the scene before saving, the method is therefore no longer const + +### Removed +- removed `ramses-scene-viewer` - use `ramses-viewer` instead +- removed `ramses-logic-viewer` - use `ramses-viewer` instead +- removed `ramses-logic-viewer-headless` - use `ramses-viewer-headless` instead +- removed cmake option `ramses-sdk_BUILD_HEADLESS_SHARED_LIB` for enabling headless shared lib since it always gets built now + 28.0.0-rc2 ------------------- ### Added @@ -10,7 +32,7 @@ - Added native support for bool uniforms, no need to use int32_t anymore to set them - existing application code using `Appearance::setInputValue` with `int32_t` type to set boolean shader uniforms must change to use `bool` type now! - Supported bool for the data container `ramses::DataObject` -- Added `RamsesFramework::getFeatureLevel()` to easily guery EFeatureLevel +- Added `RamsesFramework::getFeatureLevel()` to easily query EFeatureLevel - Added `RamsesClient::getRamsesFramework()` to be able to get reference to `RamsesFramework` from `RamsesClient` - this can be used for example to get feature level just by having a `Scene` instance: myScene.getRamsesClient().getRamsesFramework().getFeatureLevel() - Added `SceneObject::getScene()` to get reference to owning `Scene` from any object created from that Scene @@ -22,27 +44,27 @@ ### Changed -- Modernized mipLevelData from C-style array to vector for Scene::createTexture2D(), Scene::createTexture3D() and Scene::createTextureCube() +- Modernized mipLevelData from C-style array to vector for `Scene::createTexture2D()`, `Scene::createTexture3D()` and `Scene::createTextureCube()` - Scene::findObject now also searches for logic objects in all existing logic engines - Switched from fmt 7.0.1 to 10.1.1 - Switched from google-benchmark 1.5.2 to 1.8.3 - Switched from google-flatbuffers 1.12.0 to 23.5.9 - LogicEngine is now part of Scene and can only be created using Scene::createLogicEngine - - LogicEngine is now a SceneObject of type ERamsesObjectType::LogicEngine and its lifecycle is managed by Scene as for any other SceneObject. LogicEngine is no longer a movable type. - - removed scene argument from all loading functions in LogicEngine: loadFromFile, loadFromFileDescriptor, loadFromBuffer + - LogicEngine is now a SceneObject of type ERamsesObjectType::LogicEngine and its lifecycle is managed by Scene as for any other SceneObject. LogicEngine is no longer a move-able type. + - removed the ramses::Scene argument from all loading functions in LogicEngine: loadFromFile, loadFromFileDescriptor, loadFromBuffer (is now implicit) - LogicObject now derives from SceneObject and therefore RamsesObject - - LogicObject::getId is renamed to LogicObject::getLogicObjectId - - LogicObject::setName/getName are removed, methods with same name and functionality (but different return type!) are in base class RamsesObject - - LogicObject::set/getUserId moved to its base RamsesObject so any RamsesObject can use it now + - `LogicObject::getId` is renamed to `LogicObject::getLogicObjectId` + - `LogicObject::setName/getName` are removed, methods with same name and functionality (but different return type!) are in base class RamsesObject + - `LogicObject::set/getUserId` moved to its base RamsesObject so any RamsesObject can use it now - RamsesObject.h and RamsesObjectTypes.h moved from `client` include folder to `framework`, update include paths accordingly -- RamsesObject::getName returns std::string_view instead of const char* +- `RamsesObject::getName` returns `std::string_view` instead of `const char*` - Reworked API error handling for all public Ramses classes: - removed `status_t`, `StatusOK`, `StatusObject::getStatusMessage`, `LogicEngine::getErrors`, `ErrorData` and the whole `StatusObject` class - all API methods that can fail (at API call time) return `bool` (true for success) - errors are now collected centrally in `RamsesFramework` - `RamsesFramework::getLastError` can be used to get the last error that occurred (as optional), calling it will clear the error - configs and other not managed objects (`RamsesFrameworkConfig`, `RendererConfig`, `DisplayConfig`,`SceneConfig`, `RenderTargetDescription`, `EffectDescription`, `EffectInput`) - no longer inherit from StatusObject. Their methods also return `bool` but error messages are only logged (not tracked with `getLastError`). + no longer inherit from `StatusObject`. Their methods also return `bool` but error messages are only logged (not tracked with `getLastError`). - `RenderTargetDescription::addRenderBuffer` has optional argument to get human readable description of error if failed - Export whole API classes in shared libs, instead of exporting only public functions - Changed default publishing mode of scenes from EScenePublicationMode::LocalAndRemote to EScenePublicationMode::LocalOnly @@ -66,13 +88,13 @@ - Removed `EffectInput::isValid` because `UniformInput` and `AttributeInput` objects are always valid now - Changed `EffectInput::getDataType` to return `EDataType` instead of `optional` - DisplayConfig::validate produces warnings or errors if suboptimal or wrong settings are set, e.g., incompatible window and device types are set -- Remove the 4096 upper limit of offscreen buffer size in RamsesRenderer. The buffer size is limited by the driver. +- Remove the 4096 upper limit of offscreen buffer size in RamsesRenderer. The buffer size is limited by the OpenGL driver. - Changed LogHandlerFunc to use `std::string_view` instead of `const std::string&` - ramses-logic logs are output to DLT (context 'RCLI') - Changed clear flags parameters from `uint32_t` to `ramses::ClearFlags` (`ramses::Flags`) - Remove cmake option `ramses-sdk_BUILD_IVI_TEST_APPS` - ivi-gears and ivi-simple-dmabuf-egl are now controlled with option for building tools -- Remove check for cmake variable `ramses-sdk_DISABLE_WAYLAND_IVI_EXTENSION`. The extensions get built if the required +- Remove check for cmake variable `ramses-sdk_DISABLE_WAYLAND_IVI_EXTENSION`. The extensions are built if the required dependencies are available - Changed key modifier flags parameters from `uint32_t`to `ramses::KeyModifiers` (`ramses::Flags`) - Moved `ramses-client-api/TextureEnums.h` to `ramses/framework/TextureEnums.h` diff --git a/CMakeLists.txt b/CMakeLists.txt index 2635a7653..6ee997eee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -11,7 +11,7 @@ CMAKE_MINIMUM_REQUIRED(VERSION 3.13) set(RAMSES_VERSION_MAJOR 28) set(RAMSES_VERSION_MINOR 0) set(RAMSES_VERSION_PATCH 0) -set(RAMSES_VERSION_POSTFIX "-rc2") +set(RAMSES_VERSION_POSTFIX "-rc3") set(RAMSES_VERSION "${RAMSES_VERSION_MAJOR}.${RAMSES_VERSION_MINOR}.${RAMSES_VERSION_PATCH}${RAMSES_VERSION_POSTFIX}") project(ramses-sdk @@ -45,8 +45,7 @@ option(ramses-sdk_ENABLE_WINDOW_TYPE_WAYLAND_IVI "Enable building for Way option(ramses-sdk_ENABLE_WINDOW_TYPE_WAYLAND_WL_SHELL "Enable building for Wayland wl_shell window" OFF) # shared lib options -option(ramses-sdk_BUILD_FULL_SHARED_LIB "Build per-renderer shared libraries." ON) -option(ramses-sdk_BUILD_HEADLESS_SHARED_LIB "Enable building headless shared library without renderer" OFF) +option(ramses-sdk_BUILD_FULL_SHARED_LIB "Build full shared libraries (with renderer)." ON) # optional components option(ramses-sdk_ENABLE_LOGIC "Enable ramses logic - a component for scripting and animation." ON) @@ -172,23 +171,13 @@ if(NOT ANY_WINDOW_TYPE_ENABLED) elseif(CMAKE_SYSTEM_NAME STREQUAL "iOS") setDefaultWindowType(ramses-sdk_ENABLE_WINDOW_TYPE_IOS "iOS") else() - message(WARNING "Incorrect configuration. No default window type is known for the build operating system '${CMAKE_SYSTEM_NAME}':\n" + message(WARNING "No default window type is known for the build operating system '${CMAKE_SYSTEM_NAME}':\n" "* Either disable default window type by setting ramses-sdk_ENABLE_DEFAULT_WINDOW_TYPE=OFF\n" - "* or enable a window type explicitly by setting any of the options ramses-sdk_ENABLE_WINDOW_TYPE_* to ON\n" - "For current configuration ramses-sdk_BUILD_HEADLESS_SHARED_LIB will be overridden to ON, and headless shared lib will be built.") - - # Override cmake option (with normal/non-cached cmake variable) - set(ramses-sdk_BUILD_HEADLESS_SHARED_LIB ON) + "* or enable a window type explicitly by setting any of the options ramses-sdk_ENABLE_WINDOW_TYPE_* to ON") endif() endif() endif() -if(NOT ANY_WINDOW_TYPE_ENABLED AND NOT ramses-sdk_BUILD_HEADLESS_SHARED_LIB) - message(FATAL_ERROR "Invalid configuration. Neither any window type, nor headless shared lib enabled:\n" - "* Either enable at least one window type by setting any of the options ramses-sdk_ENABLE_WINDOW_TYPE_* to ON\n" - "* or enable building headless shared lib (without renderer) by setting ramses-sdk_BUILD_HEADLESS_SHARED_LIB=ON") -endif() - if(NOT ANY_WINDOW_TYPE_ENABLED AND ramses-sdk_BUILD_FULL_SHARED_LIB) message(WARNING "Incorrect configuration. Trying to build full shared lib with renderer while no window type is enabled:\n" "* If trying to build renderer enable at least one window type by setting any of the options ramses-sdk_ENABLE_WINDOW_TYPE_* to ON\n" @@ -253,11 +242,10 @@ if(ramses-sdk_BUILD_TOOLS) add_subdirectory(tools) endif() -if(ramses-sdk_BUILD_FULL_SHARED_LIB OR ramses-sdk_BUILD_HEADLESS_SHARED_LIB) - if(ramses-sdk_BUILD_EXAMPLES) - add_subdirectory(examples) - endif() +if(ramses-sdk_BUILD_EXAMPLES) + add_subdirectory(examples) endif() + if(ramses-sdk_BUILD_FULL_SHARED_LIB) if(ramses-sdk_BUILD_DEMOS) add_subdirectory(demo) @@ -283,10 +271,7 @@ if(ramses-sdk_ENABLE_INSTALL) include(CMakePackageConfigHelpers) - set(configmodules) # initially empty - if (ramses-sdk_BUILD_HEADLESS_SHARED_LIB) - list(APPEND configmodules ramses-shared-lib-headless) - endif() + list(APPEND configmodules ramses-shared-lib-headless) if (ramses-sdk_BUILD_FULL_SHARED_LIB) list(APPEND configmodules ramses-shared-lib) endif() diff --git a/README.md b/README.md index 588b5b7ae..f84cc366e 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # Table of Contents -* [What is RAMSES](#what-is-ramses) -* [Obtaining the source code](#obtaining-the-source-code) -* [Building and testing](#building-and-testing) -* [License](#license) +* +* +* +* # What is RAMSES @@ -46,7 +46,7 @@ Building RAMSES on Linux with docker: We prefer to build RAMSES in Docker because it abstracts the dependency installation and the CMake invocations away from the user. Docker is installed slightly differently on different distros, check the docker manual for your distro. The instructions below -are for Ubuntu 18.04 LTS: +are for Ubuntu 20.04 LTS: ``` apt install docker.io diff --git a/cmake/ramses/createTarget.cmake b/cmake/ramses/createTarget.cmake index 81a4e63d8..bcaecf783 100644 --- a/cmake/ramses/createTarget.cmake +++ b/cmake/ramses/createTarget.cmake @@ -147,6 +147,7 @@ function(createModule) set(LINK_VISIBILITY PUBLIC) elseif("${MODULE_TYPE}" STREQUAL "OBJECT") add_library(${MODULE_NAME} OBJECT ${GLOBBED_MODULE_SRC_FILES}) + set(LINK_VISIBILITY PUBLIC) elseif("${MODULE_TYPE}" STREQUAL "SHARED_LIBRARY") add_library(${MODULE_NAME} SHARED ${GLOBBED_MODULE_SRC_FILES}) @@ -209,7 +210,7 @@ function(createModuleWithRenderer) message(FATAL_ERROR "Unparsed createModuleWithRenderer properties: '${MODULE_UNPARSED_ARGUMENTS}'") endif() - set(MODULE_DEPENDENCIES "ramses-renderer;ramses-build-options-base;${MODULE_DEPENDENCIES}") + set(MODULE_DEPENDENCIES "ramses-renderer;ramses-client;ramses-build-options-base;${MODULE_DEPENDENCIES}") createModule(NAME ${MODULE_NAME} TYPE ${MODULE_TYPE} diff --git a/cmake/templates/ramses-shared-libTemplate.cmake.in b/cmake/templates/ramses-shared-libTemplate.cmake.in index f663523ef..44c1bd6b6 100644 --- a/cmake/templates/ramses-shared-libTemplate.cmake.in +++ b/cmake/templates/ramses-shared-libTemplate.cmake.in @@ -26,22 +26,11 @@ endif() set(ramses-shared-lib_INCLUDE_DIRS "@PACKAGE_RAMSES_INSTALL_HEADERS_PATH@") -if(IS_DIRECTORY "${ramses-shared-lib_INCLUDE_DIRS}/glm") - add_library(glm::glm INTERFACE IMPORTED) - set_target_properties(glm::glm PROPERTIES INTERFACE_INCLUDE_DIRECTORIES ${ramses-shared-lib_INCLUDE_DIRS}) -else() - find_dependency(glm REQUIRED) - - if(NOT TARGET glm::glm) - add_library(glm::glm ALIAS glm) - endif() -endif() - # find library IF(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") # no shlib versioning support on windows - FIND_LIBRARY(ramses-shared-lib_LIBRARIES + FIND_LIBRARY(ramses-shared-lib_FULL_LIBRARIES NAMES "ramses-shared-lib" HINTS @PACKAGE_RAMSES_INSTALL_RUNTIME_PATH@ ) @@ -49,7 +38,7 @@ IF(${CMAKE_SYSTEM_NAME} STREQUAL "Windows") ELSEIF(${CMAKE_SYSTEM_NAME} STREQUAL "Linux") # require exact shlib version - FIND_LIBRARY(ramses-shared-lib_LIBRARIES + FIND_LIBRARY(ramses-shared-lib_FULL_LIBRARIES NAMES "libramses-shared-lib.so.@RAMSES_VERSION_MAJOR@.@RAMSES_VERSION_MINOR@" HINTS @PACKAGE_RAMSES_INSTALL_LIBRARY_PATH@ ) @@ -57,7 +46,7 @@ ELSEIF(${CMAKE_SYSTEM_NAME} STREQUAL "Linux") ELSEIF(${CMAKE_SYSTEM_NAME} STREQUAL "Android") # no shlib versioning support on Android - FIND_LIBRARY(ramses-shared-lib_LIBRARIES + FIND_LIBRARY(ramses-shared-lib_FULL_LIBRARIES NAMES "libramses-shared-lib" HINTS @PACKAGE_RAMSES_INSTALL_LIBRARY_PATH@ CMAKE_FIND_ROOT_PATH_BOTH @@ -68,16 +57,22 @@ ELSE() ENDIF() +# find headless to add as dependency +find_package(ramses-shared-lib-headless REQUIRED) + FIND_PACKAGE_HANDLE_STANDARD_ARGS(ramses-shared-lib FOUND_VAR ramses-shared-lib_FOUND - REQUIRED_VARS ramses-shared-lib_LIBRARIES ramses-shared-lib_INCLUDE_DIRS + REQUIRED_VARS ramses-shared-lib_FULL_LIBRARIES ramses-shared-lib-headless_LIBRARIES ramses-shared-lib_INCLUDE_DIRS VERSION_VAR ramses-shared-lib_VERSION) set(ramses-sdk_VERSION "@ramses-sdk_VERSION@" CACHE STRING "Ramses version" FORCE) +set(ramses-shared-lib_LIBRARIES ${ramses-shared-lib-headless_LIBRARIES} ${ramses-shared-lib_FULL_LIBRARIES}) + message(STATUS "Found ramses-shared-lib libs: ${ramses-shared-lib_LIBRARIES}") message(STATUS "Found ramses-shared-lib includes: ${ramses-shared-lib_INCLUDE_DIRS}") + MARK_AS_ADVANCED( ramses-shared-lib_INCLUDE_DIRS ramses-shared-lib_LIBRARIES @@ -87,12 +82,13 @@ MARK_AS_ADVANCED( if (${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.13") if (NOT TARGET ramses-ramses-shared-lib) add_library(ramses-ramses-shared-lib SHARED IMPORTED GLOBAL) - set_target_properties(ramses-ramses-shared-lib PROPERTIES IMPORTED_LOCATION ${ramses-shared-lib_LIBRARIES}) + set_target_properties(ramses-ramses-shared-lib PROPERTIES IMPORTED_LOCATION ${ramses-shared-lib_FULL_LIBRARIES}) + if (MSVC) - set_target_properties(ramses-ramses-shared-lib PROPERTIES IMPORTED_IMPLIB ${ramses-shared-lib_LIBRARIES}) + set_target_properties(ramses-ramses-shared-lib PROPERTIES IMPORTED_IMPLIB ${ramses-shared-lib_FULL_LIBRARIES}) endif() target_include_directories(ramses-ramses-shared-lib INTERFACE ${ramses-shared-lib_INCLUDE_DIRS}) - target_link_libraries(ramses-ramses-shared-lib INTERFACE glm::glm) + target_link_libraries(ramses-ramses-shared-lib INTERFACE ramses::headless) if (NOT TARGET ramses::ramses) add_library(ramses::ramses ALIAS ramses-ramses-shared-lib) diff --git a/doc/sphinx/build.rst b/doc/sphinx/build.rst index cc9e2693b..eae96ff12 100644 --- a/doc/sphinx/build.rst +++ b/doc/sphinx/build.rst @@ -89,11 +89,6 @@ modify some of the build settings: * default: ON * Builds a version of the ramses shared library **with** renderer support. At least one window type must be enabled for build. -* -Dramses-sdk_BUILD_HEADLESS_SHARED_LIB - * options: ON/OFF - * default: OFF - * Builds a version of the ramses shared library **without** renderer support. - ``Ramses`` needs (at least) one platform-specific window type to support rendering. Several window types can be included into one build (e.g. X11 and Wayland). By default one suitable window type will be auto-detected. Build will fail if dependencies for an enabled window type are not found. diff --git a/doc/sphinx/conf.py b/doc/sphinx/conf.py index 49bc84550..89eb2b8ea 100644 --- a/doc/sphinx/conf.py +++ b/doc/sphinx/conf.py @@ -56,6 +56,9 @@ # Breathe options breathe_default_project = "ramses" +# Myst options +myst_heading_anchors = 1 + # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] diff --git a/doc/sphinx/logic.rst b/doc/sphinx/logic.rst index 02ff2e966..fecda4092 100644 --- a/doc/sphinx/logic.rst +++ b/doc/sphinx/logic.rst @@ -492,7 +492,7 @@ how many nodes were needed to be updated and if the topology could be improved s to only the necessary nodes. .. note:: - An easy way to quickly get insight what happens inside a logic network is to use the :ref:`GUI viewer `. + An easy way to quickly get insight what happens inside a logic network is to use the :ref:`GUI viewer `. The viewer displays the stats reported by the :class:`ramses::LogicEngineReport` dynamically or statically over multiple update cycles. diff --git a/doc/sphinx/viewer.rst b/doc/sphinx/viewer.rst index 17e270de9..78933860f 100644 --- a/doc/sphinx/viewer.rst +++ b/doc/sphinx/viewer.rst @@ -11,20 +11,20 @@ .. highlight:: lua ========================= -ramses-logic-viewer +ramses-viewer ========================= -------- Synopsis -------- -**ramses-logic-viewer** [options] [] +**ramses-viewer** [options] [] ----------- Description ----------- -:program:`ramses-logic-viewer` is a tool which can load, configure and display +:program:`ramses-viewer` is a tool which can load, configure and display Ramses (````) binary files alongside with a custom configuration (````). It also provides a GUI to inspect the displayed scene. @@ -32,10 +32,10 @@ It also provides a GUI to inspect the displayed scene. * ```` is an optional configuration file written in lua to modify the scene view (see :ref:`lua_configuration_api` for details) * ```` is found in the same path as ```` if not provided as an argument. - For auto-detection the file extensions `rlogic` and `lua` are expected. + For auto-detection the file extension `lua` is expected. * If no ```` is found, the viewer will show the scene and propose to store a default configuration. * Display size is auto-detected based on the first camera viewport found in the scene. - This can be overridden by the options :option:`ramses-logic-viewer --width` and :option:`ramses-logic-viewer --height`. + This can be overridden by the options :option:`ramses-viewer --width` and :option:`ramses-viewer --height`. The tool's intended use-cases are primarily: @@ -48,12 +48,15 @@ The tool's intended use-cases are primarily: Options ------- -.. program:: ramses-logic-viewer +.. program:: ramses-viewer -.. option:: --no-offscreen +.. option:: --gui on|off|overlay|only - Renders the scene directly to the window's framebuffer. Screenshot size will be the current window size. - If switched off (default), the scene is rendered to an offscreen buffer with the initial scene size. + Sets the Viewer's gui mode: + ``overlay`` (default) renders the scene directly to the window's framebuffer. Screenshot size will be the current window size. + ``on`` renders the scene to an offscreen buffer with the initial scene size. Screenshots only capture the scene's offscreen buffer. + ``off`` hides the viewer's gui. + ``only`` hides the loaded scene. Only the viewer's gui is shown. .. option:: --exec= @@ -68,7 +71,7 @@ Options .. option:: --headless Runs the viewer without user interface and renderer. This can be useful for CI environments to run tests - (:option:`ramses-logic-viewer --exec` :option:`ramses-logic-viewer --exec-lua`). + (:option:`ramses-viewer --exec` :option:`ramses-viewer --exec-lua`). Screenshots will not work in this mode though. .. option:: --width WIDTH @@ -83,9 +86,9 @@ Options Instructs the renderer to apply multisampling (Valid values: 1, 2, 4, 8) -.. option:: --clear-color R G B A +.. option:: --clear R,G,B,A - Sets the display clear color to other than the default black (e.g.: :code:`ramses-logic-viewer --clear-color 0 0.5 0.8 1`) + Sets the display clear color to other than the default black (e.g.: :code:`ramses-viewer --clear 0,0.5,0.8,1`) .. option:: --write-config [filename] @@ -102,7 +105,7 @@ Options Lua configuration API ============================================== -The :program:`ramses-logic-viewer` exposes a lua module ``rlogic`` that allows to interact with the viewer's +The :program:`ramses-viewer` exposes a lua module ``rlogic`` that allows to interact with the viewer's logic engine instance. ``rlogic`` mimics the Ramses Logic C++ API and provides some extra interfaces to take screenshots and define interactive views. @@ -192,7 +195,7 @@ A view is a lua table that contains the following members: A string attribute that contains the view's name ``update(time_ms)`` - A function that is called for every frame by the :program:`ramses-logic-viewer`. + A function that is called for every frame by the :program:`ramses-viewer`. The ``time_ms`` parameter is a monotonic time value in milliseconds. ``description`` @@ -239,7 +242,7 @@ Screenshots -------------------------------------------------- Screenshots can be taken by the ``rlogic.screenshot(filename)`` function. -The :program:`ramses-logic-viewer` will implicitly update the logic state before. +The :program:`ramses-viewer` will implicitly update the logic state before. .. code-block:: lua @@ -250,8 +253,9 @@ The :program:`ramses-logic-viewer` will implicitly update the logic state before .. note:: - By default the Logic Viewer creates an offscreen buffer for the scene. - That's why the screenshot's size is independent of the window size and does not contain the Logic Viewer's UI. + To exclude the Viewer's UI from the screenshot you can set the :option:`ramses-viewer --gui` to either `on` or `off`. + In `on` mode the Viewer creates an offscreen buffer for the scene. + That's why the screenshot's size is independent of the window size and does not contain the Viewer's UI. -------------------------------------------------- Logic Engine Update @@ -259,7 +263,7 @@ Logic Engine Update The logic engine is automatically updated (:cpp:func:`ramses::LogicEngine::update()`) before a new frame is drawn or before a screenshot is stored. -In batch mode (:option:`ramses-logic-viewer --exec` :option:`ramses-logic-viewer --exec-lua`) it's sometimes useful to explicitly update +In batch mode (:option:`ramses-viewer --exec` :option:`ramses-viewer --exec-lua`) it's sometimes useful to explicitly update the logic engine state by calling ``rlogic.update()``: .. code-block:: lua diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index fea7ec5ea..7c68b22c8 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -6,12 +6,6 @@ # file, You can obtain one at https://mozilla.org/MPL/2.0/. # ------------------------------------------------------------------------- -if(ramses-sdk_BUILD_FULL_SHARED_LIB) - add_library(ramses::shared-lib-for-examples ALIAS ramses-shared-lib) -else() - add_library(ramses::shared-lib-for-examples ALIAS ramses-shared-lib-headless) -endif() - add_subdirectory(ramses-example-minimal) add_subdirectory(ramses-example-basic-blending) add_subdirectory(ramses-example-basic-effect-from-glsl) diff --git a/examples/logic/05_serialization/main.cpp b/examples/logic/05_serialization/main.cpp index 94548e7da..6b31abd7d 100644 --- a/examples/logic/05_serialization/main.cpp +++ b/examples/logic/05_serialization/main.cpp @@ -202,11 +202,6 @@ void CreateAndSaveContent(const std::string &ramsesSceneFile) /** * Save the ramses scene (includes the script, the node binding and the link) - * - * Note: in this example validation on saving is disabled for simplification, since normally a warning - * gets generated for script input that is not linked. */ - ramses::SaveFileConfig saveFileConfig; - saveFileConfig.setValidationEnabled(false); - [[maybe_unused]] auto status = scene->saveToFile(ramsesSceneFile.c_str(), saveFileConfig); + [[maybe_unused]] auto status = scene->saveToFile(ramsesSceneFile.c_str(), {}); } diff --git a/examples/logic/CMakeLists.txt b/examples/logic/CMakeLists.txt index ecf3bd602..d12b775b6 100644 --- a/examples/logic/CMakeLists.txt +++ b/examples/logic/CMakeLists.txt @@ -9,19 +9,25 @@ function(add_example) cmake_parse_arguments( EXAMPLE # Prefix of parsed args - "MAKE_TEST" # Options + "MAKE_TEST;LOCAL_EXAMPLE" # Options "NAME" # Single-value args "FILES" # Multi-value-args ${ARGN} ) + if(${EXAMPLE_LOCAL_EXAMPLE}) + set(RAMSES_SHLIB ramses-shared-lib) + else() + set(RAMSES_SHLIB ramses-shared-lib-headless) + endif() + createModule( NAME ${EXAMPLE_NAME} TYPE BINARY INCLUDE_PATHS shared ENABLE_INSTALL OFF SRC_FILES ${EXAMPLE_FILES} - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ${RAMSES_SHLIB} ) if(TARGET ${EXAMPLE_NAME} AND ramses-sdk_BUILD_TESTS AND ${EXAMPLE_MAKE_TEST}) @@ -47,11 +53,11 @@ add_example(NAME 11_interfaces FILES 11_interfaces/main.cpp if(ramses-sdk_BUILD_FULL_SHARED_LIB) # Can't execute ramses animation examples as test - they have a loop which blocks test automation and wastes resources - add_example(NAME 08a_static_animation FILES 08a_static_animation/main.cpp) - add_example(NAME 08b_dynamic_animation FILES 08b_dynamic_animation/main.cpp) + add_example(NAME 08a_static_animation FILES 08a_static_animation/main.cpp LOCAL_EXAMPLE) + add_example(NAME 08b_dynamic_animation FILES 08b_dynamic_animation/main.cpp LOCAL_EXAMPLE) # Can't execute as test - it is essentially animation with loop which blocks test automation and wastes resources - add_example(NAME 14_skinbinding FILES 14_skinbinding/main.cpp) - add_example(NAME 12_anchor_point FILES 12_anchor_point/main.cpp) - add_example(NAME 13_render_order FILES 13_render_order/main.cpp) - add_example(NAME 15_meshnodebinding FILES 15_meshnodebinding/main.cpp) + add_example(NAME 14_skinbinding FILES 14_skinbinding/main.cpp LOCAL_EXAMPLE) + add_example(NAME 12_anchor_point FILES 12_anchor_point/main.cpp LOCAL_EXAMPLE) + add_example(NAME 13_render_order FILES 13_render_order/main.cpp LOCAL_EXAMPLE) + add_example(NAME 15_meshnodebinding FILES 15_meshnodebinding/main.cpp LOCAL_EXAMPLE) endif() diff --git a/examples/ramses-example-basic-blending/CMakeLists.txt b/examples/ramses-example-basic-blending/CMakeLists.txt index 17262db64..8cf34f763 100644 --- a/examples/ramses-example-basic-blending/CMakeLists.txt +++ b/examples/ramses-example-basic-blending/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-basic-effect-from-glsl/CMakeLists.txt b/examples/ramses-example-basic-effect-from-glsl/CMakeLists.txt index 23af8d9b7..8cb803199 100644 --- a/examples/ramses-example-basic-effect-from-glsl/CMakeLists.txt +++ b/examples/ramses-example-basic-effect-from-glsl/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-basic-file-loading/CMakeLists.txt b/examples/ramses-example-basic-file-loading/CMakeLists.txt index ae4ac18c3..674248134 100644 --- a/examples/ramses-example-basic-file-loading/CMakeLists.txt +++ b/examples/ramses-example-basic-file-loading/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-basic-geometry/CMakeLists.txt b/examples/ramses-example-basic-geometry/CMakeLists.txt index 2ea1b4386..20417e4d7 100644 --- a/examples/ramses-example-basic-geometry/CMakeLists.txt +++ b/examples/ramses-example-basic-geometry/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-basic-rendergroups/CMakeLists.txt b/examples/ramses-example-basic-rendergroups/CMakeLists.txt index f04d4d6cf..a2c3c5f9c 100644 --- a/examples/ramses-example-basic-rendergroups/CMakeLists.txt +++ b/examples/ramses-example-basic-rendergroups/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-basic-renderpasses/CMakeLists.txt b/examples/ramses-example-basic-renderpasses/CMakeLists.txt index 127ce7125..4b6c025f7 100644 --- a/examples/ramses-example-basic-renderpasses/CMakeLists.txt +++ b/examples/ramses-example-basic-renderpasses/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-basic-rendertarget/CMakeLists.txt b/examples/ramses-example-basic-rendertarget/CMakeLists.txt index 905afa770..38fe3dfc0 100644 --- a/examples/ramses-example-basic-rendertarget/CMakeLists.txt +++ b/examples/ramses-example-basic-rendertarget/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-basic-scenegraph/CMakeLists.txt b/examples/ramses-example-basic-scenegraph/CMakeLists.txt index e6d7efa3e..b16f02eca 100644 --- a/examples/ramses-example-basic-scenegraph/CMakeLists.txt +++ b/examples/ramses-example-basic-scenegraph/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-basic-texturing/CMakeLists.txt b/examples/ramses-example-basic-texturing/CMakeLists.txt index 016fc32e5..e50c37423 100644 --- a/examples/ramses-example-basic-texturing/CMakeLists.txt +++ b/examples/ramses-example-basic-texturing/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-data-buffers-texture/CMakeLists.txt b/examples/ramses-example-data-buffers-texture/CMakeLists.txt index 8f40a68a6..4378bcdd0 100644 --- a/examples/ramses-example-data-buffers-texture/CMakeLists.txt +++ b/examples/ramses-example-data-buffers-texture/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-data-buffers-texture/src/main.cpp b/examples/ramses-example-data-buffers-texture/src/main.cpp index 4ab6f85da..187d38fde 100644 --- a/examples/ramses-example-data-buffers-texture/src/main.cpp +++ b/examples/ramses-example-data-buffers-texture/src/main.cpp @@ -107,18 +107,18 @@ int main() const uint32_t regionDataSizeLevel0 = regionWidthLevel0 * regionHeightLevel0 * numChannels; const uint32_t regionDataSizeLevel1 = regionWidthLevel1 * regionHeightLevel1 * numChannels; - std::array textureDataLevel0{}; - std::array textureDataLevel1{}; - std::array regionDataLevel0{}; - std::array regionDataLevel1{}; + std::array textureDataLevel0{}; + std::array textureDataLevel1{}; + std::array regionDataLevel0{}; + std::array regionDataLevel1{}; - // A helper function to cast and map a float value [0.f, 1.f[ to uint8 [0,255] - auto convertToUInt8 = [](float value)->uint8_t + // A helper function to cast and map a float value [0.f, 1.f] to byte [0,255] + auto convertToByte = [](float value) { // by substracting the integer part, we just keep // the fractional part [0.f,1.f[ value -= static_cast(static_cast(value)); - return static_cast(value * 255.f); + return std::byte{ static_cast(value * 255.f) }; }; // Fill the texture mipmap level 0 whith a red-green gradient @@ -126,9 +126,9 @@ int main() for(; !fullTextureIndicesLevel0.isAtEnd(); ++fullTextureIndicesLevel0) { const uint32_t index = fullTextureIndicesLevel0.getIndexGlobal() * 3; - textureDataLevel0.begin()[index+0] = convertToUInt8(fullTextureIndicesLevel0.getPositionXGlobal()); - textureDataLevel0.begin()[index+1] = convertToUInt8(fullTextureIndicesLevel0.getPositionYGlobal()); - textureDataLevel0.begin()[index+2] = 0; + textureDataLevel0.begin()[index+0] = convertToByte(fullTextureIndicesLevel0.getPositionXGlobal()); + textureDataLevel0.begin()[index+1] = convertToByte(fullTextureIndicesLevel0.getPositionYGlobal()); + textureDataLevel0.begin()[index+2] = convertToByte(0.f); } // Fill the texture mipmap level 1 with a red-blue gradient @@ -136,9 +136,9 @@ int main() for(; !fullTextureIndicesLevel1.isAtEnd(); ++fullTextureIndicesLevel1) { const uint32_t index = fullTextureIndicesLevel1.getIndexGlobal() * 3; - textureDataLevel1.begin()[index+0] = convertToUInt8(fullTextureIndicesLevel1.getPositionXGlobal()); - textureDataLevel1.begin()[index+1] = 0; - textureDataLevel1.begin()[index+2] = convertToUInt8(fullTextureIndicesLevel1.getPositionYGlobal()); + textureDataLevel1.begin()[index+0] = convertToByte(fullTextureIndicesLevel1.getPositionXGlobal()); + textureDataLevel1.begin()[index+1] = convertToByte(0.f); + textureDataLevel1.begin()[index+2] = convertToByte(fullTextureIndicesLevel1.getPositionYGlobal()); } /// [Data Buffer Texture Example create buffer] @@ -235,18 +235,18 @@ int main() // these values can be stored in some new array, which is not necessarily the original // data array. This new array has to have the correct dimensions for the updated region // (i.e. might be just as small as the region you need to update) - regionDataLevel0.begin()[index+0] = convertToUInt8(regionIndicesLevel0.getPositionXLocal(cycleOffset)); - regionDataLevel0.begin()[index+1] = 0; - regionDataLevel0.begin()[index+2] = convertToUInt8(regionIndicesLevel0.getPositionYLocal(cycleOffset)); + regionDataLevel0.begin()[index+0] = convertToByte(regionIndicesLevel0.getPositionXLocal(cycleOffset)); + regionDataLevel0.begin()[index+1] = convertToByte(0.f); + regionDataLevel0.begin()[index+2] = convertToByte(regionIndicesLevel0.getPositionYLocal(cycleOffset)); } // iterate over the values you want to update in mipmap level 1 for(; !regionIndicesLevel1.isAtEnd(); ++regionIndicesLevel1) { const uint32_t index = regionIndicesLevel1.getIndexLocal() * 3; - regionDataLevel1.begin()[index+0] = 0; - regionDataLevel1.begin()[index+1] = convertToUInt8(regionIndicesLevel1.getPositionXLocal(cycleOffset+0.5f)); - regionDataLevel1.begin()[index+2] = convertToUInt8(regionIndicesLevel1.getPositionYLocal(cycleOffset+0.3f)); + regionDataLevel1.begin()[index+0] = convertToByte(0.f); + regionDataLevel1.begin()[index+1] = convertToByte(regionIndicesLevel1.getPositionXLocal(cycleOffset+0.5f)); + regionDataLevel1.begin()[index+2] = convertToByte(regionIndicesLevel1.getPositionYLocal(cycleOffset+0.3f)); } // with Texture2DBuffer::setData you can pass the updated array data to the data buffer diff --git a/examples/ramses-example-data-buffers-vertices/CMakeLists.txt b/examples/ramses-example-data-buffers-vertices/CMakeLists.txt index a571e5c4d..aa15e3a9f 100644 --- a/examples/ramses-example-data-buffers-vertices/CMakeLists.txt +++ b/examples/ramses-example-data-buffers-vertices/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-geometry-instancing/CMakeLists.txt b/examples/ramses-example-geometry-instancing/CMakeLists.txt index d819a9b32..2e937a835 100644 --- a/examples/ramses-example-geometry-instancing/CMakeLists.txt +++ b/examples/ramses-example-geometry-instancing/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-interleaved-vertex-buffers/CMakeLists.txt b/examples/ramses-example-interleaved-vertex-buffers/CMakeLists.txt index 27173ec99..346d5cafa 100644 --- a/examples/ramses-example-interleaved-vertex-buffers/CMakeLists.txt +++ b/examples/ramses-example-interleaved-vertex-buffers/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-minimal/CMakeLists.txt b/examples/ramses-example-minimal/CMakeLists.txt index f78f35656..812e04fbc 100644 --- a/examples/ramses-example-minimal/CMakeLists.txt +++ b/examples/ramses-example-minimal/CMakeLists.txt @@ -12,5 +12,5 @@ createModule( ENABLE_INSTALL ON SRC_FILES include/*.h src/*.cpp - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-renderonce/CMakeLists.txt b/examples/ramses-example-renderonce/CMakeLists.txt index 11921706f..77aefffa2 100644 --- a/examples/ramses-example-renderonce/CMakeLists.txt +++ b/examples/ramses-example-renderonce/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES include/*.h src/*.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-text-basic/CMakeLists.txt b/examples/ramses-example-text-basic/CMakeLists.txt index e29e512b3..01e8acb36 100644 --- a/examples/ramses-example-text-basic/CMakeLists.txt +++ b/examples/ramses-example-text-basic/CMakeLists.txt @@ -13,5 +13,5 @@ createModule( SRC_FILES src/*.cpp src/*.h RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/examples/ramses-example-text-languages/CMakeLists.txt b/examples/ramses-example-text-languages/CMakeLists.txt index fbc955006..9530dcce4 100644 --- a/examples/ramses-example-text-languages/CMakeLists.txt +++ b/examples/ramses-example-text-languages/CMakeLists.txt @@ -12,5 +12,5 @@ createModule( ENABLE_INSTALL OFF # disabled installation to save space in release tarball SRC_FILES src/main.cpp RESOURCE_FOLDERS res - DEPENDENCIES ramses::shared-lib-for-examples + DEPENDENCIES ramses-shared-lib-headless ) diff --git a/include/CMakeLists.txt b/include/CMakeLists.txt index 43c92db61..88f85e506 100644 --- a/include/CMakeLists.txt +++ b/include/CMakeLists.txt @@ -46,7 +46,7 @@ if(ANY_WINDOW_TYPE_ENABLED) endif() if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.19.0") - target_sources(ramses-api PUBLIC ${RAMSES_FRAMEWORK_API_FILES_HEADER} + target_sources(ramses-api PRIVATE ${RAMSES_FRAMEWORK_API_FILES_HEADER} ${RAMSES_CLIENT_API_FILES_HEADER} ${RAMSES_CLIENT_TEXT_API_FILES_HEADER} ${RAMSES_CLIENT_LOGIC_API_FILES_HEADER} diff --git a/include/ramses/client/AttributeInput.h b/include/ramses/client/AttributeInput.h index 177fcf4e7..dd4ab2955 100644 --- a/include/ramses/client/AttributeInput.h +++ b/include/ramses/client/AttributeInput.h @@ -32,6 +32,36 @@ namespace ramses */ [[nodiscard]] EEffectAttributeSemantic getSemantics() const; + /** + * @brief Destructor of AttributeInput. + */ + ~AttributeInput(); + + /** + * @brief Copy constructor. + * @param other source to copy from + */ + AttributeInput(const AttributeInput& other); + + /** + * @brief Move constructor. + * @param other source to move from + */ + AttributeInput(AttributeInput&& other) noexcept; + + + /** + * @brief Assignment operator. + * @param other source to assign from + */ + AttributeInput& operator=(const AttributeInput& other); + + /** + * @brief Move assignment operator. + * @param other source to move assign from + */ + AttributeInput& operator=(AttributeInput&& other) noexcept; + protected: /** * @brief Default constructor of AttributeInput. diff --git a/include/ramses/client/MipLevelData.h b/include/ramses/client/MipLevelData.h index e8419d5e2..f29538675 100644 --- a/include/ramses/client/MipLevelData.h +++ b/include/ramses/client/MipLevelData.h @@ -10,49 +10,18 @@ #include "ramses/framework/RamsesFrameworkTypes.h" #include "ramses/framework/APIExport.h" +#include +#include namespace ramses { - /** * @ingroup CoreAPI - * @brief Struct containing information about one mip-map level of a texture. + * @brief Texel data of one mip level of a texture. * * NOTE: the texel data is stored according to OpenGL convention (first byte is from the bottom texel row). See docs of glTexImage2D for more info. */ - struct MipLevelData - { - /** - * @brief Default constructor - */ - MipLevelData() = default; - - /** - * @brief Constructs a MipLevelData. The texel data must be stored according to OpenGL conventions. - * Texel rows are stored bottom-to-top, so that first byte in the data array represents the first texel from the bottom texel row. - * See docs of glTexImage2D for more info. - * - * @param size Size of mipmap data in bytes - * @param data Pointer to raw bytes data of mipmap level - */ - MipLevelData(uint32_t size, const uint8_t* data) - : m_size(size) - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - , m_data(reinterpret_cast(data)) - { - } - - MipLevelData(uint32_t size, const std::byte* data) - : m_size(size) - , m_data(data) - { - } - - /// The size of mipmap data in bytes - uint32_t m_size{0}; - /// Pointer to raw bytes data of mipmap level - const std::byte* m_data{nullptr}; - }; + using MipLevelData = std::vector; /** @@ -62,53 +31,17 @@ namespace ramses */ struct CubeMipLevelData { - /** - * @brief Default constructor - */ - CubeMipLevelData() = default; - - /** - * @brief Constructs a MipLevelData. The texel data must be stored according to OpenGL conventions. - * Texel rows are stored bottom-to-top, so that first byte in the data array represents the first texel from the bottom texel row. - * See docs of glTexImage2D for more info. - * - * @param[in] size Size of data in bytes of all cube faces - * @param[in] dataPX Data for face in positive X direction - * @param[in] dataNX Data for face in negative X direction - * @param[in] dataPY Data for face in positive Y direction - * @param[in] dataNY Data for face in negative Y direction - * @param[in] dataPZ Data for face in positive Z direction - * @param[in] dataNZ Data for face in negative Z direction - */ - CubeMipLevelData(uint32_t size, - const std::byte* dataPX, const std::byte* dataNX, - const std::byte* dataPY, const std::byte* dataNY, - const std::byte* dataPZ, const std::byte* dataNZ) - : m_faceDataSize(size) - , m_dataPX(dataPX) - , m_dataNX(dataNX) - , m_dataPY(dataPY) - , m_dataNY(dataNY) - , m_dataPZ(dataPZ) - , m_dataNZ(dataNZ) - { - } - - /// size of mip-level data of all faces in Bytes, - /// all faces must have the same data size - uint32_t m_faceDataSize{0}; - /// Data for face in positive X direction - const std::byte* m_dataPX{nullptr}; + MipLevelData m_dataPX; /// Data for face in negative X direction - const std::byte* m_dataNX{nullptr}; + MipLevelData m_dataNX; /// Data for face in positive Y direction - const std::byte* m_dataPY{nullptr}; + MipLevelData m_dataPY; /// Data for face in negative Y direction - const std::byte* m_dataNY{nullptr}; + MipLevelData m_dataNY; /// Data for face in positive Z direction - const std::byte* m_dataPZ{nullptr}; + MipLevelData m_dataPZ; /// Data for face in negative Z direction - const std::byte* m_dataNZ{nullptr}; + MipLevelData m_dataNZ; }; } diff --git a/include/ramses/client/SaveFileConfig.h b/include/ramses/client/SaveFileConfig.h index 6ad30f087..ab0582b58 100644 --- a/include/ramses/client/SaveFileConfig.h +++ b/include/ramses/client/SaveFileConfig.h @@ -52,15 +52,6 @@ namespace ramses */ void setExporterVersion(uint32_t major, uint32_t minor, uint32_t patch, uint32_t fileFormatVersion); - /** - * By default, saving to file validates the content and issues warnings (see #ramses::Scene::validate). - * This behavior can be disabled here. Calling this with validationEnabled=false will itself cause a INFO log, - * but will silence further warnings in the content. - * - * @param validationEnabled flag to disable/enable validation upon saving to file - */ - void setValidationEnabled(bool validationEnabled); - /** * Sets saving mode for all #ramses::LuaScript and/or #ramses::LuaModule instances. * See #ramses::ELuaSavingMode for the available options and their implications. diff --git a/include/ramses/client/Scene.h b/include/ramses/client/Scene.h index fd2d92152..d92075b1b 100644 --- a/include/ramses/client/Scene.h +++ b/include/ramses/client/Scene.h @@ -118,12 +118,14 @@ namespace ramses /** * @brief Saves all scene contents to a file. + * @details Note that all #ramses::LogicEngine instances in the scene will be updated (#ramses::LogicEngine::update) + * and the scene will be flushed (#flush) before saving. * * @param[in] fileName File name to save the scene to. * @param[in] config optional configuration object with exporter and asset metadata info, see #ramses::SaveFileConfig for details * @return true for success, false otherwise (check log or #ramses::RamsesFramework::getLastError for details). */ - [[nodiscard]] bool saveToFile(std::string_view fileName, const SaveFileConfig& config = {}) const; + [[nodiscard]] bool saveToFile(std::string_view fileName, const SaveFileConfig& config = {}); /** * @brief Creates a #ramses::LogicEngine instance. @@ -235,8 +237,12 @@ namespace ramses bool setExpirationTimestamp(uint64_t ptpExpirationTimestampInMilliseconds); /** - * @brief Commits all changes done to the scene since the last flush or since scene creation. This makes a new - * valid scene state available to all local and remote renderers. + * @brief Commits all changes done to the scene since the last flush or since scene creation. + * @details Flush also makes a new valid scene state available to all local and remote renderers. + * Flush will fail if a pending change makes the scene invalid to a degree that renderer would fail + * in attempt to render it, e.g. there is missing resource or a wrong configuration of #ramses::RenderTarget. + * Note that successful flush still does not guarantee a full validity of a scene, see #ramses::RamsesObject::validate + * to make a more thorough check of a scene or a particular object. * * @param[in] sceneVersionTag updates the version tag of the scene along with the flushed scene updates. * If set to a valid value, a subscribed renderer will generate a sceneFlushed() event when the diff --git a/include/ramses/client/Texture2DBuffer.h b/include/ramses/client/Texture2DBuffer.h index 597eddf89..99b0a4f50 100644 --- a/include/ramses/client/Texture2DBuffer.h +++ b/include/ramses/client/Texture2DBuffer.h @@ -10,6 +10,7 @@ #include "ramses/client/SceneObject.h" #include "ramses/framework/TextureEnums.h" +#include namespace ramses { @@ -41,12 +42,11 @@ namespace ramses * @param offsetY The vertical texel offset into the texture data * @param width The horizontal subregion size in texels * @param height The vertical subregion size in texels - * @param data Pointer in memory to the data provided for update. The function makes - * a copy of the data into Texture2DBuffer data structures. Texture2DBuffer - * object does not take ownership of the memory data passed to it. + * @param data Texel data provided for update. The data must be in row-major order wrt. provided width/height. + * Data will be copied internally and no longer needed after this call returns. * @return true for success, false otherwise (check log or #ramses::RamsesFramework::getLastError for details). */ - bool updateData(size_t mipLevel, uint32_t offsetX, uint32_t offsetY, uint32_t width, uint32_t height, const void* data); + bool updateData(size_t mipLevel, uint32_t offsetX, uint32_t offsetY, uint32_t width, uint32_t height, const std::byte* data); /** * @brief Returns the number of mipmap levels created for the Texture2DBuffer (same as provided in diff --git a/include/ramses/client/UniformInput.h b/include/ramses/client/UniformInput.h index c537a1906..382c4bcfb 100644 --- a/include/ramses/client/UniformInput.h +++ b/include/ramses/client/UniformInput.h @@ -38,6 +38,35 @@ namespace ramses */ [[nodiscard]] size_t getElementCount() const; + /** + * @brief Destructor of UniformInput. + */ + ~UniformInput(); + + /** + * @brief Copy constructor. + * @param other source to copy from + */ + UniformInput(const UniformInput& other); + + /** + * @brief Move constructor. + * @param other source to move from + */ + UniformInput(UniformInput&& other) noexcept; + + /** + * @brief Assignment operator. + * @param other source to assign from + */ + UniformInput& operator=(const UniformInput& other); + + /** + * @brief Move assignment operator. + * @param other source to move assign from + */ + UniformInput& operator=(UniformInput&& other) noexcept; + protected: /** * @brief Default constructor of UniformInput. diff --git a/include/ramses/client/logic/LogicEngine.h b/include/ramses/client/logic/LogicEngine.h index 459f83703..5a4d84873 100644 --- a/include/ramses/client/logic/LogicEngine.h +++ b/include/ramses/client/logic/LogicEngine.h @@ -33,6 +33,7 @@ namespace ramses class RenderGroup; class UniformInput; class MeshNode; + class RenderBuffer; class LogicObject; } @@ -61,6 +62,7 @@ namespace ramses class RenderGroupBindingElements; class MeshNodeBinding; class SkinBinding; + class RenderBufferBinding; class DataArray; class AnimationNode; class AnimationNodeConfig; @@ -351,6 +353,18 @@ namespace ramses const ramses::UniformInput& jointMatInput, std::string_view name = {}); + /** + * Creates a new #ramses::RenderBufferBinding which can be used to change some properties of a #ramses::RenderBuffer object. + * The creation will fail if provided #ramses::RenderBuffer is not from same #ramses::Scene as this #LogicEngine instance. + * + * @param renderBuffer the #ramses::RenderBuffer object to control with the binding. + * @param name a name for the the new #ramses::RenderBufferBinding. + * @return a pointer to the created object or nullptr if + * something went wrong during creation. In that case, use #ramses::RamsesFramework::getLastError. + * The binding can be destroyed by calling the #destroy method + */ + RenderBufferBinding* createRenderBufferBinding(ramses::RenderBuffer& renderBuffer, std::string_view name =""); + /** * Creates a new #ramses::DataArray to store data which can be used with animations. * Provided data must not be empty otherwise creation will fail. @@ -754,6 +768,7 @@ namespace ramses std::is_same_v || std::is_same_v || std::is_same_v || + std::is_same_v || std::is_same_v || std::is_same_v || std::is_same_v || diff --git a/include/ramses/client/logic/RenderBufferBinding.h b/include/ramses/client/logic/RenderBufferBinding.h new file mode 100644 index 000000000..1d5c7e678 --- /dev/null +++ b/include/ramses/client/logic/RenderBufferBinding.h @@ -0,0 +1,106 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#pragma once + +#include "ramses/framework/APIExport.h" +#include "ramses/client/logic/RamsesBinding.h" + +namespace ramses +{ + class RenderBuffer; +} + +namespace ramses::internal +{ + class RenderBufferBindingImpl; +} + +namespace ramses +{ + /** + * The #RenderBufferBinding binds to a Ramses object instance of #ramses::RenderBuffer and exposes a set of input properties + * allowing to change some parameters of the #ramses::RenderBuffer. + * + * Important note: #ramses::RenderBuffer (unlike most other scene objects that can be bound to logic node network) is a static object + * in the sense that once it is allocated on Ramses renderer side it cannot be changed. This means that #RenderBufferBinding can be + * effectively used to change properties only BEFORE the render buffer is allocated on renderer (concretely before the scene + * is in state #ramses::RendererSceneState::Ready). Note that changing its properties after this moment will not produce any API + * or runtime errors but renderer will ignore them and log an error. It is recommended to study the RenderBufferBinding example + * before using it. + * + * #RenderBufferBinding has these input properties: + * 'width' (type int32) + * - binds to RenderBuffer's resolution width, overwriting the one which was used when creating it. + * 'height' (type int32) + * - binds to RenderBuffer's resolution height, overwriting the one which was used when creating it. + * 'sampleCount' (type int32) + * - binds to RenderBuffer's sample count used for multisampling, overwriting the one which was used when creating it. + * + * The initial values of the input properties are taken from the bound #ramses::RenderBuffer. + * + * The #RenderBufferBinding class has no output properties (thus #ramses::LogicNode::getOutputs() will return nullptr) because + * the outputs are implicitly forwarded to the bound #ramses::RenderBuffer. + * + * The changes via binding objects are applied to the bound object right away when calling #ramses::LogicEngine::update, + * however keep in mind that Ramses has a mechanism for bundling scene changes and applying them at once using #ramses::Scene::flush, + * so the changes will be applied all the way only after calling this method on the scene. + * + * Possible errors: + * - #ramses::LogicEngine::update will fail to update #RenderBufferBinding if: + * - any input negative + * - 'width' or 'height' is zero + * - #ramses::Scene::flush can fail as a result of changing #ramses::RenderBuffer parameters in #ramses::Scene: + * - if #ramses::RenderBuffer is used in a #ramses::RenderTarget and becomes not compatible (different size or sample count) with other buffers + * in that render target + * - if #ramses::RenderBuffer is used as source/destination in a #ramses::BlitPass and becomes out of bounds for the pass's blitting region + * - renderer will produce an error log if a #ramses::RenderBuffer change comes after it was already allocated (see above for details) + */ + class RAMSES_API RenderBufferBinding : public RamsesBinding + { + public: + /** + * Returns the bound #ramses::RenderBuffer. + * + * @return the bound #ramses::RenderBuffer + */ + [[nodiscard]] const ramses::RenderBuffer& getRenderBuffer() const; + + /** + * Returns the bound #ramses::RenderBuffer. + * + * @return the bound #ramses::RenderBuffer + */ + [[nodiscard]] ramses::RenderBuffer& getRenderBuffer(); + + /** + * Get the internal data for implementation specifics of RenderBufferBinding. + */ + [[nodiscard]] internal::RenderBufferBindingImpl& impl(); + + /** + * Get the internal data for implementation specifics of RenderBufferBinding. + */ + [[nodiscard]] const internal::RenderBufferBindingImpl& impl() const; + + protected: + /** + * Constructor of RenderBufferBinding. User is not supposed to call this - RenderBufferBindings are created by other factory classes + * + * @param impl implementation details of the RenderBufferBinding + */ + explicit RenderBufferBinding(std::unique_ptr impl) noexcept; + + /** + * Implementation detail of RenderBufferBinding + */ + internal::RenderBufferBindingImpl& m_renderBufferBinding; + + friend class internal::ApiObjects; + }; +} diff --git a/include/ramses/client/ramses-utils.h b/include/ramses/client/ramses-utils.h index 88282b1d0..e33114d67 100644 --- a/include/ramses/client/ramses-utils.h +++ b/include/ramses/client/ramses-utils.h @@ -9,6 +9,7 @@ #pragma once #include "ramses/framework/TextureEnums.h" +#include "ramses/client/MipLevelData.h" #include "ramses/client/TextureSwizzle.h" #include "ramses/client/RamsesClient.h" #include "ramses/framework/RamsesFrameworkTypes.h" @@ -32,8 +33,6 @@ namespace ramses class Texture2D; class UniformInput; class DataObject; - struct MipLevelData; - struct CubeMipLevelData; /** * @ingroup UtilsAPI @@ -78,7 +77,7 @@ namespace ramses * only the original mip map level is part of the result. * You are responsible to destroy the generated data, e.g. by using RamsesUtils::DeleteGeneratedMipMaps */ - RAMSES_API MipLevelData* GenerateMipMapsTexture2D(uint32_t width, uint32_t height, uint8_t bytesPerPixel, std::byte* data, size_t& mipMapCount); + RAMSES_API std::vector* GenerateMipMapsTexture2D(uint32_t width, uint32_t height, uint8_t bytesPerPixel, std::byte* data, size_t& mipMapCount); /** * @brief Creates a png from image data, e.g. data generated by RamsesClientService::readPixels. @@ -127,21 +126,19 @@ namespace ramses * only the original mip map level is part of the result. * You are responsible to destroy the generated data, e.g. using RamsesUtils::DeleteGeneratedMipMaps */ - RAMSES_API CubeMipLevelData* GenerateMipMapsTextureCube(uint32_t faceWidth, uint32_t faceHeight, uint8_t bytesPerPixel, std::byte* data, size_t& mipMapCount); + RAMSES_API std::vector* GenerateMipMapsTextureCube(uint32_t faceWidth, uint32_t faceHeight, uint8_t bytesPerPixel, std::byte* data, size_t& mipMapCount); /** * @brief Deletes mip map data created with RamsesUtils::GenerateMipMapsTexture2D. * @param[in, out] data Generated mip map data. - * @param[in] mipMapCount Number of mip map levels in the generated data. */ - RAMSES_API void DeleteGeneratedMipMaps(MipLevelData*& data, size_t mipMapCount); + RAMSES_API void DeleteGeneratedMipMaps(std::vector*& data); /** * @brief Deletes mip map data created with RamsesUtils::GenerateMipMapsTextureCube. * @param[in, out] data Generated mip map data. - * @param[in] mipMapCount Number of mip map levels in the generated data. */ - RAMSES_API void DeleteGeneratedMipMaps(CubeMipLevelData*& data, size_t mipMapCount); + RAMSES_API void DeleteGeneratedMipMaps(std::vector*& data); /** * @brief Returns the identifier of a node, which is printed in the renderer logs. The identifier is guaranteed to be diff --git a/include/ramses/framework/APIExport.h b/include/ramses/framework/APIExport.h index 32314906e..f7dd76587 100644 --- a/include/ramses/framework/APIExport.h +++ b/include/ramses/framework/APIExport.h @@ -31,3 +31,7 @@ #endif #endif + +// Add macro/define for exporting non-API symbols into shared libs +// when needed. +#define RAMSES_IMPL_EXPORT RAMSES_API diff --git a/include/ramses/framework/RamsesFrameworkConfig.h b/include/ramses/framework/RamsesFrameworkConfig.h index 79f58c143..f5f9afc23 100644 --- a/include/ramses/framework/RamsesFrameworkConfig.h +++ b/include/ramses/framework/RamsesFrameworkConfig.h @@ -172,6 +172,18 @@ namespace ramses */ void setPeriodicLogInterval(std::chrono::seconds interval); + /** + * @brief Sets the logging instance name. + * All logs produced by Ramses have this format: + * "$instanceName.$threadName[.$additionalId]: $logMessage" + * The instance name can be set to an arbitrary name using this method, this can be useful to distinguish logs + * when running multiple instances of Ramses framework in same process, thus sharing the logging system. + * Note that this will only work when multiple Ramses framework instances run in separate threads. + * + * @param[in] instanceName logging instance name, default is "R". + */ + void setLoggingInstanceName(std::string_view instanceName); + /** * @brief Sets the participant identifier * diff --git a/scripts/ci/build/build.py b/scripts/ci/build/build.py index 440b4d51e..71346631f 100644 --- a/scripts/ci/build/build.py +++ b/scripts/ci/build/build.py @@ -33,7 +33,7 @@ def __init__(self, compiler, config, build_dir): def cmake_configure(self, disable_default_window_type, enable_x11, enable_android, enable_wayland_ivi, enable_wayland_wl_shell, flatbuf_gen, android_abi, disable_logic, use_imagemagick, - headless, no_full_shared_lib, + no_full_shared_lib, no_examples, no_demos, no_tests, no_tools, generator, enable_dlt, enable_lto, test_coverage, enable_coverage, sanitizer_name, package_name, cpp_std, cmake_modules, enable_luajit): @@ -70,9 +70,6 @@ def cmake_configure(self, if sanitizer_name: optional_args.append(f'-Dramses-sdk_ENABLE_SANITIZER={sanitizer_name}') - if headless: - optional_args.append('-Dramses-sdk_BUILD_HEADLESS_SHARED_LIB=1') - if no_full_shared_lib: optional_args.append('-Dramses-sdk_BUILD_FULL_SHARED_LIB=0') @@ -159,7 +156,6 @@ def copy_package(self, package_target): @click.option('--build-target', default='install', help='What CMake target to build') @click.option('--flatbuf-gen', is_flag=True, default=False, help='Generate flatbuffer file headers') @click.option('--android-abi', help='Set ABI when building on Android') -@click.option('--headless', is_flag=True, default=False, help='Build headless shared lib without renderer') @click.option('--no-full-shared-lib', is_flag=True, default=False, help='Disable building full shared lib with renderer') @click.option('--no-examples', is_flag=True, default=False, help='Dont build examples') @click.option('--no-demos', is_flag=True, default=False, help='Dont build demos') diff --git a/scripts/ci/build/test-cmake-configurations.py b/scripts/ci/build/test-cmake-configurations.py index 32e73bfeb..8027d8c1b 100755 --- a/scripts/ci/build/test-cmake-configurations.py +++ b/scripts/ci/build/test-cmake-configurations.py @@ -53,7 +53,6 @@ def check_expectations(condition, *expectations): assert all(f'+ {e} ' not in process_output for e in expectations) # check expected and non-expected output based on logical consequences of each option, and their combination together - headless = "headless" in cmake_options x11 = "enable_x11" in cmake_options wayland_ivi = "enable_wayland_ivi" in cmake_options wayland_shell = "enable_wayland_wl_shell" in cmake_options @@ -78,37 +77,37 @@ def check_expectations(condition, *expectations): assert "Found LuaJIT" in process_output # shared libs - check_expectations(headless, "ramses-shared-lib-headless") + check_expectations(True, "ramses-shared-lib-headless") check_expectations(full_shared_lib, "ramses-shared-lib") # renderer check_expectations(x11, "X11") check_expectations(wayland_ivi, "Wayland ivi") check_expectations(wayland_shell, "Wayland wl_shell") - check_expectations(renderer, "ramses-renderer-lib", "ramses-renderer") + check_expectations(renderer, "ramses-renderer-internal", "ramses-renderer") # tools check_expectations(tools, "ivi-gears", "ivi-simple-dmabuf-egl", "ramses-daemon") - check_expectations(tools and renderer, "ramses-renderer-standalone", "ramses-scene-viewer", "ramses-stream-viewer", "ramses-imgui") - check_expectations(tools and logic and headless, "ramses-logic-viewer-headless") - check_expectations(tools and logic and full_shared_lib, "ramses-logic-viewer", "test-asset-producer") + check_expectations(tools and renderer, "ramses-renderer-standalone", "ramses-stream-viewer", "ramses-imgui") + check_expectations(tools and logic, "ramses-viewer-headless", "test-asset-producer") + check_expectations(tools and logic and renderer, "ramses-viewer") # tests check_expectations(tests, "ramses-framework-test", "ramses-client-test") - check_expectations(tests and renderer, "ramses-renderer-lib-test", "ramses-renderer-test", "rendering-tests", "ramses-test-client") + check_expectations(tests and renderer, "ramses-renderer-internal-test", "ramses-renderer-test", "rendering-tests", "ramses-test-client") check_expectations(tests and logic, "ramses-logic-benchmarks") check_expectations(x11 and tests, "window-x11-test") check_expectations(wayland_ivi and tests, "window-wayland-ivi-test") check_expectations(wayland_shell and tests, "window-wayland-wl-shell-test") # tool tests - check_expectations(tests and tools and logic, "ramses-logic-viewer-test") - check_expectations(tests and tools and logic and full_shared_lib and use_imagemagick, "ramses-logic-viewer-gui-test") + check_expectations(tests and tools and logic, "ramses-viewer-test") + check_expectations(tests and tools and logic and renderer and use_imagemagick, "ramses-viewer-gui-test") # examples - check_expectations(examples and (headless or full_shared_lib), "ramses-example-basic-geometry") + check_expectations(examples, "ramses-example-basic-geometry") check_expectations(examples and full_shared_lib, "ramses-example-local-client") - check_expectations(examples and (headless or full_shared_lib) and logic, "00_minimal") + check_expectations(examples and logic, "00_minimal") check_expectations(examples and full_shared_lib and logic, "13_render_order") if tests: @@ -130,7 +129,7 @@ def check_expectations(condition, *expectations): # step 3: build list of expected tests based on cmake options expected_tests = ['ramses-framework-test_UNITTEST', 'ramses-client-test_UNITTEST'] - if (headless or full_shared_lib) and examples and logic: + if examples and logic: expected_tests += [ '00_minimal_UNITTEST', '01a_primitive_properties_UNITTEST', @@ -146,7 +145,7 @@ def check_expectations(condition, *expectations): if renderer: expected_tests += [ - 'ramses-renderer-lib-test_UNITTEST', + 'ramses-renderer-internal-test_UNITTEST', 'ramses-renderer-test_UNITTEST', 'ramses-cli-test_UNITTEST'] @@ -191,7 +190,11 @@ def check_expectations(condition, *expectations): if logic and tools: expected_tests += [ - 'ramses-logic-viewer-test_UNITTEST'] + 'ramses-viewer-test_UNITTEST'] + + if logic and tools and renderer and use_imagemagick: + expected_tests += [ + 'ramses-viewer-gui-test_RNDSANDWICHTEST_SWRAST'] # step 4: find missing and/or unexpected tests unexpected_tests = [t for t in ctest_test_entries if t not in expected_tests] @@ -220,20 +223,17 @@ def main(cli_context, build_dir): start_time = time.time() # can configure with (external) luajit - test_cmake_configuration(cli_context, build_dir, True, headless=True, enable_luajit=True) + test_cmake_configuration(cli_context, build_dir, True, enable_luajit=True) test_cmake_configuration(cli_context, build_dir, True, enable_x11=True, enable_luajit=True) - # can not configure if no useful feature is enabled, i.e., user gets a non-usable project without any shared libs or renderer - test_cmake_configuration(cli_context, build_dir, False) - test_cmake_configuration(cli_context, build_dir, False, no_full_shared_lib=True) - # can configure if trying to build shared lib (on by default) while no window types enabled (generates a warning though) - test_cmake_configuration(cli_context, build_dir, True, headless=True) + test_cmake_configuration(cli_context, build_dir, True) + test_cmake_configuration(cli_context, build_dir, True, no_full_shared_lib=True) # can configure ramses with headless lib only (without full shared lib, and without any window types enabled) - test_cmake_configuration(cli_context, build_dir, True, headless=True, no_full_shared_lib=True) + test_cmake_configuration(cli_context, build_dir, True, no_full_shared_lib=True) # can configure ramses with headless lib and full shared lib - test_cmake_configuration(cli_context, build_dir, True, headless=True, enable_x11=True) + test_cmake_configuration(cli_context, build_dir, True, enable_x11=True) # can configure with any window type enabled (full shared lib on by default) test_cmake_configuration(cli_context, build_dir, True, enable_x11=True) @@ -247,16 +247,16 @@ def main(cli_context, build_dir): test_cmake_configuration(cli_context, build_dir, True, enable_x11=True, no_tools=True) test_cmake_configuration(cli_context, build_dir, True, enable_x11=True, no_full_shared_lib=True, no_examples=True, no_demos=True, no_tests=True, no_tools=True) - test_cmake_configuration(cli_context, build_dir, True, headless=True, no_full_shared_lib=True, + test_cmake_configuration(cli_context, build_dir, True, no_full_shared_lib=True, no_examples=True, no_demos=True, no_tests=True, no_tools=True) # can configure with imagemagick enabled even if shared lib not available - test_cmake_configuration(cli_context, build_dir, True, headless=True, no_full_shared_lib=True, use_imagemagick=True) + test_cmake_configuration(cli_context, build_dir, True, no_full_shared_lib=True, use_imagemagick=True) test_cmake_configuration(cli_context, build_dir, True, enable_x11=True, no_full_shared_lib=True, use_imagemagick=True) # can configure with ramses logic disabled - test_cmake_configuration(cli_context, build_dir, True, headless=True, disable_logic=True, no_full_shared_lib=True) - test_cmake_configuration(cli_context, build_dir, True, headless=True, disable_logic=True, no_full_shared_lib=True, use_imagemagick=True) + test_cmake_configuration(cli_context, build_dir, True, disable_logic=True, no_full_shared_lib=True) + test_cmake_configuration(cli_context, build_dir, True, disable_logic=True, no_full_shared_lib=True, use_imagemagick=True) elapsed_time = time.time() - start_time print(f"Tests finished SUCCESSFULLY...Elapsed time to run cmake configuration tests : {elapsed_time:.2f} seconds") diff --git a/scripts/ci/config/clang-tidy-wrapper.yaml b/scripts/ci/config/clang-tidy-wrapper.yaml index b12d4ff8d..629d39ce6 100644 --- a/scripts/ci/config/clang-tidy-wrapper.yaml +++ b/scripts/ci/config/clang-tidy-wrapper.yaml @@ -38,7 +38,7 @@ check-filter: - check: cppcoreguidelines-pro-type-vararg exclude: # ImGui uses va_args in its api - - ^tools/ramses-scene-viewer/src/SceneViewerGui.cpp$ + - ^tools/ramses-viewer/SceneViewerGui.cpp$ - ^tools/ramses-imgui/src/ImguiWidgets.cpp$ - check: hicpp-signed-bitwise exclude: diff --git a/scripts/ci/config/valgrind/suppressions b/scripts/ci/config/valgrind/suppressions index 5b92c24bd..c67bd412f 100644 --- a/scripts/ci/config/valgrind/suppressions +++ b/scripts/ci/config/valgrind/suppressions @@ -71,24 +71,7 @@ Memcheck:Leak match-leak-kinds: possible fun:calloc - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* - obj:* + ... fun:_ZN6ramses8internal9Device_GL20drawIndexedTrianglesEiij ... } diff --git a/scripts/ci/installation-check/check-installation.py b/scripts/ci/installation-check/check-installation.py index 64bc01626..7787ad36e 100755 --- a/scripts/ci/installation-check/check-installation.py +++ b/scripts/ci/installation-check/check-installation.py @@ -45,17 +45,14 @@ def main(): parser.add_argument('--install-dir', required=True, help='Directory where ramses was installed') parser.add_argument('--ignore', required=False, action='append', help='Ignore file patterns from the installation folder') parser.add_argument('--platform', required=False, action='append', help='Platforms (x11, wayland, ...)') - parser.add_argument('--headless', required=False, action='store_true', help='Check for headless binaries (no ramses renderer)') parser.add_argument("--system-glm", required=False, action='store_true', help='glm headers are expected not to be installed') args = parser.parse_args() - if not args.headless and not args.platform: - raise Exception("Either --platform or --headless must be set") - # Expect exactly these files after installation (don't list header files here, they are cross-checked with source tree) expectNonHeaderFiles = [ r"^bin/ramses-daemon$", + r"^bin/ramses-viewer-headless$", r"^share/doc/ramses-sdk-\d+\.\d+\.\d+/LICENSE\.txt$", r"^share/doc/ramses-sdk-\d+\.\d+\.\d+/CHANGELOG\.md$", r"^share/doc/ramses-sdk-\d+\.\d+\.\d+/CONTRIBUTING\.rst$", @@ -63,16 +60,17 @@ def main(): # TODO: remove, these are a tests/demos, not needed in the package r"^bin/ramses-client-test$", r"^bin/ramses-framework-test$", - r"^bin/ramses-logic-viewer-test$", + r"^bin/ramses-viewer-test$", r"^bin/ivi-gears$", r"^bin/ivi-simple-dmabuf-egl$", ] - if args.headless: - expectNonHeaderFiles += [ - r"^lib/libramses-shared-lib-headless\.so$", - r"^lib/libramses-shared-lib-headless\.so\.\d+\.\d+$", - ] + expectNonHeaderFiles += [ + r"^lib/libramses-shared-lib-headless\.so$", + r"^lib/libramses-shared-lib-headless\.so\.\d+\.\d+$", + r"^lib/cmake/ramses-shared-lib-headless-\d+\.\d+/ramses-shared-lib-headlessConfigVersion\.cmake$", + r"^lib/cmake/ramses-shared-lib-headless-\d+\.\d+/ramses-shared-lib-headlessConfig\.cmake$", + ] if args.platform: known_platforms = ['x11-egl-es-3-0', 'wayland-shell-egl-es-3-0', 'wayland-ivi-egl-es-3-0'] @@ -81,17 +79,16 @@ def main(): raise Exception(f"Unrecognized platform {p}, must choose one from {known_platforms}") expectNonHeaderFiles += [ - r"^bin/ramses-logic-viewer$", # TODO: remove, these are a tests/demos, not needed in the package - r"^bin/ramses-renderer-lib-test$", + r"^bin/ramses-renderer-internal-test$", r"^bin/ramses-renderer-test$", r"^bin/ramses-cli-test$", - r"^bin/ramses-logic-viewer-gui-test$", + r"^bin/ramses-viewer-gui-test$", r"^lib/libramses-shared-lib\.so$", r"^lib/libramses-shared-lib\.so\.\d+\.\d+$", # TODO: These files should be packaged separately - maybe as a tools package? r"^bin/ramses-renderer-standalone$", - r"^bin/ramses-scene-viewer$", + r"^bin/ramses-viewer$", r"^bin/ramses-stream-viewer$", # TODO: remove, these are a tests/demos, not needed in the package r"^bin/ramses-test-client$", @@ -125,13 +122,6 @@ def main(): r"^lib/cmake/ramses-shared-lib-\d+\.\d+/ramses-shared-libConfig\.cmake$", ] - if args.headless: - expectNonHeaderFiles += [ - r"^lib/cmake/ramses-shared-lib-headless-\d+\.\d+/ramses-shared-lib-headlessConfigVersion\.cmake$", - r"^lib/cmake/ramses-shared-lib-headless-\d+\.\d+/ramses-shared-lib-headlessConfig\.cmake$", - r"^bin/ramses-logic-viewer-headless$", - ] - installPath = Path(args.install_dir) includePath = installPath / 'include' diff --git a/scripts/ci/installation-check/check-shared-lib-symbols.py b/scripts/ci/installation-check/check-shared-lib-symbols.py index 7f34adb78..0b93766f1 100755 --- a/scripts/ci/installation-check/check-shared-lib-symbols.py +++ b/scripts/ci/installation-check/check-shared-lib-symbols.py @@ -15,9 +15,9 @@ @click.command(help='Check if there are missing symbols from shared lib') -@click.option('--headless', is_flag=True, default=False, help='Check headless shared lib') +@click.option('--headless-only', is_flag=True, default=False, help='Check headless shared lib') @click.option('-b', '--build-dir', type=click.Path(), help='Build dir') -def main(build_dir, headless): +def main(build_dir, headless_only): if not build_dir: raise Exception("build dir needed") @@ -27,8 +27,6 @@ def main(build_dir, headless): headless_shared_lib_dir = Path(build_dir) / 'install/lib/libramses-shared-lib-headless.so' full_shared_lib_dir = Path(build_dir) / 'install/lib/libramses-shared-lib.so' - shared_lib_dir = headless_shared_lib_dir if headless else full_shared_lib_dir - def file_to_symbols(lib_file, is_shared_lib): if not lib_file.exists(): raise Exception(f'File does not exist: {lib_file}') @@ -61,10 +59,12 @@ def file_to_symbols(lib_file, is_shared_lib): static_lib_symbols = file_to_symbols(client_static_lib_dir, False) static_lib_symbols += file_to_symbols(framework_static_lib_dir, False) - if not headless: + if not headless_only: static_lib_symbols += file_to_symbols(renderer_static_lib_dir, False) - shared_lib_symbols = file_to_symbols(shared_lib_dir, True) + shared_lib_symbols = file_to_symbols(headless_shared_lib_dir, True) + if not headless_only: + shared_lib_symbols += file_to_symbols(full_shared_lib_dir, True) missing_symbols = [s for s in static_lib_symbols if s not in shared_lib_symbols] if len(missing_symbols) > 0: diff --git a/scripts/ci/installation-check/shared-lib-check/CMakeLists.txt b/scripts/ci/installation-check/shared-lib-check/CMakeLists.txt index 0c2772ce4..7432d5fb3 100644 --- a/scripts/ci/installation-check/shared-lib-check/CMakeLists.txt +++ b/scripts/ci/installation-check/shared-lib-check/CMakeLists.txt @@ -40,7 +40,7 @@ if (NOT SYSTEM_GLM) target_include_directories(${name} PRIVATE ${ramses-shared-lib_INCLUDE_DIRS}) if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU" OR "${CMAKE_CXX_COMPILER_ID}" STREQUAL "Clang") - get_filename_component(ramses-shared-lib_LIBDIR ${ramses-shared-lib_LIBRARIES} DIRECTORY) + get_filename_component(ramses-shared-lib_LIBDIR ${ramses-shared-lib-headless_LIBRARIES} DIRECTORY) target_link_libraries(${name} "-Wl,-rpath-link,${ramses-shared-lib_LIBDIR}") endif() diff --git a/scripts/code_style_checker/check_deprecated.py b/scripts/code_style_checker/check_deprecated.py index c02013b59..c8219a7bb 100644 --- a/scripts/code_style_checker/check_deprecated.py +++ b/scripts/code_style_checker/check_deprecated.py @@ -17,7 +17,6 @@ g_re_unwanted_gmock_include = re.compile(r'#\s*include\s*["<]gmock/(?!gmock\.h[">])') g_re_unwanted_fmt_include = re.compile(r'#\s*include\s*["<]fmt/(?!(?:format|chrono)\.h[">])') g_re_unwanted_system_include = re.compile(r'#\s*include\s*"[^\.]+"') -g_re_unwanted_force_thread_local = re.compile(r'#include\s*["<"]Utils/ThreadLocalLogForced\.h[">]') g_max_line_length = 350 @@ -47,10 +46,6 @@ def check_deprecated(filename, file_contents, clean_file_contents, file_lines, c common.log_warning("check_deprecated", filename, line_number + 1, 'found system include with "...", use <...> instead"', file_lines[line_number].strip(" \t\r\n")) - if filename.endswith('.h') and g_re_unwanted_force_thread_local.search(line): - common.log_warning("check_deprecated", filename, line_number + 1, - 'found disallowed #include "internal/Core/Utils/ThreadLocalLogForced.h" in header"', file_lines[line_number].strip(" \t\r\n")) - # TODO: Fix offenders and reduce limit until some reasonable length is reached if len(line) > g_max_line_length: common.log_warning("check_deprecated", filename, line_number + 1, diff --git a/src/client/CMakeLists.txt b/src/client/CMakeLists.txt index a9a353aaa..cdc1c26cb 100644 --- a/src/client/CMakeLists.txt +++ b/src/client/CMakeLists.txt @@ -6,51 +6,25 @@ # file, You can obtain one at https://mozilla.org/MPL/2.0/. # ------------------------------------------------------------------------- +add_subdirectory(internal) + if(ramses-sdk_TEXT_SUPPORT) - list(APPEND CLIENT_SOURCES impl/text/*.h - impl/text/*.cpp) - list(APPEND CLIENT_LIBS freetype - harfbuzz) + list(APPEND CLIENT_IMPL_SOURCES impl/text/*.h + impl/text/*.cpp) endif() if(ramses-sdk_ENABLE_LOGIC) - list(APPEND CLIENT_SOURCES impl/logic/*.h - impl/logic/*.cpp - internal/logic/*.h - internal/logic/*.cpp - internal/logic/flatbuffers/generated/*.h - internal/logic/flatbuffers/schemas/*.fbs) - list(APPEND CLIENT_LIBS sol2::sol2 - lua::lua - ramses::flatbuffers - fmt::fmt) + list(APPEND CLIENT_IMPL_SOURCES impl/logic/*.h + impl/logic/*.cpp) endif() createModule( NAME ramses-client TYPE STATIC_LIBRARY ENABLE_INSTALL OFF - INCLUDE_PATHS . - SRC_FILES impl/*.h impl/*.cpp - internal/*.h - internal/*.cpp - internal/glslEffectBlock/*.h - internal/glslEffectBlock/*.cpp - internal/ClientCommands/*.h - internal/ClientCommands/*.cpp - ${CLIENT_SOURCES} - DEPENDENCIES ramses-api + ${CLIENT_IMPL_SOURCES} + DEPENDENCIES ramses-client-internal ramses-framework - ramses-glslang - ${CLIENT_LIBS} ) - -if(TARGET FlatbufGen) - add_dependencies(ramses-client FlatbufGen) -endif() - -if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - target_compile_options(ramses-client PRIVATE "-Wsuggest-override") -endif() diff --git a/src/client/impl/AttributeInput.cpp b/src/client/impl/AttributeInput.cpp index e3173c18c..375b73802 100644 --- a/src/client/impl/AttributeInput.cpp +++ b/src/client/impl/AttributeInput.cpp @@ -16,6 +16,16 @@ namespace ramses { } + AttributeInput::~AttributeInput() = default; + + AttributeInput::AttributeInput(const AttributeInput& other) = default; + + AttributeInput::AttributeInput(AttributeInput&& other) noexcept = default; + + AttributeInput& AttributeInput::operator=(const AttributeInput& other) = default; + + AttributeInput& AttributeInput::operator=(AttributeInput&& other) noexcept = default; + EEffectAttributeSemantic AttributeInput::getSemantics() const { return m_impl->getAttributeSemantics(); diff --git a/src/client/impl/BlitPassImpl.cpp b/src/client/impl/BlitPassImpl.cpp index 1b0662532..c05862ba6 100644 --- a/src/client/impl/BlitPassImpl.cpp +++ b/src/client/impl/BlitPassImpl.cpp @@ -13,6 +13,7 @@ #include "impl/RamsesObjectTypeUtils.h" #include "impl/ErrorReporting.h" #include "internal/SceneGraph/SceneAPI/BlitPass.h" +#include "internal/SceneGraph/SceneAPI/PixelRectangle.h" #include "internal/SceneGraph/Scene/ClientScene.h" namespace ramses::internal @@ -44,31 +45,27 @@ namespace ramses::internal m_blitPassHandle = BlitPassHandle::Invalid(); } + bool BlitPassImpl::validateBlittingRegions(const PixelRectangle& src, const PixelRectangle& dst) const + { + const auto& blitPass = getIScene().getBlitPass(m_blitPassHandle); + const auto& renderBufferSrc = getIScene().getRenderBuffer(blitPass.sourceRenderBuffer); + const auto& renderBufferDst = getIScene().getRenderBuffer(blitPass.destinationRenderBuffer); + return + src.x + src.width <= renderBufferSrc.width && src.y + src.height <= renderBufferSrc.height && + dst.x + dst.width <= renderBufferDst.width && dst.y + dst.height <= renderBufferDst.height; + } + bool BlitPassImpl::setBlittingRegion(uint32_t sourceX, uint32_t sourceY, uint32_t destinationX, uint32_t destinationY, uint32_t width, uint32_t height) { - const ramses::internal::BlitPass& blitPass = getIScene().getBlitPass(m_blitPassHandle); - const ramses::internal::RenderBuffer& renderBufferSrc = getIScene().getRenderBuffer(blitPass.sourceRenderBuffer); - const ramses::internal::RenderBuffer& renderBufferDst = getIScene().getRenderBuffer(blitPass.destinationRenderBuffer); - if (sourceX + width > renderBufferSrc.width || sourceY + height > renderBufferSrc.height) - { - getErrorReporting().set("BlitPass::setBlittingRegion failed - invalid source region", *this); - return false; - } + const PixelRectangle sourceRegion = { sourceX, sourceY, static_cast(width), static_cast(height) }; + const PixelRectangle destinationRegion = { destinationX, destinationY, static_cast(width), static_cast(height) }; - if (destinationX + width > renderBufferDst.width || destinationY + height > renderBufferDst.height) + if (!validateBlittingRegions(sourceRegion, destinationRegion)) { - getErrorReporting().set("BlitPass::setBlittingRegion failed - invalid destination region", *this); + getErrorReporting().set("BlitPass::setBlittingRegion failed - region out of source or destination buffer size", *this); return false; } - const PixelRectangle sourceRegion = { - sourceX, sourceY, static_cast(width), static_cast(height) - }; - - const PixelRectangle destinationRegion = { - destinationX, destinationY, static_cast(width), static_cast(height) - }; - getIScene().setBlitPassRegions(m_blitPassHandle, sourceRegion, destinationRegion); return true; @@ -148,11 +145,14 @@ namespace ramses::internal const ramses::internal::BlitPass& blitPass = getIScene().getBlitPass(m_blitPassHandle); - if (!getIScene().isRenderBufferAllocated(blitPass.sourceRenderBuffer)) - report.add(EIssueType::Error, "blitpass references a deleted source render buffer", &getRamsesObject()); - - if (!getIScene().isRenderBufferAllocated(blitPass.destinationRenderBuffer)) - report.add(EIssueType::Error, "blitpass references a deleted destination render buffer", &getRamsesObject()); + if (!getIScene().isRenderBufferAllocated(blitPass.sourceRenderBuffer) || !getIScene().isRenderBufferAllocated(blitPass.destinationRenderBuffer)) + { + report.add(EIssueType::Error, "blitpass references a deleted source or destination render buffer", &getRamsesObject()); + } + else if (!validateBlittingRegions(blitPass.sourceRegion, blitPass.destinationRegion)) + { + report.add(EIssueType::Error, "blitpass blit region out of source or destination buffer size", &getRamsesObject()); + } } const ramses::RenderBuffer& BlitPassImpl::getSourceRenderBuffer() const diff --git a/src/client/impl/BlitPassImpl.h b/src/client/impl/BlitPassImpl.h index 2b95b6b75..ec69d954c 100644 --- a/src/client/impl/BlitPassImpl.h +++ b/src/client/impl/BlitPassImpl.h @@ -21,6 +21,7 @@ namespace ramses namespace ramses::internal { class RenderBufferImpl; + struct PixelRectangle; class BlitPassImpl final : public SceneObjectImpl { @@ -50,6 +51,8 @@ namespace ramses::internal [[nodiscard]] BlitPassHandle getBlitPassHandle() const; private: + [[nodiscard]] bool validateBlittingRegions(const PixelRectangle& src, const PixelRectangle& dst) const; + BlitPassHandle m_blitPassHandle; const RenderBufferImpl* m_sourceRenderBufferImpl = nullptr; const RenderBufferImpl* m_destinationRenderBufferImpl = nullptr; diff --git a/src/client/impl/CameraNodeImpl.cpp b/src/client/impl/CameraNodeImpl.cpp index 4e6ba5bbe..ff344c163 100644 --- a/src/client/impl/CameraNodeImpl.cpp +++ b/src/client/impl/CameraNodeImpl.cpp @@ -12,6 +12,7 @@ #include "impl/SerializationContext.h" #include "impl/ErrorReporting.h" #include "internal/SceneGraph/Scene/ClientScene.h" +#include "internal/SceneGraph/SceneUtils/DataInstanceHelper.h" #include "internal/Core/Math3d/CameraMatrixHelper.h" #include @@ -201,14 +202,12 @@ namespace ramses::internal float CameraNodeImpl::getNearPlane() const { - const auto nearFarData = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::FrustumNearFarPlanesField); - return getIScene().getDataSingleVector2f(nearFarData, DataFieldHandle{ 0 }).x; + return DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::FrustumNearFarPlanesField).x; } float CameraNodeImpl::getFarPlane() const { - const auto nearFarData = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::FrustumNearFarPlanesField); - return getIScene().getDataSingleVector2f(nearFarData, DataFieldHandle{ 0 }).y; + return DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::FrustumNearFarPlanesField).y; } bool CameraNodeImpl::setViewport(int32_t x, int32_t y, uint32_t width, uint32_t height) @@ -231,50 +230,42 @@ namespace ramses::internal int32_t CameraNodeImpl::getViewportX() const { - const auto vpOffsetData = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::ViewportOffsetField); - return getIScene().getDataSingleVector2i(vpOffsetData, DataFieldHandle{ 0 }).x; + return DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::ViewportOffsetField).x; } int32_t CameraNodeImpl::getViewportY() const { - const auto vpOffsetData = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::ViewportOffsetField); - return getIScene().getDataSingleVector2i(vpOffsetData, DataFieldHandle{ 0 }).y; + return DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::ViewportOffsetField).y; } uint32_t CameraNodeImpl::getViewportWidth() const { - const auto vpSizeData = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::ViewportSizeField); - return getIScene().getDataSingleVector2i(vpSizeData, DataFieldHandle{ 0 }).x; + return DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::ViewportSizeField).x; } uint32_t CameraNodeImpl::getViewportHeight() const { - const auto vpSizeData = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::ViewportSizeField); - return getIScene().getDataSingleVector2i(vpSizeData, DataFieldHandle{ 0 }).y; + return DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::ViewportSizeField).y; } float CameraNodeImpl::getLeftPlane() const { - const auto frustumData = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::FrustumPlanesField); - return getIScene().getDataSingleVector4f(frustumData, DataFieldHandle{ 0 }).x; + return DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::FrustumPlanesField).x; } float CameraNodeImpl::getRightPlane() const { - const auto frustumData = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::FrustumPlanesField); - return getIScene().getDataSingleVector4f(frustumData, DataFieldHandle{ 0 }).y; + return DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::FrustumPlanesField).y; } float CameraNodeImpl::getBottomPlane() const { - const auto frustumData = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::FrustumPlanesField); - return getIScene().getDataSingleVector4f(frustumData, DataFieldHandle{ 0 }).z; + return DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::FrustumPlanesField).z; } float CameraNodeImpl::getTopPlane() const { - const auto frustumData = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::FrustumPlanesField); - return getIScene().getDataSingleVector4f(frustumData, DataFieldHandle{ 0 }).w; + return DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::FrustumPlanesField).w; } CameraHandle CameraNodeImpl::getCameraHandle() const @@ -297,10 +288,8 @@ namespace ramses::internal ProjectionParams CameraNodeImpl::getProjectionParams() const { - const auto frustumDataInstance = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::FrustumPlanesField); - const auto& frustumData = getIScene().getDataSingleVector4f(frustumDataInstance, DataFieldHandle{ 0 }); - const auto nearFarDataInstance = getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::FrustumNearFarPlanesField); - const auto& nearFarData = getIScene().getDataSingleVector2f(nearFarDataInstance, DataFieldHandle{ 0 }); + const auto& frustumData = DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::FrustumPlanesField); + const auto& nearFarData = DataInstanceHelper::GetReferencedData(getIScene(), m_dataInstance, ramses::internal::Camera::FrustumNearFarPlanesField); return ProjectionParams::Frustum( getIScene().getCamera(m_cameraHandle).projectionType, @@ -419,12 +408,12 @@ namespace ramses::internal return getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::ViewportSizeField); } - DataInstanceHandle CameraNodeImpl::getFrustrumPlanesHandle() const + DataInstanceHandle CameraNodeImpl::getFrustumPlanesHandle() const { return getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::FrustumPlanesField); } - DataInstanceHandle CameraNodeImpl::getFrustrumNearFarPlanesHandle() const + DataInstanceHandle CameraNodeImpl::getFrustumNearFarPlanesHandle() const { return getIScene().getDataReference(m_dataInstance, ramses::internal::Camera::FrustumNearFarPlanesField); } diff --git a/src/client/impl/CameraNodeImpl.h b/src/client/impl/CameraNodeImpl.h index f8b87d69b..b20715527 100644 --- a/src/client/impl/CameraNodeImpl.h +++ b/src/client/impl/CameraNodeImpl.h @@ -74,8 +74,8 @@ namespace ramses::internal [[nodiscard]] DataInstanceHandle getViewportOffsetHandle() const; [[nodiscard]] DataInstanceHandle getViewportSizeHandle() const; - [[nodiscard]] DataInstanceHandle getFrustrumPlanesHandle() const; - [[nodiscard]] DataInstanceHandle getFrustrumNearFarPlanesHandle() const; + [[nodiscard]] DataInstanceHandle getFrustumPlanesHandle() const; + [[nodiscard]] DataInstanceHandle getFrustumNearFarPlanesHandle() const; private: [[nodiscard]] ProjectionParams getProjectionParams() const; diff --git a/src/client/impl/EffectDescriptionImpl.cpp b/src/client/impl/EffectDescriptionImpl.cpp index 890981c5b..128f61c5d 100644 --- a/src/client/impl/EffectDescriptionImpl.cpp +++ b/src/client/impl/EffectDescriptionImpl.cpp @@ -153,13 +153,13 @@ namespace ramses::internal File inFile(fileName); if (!inFile.exists()) { - LOG_ERROR(CONTEXT_CLIENT, "EffectDescriptionImpl::ReadFileContentsToString: could not find file: " << fileName); + LOG_ERROR(CONTEXT_CLIENT, "EffectDescriptionImpl::ReadFileContentsToString: could not find file: {}", fileName); return false; } if (!inFile.open(File::Mode::ReadOnlyBinary)) { - LOG_ERROR(CONTEXT_CLIENT, "EffectDescriptionImpl::ReadFileContentsToString: could not open file: " << fileName); + LOG_ERROR(CONTEXT_CLIENT, "EffectDescriptionImpl::ReadFileContentsToString: could not open file: {}", fileName); return false; } @@ -167,7 +167,7 @@ namespace ramses::internal size_t readBytes = 0; if (!inFile.getSizeInBytes(fileSize)) { - LOG_ERROR(CONTEXT_CLIENT, "EffectDescriptionImpl::ReadFileContentsToString: error reading file info: " << fileName); + LOG_ERROR(CONTEXT_CLIENT, "EffectDescriptionImpl::ReadFileContentsToString: error reading file info: {}", fileName); return false; } @@ -179,7 +179,7 @@ namespace ramses::internal fileContents = &charVector[0]; return true; } - LOG_ERROR(CONTEXT_CLIENT, "EffectDescriptionImpl::ReadFileContentsToString: error reading file contents: " << fileName); + LOG_ERROR(CONTEXT_CLIENT, "EffectDescriptionImpl::ReadFileContentsToString: error reading file contents: {}", fileName); return false; } } diff --git a/src/client/impl/EffectImpl.cpp b/src/client/impl/EffectImpl.cpp index 722d0aaf1..adb317f00 100644 --- a/src/client/impl/EffectImpl.cpp +++ b/src/client/impl/EffectImpl.cpp @@ -184,7 +184,7 @@ namespace ramses::internal { if (index >= getUniformInputCount()) { - LOG_ERROR_P(CONTEXT_CLIENT, "Effect: getUniformInput failed, index out of range!"); + LOG_ERROR(CONTEXT_CLIENT, "Effect: getUniformInput failed, index out of range!"); return std::nullopt; } @@ -198,7 +198,7 @@ namespace ramses::internal { if (index >= getAttributeInputCount()) { - LOG_ERROR_P(CONTEXT_CLIENT, "Effect: getAttributeInput failed, index out of range!"); + LOG_ERROR(CONTEXT_CLIENT, "Effect: getAttributeInput failed, index out of range!"); return std::nullopt; } @@ -213,7 +213,7 @@ namespace ramses::internal const size_t index = GetEffectInputIndex(m_effectUniformInputs, inputName); if (index == InvalidInputIndex) { - LOG_ERROR_P(CONTEXT_CLIENT, "Effect: findUniformInput failed, uniform input '{}' could not be found in effect '{}'", inputName, getName()); + LOG_ERROR(CONTEXT_CLIENT, "Effect: findUniformInput failed, uniform input '{}' could not be found in effect '{}'", inputName, getName()); return std::nullopt; } @@ -228,7 +228,7 @@ namespace ramses::internal const size_t index = GetEffectInputIndex(m_effectAttributeInputs, inputName); if (index == InvalidInputIndex) { - LOG_ERROR_P(CONTEXT_CLIENT, "Effect: findAttributeInput failed, attribute input '{}' could not be found in effect '{}'", inputName, getName()); + LOG_ERROR(CONTEXT_CLIENT, "Effect: findAttributeInput failed, attribute input '{}' could not be found in effect '{}'", inputName, getName()); return std::nullopt; } @@ -243,7 +243,7 @@ namespace ramses::internal const size_t index = FindEffectInputIndex(m_effectUniformInputs, EffectInputSemanticUtils::GetEffectInputSemanticInternal(uniformSemantic)); if (index == InvalidInputIndex) { - LOG_ERROR_P(CONTEXT_CLIENT, "Effect: findUniformInput failed, semantic is not defined in effect!"); + LOG_ERROR(CONTEXT_CLIENT, "Effect: findUniformInput failed, semantic is not defined in effect!"); return std::nullopt; } @@ -258,7 +258,7 @@ namespace ramses::internal const size_t index = FindEffectInputIndex(m_effectAttributeInputs, EffectInputSemanticUtils::GetEffectInputSemanticInternal(attributeSemantic)); if (index == InvalidInputIndex) { - LOG_ERROR_P(CONTEXT_CLIENT, "Effect: findAttributeInput failed, semantic not defined in effect!"); + LOG_ERROR(CONTEXT_CLIENT, "Effect: findAttributeInput failed, semantic not defined in effect!"); return std::nullopt; } diff --git a/src/client/impl/RamsesClientImpl.cpp b/src/client/impl/RamsesClientImpl.cpp index a1d36cccb..e817529bd 100644 --- a/src/client/impl/RamsesClientImpl.cpp +++ b/src/client/impl/RamsesClientImpl.cpp @@ -130,7 +130,7 @@ namespace ramses::internal { if (!sceneConfig.getSceneId().isValid()) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::createScene: invalid sceneId"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::createScene: invalid sceneId"); return nullptr; } @@ -230,20 +230,20 @@ namespace ramses::internal ramses::internal::IInputStream& inputStream, const SceneConfigImpl& config) { - LOG_TRACE(ramses::internal::CONTEXT_CLIENT, "RamsesClient::prepareSceneFromInputStream: start loading scene from input stream"); + LOG_TRACE(CONTEXT_CLIENT, "RamsesClient::prepareSceneFromInputStream: start loading scene from input stream"); ramses::internal::SceneCreationInformation createInfo; ramses::internal::ScenePersistation::ReadSceneMetadataFromStream(inputStream, createInfo); if (config.getSceneId().isValid()) { const auto newSceneId = ramses::internal::SceneId(config.getSceneId().getValue()); - LOG_INFO_P(ramses::internal::CONTEXT_CLIENT, "RamsesClient::{}: Override stored scene id: {} with user provided scene id: {}", caller, createInfo.m_id, newSceneId); + LOG_INFO(CONTEXT_CLIENT, "RamsesClient::{}: Override stored scene id: {} with user provided scene id: {}", caller, createInfo.m_id, newSceneId); createInfo.m_id = newSceneId; } const ramses::internal::SceneSizeInformation& sizeInformation = createInfo.m_sizeInfo; const ramses::internal::SceneInfo sceneInfo(createInfo.m_id, createInfo.m_name); - LOG_DEBUG(ramses::internal::CONTEXT_CLIENT, "RamsesClient::prepareSceneFromInputStream: scene to be loaded has " << sizeInformation); + LOG_DEBUG(CONTEXT_CLIENT, "RamsesClient::prepareSceneFromInputStream: scene to be loaded has {}", sizeInformation); ramses::internal::ClientScene* internalScene = nullptr; { @@ -259,30 +259,30 @@ namespace ramses::internal // need first to create the pimpl, so that internal framework components know the new scene if (config.getPublicationMode() == EScenePublicationMode::LocalOnly) { - LOG_INFO(ramses::internal::CONTEXT_CLIENT, "RamsesClient::" << caller << ": Mark file loaded from " << filename << " with sceneId " << createInfo.m_id << " as local only"); + LOG_INFO(CONTEXT_CLIENT, "RamsesClient::{}: Mark file loaded from {} with sceneId {} as local only", caller, filename, createInfo.m_id); } else { - LOG_INFO(ramses::internal::CONTEXT_CLIENT, "RamsesClient::" << caller << ": Mark file loaded from " << filename << " with sceneId " << createInfo.m_id << " as local and remote"); + LOG_INFO(CONTEXT_CLIENT, "RamsesClient::{}: Mark file loaded from {} with sceneId {} as local and remote", caller, filename, createInfo.m_id); } auto impl = std::make_unique(*internalScene, config, *m_hlClient); // now the scene is registered, so it's possible to load the low level content into the scene - LOG_TRACE(ramses::internal::CONTEXT_CLIENT, " Reading low level scene from stream"); + LOG_TRACE(CONTEXT_CLIENT, " Reading low level scene from stream"); ramses::internal::ScenePersistation::ReadSceneFromStream(inputStream, *internalScene); - LOG_TRACE(ramses::internal::CONTEXT_CLIENT, " Deserializing high level scene objects from stream"); + LOG_TRACE(CONTEXT_CLIENT, " Deserializing high level scene objects from stream"); DeserializationContext deserializationContext(config); SerializationHelper::DeserializeObjectID(inputStream); if (!impl->deserialize(inputStream, deserializationContext)) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, " Failed to deserialize high level scene:"); - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, m_framework.getErrorReporting().getError().value_or(Issue{}).message); + LOG_ERROR(CONTEXT_CLIENT, " Failed to deserialize high level scene:"); + LOG_ERROR(CONTEXT_CLIENT, m_framework.getErrorReporting().getError().value_or(Issue{}).message); return nullptr; } - LOG_TRACE(ramses::internal::CONTEXT_CLIENT, " Done with preparing scene from input stream."); + LOG_TRACE(CONTEXT_CLIENT, " Done with preparing scene from input stream."); return SceneOwningPtr{ new ramses::Scene{ std::move(impl) }, [](ramses::Scene* s) { delete s; } }; } @@ -293,13 +293,13 @@ namespace ramses::internal ramses::internal::IInputStream& inputStream = cconfig.streamContainer->getStream(); if (inputStream.getState() != ramses::internal::EStatus::Ok) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::" << cconfig.caller << ": failed to open scene source " << cconfig.dataSource); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::{}: failed to open scene source {}", cconfig.caller, cconfig.dataSource); return nullptr; } if (!ReadRamsesVersionAndPrintWarningOnMismatch(inputStream, "scene file", getFramework().getFeatureLevel())) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::" << cconfig.caller << ": failed to read from scene source " << cconfig.dataSource); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::{}: failed to read from scene source {}", cconfig.caller, cconfig.dataSource); return nullptr; } @@ -308,8 +308,8 @@ namespace ramses::internal inputStream >> exporter; inputStream >> metadataString; - LOG_INFO_P(CONTEXT_CLIENT, "Metadata: '{}'", metadataString); - LOG_INFO_P(CONTEXT_CLIENT, "Exporter version: {}.{}.{} (file format version {})", exporter.major, exporter.minor, exporter.patch, exporter.fileFormat); + LOG_INFO(CONTEXT_CLIENT, "Metadata: '{}'", metadataString); + LOG_INFO(CONTEXT_CLIENT, "Exporter version: {}.{}.{} (file format version {})", exporter.major, exporter.minor, exporter.patch, exporter.fileFormat); uint64_t sceneObjectStart = 0; uint64_t llResourceStart = 0; @@ -324,7 +324,7 @@ namespace ramses::internal if (inputStream.getState() != ramses::internal::EStatus::Ok) { - LOG_ERROR_P(ramses::internal::CONTEXT_CLIENT, "RamsesClient::{}: Failed reading scene from file: {} ", cconfig.caller, inputStream.getState()); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::{}: Failed reading scene from file: {} ", cconfig.caller, inputStream.getState()); return nullptr; } @@ -338,7 +338,7 @@ namespace ramses::internal } if (!scene) { - LOG_ERROR_P(ramses::internal::CONTEXT_CLIENT, "RamsesClient::{}: scene creation for '{}' failed", cconfig.caller, cconfig.dataSource); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::{}: scene creation for '{}' failed", cconfig.caller, cconfig.dataSource); return nullptr; } @@ -349,7 +349,7 @@ namespace ramses::internal const ramses::internal::SceneFileHandle fileHandle = m_appLogic.addResourceFile(cconfig.streamContainer, loadedTOC); scene->m_impl.setSceneFileHandle(fileHandle); - LOG_INFO_P(CONTEXT_CLIENT, "RamsesClient::{}: Source '{}' has handle {}", cconfig.caller, cconfig.dataSource, fileHandle); + LOG_INFO(CONTEXT_CLIENT, "RamsesClient::{}: Source '{}' has handle {}", cconfig.caller, cconfig.dataSource, fileHandle); return scene; } @@ -358,7 +358,7 @@ namespace ramses::internal { if (fileName.empty()) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::loadSceneFromFile: filename may not be empty"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::loadSceneFromFile: filename may not be empty"); return nullptr; } @@ -374,12 +374,12 @@ namespace ramses::internal { if (!data) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::loadSceneFromMemory: data may not be null"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::loadSceneFromMemory: data may not be null"); return nullptr; } if (size == 0) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::loadSceneFromMemory: size may not be 0"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::loadSceneFromMemory: size may not be 0"); return nullptr; } @@ -396,12 +396,12 @@ namespace ramses::internal { if (fd <= 0) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::loadSceneFromFileDescriptor: filedescriptor must be valid " << fd); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::loadSceneFromFileDescriptor: filedescriptor must be valid {}", fd); return nullptr; } if (length == 0) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::loadSceneFromFileDescriptor: length may not be 0"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::loadSceneFromFileDescriptor: length may not be 0"); return nullptr; } @@ -425,7 +425,7 @@ namespace ramses::internal finalizeLoadedScene(std::move(scene)); const uint64_t end = ramses::internal::PlatformTime::GetMillisecondsMonotonic(); - LOG_INFO(ramses::internal::CONTEXT_CLIENT, "RamsesClient::" << cconfig.caller << " ramses::Scene loaded from '" << cconfig.dataSource << "' in " << (end - start) << " ms"); + LOG_INFO(CONTEXT_CLIENT, "RamsesClient::{} ramses::Scene loaded from '{}' in {} ms", cconfig.caller, cconfig.dataSource, end - start); return scenePtr; } @@ -447,7 +447,7 @@ namespace ramses::internal ramses::internal::RamsesVersion::VersionInfo readVersion; if (!ramses::internal::RamsesVersion::ReadFromStream(streamContainer.getStream(), readVersion, detectedFeatureLevel)) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::GetFeatureLevelFromSceneFile: failed to read RAMSES version and feature level from '" << desc << "'."); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::GetFeatureLevelFromSceneFile: failed to read RAMSES version and feature level from '{}'.", desc); return false; } @@ -464,12 +464,12 @@ namespace ramses::internal { if (fd <= 0) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::GetFeatureLevelFromFile: filedescriptor must be valid " << fd); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::GetFeatureLevelFromFile: filedescriptor must be valid {}", fd); return false; } if (length == 0u) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::GetFeatureLevelFromFile: length may not be 0"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::GetFeatureLevelFromFile: length may not be 0"); return false; } @@ -484,22 +484,22 @@ namespace ramses::internal EFeatureLevel featureLevelFromFile = EFeatureLevel_01; if (!ramses::internal::RamsesVersion::ReadFromStream(inputStream, readVersion, featureLevelFromFile)) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::ReadRamsesVersionAndPrintWarningOnMismatch: failed to read RAMSES version for " << verboseFileName << ", file probably corrupt. Loading aborted."); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::ReadRamsesVersionAndPrintWarningOnMismatch: failed to read RAMSES version for {}, file probably corrupt. Loading aborted.", verboseFileName); return false; } - LOG_INFO(ramses::internal::CONTEXT_CLIENT, "RAMSES version in file '" << verboseFileName << "': [" << readVersion.versionString << "]; GitHash: [" << readVersion.gitHash << "]; FeatureLevel: [" << featureLevelFromFile << "];"); + LOG_INFO(CONTEXT_CLIENT, "RAMSES version in file '{}': [{}]; GitHash: [{}]; FeatureLevel: [{}];", verboseFileName, readVersion.versionString, readVersion.gitHash, featureLevelFromFile); if (!ramses::internal::RamsesVersion::MatchesMajorMinor(::ramses_sdk::RAMSES_SDK_PROJECT_VERSION_MAJOR_INT, ::ramses_sdk::RAMSES_SDK_PROJECT_VERSION_MINOR_INT, readVersion)) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::ReadRamsesVersionAndPrintWarningOnMismatch: Version of file " << verboseFileName << " does not match MAJOR.MINOR of this build. Cannot load the file."); - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "SDK version of loader: [" << ::ramses_sdk::RAMSES_SDK_RAMSES_VERSION << "]; GitHash: [" << ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_HASH << "]"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::ReadRamsesVersionAndPrintWarningOnMismatch: Version of file {} does not match MAJOR.MINOR of this build. Cannot load the file.", verboseFileName); + LOG_ERROR(CONTEXT_CLIENT, "SDK version of loader: [{}]; GitHash: [{}]", ::ramses_sdk::RAMSES_SDK_RAMSES_VERSION, ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_HASH); return false; } if (featureLevelFromFile != featureLevel) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::ReadRamsesVersionAndPrintWarningOnMismatch: Feature level of file '" << verboseFileName - << "' is " << featureLevelFromFile << " which does not match feature level of this Ramses instance (" << featureLevel << "). Cannot load the file."); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::ReadRamsesVersionAndPrintWarningOnMismatch: Feature level of file '{}' is {} which does not match feature level of this Ramses instance({}).Cannot load the file.", + verboseFileName, featureLevelFromFile, featureLevel); return false; } @@ -556,14 +556,14 @@ namespace ramses::internal const uint64_t start = ramses::internal::PlatformTime::GetMillisecondsMonotonic(); finalizeLoadedScene(std::move(sceneStatus.scene)); const uint64_t end = ramses::internal::PlatformTime::GetMillisecondsMonotonic(); - LOG_INFO(ramses::internal::CONTEXT_CLIENT, "RamsesClient::dispatchEvents(sceneFileLoadSucceeded): Synchronous postprocessing of scene loaded from '" << - sceneStatus.sceneFilename << "' (sceneName: " << scene->getName() << ", sceneId " << scene->getSceneId() << ") in " << (end - start) << " ms"); + LOG_INFO(CONTEXT_CLIENT, "RamsesClient::dispatchEvents(sceneFileLoadSucceeded): Synchronous postprocessing of scene loaded from '{}' (sceneName: {}, sceneId {}) in {} ms", + sceneStatus.sceneFilename, scene->getName(), scene->getSceneId(), end - start); clientEventHandler.sceneFileLoadSucceeded(sceneStatus.sceneFilename.c_str(), scene); } else { - LOG_INFO(ramses::internal::CONTEXT_CLIENT, "RamsesClient::dispatchEvents(sceneFileLoadFailed): " << sceneStatus.sceneFilename); + LOG_INFO(CONTEXT_CLIENT, "RamsesClient::dispatchEvents(sceneFileLoadFailed): {}", sceneStatus.sceneFilename); clientEventHandler.sceneFileLoadFailed(sceneStatus.sceneFilename.c_str()); } } @@ -578,17 +578,16 @@ namespace ramses::internal auto sr = findSceneReference(sceneId_t{ rendererEvent.masterSceneId.getValue() }, sceneId_t{ rendererEvent.referencedScene.getValue() }); if (sr) { - LOG_INFO(CONTEXT_CLIENT, "RamsesClient::dispatchEvents master:reference scene state changed: " - << rendererEvent.masterSceneId << ":" << rendererEvent.referencedScene << " " << ramses::internal::EnumToString(rendererEvent.sceneState)); + LOG_INFO(CONTEXT_CLIENT, "RamsesClient::dispatchEvents master:reference scene state changed: {}:{} {}", + rendererEvent.masterSceneId, rendererEvent.referencedScene, ramses::internal::EnumToString(rendererEvent.sceneState)); sr->impl().setReportedState(rendererEvent.sceneState); clientEventHandler.sceneReferenceStateChanged(*sr, rendererEvent.sceneState); } else { - LOG_WARN(CONTEXT_CLIENT, - "RamsesClientImpl::dispatchEvents: did not find SceneReference for a SceneStateChanged event: " - << rendererEvent.masterSceneId << " " << rendererEvent.referencedScene << " " << ramses::internal::EnumToString(rendererEvent.sceneState)); + LOG_WARN(CONTEXT_CLIENT, "RamsesClientImpl::dispatchEvents: did not find SceneReference for a SceneStateChanged event: {} {} {}", + rendererEvent.masterSceneId, rendererEvent.referencedScene, ramses::internal::EnumToString(rendererEvent.sceneState)); } break; } @@ -601,9 +600,8 @@ namespace ramses::internal } else { - LOG_WARN(CONTEXT_CLIENT, - "RamsesClientImpl::dispatchEvents: did not find SceneReference for a SceneFlushed event: " - << rendererEvent.masterSceneId << " " << rendererEvent.referencedScene << " " << rendererEvent.tag); + LOG_WARN(CONTEXT_CLIENT, "RamsesClientImpl::dispatchEvents: did not find SceneReference for a SceneFlushed event: {} {} {}", + rendererEvent.masterSceneId, rendererEvent.referencedScene, rendererEvent.tag); } break; } @@ -634,8 +632,8 @@ namespace ramses::internal if (scene) { - LOG_INFO(ramses::internal::CONTEXT_CLIENT, "RamsesClient::loadSceneFromFileAsync: ramses::Scene loaded from '" << m_cconfig.dataSource << - "' (sceneName: " << scene->getName() << ", sceneId " << scene->getSceneId() << ") in " << (end - start) << " ms"); + LOG_INFO(CONTEXT_CLIENT, "RamsesClient::loadSceneFromFileAsync: ramses::Scene loaded from '{}' (sceneName: {}, sceneId {}) in {} ms", + m_cconfig.dataSource, scene->getName(), scene->getSceneId(), end - start); } ramses::internal::PlatformGuard g(m_client.m_clientLock); @@ -705,7 +703,7 @@ namespace ramses::internal ramses::internal::ManagedResource RamsesClientImpl::manageResource(const ramses::internal::IResource* res) { ramses::internal::ManagedResource managedRes = m_appLogic.addResource(res); - LOG_HL_CLIENT_API_STR("Created resource with internal hash " << managedRes->getHash() << ", name: " << managedRes->getName()); + LOG_HL_CLIENT_API_STR("Created resource with internal hash {}, name: {}", managedRes->getHash(), managedRes->getName()); return managedRes; } @@ -745,7 +743,7 @@ namespace ramses::internal { if (0u == numElements || nullptr == arrayData) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClientImpl::createManagedArrayResource Array resource must have element count > 0 and data must not be nullptr!"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClientImpl::createManagedArrayResource Array resource must have element count > 0 and data must not be nullptr!"); return {}; } @@ -765,13 +763,13 @@ namespace ramses::internal { if (!TextureUtils::TextureParametersValid(width, height, depth, static_cast(mipLevelData.size())) || !TextureUtils::MipDataValid(width, height, depth, mipLevelData, format)) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::createTexture: invalid parameters"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::createTexture: invalid parameters"); return {}; } if (generateMipChain && (!FormatSupportsMipChainGeneration(format) || (mipLevelData.size() > 1))) { - LOG_WARN(ramses::internal::CONTEXT_CLIENT, "RamsesClient::createTexture: cannot auto generate mipmaps when custom mipmap data provided or unsupported format used"); + LOG_WARN(CONTEXT_CLIENT, "RamsesClient::createTexture: cannot auto generate mipmaps when custom mipmap data provided or unsupported format used"); generateMipChain = false; } @@ -810,7 +808,7 @@ namespace ramses::internal if (!effectResource) { errorMessages = effectBlock.getEffectErrorMessages(); - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesClient::createEffect Failed to create effect resource (name: '" << name << "') :\n " << effectBlock.getEffectErrorMessages()); + LOG_ERROR(CONTEXT_CLIENT, "RamsesClient::createEffect Failed to create effect resource (name: '{}') :\n {}", name, effectBlock.getEffectErrorMessages()); return {}; } return manageResource(effectResource); diff --git a/src/client/impl/RamsesClientTypesImpl.h b/src/client/impl/RamsesClientTypesImpl.h index 5f138c95a..4f6e74466 100644 --- a/src/client/impl/RamsesClientTypesImpl.h +++ b/src/client/impl/RamsesClientTypesImpl.h @@ -55,12 +55,6 @@ namespace ramses "TextureSamplerCube", "TextureSamplerExternal", }; - - namespace internal - { - struct SceneObjectRegistryHandleTag {}; - using SceneObjectRegistryHandle = ramses::internal::TypedMemoryHandle; - } } MAKE_ENUM_CLASS_PRINTABLE(ramses::EDataType, "EDataType", ramses::DataTypeNames, ramses::EDataType::TextureSamplerExternal); diff --git a/src/client/impl/RenderBufferImpl.cpp b/src/client/impl/RenderBufferImpl.cpp index 88914a70d..552dd53f0 100644 --- a/src/client/impl/RenderBufferImpl.cpp +++ b/src/client/impl/RenderBufferImpl.cpp @@ -7,9 +7,10 @@ // ------------------------------------------------------------------------- #include "impl/RenderBufferImpl.h" -#include "internal/SceneGraph/Scene/ClientScene.h" #include "impl/TextureUtils.h" #include "impl/TextureEnumsImpl.h" +#include "impl/ErrorReporting.h" +#include "internal/SceneGraph/Scene/ClientScene.h" namespace ramses::internal { @@ -36,13 +37,11 @@ namespace ramses::internal uint32_t RenderBufferImpl::getWidth() const { - assert(m_renderBufferHandle.isValid()); return getIScene().getRenderBuffer(m_renderBufferHandle).width; } uint32_t RenderBufferImpl::getHeight() const { - assert(m_renderBufferHandle.isValid()); return getIScene().getRenderBuffer(m_renderBufferHandle).height; } @@ -58,7 +57,6 @@ namespace ramses::internal uint32_t RenderBufferImpl::getSampleCount() const { - assert(m_renderBufferHandle.isValid()); return getIScene().getRenderBuffer(m_renderBufferHandle).sampleCount; } @@ -185,4 +183,16 @@ namespace ramses::internal return report.add(EIssueType::Warning, rbDesc.release(), &getRamsesObject()); } } + + bool RenderBufferImpl::setProperties(uint32_t width, uint32_t height, uint32_t sampleCount) + { + if (width == 0 || height == 0) + { + getErrorReporting().set("RenderBuffer::setProperties: width and height cannot be zero", *this); + return false; + } + + getIScene().setRenderBufferProperties(m_renderBufferHandle, width, height, sampleCount); + return true; + } } diff --git a/src/client/impl/RenderBufferImpl.h b/src/client/impl/RenderBufferImpl.h index 4ede5f871..f2e1748a8 100644 --- a/src/client/impl/RenderBufferImpl.h +++ b/src/client/impl/RenderBufferImpl.h @@ -39,6 +39,8 @@ namespace ramses::internal [[nodiscard]] ERenderBufferAccessMode getAccessMode() const; [[nodiscard]] uint32_t getSampleCount() const; + bool setProperties(uint32_t width, uint32_t height, uint32_t sampleCount); + [[nodiscard]] ramses::internal::RenderBufferHandle getRenderBufferHandle() const; private: diff --git a/src/client/impl/RenderTargetDescriptionImpl.cpp b/src/client/impl/RenderTargetDescriptionImpl.cpp index a8d83be25..a55b4f323 100644 --- a/src/client/impl/RenderTargetDescriptionImpl.cpp +++ b/src/client/impl/RenderTargetDescriptionImpl.cpp @@ -7,9 +7,9 @@ // ------------------------------------------------------------------------- #include "impl/RenderTargetDescriptionImpl.h" -#include "ramses/client/SceneObjectIterator.h" #include "impl/SceneImpl.h" #include "impl/RenderBufferImpl.h" +#include "ramses/client/SceneObjectIterator.h" #include "internal/SceneGraph/Scene/ClientScene.h" namespace ramses::internal diff --git a/src/client/impl/RenderTargetImpl.cpp b/src/client/impl/RenderTargetImpl.cpp index 530e281d8..96496db8c 100644 --- a/src/client/impl/RenderTargetImpl.cpp +++ b/src/client/impl/RenderTargetImpl.cpp @@ -90,4 +90,26 @@ namespace ramses::internal return true; } + + void RenderTargetImpl::onValidate(ValidationReportImpl& report) const + { + SceneObjectImpl::onValidate(report); + + const auto& iscene = getIScene(); + const uint32_t rbCount = iscene.getRenderTargetRenderBufferCount(m_renderTargetHandle); + assert(rbCount > 0u); + const auto& firstRB = iscene.getRenderBuffer(iscene.getRenderTargetRenderBuffer(m_renderTargetHandle, 0u)); + + for (uint32_t i = 1u; i < rbCount; ++i) + { + const auto& rb = iscene.getRenderBuffer(iscene.getRenderTargetRenderBuffer(m_renderTargetHandle, i)); + if (firstRB.width != rb.width || + firstRB.height != rb.height || + firstRB.sampleCount != rb.sampleCount) + { + report.add(EIssueType::Error, + "RenderTarget uses render buffers with mismatching resolution and/or sample count. This RenderTarget cannot be used and attempt to flush scene will fail.", &getRamsesObject()); + } + } + } } diff --git a/src/client/impl/RenderTargetImpl.h b/src/client/impl/RenderTargetImpl.h index bf4a9f4af..a335b795d 100644 --- a/src/client/impl/RenderTargetImpl.h +++ b/src/client/impl/RenderTargetImpl.h @@ -31,6 +31,8 @@ namespace ramses::internal bool serialize(ramses::internal::IOutputStream& outStream, SerializationContext& serializationContext) const override; bool deserialize(ramses::internal::IInputStream& inStream, DeserializationContext& serializationContext) override; + void onValidate(ValidationReportImpl& report) const override; + [[nodiscard]] uint32_t getWidth() const; [[nodiscard]] uint32_t getHeight() const; diff --git a/src/client/impl/ResourceImpl.cpp b/src/client/impl/ResourceImpl.cpp index 73d3457fb..b333809e3 100644 --- a/src/client/impl/ResourceImpl.cpp +++ b/src/client/impl/ResourceImpl.cpp @@ -42,7 +42,7 @@ namespace ramses::internal ResourceImpl::~ResourceImpl() { - LOG_DEBUG_P(CONTEXT_FRAMEWORK, "Destroy resource type {}, hl {}, ll {}", getType(), m_resourceId, getLowlevelResourceHash()); + LOG_DEBUG(CONTEXT_FRAMEWORK, "Destroy resource type {}, hl {}, ll {}", getType(), m_resourceId, getLowlevelResourceHash()); } resourceId_t ResourceImpl::getResourceId() const diff --git a/src/client/impl/SaveFileConfig.cpp b/src/client/impl/SaveFileConfig.cpp index cf8669ab3..41e5f55e2 100644 --- a/src/client/impl/SaveFileConfig.cpp +++ b/src/client/impl/SaveFileConfig.cpp @@ -43,11 +43,6 @@ namespace ramses m_impl->setExporterVersion(major, minor, patch, fileFormatVersion); } - void SaveFileConfig::setValidationEnabled(bool validationEnabled) - { - m_impl->setValidationEnabled(validationEnabled); - } - void SaveFileConfig::setLuaSavingMode(ELuaSavingMode mode) { m_impl->setLuaSavingMode(mode); diff --git a/src/client/impl/SaveFileConfigImpl.cpp b/src/client/impl/SaveFileConfigImpl.cpp index 65e878e42..b44a96530 100644 --- a/src/client/impl/SaveFileConfigImpl.cpp +++ b/src/client/impl/SaveFileConfigImpl.cpp @@ -24,20 +24,6 @@ namespace ramses::internal m_exporterVersion.fileFormat = fileFormatVersion; } - void SaveFileConfigImpl::setValidationEnabled(bool validationEnabled) - { - if (validationEnabled == false) - { - LOG_INFO_P(CONTEXT_CLIENT, "Validation before saving was disabled during save*() calls! Possible content issues will not yield further warnings."); - } - m_validationEnabled = validationEnabled; - } - - bool SaveFileConfigImpl::getValidationEnabled() const - { - return m_validationEnabled; - } - const SaveFileConfigImpl::ExporterVersion& SaveFileConfigImpl::getExporterVersion() const { return m_exporterVersion; diff --git a/src/client/impl/SaveFileConfigImpl.h b/src/client/impl/SaveFileConfigImpl.h index f2bc9e6c2..5acefae25 100644 --- a/src/client/impl/SaveFileConfigImpl.h +++ b/src/client/impl/SaveFileConfigImpl.h @@ -27,7 +27,6 @@ namespace ramses::internal public: void setMetadataString(std::string_view metadata); void setExporterVersion(uint32_t major, uint32_t minor, uint32_t patch, uint32_t fileFormatVersion); - void setValidationEnabled(bool validationEnabled); void setLuaSavingMode(ELuaSavingMode mode); void setCompressionEnabled(bool compressionEnabled); @@ -41,14 +40,12 @@ namespace ramses::internal [[nodiscard]] const std::string& getMetadataString() const; [[nodiscard]] const ExporterVersion& getExporterVersion() const; - [[nodiscard]] bool getValidationEnabled() const; [[nodiscard]] ELuaSavingMode getLuaSavingMode() const; [[nodiscard]] bool getCompressionEnabled() const; private: std::string m_metadata; ExporterVersion m_exporterVersion; - bool m_validationEnabled = true; bool m_compressionEnabled = false; ELuaSavingMode m_luaSavingMode = ELuaSavingMode::SourceAndByteCode; }; @@ -71,13 +68,12 @@ template <> struct fmt::formatter : public template constexpr auto format(const ramses::internal::SaveFileConfigImpl& c, FormatContext& ctx) { const auto& exporter = c.getExporterVersion(); - return fmt::format_to(ctx.out(), "'{}' exporter:{}.{}.{}.{} validate:{} compress:{} lua:{}", + return fmt::format_to(ctx.out(), "'{}' exporter:{}.{}.{}.{} compress:{} lua:{}", c.getMetadataString(), exporter.major, exporter.minor, exporter.patch, exporter.fileFormat, - c.getValidationEnabled(), c.getCompressionEnabled(), c.getLuaSavingMode() ); diff --git a/src/client/impl/Scene.cpp b/src/client/impl/Scene.cpp index 69f263c46..db773a400 100644 --- a/src/client/impl/Scene.cpp +++ b/src/client/impl/Scene.cpp @@ -118,7 +118,7 @@ namespace ramses return m_impl.getSceneId(); } - bool Scene::saveToFile(std::string_view fileName, const SaveFileConfig& config) const + bool Scene::saveToFile(std::string_view fileName, const SaveFileConfig& config) { const auto status = m_impl.saveToFile(fileName, config.impl()); LOG_HL_CLIENT_API2(status, fileName, config.impl()); diff --git a/src/client/impl/SceneDumper.cpp b/src/client/impl/SceneDumper.cpp index 729766684..ea4b154f9 100644 --- a/src/client/impl/SceneDumper.cpp +++ b/src/client/impl/SceneDumper.cpp @@ -43,6 +43,7 @@ #include "impl/BlitPassImpl.h" #include "impl/EffectImpl.h" #include "impl/SceneImpl.h" +#include "impl/logic/LogicEngineImpl.h" #include "internal/SceneGraph/Scene/ClientScene.h" #include "internal/SceneGraph/SceneAPI/Handles.h" @@ -93,6 +94,7 @@ namespace ramses::internal { setupMaps(); + markRequiredLogic(); RenderPassSet requiredRenderPasses = markRequiredScreenRenderPasses(); while (requiredRenderPasses.size() > 0) { @@ -195,9 +197,9 @@ namespace ramses::internal } else { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, - "SceneDumper::setupRenderBufferSetMap Could not lookup render buffer handle: " - << blitPassData.sourceRenderBuffer << " !!!"); + LOG_ERROR(CONTEXT_CLIENT, + "SceneDumper::setupRenderBufferSetMap Could not lookup render buffer handle: {} !!!", + blitPassData.sourceRenderBuffer); assert(false); } } @@ -213,6 +215,16 @@ namespace ramses::internal return false; } + void SceneDumper::markRequiredLogic() + { + SceneObjectRegistryIterator objectIterator(m_objectRegistry, ERamsesObjectType::LogicEngine); + while (const auto* obj = objectIterator.getNext()) + { + addToRequiredObjects(obj->impl()); + // Logic objects are not part of the registry + } + } + SceneDumper::RenderPassSet SceneDumper::markRequiredScreenRenderPasses() { RenderPassSet requiredRenderPasses; @@ -359,9 +371,9 @@ namespace ramses::internal else { LOG_ERROR( - ramses::internal::CONTEXT_CLIENT, - "SceneDumper::markRequiredTextureSampler Could not lookup texture sampler handle: " - << textureSamplerHandle << " !!!"); + CONTEXT_CLIENT, + "SceneDumper::markRequiredTextureSampler Could not lookup texture sampler handle: {} !!!", + textureSamplerHandle); assert(false); } } @@ -481,9 +493,9 @@ namespace ramses::internal } else { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, - "SceneDumper::markRequiredResourcesFromHash Could not lookup resource content hash: " - << requiredResourceHash << " !!!"); + LOG_ERROR(CONTEXT_CLIENT, + "SceneDumper::markRequiredResourcesFromHash Could not lookup resource content hash: {} !!!", + requiredResourceHash); assert(false); } } @@ -521,8 +533,8 @@ namespace ramses::internal else { LOG_ERROR(ramses::internal::CONTEXT_CLIENT, - "SceneDumper::getRequiredRenderBuffer Could not lookup render buffer handle: " - << renderBufferHandle << " !!!"); + "SceneDumper::getRequiredRenderBuffer Could not lookup render buffer handle: {} !!!", + renderBufferHandle); assert(false); } } @@ -552,8 +564,8 @@ namespace ramses::internal else { LOG_ERROR(ramses::internal::CONTEXT_CLIENT, - "SceneDumper::getRequiredTextureBuffers Could not lookup texture buffer handle: " - << textureBufferHandle << " !!!"); + "SceneDumper::getRequiredTextureBuffers Could not lookup texture buffer handle: {} !!!", + textureBufferHandle); assert(false); } } diff --git a/src/client/impl/SceneDumper.h b/src/client/impl/SceneDumper.h index e41d135dd..3480a47f0 100644 --- a/src/client/impl/SceneDumper.h +++ b/src/client/impl/SceneDumper.h @@ -94,6 +94,7 @@ namespace ramses::internal bool addToRequiredObjects(const RamsesObjectImpl& object); + void markRequiredLogic(); RenderPassSet markRequiredScreenRenderPasses(); RenderPassSet getRequiredRenderPasses(const RenderBufferSet& requiredRenderBuffers); RenderPassSet getRequiredRenderPasses(); diff --git a/src/client/impl/SceneFactory.cpp b/src/client/impl/SceneFactory.cpp index 7206ca6ac..28f41af2c 100644 --- a/src/client/impl/SceneFactory.cpp +++ b/src/client/impl/SceneFactory.cpp @@ -16,7 +16,7 @@ namespace ramses::internal { if (m_scenes.count(sceneInfo.sceneID) != 0) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "SceneFactory::createScene: scene with id " << sceneInfo.sceneID << " already exists, scene ID must be unique!"); + LOG_ERROR(CONTEXT_CLIENT, "SceneFactory::createScene: scene with id {} already exists, scene ID must be unique!", sceneInfo.sceneID); return nullptr; } diff --git a/src/client/impl/SceneImpl.cpp b/src/client/impl/SceneImpl.cpp index d8121baba..d71776acf 100644 --- a/src/client/impl/SceneImpl.cpp +++ b/src/client/impl/SceneImpl.cpp @@ -115,8 +115,7 @@ namespace ramses::internal , m_futurePublicationMode(sceneConfig.getPublicationMode()) , m_hlClient(ramsesClient) { - LOG_INFO(ramses::internal::CONTEXT_CLIENT, "Scene::Scene: sceneId " << scene.getSceneId() << - ", publicationMode " << (sceneConfig.getPublicationMode() == EScenePublicationMode::LocalAndRemote ? "LocalAndRemote" : "LocalOnly")); + LOG_INFO(CONTEXT_CLIENT, "Scene::Scene: sceneId {}, publicationMode {}", scene.getSceneId(), sceneConfig.getPublicationMode() == EScenePublicationMode::LocalAndRemote ? "LocalAndRemote" : "LocalOnly"); getClientImpl().getFramework().getPeriodicLogger().registerStatisticCollectionScene(m_scene.getSceneId(), m_scene.getStatisticCollection()); const bool enableLocalOnlyOptimization = sceneConfig.getPublicationMode() == EScenePublicationMode::LocalOnly; getClientImpl().getClientApplication().createScene(scene, enableLocalOnlyOptimization); @@ -316,7 +315,7 @@ namespace ramses::internal inStream >> m_lastSceneObjectId.getReference(); - LOG_DEBUG_F(ramses::internal::CONTEXT_PROFILING, ([&](ramses::internal::StringOutputStream& sos) { + LOG_DEBUG_F(CONTEXT_PROFILING, ([&](ramses::internal::StringOutputStream& sos) { sos << "SceneImpl::deserialize: HL scene object counts for SceneID " << m_scene.getSceneId() << "\n"; for (uint32_t i = 0; i < objectCounts.size(); i++) { @@ -461,7 +460,7 @@ namespace ramses::internal return false; case ERamsesObjectType::SceneReference: { auto& sceneReference = RamsesObjectTypeUtils::ConvertTo(object); - LOG_INFO_P(ramses::internal::CONTEXT_CLIENT, "Scene::destroySceneReference: (master {} / ref {})", getSceneId(), sceneReference.getReferencedSceneId()); + LOG_INFO(CONTEXT_CLIENT, "Scene::destroySceneReference: (master {} / ref {})", getSceneId(), sceneReference.getReferencedSceneId()); m_sceneReferences.remove(sceneReference.getReferencedSceneId()); return destroyObject(object); } @@ -618,7 +617,7 @@ namespace ramses::internal } if (requestedPublicationMode != EScenePublicationMode::LocalOnly && !getClientImpl().getFramework().isConnected()) { - LOG_INFO(ramses::internal::CONTEXT_CLIENT, "Scene(" << m_scene.getSceneId() << ")::publish(LocalAndRemote): Scene is only published locally until framework is connected (RamsesFramework::connect)"); + LOG_INFO(CONTEXT_CLIENT, "Scene({})::publish(LocalAndRemote): Scene is only published locally until framework is connected (RamsesFramework::connect)", m_scene.getSceneId()); } getClientImpl().getClientApplication().publishScene(m_scene.getSceneId(), requestedPublicationMode); return true; @@ -684,32 +683,32 @@ namespace ramses::internal { if (!containsSceneObject(sourceRenderBuffer.impl())) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "Scene(" << m_scene.getSceneId() << ")::createBlitPass failed, source render buffer is not from this scene."); + LOG_ERROR(CONTEXT_CLIENT, "Scene({})::createBlitPass failed, source render buffer is not from this scene.", m_scene.getSceneId()); return nullptr; } if (!containsSceneObject(destinationRenderBuffer.impl())) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "Scene(" << m_scene.getSceneId() << ")::createBlitPass failed, destination render buffer is not from this scene."); + LOG_ERROR(CONTEXT_CLIENT, "Scene({})::createBlitPass failed, destination render buffer is not from this scene.", m_scene.getSceneId()); return nullptr; } if (sourceRenderBuffer.getBufferFormat() != destinationRenderBuffer.getBufferFormat()) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "Scene(" << m_scene.getSceneId() << ")::createBlitPass failed, source and destination buffers have different buffer formats"); + LOG_ERROR(CONTEXT_CLIENT, "Scene({})::createBlitPass failed, source and destination buffers have different buffer formats", m_scene.getSceneId()); return nullptr; } if (sourceRenderBuffer.getHeight() != destinationRenderBuffer.getHeight() || sourceRenderBuffer.getWidth() != destinationRenderBuffer.getWidth()) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "Scene(" << m_scene.getSceneId() << ")::createBlitPass failed, source and destination buffers have different dimensions"); + LOG_ERROR(CONTEXT_CLIENT, "Scene({})::createBlitPass failed, source and destination buffers have different dimensions", m_scene.getSceneId()); return nullptr; } if (&sourceRenderBuffer == &destinationRenderBuffer) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "Scene(" << m_scene.getSceneId() << ")::createBlitPass failed, source and destination cannot be the same buffer"); + LOG_ERROR(CONTEXT_CLIENT, "Scene({})::createBlitPass failed, source and destination cannot be the same buffer", m_scene.getSceneId()); return nullptr; } @@ -723,17 +722,13 @@ namespace ramses::internal { if (!containsSceneObject(geometryBuffer.impl())) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, - "Scene(" << m_scene.getSceneId() - << ")::createPickableObject failed, geometry buffer is not from this scene."); + LOG_ERROR(CONTEXT_CLIENT, "Scene({})::createPickableObject failed, geometry buffer is not from this scene.", m_scene.getSceneId()); return nullptr; } if (geometryBuffer.getDataType() != ramses::EDataType::Vector3F || 0 != (geometryBuffer.impl().getElementCount() % 3)) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, - "Scene(" << m_scene.getSceneId() - << ")::createPickableObject failed, geometry buffer has the wrong format."); + LOG_ERROR(CONTEXT_CLIENT, "Scene({})::createPickableObject failed, geometry buffer has the wrong format.", m_scene.getSceneId()); return nullptr; } @@ -747,7 +742,7 @@ namespace ramses::internal { if (0 == width || 0 == height) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "Scene(" << m_scene.getSceneId() << ")::createRenderBuffer failed: cannot create a render buffer with 0 width and/or height!"); + LOG_ERROR(CONTEXT_CLIENT, "Scene({})::createRenderBuffer failed: cannot create a render buffer with 0 width and/or height!", m_scene.getSceneId()); return nullptr; } @@ -763,7 +758,7 @@ namespace ramses::internal rtDesc.validate(report); if (report.hasError()) { - LOG_ERROR(CONTEXT_CLIENT, "Scene::createRenderTarget failed, RenderTargetDescription is invalid: " << report.toString()); + LOG_ERROR(CONTEXT_CLIENT, "Scene::createRenderTarget failed, RenderTargetDescription is invalid: {}", report.toString()); return nullptr; } @@ -1251,7 +1246,7 @@ namespace ramses::internal { const auto timestampOfFlushCall = m_sendEffectTimeSync ? getIScene().getEffectTimeSync() : ramses::internal::FlushTime::Clock::now(); - LOG_DEBUG_P(CONTEXT_CLIENT, "Scene::flush: sceneVersion {}, prevSceneVersion {}, syncFlushTime {}", sceneVersion, m_nextSceneVersion, ramses::internal::asMilliseconds(timestampOfFlushCall)); + LOG_DEBUG(CONTEXT_CLIENT, "Scene::flush: sceneVersion {}, prevSceneVersion {}, syncFlushTime {}", sceneVersion, m_nextSceneVersion, ramses::internal::asMilliseconds(timestampOfFlushCall)); if (m_nextSceneVersion != InvalidSceneVersionTag && sceneVersion == InvalidSceneVersionTag) { @@ -1264,9 +1259,18 @@ namespace ramses::internal m_commandBuffer.execute(ramses::internal::SceneCommandVisitor(*this)); applyHierarchicalVisibility(); - const ramses::internal::FlushTimeInformation flushTimeInfo { m_expirationTimestamp, timestampOfFlushCall, ramses::internal::FlushTime::Clock::getClockType(), m_sendEffectTimeSync }; - m_sendEffectTimeSync = false; + if (m_scene.haveResourcesChanged()) + { + const auto maybeIssue = validateRenderBufferDependingObjects(); + if (maybeIssue) + { + getErrorReporting().set(fmt::format("Scene::flush: Flushing scene failed: {}", maybeIssue->message), maybeIssue->object); + return false; + } + } + const ramses::internal::FlushTimeInformation flushTimeInfo { m_expirationTimestamp, timestampOfFlushCall, ramses::internal::FlushTime::Clock::getClockType(), m_sendEffectTimeSync }; + m_sendEffectTimeSync = false; if (!getClientImpl().getClientApplication().flush(m_scene.getSceneId(), flushTimeInfo, sceneVersionInternal)) { getErrorReporting().set("Scene::flush: Flushing scene failed, consult logs for more details.", *this); @@ -1281,7 +1285,7 @@ namespace ramses::internal { const auto now = ramses::internal::FlushTime::Clock::now(); const auto nowMs = std::chrono::time_point_cast(now); - LOG_INFO_P(CONTEXT_CLIENT, "Scene({})::resetUniformTimeMs: {}", getSceneId(), nowMs.time_since_epoch().count()); + LOG_INFO(CONTEXT_CLIENT, "Scene({})::resetUniformTimeMs: {}", getSceneId(), nowMs.time_since_epoch().count()); m_sendEffectTimeSync = true; getIScene().setEffectTimeSync(now); return true; @@ -1452,6 +1456,31 @@ namespace ramses::internal m_objectRegistry.clearDirtyNodes(); } + std::optional SceneImpl::validateRenderBufferDependingObjects() const + { + SceneObjectRegistryIterator itRT{ m_objectRegistry, ERamsesObjectType::RenderTarget }; + SceneObjectRegistryIterator itBP{ m_objectRegistry, ERamsesObjectType::BlitPass }; + + ValidationReportImpl report; + for (auto* registryIter : { &itRT, &itBP }) + { + while (const auto* obj = registryIter->getNext()) + { + obj->impl().onValidate(report); + if (report.hasError()) + { + // get last error reported + const auto& issues = report.getIssues(); + const auto it = std::find_if(issues.crbegin(), issues.crend(), [](const auto& issue) { return issue.type == EIssueType::Error; }); + assert(it != issues.crend()); + return *it; + } + } + } + + return std::nullopt; + } + void SceneImpl::setSceneVersionForNextFlush(sceneVersionTag_t sceneVersion) { assert(m_nextSceneVersion == InvalidSceneVersionTag); @@ -1515,13 +1544,13 @@ namespace ramses::internal { if (!referencedScene.isValid()) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "Scene::createSceneReference: cannot reference a scene with invalid scene ID."); + LOG_ERROR(CONTEXT_CLIENT, "Scene::createSceneReference: cannot reference a scene with invalid scene ID."); return nullptr; } if (referencedScene == getSceneId()) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "Scene::createSceneReference: cannot self reference."); + LOG_ERROR(CONTEXT_CLIENT, "Scene::createSceneReference: cannot self reference."); return nullptr; } @@ -1529,13 +1558,13 @@ namespace ramses::internal { if (getClientImpl().findSceneReference(scene->getSceneId(), referencedScene) != nullptr) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "Scene::createSceneReference: there is already a SceneReference with sceneId " - << referencedScene << " in master scene " << scene->getSceneId() << ", cannot create another one"); + LOG_ERROR(CONTEXT_CLIENT, "Scene::createSceneReference: there is already a SceneReference with sceneId {} in master scene {}, cannot create another one", + referencedScene, scene->getSceneId()); return nullptr; } } - LOG_INFO_P(ramses::internal::CONTEXT_CLIENT, "Scene::createSceneReference: creating scene reference (master {} / ref {})", getSceneId(), referencedScene); + LOG_INFO(CONTEXT_CLIENT, "Scene::createSceneReference: creating scene reference (master {} / ref {})", getSceneId(), referencedScene); auto pimpl = std::make_unique(*this, name); pimpl->initializeFrameworkData(referencedScene); @@ -1621,7 +1650,7 @@ namespace ramses::internal { if (0u == numElements || nullptr == arrayData) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "Scene::createArrayResource: Array resource must have element count > 0 and data must not be nullptr!"); + LOG_ERROR(CONTEXT_CLIENT, "Scene::createArrayResource: Array resource must have element count > 0 and data must not be nullptr!"); return nullptr; } @@ -1732,7 +1761,7 @@ namespace ramses::internal ramses::internal::ManagedResource res = getClientImpl().createManagedEffect(effectDesc, name, m_effectErrorMessages); if (!res) { - LOG_ERROR(CONTEXT_CLIENT, "Scene::createEffect: failed to create managed effect resource: " << m_effectErrorMessages); + LOG_ERROR(CONTEXT_CLIENT, "Scene::createEffect: failed to create managed effect resource: {}", m_effectErrorMessages); return nullptr; } @@ -1797,32 +1826,6 @@ namespace ramses::internal bool SceneImpl::serialize(std::vector& outputBuffer, const SaveFileConfigImpl& config) const { - if (config.getValidationEnabled()) - { - ValidationReportImpl report; - validate(report); - - for (const auto& msg : report.getIssues()) - { - if (msg.object) - { - LOG_WARN_P(CONTEXT_CLIENT, "[{}] {}", msg.object->impl().getIdentificationString(), msg.message); - } - else - { - LOG_WARN_P(CONTEXT_CLIENT, "{}", msg.message); - } - } - - if (report.hasError()) - { - getErrorReporting().set( - "Failed to saveToFile() because validation errors were encountered! " - "Refer to the documentation of saveToFile() for details how to address these gracefully."); - return false; - } - } - ramses::internal::BinaryOutputStream outputStream; const EFeatureLevel featureLevel = m_hlClient.impl().getFramework().getFeatureLevel(); ramses::internal::RamsesVersion::WriteToStream(outputStream, ::ramses_sdk::RAMSES_SDK_RAMSES_VERSION, ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_HASH, featureLevel); @@ -1855,7 +1858,7 @@ namespace ramses::internal return status; } - bool SceneImpl::saveToFile(std::string_view fileName, const SaveFileConfigImpl& config) const + bool SceneImpl::saveToFile(std::string_view fileName, const SaveFileConfigImpl& config) { if (fileName.empty()) { @@ -1863,7 +1866,25 @@ namespace ramses::internal return false; } - LOG_INFO_P(CONTEXT_CLIENT, "Scene::saveToFile: filename '{}', compress {}", fileName, config.getCompressionEnabled()); + LOG_INFO(CONTEXT_CLIENT, "Scene::saveToFile: filename '{}', compress {}", fileName, config.getCompressionEnabled()); + + LOG_INFO(CONTEXT_CLIENT, "Scene::saveToFile: updating LogicEngine instances before saving to file"); + SceneObjectRegistryIterator leIter{ m_objectRegistry, ramses::ERamsesObjectType::LogicEngine }; + while (auto le = leIter.getNextNonConst()) + { + if (!le->update()) + { + getErrorReporting().set(fmt::format("Scene::saveToFile failed due to failed logic engine update: {}", getErrorReporting().getError()->message), le); + return false; + } + } + + LOG_INFO(CONTEXT_CLIENT, "Scene::saveToFile: flushing scene before saving to file"); + if (!flush(sceneVersionTag_t{})) + { + getErrorReporting().set(fmt::format("Scene::saveToFile failed due to failed scene flush: {}", getErrorReporting().getError()->message), *this); + return false; + } std::vector outputBuffer; if (!serialize(outputBuffer, config)) @@ -1888,7 +1909,7 @@ namespace ramses::internal return false; } - LOG_INFO_P(ramses::internal::CONTEXT_CLIENT, "Scene::saveToFile: done writing '{}'", fileName); + LOG_INFO(CONTEXT_CLIENT, "Scene::saveToFile: done writing '{}'", fileName); return true; } @@ -1904,7 +1925,7 @@ namespace ramses::internal return; getClientImpl().getClientApplication().removeResourceFile(m_sceneFileHandle); - LOG_INFO(CONTEXT_CLIENT, "SceneImpl::closeSceneFile closed: " << m_sceneFileHandle); + LOG_INFO(CONTEXT_CLIENT, "SceneImpl::closeSceneFile closed: {}", m_sceneFileHandle); m_sceneFileHandle = ramses::internal::SceneFileHandle::Invalid(); } diff --git a/src/client/impl/SceneImpl.h b/src/client/impl/SceneImpl.h index 95cc5d7fe..c46d0d5b6 100644 --- a/src/client/impl/SceneImpl.h +++ b/src/client/impl/SceneImpl.h @@ -109,7 +109,7 @@ namespace ramses::internal EScenePublicationMode getPublicationModeSetFromSceneConfig() const; bool serialize(std::vector& outputBuffer, const SaveFileConfigImpl& config) const; - bool saveToFile(std::string_view fileName, const SaveFileConfigImpl& config) const; + bool saveToFile(std::string_view fileName, const SaveFileConfigImpl& config); LogicEngine* createLogicEngine(std::string_view name); @@ -307,6 +307,7 @@ namespace ramses::internal void applyVisibilityToSubtree(NodeImpl& initialNode, EVisibilityMode initialVisibility); void prepareListOfDirtyNodesForHierarchicalVisibility(NodeVisibilityInfoVector& nodesToProcess); void applyHierarchicalVisibility(); + std::optional validateRenderBufferDependingObjects() const; bool writeSceneObjectsToStream(ramses::internal::IOutputStream& outputStream, const SaveFileConfigImpl& saveConfig) const; diff --git a/src/client/impl/SceneObjectImpl.cpp b/src/client/impl/SceneObjectImpl.cpp index babfe999c..9685429ad 100644 --- a/src/client/impl/SceneObjectImpl.cpp +++ b/src/client/impl/SceneObjectImpl.cpp @@ -100,14 +100,4 @@ namespace ramses::internal return idString; } - - void SceneObjectImpl::setObjectRegistryHandle(SceneObjectRegistryHandle handle) - { - m_objectRegistryHandle = handle; - } - - SceneObjectRegistryHandle SceneObjectImpl::getObjectRegistryHandle() const - { - return m_objectRegistryHandle; - } } diff --git a/src/client/impl/SceneObjectImpl.h b/src/client/impl/SceneObjectImpl.h index 6f46c9615..68c48fca5 100644 --- a/src/client/impl/SceneObjectImpl.h +++ b/src/client/impl/SceneObjectImpl.h @@ -33,9 +33,6 @@ namespace ramses::internal [[nodiscard]] Scene& getScene(); // impl methods - void setObjectRegistryHandle(SceneObjectRegistryHandle handle); - [[nodiscard]] SceneObjectRegistryHandle getObjectRegistryHandle() const; - [[nodiscard]] const SceneImpl& getSceneImpl() const; [[nodiscard]] SceneImpl& getSceneImpl(); bool serialize(ramses::internal::IOutputStream& outStream, SerializationContext& serializationContext) const override; @@ -53,6 +50,5 @@ namespace ramses::internal private: SceneImpl& m_scene; - SceneObjectRegistryHandle m_objectRegistryHandle; }; } diff --git a/src/client/impl/SceneObjectRegistry.cpp b/src/client/impl/SceneObjectRegistry.cpp index b871b9d82..3b36c0204 100644 --- a/src/client/impl/SceneObjectRegistry.cpp +++ b/src/client/impl/SceneObjectRegistry.cpp @@ -13,7 +13,6 @@ #include "impl/ObjectIteratorImpl.h" #include "impl/NodeImpl.h" #include "impl/RamsesObjectTypeUtils.h" -#include "internal/PlatformAbstraction/PlatformStringUtils.h" namespace ramses::internal { @@ -23,9 +22,7 @@ namespace ramses::internal assert(!containsObject(object)); const ERamsesObjectType type = object.impl().getType(); - const SceneObjectRegistryHandle handle = m_objects[static_cast(type)].allocate(); - *m_objects[static_cast(type)].getMemory(handle) = &object; - object.impl().setObjectRegistryHandle(handle); + m_objects[static_cast(type)].push_back(&object); trackSceneObjectById(object); } @@ -44,39 +41,38 @@ namespace ramses::internal m_objectsById.erase(sceneObjectId); } - const SceneObjectRegistryHandle handle = object.impl().getObjectRegistryHandle(); - const auto type = static_cast(object.impl().getType()); - m_objects[type].release(handle); + auto& objects = m_objects[static_cast(object.impl().getType())]; + auto it = std::find(objects.begin(), objects.end(), &object); + assert(it != objects.end()); + objects.erase(it); - auto it = std::find_if(m_objectsOwningContainer.begin(), m_objectsOwningContainer.end(), [&object](auto& ro) { return ro.get() == &object; }); - assert(it != m_objectsOwningContainer.end()); - m_objectsOwningContainer.erase(it); + auto it2 = std::find_if(m_objectsOwningContainer.begin(), m_objectsOwningContainer.end(), [&object](auto& ro) { return ro.get() == &object; }); + assert(it2 != m_objectsOwningContainer.end()); + m_objectsOwningContainer.erase(it2); } - void SceneObjectRegistry::reserveAdditionalGeneralCapacity(uint32_t additionalCount) + void SceneObjectRegistry::reserveAdditionalGeneralCapacity(size_t additionalCount) { m_objectsOwningContainer.reserve(m_objectsOwningContainer.size() + additionalCount); } - void SceneObjectRegistry::reserveAdditionalObjectCapacity(ERamsesObjectType type, uint32_t additionalCount) + void SceneObjectRegistry::reserveAdditionalObjectCapacity(ERamsesObjectType type, size_t additionalCount) { assert(RamsesObjectTypeUtils::IsConcreteType(type)); const auto index = static_cast(type); - m_objects[index].preallocateSize(m_objects[index].getActualCount() + additionalCount); + m_objects[index].reserve(m_objects[index].size() + additionalCount); } - uint32_t SceneObjectRegistry::getNumberOfObjects(ERamsesObjectType type) const + size_t SceneObjectRegistry::getNumberOfObjects(ERamsesObjectType type) const { assert(RamsesObjectTypeUtils::IsConcreteType(type)); - return m_objects[static_cast(type)].getActualCount(); + return m_objects[static_cast(type)].size(); } bool SceneObjectRegistry::containsObject(const SceneObject& object) const { - const SceneObjectRegistryHandle handle = object.impl().getObjectRegistryHandle(); - const ERamsesObjectType type = object.impl().getType(); - const SceneObjectsPool& objectsPool = m_objects[static_cast(type)]; - return objectsPool.isAllocated(handle) && (*objectsPool.getMemory(handle) == &object); + const auto& objects = m_objects[static_cast(object.impl().getType())]; + return std::find(objects.begin(), objects.end(), &object) != objects.end(); } void SceneObjectRegistry::trackSceneObjectById(SceneObject& object) @@ -97,9 +93,9 @@ namespace ramses::internal return it->second; auto& logicEngines = m_objects[static_cast(ERamsesObjectType::LogicEngine)]; - for (auto& le : logicEngines) + for (auto* le : logicEngines) { - auto obj = (*le.second)->as()->findObject(id); + auto obj = le->as()->findObject(id); if (obj) return obj; } @@ -118,14 +114,12 @@ namespace ramses::internal assert(objects.empty()); // preallocate memory in container - uint32_t objectCount = 0u; + size_t objectCount = 0u; for (size_t i = 0u; i < RamsesObjectTypeCount; ++i) { const auto type = ERamsesObjectType(i); if (RamsesObjectTypeUtils::IsConcreteType(type) && RamsesObjectTypeUtils::IsTypeMatchingBaseType(type, ofType)) - { - objectCount += m_objects[i].getActualCount(); - } + objectCount += m_objects[i].size(); } objects.reserve(objectCount); @@ -133,16 +127,7 @@ namespace ramses::internal { const auto type = ERamsesObjectType(i); if (RamsesObjectTypeUtils::IsConcreteType(type) && RamsesObjectTypeUtils::IsTypeMatchingBaseType(type, ofType)) - { - const SceneObjectsPool& objectsPool = m_objects[i]; - for (SceneObjectRegistryHandle handle(0u); handle < objectsPool.getTotalCount(); ++handle) - { - if (objectsPool.isAllocated(handle)) - { - objects.push_back(*objectsPool.getMemory(handle)); - } - } - } + objects.insert(objects.end(), m_objects[i].begin(), m_objects[i].end()); } } diff --git a/src/client/impl/SceneObjectRegistry.h b/src/client/impl/SceneObjectRegistry.h index 1017608c3..5bf5bd8e1 100644 --- a/src/client/impl/SceneObjectRegistry.h +++ b/src/client/impl/SceneObjectRegistry.h @@ -18,9 +18,8 @@ #include "impl/RamsesObjectTypeTraits.h" #include "impl/RamsesObjectTypeUtils.h" -#include "internal/Core/Utils/MemoryPool.h" - #include +#include #include #include #include @@ -36,9 +35,9 @@ namespace ramses::internal T& createAndRegisterObject(std::unique_ptr impl); void destroyAndUnregisterObject(SceneObject& object); - void reserveAdditionalGeneralCapacity(uint32_t additionalCount); - void reserveAdditionalObjectCapacity(ERamsesObjectType type, uint32_t additionalCount); - [[nodiscard]] uint32_t getNumberOfObjects(ERamsesObjectType type) const; + void reserveAdditionalGeneralCapacity(size_t additionalCount); + void reserveAdditionalObjectCapacity(ERamsesObjectType type, size_t additionalCount); + [[nodiscard]] size_t getNumberOfObjects(ERamsesObjectType type) const; void getObjectsOfType(SceneObjectVector& objects, ERamsesObjectType ofType) const; @@ -61,8 +60,7 @@ namespace ramses::internal std::unordered_map m_objectsById; - using SceneObjectsPool = ramses::internal::MemoryPool; - std::array m_objects; + std::array, RamsesObjectTypeCount> m_objects; using SceneObjectUniquePtr = std::unique_ptr>; std::vector m_objectsOwningContainer; @@ -97,9 +95,9 @@ namespace ramses::internal if (RamsesObjectTypeUtils::IsConcreteType(type) && RamsesObjectTypeUtils::IsTypeMatchingBaseType(type, typeToReturn)) { const auto& objs = m_objects[typeIdx]; - const auto it = std::find_if(objs.begin(), objs.end(), [name](const auto o) { return (*o.second)->getName() == name; }); + const auto it = std::find_if(objs.begin(), objs.end(), [name](const auto o) { return o->getName() == name; }); if (it != objs.end()) - return (*it->second)->template as(); + return (*it)->template as(); } } } @@ -110,7 +108,7 @@ namespace ramses::internal auto& logicEngines = m_objects[static_cast(ERamsesObjectType::LogicEngine)]; for (auto& le : logicEngines) { - auto obj = (*le.second)->as()->findObject(name); + auto obj = le->as()->findObject(name); if (obj) return obj; } diff --git a/src/client/impl/SceneObjectRegistryIterator.h b/src/client/impl/SceneObjectRegistryIterator.h index c54b5cc94..2153f84f3 100644 --- a/src/client/impl/SceneObjectRegistryIterator.h +++ b/src/client/impl/SceneObjectRegistryIterator.h @@ -18,9 +18,9 @@ namespace ramses::internal { public: SceneObjectRegistryIterator(const SceneObjectRegistry& registry, ERamsesObjectType type) - : m_objects(registry.m_objects[static_cast(type)]) - , m_objectsTotalCount(m_objects.getTotalCount()) - , m_current(0u) + : m_objects{ registry.m_objects[static_cast(type)] } + , m_current{ m_objects.cbegin() } + , m_objectsTotalCount{ m_objects.size() } { assert(RamsesObjectTypeUtils::IsConcreteType(type)); } @@ -29,18 +29,15 @@ namespace ramses::internal const T* getNext() { static_assert(std::is_base_of_v); - assert((m_objectsTotalCount == m_objects.getTotalCount()) && "Container size changed while iterating!"); - for (; m_current < m_objectsTotalCount; ++m_current) - { - if (m_objects.isAllocated(m_current)) - { - const SceneObject& obj = **m_objects.getMemory(m_current); - ++m_current; - return &RamsesObjectTypeUtils::ConvertTo(obj); - } - } - - return nullptr; + assert((m_objectsTotalCount == m_objects.size()) && "Container size changed while iterating!"); + + if (m_current == m_objects.cend()) + return nullptr; + + const auto obj = *m_current; + ++m_current; + + return &RamsesObjectTypeUtils::ConvertTo(*obj); } template @@ -51,8 +48,8 @@ namespace ramses::internal } private: - const SceneObjectRegistry::SceneObjectsPool& m_objects; - const uint32_t m_objectsTotalCount; - SceneObjectRegistryHandle m_current; + const std::vector& m_objects; + std::vector::const_iterator m_current; + size_t m_objectsTotalCount = 0u; }; } diff --git a/src/client/impl/SerializationHelper.h b/src/client/impl/SerializationHelper.h index 1f07aa1d8..e201734c2 100644 --- a/src/client/impl/SerializationHelper.h +++ b/src/client/impl/SerializationHelper.h @@ -46,7 +46,7 @@ namespace ramses::internal if (RamsesObjectTypeUtils::IsConcreteType(type) && RamsesObjectTypeUtils::IsTypeMatchingBaseType(type, baseType)) { - const uint32_t count = registry.getNumberOfObjects(type); + const auto count = static_cast(registry.getNumberOfObjects(type)); if (count > 0u) { const TypeCountPair typeCountEntry = { type, count }; diff --git a/src/client/impl/Texture2DBuffer.cpp b/src/client/impl/Texture2DBuffer.cpp index 8b4530d85..a7de91528 100644 --- a/src/client/impl/Texture2DBuffer.cpp +++ b/src/client/impl/Texture2DBuffer.cpp @@ -20,9 +20,9 @@ namespace ramses { } - bool Texture2DBuffer::updateData(size_t mipLevel, uint32_t offsetX, uint32_t offsetY, uint32_t width, uint32_t height, const void* data) + bool Texture2DBuffer::updateData(size_t mipLevel, uint32_t offsetX, uint32_t offsetY, uint32_t width, uint32_t height, const std::byte* data) { - const bool status = m_impl.setData(static_cast(data), mipLevel, offsetX, offsetY, width, height); + const bool status = m_impl.setData(data, mipLevel, offsetX, offsetY, width, height); LOG_HL_CLIENT_API6(status, LOG_API_GENERIC_PTR_STRING(data), mipLevel, offsetX, offsetY, width, height); return status; } diff --git a/src/client/impl/TextureUtils.cpp b/src/client/impl/TextureUtils.cpp index 69669f4c8..cbc520b77 100644 --- a/src/client/impl/TextureUtils.cpp +++ b/src/client/impl/TextureUtils.cpp @@ -20,8 +20,7 @@ namespace ramses::internal mipDataSizes.reserve(mipLevelData.size()); for (const auto& data : mipLevelData) { - const uint32_t mipDataSize = data.m_size; - mipDataSizes.push_back(mipDataSize); + mipDataSizes.push_back(static_cast(data.size())); } } @@ -31,8 +30,7 @@ namespace ramses::internal mipDataSizes.reserve(mipLevelData.size()); for (const auto& data : mipLevelData) { - const uint32_t mipDataSize = data.m_faceDataSize; - mipDataSizes.push_back(mipDataSize); + mipDataSizes.push_back(static_cast(data.m_dataPX.size())); } } @@ -40,8 +38,8 @@ namespace ramses::internal { for (const auto& data : mipLevelData) { - const uint32_t mipDataSize = data.m_size; - ramses::internal::PlatformMemory::Copy(dest, data.m_data, mipDataSize); + const size_t mipDataSize = data.size(); + ramses::internal::PlatformMemory::Copy(dest, data.data(), mipDataSize); dest += mipDataSize; } } @@ -50,38 +48,38 @@ namespace ramses::internal { for (const auto& data : mipLevelData) { - const uint32_t mipDataSize = data.m_faceDataSize; - ramses::internal::PlatformMemory::Copy(dest, data.m_dataPX, mipDataSize); + const size_t mipDataSize = data.m_dataPX.size(); + ramses::internal::PlatformMemory::Copy(dest, data.m_dataPX.data(), mipDataSize); dest += mipDataSize; } for (const auto& data : mipLevelData) { - const uint32_t mipDataSize = data.m_faceDataSize; - ramses::internal::PlatformMemory::Copy(dest, data.m_dataNX, mipDataSize); + const size_t mipDataSize = data.m_dataNX.size(); + ramses::internal::PlatformMemory::Copy(dest, data.m_dataNX.data(), mipDataSize); dest += mipDataSize; } for (const auto& data : mipLevelData) { - const uint32_t mipDataSize = data.m_faceDataSize; - ramses::internal::PlatformMemory::Copy(dest, data.m_dataPY, mipDataSize); + const size_t mipDataSize = data.m_dataPY.size(); + ramses::internal::PlatformMemory::Copy(dest, data.m_dataPY.data(), mipDataSize); dest += mipDataSize; } for (const auto& data : mipLevelData) { - const uint32_t mipDataSize = data.m_faceDataSize; - ramses::internal::PlatformMemory::Copy(dest, data.m_dataNY, mipDataSize); + const size_t mipDataSize = data.m_dataNY.size(); + ramses::internal::PlatformMemory::Copy(dest, data.m_dataNY.data(), mipDataSize); dest += mipDataSize; } for (const auto& data : mipLevelData) { - const uint32_t mipDataSize = data.m_faceDataSize; - ramses::internal::PlatformMemory::Copy(dest, data.m_dataPZ, mipDataSize); + const size_t mipDataSize = data.m_dataPZ.size(); + ramses::internal::PlatformMemory::Copy(dest, data.m_dataPZ.data(), mipDataSize); dest += mipDataSize; } for (const auto& data : mipLevelData) { - const uint32_t mipDataSize = data.m_faceDataSize; - ramses::internal::PlatformMemory::Copy(dest, data.m_dataNZ, mipDataSize); + const size_t mipDataSize = data.m_dataNZ.size(); + ramses::internal::PlatformMemory::Copy(dest, data.m_dataNZ.data(), mipDataSize); dest += mipDataSize; } } @@ -95,7 +93,7 @@ namespace ramses::internal for (size_t i = 0u; i < mipLevelData.size(); ++i) { - if (mipLevelData[i].m_data == nullptr || mipLevelData[i].m_size == 0u) + if (mipLevelData[i].empty()) { return false; } @@ -107,20 +105,20 @@ namespace ramses::internal if (!ramses::internal::IsFormatCompressed(internalFormat)) { const uint32_t expectedMipDataSize = mipWidth * mipHeight * mipDepth * ramses::internal::GetTexelSizeFromFormat(internalFormat); - if (mipLevelData[i].m_size < expectedMipDataSize) + if (mipLevelData[i].size() < expectedMipDataSize) { return false; } - if (mipLevelData[i].m_size > expectedMipDataSize) + if (mipLevelData[i].size() > expectedMipDataSize) { - LOG_WARN(ramses::internal::CONTEXT_CLIENT, "Provided texture mip data does not match expected size, texture might not be as expected"); + LOG_WARN(CONTEXT_CLIENT, "Provided texture mip data does not match expected size, texture might not be as expected"); } } if (!TextureUtils::IsTextureSizeSupportedByFormat(mipWidth, mipHeight, format)) { - LOG_WARN(ramses::internal::CONTEXT_CLIENT, "Provided texture mip " << i << " might fail to be uploaded due to its size " - << mipWidth << "x" << mipHeight << " not supported by used format " << toString(format)); + LOG_WARN(CONTEXT_CLIENT, "Provided texture mip {} might fail to be uploaded due to its size {}x{} not supported by used format {}", + i, mipWidth, mipHeight, toString(format)); } } @@ -142,13 +140,18 @@ namespace ramses::internal for (size_t i = 0u; i < mipLevelData.size(); ++i) { - if (mipLevelData[i].m_dataPX == nullptr || - mipLevelData[i].m_dataNX == nullptr || - mipLevelData[i].m_dataPY == nullptr || - mipLevelData[i].m_dataNY == nullptr || - mipLevelData[i].m_dataPZ == nullptr || - mipLevelData[i].m_dataNZ == nullptr || - mipLevelData[i].m_faceDataSize == 0u) + if (mipLevelData[i].m_dataPX.empty() || + mipLevelData[i].m_dataNX.empty() || + mipLevelData[i].m_dataPY.empty() || + mipLevelData[i].m_dataNY.empty() || + mipLevelData[i].m_dataPZ.empty() || + mipLevelData[i].m_dataNZ.empty() || + (mipLevelData[i].m_dataPX.size() != mipLevelData[i].m_dataNX.size() || + mipLevelData[i].m_dataNX.size() != mipLevelData[i].m_dataPY.size() || + mipLevelData[i].m_dataPY.size() != mipLevelData[i].m_dataNY.size() || + mipLevelData[i].m_dataNY.size() != mipLevelData[i].m_dataPZ.size() || + mipLevelData[i].m_dataPZ.size() != mipLevelData[i].m_dataNZ.size() || + mipLevelData[i].m_dataNZ.size() != mipLevelData[i].m_dataPX.size())) { return false; } @@ -158,20 +161,20 @@ namespace ramses::internal if (!ramses::internal::IsFormatCompressed(internalFormat)) { const uint32_t expectedMipDataSize = mipSize * mipSize * ramses::internal::GetTexelSizeFromFormat(internalFormat); - if (mipLevelData[i].m_faceDataSize < expectedMipDataSize) + if (mipLevelData[i].m_dataPX.size() < expectedMipDataSize) { return false; } - if (mipLevelData[i].m_faceDataSize > expectedMipDataSize) + if (mipLevelData[i].m_dataPX.size() > expectedMipDataSize) { - LOG_WARN(ramses::internal::CONTEXT_CLIENT, "Provided texture mip data does not match expected size, texture might not be as expected"); + LOG_WARN(CONTEXT_CLIENT, "Provided texture mip data does not match expected size, texture might not be as expected"); } } if (!TextureUtils::IsTextureSizeSupportedByFormat(mipSize, mipSize, format)) { - LOG_WARN(ramses::internal::CONTEXT_CLIENT, "Provided texture mip " << i << " might fail to be uploaded due to its size " - << mipSize << "x" << mipSize << " not supported by used format " << toString(format)); + LOG_WARN(CONTEXT_CLIENT, "Provided texture mip {} might fail to be uploaded due to its size {}x{} not supported by used format {}", + i, mipSize, mipSize, toString(format)); } } @@ -182,14 +185,14 @@ namespace ramses::internal { if (width == 0u || height == 0u || depth == 0u) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "TextureParametersValid: texture size cannot be 0."); + LOG_ERROR(CONTEXT_CLIENT, "TextureParametersValid: texture size cannot be 0."); return false; } const uint32_t fullChainMipMapCount = ramses::internal::TextureMathUtils::GetMipLevelCount(width, height, depth); if (mipMapCount > fullChainMipMapCount) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "TextureParametersValid: too many mip levels provided."); + LOG_ERROR(CONTEXT_CLIENT, "TextureParametersValid: too many mip levels provided."); return false; } diff --git a/src/client/impl/UniformInput.cpp b/src/client/impl/UniformInput.cpp index f51d95e62..7d0ea96a0 100644 --- a/src/client/impl/UniformInput.cpp +++ b/src/client/impl/UniformInput.cpp @@ -16,6 +16,16 @@ namespace ramses { } + UniformInput::~UniformInput() = default; + + UniformInput::UniformInput(const UniformInput& other) = default; + + UniformInput::UniformInput(UniformInput&& other) noexcept = default; + + UniformInput& UniformInput::operator=(const UniformInput& other) = default; + + UniformInput& UniformInput::operator=(UniformInput&& other) noexcept = default; + EEffectUniformSemantic UniformInput::getSemantics() const { return m_impl->getUniformSemantics(); diff --git a/src/client/impl/logic/AnimationNodeConfigImpl.cpp b/src/client/impl/logic/AnimationNodeConfigImpl.cpp index b3ee6fec1..d7cecb36a 100644 --- a/src/client/impl/logic/AnimationNodeConfigImpl.cpp +++ b/src/client/impl/logic/AnimationNodeConfigImpl.cpp @@ -18,32 +18,32 @@ namespace ramses::internal { if (!channelData.timeStamps || !channelData.keyframes) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', missing timestamps and/or keyframes.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', missing timestamps and/or keyframes.", channelData.name); return false; } if (!CanPropertyTypeBeAnimated(channelData.keyframes->getDataType())) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', keyframes data type cannot be animated.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', keyframes data type cannot be animated.", channelData.name); return false; } if (channelData.timeStamps->getDataType() != EPropertyType::Float) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', timestamps must be of type Float.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', timestamps must be of type Float.", channelData.name); return false; } if (channelData.timeStamps->getNumElements() != channelData.keyframes->getNumElements()) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', number of keyframes must be same as number of timestamps.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', number of keyframes must be same as number of timestamps.", channelData.name); return false; } const auto& timestamps = *channelData.timeStamps->getData(); if (std::adjacent_find(timestamps.cbegin(), timestamps.cend(), std::greater_equal()) != timestamps.cend()) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', timestamps have to be strictly in ascending order.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', timestamps have to be strictly in ascending order.", channelData.name); return false; } @@ -52,7 +52,7 @@ namespace ramses::internal const size_t elementArraySize = channelData.keyframes->getData>()->front().size(); if (elementArraySize > MaxArrayPropertySize) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}'," + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}'," " when using elements of data type float array, the float array size ({}) cannot exceed {}.", channelData.name, elementArraySize, MaxArrayPropertySize); return false; @@ -62,7 +62,7 @@ namespace ramses::internal if ((channelData.interpolationType == EInterpolationType::Linear_Quaternions || channelData.interpolationType == EInterpolationType::Cubic_Quaternions) && channelData.keyframes->getDataType() != EPropertyType::Vec4f) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', quaternion animation requires the keyframes to be of type vec4f.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', quaternion animation requires the keyframes to be of type vec4f.", channelData.name); return false; } @@ -70,19 +70,19 @@ namespace ramses::internal { if (!channelData.tangentsIn || !channelData.tangentsOut) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', cubic interpolation requires tangents to be provided.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', cubic interpolation requires tangents to be provided.", channelData.name); return false; } if (channelData.tangentsIn->getDataType() != channelData.keyframes->getDataType() || channelData.tangentsOut->getDataType() != channelData.keyframes->getDataType()) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', tangents must be of same data type as keyframes.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', tangents must be of same data type as keyframes.", channelData.name); return false; } if (channelData.tangentsIn->getNumElements() != channelData.keyframes->getNumElements() || channelData.tangentsOut->getNumElements() != channelData.keyframes->getNumElements()) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', number of tangents in/out must be same as number of keyframes.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', number of tangents in/out must be same as number of keyframes.", channelData.name); return false; } if (channelData.keyframes->getDataType() == EPropertyType::Array) @@ -91,14 +91,14 @@ namespace ramses::internal if (channelData.tangentsIn->getData>()->front().size() != elementArraySize || channelData.tangentsOut->getData>()->front().size() != elementArraySize) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', tangents must have same array element size as keyframes.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', tangents must have same array element size as keyframes.", channelData.name); return false; } } } else if (channelData.tangentsIn || channelData.tangentsOut) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', tangents were provided for other than cubic interpolation type.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', tangents were provided for other than cubic interpolation type.", channelData.name); return false; } @@ -106,14 +106,14 @@ namespace ramses::internal { if (channelData.keyframes->getNumElements() > MaxArrayPropertySize) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', number of keyframes ({}) cannot exceed {} when animation data exposed as properties.", + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', number of keyframes ({}) cannot exceed {} when animation data exposed as properties.", channelData.name, channelData.keyframes->getNumElements(), MaxArrayPropertySize); return false; } if (channelData.keyframes->getDataType() == EPropertyType::Array) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', elements of data type float arrays cannot be exposed as properties.", channelData.name); + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::addChannel: Cannot add channelData data '{}', elements of data type float arrays cannot be exposed as properties.", channelData.name); return false; } } @@ -139,7 +139,7 @@ namespace ramses::internal { if (channelData.keyframes->getNumElements() > MaxArrayPropertySize) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::setExposingOfChannelDataAsProperties: Cannot enable channel data properties for channel '{}'," + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::setExposingOfChannelDataAsProperties: Cannot enable channel data properties for channel '{}'," " number of keyframes ({}) cannot exceed {} when animation data exposed as properties.", channelData.name, channelData.keyframes->getNumElements(), MaxArrayPropertySize); return false; @@ -147,7 +147,7 @@ namespace ramses::internal if (channelData.keyframes->getDataType() == EPropertyType::Array) { - LOG_ERROR_P(CONTEXT_CLIENT, "AnimationNodeConfig::setExposingOfChannelDataAsProperties: Cannot enable channel data properties for channel '{}'," + LOG_ERROR(CONTEXT_CLIENT, "AnimationNodeConfig::setExposingOfChannelDataAsProperties: Cannot enable channel data properties for channel '{}'," " elements of data type float arrays cannot be exposed as properties.", channelData.name); return false; } diff --git a/src/client/impl/logic/DataArrayImpl.cpp b/src/client/impl/logic/DataArrayImpl.cpp index 551a5ae5a..443c016b4 100644 --- a/src/client/impl/logic/DataArrayImpl.cpp +++ b/src/client/impl/logic/DataArrayImpl.cpp @@ -30,7 +30,7 @@ namespace ramses::internal { if (PropertyTypeToEnum::TYPE != m_dataType) { - LOG_ERROR_P(CONTEXT_CLIENT, "DataArray::getData failed for '{}', correct template that matches stored data type must be used.", getIdentificationString()); + LOG_ERROR(CONTEXT_CLIENT, "DataArray::getData failed for '{}', correct template that matches stored data type must be used.", getIdentificationString()); return nullptr; } diff --git a/src/client/impl/logic/LogicEngine.cpp b/src/client/impl/logic/LogicEngine.cpp index b51db95d3..f06757593 100644 --- a/src/client/impl/logic/LogicEngine.cpp +++ b/src/client/impl/logic/LogicEngine.cpp @@ -22,6 +22,7 @@ #include "ramses/client/logic/AnimationNode.h" #include "ramses/client/logic/TimerNode.h" #include "ramses/client/logic/AnchorPoint.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "impl/logic/LogicEngineImpl.h" #include "impl/logic/LuaConfigImpl.h" @@ -157,6 +158,11 @@ namespace ramses return m_impl.createSkinBinding(joints, inverseBindMatrices, appearanceBinding, jointMatInput, name); } + RenderBufferBinding* LogicEngine::createRenderBufferBinding(ramses::RenderBuffer& renderBuffer, std::string_view name) + { + return m_impl.createRenderBufferBinding(renderBuffer, name); + } + template DataArray* LogicEngine::createDataArrayInternal(const std::vector& data, std::string_view name) { @@ -240,85 +246,90 @@ namespace ramses return m_impl.getApiObjects().getAllPropertyLinks(); } - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; - - template RAMSES_API const LogicObject* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const LuaScript* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const LuaModule* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const LuaInterface* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const NodeBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const AppearanceBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const CameraBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const RenderPassBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const RenderGroupBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const MeshNodeBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const SkinBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const DataArray* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const AnimationNode* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const TimerNode* LogicEngine::findLogicObjectInternal(std::string_view) const; - template RAMSES_API const AnchorPoint* LogicEngine::findLogicObjectInternal(std::string_view) const; - - template RAMSES_API LogicObject* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API LuaScript* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API LuaModule* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API LuaInterface* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API NodeBinding* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API AppearanceBinding* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API CameraBinding* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API RenderPassBinding* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API RenderGroupBinding* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API MeshNodeBinding* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API SkinBinding* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API DataArray* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API AnimationNode* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API TimerNode* LogicEngine::findLogicObjectInternal(std::string_view); - template RAMSES_API AnchorPoint* LogicEngine::findLogicObjectInternal(std::string_view); - - template RAMSES_API const LogicObject* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const LuaScript* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const LuaModule* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const LuaInterface* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const NodeBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const AppearanceBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const CameraBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const RenderPassBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const RenderGroupBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const MeshNodeBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const SkinBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const DataArray* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const AnimationNode* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const TimerNode* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - template RAMSES_API const AnchorPoint* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; - - template RAMSES_API LogicObject* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API LuaScript* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API LuaModule* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API LuaInterface* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API NodeBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API AppearanceBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API CameraBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API RenderPassBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API RenderGroupBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API MeshNodeBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API SkinBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API DataArray* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API AnimationNode* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API TimerNode* LogicEngine::findLogicObjectInternal(sceneObjectId_t); - template RAMSES_API AnchorPoint* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + template RAMSES_API Collection LogicEngine::getLogicObjectsInternal() const; + + template RAMSES_API const LogicObject* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const LuaScript* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const LuaModule* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const LuaInterface* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const NodeBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const AppearanceBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const CameraBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const RenderPassBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const RenderGroupBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const MeshNodeBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const SkinBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const DataArray* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const AnimationNode* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const TimerNode* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const AnchorPoint* LogicEngine::findLogicObjectInternal(std::string_view) const; + template RAMSES_API const RenderBufferBinding* LogicEngine::findLogicObjectInternal(std::string_view) const; + + template RAMSES_API LogicObject* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API LuaScript* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API LuaModule* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API LuaInterface* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API NodeBinding* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API AppearanceBinding* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API CameraBinding* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API RenderPassBinding* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API RenderGroupBinding* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API MeshNodeBinding* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API SkinBinding* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API DataArray* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API AnimationNode* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API TimerNode* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API AnchorPoint* LogicEngine::findLogicObjectInternal(std::string_view); + template RAMSES_API RenderBufferBinding* LogicEngine::findLogicObjectInternal(std::string_view); + + template RAMSES_API const LogicObject* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const LuaScript* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const LuaModule* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const LuaInterface* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const NodeBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const AppearanceBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const CameraBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const RenderPassBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const RenderGroupBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const MeshNodeBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const SkinBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const DataArray* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const AnimationNode* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const TimerNode* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const AnchorPoint* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + template RAMSES_API const RenderBufferBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t) const; + + template RAMSES_API LogicObject* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API LuaScript* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API LuaModule* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API LuaInterface* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API NodeBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API AppearanceBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API CameraBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API RenderPassBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API RenderGroupBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API MeshNodeBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API SkinBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API DataArray* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API AnimationNode* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API TimerNode* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API AnchorPoint* LogicEngine::findLogicObjectInternal(sceneObjectId_t); + template RAMSES_API RenderBufferBinding* LogicEngine::findLogicObjectInternal(sceneObjectId_t); template RAMSES_API DataArray* LogicEngine::createDataArrayInternal(const std::vector&, std::string_view); template RAMSES_API DataArray* LogicEngine::createDataArrayInternal(const std::vector&, std::string_view); @@ -345,4 +356,5 @@ namespace ramses template RAMSES_API size_t LogicEngine::getSerializedSizeInternal(ELuaSavingMode) const; template RAMSES_API size_t LogicEngine::getSerializedSizeInternal(ELuaSavingMode) const; template RAMSES_API size_t LogicEngine::getSerializedSizeInternal(ELuaSavingMode) const; + template RAMSES_API size_t LogicEngine::getSerializedSizeInternal(ELuaSavingMode) const; } diff --git a/src/client/impl/logic/LogicEngineImpl.cpp b/src/client/impl/logic/LogicEngineImpl.cpp index ce4eb4e69..8609fa916 100644 --- a/src/client/impl/logic/LogicEngineImpl.cpp +++ b/src/client/impl/logic/LogicEngineImpl.cpp @@ -24,6 +24,7 @@ #include "ramses/client/logic/RenderGroupBindingElements.h" #include "ramses/client/logic/MeshNodeBinding.h" #include "ramses/client/logic/SkinBinding.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "impl/logic/AnchorPointImpl.h" #include "impl/logic/LogicNodeImpl.h" @@ -41,6 +42,7 @@ #include "impl/RenderGroupImpl.h" #include "impl/RenderPassImpl.h" #include "impl/MeshNodeImpl.h" +#include "impl/RenderBufferImpl.h" #include "impl/RamsesClientImpl.h" #include "impl/RamsesFrameworkImpl.h" #include "impl/EFeatureLevelImpl.h" @@ -59,6 +61,7 @@ #include "ramses/client/UniformInput.h" #include "ramses/client/Appearance.h" #include "ramses/client/Effect.h" +#include "ramses/client/RenderBuffer.h" #include "ramses/client/ramses-utils.h" #include "internal/Core/Utils/LogMacros.h" @@ -274,6 +277,17 @@ namespace ramses::internal return m_apiObjects->createSkinBinding(std::move(jointsAsImpls), inverseBindMatrices, appearanceBinding.impl(), *actualUniformInputOpt, name); } + RenderBufferBinding* LogicEngineImpl::createRenderBufferBinding(ramses::RenderBuffer& renderBuffer, std::string_view name) + { + if (!isFromTheSameSceneAs(renderBuffer.impl())) + { + getErrorReporting().set(fmt::format("Failed to create RenderBufferBinding, object is from sceneId={} but LogicEngine is from sceneId={}", renderBuffer.impl().getSceneImpl().getSceneId(), getSceneImpl().getSceneId()), *this); + return nullptr; + } + + return m_apiObjects->createRenderBufferBinding(renderBuffer, name); + } + template DataArray* LogicEngineImpl::createDataArray(const std::vector& data, std::string_view name) { @@ -531,7 +545,7 @@ namespace ramses::internal return false; } - LOG_INFO_P(CONTEXT_CLIENT, "Loading logic engine content from '{}'", dataSourceDescription); + LOG_INFO(CONTEXT_CLIENT, "Loading logic engine content from '{}'", dataSourceDescription); if (nullptr == logicEngine->apiObjects()) { diff --git a/src/client/impl/logic/LogicEngineImpl.h b/src/client/impl/logic/LogicEngineImpl.h index 2e2f62dc9..3c59859a6 100644 --- a/src/client/impl/logic/LogicEngineImpl.h +++ b/src/client/impl/logic/LogicEngineImpl.h @@ -38,6 +38,7 @@ namespace ramses class RenderGroup; class UniformInput; class MeshNode; + class RenderBuffer; class NodeBinding; class AppearanceBinding; @@ -47,6 +48,7 @@ namespace ramses class RenderGroupBindingElements; class MeshNodeBinding; class SkinBinding; + class RenderBufferBinding; class DataArray; class AnimationNode; class AnimationNodeConfig; @@ -92,6 +94,7 @@ namespace ramses::internal AppearanceBinding& appearanceBinding, const UniformInput& jointMatInput, std::string_view name); + RenderBufferBinding* createRenderBufferBinding(ramses::RenderBuffer& renderBuffer, std::string_view name); template DataArray* createDataArray(const std::vector& data, std::string_view name); AnimationNode* createAnimationNode(const AnimationNodeConfig& config, std::string_view name); diff --git a/src/client/impl/logic/LogicObject.cpp b/src/client/impl/logic/LogicObject.cpp index e3e89eb64..ca53cc769 100644 --- a/src/client/impl/logic/LogicObject.cpp +++ b/src/client/impl/logic/LogicObject.cpp @@ -7,20 +7,6 @@ // ------------------------------------------------------------------------- #include "ramses/client/logic/LogicObject.h" -#include "ramses/client/logic/LuaModule.h" -#include "ramses/client/logic/LuaScript.h" -#include "ramses/client/logic/LuaInterface.h" -#include "ramses/client/logic/NodeBinding.h" -#include "ramses/client/logic/CameraBinding.h" -#include "ramses/client/logic/AppearanceBinding.h" -#include "ramses/client/logic/RenderPassBinding.h" -#include "ramses/client/logic/RenderGroupBinding.h" -#include "ramses/client/logic/MeshNodeBinding.h" -#include "ramses/client/logic/SkinBinding.h" -#include "ramses/client/logic/DataArray.h" -#include "ramses/client/logic/AnimationNode.h" -#include "ramses/client/logic/TimerNode.h" -#include "ramses/client/logic/AnchorPoint.h" #include "impl/logic/LogicObjectImpl.h" namespace ramses @@ -40,5 +26,4 @@ namespace ramses { return m_impl; } - } diff --git a/src/client/impl/logic/LuaConfigImpl.cpp b/src/client/impl/logic/LuaConfigImpl.cpp index 71997b44b..ff2e33e5a 100644 --- a/src/client/impl/logic/LuaConfigImpl.cpp +++ b/src/client/impl/logic/LuaConfigImpl.cpp @@ -18,13 +18,13 @@ namespace ramses::internal { if (!LuaCompilationUtils::CheckModuleName(aliasName)) { - LOG_ERROR_P(CONTEXT_CLIENT, "Failed to add dependency '{}'! The alias name should be a valid Lua label.", aliasName); + LOG_ERROR(CONTEXT_CLIENT, "Failed to add dependency '{}'! The alias name should be a valid Lua label.", aliasName); return false; } if (SolState::IsReservedModuleName(aliasName)) { - LOG_ERROR_P(CONTEXT_CLIENT, "Failed to add dependency '{}'! The alias collides with a standard library name!", aliasName); + LOG_ERROR(CONTEXT_CLIENT, "Failed to add dependency '{}'! The alias collides with a standard library name!", aliasName); return false; } @@ -32,7 +32,7 @@ namespace ramses::internal if (m_modulesMapping.cend() != m_modulesMapping.find(aliasNameStr)) { - LOG_ERROR_P(CONTEXT_CLIENT, "Module dependencies must be uniquely aliased! Alias '{}' is already used!", aliasName); + LOG_ERROR(CONTEXT_CLIENT, "Module dependencies must be uniquely aliased! Alias '{}' is already used!", aliasName); return false; } @@ -49,7 +49,7 @@ namespace ramses::internal { if (std::find(m_stdModules.cbegin(), m_stdModules.cend(), stdModule) != m_stdModules.cend()) { - LOG_ERROR_P(CONTEXT_CLIENT, "Standard module {} already added, can't add twice!", stdModule); + LOG_ERROR(CONTEXT_CLIENT, "Standard module {} already added, can't add twice!", stdModule); return false; } diff --git a/src/client/impl/logic/NodeBindingImpl.cpp b/src/client/impl/logic/NodeBindingImpl.cpp index 4bec100ae..4edc146a2 100644 --- a/src/client/impl/logic/NodeBindingImpl.cpp +++ b/src/client/impl/logic/NodeBindingImpl.cpp @@ -254,7 +254,7 @@ namespace ramses::internal // Otherwise issue a warning if (euler[0] != 0.f || euler[1] != 0.f || euler[2] != 0.f) { - LOG_WARN_P(CONTEXT_CLIENT, "Initial rotation values for NodeBinding '{}' will not be imported from bound Ramses node due to mismatching rotation type. Expected Quaternion, got Euler.", + LOG_WARN(CONTEXT_CLIENT, "Initial rotation values for NodeBinding '{}' will not be imported from bound Ramses node due to mismatching rotation type. Expected Quaternion, got Euler.", binding.getIdentificationString()); } } @@ -271,7 +271,7 @@ namespace ramses::internal // Otherwise issue a warning if (rotationValue[0] != 0.f || rotationValue[1] != 0.f || rotationValue[2] != 0.f) { - LOG_WARN_P(CONTEXT_CLIENT, "Initial rotation values for NodeBinding '{}' will not be imported from bound Ramses node due to mismatching rotation type.", binding.getIdentificationString()); + LOG_WARN(CONTEXT_CLIENT, "Initial rotation values for NodeBinding '{}' will not be imported from bound Ramses node due to mismatching rotation type.", binding.getIdentificationString()); } } else diff --git a/src/client/impl/logic/Property.cpp b/src/client/impl/logic/Property.cpp index 8c8690d20..eabf6ff64 100644 --- a/src/client/impl/logic/Property.cpp +++ b/src/client/impl/logic/Property.cpp @@ -142,7 +142,7 @@ namespace ramses { if (index >= getOutgoingLinksCount()) { - LOG_ERROR_P(CONTEXT_CLIENT, "Failed to get outgoing link: zero-based index #{} exceeds the total count of outgoing links which is {}.", index, getOutgoingLinksCount()); + LOG_ERROR(CONTEXT_CLIENT, "Failed to get outgoing link: zero-based index #{} exceeds the total count of outgoing links which is {}.", index, getOutgoingLinksCount()); return std::nullopt; } @@ -154,7 +154,7 @@ namespace ramses { if (index >= getOutgoingLinksCount()) { - LOG_ERROR_P(CONTEXT_CLIENT, "Failed to get outgoing link: zero-based index #{} exceeds the total count of outgoing links which is {}.", index, getOutgoingLinksCount()); + LOG_ERROR(CONTEXT_CLIENT, "Failed to get outgoing link: zero-based index #{} exceeds the total count of outgoing links which is {}.", index, getOutgoingLinksCount()); return std::nullopt; } diff --git a/src/client/impl/logic/PropertyImpl.cpp b/src/client/impl/logic/PropertyImpl.cpp index 6fe41c5a5..2ded58995 100644 --- a/src/client/impl/logic/PropertyImpl.cpp +++ b/src/client/impl/logic/PropertyImpl.cpp @@ -434,7 +434,7 @@ namespace ramses::internal return m_children[index].get(); } - LOG_ERROR_P(CONTEXT_CLIENT, "No child property with index '{}' found in '{}'", index, m_typeData.name); + LOG_ERROR(CONTEXT_CLIENT, "No child property with index '{}' found in '{}'", index, m_typeData.name); return nullptr; } @@ -445,7 +445,7 @@ namespace ramses::internal return m_children[index].get(); } - LOG_ERROR_P(CONTEXT_CLIENT, "No child property with index '{}' found in '{}'", index, m_typeData.name); + LOG_ERROR(CONTEXT_CLIENT, "No child property with index '{}' found in '{}'", index, m_typeData.name); return nullptr; } @@ -464,7 +464,7 @@ namespace ramses::internal { return it->get(); } - LOG_ERROR_P(CONTEXT_CLIENT, "No child property with name '{}' found in '{}'", name, m_typeData.name); + LOG_ERROR(CONTEXT_CLIENT, "No child property with name '{}' found in '{}'", name, m_typeData.name); return nullptr; } @@ -509,7 +509,7 @@ namespace ramses::internal assert(std::holds_alternative(m_value)); return std::get(m_value); } - LOG_ERROR_P(CONTEXT_CLIENT, "Invalid type '{}' when accessing property '{}', correct type is '{}'", + LOG_ERROR(CONTEXT_CLIENT, "Invalid type '{}' when accessing property '{}', correct type is '{}'", GetLuaPrimitiveTypeName(PropertyTypeToEnum::TYPE), m_typeData.name, GetLuaPrimitiveTypeName(m_typeData.type)); return std::nullopt; } @@ -530,25 +530,25 @@ namespace ramses::internal { if (m_semantics == EPropertySemantics::ScriptOutput) { - LOG_ERROR_P(CONTEXT_CLIENT, "Cannot set property '{}' which is an output.", m_typeData.name); + LOG_ERROR(CONTEXT_CLIENT, "Cannot set property '{}' which is an output.", m_typeData.name); return false; } if (m_incomingLink.property != nullptr) { - LOG_ERROR_P(CONTEXT_CLIENT, "Property '{}' is currently linked (to property '{}'). Unlink it first before setting its value!", m_typeData.name, m_incomingLink.property->getName()); + LOG_ERROR(CONTEXT_CLIENT, "Property '{}' is currently linked (to property '{}'). Unlink it first before setting its value!", m_typeData.name, m_incomingLink.property->getName()); return false; } if (!TypeUtils::IsPrimitiveType(m_typeData.type)) { - LOG_ERROR_P(CONTEXT_CLIENT, "Property '{}' is not a primitive type, can't set its value directly!", m_typeData.name); + LOG_ERROR(CONTEXT_CLIENT, "Property '{}' is not a primitive type, can't set its value directly!", m_typeData.name); return false; } if (value.index() != m_value.index()) { - LOG_ERROR_P(CONTEXT_CLIENT, "Invalid type when setting property '{}', correct type is '{}'", m_typeData.name, GetLuaPrimitiveTypeName(m_typeData.type)); + LOG_ERROR(CONTEXT_CLIENT, "Invalid type when setting property '{}', correct type is '{}'", m_typeData.name, GetLuaPrimitiveTypeName(m_typeData.type)); return false; } @@ -561,7 +561,7 @@ namespace ramses::internal const auto int64Value = std::get(value); if (int64Value > maxIntegerAsDouble || int64Value < -maxIntegerAsDouble) { - LOG_ERROR_P(CONTEXT_CLIENT, "Invalid value when setting property '{}', Lua cannot handle full range of 64-bit integer, trying to set '{}' which is out of this range!", + LOG_ERROR(CONTEXT_CLIENT, "Invalid value when setting property '{}', Lua cannot handle full range of 64-bit integer, trying to set '{}' which is out of this range!", m_typeData.name, int64Value); return false; } diff --git a/src/client/impl/logic/RenderBufferBinding.cpp b/src/client/impl/logic/RenderBufferBinding.cpp new file mode 100644 index 000000000..56f53383f --- /dev/null +++ b/src/client/impl/logic/RenderBufferBinding.cpp @@ -0,0 +1,40 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#include "ramses/client/logic/RenderBufferBinding.h" +#include "impl/logic/RenderBufferBindingImpl.h" + +namespace ramses +{ + RenderBufferBinding::RenderBufferBinding(std::unique_ptr impl) noexcept + : RamsesBinding{ std::move(impl) } + /* NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) */ + , m_renderBufferBinding{ static_cast(RamsesBinding::m_impl) } + { + } + + const ramses::RenderBuffer& RenderBufferBinding::getRenderBuffer() const + { + return m_renderBufferBinding.getRenderBuffer(); + } + + ramses::RenderBuffer& RenderBufferBinding::getRenderBuffer() + { + return m_renderBufferBinding.getRenderBuffer(); + } + + internal::RenderBufferBindingImpl& RenderBufferBinding::impl() + { + return m_renderBufferBinding; + } + + const internal::RenderBufferBindingImpl& RenderBufferBinding::impl() const + { + return m_renderBufferBinding; + } +} diff --git a/src/client/impl/logic/RenderBufferBindingImpl.cpp b/src/client/impl/logic/RenderBufferBindingImpl.cpp new file mode 100644 index 000000000..3277313e4 --- /dev/null +++ b/src/client/impl/logic/RenderBufferBindingImpl.cpp @@ -0,0 +1,188 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#include "impl/logic/RenderBufferBindingImpl.h" +#include "impl/logic/PropertyImpl.h" +#include "impl/ErrorReporting.h" +#include "impl/RenderBufferImpl.h" +#include "ramses/client/RenderBuffer.h" +#include "ramses/client/logic/Property.h" +#include "ramses/client/ramses-utils.h" +#include "internal/logic/RamsesObjectResolver.h" +#include "internal/logic/flatbuffers/generated/RenderBufferBindingGen.h" +#include "fmt/format.h" + +namespace ramses::internal +{ + RenderBufferBindingImpl::RenderBufferBindingImpl(SceneImpl& scene, ramses::RenderBuffer& renderBuffer, std::string_view name, sceneObjectId_t id) + : RamsesBindingImpl{ scene, name, id } + , m_renderBuffer{ renderBuffer } + { + } + + void RenderBufferBindingImpl::createRootProperties() + { + HierarchicalTypeData inputsType = MakeStruct("", { + TypeData{"width", EPropertyType::Int32}, //EInputProperty::Width + TypeData{"height", EPropertyType::Int32}, //EInputProperty::Height + TypeData{"sampleCount", EPropertyType::Int32}, //EInputProperty::SampleCount + }); + auto inputs = std::make_unique(std::move(inputsType), EPropertySemantics::BindingInput); + + setRootInputs(std::move(inputs)); + + ApplyValuesToInputProperties(*this, m_renderBuffer); + } + + flatbuffers::Offset RenderBufferBindingImpl::Serialize( + const RenderBufferBindingImpl& renderBufferBinding, + flatbuffers::FlatBufferBuilder& builder, + SerializationMap& serializationMap) + { + const auto logicObject = LogicObjectImpl::Serialize(renderBufferBinding, builder); + const auto fbRamsesRef = RamsesBindingImpl::SerializeRamsesReference(renderBufferBinding.m_renderBuffer, builder); + const auto propertyObject = PropertyImpl::Serialize(renderBufferBinding.getInputs()->impl(), builder, serializationMap); + auto fbRamsesBinding = rlogic_serialization::CreateRamsesBinding(builder, + logicObject, + fbRamsesRef, + propertyObject); + + auto fbRenderBufferBinding = rlogic_serialization::CreateRenderBufferBinding(builder, fbRamsesBinding); + builder.Finish(fbRenderBufferBinding); + + return fbRenderBufferBinding; + } + + std::unique_ptr RenderBufferBindingImpl::Deserialize( + const rlogic_serialization::RenderBufferBinding& renderBufferBinding, + const IRamsesObjectResolver& ramsesResolver, + ErrorReporting& errorReporting, + DeserializationMap& deserializationMap) + { + if (!renderBufferBinding.base()) + { + errorReporting.set("Fatal error during loading of RenderBufferBinding from serialized data: missing base class info!", nullptr); + return nullptr; + } + + std::string name; + sceneObjectId_t id{}; + uint64_t userIdHigh = 0u; + uint64_t userIdLow = 0u; + if (!LogicObjectImpl::Deserialize(renderBufferBinding.base()->base(), name, id, userIdHigh, userIdLow, errorReporting)) + { + errorReporting.set("Fatal error during loading of RenderBufferBinding from serialized data: missing name and/or ID!", nullptr); + return nullptr; + } + + if (!renderBufferBinding.base()->rootInput()) + { + errorReporting.set("Fatal error during loading of RenderBufferBinding from serialized data: missing root input!", nullptr); + return nullptr; + } + + std::unique_ptr deserializedRootInput = PropertyImpl::Deserialize(*renderBufferBinding.base()->rootInput(), EPropertySemantics::BindingInput, errorReporting, deserializationMap); + if (!deserializedRootInput) + return nullptr; + + if (deserializedRootInput->getType() != EPropertyType::Struct || + deserializedRootInput->getChildCount() != size_t(EInputProperty::COUNT) || + deserializedRootInput->getChild(size_t(EInputProperty::Width))->getName() != "width" || + deserializedRootInput->getChild(size_t(EInputProperty::Height))->getName() != "height" || + deserializedRootInput->getChild(size_t(EInputProperty::SampleCount))->getName() != "sampleCount") + { + errorReporting.set("Fatal error during loading of RenderBufferBinding from serialized data: corrupted root input!", nullptr); + return nullptr; + } + + const auto* boundObject = renderBufferBinding.base()->boundRamsesObject(); + if (!boundObject) + { + errorReporting.set("Fatal error during loading of RenderBufferBinding from serialized data: missing ramses object reference!", nullptr); + return nullptr; + } + + const ramses::sceneObjectId_t objectId{ boundObject->objectId() }; + ramses::SceneObject* ramsesObject = ramsesResolver.findRamsesSceneObjectInScene(name, objectId); + if (!ramsesObject) + return nullptr; + + if (ramsesObject->getType() != ramses::ERamsesObjectType::RenderBuffer || ramsesObject->getType() != static_cast(boundObject->objectType())) + { + errorReporting.set("Fatal error during loading of RenderBufferBinding from serialized data: loaded object type does not match referenced object type!", nullptr); + return nullptr; + } + + auto* ramsesRenderBuffer = ramsesObject->as(); + assert(ramsesRenderBuffer); + auto binding = std::make_unique(deserializationMap.getScene(), *ramsesRenderBuffer, name, id); + binding->setUserId(userIdHigh, userIdLow); + binding->setRootInputs(std::move(deserializedRootInput)); + + ApplyValuesToInputProperties(*binding, *ramsesRenderBuffer); + + return binding; + } + + std::optional RenderBufferBindingImpl::update() + { + static constexpr auto PropertyCount = static_cast(EInputProperty::COUNT); + std::array props; + std::array propChanges; + for (size_t i = 0; i < PropertyCount; ++i) + { + props[i] = &getInputs()->getChild(i)->impl(); + propChanges[i] = props[i]->checkForBindingInputNewValueAndReset(); + } + // early out if no change + if (std::none_of(propChanges.cbegin(), propChanges.cend(), [](bool x) { return x; })) + return std::nullopt; + + std::array propValues; + for (size_t i = 0; i < PropertyCount; ++i) + { + const auto propValue = props[i]->getValueAs(); + if (propValue < 0) + return LogicNodeRuntimeError{ "RenderBufferBinding input cannot be negative" }; + propValues[i] = static_cast(propValue); + } + + const std::array currValues{ m_renderBuffer.get().getWidth(), m_renderBuffer.get().getHeight(), m_renderBuffer.get().getSampleCount() }; + if (propValues != currValues) + { + if (!m_renderBuffer.get().impl().setProperties( + propValues[size_t(EInputProperty::Width)], + propValues[size_t(EInputProperty::Height)], + propValues[size_t(EInputProperty::SampleCount)])) + { + return LogicNodeRuntimeError{ getErrorReporting().getError()->message }; + } + } + + return std::nullopt; + } + + const ramses::RenderBuffer& RenderBufferBindingImpl::getRenderBuffer() const + { + return m_renderBuffer; + } + + ramses::RenderBuffer& RenderBufferBindingImpl::getRenderBuffer() + { + return m_renderBuffer; + } + + // Overwrites binding value cache silently (without triggering dirty check) - this code is only executed at creation or deserialization, + // should not overwrite values unless set() or link explicitly called + void RenderBufferBindingImpl::ApplyValuesToInputProperties(RenderBufferBindingImpl& binding, ramses::RenderBuffer& renderBuffer) + { + binding.getInputs()->getChild(size_t(EInputProperty::Width))->impl().initializeBindingInputValue(static_cast(renderBuffer.getWidth())); + binding.getInputs()->getChild(size_t(EInputProperty::Height))->impl().initializeBindingInputValue(static_cast(renderBuffer.getHeight())); + binding.getInputs()->getChild(size_t(EInputProperty::SampleCount))->impl().initializeBindingInputValue(static_cast(renderBuffer.getSampleCount())); + } +} diff --git a/src/client/impl/logic/RenderBufferBindingImpl.h b/src/client/impl/logic/RenderBufferBindingImpl.h new file mode 100644 index 000000000..f36f85be0 --- /dev/null +++ b/src/client/impl/logic/RenderBufferBindingImpl.h @@ -0,0 +1,76 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#pragma once + +#include "impl/logic/RamsesBindingImpl.h" +#include + +namespace ramses +{ + class RenderBuffer; +} + +namespace rlogic_serialization +{ + struct RenderBufferBinding; +} + +namespace flatbuffers +{ + template struct Offset; + template class FlatBufferBuilderImpl; + using FlatBufferBuilder = FlatBufferBuilderImpl; +} + +namespace ramses::internal +{ + class IRamsesObjectResolver; + class ErrorReporting; + class SerializationMap; + class DeserializationMap; + + class RenderBufferBindingImpl : public RamsesBindingImpl + { + public: + explicit RenderBufferBindingImpl(SceneImpl& scene, ramses::RenderBuffer& renderBuffer, std::string_view name, sceneObjectId_t id); + ~RenderBufferBindingImpl() noexcept override = default; + + [[nodiscard]] static flatbuffers::Offset Serialize( + const RenderBufferBindingImpl& renderBufferBinding, + flatbuffers::FlatBufferBuilder& builder, + SerializationMap& serializationMap); + + [[nodiscard]] static std::unique_ptr Deserialize( + const rlogic_serialization::RenderBufferBinding& renderBufferBinding, + const IRamsesObjectResolver& ramsesResolver, + ErrorReporting& errorReporting, + DeserializationMap& deserializationMap); + + [[nodiscard]] const ramses::RenderBuffer& getRenderBuffer() const; + [[nodiscard]] ramses::RenderBuffer& getRenderBuffer(); + + std::optional update() override; + + void createRootProperties() final; + + enum class EInputProperty + { + Width = 0, + Height, + SampleCount, + + COUNT + }; + + private: + static void ApplyValuesToInputProperties(RenderBufferBindingImpl& binding, ramses::RenderBuffer& renderBuffer); + + std::reference_wrapper m_renderBuffer; + }; +} diff --git a/src/client/impl/logic/RenderGroupBindingElementsImpl.cpp b/src/client/impl/logic/RenderGroupBindingElementsImpl.cpp index 9bdc1fd1c..d132c4b62 100644 --- a/src/client/impl/logic/RenderGroupBindingElementsImpl.cpp +++ b/src/client/impl/logic/RenderGroupBindingElementsImpl.cpp @@ -20,21 +20,21 @@ namespace ramses::internal if (!m_elements.empty() && !m_elements.front().second->impl().isFromTheSameSceneAs(ramsesObject.impl())) { - LOG_ERROR_P(CONTEXT_CLIENT, "RenderGroupBindingElements: Failed to add element, element is from different Scene than those already added."); + LOG_ERROR(CONTEXT_CLIENT, "RenderGroupBindingElements: Failed to add element, element is from different Scene than those already added."); return false; } std::string name{ elementName.empty() ? ramsesObject.getName() : elementName }; if (name.empty()) { - LOG_ERROR_P(CONTEXT_CLIENT, "RenderGroupBindingElements: Failed to add element, object has no name and provided element name is empty."); + LOG_ERROR(CONTEXT_CLIENT, "RenderGroupBindingElements: Failed to add element, object has no name and provided element name is empty."); return false; } const auto it = std::find_if(m_elements.cbegin(), m_elements.cend(), [&ramsesObject](const auto& e) { return e.second == &ramsesObject; }); if (it != m_elements.cend()) { - LOG_ERROR_P(CONTEXT_CLIENT, "RenderGroupBindingElements: Failed to add element '{}', it is already contained under name '{}'.", name, it->first); + LOG_ERROR(CONTEXT_CLIENT, "RenderGroupBindingElements: Failed to add element '{}', it is already contained under name '{}'.", name, it->first); return false; } diff --git a/src/client/impl/ramses-utils.cpp b/src/client/impl/ramses-utils.cpp index 222791248..b5441eed5 100644 --- a/src/client/impl/ramses-utils.cpp +++ b/src/client/impl/ramses-utils.cpp @@ -78,12 +78,13 @@ namespace ramses const unsigned int ret = lodepng::decode(data, width, height, pngFilePath); if (ret != 0) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesUtils::CreateTextureResourceFromPng: Could not load PNG. File not found or invalid format: " << - pngFilePath << " (error " << ret << ": " << lodepng_error_text(ret) << ")"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesUtils::CreateTextureResourceFromPng: Could not load PNG. File not found or invalid format: {} (error {}: {})", + pngFilePath, ret, lodepng_error_text(ret)); return nullptr; } - const std::vector mipLevelData{ MipLevelData(static_cast(data.size()), data.data()) }; + auto dataBytes = reinterpret_cast(data.data()); + const std::vector mipLevelData{ MipLevelData( dataBytes, dataBytes + data.size() ) }; return scene.createTexture2D(ETextureFormat::RGBA8, width, height, mipLevelData, false, swizzle, name); } @@ -96,11 +97,12 @@ namespace ramses const unsigned int ret = lodepng::decode(data, width, height, pngData.data(), pngData.size()); if (ret != 0) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesUtils::CreateTextureResourceFromPngBuffer: Could not load PNG. Invalid format (error " << ret << ": " << lodepng_error_text(ret) << ")"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesUtils::CreateTextureResourceFromPngBuffer: Could not load PNG. Invalid format (error {}: {})", ret, lodepng_error_text(ret)); return nullptr; } - const std::vector mipLevelData{ MipLevelData(static_cast(data.size()), data.data()) }; + auto dataBytes = reinterpret_cast(data.data()); + const std::vector mipLevelData{ MipLevelData( dataBytes, dataBytes + data.size() ) }; return scene.createTexture2D(ETextureFormat::RGBA8, width, height, mipLevelData, false, swizzle, name); } @@ -127,7 +129,7 @@ namespace ramses const unsigned int ret = lodepng::encode(filePath, reinterpret_cast(imageData.data()), width, height); if (ret != 0) { - LOG_ERROR(ramses::internal::CONTEXT_CLIENT, "RamsesUtils::SaveImageBufferToPng: Error while saving PNG file: " << filePath << " (error " << ret << ": " << lodepng_error_text(ret) << ")"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesUtils::SaveImageBufferToPng: Error while saving PNG file: {} (error {}: {})", filePath, ret, lodepng_error_text(ret)); return false; } return true; @@ -177,13 +179,8 @@ namespace ramses return true; } - MipLevelData* RamsesUtils::GenerateMipMapsTexture2D(uint32_t originalWidth, uint32_t originalHeight, uint8_t bytesPerPixel, std::byte* data, size_t& mipMapCount) + std::vector* RamsesUtils::GenerateMipMapsTexture2D(uint32_t originalWidth, uint32_t originalHeight, uint8_t bytesPerPixel, std::byte* data, size_t& mipMapCount) { - // copy original data - const uint32_t originalSize = originalWidth * originalHeight * bytesPerPixel; - auto* originalData = new std::byte[originalSize]; - ramses::internal::PlatformMemory::Copy(originalData, data, originalSize); - if (!IsPowerOfTwo(originalWidth) || !IsPowerOfTwo(originalHeight)) { // if no mip maps can be created only return original data @@ -195,18 +192,20 @@ namespace ramses } // prepare mip data generation - auto* mipLevelData = new ramses::MipLevelData[mipMapCount]; + auto* mipLevelData = new std::vector(mipMapCount); - mipLevelData[0].m_size = originalSize; - mipLevelData[0].m_data = originalData; + // copy original data + const uint32_t originalSize = originalWidth * originalHeight * bytesPerPixel; + (*mipLevelData)[0].assign(data, data + originalSize); size_t currentMipMapIndex = 1u; while (currentMipMapIndex < mipMapCount) { + const auto& originalData = (*mipLevelData)[currentMipMapIndex-1]; uint32_t nextWidth = std::max(originalWidth >> 1, 1u); uint32_t nextHeight = std::max(originalHeight >> 1, 1u); uint32_t nextSize = nextWidth * nextHeight * bytesPerPixel; - auto* nextData = new std::byte[nextSize]; + (*mipLevelData)[currentMipMapIndex].resize(nextSize); uint32_t originalRowSize = originalWidth * bytesPerPixel; uint32_t nextRowSize = nextWidth * bytesPerPixel; @@ -245,16 +244,11 @@ namespace ramses } } - nextData[nextIndex + i] = std::byte{static_cast(tmp)}; + (*mipLevelData)[currentMipMapIndex][nextIndex + i] = static_cast(tmp); } } } - mipLevelData[currentMipMapIndex].m_size = nextSize; - mipLevelData[currentMipMapIndex].m_data = nextData; - - originalData = nextData; - nextData = nullptr; originalWidth = nextWidth; originalHeight = nextHeight; currentMipMapIndex++; @@ -263,11 +257,11 @@ namespace ramses return mipLevelData; } - CubeMipLevelData* RamsesUtils::GenerateMipMapsTextureCube(uint32_t faceWidth, uint32_t faceHeight, uint8_t bytesPerPixel, std::byte* data, size_t& mipMapCount) + std::vector* RamsesUtils::GenerateMipMapsTextureCube(uint32_t faceWidth, uint32_t faceHeight, uint8_t bytesPerPixel, std::byte* data, size_t& mipMapCount) { const uint32_t faceSize = faceWidth * faceHeight * bytesPerPixel; mipMapCount = 0u; - std::array faceMips{}; + std::array*,6> faceMips{}; faceMips[0] = GenerateMipMapsTexture2D(faceWidth, faceHeight, bytesPerPixel, &data[faceSize * 0], mipMapCount); faceMips[1] = GenerateMipMapsTexture2D(faceWidth, faceHeight, bytesPerPixel, &data[faceSize * 1], mipMapCount); faceMips[2] = GenerateMipMapsTexture2D(faceWidth, faceHeight, bytesPerPixel, &data[faceSize * 2], mipMapCount); @@ -275,49 +269,34 @@ namespace ramses faceMips[4] = GenerateMipMapsTexture2D(faceWidth, faceHeight, bytesPerPixel, &data[faceSize * 4], mipMapCount); faceMips[5] = GenerateMipMapsTexture2D(faceWidth, faceHeight, bytesPerPixel, &data[faceSize * 5], mipMapCount); - auto* cubeMipMaps = new CubeMipLevelData[mipMapCount]; + auto cubeMipMaps = new std::vector(mipMapCount); for (size_t level = 0; level < mipMapCount; level++) { - new (&cubeMipMaps[level]) CubeMipLevelData{ - faceMips[0][level].m_size, - faceMips[0][level].m_data, - faceMips[1][level].m_data, - faceMips[2][level].m_data, - faceMips[3][level].m_data, - faceMips[4][level].m_data, - faceMips[5][level].m_data}; + (*cubeMipMaps)[level] = CubeMipLevelData{ + std::move((*faceMips[0])[level]), + std::move((*faceMips[1])[level]), + std::move((*faceMips[2])[level]), + std::move((*faceMips[3])[level]), + std::move((*faceMips[4])[level]), + std::move((*faceMips[5])[level])}; } - for (uint8_t level = 0; level < 6u; level++) + for (auto*& ptr : faceMips) { - delete[] faceMips[level]; + delete ptr; } return cubeMipMaps; } - void RamsesUtils::DeleteGeneratedMipMaps(MipLevelData*& data, size_t mipMapCount) + void RamsesUtils::DeleteGeneratedMipMaps(std::vector*& data) { - for (size_t i = 0; i < mipMapCount; i++) - { - delete[] data[i].m_data; - } - - delete[] data; + delete data; data = nullptr; } - void RamsesUtils::DeleteGeneratedMipMaps(CubeMipLevelData*& data, size_t mipMapCount) + void RamsesUtils::DeleteGeneratedMipMaps(std::vector*& data) { - for (size_t level = 0u; level < mipMapCount; level++) - { - delete[] data[level].m_dataPX; - delete[] data[level].m_dataNX; - delete[] data[level].m_dataPY; - delete[] data[level].m_dataNY; - delete[] data[level].m_dataPZ; - delete[] data[level].m_dataNZ; - } - delete[] data; + delete data; data = nullptr; } diff --git a/src/client/impl/text/FontRegistryImpl.cpp b/src/client/impl/text/FontRegistryImpl.cpp index 627994540..0826af05c 100644 --- a/src/client/impl/text/FontRegistryImpl.cpp +++ b/src/client/impl/text/FontRegistryImpl.cpp @@ -29,7 +29,7 @@ namespace ramses::internal if (error != 0) { Ft2Library = nullptr; - LOG_ERROR(CONTEXT_TEXT, "SharedFTLibrary: Failed to initialize FreeType with error " << error); + LOG_ERROR(CONTEXT_TEXT, "SharedFTLibrary: Failed to initialize FreeType with error {}", error); } } NumRefs++; @@ -62,11 +62,11 @@ namespace ramses::internal // basic checks if (fontPath.empty() || !ramses::internal::File(fontPath).exists()) { - LOG_ERROR(CONTEXT_TEXT, "FontRegistry::createFreetype2Font: Font file not found " << fontPath); + LOG_ERROR(CONTEXT_TEXT, "FontRegistry::createFreetype2Font: Font file not found {}", fontPath); return {}; } - LOG_INFO_P(CONTEXT_CLIENT, "FontRegistry::createFreetype2Font: path {}", fontPath); + LOG_INFO(CONTEXT_CLIENT, "FontRegistry::createFreetype2Font: path {}", fontPath); return createFreetype2FontCommon(std::make_unique(fontPath, SharedFTLibrary::Get())); } @@ -75,7 +75,7 @@ namespace ramses::internal // basic checks if (fd <= 0) { - LOG_ERROR(CONTEXT_CLIENT, "FontRegistry::createFreetype2FontFromFileDescriptor: filedescriptor must be valid " << fd); + LOG_ERROR(CONTEXT_CLIENT, "FontRegistry::createFreetype2FontFromFileDescriptor: filedescriptor must be valid {}", fd); return {}; } if (length == 0) @@ -84,7 +84,7 @@ namespace ramses::internal return {}; } - LOG_INFO_P(CONTEXT_CLIENT, "FontRegistry::createFreetype2FontFromFileDescriptor: fd {}, offset {}, length {}", fd, offset, length); + LOG_INFO(CONTEXT_CLIENT, "FontRegistry::createFreetype2FontFromFileDescriptor: fd {}, offset {}, length {}", fd, offset, length); return createFreetype2FontCommon(std::make_unique(fd, offset, length, SharedFTLibrary::Get())); } @@ -106,7 +106,7 @@ namespace ramses::internal { if (m_fonts.erase(fontId) == 0u) { - LOG_ERROR(CONTEXT_TEXT, "FontRegistryImpl::deleteFont: Cannot delete font " << fontId << ", no such entry"); + LOG_ERROR(CONTEXT_TEXT, "FontRegistryImpl::deleteFont: Cannot delete font {}, no such entry", fontId); return false; } return true; @@ -117,7 +117,7 @@ namespace ramses::internal const auto fontIt = m_fonts.find(fontId); if (fontIt == m_fonts.cend()) { - LOG_ERROR(CONTEXT_TEXT, "FontRegistry: Failed to create font instance, fontId " << fontId << " does not exist"); + LOG_ERROR(CONTEXT_TEXT, "FontRegistry: Failed to create font instance, fontId {} does not exist", fontId); return {}; } @@ -132,7 +132,7 @@ namespace ramses::internal const auto fontIt = m_fonts.find(fontId); if (fontIt == m_fonts.cend()) { - LOG_ERROR(CONTEXT_TEXT, "FontRegistry: Failed to create font instance, fontId " << fontId << " does not exist"); + LOG_ERROR(CONTEXT_TEXT, "FontRegistry: Failed to create font instance, fontId {} does not exist", fontId); return {}; } @@ -146,7 +146,7 @@ namespace ramses::internal { if (m_fontInstances.erase(fontInstance) == 0u) { - LOG_ERROR(CONTEXT_TEXT, "FontRegistryImpl::deleteFontInstance: Cannot delete font instance " << fontInstance << ", no such entry"); + LOG_ERROR(CONTEXT_TEXT, "FontRegistryImpl::deleteFontInstance: Cannot delete font instance {}, no such entry", fontInstance); return false; } return true; diff --git a/src/client/impl/text/Freetype2FontInstance.cpp b/src/client/impl/text/Freetype2FontInstance.cpp index caf473ed9..62dd7b3ea 100644 --- a/src/client/impl/text/Freetype2FontInstance.cpp +++ b/src/client/impl/text/Freetype2FontInstance.cpp @@ -22,14 +22,14 @@ namespace ramses::internal { int error = FT_New_Size(m_face, &m_size); if (error != 0) - LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance: Failed to initialize FT size, FT error " << error); + LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance: Failed to initialize FT size, FT error {}", error); assert(0 == error); activateSize(); error = FT_Set_Pixel_Sizes(m_face, 0, pixelSize); if (error != 0) - LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance: Failed to set pixel sizes, FT error " << error); + LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance: Failed to set pixel sizes, FT error {}", error); assert(0 == error); m_height = static_cast(m_size->metrics.height / 64); @@ -142,7 +142,7 @@ namespace ramses::internal { if (error != 0) { - LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance::extractGlyphBitmapData: FT_Get_Glyph failed - error: " << error); + LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance::extractGlyphBitmapData: FT_Get_Glyph failed - error: {}", error); assert(ftGlyph == nullptr); return nullptr; } @@ -153,7 +153,7 @@ namespace ramses::internal error = FT_Glyph_To_Bitmap(&ftGlyph, FT_RENDER_MODE_NORMAL, nullptr, 1); if (error != 0) { - LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance::extractGlyphBitmapData: FT_Glyph_To_Bitmap failed - error: " << error); + LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance::extractGlyphBitmapData: FT_Glyph_To_Bitmap failed - error: {}", error); FT_Done_Glyph(ftGlyph); return nullptr; } @@ -177,7 +177,7 @@ namespace ramses::internal { if (glyphId.getValue() == 0) { - LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance: Failed to load glyph " << glyphId << ", invalid character"); + LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance: Failed to load glyph {}, invalid character", glyphId); return false; } @@ -191,7 +191,7 @@ namespace ramses::internal const uint32_t error = FT_Load_Glyph(m_face, glyphId.getValue(), flags); if (error != 0) { - LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance: Failed to load glyph " << glyphId << ", FT error " << error); + LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance: Failed to load glyph {}, FT error {}", glyphId, error); return false; } @@ -203,7 +203,7 @@ namespace ramses::internal const uint32_t error = FT_Activate_Size(m_size); if (error != 0u) { - LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance::activateSize: FT_Activate_Size failed - error: " << error); + LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance::activateSize: FT_Activate_Size failed - error: {}", error); assert(false); } } @@ -219,7 +219,7 @@ namespace ramses::internal FT_Get_Kerning(m_face, glyphIdentifier1.getValue(), glyphIdentifier2.getValue(), FT_KERNING_DEFAULT, &delta); return static_cast(delta.x / 64); } - LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance::getKerningAdvance: Character not found for kerning; Character codes: " << glyphIdentifier1 << ", " << glyphIdentifier2); + LOG_ERROR(CONTEXT_TEXT, "Freetype2FontInstance::getKerningAdvance: Character not found for kerning; Character codes: {}, {}", glyphIdentifier1, glyphIdentifier2); } return 0; diff --git a/src/client/impl/text/FreetypeFontFace.cpp b/src/client/impl/text/FreetypeFontFace.cpp index de91237a1..2ef7523a2 100644 --- a/src/client/impl/text/FreetypeFontFace.cpp +++ b/src/client/impl/text/FreetypeFontFace.cpp @@ -25,7 +25,7 @@ namespace ramses::internal int32_t error = FT_Open_Face(m_freetypeLib, fontDataArgs, -1, &localFaceForQuery); if (error != 0) { - LOG_ERROR(CONTEXT_TEXT, "FreetypeFontFace::initFromOpenArgs: Failed to open face, FT error " << error); + LOG_ERROR(CONTEXT_TEXT, "FreetypeFontFace::initFromOpenArgs: Failed to open face, FT error {}", error); return false; } if (localFaceForQuery->num_faces < 1) @@ -35,7 +35,7 @@ namespace ramses::internal return false; } if (localFaceForQuery->num_faces > 1) - LOG_INFO(CONTEXT_TEXT, "FreetypeFontFace::initFromOpenArgs: current implementation does not support multiple faces, face with index 0 will be used (" << localFaceForQuery->num_faces << " faces found in file)"); + LOG_INFO(CONTEXT_TEXT, "FreetypeFontFace::initFromOpenArgs: current implementation does not support multiple faces, face with index 0 will be used ({} faces found in file)", localFaceForQuery->num_faces); // close temporary face FT_Done_Face(localFaceForQuery); @@ -47,7 +47,7 @@ namespace ramses::internal int32_t error = FT_Open_Face(m_freetypeLib, fontDataArgs, 0, &localFace); if (error != 0) { - LOG_ERROR(CONTEXT_TEXT, "FreetypeFontFace::initFromOpenArgs: Failed to open face, FT error " << error); + LOG_ERROR(CONTEXT_TEXT, "FreetypeFontFace::initFromOpenArgs: Failed to open face, FT error {}", error); return false; } diff --git a/src/client/impl/text/GlyphTexturePage.cpp b/src/client/impl/text/GlyphTexturePage.cpp index 4f50d07c8..b31ee94b8 100644 --- a/src/client/impl/text/GlyphTexturePage.cpp +++ b/src/client/impl/text/GlyphTexturePage.cpp @@ -200,7 +200,7 @@ namespace ramses::internal void GlyphTexturePage::updateTextureResource(const Quad& updateQuade, const GlyphPageData& pageData) { - m_textureBuffer.updateData(0, updateQuade.getOrigin().x, updateQuade.getOrigin().y, updateQuade.getSize().x, updateQuade.getSize().y, pageData.data()); + m_textureBuffer.updateData(0, updateQuade.getOrigin().x, updateQuade.getOrigin().y, updateQuade.getSize().x, updateQuade.getSize().y, reinterpret_cast(pageData.data())); } GlyphTexturePage::QuadIndex GlyphTexturePage::findFreeSpace(QuadSize const& size) const diff --git a/src/client/impl/text/TextCacheImpl.cpp b/src/client/impl/text/TextCacheImpl.cpp index 6b7eaf922..531dc19e2 100644 --- a/src/client/impl/text/TextCacheImpl.cpp +++ b/src/client/impl/text/TextCacheImpl.cpp @@ -54,7 +54,7 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_TEXT, "TextCache::getPositionedGlyphs: Could not find font instance " << fontIt->fontInstance); + LOG_ERROR(CONTEXT_TEXT, "TextCache::getPositionedGlyphs: Could not find font instance {}", fontIt->fontInstance); } } @@ -91,7 +91,7 @@ namespace ramses::internal IFontInstance* fontInstance = m_fontAccessor.getFontInstance(glyph.key.fontInstanceId); if (fontInstance == nullptr) { - LOG_ERROR(CONTEXT_TEXT, "TextCache::createTextLine: Could not find font instance " << glyph.key.fontInstanceId); + LOG_ERROR(CONTEXT_TEXT, "TextCache::createTextLine: Could not find font instance {}", glyph.key.fontInstanceId); return {}; } QuadSize glyphSize; @@ -174,7 +174,7 @@ namespace ramses::internal { if (m_textLines.count(textId) != 1) { - LOG_ERROR(CONTEXT_TEXT, "TextCache::deleteTextLine: Cannot delete text line " << textId << ", no such entry"); + LOG_ERROR(CONTEXT_TEXT, "TextCache::deleteTextLine: Cannot delete text line {}, no such entry", textId); return false; } diff --git a/src/client/impl/text/UtfUtils.cpp b/src/client/impl/text/UtfUtils.cpp index f5ed91676..88a8a51e5 100644 --- a/src/client/impl/text/UtfUtils.cpp +++ b/src/client/impl/text/UtfUtils.cpp @@ -131,7 +131,7 @@ namespace ramses } else { - LOG_ERROR(CONTEXT_TEXT, "UtfUtils::ConvertCharUtf32ToUtf8: invalid Unicode " << static_cast(convertChar) << " Skipping Character\n" ); + LOG_ERROR(CONTEXT_TEXT, "UtfUtils::ConvertCharUtf32ToUtf8: invalid Unicode {} Skipping Character\n", static_cast(convertChar)); } return utf8string; @@ -165,7 +165,7 @@ namespace ramses if (!UtfUtils::IsValidUTF8Byte(currentByte)) { //invalid byte - LOG_ERROR(CONTEXT_TEXT, "UtfUtils: invalid UTF-8 byte " << currentByte); + LOG_ERROR(CONTEXT_TEXT, "UtfUtils: invalid UTF-8 byte {}", currentByte); result.extractionSuccessful = false; break; } @@ -176,7 +176,7 @@ namespace ramses { //trailing byte expected, but lead byte found //previous character did not finish correctly - LOG_ERROR(CONTEXT_TEXT, "UtfUtils: unexpected UTF-8 lead byte " << currentByte << "! Aborting previous code point and re-starting from this one"); + LOG_ERROR(CONTEXT_TEXT, "UtfUtils: unexpected UTF-8 lead byte {}! Aborting previous code point and re-starting from this one", currentByte); result.extractionSuccessful = false; // TODO Violin this is weird logic... We "unread" this unexpected lead byte and pretend we didn't see the wrong bytes before // Check if there is a better way @@ -212,11 +212,11 @@ namespace ramses } else { - LOG_ERROR(CONTEXT_TEXT, "UtfUtils::GetNextUTF8CharacterFromStream: overlong encoded UTF-8 character " << result.codePoint); + LOG_ERROR(CONTEXT_TEXT, "UtfUtils::GetNextUTF8CharacterFromStream: overlong encoded UTF-8 character {}", result.codePoint); } } else - LOG_ERROR(CONTEXT_TEXT, "UtfUtils::GetNextUTF8CharacterFromStream invalid UTF-8 code point " << result.codePoint); + LOG_ERROR(CONTEXT_TEXT, "UtfUtils::GetNextUTF8CharacterFromStream invalid UTF-8 code point {}", result.codePoint); // TODO Violin this is wrong! If the codepoint is invalid, it should not be returned // Otherwise this might result in further errors along the text processing stages @@ -227,7 +227,7 @@ namespace ramses else { //lead byte expected, but continuation byte, something is wrong - LOG_ERROR(CONTEXT_TEXT, "UtfUtils::GetNextUTF8CharacterFromStream: unexpected UTF-8 continuation byte " << currentByte); + LOG_ERROR(CONTEXT_TEXT, "UtfUtils::GetNextUTF8CharacterFromStream: unexpected UTF-8 continuation byte {}", currentByte); result.extractionSuccessful = false; break; } @@ -255,7 +255,7 @@ namespace ramses { if (lowSurrogateExpected) { - LOG_ERROR(CONTEXT_TEXT, "UtfUtils::ExtractUnicodePointFromUTF16Array: unexpected UTF-16 word " << currentWord << ", low surrogate was expected"); + LOG_ERROR(CONTEXT_TEXT, "UtfUtils::ExtractUnicodePointFromUTF16Array: unexpected UTF-16 word {}, low surrogate was expected", currentWord); // TODO Violin this looks quite weird, check if it is correct to "unread" one word --strBegin; result.extractionSuccessful = false; @@ -271,7 +271,7 @@ namespace ramses { if (lowSurrogateExpected) { - LOG_ERROR(CONTEXT_TEXT, "UtfUtils::ExtractUnicodePointFromUTF16Array: unexpected UTF-16 high surrogate " << currentWord << " in string, low surrogate was expected"); + LOG_ERROR(CONTEXT_TEXT, "UtfUtils::ExtractUnicodePointFromUTF16Array: unexpected UTF-16 high surrogate {} in string, low surrogate was expected", currentWord); // TODO Violin this looks quite weird, check if it is correct to "unread" one word --strBegin; result.extractionSuccessful = false; @@ -284,7 +284,7 @@ namespace ramses { if (!lowSurrogateExpected) { - LOG_ERROR(CONTEXT_TEXT, "UtfUtils::ExtractUnicodePointFromUTF16Array: unexpected UTF-16 low surrogate " << currentWord << " in string, no high surrogate"); + LOG_ERROR(CONTEXT_TEXT, "UtfUtils::ExtractUnicodePointFromUTF16Array: unexpected UTF-16 low surrogate {} in string, no high surrogate", currentWord); result.extractionSuccessful = false; break; } diff --git a/src/client/internal/CMakeLists.txt b/src/client/internal/CMakeLists.txt new file mode 100644 index 000000000..ec3098a26 --- /dev/null +++ b/src/client/internal/CMakeLists.txt @@ -0,0 +1,50 @@ +# ------------------------------------------------------------------------- +# Copyright (C) 2023 BMW AG +# ------------------------------------------------------------------------- +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# ------------------------------------------------------------------------- + +if(ramses-sdk_TEXT_SUPPORT) + list(APPEND CLIENT_INTERNAL_LIBS freetype + harfbuzz) +endif() + +if(ramses-sdk_ENABLE_LOGIC) + list(APPEND CLIENT_INTERNAL_SOURCES logic/*.h + logic/*.cpp + logic/flatbuffers/generated/*.h + logic/flatbuffers/schemas/*.fbs) + list(APPEND CLIENT_INTERNAL_LIBS sol2::sol2 + lua::lua + ramses::flatbuffers + fmt::fmt) +endif() + +createModule( + NAME ramses-client-internal + TYPE OBJECT + ENABLE_INSTALL OFF + INCLUDE_PATHS ${PROJECT_SOURCE_DIR}/src/client + + SRC_FILES *.h + *.cpp + glslEffectBlock/*.h + glslEffectBlock/*.cpp + ClientCommands/*.h + ClientCommands/*.cpp + ${CLIENT_INTERNAL_SOURCES} + DEPENDENCIES ramses-api + ramses-framework-internal + ramses-glslang + ${CLIENT_INTERNAL_LIBS} +) + +if(TARGET FlatbufGen) + add_dependencies(ramses-client-internal FlatbufGen) +endif() + +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + target_compile_options(ramses-client-internal PRIVATE "-Wsuggest-override") +endif() diff --git a/src/client/internal/ClientApplicationLogic.cpp b/src/client/internal/ClientApplicationLogic.cpp index bddb0897b..51826cad1 100644 --- a/src/client/internal/ClientApplicationLogic.cpp +++ b/src/client/internal/ClientApplicationLogic.cpp @@ -43,7 +43,7 @@ namespace ramses::internal void ClientApplicationLogic::createScene(ClientScene& scene, bool enableLocalOnlyOptimization) { PlatformGuard guard(m_frameworkLock); - LOG_TRACE(CONTEXT_CLIENT, "ClientApplicationLogic::createScene: '" << scene.getName() << "' with id '" << scene.getSceneId().getValue() << "'"); + LOG_TRACE(CONTEXT_CLIENT, "ClientApplicationLogic::createScene: '{}' with id '{}'", scene.getName(), scene.getSceneId().getValue()); m_scenegraphProviderComponent->handleCreateScene(scene, enableLocalOnlyOptimization, *this); } @@ -150,7 +150,7 @@ namespace ramses::internal PlatformGuard guard(m_frameworkLock); auto mr = m_resourceComponent->loadResource(hash); if (!mr) - LOG_WARN(CONTEXT_FRAMEWORK, "ResourceComponent::loadResource: Could not find or load requested resource: " << hash); + LOG_WARN(CONTEXT_FRAMEWORK, "ResourceComponent::loadResource: Could not find or load requested resource: {}", hash); return mr; } diff --git a/src/client/internal/ClientCommands/DumpSceneToFile.cpp b/src/client/internal/ClientCommands/DumpSceneToFile.cpp index 5c408eca1..1c9f0ff52 100644 --- a/src/client/internal/ClientCommands/DumpSceneToFile.cpp +++ b/src/client/internal/ClientCommands/DumpSceneToFile.cpp @@ -50,12 +50,12 @@ namespace ramses::internal case 2: if (!command.sendViaDLT) { - LOG_ERROR_P(CONTEXT_RAMSH, "Expected [filename] or -sendViaDlt"); + LOG_ERROR(CONTEXT_RAMSH, "Expected [filename] or -sendViaDlt"); return false; } break; default: - LOG_ERROR_P(CONTEXT_RAMSH, "None or too many arguments provided: {}", arguments.size() - 1); + LOG_ERROR(CONTEXT_RAMSH, "None or too many arguments provided: {}", arguments.size() - 1); return false; } @@ -63,7 +63,7 @@ namespace ramses::internal ramses::internal::ArgumentConverter::tryConvert(arguments[1], sceneId.getReference()); if (!sceneId.isValid()) { - LOG_ERROR_P(CONTEXT_RAMSH, "Invalid SceneId: {}", arguments[0]); + LOG_ERROR(CONTEXT_RAMSH, "Invalid SceneId: {}", arguments[0]); return false; } @@ -73,7 +73,7 @@ namespace ramses::internal auto* scene = m_client.getScene(sceneId); if (!scene) { - LOG_ERROR_P(CONTEXT_RAMSH, "Scene not available: {}", sceneId); + LOG_ERROR(CONTEXT_RAMSH, "Scene not available: {}", sceneId); return false; } scene->flush(); diff --git a/src/client/internal/ClientCommands/SceneCommandVisitor.cpp b/src/client/internal/ClientCommands/SceneCommandVisitor.cpp index 2ac09fb5d..fb05088eb 100644 --- a/src/client/internal/ClientCommands/SceneCommandVisitor.cpp +++ b/src/client/internal/ClientCommands/SceneCommandVisitor.cpp @@ -22,7 +22,7 @@ namespace ramses::internal void SceneCommandVisitor::operator()(const SceneCommandFlushSceneVersion& cmd) { - LOG_INFO(CONTEXT_CLIENT, "SceneCommandVisitor::execute: set scene version in next flush to \"" << cmd.sceneVersion << "\""); + LOG_INFO(CONTEXT_CLIENT, "SceneCommandVisitor::execute: set scene version in next flush to \"{}\"", cmd.sceneVersion); m_scene.setSceneVersionForNextFlush(cmd.sceneVersion); } @@ -33,7 +33,7 @@ namespace ramses::internal // no object, validate whole scene ValidationReportImpl report; m_scene.validate(report); - LOG_INFO(CONTEXT_CLIENT, "Validation: " << report.toString()); + LOG_INFO(CONTEXT_CLIENT, "Validation: {}", report.toString()); } else { @@ -41,10 +41,10 @@ namespace ramses::internal { ValidationReportImpl report; ro->impl().validate(report); - LOG_INFO(CONTEXT_CLIENT, "Validation: " << report.toString()); + LOG_INFO(CONTEXT_CLIENT, "Validation: {}", report.toString()); } else - LOG_ERROR(CONTEXT_CLIENT, "Validation could not find requested object with name: " << cmd.optionalObjectName); + LOG_ERROR(CONTEXT_CLIENT, "Validation could not find requested object with name: {}", cmd.optionalObjectName); } } @@ -52,11 +52,10 @@ namespace ramses::internal { std::vector sceneData; SaveFileConfigImpl config; - config.setValidationEnabled(false); config.setCompressionEnabled(false); if (!m_scene.serialize(sceneData, config)) { - LOG_ERROR_P(CONTEXT_CLIENT, "SceneCommandVisitor::execute: failed dump scene: {} (file:{} dlt:{})", m_scene.getSceneId(), cmd.fileName, cmd.sendViaDLT); + LOG_ERROR(CONTEXT_CLIENT, "SceneCommandVisitor::execute: failed dump scene: {} (file:{} dlt:{})", m_scene.getSceneId(), cmd.fileName, cmd.sendViaDLT); return; } @@ -68,12 +67,12 @@ namespace ramses::internal { if (!file.write(sceneData.data(), sceneData.size())) { - LOG_ERROR_P(CONTEXT_CLIENT, "SceneCommandVisitor::execute: failed to write scene dump: {}", file.getPath()); + LOG_ERROR(CONTEXT_CLIENT, "SceneCommandVisitor::execute: failed to write scene dump: {}", file.getPath()); } } else { - LOG_ERROR_P(CONTEXT_CLIENT, "SceneCommandVisitor::execute: failed to open: {}", file.getPath()); + LOG_ERROR(CONTEXT_CLIENT, "SceneCommandVisitor::execute: failed to open: {}", file.getPath()); } } @@ -81,11 +80,11 @@ namespace ramses::internal { if (GetRamsesLogger().transmit(std::move(sceneData), filename)) { - LOG_INFO_P(CONTEXT_CLIENT, "SceneCommandVisitor::execute: started dlt file transfer: {}", filename); + LOG_INFO(CONTEXT_CLIENT, "SceneCommandVisitor::execute: started dlt file transfer: {}", filename); } else { - LOG_ERROR_P(CONTEXT_CLIENT, "SceneCommandVisitor::execute: failed to send scene dump file via dlt: {}", filename); + LOG_ERROR(CONTEXT_CLIENT, "SceneCommandVisitor::execute: failed to send scene dump file via dlt: {}", filename); } } } diff --git a/src/client/internal/RamsesVersion.cpp b/src/client/internal/RamsesVersion.cpp index af461bc94..eef9d8758 100644 --- a/src/client/internal/RamsesVersion.cpp +++ b/src/client/internal/RamsesVersion.cpp @@ -23,7 +23,7 @@ namespace ramses::internal { void WriteToStream(IOutputStream& stream, std::string_view versionString, std::string_view gitHash, EFeatureLevel featureLevel) { - LOG_INFO(CONTEXT_CLIENT, "RamsesVersion::WriteToStream: Version: " << versionString << " Git Hash: " << gitHash << " Feature Level: " << featureLevel); + LOG_INFO(CONTEXT_CLIENT, "RamsesVersion::WriteToStream: Version: {} Git Hash: {} Feature Level: {}", versionString, gitHash, featureLevel); StringOutputStream out; out << "[RamsesVersion:" << versionString << "]\n[GitHash:" << gitHash << "]\n[FeatureLevel:" << featureLevel << "]\n"; stream.write(out.c_str(), out.size()); @@ -141,7 +141,7 @@ namespace ramses::internal if (!IsFeatureLevel(num)) { - LOG_ERROR(CONTEXT_CLIENT, "RamsesVersion::ReadFromStream: Unknown feature level " << num << " in file, either file corrupt or file exported with future version"); + LOG_ERROR(CONTEXT_CLIENT, "RamsesVersion::ReadFromStream: Unknown feature level {} in file, either file corrupt or file exported with future version", num); return false; } outFeatureLevel = static_cast(num); diff --git a/src/client/internal/logic/ApiObjects.cpp b/src/client/internal/logic/ApiObjects.cpp index 4684bbeb6..f005d1fb6 100644 --- a/src/client/internal/logic/ApiObjects.cpp +++ b/src/client/internal/logic/ApiObjects.cpp @@ -28,6 +28,7 @@ #include "ramses/client/logic/AnimationNode.h" #include "ramses/client/logic/TimerNode.h" #include "ramses/client/logic/AnchorPoint.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "impl/ValidationReportImpl.h" #include "impl/logic/PropertyImpl.h" @@ -46,6 +47,7 @@ #include "impl/logic/AnimationNodeConfigImpl.h" #include "impl/logic/TimerNodeImpl.h" #include "impl/logic/AnchorPointImpl.h" +#include "impl/logic/RenderBufferBindingImpl.h" #include "ramses/client/Scene.h" #include "ramses/client/Node.h" @@ -64,6 +66,7 @@ #include "internal/logic/flatbuffers/generated/DataArrayGen.h" #include "internal/logic/flatbuffers/generated/AnimationNodeGen.h" #include "internal/logic/flatbuffers/generated/TimerNodeGen.h" +#include "internal/logic/flatbuffers/generated/RenderBufferBindingGen.h" #include "fmt/format.h" #include "TypeUtils.h" @@ -274,6 +277,13 @@ namespace ramses::internal return &anchor; } + RenderBufferBinding* ApiObjects::createRenderBufferBinding(ramses::RenderBuffer& renderBuffer, std::string_view name) + { + auto impl = std::make_unique(m_scene, renderBuffer, name, sceneObjectId_t{}); + impl->createRootProperties(); + return &createAndRegisterObject(std::move(impl)); + } + bool ApiObjects::destroy(LogicObject& object, ErrorReporting& errorReporting) { auto luaScript = dynamic_cast(&object); @@ -332,6 +342,10 @@ namespace ramses::internal if (anchor) return destroyInternal(*anchor, errorReporting); + auto renderBufferBinding = dynamic_cast(&object); + if (renderBufferBinding) + return destroyAndUnregisterObject(*renderBufferBinding, errorReporting); + errorReporting.set(fmt::format("Tried to destroy object '{}' with unknown type", object.getName()), &object); return false; @@ -518,6 +532,10 @@ namespace ramses::internal { this->m_anchorPoints.push_back(&objRaw); } + else if constexpr (std::is_same_v) + { + this->m_renderBufferBindings.push_back(&objRaw); + } else { assert(!"unhandled type"); @@ -612,6 +630,10 @@ namespace ramses::internal { eraseFromPool(objToDelete, this->m_anchorPoints); } + else if constexpr (std::is_same_v) + { + eraseFromPool(objToDelete, this->m_renderBufferBindings); + } else { assert(!"unhandled type"); @@ -715,7 +737,7 @@ namespace ramses::internal anyInputLinked |= (input->hasIncomingLink()); if (!anyInputLinked) - report.add(EIssueType::Warning, fmt::format("Node [{}] has no ingoing links! Node should be deleted or properly linked!", objAsNode->getName()), objAsNode); + report.add(EIssueType::Warning, fmt::format("Node [{}] has no incoming links! Node should be deleted or properly linked!", objAsNode->getName()), objAsNode); } } } @@ -784,6 +806,10 @@ namespace ramses::internal { return m_anchorPoints; } + else if constexpr (std::is_same_v) + { + return m_renderBufferBindings; + } } template @@ -907,6 +933,11 @@ namespace ramses::internal for (const auto& skinBinding : apiObjects.m_skinBindings) skinBindings.push_back(SkinBindingImpl::Serialize(skinBinding->impl(), builder, serializationMap)); + std::vector> rbBindings; + rbBindings.reserve(apiObjects.m_renderBufferBindings.size()); + for (const auto& rbBinding : apiObjects.m_renderBufferBindings) + rbBindings.push_back(RenderBufferBindingImpl::Serialize(rbBinding->impl(), builder, serializationMap)); + // links must go last due to dependency on serialized properties const auto collectedLinks = apiObjects.collectPropertyLinks(); std::vector> links; @@ -934,6 +965,7 @@ namespace ramses::internal const auto fbRenderGroupBindings = builder.CreateVector(renderGroupBindings); const auto fbMeshNodeBindings = builder.CreateVector(meshNodeBindings); const auto fbSkinBindings = builder.CreateVector(skinBindings); + const auto fbRbBindings = builder.CreateVector(rbBindings); const auto logicEngine = rlogic_serialization::CreateApiObjects( builder, @@ -951,7 +983,8 @@ namespace ramses::internal fbAnchorPoints, fbRenderGroupBindings, fbSkinBindings, - fbMeshNodeBindings + fbMeshNodeBindings, + fbRbBindings ); builder.Finish(logicEngine); @@ -1063,6 +1096,12 @@ namespace ramses::internal return nullptr; } + if (!apiObjects.renderBufferBindings()) + { + errorReporting.set("Fatal error during loading from serialized data: missing render buffer bindings container!", nullptr); + return nullptr; + } + const size_t logicObjectsTotalSize = static_cast(apiObjects.luaModules()->size()) + static_cast(apiObjects.luaScripts()->size()) + @@ -1077,7 +1116,8 @@ namespace ramses::internal static_cast(apiObjects.anchorPoints()->size()) + static_cast(apiObjects.renderGroupBindings()->size()) + static_cast(apiObjects.meshNodeBindings()->size()) + - static_cast(apiObjects.skinBindings()->size()); + static_cast(apiObjects.skinBindings()->size()) + + static_cast(apiObjects.renderBufferBindings()->size()); deserialized->m_objectsOwningContainer.reserve(logicObjectsTotalSize); deserialized->m_logicObjects.reserve(logicObjectsTotalSize); @@ -1260,6 +1300,18 @@ namespace ramses::internal deserialized->createAndRegisterObject(std::move(deserializedBinding)); } + const auto& rbBindings = *apiObjects.renderBufferBindings(); + deserialized->m_renderBufferBindings.reserve(rbBindings.size()); + for (const auto* binding : rbBindings) + { + assert(binding); + std::unique_ptr deserializedBinding = RenderBufferBindingImpl::Deserialize(*binding, ramsesResolver, errorReporting, deserializationMap); + if (!deserializedBinding) + return nullptr; + + deserialized->createAndRegisterObject(std::move(deserializedBinding)); + } + // links must go last due to dependency on deserialized properties const auto& links = *apiObjects.links(); // TODO Violin move this code (serialization parts too) to LogicNodeDependencies @@ -1311,7 +1363,8 @@ namespace ramses::internal std::any_of(m_renderPassBindings.cbegin(), m_renderPassBindings.cend(), [](const auto& b) { return b->m_impl.isDirty(); }) || std::any_of(m_renderGroupBindings.cbegin(), m_renderGroupBindings.cend(), [](const auto& b) { return b->m_impl.isDirty(); }) || std::any_of(m_meshNodeBindings.cbegin(), m_meshNodeBindings.cend(), [](const auto& b) { return b->m_impl.isDirty(); }) || - std::any_of(m_skinBindings.cbegin(), m_skinBindings.cend(), [](const auto& b) { return b->m_impl.isDirty(); }); + std::any_of(m_skinBindings.cbegin(), m_skinBindings.cend(), [](const auto& b) { return b->m_impl.isDirty(); }) || + std::any_of(m_renderBufferBindings.cbegin(), m_renderBufferBindings.cend(), [](const auto& b) { return b->m_impl.isDirty(); }); } int ApiObjects::getNumElementsInLuaStack() const @@ -1379,35 +1432,37 @@ namespace ramses::internal template DataArray* ApiObjects::createDataArray(const std::vector&, std::string_view); template DataArray* ApiObjects::createDataArray>(const std::vector>&, std::string_view); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - template ApiObjectContainer& ApiObjects::getApiObjectContainer(); - - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; - template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + template ApiObjectContainer& ApiObjects::getApiObjectContainer(); + + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; + template const ApiObjectContainer& ApiObjects::getApiObjectContainer() const; } diff --git a/src/client/internal/logic/ApiObjects.h b/src/client/internal/logic/ApiObjects.h index 7e5cef1fc..6a7ca672b 100644 --- a/src/client/internal/logic/ApiObjects.h +++ b/src/client/internal/logic/ApiObjects.h @@ -47,6 +47,7 @@ namespace ramses class RenderGroup; class UniformInput; class MeshNode; + class RenderBuffer; class LogicObject; class LogicNode; @@ -65,6 +66,7 @@ namespace ramses class AnimationNode; class TimerNode; class AnchorPoint; + class RenderBufferBinding; } namespace ramses::internal @@ -144,6 +146,7 @@ namespace ramses::internal AnimationNode* createAnimationNode(const AnimationNodeConfigImpl& config, std::string_view name); TimerNode* createTimerNode(std::string_view name); AnchorPoint* createAnchorPoint(NodeBindingImpl& nodeBinding, CameraBindingImpl& cameraBinding, std::string_view name); + RenderBufferBinding* createRenderBufferBinding(ramses::RenderBuffer& renderBuffer, std::string_view name); bool destroy(LogicObject& object, ErrorReporting& errorReporting); // Invariance checks @@ -200,6 +203,8 @@ namespace ramses::internal ApiObjectContainer m_animationNodes; ApiObjectContainer m_timerNodes; ApiObjectContainer m_anchorPoints; + ApiObjectContainer m_renderBufferBindings; + ApiObjectContainer m_logicObjects; ApiObjectOwningContainer m_objectsOwningContainer; diff --git a/src/client/internal/logic/ApiObjectsSerializedSize.cpp b/src/client/internal/logic/ApiObjectsSerializedSize.cpp index 7169b9a29..3ff8b4c30 100644 --- a/src/client/internal/logic/ApiObjectsSerializedSize.cpp +++ b/src/client/internal/logic/ApiObjectsSerializedSize.cpp @@ -23,6 +23,7 @@ #include "ramses/client/logic/MeshNodeBinding.h" #include "ramses/client/logic/SkinBinding.h" #include "ramses/client/logic/TimerNode.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "internal/logic/flatbuffers/generated/ApiObjectsGen.h" @@ -40,6 +41,7 @@ #include "impl/logic/MeshNodeBindingImpl.h" #include "impl/logic/SkinBindingImpl.h" #include "impl/logic/TimerNodeImpl.h" +#include "impl/logic/RenderBufferBindingImpl.h" namespace ramses::internal { @@ -204,6 +206,12 @@ namespace ramses::internal return calculateSerializedSize(apiObjects.getApiObjectContainer(), luaSavingMode); } + template<> + size_t ApiObjectsSerializedSize::GetSerializedSize(const ApiObjects& apiObjects, ELuaSavingMode luaSavingMode) + { + return calculateSerializedSize(apiObjects.getApiObjectContainer(), luaSavingMode); + } + template<> size_t ApiObjectsSerializedSize::GetSerializedSize(const ApiObjects& apiObjects, ELuaSavingMode luaSavingMode) { diff --git a/src/client/internal/logic/DirectedAcyclicGraph.cpp b/src/client/internal/logic/DirectedAcyclicGraph.cpp index f4625fa40..6ddb37452 100644 --- a/src/client/internal/logic/DirectedAcyclicGraph.cpp +++ b/src/client/internal/logic/DirectedAcyclicGraph.cpp @@ -218,10 +218,10 @@ namespace ramses::internal // reserve to all nodes count because it will be used to store all sorted nodes later rootNodes.reserve(m_nodeIncomingEdges.size()); - for (const auto& nodeIngoingEdges : m_nodeIncomingEdges) + for (const auto& incomingEdge : m_nodeIncomingEdges) { - if (nodeIngoingEdges.second.empty()) - rootNodes.push_back(nodeIngoingEdges.first); + if (incomingEdge.second.empty()) + rootNodes.push_back(incomingEdge.first); } return rootNodes; diff --git a/src/client/internal/logic/LogicNodeUpdateStatistics.cpp b/src/client/internal/logic/LogicNodeUpdateStatistics.cpp index 49e1dc1e4..3d7f3fb5b 100644 --- a/src/client/internal/logic/LogicNodeUpdateStatistics.cpp +++ b/src/client/internal/logic/LogicNodeUpdateStatistics.cpp @@ -100,14 +100,14 @@ namespace ramses::internal else { const auto timeSinceLastLog = std::chrono::duration_cast(now - m_lastTimeLogged.value()); - LOG_INFO_P(CONTEXT_PERIODIC, "Time since last log: {:.2f} sec", static_cast(timeSinceLastLog.count()) / 1000.f); + LOG_INFO(CONTEXT_PERIODIC, "Time since last log: {:.2f} sec", static_cast(timeSinceLastLog.count()) / 1000.f); } m_lastTimeLogged = now; } void LogicNodeUpdateStatistics::logUpdateExecutionTime() { - LOG_INFO_P(CONTEXT_PERIODIC, "Update Execution time (min/max/avg): {}/{}/{} [u]sec", + LOG_INFO(CONTEXT_PERIODIC, "Update Execution time (min/max/avg): {}/{}/{} [u]sec", m_updateExecutionTime.min, m_updateExecutionTime.max, m_updateExecutionTime.acc / m_currentStatisticsFrame); @@ -117,11 +117,11 @@ namespace ramses::internal { if (m_currentStatisticsFrame == 1) { - LOG_INFO_P(CONTEXT_PERIODIC, "Time between Update calls cannot be measured with loggingRate = 1"); + LOG_INFO(CONTEXT_PERIODIC, "Time between Update calls cannot be measured with loggingRate = 1"); } else { - LOG_INFO_P(CONTEXT_PERIODIC, "Time between Update calls (min/max/avg): {:.2f}/{:.2f}/{:.2f} [m]sec", + LOG_INFO(CONTEXT_PERIODIC, "Time between Update calls (min/max/avg): {:.2f}/{:.2f}/{:.2f} [m]sec", static_cast(m_timeSinceLastUpdate.min) / 1000.f, static_cast(m_timeSinceLastUpdate.max) / 1000.f, (static_cast(m_timeSinceLastUpdate.acc) / static_cast(m_currentStatisticsFrame - 1)) / 1000.f); @@ -131,7 +131,7 @@ namespace ramses::internal void LogicNodeUpdateStatistics::logNodesExecuted() { const size_t totalNodesNotZero = std::max(size_t(1), m_totalNodesCount); - LOG_INFO_P(CONTEXT_PERIODIC, "Nodes Executed (min/max/avg): {}%/{}%/{}% ({}/{}/{}) of {} nodes total", + LOG_INFO(CONTEXT_PERIODIC, "Nodes Executed (min/max/avg): {}%/{}%/{}% ({}/{}/{}) of {} nodes total", static_cast(static_cast(m_nodesExecuted.min) / totalNodesNotZero * 100.f), static_cast(static_cast(m_nodesExecuted.max) / totalNodesNotZero * 100.f), static_cast(static_cast(m_nodesExecuted.acc) / m_currentStatisticsFrame / totalNodesNotZero * 100.f), @@ -143,7 +143,7 @@ namespace ramses::internal void LogicNodeUpdateStatistics::logActivatedLinks() { - LOG_INFO_P(CONTEXT_PERIODIC, "Activated links (min/max/avg): {}/{}/{}", + LOG_INFO(CONTEXT_PERIODIC, "Activated links (min/max/avg): {}/{}/{}", m_activatedLinks.min, m_activatedLinks.max, m_activatedLinks.acc / m_currentStatisticsFrame); @@ -160,7 +160,7 @@ namespace ramses::internal if (node.first != nullptr) nodes += fmt::format(" [{}:{}]", node.first->getName(), node.second.count()); } - LOG_INFO_P(CONTEXT_PERIODIC, "Slowest nodes [name:time_us]:{}", nodes); + LOG_INFO(CONTEXT_PERIODIC, "Slowest nodes [name:time_us]:{}", nodes); } void LogicNodeUpdateStatistics::calculateAndLog() diff --git a/src/client/internal/logic/LuaCompilationUtils.cpp b/src/client/internal/logic/LuaCompilationUtils.cpp index adfee36a0..781e4a1f3 100644 --- a/src/client/internal/logic/LuaCompilationUtils.cpp +++ b/src/client/internal/logic/LuaCompilationUtils.cpp @@ -59,7 +59,7 @@ namespace ramses::internal return std::nullopt; } - LOG_WARN_P(CONTEXT_CLIENT, "Performance warning! Error during loading of LuaScript '{}' from pre-compiled byte code, will try to recompile script from source code. Error:\n{}!", name, error.what()); + LOG_WARN(CONTEXT_CLIENT, "Performance warning! Error during loading of LuaScript '{}' from pre-compiled byte code, will try to recompile script from source code. Error:\n{}!", name, error.what()); byteCodeFromPrecompiledScript.clear(); } } @@ -326,7 +326,7 @@ namespace ramses::internal return std::nullopt; } - LOG_WARN_P(CONTEXT_CLIENT, "Performance warning! Error during loading of LuaScript '{}' from pre-compiled byte code, will try to recompile script from source code. Error:\n{}!", name, error.what()); + LOG_WARN(CONTEXT_CLIENT, "Performance warning! Error during loading of LuaScript '{}' from pre-compiled byte code, will try to recompile script from source code. Error:\n{}!", name, error.what()); byteCodeFromPrecompiledModule.clear(); } } @@ -513,7 +513,7 @@ namespace ramses::internal if (!scriptFuncResult.valid()) { const sol::error error = scriptFuncResult; - LOG_DEBUG_P(CONTEXT_CLIENT, "Lua runtime error while extracting module dependencies, this is ignored for the actual extraction but might affect its result:\n{}", error.what()); + LOG_DEBUG(CONTEXT_CLIENT, "Lua runtime error while extracting module dependencies, this is ignored for the actual extraction but might affect its result:\n{}", error.what()); } if (!success) diff --git a/src/client/internal/logic/LuaCustomizations.cpp b/src/client/internal/logic/LuaCustomizations.cpp index 16d3f7244..8e1b23d43 100644 --- a/src/client/internal/logic/LuaCustomizations.cpp +++ b/src/client/internal/logic/LuaCustomizations.cpp @@ -41,15 +41,15 @@ namespace ramses::internal { auto rl_logInfo = [](const std::string& msg) { - LOG_INFO_P(CONTEXT_CLIENT, "LuaDebugLog: {}", msg); + LOG_INFO(CONTEXT_CLIENT, "LuaDebugLog: {}", msg); }; auto rl_logWarn = [](const std::string& msg) { - LOG_WARN_P(CONTEXT_CLIENT, "LuaDebugLog: {}", msg); + LOG_WARN(CONTEXT_CLIENT, "LuaDebugLog: {}", msg); }; auto rl_logError = [](const std::string& msg) { - LOG_ERROR_P(CONTEXT_CLIENT, "LuaDebugLog: {}", msg); + LOG_ERROR(CONTEXT_CLIENT, "LuaDebugLog: {}", msg); }; env["rl_logInfo"] = rl_logInfo; diff --git a/src/client/internal/logic/flatbuffers/generated/ApiObjectsGen.h b/src/client/internal/logic/flatbuffers/generated/ApiObjectsGen.h index c55d1d66d..ab0980615 100644 --- a/src/client/internal/logic/flatbuffers/generated/ApiObjectsGen.h +++ b/src/client/internal/logic/flatbuffers/generated/ApiObjectsGen.h @@ -24,6 +24,7 @@ static_assert(FLATBUFFERS_VERSION_MAJOR == 23 && #include "LuaScriptGen.h" #include "MeshNodeBindingGen.h" #include "NodeBindingGen.h" +#include "RenderBufferBindingGen.h" #include "RenderGroupBindingGen.h" #include "RenderPassBindingGen.h" #include "SkinBindingGen.h" @@ -57,7 +58,8 @@ struct ApiObjects FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { VT_ANCHORPOINTS = 26, VT_RENDERGROUPBINDINGS = 28, VT_SKINBINDINGS = 30, - VT_MESHNODEBINDINGS = 32 + VT_MESHNODEBINDINGS = 32, + VT_RENDERBUFFERBINDINGS = 34 }; const ::flatbuffers::Vector<::flatbuffers::Offset> *luaModules() const { return GetPointer> *>(VT_LUAMODULES); @@ -104,6 +106,9 @@ struct ApiObjects FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { const ::flatbuffers::Vector<::flatbuffers::Offset> *meshNodeBindings() const { return GetPointer> *>(VT_MESHNODEBINDINGS); } + const ::flatbuffers::Vector<::flatbuffers::Offset> *renderBufferBindings() const { + return GetPointer> *>(VT_RENDERBUFFERBINDINGS); + } bool Verify(::flatbuffers::Verifier &verifier) const { return VerifyTableStart(verifier) && VerifyOffset(verifier, VT_LUAMODULES) && @@ -151,6 +156,9 @@ struct ApiObjects FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { VerifyOffset(verifier, VT_MESHNODEBINDINGS) && verifier.VerifyVector(meshNodeBindings()) && verifier.VerifyVectorOfTables(meshNodeBindings()) && + VerifyOffset(verifier, VT_RENDERBUFFERBINDINGS) && + verifier.VerifyVector(renderBufferBindings()) && + verifier.VerifyVectorOfTables(renderBufferBindings()) && verifier.EndTable(); } }; @@ -204,6 +212,9 @@ struct ApiObjectsBuilder { void add_meshNodeBindings(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> meshNodeBindings) { fbb_.AddOffset(ApiObjects::VT_MESHNODEBINDINGS, meshNodeBindings); } + void add_renderBufferBindings(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> renderBufferBindings) { + fbb_.AddOffset(ApiObjects::VT_RENDERBUFFERBINDINGS, renderBufferBindings); + } explicit ApiObjectsBuilder(::flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); @@ -231,8 +242,10 @@ inline ::flatbuffers::Offset CreateApiObjects( ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> anchorPoints = 0, ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> renderGroupBindings = 0, ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> skinBindings = 0, - ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> meshNodeBindings = 0) { + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> meshNodeBindings = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> renderBufferBindings = 0) { ApiObjectsBuilder builder_(_fbb); + builder_.add_renderBufferBindings(renderBufferBindings); builder_.add_meshNodeBindings(meshNodeBindings); builder_.add_skinBindings(skinBindings); builder_.add_renderGroupBindings(renderGroupBindings); @@ -272,7 +285,8 @@ inline ::flatbuffers::Offset CreateApiObjectsDirect( const std::vector<::flatbuffers::Offset> *anchorPoints = nullptr, const std::vector<::flatbuffers::Offset> *renderGroupBindings = nullptr, const std::vector<::flatbuffers::Offset> *skinBindings = nullptr, - const std::vector<::flatbuffers::Offset> *meshNodeBindings = nullptr) { + const std::vector<::flatbuffers::Offset> *meshNodeBindings = nullptr, + const std::vector<::flatbuffers::Offset> *renderBufferBindings = nullptr) { auto luaModules__ = luaModules ? _fbb.CreateVector<::flatbuffers::Offset>(*luaModules) : 0; auto luaScripts__ = luaScripts ? _fbb.CreateVector<::flatbuffers::Offset>(*luaScripts) : 0; auto luaInterfaces__ = luaInterfaces ? _fbb.CreateVector<::flatbuffers::Offset>(*luaInterfaces) : 0; @@ -288,6 +302,7 @@ inline ::flatbuffers::Offset CreateApiObjectsDirect( auto renderGroupBindings__ = renderGroupBindings ? _fbb.CreateVector<::flatbuffers::Offset>(*renderGroupBindings) : 0; auto skinBindings__ = skinBindings ? _fbb.CreateVector<::flatbuffers::Offset>(*skinBindings) : 0; auto meshNodeBindings__ = meshNodeBindings ? _fbb.CreateVector<::flatbuffers::Offset>(*meshNodeBindings) : 0; + auto renderBufferBindings__ = renderBufferBindings ? _fbb.CreateVector<::flatbuffers::Offset>(*renderBufferBindings) : 0; return rlogic_serialization::CreateApiObjects( _fbb, luaModules__, @@ -304,7 +319,8 @@ inline ::flatbuffers::Offset CreateApiObjectsDirect( anchorPoints__, renderGroupBindings__, skinBindings__, - meshNodeBindings__); + meshNodeBindings__, + renderBufferBindings__); } inline const ::flatbuffers::TypeTable *ApiObjectsTypeTable() { @@ -323,7 +339,8 @@ inline const ::flatbuffers::TypeTable *ApiObjectsTypeTable() { { ::flatbuffers::ET_SEQUENCE, 1, 11 }, { ::flatbuffers::ET_SEQUENCE, 1, 12 }, { ::flatbuffers::ET_SEQUENCE, 1, 13 }, - { ::flatbuffers::ET_SEQUENCE, 1, 14 } + { ::flatbuffers::ET_SEQUENCE, 1, 14 }, + { ::flatbuffers::ET_SEQUENCE, 1, 15 } }; static const ::flatbuffers::TypeFunction type_refs[] = { rlogic_serialization::LuaModuleTypeTable, @@ -340,7 +357,8 @@ inline const ::flatbuffers::TypeTable *ApiObjectsTypeTable() { rlogic_serialization::AnchorPointTypeTable, rlogic_serialization::RenderGroupBindingTypeTable, rlogic_serialization::SkinBindingTypeTable, - rlogic_serialization::MeshNodeBindingTypeTable + rlogic_serialization::MeshNodeBindingTypeTable, + rlogic_serialization::RenderBufferBindingTypeTable }; static const char * const names[] = { "luaModules", @@ -357,10 +375,11 @@ inline const ::flatbuffers::TypeTable *ApiObjectsTypeTable() { "anchorPoints", "renderGroupBindings", "skinBindings", - "meshNodeBindings" + "meshNodeBindings", + "renderBufferBindings" }; static const ::flatbuffers::TypeTable tt = { - ::flatbuffers::ST_TABLE, 15, type_codes, type_refs, nullptr, nullptr, names + ::flatbuffers::ST_TABLE, 16, type_codes, type_refs, nullptr, nullptr, names }; return &tt; } diff --git a/src/client/internal/logic/flatbuffers/generated/RenderBufferBindingGen.h b/src/client/internal/logic/flatbuffers/generated/RenderBufferBindingGen.h new file mode 100644 index 000000000..e3598c284 --- /dev/null +++ b/src/client/internal/logic/flatbuffers/generated/RenderBufferBindingGen.h @@ -0,0 +1,94 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_RENDERBUFFERBINDING_RLOGIC_SERIALIZATION_H_ +#define FLATBUFFERS_GENERATED_RENDERBUFFERBINDING_RLOGIC_SERIALIZATION_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 23 && + FLATBUFFERS_VERSION_MINOR == 5 && + FLATBUFFERS_VERSION_REVISION == 9, + "Non-compatible flatbuffers version included"); + +#include "RamsesBindingGen.h" + +namespace rlogic_serialization { + +struct RenderBufferBinding; +struct RenderBufferBindingBuilder; + +inline const ::flatbuffers::TypeTable *RenderBufferBindingTypeTable(); + +struct RenderBufferBinding FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef RenderBufferBindingBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return RenderBufferBindingTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_BASE = 4 + }; + const rlogic_serialization::RamsesBinding *base() const { + return GetPointer(VT_BASE); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_BASE) && + verifier.VerifyTable(base()) && + verifier.EndTable(); + } +}; + +struct RenderBufferBindingBuilder { + typedef RenderBufferBinding Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_base(::flatbuffers::Offset base) { + fbb_.AddOffset(RenderBufferBinding::VT_BASE, base); + } + explicit RenderBufferBindingBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateRenderBufferBinding( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset base = 0) { + RenderBufferBindingBuilder builder_(_fbb); + builder_.add_base(base); + return builder_.Finish(); +} + +struct RenderBufferBinding::Traits { + using type = RenderBufferBinding; + static auto constexpr Create = CreateRenderBufferBinding; +}; + +inline const ::flatbuffers::TypeTable *RenderBufferBindingTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + rlogic_serialization::RamsesBindingTypeTable + }; + static const char * const names[] = { + "base" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +} // namespace rlogic_serialization + +#endif // FLATBUFFERS_GENERATED_RENDERBUFFERBINDING_RLOGIC_SERIALIZATION_H_ diff --git a/src/client/internal/logic/flatbuffers/schemas/ApiObjects.fbs b/src/client/internal/logic/flatbuffers/schemas/ApiObjects.fbs index 6533eb1d0..3f4ccc991 100644 --- a/src/client/internal/logic/flatbuffers/schemas/ApiObjects.fbs +++ b/src/client/internal/logic/flatbuffers/schemas/ApiObjects.fbs @@ -21,6 +21,7 @@ include "DataArray.fbs"; include "AnimationNode.fbs"; include "TimerNode.fbs"; include "AnchorPoint.fbs"; +include "RenderBufferBinding.fbs"; namespace rlogic_serialization; @@ -41,4 +42,5 @@ table ApiObjects renderGroupBindings:[RenderGroupBinding]; skinBindings:[SkinBinding]; meshNodeBindings:[MeshNodeBinding]; + renderBufferBindings:[RenderBufferBinding]; } diff --git a/tools/ramses-logic-viewer/main.cpp b/src/client/internal/logic/flatbuffers/schemas/RenderBufferBinding.fbs similarity index 73% rename from tools/ramses-logic-viewer/main.cpp rename to src/client/internal/logic/flatbuffers/schemas/RenderBufferBinding.fbs index 4512289fb..8038f4960 100644 --- a/tools/ramses-logic-viewer/main.cpp +++ b/src/client/internal/logic/flatbuffers/schemas/RenderBufferBinding.fbs @@ -1,15 +1,16 @@ // ------------------------------------------------------------------------- -// Copyright (C) 2021 BMW AG +// Copyright (C) 2023 BMW AG // ------------------------------------------------------------------------- // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // ------------------------------------------------------------------------- -#include "LogicViewerGuiApp.h" +include "RamsesBinding.fbs"; -int main(int argc, char* argv[]) +namespace rlogic_serialization; + +table RenderBufferBinding { - ramses::LogicViewerGuiApp app(argc, argv); - return app.run(); + base:RamsesBinding; } diff --git a/src/framework/CMakeLists.txt b/src/framework/CMakeLists.txt index 86cc393d1..740c354d0 100644 --- a/src/framework/CMakeLists.txt +++ b/src/framework/CMakeLists.txt @@ -6,114 +6,13 @@ # file, You can obtain one at https://mozilla.org/MPL/2.0/. # ------------------------------------------------------------------------- -if (ramses-sdk_ENABLE_TCP_SUPPORT) - list(APPEND FRAMEWORK_SOURCES internal/Communication/TransportTCP/*.h - internal/Communication/TransportTCP/*.cpp) - list(APPEND FRAMEWORK_LIBS asio) -endif() - -if(ramses-sdk_HAS_DLT) - list(APPEND FRAMEWORK_SOURCES internal/DltLogAppender/DltAdapterImpl/*.h - internal/DltLogAppender/DltAdapterImpl/*.cpp) - list(APPEND FRAMEWORK_LIBS automotive-dlt) -endif() - -find_package(AndroidSDK) -if(AndroidSDK_FOUND) - list(APPEND FRAMEWORK_SOURCES internal/Core/Utils/AndroidLogger/*.h - internal/Core/Utils/AndroidLogger/*.cpp) - list(APPEND FRAMEWORK_LIBS AndroidSDK) -endif() +add_subdirectory(internal) createModule( NAME ramses-framework TYPE STATIC_LIBRARY ENABLE_INSTALL OFF - - INCLUDE_PATHS . - - # impl SRC_FILES impl/*.h impl/*.cpp - # internal - SRC_FILES ${FRAMEWORK_SOURCES} - SRC_FILES internal/Watchdog/*.h - internal/Watchdog/*.cpp - SRC_FILES internal/PlatformAbstraction/*.h - internal/PlatformAbstraction/Collections/*.h - internal/PlatformAbstraction/internal/*.h - internal/PlatformAbstraction/*.cpp - SRC_FILES internal/Core/Math3d/*.h - internal/Core/Math3d/*.cpp - SRC_FILES internal/Core/Utils/*.h - internal/Core/Utils/*.cpp - SRC_FILES internal/Core/Common/*.h - internal/Core/Common/*.cpp - SRC_FILES internal/Core/TaskFramework/*.h - internal/Core/TaskFramework/*.cpp - SRC_FILES internal/SceneGraph/SceneAPI/*.h - internal/SceneGraph/SceneAPI/*.cpp - SRC_FILES internal/SceneGraph/Scene/*.h - internal/SceneGraph/Scene/*.cpp - SRC_FILES internal/SceneGraph/Resource/*.h - internal/SceneGraph/Resource/*.cpp - SRC_FILES internal/SceneGraph/SceneUtils/*.h - internal/SceneGraph/SceneUtils/*.cpp - SRC_FILES internal/Communication/TransportCommon/*.h - internal/Communication/TransportCommon/*.cpp - SRC_FILES internal/Ramsh/*.h - internal/Ramsh/*.cpp - SRC_FILES internal/Components/*.h - internal/Components/*.cpp - SRC_FILES internal/DltLogAppender/*.h - internal/DltLogAppender/*.cpp - internal/DltLogAppender/src/*.cpp - SRC_FILES internal/SceneReferencing/*.h - internal/SceneReferencing/*.cpp - - DEPENDENCIES ramses-api - ramses-common-base - lz4 - fmt::fmt - ramses-abseil - lodepng - cityhash - ${FRAMEWORK_LIBS} + DEPENDENCIES ramses-framework-internal ) - -if (ramses-sdk_ENABLE_TCP_SUPPORT) - message(STATUS "+ TCP communication system support enabled") - target_compile_definitions(ramses-framework PUBLIC "-DHAS_TCP_COMM=1") -else() - message(STATUS "- TCP communication system support disabled") -endif() - -if (ramses-sdk_HAS_DLT) - target_compile_definitions(ramses-framework PUBLIC "-DDLT_ENABLED") - - if (automotive-dlt_HAS_FILETRANSFER) - target_compile_definitions(ramses-framework PUBLIC "-DDLT_HAS_FILETRANSFER") - endif() -endif() - -if(ramses-sdk_USE_LINUX_DEV_PTP) - target_compile_definitions(ramses-framework PUBLIC "-DRAMSES_LINUX_USE_DEV_PTP=1") -endif() - -# Thread priority and binding for worker threads -if (DEFINED ramses-sdk_WORKER_THREAD_PRIORITY AND NOT ramses-sdk_WORKER_THREAD_PRIORITY STREQUAL "") - target_compile_definitions(ramses-framework PRIVATE "-DRAMSES_WORKER_THREAD_PRIORITY=${ramses-sdk_WORKER_THREAD_PRIORITY}") -endif() - -if (DEFINED ramses-sdk_WORKER_THREAD_CORE_BINDING AND NOT ramses-sdk_WORKER_THREAD_CORE_BINDING STREQUAL "") - target_compile_definitions(ramses-framework PRIVATE "-DRAMSES_WORKER_THREAD_CORE_BINDING=${ramses-sdk_WORKER_THREAD_CORE_BINDING}") -endif() - -if (DEFINED ramses-sdk_CONN_KEEPALIVE_THREAD_CORE_BINDING AND NOT ramses-sdk_CONN_KEEPALIVE_THREAD_CORE_BINDING STREQUAL "") - target_compile_definitions(ramses-framework PRIVATE "-DRAMSES_CONN_KEEPALIVE_THREAD_CORE_BINDING=${ramses-sdk_CONN_KEEPALIVE_THREAD_CORE_BINDING}") -endif() - - -if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") - target_compile_options(ramses-framework PRIVATE "-Wsuggest-override") -endif() diff --git a/src/framework/impl/APILoggingHelper.h b/src/framework/impl/APILoggingHelper.h deleted file mode 100644 index 58edfffdb..000000000 --- a/src/framework/impl/APILoggingHelper.h +++ /dev/null @@ -1,31 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2014 BMW Car IT GmbH -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -#include "internal/PlatformAbstraction/Collections/StringOutputStream.h" - -namespace ramses::internal -{ - class APILoggingHelper - { - public: - static std::string MakeLoggingString(int32_t argc, char const* const* argv) - { - StringOutputStream argumentsStream; - argumentsStream << argc << " arguments: [ "; - for (int32_t i = 0; i < argc; ++i) - { - argumentsStream << (i != 0 ? " ; " : "") << argv[i]; - } - argumentsStream << " ]"; - return argumentsStream.release(); - } - }; -} - diff --git a/src/framework/impl/APILoggingMacros.h b/src/framework/impl/APILoggingMacros.h index be73c5451..fa65af80a 100644 --- a/src/framework/impl/APILoggingMacros.h +++ b/src/framework/impl/APILoggingMacros.h @@ -36,56 +36,57 @@ LOG_API_RAMSESOBJECT_PTR_STRING(&(OBJ)) #define LOG_API_RESOURCE_PTR_STRING(PTR) \ - LOG_API_RAMSESOBJECT_PTR_STRING(PTR) << " with resID " << ((PTR) ? fmt::to_string((PTR)->getResourceId()) : "") + ::fmt::format("{} with resID {}", LOG_API_RAMSESOBJECT_PTR_STRING(PTR), (PTR) ? fmt::to_string((PTR)->getResourceId()) : "") -#define LOG_API_SEPERATOR << " ; " << +#define LOG_API_SEPERATOR(arg1, arg2) \ + ::fmt::format("{} ; {}", arg1, arg2) #define LOG_API_BASE(retval) \ - CLASS_FUNCTION_NAME << " at " << LOG_API_GENERIC_PTR_STRING(this) << " ret " << retval + ::fmt::format("{} at {} ret {}", CLASS_FUNCTION_NAME, LOG_API_GENERIC_PTR_STRING(this), retval) #define LOG_STATIC_API_BASE(retval) \ - CLASS_FUNCTION_NAME << " ret " << retval + ::fmt::format("{} ret {}", CLASS_FUNCTION_NAME, retval) #define LOG_API_ARGUMENTS(arguments) \ - " ( args: " << arguments << " )" // NOLINT(bugprone-macro-parentheses) + ::fmt::format(" ( args: {} )", arguments) // Client side macros -#define LOG_HL_CLIENT_API_STR(str) \ - LOG_API_LOGLEVEL(ramses::internal::CONTEXT_HLAPI_CLIENT, str) +#define LOG_HL_CLIENT_API_STR(...) \ + LOG_API_LOGLEVEL(ramses::internal::CONTEXT_HLAPI_CLIENT, __VA_ARGS__) #define LOG_HL_CLIENT_API_NOARG(retval) \ LOG_HL_CLIENT_API_STR(LOG_API_BASE(retval)) #define LOG_HL_CLIENT_API1(retval, arg1) \ - LOG_HL_CLIENT_API_STR(LOG_API_BASE(retval) << LOG_API_ARGUMENTS(arg1)) + LOG_HL_CLIENT_API_STR(::fmt::format("{}{}", LOG_API_BASE(retval), LOG_API_ARGUMENTS(arg1))) #define LOG_HL_CLIENT_API2(retval, arg1, arg2) \ - LOG_HL_CLIENT_API1(retval, arg1 LOG_API_SEPERATOR arg2) + LOG_HL_CLIENT_API1(retval, LOG_API_SEPERATOR(arg1, arg2)) #define LOG_HL_CLIENT_API3(retval, arg1, arg2, arg3) \ - LOG_HL_CLIENT_API2(retval, arg1, arg2 LOG_API_SEPERATOR arg3) + LOG_HL_CLIENT_API2(retval, arg1, LOG_API_SEPERATOR(arg2, arg3)) #define LOG_HL_CLIENT_API4(retval, arg1, arg2, arg3, arg4) \ - LOG_HL_CLIENT_API3(retval, arg1, arg2, arg3 LOG_API_SEPERATOR arg4) + LOG_HL_CLIENT_API3(retval, arg1, arg2, LOG_API_SEPERATOR(arg3, arg4)) #define LOG_HL_CLIENT_API5(retval, arg1, arg2, arg3, arg4, arg5) \ - LOG_HL_CLIENT_API4(retval, arg1, arg2, arg3, arg4 LOG_API_SEPERATOR arg5) + LOG_HL_CLIENT_API4(retval, arg1, arg2, arg3, LOG_API_SEPERATOR(arg4, arg5)) #define LOG_HL_CLIENT_API6(retval, arg1, arg2, arg3, arg4, arg5, arg6) \ - LOG_HL_CLIENT_API5(retval, arg1, arg2, arg3, arg4, arg5 LOG_API_SEPERATOR arg6) + LOG_HL_CLIENT_API5(retval, arg1, arg2, arg3, arg4, LOG_API_SEPERATOR(arg5, arg6)) #define LOG_HL_CLIENT_API7(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7) \ - LOG_HL_CLIENT_API6(retval, arg1, arg2, arg3, arg4, arg5, arg6 LOG_API_SEPERATOR arg7) + LOG_HL_CLIENT_API6(retval, arg1, arg2, arg3, arg4, arg5, LOG_API_SEPERATOR(arg6, arg7)) #define LOG_HL_CLIENT_API8(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) \ - LOG_HL_CLIENT_API7(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7 LOG_API_SEPERATOR arg8) + LOG_HL_CLIENT_API7(retval, arg1, arg2, arg3, arg4, arg5, arg6, LOG_API_SEPERATOR(arg7, arg8)) #define LOG_HL_CLIENT_API9(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) \ - LOG_HL_CLIENT_API8(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 LOG_API_SEPERATOR arg9) + LOG_HL_CLIENT_API8(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, LOG_API_SEPERATOR(arg8, arg9)) #define LOG_HL_CLIENT_API10(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) \ - LOG_HL_CLIENT_API9 (retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9 LOG_API_SEPERATOR arg10) + LOG_HL_CLIENT_API9 (retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, LOG_API_SEPERATOR(arg9, arg10)) #define LOG_HL_CLIENT_API11(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11) \ - LOG_HL_CLIENT_API10(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10 LOG_API_SEPERATOR arg11) + LOG_HL_CLIENT_API10(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, LOG_API_SEPERATOR(arg10, arg11)) #define LOG_HL_CLIENT_STATIC_API1(retval, arg1) \ - LOG_HL_CLIENT_API_STR(LOG_STATIC_API_BASE(retval) << LOG_API_ARGUMENTS(arg1)) + LOG_HL_CLIENT_API_STR(::fmt::format("{}{}", LOG_STATIC_API_BASE(retval), LOG_API_ARGUMENTS(arg1))) #define LOG_HL_CLIENT_STATIC_API2(retval, arg1, arg2) \ - LOG_HL_CLIENT_STATIC_API1(retval, arg1 LOG_API_SEPERATOR arg2) + LOG_HL_CLIENT_STATIC_API1(retval, LOG_API_SEPERATOR(arg1, arg2)) #define LOG_HL_CLIENT_STATIC_API3(retval, arg1, arg2, arg3) \ - LOG_HL_CLIENT_STATIC_API2(retval, arg1, arg2 LOG_API_SEPERATOR arg3) + LOG_HL_CLIENT_STATIC_API2(retval, arg1, LOG_API_SEPERATOR(arg2, arg3)) #define LOG_HL_CLIENT_STATIC_API4(retval, arg1, arg2, arg3, arg4) \ - LOG_HL_CLIENT_STATIC_API3(retval, arg1, arg2, arg3 LOG_API_SEPERATOR arg4) + LOG_HL_CLIENT_STATIC_API3(retval, arg1, arg2, LOG_API_SEPERATOR(arg3, arg4)) #define LOG_HL_CLIENT_STATIC_API5(retval, arg1, arg2, arg3, arg4, arg5) \ - LOG_HL_CLIENT_STATIC_API4(retval, arg1, arg2, arg3, arg4 LOG_API_SEPERATOR arg5) + LOG_HL_CLIENT_STATIC_API4(retval, arg1, arg2, arg3, LOG_API_SEPERATOR(arg4, arg5)) // Renderer side macros #define LOG_HL_RENDERER_API_STR(str) \ @@ -94,31 +95,31 @@ #define LOG_HL_RENDERER_API_NOARG(retval) \ LOG_HL_RENDERER_API_STR(LOG_API_BASE(retval)) #define LOG_HL_RENDERER_API1(retval, arg1) \ - LOG_HL_RENDERER_API_STR(LOG_API_BASE(retval) << LOG_API_ARGUMENTS(arg1)) + LOG_HL_RENDERER_API_STR(::fmt::format("{}{}", LOG_API_BASE(retval), LOG_API_ARGUMENTS(arg1))) #define LOG_HL_RENDERER_API2(retval, arg1, arg2) \ - LOG_HL_RENDERER_API1(retval, arg1 LOG_API_SEPERATOR arg2) + LOG_HL_RENDERER_API1(retval, LOG_API_SEPERATOR(arg1, arg2)) #define LOG_HL_RENDERER_API3(retval, arg1, arg2, arg3) \ - LOG_HL_RENDERER_API2(retval, arg1, arg2 LOG_API_SEPERATOR arg3) + LOG_HL_RENDERER_API2(retval, arg1, LOG_API_SEPERATOR(arg2, arg3)) #define LOG_HL_RENDERER_API4(retval, arg1, arg2, arg3, arg4) \ - LOG_HL_RENDERER_API3(retval, arg1, arg2, arg3 LOG_API_SEPERATOR arg4) + LOG_HL_RENDERER_API3(retval, arg1, arg2, LOG_API_SEPERATOR(arg3, arg4)) #define LOG_HL_RENDERER_API5(retval, arg1, arg2, arg3, arg4, arg5) \ - LOG_HL_RENDERER_API4(retval, arg1, arg2, arg3, arg4 LOG_API_SEPERATOR arg5) + LOG_HL_RENDERER_API4(retval, arg1, arg2, arg3, LOG_API_SEPERATOR(arg4, arg5)) #define LOG_HL_RENDERER_API6(retval, arg1, arg2, arg3, arg4, arg5, arg6) \ - LOG_HL_RENDERER_API5(retval, arg1, arg2, arg3, arg4, arg5 LOG_API_SEPERATOR arg6) + LOG_HL_RENDERER_API5(retval, arg1, arg2, arg3, arg4, LOG_API_SEPERATOR(arg5, arg6)) #define LOG_HL_RENDERER_API7(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7) \ - LOG_HL_RENDERER_API6(retval, arg1, arg2, arg3, arg4, arg5, arg6 LOG_API_SEPERATOR arg7) + LOG_HL_RENDERER_API6(retval, arg1, arg2, arg3, arg4, arg5, LOG_API_SEPERATOR(arg6, arg7)) #define LOG_HL_RENDERER_API8(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) \ - LOG_HL_RENDERER_API7(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7 LOG_API_SEPERATOR arg8) + LOG_HL_RENDERER_API7(retval, arg1, arg2, arg3, arg4, arg5, arg6, LOG_API_SEPERATOR(arg7, arg8)) #define LOG_HL_RENDERER_API9(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) \ - LOG_HL_RENDERER_API8(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8 LOG_API_SEPERATOR arg9) + LOG_HL_RENDERER_API8(retval, arg1, arg2, arg3, arg4, arg5, arg6, arg7, LOG_API_SEPERATOR(arg8, arg9)) #define LOG_HL_RENDERER_STATIC_API1(retval, arg1) \ - LOG_HL_RENDERER_API_STR(LOG_STATIC_API_BASE(retval) << LOG_API_ARGUMENTS(arg1)) + LOG_HL_RENDERER_API_STR(::fmt::format("{}{}", LOG_STATIC_API_BASE(retval), LOG_API_ARGUMENTS(arg1))) #define LOG_HL_RENDERER_STATIC_API2(retval, arg1, arg2) \ - LOG_HL_RENDERER_STATIC_API1(retval, arg1 LOG_API_SEPERATOR arg2) + LOG_HL_RENDERER_STATIC_API1(retval, LOG_API_SEPERATOR(arg1, arg2)) #define LOG_HL_RENDERER_STATIC_API3(retval, arg1, arg2, arg3) \ - LOG_HL_RENDERER_STATIC_API2(retval, arg1, arg2 LOG_API_SEPERATOR arg3) + LOG_HL_RENDERER_STATIC_API2(retval, arg1, LOG_API_SEPERATOR(arg2, arg3)) #define LOG_HL_RENDERER_STATIC_API4(retval, arg1, arg2, arg3, arg4) \ - LOG_HL_RENDERER_STATIC_API3(retval, arg1, arg2, arg3 LOG_API_SEPERATOR arg4) + LOG_HL_RENDERER_STATIC_API3(retval, arg1, arg2, LOG_API_SEPERATOR(arg3, arg4)) #define LOG_HL_RENDERER_STATIC_API5(retval, arg1, arg2, arg3, arg4, arg5) \ - LOG_HL_RENDERER_STATIC_API4(retval, arg1, arg2, arg3, arg4 LOG_API_SEPERATOR arg5) + LOG_HL_RENDERER_STATIC_API4(retval, arg1, arg2, arg3, LOG_API_SEPERATOR(arg4, arg5)) diff --git a/src/framework/impl/ErrorReporting.cpp b/src/framework/impl/ErrorReporting.cpp index fe0fa160a..e9d72ba43 100644 --- a/src/framework/impl/ErrorReporting.cpp +++ b/src/framework/impl/ErrorReporting.cpp @@ -17,11 +17,11 @@ namespace ramses::internal { if (object) { - LOG_ERROR_P(CONTEXT_CLIENT, "[{}] {}", object->getName(), errorMessage); + LOG_ERROR(CONTEXT_CLIENT, "[{}] {}", object->getName(), errorMessage); } else { - LOG_ERROR_P(CONTEXT_CLIENT, "{}", errorMessage); + LOG_ERROR(CONTEXT_CLIENT, "{}", errorMessage); } std::lock_guard g{ m_lock }; diff --git a/src/framework/impl/ErrorReporting.h b/src/framework/impl/ErrorReporting.h index 0aed8fb51..5be1f9817 100644 --- a/src/framework/impl/ErrorReporting.h +++ b/src/framework/impl/ErrorReporting.h @@ -9,6 +9,7 @@ #pragma once #include "ramses/framework/Issue.h" +#include "ramses/framework/APIExport.h" #include #include @@ -21,7 +22,7 @@ namespace ramses::internal { class RamsesObjectImpl; - class ErrorReporting + class RAMSES_IMPL_EXPORT ErrorReporting { public: void reset(); diff --git a/src/framework/impl/FrameworkFactoryRegistry.cpp b/src/framework/impl/FrameworkFactoryRegistry.cpp index f9e5b209a..c985dc8ef 100644 --- a/src/framework/impl/FrameworkFactoryRegistry.cpp +++ b/src/framework/impl/FrameworkFactoryRegistry.cpp @@ -25,7 +25,7 @@ namespace ramses::internal m_clientFactory = std::move(factory); } - void FrameworkFactoryRegistry::registerRendererFactory(std::unique_ptr factory) + void FrameworkFactoryRegistry::registerRendererFactory(UniquePtrWithDeleter factory) { if (m_rendererFactory) LOG_WARN(CONTEXT_FRAMEWORK, "FrameworkFactoryRegistry::registerRendererFactory called more than once"); diff --git a/src/framework/impl/FrameworkFactoryRegistry.h b/src/framework/impl/FrameworkFactoryRegistry.h index e432f3117..14842859a 100644 --- a/src/framework/impl/FrameworkFactoryRegistry.h +++ b/src/framework/impl/FrameworkFactoryRegistry.h @@ -8,12 +8,13 @@ #pragma once +#include "ramses/framework/APIExport.h" #include "impl/RamsesObjectFactoryInterfaces.h" #include namespace ramses::internal { - class FrameworkFactoryRegistry + class RAMSES_IMPL_EXPORT FrameworkFactoryRegistry { public: FrameworkFactoryRegistry(FrameworkFactoryRegistry const&) = delete; @@ -22,7 +23,7 @@ namespace ramses::internal static FrameworkFactoryRegistry& GetInstance(); void registerClientFactory(std::unique_ptr factory); - void registerRendererFactory(std::unique_ptr factory); + void registerRendererFactory(UniquePtrWithDeleter factory); IClientFactory* getClientFactory(); IRendererFactory* getRendererFactory(); @@ -31,7 +32,7 @@ namespace ramses::internal FrameworkFactoryRegistry() = default; std::unique_ptr m_clientFactory; - std::unique_ptr m_rendererFactory; + UniquePtrWithDeleter m_rendererFactory; }; } diff --git a/src/framework/impl/RamsesFramework.cpp b/src/framework/impl/RamsesFramework.cpp index 72648e1e9..11523614a 100644 --- a/src/framework/impl/RamsesFramework.cpp +++ b/src/framework/impl/RamsesFramework.cpp @@ -11,8 +11,6 @@ #include "impl/APILoggingMacros.h" #include "internal/PlatformAbstraction/PlatformTime.h" -#include "APILoggingHelper.h" - #include namespace ramses diff --git a/src/framework/impl/RamsesFrameworkConfig.cpp b/src/framework/impl/RamsesFrameworkConfig.cpp index a11e139b0..e8fdd5f16 100644 --- a/src/framework/impl/RamsesFrameworkConfig.cpp +++ b/src/framework/impl/RamsesFrameworkConfig.cpp @@ -106,6 +106,11 @@ namespace ramses m_impl->setPeriodicLogInterval(interval); } + void RamsesFrameworkConfig::setLoggingInstanceName(std::string_view instanceName) + { + m_impl->setLoggingInstanceName(instanceName); + } + bool RamsesFrameworkConfig::setParticipantGuid(uint64_t guid) { return m_impl->setParticipantGuid(guid); diff --git a/src/framework/impl/RamsesFrameworkConfigImpl.cpp b/src/framework/impl/RamsesFrameworkConfigImpl.cpp index 883556124..2ef0812a9 100644 --- a/src/framework/impl/RamsesFrameworkConfigImpl.cpp +++ b/src/framework/impl/RamsesFrameworkConfigImpl.cpp @@ -31,7 +31,7 @@ namespace ramses::internal m_featureLevel = featureLevel; if (!IsFeatureLevel(featureLevel)) { - LOG_ERROR_P(CONTEXT_CLIENT, "Unrecognized feature level '0{}' provided, falling back to feature level 01", featureLevel); + LOG_ERROR(CONTEXT_CLIENT, "Unrecognized feature level '0{}' provided, falling back to feature level 01", featureLevel); m_featureLevel = EFeatureLevel_01; } } @@ -42,7 +42,7 @@ namespace ramses::internal { if (!IsFeatureLevel(featureLevel)) { - LOG_ERROR_P(CONTEXT_CLIENT, "RamsesFrameworkConfig::setFeatureLevel: Failed to set unsupported feature level '{}'.", featureLevel); + LOG_ERROR(CONTEXT_CLIENT, "RamsesFrameworkConfig::setFeatureLevel: Failed to set unsupported feature level '{}'.", featureLevel); return false; } @@ -163,12 +163,22 @@ namespace ramses::internal m_periodicLogsEnabled = (periodicLogTimeout > 0); } + void RamsesFrameworkConfigImpl::setLoggingInstanceName(std::string_view instanceName) + { + m_loggingInstanceName = instanceName; + } + + const std::string& RamsesFrameworkConfigImpl::getLoggingInstanceName() const + { + return m_loggingInstanceName; + } + bool RamsesFrameworkConfigImpl::setParticipantGuid(uint64_t guid) { m_userProvidedGuid = Guid(guid); if (!m_userProvidedGuid.isValid() || guid < 256) { - LOG_ERROR_P(CONTEXT_CLIENT, "RamsesFrameworkConfig::setParticipantGuid: Failed to set invalid id '{}'.", m_userProvidedGuid); + LOG_ERROR(CONTEXT_CLIENT, "RamsesFrameworkConfig::setParticipantGuid: Failed to set invalid id '{}'.", m_userProvidedGuid); return false; } return true; diff --git a/src/framework/impl/RamsesFrameworkConfigImpl.h b/src/framework/impl/RamsesFrameworkConfigImpl.h index 6484a2b62..3c04e5511 100644 --- a/src/framework/impl/RamsesFrameworkConfigImpl.h +++ b/src/framework/impl/RamsesFrameworkConfigImpl.h @@ -54,6 +54,8 @@ namespace ramses::internal void setLogLevelConsole(ELogLevel logLevel); void setPeriodicLogInterval(std::chrono::seconds interval); + void setLoggingInstanceName(std::string_view instanceName); + [[nodiscard]] const std::string& getLoggingInstanceName() const; [[nodiscard]] bool setParticipantGuid(uint64_t guid); [[nodiscard]] Guid getUserProvidedGuid() const; @@ -79,5 +81,6 @@ namespace ramses::internal std::string m_participantName; bool m_enableDltApplicationRegistration = true; Guid m_userProvidedGuid; + std::string m_loggingInstanceName = "R"; }; } diff --git a/src/framework/impl/RamsesFrameworkImpl.cpp b/src/framework/impl/RamsesFrameworkImpl.cpp index 4ee2d4caf..aea1d5d3b 100644 --- a/src/framework/impl/RamsesFrameworkImpl.cpp +++ b/src/framework/impl/RamsesFrameworkImpl.cpp @@ -56,8 +56,8 @@ namespace ramses::internal RamsesFrameworkImpl::~RamsesFrameworkImpl() { - LOG_INFO(CONTEXT_CLIENT, "RamsesFramework::~RamsesFramework: guid " << m_participantAddress.getParticipantId() << ", wasConnected " << m_connected - << ", has Renderer " << !!m_ramsesRenderer << ", number of Clients " << m_ramsesClients.size()); + LOG_INFO(CONTEXT_CLIENT, "RamsesFramework::~RamsesFramework: guid {}, wasConnected {}, has Renderer {}, number of Clients {}", + m_participantAddress.getParticipantId(), m_connected, !!m_ramsesRenderer, m_ramsesClients.size()); if (m_connected) disconnect(); @@ -245,7 +245,7 @@ namespace ramses::internal m_errorReporting.set("addRamshCommand: command may not be null"); return false; } - LOG_INFO_P(CONTEXT_FRAMEWORK, "RamsesFrameworkImpl::addRamshCommand: keyword '{}'", command->keyword()); + LOG_INFO(CONTEXT_FRAMEWORK, "RamsesFrameworkImpl::addRamshCommand: keyword '{}'", command->keyword()); auto commandWrapper = std::make_shared(command); if (!m_ramsh->add(commandWrapper, false)) { @@ -263,7 +263,7 @@ namespace ramses::internal m_errorReporting.set("executeRamshCommand: command may not be empty"); return false; } - LOG_INFO_P(CONTEXT_FRAMEWORK, "RamsesFrameworkImpl::executeRamshCommand: '{}'", input); + LOG_INFO(CONTEXT_FRAMEWORK, "RamsesFrameworkImpl::executeRamshCommand: '{}'", input); if (!m_ramsh->execute(RamshTools::parseCommandString(input))) { m_errorReporting.set("executeRamshCommand: executing command failed"); @@ -325,6 +325,7 @@ namespace ramses::internal std::unique_ptr RamsesFrameworkImpl::CreateImpl(const RamsesFrameworkConfig& config) { + RamsesLogger::SetPrefixes(config.impl().getLoggingInstanceName(), "main"); GetRamsesLogger().initialize(config.impl().loggerConfig, false, config.impl().getDltApplicationRegistrationEnabled()); Guid myGuid = config.impl().getUserProvidedGuid(); @@ -344,8 +345,8 @@ namespace ramses::internal } ParticipantIdentifier participantAddress(myGuid, config.impl().getParticipantName()); - LOG_INFO(CONTEXT_FRAMEWORK, "Starting Ramses Client Application: " << participantAddress.getParticipantName() << " guid:" << participantAddress.getParticipantId() << - " stack: " << config.impl().getUsedProtocol()); + LOG_INFO(CONTEXT_FRAMEWORK, "Starting Ramses Client Application: {} guid:{} stack: {}", + participantAddress.getParticipantName(), participantAddress.getParticipantId(), config.impl().getUsedProtocol()); LogEnvironmentVariableIfSet("XDG_RUNTIME_DIR"); LogEnvironmentVariableIfSet("LIBGL_DRIVERS_PATH"); @@ -354,18 +355,18 @@ namespace ramses::internal const auto currentSyncTime = synchronized_clock::now(); const uint64_t systemClockTime = PlatformTime::GetMicrosecondsAbsolute(); - LOG_INFO(CONTEXT_FRAMEWORK, "Ramses synchronized time is using " << synchronized_clock::source() << - ". Currrent sync time " << asMicroseconds(currentSyncTime) << " us, system clock is " << systemClockTime << " us"); + LOG_INFO(CONTEXT_FRAMEWORK, "Ramses synchronized time is using {}. Currrent sync time {} us, system clock is {} us", + synchronized_clock::source(), asMicroseconds(currentSyncTime), systemClockTime); std::unique_ptr impl{ new RamsesFrameworkImpl(config.impl(), participantAddress) }; if (config.impl().m_periodicLogsEnabled) { - LOG_INFO_P(CONTEXT_FRAMEWORK, "RamsesFramework: periodic logs enabled with period of {}s", config.impl().periodicLogTimeout); + LOG_INFO(CONTEXT_FRAMEWORK, "RamsesFramework: periodic logs enabled with period of {}s", config.impl().periodicLogTimeout); impl->m_periodicLogger.startLogging(config.impl().periodicLogTimeout); } else { - LOG_INFO_P(CONTEXT_FRAMEWORK, "RamsesFramework: periodic logs disabled"); + LOG_INFO(CONTEXT_FRAMEWORK, "RamsesFramework: periodic logs disabled"); } return impl; @@ -382,7 +383,7 @@ namespace ramses::internal // TODO(tobias) envVarValue.getLength should not be there because empty variable is also set. remove when fixed if (PlatformEnvironmentVariables::get(std::string{envVarName}, envVarValue) && !envVarValue.empty()) { - LOG_INFO(CONTEXT_FRAMEWORK, "Environment variable set: " << envVarName << "=" << envVarValue); + LOG_INFO(CONTEXT_FRAMEWORK, "Environment variable set: {}={}", envVarName, envVarValue); } } diff --git a/src/framework/impl/RamsesFrameworkImpl.h b/src/framework/impl/RamsesFrameworkImpl.h index 8898fe6aa..4f3e1e9c5 100644 --- a/src/framework/impl/RamsesFrameworkImpl.h +++ b/src/framework/impl/RamsesFrameworkImpl.h @@ -16,6 +16,7 @@ #include "internal/Core/Utils/StatisticCollection.h" #include "internal/Communication/TransportCommon/LogConnectionInfo.h" #include "internal/Communication/TransportCommon/EConnectionProtocol.h" +#include "ramses/framework/APIExport.h" #include "ramses/framework/RamsesFrameworkTypes.h" #include "ramses/framework/EFeatureLevel.h" #include "ramses/framework/Issue.h" @@ -45,7 +46,7 @@ namespace ramses::internal class PublicRamshCommand; class RamsesFrameworkConfigImpl; - class RamsesFrameworkImpl + class RAMSES_IMPL_EXPORT RamsesFrameworkImpl { public: ~RamsesFrameworkImpl(); diff --git a/src/framework/impl/RamsesObject.cpp b/src/framework/impl/RamsesObject.cpp index 89f702036..f80fd4bb2 100644 --- a/src/framework/impl/RamsesObject.cpp +++ b/src/framework/impl/RamsesObject.cpp @@ -27,6 +27,7 @@ #include "ramses/client/logic/AnimationNode.h" #include "ramses/client/logic/TimerNode.h" #include "ramses/client/logic/AnchorPoint.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/Effect.h" #include "ramses/client/RamsesClient.h" @@ -128,41 +129,43 @@ namespace ramses return dynamic_cast(this); } - template RAMSES_API const LogicObject* RamsesObject::internalCast() const; - template RAMSES_API const LogicNode* RamsesObject::internalCast() const; - template RAMSES_API const RamsesBinding* RamsesObject::internalCast() const; - template RAMSES_API const LuaModule* RamsesObject::internalCast() const; - template RAMSES_API const LuaScript* RamsesObject::internalCast() const; - template RAMSES_API const LuaInterface* RamsesObject::internalCast() const; - template RAMSES_API const NodeBinding* RamsesObject::internalCast() const; - template RAMSES_API const AppearanceBinding* RamsesObject::internalCast() const; - template RAMSES_API const CameraBinding* RamsesObject::internalCast() const; - template RAMSES_API const RenderPassBinding* RamsesObject::internalCast() const; - template RAMSES_API const RenderGroupBinding* RamsesObject::internalCast() const; - template RAMSES_API const MeshNodeBinding* RamsesObject::internalCast() const; - template RAMSES_API const SkinBinding* RamsesObject::internalCast() const; - template RAMSES_API const DataArray* RamsesObject::internalCast() const; - template RAMSES_API const AnimationNode* RamsesObject::internalCast() const; - template RAMSES_API const TimerNode* RamsesObject::internalCast() const; - template RAMSES_API const AnchorPoint* RamsesObject::internalCast() const; - - template RAMSES_API LogicObject* RamsesObject::internalCast(); - template RAMSES_API LogicNode* RamsesObject::internalCast(); - template RAMSES_API RamsesBinding* RamsesObject::internalCast(); - template RAMSES_API LuaModule* RamsesObject::internalCast(); - template RAMSES_API LuaScript* RamsesObject::internalCast(); - template RAMSES_API LuaInterface* RamsesObject::internalCast(); - template RAMSES_API NodeBinding* RamsesObject::internalCast(); - template RAMSES_API AppearanceBinding* RamsesObject::internalCast(); - template RAMSES_API CameraBinding* RamsesObject::internalCast(); - template RAMSES_API RenderPassBinding* RamsesObject::internalCast(); - template RAMSES_API RenderGroupBinding* RamsesObject::internalCast(); - template RAMSES_API MeshNodeBinding* RamsesObject::internalCast(); - template RAMSES_API SkinBinding* RamsesObject::internalCast(); - template RAMSES_API DataArray* RamsesObject::internalCast(); - template RAMSES_API AnimationNode* RamsesObject::internalCast(); - template RAMSES_API TimerNode* RamsesObject::internalCast(); - template RAMSES_API AnchorPoint* RamsesObject::internalCast(); + template RAMSES_API const LogicObject* RamsesObject::internalCast() const; + template RAMSES_API const LogicNode* RamsesObject::internalCast() const; + template RAMSES_API const RamsesBinding* RamsesObject::internalCast() const; + template RAMSES_API const LuaModule* RamsesObject::internalCast() const; + template RAMSES_API const LuaScript* RamsesObject::internalCast() const; + template RAMSES_API const LuaInterface* RamsesObject::internalCast() const; + template RAMSES_API const NodeBinding* RamsesObject::internalCast() const; + template RAMSES_API const AppearanceBinding* RamsesObject::internalCast() const; + template RAMSES_API const CameraBinding* RamsesObject::internalCast() const; + template RAMSES_API const RenderPassBinding* RamsesObject::internalCast() const; + template RAMSES_API const RenderGroupBinding* RamsesObject::internalCast() const; + template RAMSES_API const MeshNodeBinding* RamsesObject::internalCast() const; + template RAMSES_API const SkinBinding* RamsesObject::internalCast() const; + template RAMSES_API const DataArray* RamsesObject::internalCast() const; + template RAMSES_API const AnimationNode* RamsesObject::internalCast() const; + template RAMSES_API const TimerNode* RamsesObject::internalCast() const; + template RAMSES_API const AnchorPoint* RamsesObject::internalCast() const; + template RAMSES_API const RenderBufferBinding* RamsesObject::internalCast() const; + + template RAMSES_API LogicObject* RamsesObject::internalCast(); + template RAMSES_API LogicNode* RamsesObject::internalCast(); + template RAMSES_API RamsesBinding* RamsesObject::internalCast(); + template RAMSES_API LuaModule* RamsesObject::internalCast(); + template RAMSES_API LuaScript* RamsesObject::internalCast(); + template RAMSES_API LuaInterface* RamsesObject::internalCast(); + template RAMSES_API NodeBinding* RamsesObject::internalCast(); + template RAMSES_API AppearanceBinding* RamsesObject::internalCast(); + template RAMSES_API CameraBinding* RamsesObject::internalCast(); + template RAMSES_API RenderPassBinding* RamsesObject::internalCast(); + template RAMSES_API RenderGroupBinding* RamsesObject::internalCast(); + template RAMSES_API MeshNodeBinding* RamsesObject::internalCast(); + template RAMSES_API SkinBinding* RamsesObject::internalCast(); + template RAMSES_API DataArray* RamsesObject::internalCast(); + template RAMSES_API AnimationNode* RamsesObject::internalCast(); + template RAMSES_API TimerNode* RamsesObject::internalCast(); + template RAMSES_API AnchorPoint* RamsesObject::internalCast(); + template RAMSES_API RenderBufferBinding* RamsesObject::internalCast(); template RAMSES_API const ClientObject* RamsesObject::internalCast() const; template RAMSES_API const RamsesObject* RamsesObject::internalCast() const; diff --git a/src/framework/impl/RamsesObjectImpl.h b/src/framework/impl/RamsesObjectImpl.h index 6fdac5e8f..9bd05145e 100644 --- a/src/framework/impl/RamsesObjectImpl.h +++ b/src/framework/impl/RamsesObjectImpl.h @@ -54,8 +54,6 @@ namespace ramses::internal virtual void deinitializeFrameworkData() = 0; void validate(ValidationReportImpl& report) const; - - protected: virtual void onValidate(ValidationReportImpl& /*report*/) const {}; private: diff --git a/src/framework/internal/CMakeLists.txt b/src/framework/internal/CMakeLists.txt new file mode 100644 index 000000000..7050e73a3 --- /dev/null +++ b/src/framework/internal/CMakeLists.txt @@ -0,0 +1,115 @@ +# ------------------------------------------------------------------------- +# Copyright (C) 2023 BMW AG +# ------------------------------------------------------------------------- +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# ------------------------------------------------------------------------- + +if (ramses-sdk_ENABLE_TCP_SUPPORT) + list(APPEND FRAMEWORK_INTERNAL_SOURCES Communication/TransportTCP/*.h + Communication/TransportTCP/*.cpp) + list(APPEND FRAMEWORK_INTERNAL_LIBS asio) +endif() + +if(ramses-sdk_HAS_DLT) + list(APPEND FRAMEWORK_INTERNAL_SOURCES DltLogAppender/DltAdapterImpl/*.h + DltLogAppender/DltAdapterImpl/*.cpp) + list(APPEND FRAMEWORK_INTERNAL_LIBS automotive-dlt) +endif() + +find_package(AndroidSDK) +if(AndroidSDK_FOUND) + list(APPEND FRAMEWORK_INTERNAL_SOURCES Core/Utils/AndroidLogger/*.h + Core/Utils/AndroidLogger/*.cpp) + list(APPEND FRAMEWORK_INTERNAL_LIBS AndroidSDK) +endif() + +createModule( + NAME ramses-framework-internal + TYPE STATIC_LIBRARY + ENABLE_INSTALL OFF + + INCLUDE_PATHS ${PROJECT_SOURCE_DIR}/src/framework + # internal + SRC_FILES ${FRAMEWORK_INTERNAL_SOURCES} + SRC_FILES Watchdog/*.h + Watchdog/*.cpp + SRC_FILES PlatformAbstraction/*.h + PlatformAbstraction/Collections/*.h + PlatformAbstraction/*.h + PlatformAbstraction/*.cpp + SRC_FILES Core/Math3d/*.h + Core/Math3d/*.cpp + SRC_FILES Core/Utils/*.h + Core/Utils/*.cpp + SRC_FILES Core/Common/*.h + Core/Common/*.cpp + SRC_FILES Core/TaskFramework/*.h + Core/TaskFramework/*.cpp + SRC_FILES SceneGraph/SceneAPI/*.h + SceneGraph/SceneAPI/*.cpp + SRC_FILES SceneGraph/Scene/*.h + SceneGraph/Scene/*.cpp + SRC_FILES SceneGraph/Resource/*.h + SceneGraph/Resource/*.cpp + SRC_FILES SceneGraph/SceneUtils/*.h + SceneGraph/SceneUtils/*.cpp + SRC_FILES Communication/TransportCommon/*.h + Communication/TransportCommon/*.cpp + SRC_FILES Ramsh/*.h + Ramsh/*.cpp + SRC_FILES Components/*.h + Components/*.cpp + SRC_FILES DltLogAppender/*.h + DltLogAppender/*.cpp + DltLogAppender/src/*.cpp + SRC_FILES SceneReferencing/*.h + SceneReferencing/*.cpp + + DEPENDENCIES ramses-api + ramses-common-base + lz4 + fmt::fmt + ramses-abseil + lodepng + cityhash + ${FRAMEWORK_INTERNAL_LIBS} + ) + +if (ramses-sdk_ENABLE_TCP_SUPPORT) + message(STATUS "+ TCP communication system support enabled") + target_compile_definitions(ramses-framework-internal PUBLIC "-DHAS_TCP_COMM=1") +else() + message(STATUS "- TCP communication system support disabled") +endif() + +if (ramses-sdk_HAS_DLT) + target_compile_definitions(ramses-framework-internal PUBLIC "-DDLT_ENABLED") + + if (automotive-dlt_HAS_FILETRANSFER) + target_compile_definitions(ramses-framework-internal PUBLIC "-DDLT_HAS_FILETRANSFER") + endif() +endif() + +if(ramses-sdk_USE_LINUX_DEV_PTP) + target_compile_definitions(ramses-framework-internal PUBLIC "-DRAMSES_LINUX_USE_DEV_PTP=1") +endif() + +# Thread priority and binding for worker threads +if (DEFINED ramses-sdk_WORKER_THREAD_PRIORITY AND NOT ramses-sdk_WORKER_THREAD_PRIORITY STREQUAL "") + target_compile_definitions(ramses-framework-internal PRIVATE "-DRAMSES_WORKER_THREAD_PRIORITY=${ramses-sdk_WORKER_THREAD_PRIORITY}") +endif() + +if (DEFINED ramses-sdk_WORKER_THREAD_CORE_BINDING AND NOT ramses-sdk_WORKER_THREAD_CORE_BINDING STREQUAL "") + target_compile_definitions(ramses-framework-internal PRIVATE "-DRAMSES_WORKER_THREAD_CORE_BINDING=${ramses-sdk_WORKER_THREAD_CORE_BINDING}") +endif() + +if (DEFINED ramses-sdk_CONN_KEEPALIVE_THREAD_CORE_BINDING AND NOT ramses-sdk_CONN_KEEPALIVE_THREAD_CORE_BINDING STREQUAL "") + target_compile_definitions(ramses-framework-internal PRIVATE "-DRAMSES_CONN_KEEPALIVE_THREAD_CORE_BINDING=${ramses-sdk_CONN_KEEPALIVE_THREAD_CORE_BINDING}") +endif() + + +if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU") + target_compile_options(ramses-framework-internal PRIVATE "-Wsuggest-override") +endif() diff --git a/src/framework/internal/Communication/TransportCommon/CommunicationSystemFactory.cpp b/src/framework/internal/Communication/TransportCommon/CommunicationSystemFactory.cpp index 5663559a4..4880f3530 100644 --- a/src/framework/internal/Communication/TransportCommon/CommunicationSystemFactory.cpp +++ b/src/framework/internal/Communication/TransportCommon/CommunicationSystemFactory.cpp @@ -41,12 +41,12 @@ namespace ramses::internal const bool isDaemon = false; const NetworkParticipantAddress participantNetworkAddress(participantIdentifier.getParticipantId(), participantIdentifier.getParticipantName(), config.m_tcpConfig.getIPAddress(), config.m_tcpConfig.getPort(isDaemon)); - LOG_DEBUG(CONTEXT_COMMUNICATION, "ConstructTCPConnectionManager: My Address: " << participantNetworkAddress.getIp() << ":" << participantNetworkAddress.getPort()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "ConstructTCPConnectionManager: My Address: {}:{}", participantNetworkAddress.getIp(), participantNetworkAddress.getPort()); // daemon address const NetworkParticipantAddress daemonNetworkAddress = NetworkParticipantAddress(TCPConnectionSystem::GetDaemonId(), "SM", config.m_tcpConfig.getDaemonIPAddress(), config.m_tcpConfig.getDaemonPort()); - LOG_DEBUG(CONTEXT_COMMUNICATION, "ConstructTCPConnectionManager: Daemon Address: " << daemonNetworkAddress.getIp() << ":" << daemonNetworkAddress.getPort()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "ConstructTCPConnectionManager: Daemon Address: {}:{}", daemonNetworkAddress.getIp(), daemonNetworkAddress.getPort()); // allocate return std::make_unique(participantNetworkAddress, config.getProtocolVersion(), daemonNetworkAddress, false, frameworkLock, statisticCollection, config.m_tcpConfig.getAliveInterval(), config.m_tcpConfig.getAliveTimeout()); @@ -99,7 +99,7 @@ namespace ramses::internal return std::make_unique(); } default: - LOG_FATAL(CONTEXT_COMMUNICATION, "Unable to construct connection system for given protocol: " << config.getUsedProtocol() << ". Ensure that TCP or the fake connection system is enabled."); + LOG_FATAL(CONTEXT_COMMUNICATION, "Unable to construct connection system for given protocol: {}. Ensure that TCP or the fake connection system is enabled.", config.getUsedProtocol()); assert(false && "Unable to construct connection system for given protocol. Ensure that TCP or the fake connection system is enabled."); return nullptr; } diff --git a/src/framework/internal/Communication/TransportCommon/ConnectionStatusUpdateNotifier.cpp b/src/framework/internal/Communication/TransportCommon/ConnectionStatusUpdateNotifier.cpp index 70f591900..53d15ea40 100644 --- a/src/framework/internal/Communication/TransportCommon/ConnectionStatusUpdateNotifier.cpp +++ b/src/framework/internal/Communication/TransportCommon/ConnectionStatusUpdateNotifier.cpp @@ -51,7 +51,7 @@ namespace ramses::internal assert(status == EConnectionStatus_Connected || status == EConnectionStatus_NotConnected); if (status == EConnectionStatus_Connected) { - LOG_INFO(m_logContext, "ConnectionStatusUpdateNotifier(" << m_participantName << ":" << m_usage << ")::doStatusUpdate: newParticipantHasConnected " << participant); + LOG_INFO(m_logContext, "ConnectionStatusUpdateNotifier({}:{})::doStatusUpdate: newParticipantHasConnected {}", m_participantName, m_usage, participant); m_currentState.put(participant); for(auto listener : m_listeners) { @@ -60,7 +60,7 @@ namespace ramses::internal } else { - LOG_INFO(m_logContext, "ConnectionStatusUpdateNotifier(" << m_participantName << ":" << m_usage << ")::doStatusUpdate: participantHasDisconnected " << participant); + LOG_INFO(m_logContext, "ConnectionStatusUpdateNotifier({}:{})::doStatusUpdate: participantHasDisconnected {}", m_participantName, m_usage, participant); m_currentState.remove(participant); for (auto listener : m_listeners) { diff --git a/src/framework/internal/Communication/TransportCommon/RamsesTransportProtocolVersion.h b/src/framework/internal/Communication/TransportCommon/RamsesTransportProtocolVersion.h index 21fbbe14c..ffbf23a26 100644 --- a/src/framework/internal/Communication/TransportCommon/RamsesTransportProtocolVersion.h +++ b/src/framework/internal/Communication/TransportCommon/RamsesTransportProtocolVersion.h @@ -8,4 +8,4 @@ #pragma once -#define RAMSES_TRANSPORT_PROTOCOL_VERSION_MAJOR 124 +#define RAMSES_TRANSPORT_PROTOCOL_VERSION_MAJOR 126 diff --git a/src/framework/internal/Communication/TransportCommon/SceneUpdateSerializationHelper.cpp b/src/framework/internal/Communication/TransportCommon/SceneUpdateSerializationHelper.cpp index 283513172..9eb36e552 100644 --- a/src/framework/internal/Communication/TransportCommon/SceneUpdateSerializationHelper.cpp +++ b/src/framework/internal/Communication/TransportCommon/SceneUpdateSerializationHelper.cpp @@ -264,7 +264,7 @@ namespace ramses::internal if (data.size() != expectedDataSize) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "ResourceSerialization::Deserialize: Expected resource size {} but got {}, compression state {}", + LOG_ERROR(CONTEXT_FRAMEWORK, "ResourceSerialization::Deserialize: Expected resource size {} but got {}, compression state {}", expectedDataSize, data.size(), header.compressionStatus); return nullptr; } diff --git a/src/framework/internal/Communication/TransportCommon/SceneUpdateStreamDeserializer.cpp b/src/framework/internal/Communication/TransportCommon/SceneUpdateStreamDeserializer.cpp index 760a7c658..d58504ff8 100644 --- a/src/framework/internal/Communication/TransportCommon/SceneUpdateStreamDeserializer.cpp +++ b/src/framework/internal/Communication/TransportCommon/SceneUpdateStreamDeserializer.cpp @@ -19,13 +19,13 @@ namespace ramses::internal // check state + input if (m_hasFailed) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::processData: Invalid state due to previous error"); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::processData: Invalid state due to previous error"); return fail(); } if (data.size() < sizeof(uint32_t)*2 + 1) // must at least be packet header + 'some' data { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::processData: Packet too small (size {})", data.size()); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::processData: Packet too small (size {})", data.size()); return fail(); } @@ -38,7 +38,7 @@ namespace ramses::internal if (packetNum != m_nextExpectedPacketNum) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::processData: expected packet {}, got {}", m_nextExpectedPacketNum, packetNum); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::processData: expected packet {}, got {}", m_nextExpectedPacketNum, packetNum); return fail(); } @@ -52,7 +52,7 @@ namespace ramses::internal } else { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::processData: Corrupted packet, more flag is {}", hasMorePackets); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::processData: Corrupted packet, more flag is {}", hasMorePackets); return fail(); } @@ -82,7 +82,7 @@ namespace ramses::internal { if (!m_currentBlock.empty() || m_currentBlockSize != 0) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::processData: Last packet but data left to read (read {}, needed {}, type {})", + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::processData: Last packet but data left to read (read {}, needed {}, type {})", m_currentBlock.size(), m_currentBlockSize, m_blockType); return fail(); } @@ -115,7 +115,7 @@ namespace ramses::internal // block header is guaranteed continuous if (is.getCurrentReadBytes() + sizeof(uint32_t)*2 > dataSize) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::startReadingNewBlock: Could not read header"); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::startReadingNewBlock: Could not read header"); return false; } @@ -147,7 +147,7 @@ namespace ramses::internal else { // only warn on unknown block, no fail - LOG_WARN_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::finalizeBlock: Ignore unexpected block type {}", m_blockType); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::finalizeBlock: Ignore unexpected block type {}", m_blockType); } m_currentBlock.clear(); @@ -165,12 +165,12 @@ namespace ramses::internal { if (m_currentBlock.size() < sizeof(uint32_t)*2) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::handleSceneActionCollection: Block too small ({})", m_currentBlock.size()); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::handleSceneActionCollection: Block too small ({})", m_currentBlock.size()); return false; } if (m_currentResult.actions.numberOfActions() != 0) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::handleSceneActionCollection: More than one SceneActionCollection in packet"); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::handleSceneActionCollection: More than one SceneActionCollection in packet"); return false; } @@ -189,7 +189,7 @@ namespace ramses::internal { if (m_currentBlock.size() < sizeof(uint32_t)*2) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::handleResource: Block to small ({})", m_currentBlock.size()); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::handleResource: Block to small ({})", m_currentBlock.size()); return false; } @@ -209,7 +209,7 @@ namespace ramses::internal { if (m_currentBlock.size() < sizeof(uint32_t)) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::handleFlushInfos: Block to small ({})", m_currentBlock.size()); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::handleFlushInfos: Block to small ({})", m_currentBlock.size()); return false; } @@ -219,7 +219,7 @@ namespace ramses::internal if (dataSize < FlushInformation::getMinimumSize()) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::handleFlushInfos: Block to small for a valid FlushInfo ({})", dataSize); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneUpdateStreamDeserializer::handleFlushInfos: Block to small for a valid FlushInfo ({})", dataSize); return false; } diff --git a/src/framework/internal/Communication/TransportCommon/SingleSceneUpdateWriter.cpp b/src/framework/internal/Communication/TransportCommon/SingleSceneUpdateWriter.cpp index d33e22fe4..5bef2eeab 100644 --- a/src/framework/internal/Communication/TransportCommon/SingleSceneUpdateWriter.cpp +++ b/src/framework/internal/Communication/TransportCommon/SingleSceneUpdateWriter.cpp @@ -53,7 +53,7 @@ namespace ramses::internal { if (m_packetMem.size() < 50) { - LOG_FATAL_P(CONTEXT_COMMUNICATION, "SingleSceneUpdateWriter::write: Packet size of {} is too small", m_packetMem.size()); + LOG_FATAL(CONTEXT_COMMUNICATION, "SingleSceneUpdateWriter::write: Packet size of {} is too small", m_packetMem.size()); return false; } @@ -182,7 +182,7 @@ namespace ramses::internal if (!m_writeDoneFunc(m_packetWriter.getBytesWritten())) { - LOG_ERROR_P(CONTEXT_COMMUNICATION, "SingleSceneUpdateWriter::finalizePacket: Packet write failed (size {})", m_packetWriter.getBytesWritten()); + LOG_ERROR(CONTEXT_COMMUNICATION, "SingleSceneUpdateWriter::finalizePacket: Packet write failed (size {})", m_packetWriter.getBytesWritten()); return false; } const auto bytesWritten{m_packetWriter.getBytesWritten()}; diff --git a/src/framework/internal/Communication/TransportTCP/TCPConnectionSystem.cpp b/src/framework/internal/Communication/TransportTCP/TCPConnectionSystem.cpp index c0633bcd8..907f829f4 100644 --- a/src/framework/internal/Communication/TransportTCP/TCPConnectionSystem.cpp +++ b/src/framework/internal/Communication/TransportTCP/TCPConnectionSystem.cpp @@ -44,7 +44,7 @@ namespace ramses::internal , m_aliveInterval(aliveInterval) , m_aliveIntervalTimeout(aliveTimeout) , m_frameworkLock(frameworkLock) - , m_thread("R_TCP_ConnSys") + , m_thread("TCP_ConnSys") , m_statisticCollection(statisticCollection) , m_ramsesConnectionStatusUpdateNotifier(m_participantAddress.getParticipantName(), CONTEXT_COMMUNICATION, "ramses", frameworkLock) , m_sceneProviderHandler(nullptr) @@ -77,14 +77,14 @@ namespace ramses::internal })); if (m_aliveIntervalTimeout < m_aliveInterval + std::chrono::milliseconds{100}) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << "): Alive timeout very low, expect issues " << - "(alive " << m_aliveInterval.count() << ", timeout " << m_aliveIntervalTimeout.count() << ")"); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({}): Alive timeout very low, expect issues (alive {}, timeout {})", + m_participantAddress.getParticipantName(), m_aliveInterval.count(), m_aliveIntervalTimeout.count()); } PlatformGuard guard(m_frameworkLock); if (m_runState) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::connectServices: called more than once"); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::connectServices: called more than once", m_participantAddress.getParticipantName()); return false; } @@ -96,12 +96,12 @@ namespace ramses::internal bool TCPConnectionSystem::disconnectServices() { - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::disconnectServices"); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::disconnectServices", m_participantAddress.getParticipantName()); PlatformGuard guard(m_frameworkLock); if (!m_runState) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::disconnectServices: called without being connected"); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::disconnectServices: called without being connected", m_participantAddress.getParticipantName()); return false; } @@ -115,7 +115,7 @@ namespace ramses::internal } m_runState.reset(); - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::disconnectServices: done"); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::disconnectServices: done", m_participantAddress.getParticipantName()); return true; } @@ -144,7 +144,7 @@ namespace ramses::internal // initiate connection to daemon (when not self) if (m_daemonAddress.getPort() != 0 && m_hasOtherDaemon) { - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::run: Initiate connection to daemon at " << m_daemonAddress.getIp() << ":" << m_daemonAddress.getPort()); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::run: Initiate connection to daemon at {}:{}", m_participantAddress.getParticipantName(), m_daemonAddress.getIp(), m_daemonAddress.getPort()); auto daemonPp = std::make_shared(m_daemonAddress, m_runState->m_io, EParticipantType::Daemon, EParticipantState::Connecting); m_connectingParticipants.put(daemonPp); @@ -175,7 +175,7 @@ namespace ramses::internal m_runState->m_acceptor.open(asio::ip::tcp::v4(), e); if (e) { - LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::openAcceptor: open failed. " << e.message().c_str()); + LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::openAcceptor: open failed. {}", m_participantAddress.getParticipantName(), e.message().c_str()); return false; } @@ -185,19 +185,19 @@ namespace ramses::internal m_runState->m_acceptor.bind(asio::ip::tcp::endpoint(asio::ip::address::from_string("0.0.0.0"), m_participantAddress.getPort()), e); if (e) { - LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::openAcceptor: bind failed. " << e.message().c_str()); + LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::openAcceptor: bind failed. {}", m_participantAddress.getParticipantName(), e.message().c_str()); return false; } m_runState->m_acceptor.listen(asio::socket_base::max_connections, e); if (e) { - LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::openAcceptor: listen failed. " << e.message().c_str()); + LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::openAcceptor: listen failed. {}", m_participantAddress.getParticipantName(), e.message().c_str()); return false; } const auto endpoint = m_runState->m_acceptor.local_endpoint(); - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::openAcceptor: Listening for connections on " << endpoint.address().to_string().c_str() << ":" << endpoint.port()); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::openAcceptor: Listening for connections on {}:{}", m_participantAddress.getParticipantName(), endpoint.address().to_string().c_str(), endpoint.port()); return true; } @@ -208,15 +208,15 @@ namespace ramses::internal [this](asio::error_code e) { if (e) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doAcceptIncomingConnections: accept failed. " << e.message().c_str()); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doAcceptIncomingConnections: accept failed. {}", m_participantAddress.getParticipantName(), e.message().c_str()); doAcceptIncomingConnections(); // TODO: not sure if correct response or is really recoverable (close + reopen acceptor?) } else { auto remoteEp = m_runState->m_acceptorSocket.remote_endpoint(); - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doAcceptIncomingConnections: Accepted new connection from " << - remoteEp.address().to_string().c_str() << ":" << remoteEp.port()); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doAcceptIncomingConnections: Accepted new connection from {}:{}", + m_participantAddress.getParticipantName(), remoteEp.address().to_string().c_str(), remoteEp.port()); // create new participant auto pp = std::make_shared(NetworkParticipantAddress(), m_runState->m_io, EParticipantType::Client, EParticipantState::WaitingForHello); @@ -234,7 +234,7 @@ namespace ramses::internal void TCPConnectionSystem::doConnect(const ParticipantPtr& pp) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doConnect: Try connect to participant at " << pp->address.getIp() << ":" << pp->address.getPort()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doConnect: Try connect to participant at {}:{}", m_participantAddress.getParticipantName(), pp->address.getIp(), pp->address.getPort()); // convert localhost to an actual ip, no need for dns resolving here const char* const ipStr = (pp->address.getIp() == "localhost" ? "127.0.0.1" : pp->address.getIp().c_str()); @@ -244,7 +244,7 @@ namespace ramses::internal const auto asioIp = asio::ip::address::from_string(ipStr, err); if (err) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doConnect: Failed to parse ip address '" << pp->address.getIp() << ":" << pp->address.getPort() << "'"); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doConnect: Failed to parse ip address '{}:{}'", m_participantAddress.getParticipantName(), pp->address.getIp(), pp->address.getPort()); return; } @@ -254,14 +254,14 @@ namespace ramses::internal if (e) { // connect failed, try again after timeout - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doConnect: Connect to " - << pp->address.getIp() << ":" << pp->address.getPort() << " failed. " << e.message().c_str()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doConnect: Connect to {}:{} failed. {}", + m_participantAddress.getParticipantName(), pp->address.getIp(), pp->address.getPort(), e.message().c_str()); pp->connectTimer.expires_after(std::chrono::milliseconds{100}); pp->connectTimer.async_wait([this, pp](asio::error_code ee) { if (ee) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doConnect: Connect to " - << pp->address.getIp() << ":" << pp->address.getPort() << " failed. Timer canceled"); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doConnect: Connect to {}:{} failed. Timer canceled", + m_participantAddress.getParticipantName(), pp->address.getIp(), pp->address.getPort()); } else { @@ -272,7 +272,7 @@ namespace ramses::internal else { // connected - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doConnect: Established to " << usedEndpoint.address().to_string().c_str() << ":" << usedEndpoint.port()); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doConnect: Established to {}:{}", m_participantAddress.getParticipantName(), usedEndpoint.address().to_string().c_str(), usedEndpoint.port()); initializeNewlyConnectedParticipant(pp); } }); @@ -280,7 +280,7 @@ namespace ramses::internal void TCPConnectionSystem::initializeNewlyConnectedParticipant(const ParticipantPtr& pp) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::initializeNewlyConnectedParticipant: " << pp->address.getParticipantId()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::initializeNewlyConnectedParticipant: {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId()); assert(m_connectingParticipants.contains(pp)); // Set send buffer to resource chunk size to allow maximum one resource chunk to use up send buffer. This @@ -303,8 +303,8 @@ namespace ramses::internal pp->currentOutBuffer = msg.stream.release(); const auto fullSize = static_cast(pp->currentOutBuffer.size()); - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendMessageToParticipant: To " << pp->address.getParticipantId() << - ", MsgType " << msg.messageType << ", Size " << fullSize); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendMessageToParticipant: To {}, MsgType {}, Size {}", + m_participantAddress.getParticipantName(), pp->address.getParticipantId(), msg.messageType, fullSize); RawBinaryOutputStream s(pp->currentOutBuffer.data(), pp->currentOutBuffer.size()); const uint32_t remainingSize = fullSize - sizeof(pp->lengthReceiveBuffer); @@ -315,16 +315,15 @@ namespace ramses::internal [this, pp](asio::error_code e, std::size_t sentBytes) { if (e) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendMessageToParticipant: Send to " - << pp->address.ParticipantIdentifier::getParticipantId() << "/" << pp->address.ParticipantIdentifier::getParticipantName() << - " failed. " << e.message().c_str() << ". Remove participant"); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendMessageToParticipant: Send to {}/{} failed. {}. Remove participant", + m_participantAddress.getParticipantName(), pp->address.ParticipantIdentifier::getParticipantId(), pp->address.ParticipantIdentifier::getParticipantName(), e.message().c_str()); removeParticipant(pp); } else { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendMessageToParticipant: To " << pp->address.getParticipantId() << - ", MsgBytes " << pp->currentOutBuffer.size() << ", SentBytes " << sentBytes); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendMessageToParticipant: To {}, MsgBytes {}, SentBytes {}", + m_participantAddress.getParticipantName(), pp->address.getParticipantId(), pp->currentOutBuffer.size(), sentBytes); pp->currentOutBuffer.clear(); pp->lastSent = std::chrono::steady_clock::now(); @@ -366,21 +365,20 @@ namespace ramses::internal void TCPConnectionSystem::doReadHeader(const ParticipantPtr& pp) { - LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doReadHeader: start reading from " << pp->address.getParticipantId()); + LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doReadHeader: start reading from {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId()); asio::async_read(pp->socket, asio::mutable_buffer(&pp->lengthReceiveBuffer, sizeof(pp->lengthReceiveBuffer)), [this, pp](asio::error_code e, size_t readBytes) { if (e) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doReadHeader: read from " - << pp->address.getParticipantId() << " failed (len " << readBytes << "). " << e.message().c_str()); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doReadHeader: read from {} failed (len {}). ", + m_participantAddress.getParticipantName(), pp->address.getParticipantId(), readBytes, e.message().c_str()); removeParticipant(pp); } else { - LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doReadHeader: done read from " - << pp->address.getParticipantId() << ". Expect " << pp->lengthReceiveBuffer << " bytes"); + LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doReadHeader: done read from {}. Expect {} bytes", m_participantAddress.getParticipantName(), pp->address.getParticipantId(), pp->lengthReceiveBuffer); updateLastReceivedTime(pp); pp->receiveBuffer.resize(pp->lengthReceiveBuffer); @@ -396,14 +394,14 @@ namespace ramses::internal [this, pp](asio::error_code e, size_t readBytes) { if (e) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doReadContent: read from " - << pp->address.getParticipantId() << " failed (len " << readBytes << "). " << e.message().c_str()); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doReadContent: read from {} failed (len {}). {}", + m_participantAddress.getParticipantName(), pp->address.getParticipantId(), readBytes, e.message().c_str()); removeParticipant(pp); } else { - LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::doReadContent: done read from " - << pp->address.getParticipantId() << ", " << readBytes << " bytes"); + LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::doReadContent: done read from {}, {} bytes", + m_participantAddress.getParticipantName(), pp->address.getParticipantId(), readBytes); m_statisticCollection.statMessagesReceived.incCounter(1); @@ -441,8 +439,8 @@ namespace ramses::internal if (pp->state == EParticipantState::Invalid) return; - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::removeParticipant: " << pp->address.getParticipantId() << "/" << pp->address.getParticipantName() << - ", state " << EnumToString(pp->state)); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::removeParticipant: {}/{}, state {}", + m_participantAddress.getParticipantName(), pp->address.getParticipantId(), pp->address.getParticipantName(), EnumToString(pp->state)); if (pp->state == EParticipantState::Established && pp->type != EParticipantType::PureDaemon) { @@ -467,12 +465,12 @@ namespace ramses::internal if (reconnectWithBackoff) { const std::chrono::milliseconds backoffTime{2000}; - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::removeParticipant: will delay reconnect by " << backoffTime.count() << "ms"); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::removeParticipant: will delay reconnect by {}ms", m_participantAddress.getParticipantName(), backoffTime.count()); pp->connectTimer.expires_after(backoffTime); pp->connectTimer.async_wait([this, pp](asio::error_code ee) { if (ee) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::removeParticipant: Backoff timer got canceled."); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::removeParticipant: Backoff timer got canceled.", m_participantAddress.getParticipantName()); } else { @@ -517,9 +515,8 @@ namespace ramses::internal if (!m_actAsDaemon && (otherIsDaemon || (!address.getParticipantId().isInvalid() && shouldConnectbasedOnGuid))) { - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::addNewParticipantByAddress: attemp new connection to participant " - << address.getParticipantId() << " / " << address.getParticipantName() - << " based on: otherIsDaemon " << otherIsDaemon << ", guid valid " << !address.getParticipantId().isInvalid() << " , guid comparison " << (shouldConnectbasedOnGuid ? "will connect" : "wait for connection")); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::addNewParticipantByAddress: attempt new connection to participant {} / {} based on: otherIsDaemon {}, guid valid {}, guid comparison {}", + m_participantAddress.getParticipantName(), address.getParticipantId(), address.getParticipantName(), otherIsDaemon, !address.getParticipantId().isInvalid(), shouldConnectbasedOnGuid ? "will connect" : "wait for connection"); auto pp = std::make_shared(address, m_runState->m_io, otherIsDaemon ? EParticipantType::Daemon : EParticipantType::Client, EParticipantState::Connecting); m_connectingParticipants.put(pp); @@ -527,9 +524,8 @@ namespace ramses::internal } else { - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::addNewParticipantByAddress: will wait for connection from participant " - << address.getParticipantId() << " / " << address.getParticipantName() - << " based on: otherIsDaemon " << otherIsDaemon << ", guid valid " << !address.getParticipantId().isInvalid() << " , guid comparison " << (shouldConnectbasedOnGuid ? "will connect" : "wait for connection")); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::addNewParticipantByAddress: will wait for connection from participant {} / {} based on: otherIsDaemon {}, guid valid {}, guid comparison {}", + m_participantAddress.getParticipantName(), address.getParticipantId(), address.getParticipantName(), otherIsDaemon, !address.getParticipantId().isInvalid(), shouldConnectbasedOnGuid ? "will connect" : "wait for connection"); } } @@ -538,7 +534,7 @@ namespace ramses::internal // expect framework lock to be held if (!m_runState) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::postMessageForSending: called without being connected"); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::postMessageForSending: called without being connected", m_participantAddress.getParticipantName()); return false; } @@ -569,8 +565,8 @@ namespace ramses::internal ParticipantPtr pp; if (m_establishedParticipants.get(msg.to.front(), pp) != EStatus::Ok) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::postMessageForSending: post message " << msg.messageType << - " to not (fully) connected participant " << msg.to.front()); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::postMessageForSending: post message {} to not (fully) connected participant {}", + m_participantAddress.getParticipantName(), msg.messageType, msg.to.front()); return; } assert(pp); @@ -594,8 +590,8 @@ namespace ramses::internal if (m_protocolVersion != recvProtocolVersion) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleReceivedMessage: Invalid protocol version received (expected " - << m_protocolVersion << ", got " << recvProtocolVersion << "). Drop connection"); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleReceivedMessage: Invalid protocol version received (expected {}, got {}). Drop connection", + m_participantAddress.getParticipantName(), m_protocolVersion, recvProtocolVersion); removeParticipant(pp, true); return; } @@ -604,8 +600,7 @@ namespace ramses::internal stream >> messageTypeTmp; auto messageType = static_cast(messageTypeTmp); - LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleReceivedMessage: From " << - pp->address.getParticipantId() << ", type " << messageType); + LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleReceivedMessage: From {}, type {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId(), messageType); switch (messageType) { @@ -640,14 +635,14 @@ namespace ramses::internal handleRendererEvent(pp, stream); break; default: - LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleReceivedMessage: Invalid messagetype " << messageType << " From " << pp->address.getParticipantId()); + LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleReceivedMessage: Invalid messagetype {} From {}", m_participantAddress.getParticipantName(), messageType, pp->address.getParticipantId()); removeParticipant(pp); } } void TCPConnectionSystem::sendConnectionDescriptionOnNewConnection(const ParticipantPtr& pp) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendConnectionDescriptionOnNewConnection: " << pp->address.getParticipantId()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendConnectionDescriptionOnNewConnection: {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId()); OutMessage msg(std::vector(), EMessageId::ConnectionDescriptionMessage); msg.stream << m_participantAddress.getParticipantId() @@ -662,13 +657,13 @@ namespace ramses::internal { if (pp->state == EParticipantState::Established) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleConnectionDescriptionMessage: Duplicate connection description while established from " << pp->address.getParticipantId()); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleConnectionDescriptionMessage: Duplicate connection description while established from {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId()); return; } if (pp->state != EParticipantState::WaitingForHello) { - LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleConnectionDescriptionMessage: Unexpected connection description from " << pp->address.getParticipantId() << - " in state " << EnumToString(pp->state)); + LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleConnectionDescriptionMessage: Unexpected connection description from {} in state {}", + m_participantAddress.getParticipantName(), pp->address.getParticipantId(), EnumToString(pp->state)); removeParticipant(pp, true); return; } @@ -688,8 +683,8 @@ namespace ramses::internal pp->address = NetworkParticipantAddress(guid, name, ip, port); assert(!guid.isInvalid()); - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleConnectionDescriptionMessage: Hello from " << - guid << "/" << name << " type " << EnumToString(participantType) << " at " << ip << ":" << port << ". Established now"); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleConnectionDescriptionMessage: Hello from {}/{} type {} at {}:{}. Established now", + m_participantAddress.getParticipantName(), guid, name, EnumToString(participantType), ip, port); pp->type = participantType; pp->state = EParticipantState::Established; @@ -707,8 +702,8 @@ namespace ramses::internal { if (m_participantType == EParticipantType::Daemon || m_participantType == EParticipantType::PureDaemon) { - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendConnectorAddressExchangeMessagesForNewParticipant: Send address exchange for " << - newPp->address.getParticipantId() << "/" << newPp->address.getParticipantName()); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendConnectorAddressExchangeMessagesForNewParticipant: Send address exchange for {}/{}", + m_participantAddress.getParticipantName(), newPp->address.getParticipantId(), newPp->address.getParticipantName()); // send all established non-daemon participants to new one { @@ -719,8 +714,8 @@ namespace ramses::internal ++relevantParticipants; } - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendConnectorAddressExchangeMessagesForNewParticipant: Send " << relevantParticipants << " entries to " << - newPp->address.getParticipantId() << "/" << newPp->address.getParticipantName()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendConnectorAddressExchangeMessagesForNewParticipant: Send {} entries to {}/{}", + m_participantAddress.getParticipantName(), relevantParticipants, newPp->address.getParticipantId(), newPp->address.getParticipantName()); OutMessage msg(newPp->address.getParticipantId(), EMessageId::ConnectorAddressExchange); msg.stream << relevantParticipants; @@ -744,9 +739,8 @@ namespace ramses::internal { if (newPp != p.value) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendConnectorAddressExchangeMessagesForNewParticipant: Send " - << newPp->address.getParticipantId() << "/" << newPp->address.getParticipantName() << " to " - << p.value->address.getParticipantId() << "/" << p.value->address.getParticipantName()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendConnectorAddressExchangeMessagesForNewParticipant: Send {}/{} to {}/{}", + m_participantAddress.getParticipantName(), newPp->address.getParticipantId(), newPp->address.getParticipantName(), p.value->address.getParticipantId(), p.value->address.getParticipantName()); OutMessage msg(p.value->address.getParticipantId(), EMessageId::ConnectorAddressExchange); const NetworkParticipantAddress& addr = newPp->address; @@ -767,7 +761,7 @@ namespace ramses::internal uint32_t numEntries = 0; stream >> numEntries; - LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleConnectorAddressExchange: from " << pp->address.getParticipantId() << ", numEntries " << numEntries); + LOG_INFO(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleConnectorAddressExchange: from {}, numEntries {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId(), numEntries); for (uint32_t i = 0; i < numEntries; ++i) { @@ -783,8 +777,8 @@ namespace ramses::internal >> participantType; NetworkParticipantAddress addr(guid, name, ip, port); - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleConnectorAddressExchange: from " << pp->address.getParticipantId() << ". " << - guid << "/" << name << " at " << ip << ":" << port << ", type " << EnumToString(participantType)); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleConnectorAddressExchange: from {}. {}/{} at {}:{}, type {}", + m_participantAddress.getParticipantName(), pp->address.getParticipantId(), guid, name, ip, port, EnumToString(participantType)); ParticipantPtr* newPpPtr = m_establishedParticipants.get(addr.getParticipantId()); if (newPpPtr) @@ -793,18 +787,18 @@ namespace ramses::internal const ParticipantPtr& newPp = *newPpPtr; if (newPp->address != addr) { - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleConnectorAddressExchange: Received mismatching participant info for " - << addr.getParticipantId() << ". Expect problems"); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleConnectorAddressExchange: Received mismatching participant info for {}. Expect problems", + m_participantAddress.getParticipantName(), addr.getParticipantId()); } else { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleConnectorAddressExchange: Same information for existing participant " - << addr.getParticipantId()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleConnectorAddressExchange: Same information for existing participant {}", + m_participantAddress.getParticipantName(), addr.getParticipantId()); } } else if (guid == m_participantAddress.getParticipantId()) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleConnectorAddressExchange: Got info for self"); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleConnectorAddressExchange: Got info for self", m_participantAddress.getParticipantName()); // TODO: check if correct } else @@ -833,7 +827,7 @@ namespace ramses::internal // --- user message handling --- bool TCPConnectionSystem::sendSubscribeScene(const Guid& to, const SceneId& sceneId) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendSubscribeScene: to " << to << ", sceneId " << sceneId); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendSubscribeScene: to {}, sceneId {}", m_participantAddress.getParticipantName(), to, sceneId); OutMessage msg(to, EMessageId::SubscribeScene); msg.stream << sceneId.getValue(); return postMessageForSending(std::move(msg)); @@ -846,7 +840,7 @@ namespace ramses::internal SceneId sceneId; stream >> sceneId.getReference(); - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleSubscribeScene: from " << pp->address.getParticipantId() << ", sceneId " << sceneId); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleSubscribeScene: from {}, sceneId {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId(), sceneId); PlatformGuard guard(m_frameworkLock); m_sceneProviderHandler->handleSubscribeScene(sceneId, pp->address.getParticipantId()); } @@ -855,7 +849,7 @@ namespace ramses::internal // -- bool TCPConnectionSystem::sendUnsubscribeScene(const Guid& to, const SceneId& sceneId) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendUnsubscribeScene: to " << to << ", sceneId " << sceneId); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendUnsubscribeScene: to {}, sceneId {}", m_participantAddress.getParticipantName(), to, sceneId); OutMessage msg(to, EMessageId::UnsubscribeScene); msg.stream << sceneId.getValue(); return postMessageForSending(std::move(msg)); @@ -868,7 +862,7 @@ namespace ramses::internal SceneId sceneId; stream >> sceneId.getReference(); - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleUnsubscribeScene: from " << pp->address.getParticipantId() << ", sceneId " << sceneId); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleUnsubscribeScene: from {}, sceneId {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId(), sceneId); PlatformGuard guard(m_frameworkLock); m_sceneProviderHandler->handleUnsubscribeScene(sceneId, pp->address.getParticipantId()); } @@ -877,7 +871,7 @@ namespace ramses::internal // -- bool TCPConnectionSystem::sendInitializeScene(const Guid& to, const SceneId& sceneId) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendInitializeScene: to " << to << ", sceneId " << sceneId); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendInitializeScene: to {}, sceneId {}", m_participantAddress.getParticipantName(), to, sceneId); OutMessage msg(to, EMessageId::CreateScene); msg.stream << sceneId.getValue(); return postMessageForSending(std::move(msg)); @@ -890,8 +884,7 @@ namespace ramses::internal SceneId sceneId; stream >> sceneId.getReference(); - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleCreateScene: from " << pp->address.getParticipantId() << - ", sceneId " << sceneId); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleCreateScene: from {}, sceneId {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId(), sceneId); PlatformGuard guard(m_frameworkLock); m_sceneRendererHandler->handleInitializeScene(sceneId, pp->address.getParticipantId()); } @@ -900,7 +893,7 @@ namespace ramses::internal // -- bool TCPConnectionSystem::sendSceneUpdate(const Guid& to, const SceneId& sceneId, const ISceneUpdateSerializer& serializer) { - LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendSceneActionList: to " << to); + LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendSceneActionList: to {}", m_participantAddress.getParticipantName(), to); static_assert(SceneActionDataSize < 1000000, "SceneActionDataSize too big"); @@ -930,7 +923,7 @@ namespace ramses::internal std::vector data(dataSize); stream.read(data.data(), dataSize); - LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleSceneActionList: from " << pp->address.getParticipantId()); + LOG_TRACE(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleSceneActionList: from {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId()); PlatformGuard guard(m_frameworkLock); m_sceneRendererHandler->handleSceneUpdate(sceneId, data, pp->address.getParticipantId()); @@ -1065,10 +1058,10 @@ namespace ramses::internal // -- bool TCPConnectionSystem::sendRendererEvent(const Guid& to, const SceneId& sceneId, const std::vector& data) { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendRendererEvent: to " << to << ", size " << data.size()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendRendererEvent: to {}, size {}", m_participantAddress.getParticipantName(), to, data.size()); if (data.size() > 32000) // really 32768 { - LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::sendRendererEvent: to " << to << " failed because size too large " << data.size()); + LOG_ERROR(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::sendRendererEvent: to {} failed because size too large {}", m_participantAddress.getParticipantName(), to, data.size()); return false; } OutMessage msg(to, EMessageId::RendererEvent); @@ -1092,7 +1085,7 @@ namespace ramses::internal stream.read(data.data(), dataSize); - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << ")::handleRendererEvent: from " << pp->address.getParticipantId() << ", size " << dataSize); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem({})::handleRendererEvent: from {}, size {}", m_participantAddress.getParticipantName(), pp->address.getParticipantId(), dataSize); PlatformGuard guard(m_frameworkLock); m_sceneProviderHandler->handleRendererEvent(sceneId, data, pp->address.getParticipantId()); } @@ -1176,7 +1169,7 @@ namespace ramses::internal } else { - LOG_INFO(CONTEXT_PERIODIC, "TCPConnectionSystem(" << m_participantAddress.getParticipantName() << "): Not connected"); + LOG_INFO(CONTEXT_PERIODIC, "TCPConnectionSystem({}): Not connected", m_participantAddress.getParticipantName()); } } @@ -1214,17 +1207,17 @@ namespace ramses::internal TCPConnectionSystem::Participant::~Participant() { - LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem::~Participant(" << address.getParticipantName() << ")"); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TCPConnectionSystem::~Participant({})", address.getParticipantName()); if (socket.is_open()) { asio::error_code ec; socket.shutdown(asio::ip::tcp::socket::shutdown_both, ec); if (ec) - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem::~Participant(" << address.getParticipantName() << "): shutdown failed: " << ec.message().c_str()); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem::~Participant({}): shutdown failed: {}", address.getParticipantName(), ec.message().c_str()); socket.close(ec); if (ec) - LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem::~Participant(" << address.getParticipantName() << "): close failed: " << ec.message().c_str()); + LOG_WARN(CONTEXT_COMMUNICATION, "TCPConnectionSystem::~Participant({}): close failed: {}", address.getParticipantName(), ec.message().c_str()); } } diff --git a/src/framework/internal/Communication/TransportTCP/TcpDiscoveryDaemon.cpp b/src/framework/internal/Communication/TransportTCP/TcpDiscoveryDaemon.cpp index f84fceca0..573250569 100644 --- a/src/framework/internal/Communication/TransportTCP/TcpDiscoveryDaemon.cpp +++ b/src/framework/internal/Communication/TransportTCP/TcpDiscoveryDaemon.cpp @@ -23,7 +23,7 @@ namespace ramses::internal const bool isDaemon = true; const NetworkParticipantAddress participantNetworkAddress(TCPConnectionSystem::GetDaemonId(), "SM", config.m_tcpConfig.getIPAddress(), config.m_tcpConfig.getPort(isDaemon)); - LOG_DEBUG(CONTEXT_COMMUNICATION, "TcpDiscoveryDaemon::TcpDiscoveryDaemon: My Address: " << participantNetworkAddress.getIp() << ":" << participantNetworkAddress.getPort()); + LOG_DEBUG(CONTEXT_COMMUNICATION, "TcpDiscoveryDaemon::TcpDiscoveryDaemon: My Address: {}:{}", participantNetworkAddress.getIp(), participantNetworkAddress.getPort()); const NetworkParticipantAddress daemonNetworkAddress; m_communicationSystem = std::make_unique(participantNetworkAddress, config.getProtocolVersion(), diff --git a/src/framework/internal/Components/ClientSceneLogicBase.cpp b/src/framework/internal/Components/ClientSceneLogicBase.cpp index 452e473d6..df4d7edb5 100644 --- a/src/framework/internal/Components/ClientSceneLogicBase.cpp +++ b/src/framework/internal/Components/ClientSceneLogicBase.cpp @@ -70,11 +70,11 @@ namespace ramses::internal { if (contains_c(m_subscribersActive, newSubscriber) || contains_c(m_subscribersWaitingForScene, newSubscriber)) { - LOG_WARN(CONTEXT_CLIENT, "ClientSceneLogic::addSubscriber: already has " << newSubscriber << " for scene " << m_sceneId); + LOG_WARN(CONTEXT_CLIENT, "ClientSceneLogic::addSubscriber: already has {} for scene {}", newSubscriber, m_sceneId); return; } - LOG_INFO(CONTEXT_CLIENT, "ClientSceneLogic::addSubscriber: add " << newSubscriber << " for scene " << m_sceneId << ", flushCounter " << m_flushCounter); + LOG_INFO(CONTEXT_CLIENT, "ClientSceneLogic::addSubscriber: add {} for scene {}, flushCounter {}", newSubscriber, m_sceneId, m_flushCounter); m_subscribersWaitingForScene.push_back(newSubscriber); postAddSubscriber(); } @@ -85,7 +85,7 @@ namespace ramses::internal if (it != m_subscribersActive.end()) { m_subscribersActive.erase(it); - LOG_INFO(CONTEXT_CLIENT, "ClientSceneLogic::removeSubscriber: remove active subscriber " << subscriber << " from scene " << m_sceneId << ", numRemaining " << m_subscribersActive.size()); + LOG_INFO(CONTEXT_CLIENT, "ClientSceneLogic::removeSubscriber: remove active subscriber {} from scene {}, numRemaining {}", subscriber, m_sceneId, m_subscribersActive.size()); } else { @@ -93,7 +93,7 @@ namespace ramses::internal if (waitingForSceneIter != m_subscribersWaitingForScene.end()) { m_subscribersWaitingForScene.erase(waitingForSceneIter); - LOG_INFO(CONTEXT_CLIENT, "ClientSceneLogic::removeSubscriber: remove waiting subscriber " << subscriber << " from scene " << m_sceneId << ", numRemaining " << m_subscribersWaitingForScene.size()); + LOG_INFO(CONTEXT_CLIENT, "ClientSceneLogic::removeSubscriber: remove waiting subscriber {} from scene {}, numRemaining {}", subscriber, m_sceneId, m_subscribersWaitingForScene.size()); } } } @@ -109,7 +109,7 @@ namespace ramses::internal { if (m_subscribersWaitingForScene.empty()) { - LOG_DEBUG(CONTEXT_CLIENT, "ClientSceneLogicBase::sendSceneToWaitingSubscribers: No subscribers waiting for scene " << m_sceneId); + LOG_DEBUG(CONTEXT_CLIENT, "ClientSceneLogicBase::sendSceneToWaitingSubscribers: No subscribers waiting for scene {}", m_sceneId); return; } @@ -128,10 +128,10 @@ namespace ramses::internal sceneUpdate.resources = m_resourceComponent.resolveResources(m_resourceChangesSinceLastFlush.m_resourcesAdded); assert(sceneUpdate.resources.size() == m_resourceChangesSinceLastFlush.m_resourcesAdded.size()); sceneUpdate.flushInfos = { m_flushCounter, versionTag, scene.getSceneSizeInformation(), m_resourceChangesSinceLastFlush, {}, flushTimeInfo, true, true }; - LOG_INFO(CONTEXT_CLIENT, "Sending scene " << scene.getSceneId() << " to " << m_subscribersWaitingForScene.size() << " subscribers, " << - sceneUpdate.actions.numberOfActions() << " scene actions (" << sceneUpdate.actions.collectionData().size() << " bytes)" << - m_resourceChangesSinceLastFlush.m_resourcesAdded.size() << " client resources, " << - m_resourceChangesSinceLastFlush.m_sceneResourceActions.size() << " scene resource actions (" << sceneResourcesSize << " bytes in total used by scene resources)"); + LOG_INFO(CONTEXT_CLIENT, "Sending scene {} to {} subscribers, {} scene actions ({} bytes), {} client resources, {} scene resource actions ({} bytes in total used by scene resources)", + scene.getSceneId(), m_subscribersWaitingForScene.size(), sceneUpdate.actions.numberOfActions(), + sceneUpdate.actions.collectionData().size(), m_resourceChangesSinceLastFlush.m_resourcesAdded.size(), + m_resourceChangesSinceLastFlush.m_sceneResourceActions.size(), sceneResourcesSize); assert(m_scenePublicationMode.has_value()); for(const auto& subscriber : m_subscribersWaitingForScene) diff --git a/src/framework/internal/Components/ClientSceneLogicDirect.cpp b/src/framework/internal/Components/ClientSceneLogicDirect.cpp index ab77125e4..8f92ee2a1 100644 --- a/src/framework/internal/Components/ClientSceneLogicDirect.cpp +++ b/src/framework/internal/Components/ClientSceneLogicDirect.cpp @@ -35,7 +35,7 @@ namespace ramses::internal const auto resourceChangeState = verifyAndGetResourceChanges(sceneUpdate, hasNewActions); if (resourceChangeState == ResourceChangeState::MissingResource) { - LOG_ERROR_P(CONTEXT_CLIENT, "ClientSceneLogicDirect::flushSceneActions: At least one resource can't be loaded, " + LOG_ERROR(CONTEXT_CLIENT, "ClientSceneLogicDirect::flushSceneActions: At least one resource can't be loaded, " "Scene {} can't be rendered. Consult log and run Scene::validate() for more information", m_scene.getSceneId()); return false; } @@ -89,7 +89,7 @@ namespace ramses::internal { if (skipSceneActionSend) { - LOG_DEBUG(CONTEXT_CLIENT, "ClientSceneLogicDirect::flushSceneActions: skip flush for sceneId " << m_sceneId << ", cnt " << m_flushCounter << " because empty"); + LOG_DEBUG(CONTEXT_CLIENT, "ClientSceneLogicDirect::flushSceneActions: skip flush for sceneId {}, cnt {} because empty", m_sceneId, m_flushCounter); m_scene.getStatisticCollection().statSceneActionsSentSkipped.incCounter(1); } else diff --git a/src/framework/internal/Components/ClientSceneLogicShadowCopy.cpp b/src/framework/internal/Components/ClientSceneLogicShadowCopy.cpp index a3cfb1d2e..84372c667 100644 --- a/src/framework/internal/Components/ClientSceneLogicShadowCopy.cpp +++ b/src/framework/internal/Components/ClientSceneLogicShadowCopy.cpp @@ -40,7 +40,7 @@ namespace ramses::internal const auto resourceChangeState = verifyAndGetResourceChanges(sceneUpdate, hasNewActions); if (resourceChangeState == ResourceChangeState::MissingResource) { - LOG_ERROR_P(CONTEXT_CLIENT, "ClientSceneLogicShadowCopy::flushSceneActions: At least one resource can't be loaded, " + LOG_ERROR(CONTEXT_CLIENT, "ClientSceneLogicShadowCopy::flushSceneActions: At least one resource can't be loaded, " "Scene {} can't be rendered. Consult log and run Scene::validate() for more information", m_scene.getSceneId()); return false; } @@ -93,7 +93,7 @@ namespace ramses::internal { if (skipSceneActionSend) { - LOG_DEBUG(CONTEXT_CLIENT, "ClientSceneLogicShadowCopy::flushSceneActions: skip flush for sceneId " << m_sceneId << ", cnt " << m_flushCounter << " because empty"); + LOG_DEBUG(CONTEXT_CLIENT, "ClientSceneLogicShadowCopy::flushSceneActions: skip flush for sceneId {}, cnt {} because empty", m_sceneId, m_flushCounter); m_scene.getStatisticCollection().statSceneActionsSentSkipped.incCounter(1); } else @@ -127,8 +127,8 @@ namespace ramses::internal { if (m_flushCounter == 0u || !isPublished()) { - LOG_DEBUG(CONTEXT_CLIENT, "ClientSceneLogic::sendShadowCopySceneToWaitingSubscribers: delay sending of scene " << m_sceneId << " (numWaiting " << - m_subscribersWaitingForScene.size() << ", flushCnt " << m_flushCounter << ", published " << isPublished() << ")"); + LOG_DEBUG(CONTEXT_CLIENT, "ClientSceneLogic::sendShadowCopySceneToWaitingSubscribers: delay sending of scene {} (numWaiting {}, flushCnt {}, published {})", + m_sceneId, m_subscribersWaitingForScene.size(), m_flushCounter, isPublished()); return; } diff --git a/src/framework/internal/Components/ResourceComponent.cpp b/src/framework/internal/Components/ResourceComponent.cpp index 67e31f26b..a4778ebd6 100644 --- a/src/framework/internal/Components/ResourceComponent.cpp +++ b/src/framework/internal/Components/ResourceComponent.cpp @@ -70,7 +70,7 @@ namespace ramses::internal const FileContentsMap* content = m_resourceFiles.getContentsOfResourceFile(handle); if (!content) { - LOG_WARN(CONTEXT_FRAMEWORK, "ResourceComponent::loadResourceFromFile: handle " << handle << " unknown, can't force load"); + LOG_WARN(CONTEXT_FRAMEWORK, "ResourceComponent::loadResourceFromFile: handle {} unknown, can't force load", handle); return; } @@ -116,7 +116,7 @@ namespace ramses::internal { size_t currentPos = 0; resourceStream->getPos(currentPos); - LOG_ERROR_P(CONTEXT_FRAMEWORK, "ResourceComponent::loadResource: RetrieveResourceFromStream CRITICALLY failed with a std::exception ('{}')" + LOG_ERROR(CONTEXT_FRAMEWORK, "ResourceComponent::loadResource: RetrieveResourceFromStream CRITICALLY failed with a std::exception ('{}')" " for type {}, hash {}, fileHandle {}, offset {}, size {}, streamState {}, current streamPos {}. No resource created, expect further errors.", e.what(), entry.resourceInfo.type, entry.resourceInfo.hash, fileHandle, entry.offsetInBytes, entry.sizeInBytes, resourceStream->getState(), currentPos); return {}; @@ -125,7 +125,7 @@ namespace ramses::internal { size_t currentPos = 0; resourceStream->getPos(currentPos); - LOG_ERROR_P(CONTEXT_FRAMEWORK, "ResourceComponent::loadResource: RetrieveResourceFromStream CRITICALLY failed and did not return a resource" + LOG_ERROR(CONTEXT_FRAMEWORK, "ResourceComponent::loadResource: RetrieveResourceFromStream CRITICALLY failed and did not return a resource" " for type {}, hash {}, fileHandle {}, offset {}, size {}, streamState {}, current streamPos {}. Expect further errors.", entry.resourceInfo.type, entry.resourceInfo.hash, fileHandle, entry.offsetInBytes, entry.sizeInBytes, resourceStream->getState(), currentPos); return {}; @@ -164,7 +164,7 @@ namespace ramses::internal } if (!failed.empty()) - LOG_ERROR_P(CONTEXT_FRAMEWORK, "ResourceComponent::resolveResources: failed to load resources: {}", failed); + LOG_ERROR(CONTEXT_FRAMEWORK, "ResourceComponent::resolveResources: failed to load resources: {}", failed); return result; } diff --git a/src/framework/internal/Components/ResourcePersistation.cpp b/src/framework/internal/Components/ResourcePersistation.cpp index dc024f7d7..d9df3e8bc 100644 --- a/src/framework/internal/Components/ResourcePersistation.cpp +++ b/src/framework/internal/Components/ResourcePersistation.cpp @@ -93,12 +93,12 @@ namespace ramses::internal std::unique_ptr ResourcePersistation::RetrieveResourceFromStream(IInputStream& inStream, const ResourceFileEntry& fileEntry) { - LOG_DEBUG_P(CONTEXT_FRAMEWORK, "ResourcePersistation::RetrieveResourceFromStream: Hash {}, Size {}, Offset {}", + LOG_DEBUG(CONTEXT_FRAMEWORK, "ResourcePersistation::RetrieveResourceFromStream: Hash {}, Size {}, Offset {}", fileEntry.resourceInfo.hash, fileEntry.sizeInBytes, fileEntry.offsetInBytes); if (inStream.seek(fileEntry.offsetInBytes, IInputStream::Seek::FromBeginning) != EStatus::Ok) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "ResourcePersistation::RetrieveResourceFromStream: seek failed for resource {}", fileEntry.resourceInfo.hash); + LOG_ERROR(CONTEXT_FRAMEWORK, "ResourcePersistation::RetrieveResourceFromStream: seek failed for resource {}", fileEntry.resourceInfo.hash); return {}; } @@ -108,7 +108,7 @@ namespace ramses::internal if (inStream.getState() != EStatus::Ok) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "ResourcePersistation::RetrieveResourceFromStream: resource deserialization failed for {}", fileEntry.resourceInfo.hash); + LOG_ERROR(CONTEXT_FRAMEWORK, "ResourcePersistation::RetrieveResourceFromStream: resource deserialization failed for {}", fileEntry.resourceInfo.hash); return {}; } @@ -116,7 +116,7 @@ namespace ramses::internal const EStatus posStatus = inStream.getPos(currentPosAfterRead); if (posStatus != EStatus::Ok || currentPosAfterRead - fileEntry.offsetInBytes != fileEntry.sizeInBytes) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "ResourcePersistation::RetrieveResourceFromStream: read position fail for {}, state {} (resOffset {}, resSize {}, filePos{})", + LOG_ERROR(CONTEXT_FRAMEWORK, "ResourcePersistation::RetrieveResourceFromStream: read position fail for {}, state {} (resOffset {}, resSize {}, filePos{})", fileEntry.resourceInfo.hash, posStatus, fileEntry.offsetInBytes, fileEntry.sizeInBytes, currentPosAfterRead); return {}; } diff --git a/src/framework/internal/Components/ResourceSerializationHelper.cpp b/src/framework/internal/Components/ResourceSerializationHelper.cpp index f022b1321..ec2d817ac 100644 --- a/src/framework/internal/Components/ResourceSerializationHelper.cpp +++ b/src/framework/internal/Components/ResourceSerializationHelper.cpp @@ -72,7 +72,7 @@ namespace ramses::internal resource = EffectResource::CreateResourceFromMetadataStream(input, name); break; default: - LOG_ERROR_P(CONTEXT_FRAMEWORK, "ResourceSerializationHelper::ResourceFromMetadataStream: Failed for unknown resource type {}", resourceType); + LOG_ERROR(CONTEXT_FRAMEWORK, "ResourceSerializationHelper::ResourceFromMetadataStream: Failed for unknown resource type {}", resourceType); } DeserializedResourceHeader result; diff --git a/src/framework/internal/Components/ResourceStorage.cpp b/src/framework/internal/Components/ResourceStorage.cpp index 94453e703..dbad4ee65 100644 --- a/src/framework/internal/Components/ResourceStorage.cpp +++ b/src/framework/internal/Components/ResourceStorage.cpp @@ -143,7 +143,7 @@ namespace ramses::internal ResourceDeleterCallingCallback deleter(*this); const ResourceContentHash hash = resource.getHash(); - LOG_TRACE(CONTEXT_FRAMEWORK, "Adding resource:" << hash); + LOG_TRACE(CONTEXT_FRAMEWORK, "Adding resource:{}", hash); const IResource* resourceToReturn = nullptr; m_resourceMapLock.lock(); RefCntResource* entry = m_resourceMap.get(hash); @@ -192,7 +192,7 @@ namespace ramses::internal void ResourceStorage::resourceHashUsageZero(const ResourceContentHash& hash) { - LOG_TRACE(CONTEXT_FRAMEWORK, "ResourceStorage::resourceHashUsageZero resource:" << hash); + LOG_TRACE(CONTEXT_FRAMEWORK, "ResourceStorage::resourceHashUsageZero resource:{}", hash); m_resourceMapLock.lock(); RefCntResource* entry = m_resourceMap.get(hash); assert(entry && entry->hashUsages > 0); @@ -204,7 +204,7 @@ namespace ramses::internal void ResourceStorage::managedResourceDeleted(const IResource& resourceToRemove) { const ResourceContentHash hashToRemove = resourceToRemove.getHash(); - LOG_TRACE(CONTEXT_FRAMEWORK, "ResourceStorage::managedResourceDeleted unreference resource:" << hashToRemove); + LOG_TRACE(CONTEXT_FRAMEWORK, "ResourceStorage::managedResourceDeleted unreference resource:{}", hashToRemove); m_resourceMapLock.lock(); RefCntResource* entry = m_resourceMap.get(hashToRemove); assert(entry && entry->refCount > 0); @@ -234,7 +234,7 @@ namespace ramses::internal if (entry.hashUsages == 0) { - LOG_TRACE(CONTEXT_FRAMEWORK, "ResourceStorage::checkForDeletion hashusages is zero, really delete:" << hash); + LOG_TRACE(CONTEXT_FRAMEWORK, "ResourceStorage::checkForDeletion hashusages is zero, really delete:{}", hash); ResourceContentHash* hashObject = entry.hash; m_resourceMap.remove(hash); delete hashObject; diff --git a/src/framework/internal/Components/ResourceTableOfContents.cpp b/src/framework/internal/Components/ResourceTableOfContents.cpp index d161f0f9c..7012783f0 100644 --- a/src/framework/internal/Components/ResourceTableOfContents.cpp +++ b/src/framework/internal/Components/ResourceTableOfContents.cpp @@ -93,7 +93,7 @@ namespace ramses::internal const uint32_t resourceSizeToWarnAboutInBytes = 100 * 1024 * 1024; if (info.decompressedSize > resourceSizeToWarnAboutInBytes) { - LOG_WARN(CONTEXT_FRAMEWORK, "ResourceTableOfContents::readTOCPosAndTOCFromStream: Loading a resource that is larger than " << resourceSizeToWarnAboutInBytes << " bytes, hash: " << info.hash << " (" << info.decompressedSize << " bytes)"); + LOG_WARN(CONTEXT_FRAMEWORK, "ResourceTableOfContents::readTOCPosAndTOCFromStream: Loading a resource that is larger than {} bytes, hash: {} ({} bytes)", resourceSizeToWarnAboutInBytes, info.hash, info.decompressedSize); } } diff --git a/src/framework/internal/Components/SceneGraphComponent.cpp b/src/framework/internal/Components/SceneGraphComponent.cpp index 950f25c68..24622e8f0 100644 --- a/src/framework/internal/Components/SceneGraphComponent.cpp +++ b/src/framework/internal/Components/SceneGraphComponent.cpp @@ -92,12 +92,12 @@ namespace ramses::internal // TODO(tobias) remove mode, already given with publish void SceneGraphComponent::sendCreateScene(const Guid& to, const SceneId& sceneId, [[maybe_unused]] EScenePublicationMode mode) { - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::sendCreateScene: sceneId " << sceneId << ", to " << to); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::sendCreateScene: sceneId {}, to {}", sceneId, to); const SceneInfo* info = m_locallyPublishedScenes.get(sceneId); if (!info) { - LOG_ERROR(CONTEXT_FRAMEWORK, "SceneGraphComponent::sendCreateScene: scene not published, sceneId " << sceneId); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneGraphComponent::sendCreateScene: scene not published, sceneId {}", sceneId); // return; // TODO: lots of tests must be fixed for this check } @@ -154,7 +154,7 @@ namespace ramses::internal void SceneGraphComponent::sendPublishScene(SceneId sceneId, EScenePublicationMode mode, std::string_view name) { - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::publishScene: publishing scene: " << sceneId << " mode: " << EnumToString(mode)); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::publishScene: publishing scene: {} mode: {}", sceneId, EnumToString(mode)); SceneInfo info(sceneId, name, mode); @@ -169,7 +169,7 @@ namespace ramses::internal void SceneGraphComponent::sendUnpublishScene(SceneId sceneId, EScenePublicationMode mode) { - LOG_DEBUG(CONTEXT_FRAMEWORK, "SceneGraphComponent::unpublishScene: unpublishing scene: " << sceneId << " mode: " << EnumToString(mode)); + LOG_DEBUG(CONTEXT_FRAMEWORK, "SceneGraphComponent::unpublishScene: unpublishing scene: {} mode: {}", sceneId, EnumToString(mode)); assert(m_locallyPublishedScenes.contains(sceneId)); const SceneInfo info = *m_locallyPublishedScenes.get(sceneId); @@ -186,12 +186,12 @@ namespace ramses::internal { if (m_myID == to) { - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::subscribeScene: subscribing to local scene " << sceneId); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::subscribeScene: subscribing to local scene {}", sceneId); handleSubscribeScene(sceneId, m_myID); } else { - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::subscribeScene: subscribing to scene " << sceneId << " from " << to); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::subscribeScene: subscribing to scene {} from {}", sceneId, to); m_communicationSystem.sendSubscribeScene(to, sceneId); } } @@ -258,7 +258,7 @@ namespace ramses::internal { if (p.value.publicationMode != EScenePublicationMode::LocalOnly) { - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::newParticipantHasConnected: publishing scene to new particpant: " << connnectedParticipant << " scene is: " << p.key << " mode: " << EnumToString(p.value.publicationMode) << " from: " << m_myID); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::newParticipantHasConnected: publishing scene to new participant: {} scene is: {} mode: {} from: {}", connnectedParticipant, p.key, EnumToString(p.value.publicationMode), m_myID); availableScenes.push_back(p.value); } } @@ -271,7 +271,7 @@ namespace ramses::internal void SceneGraphComponent::participantHasDisconnected(const Guid& disconnnectedParticipant) { - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::participantHasDisconnected: unsubscribing all scenes for particpant: " << disconnnectedParticipant); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::participantHasDisconnected: unsubscribing all scenes for participant: {}", disconnnectedParticipant); PlatformGuard guard(m_frameworkLock); for(const auto& publishedScene : m_locallyPublishedScenes) @@ -300,12 +300,12 @@ namespace ramses::internal ClientSceneLogicBase* sceneLogic = nullptr; if (enableLocalOnlyOptimization) { - LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleCreateScene: creating scene " << scene.getSceneId() << " (direct)"); + LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleCreateScene: creating scene {} (direct)", scene.getSceneId()); sceneLogic = new ClientSceneLogicDirect(*this, scene, m_resourceComponent, m_myID); } else { - LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleCreateScene: creating scene " << scene.getSceneId() << " (shadow copy)"); + LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleCreateScene: creating scene {} (shadow copy)", scene.getSceneId()); sceneLogic = new ClientSceneLogicShadowCopy(*this, scene, m_resourceComponent, m_myID); } m_sceneEventConsumers.put(sceneId, &eventConsumer); @@ -317,7 +317,7 @@ namespace ramses::internal assert(m_clientSceneLogicMap.contains(sceneId)); ClientSceneLogicBase& sceneLogic = **m_clientSceneLogicMap.get(sceneId); - LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handlePublishScene: " << sceneId << " in mode " << EnumToString(publicationMode)); + LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handlePublishScene: {} in mode {}", sceneId, EnumToString(publicationMode)); sceneLogic.publish(publicationMode); } @@ -326,7 +326,7 @@ namespace ramses::internal assert(m_clientSceneLogicMap.contains(sceneId)); ClientSceneLogicBase& sceneLogic = **m_clientSceneLogicMap.get(sceneId); - LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleUnpublishScene: unpublishing scene " << sceneId); + LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleUnpublishScene: unpublishing scene {}", sceneId); sceneLogic.unpublish(); } @@ -341,7 +341,7 @@ namespace ramses::internal void SceneGraphComponent::handleRemoveScene(SceneId sceneId) { - LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleRemoveScene: " << sceneId); + LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleRemoveScene: {}", sceneId); ClientSceneLogicBase* sceneLogic = *m_clientSceneLogicMap.get(sceneId); assert(sceneLogic != nullptr); m_clientSceneLogicMap.remove(sceneId); @@ -354,12 +354,12 @@ namespace ramses::internal ClientSceneLogicBase** sceneLogic = m_clientSceneLogicMap.get(sceneId); if (sceneLogic != nullptr) { - LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleSceneSubscription: received scene subscription for scene " << sceneId << " from " << consumerID); + LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleSceneSubscription: received scene subscription for scene {} from {}", sceneId, consumerID); (*sceneLogic)->addSubscriber(consumerID); } else { - LOG_WARN(CONTEXT_CLIENT, "SceneGraphComponent::handleSceneSubscription: received scene subscription for unknown scene " << sceneId << " from " << consumerID); + LOG_WARN(CONTEXT_CLIENT, "SceneGraphComponent::handleSceneSubscription: received scene subscription for unknown scene {} from {}", sceneId, consumerID); } } @@ -368,12 +368,12 @@ namespace ramses::internal ClientSceneLogicBase** sceneLogic = m_clientSceneLogicMap.get(sceneId); if (sceneLogic != nullptr) { - LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleSceneUnsubscription: received scene unsubscription for scene " << sceneId << " from " << consumerID); + LOG_INFO(CONTEXT_CLIENT, "SceneGraphComponent::handleSceneUnsubscription: received scene unsubscription for scene {} from {}", sceneId, consumerID); (*sceneLogic)->removeSubscriber(consumerID); } else { - LOG_WARN(CONTEXT_CLIENT, "SceneGraphComponent::handleSceneUnsubscription: received scene unsubscription for unknown scene " << sceneId << " from " << consumerID); + LOG_WARN(CONTEXT_CLIENT, "SceneGraphComponent::handleSceneUnsubscription: received scene unsubscription for unknown scene {} from {}", sceneId, consumerID); } } @@ -455,7 +455,7 @@ namespace ramses::internal break; } default: - LOG_ERROR(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleRendererEvent: unknown event type: " << eventType); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleRendererEvent: unknown event type: {}", eventType); break; } } @@ -470,8 +470,8 @@ namespace ramses::internal else { LOG_WARN(CONTEXT_CLIENT, - "SceneGraphComponent::forwardToSceneProviderEventConsumer: trying to send event to local client, but no event handler registered for sceneId " - << event.masterSceneId); + "SceneGraphComponent::forwardToSceneProviderEventConsumer: trying to send event to local client, but no event handler registered for sceneId {}", + event.masterSceneId); } } @@ -485,8 +485,8 @@ namespace ramses::internal else { LOG_WARN(CONTEXT_CLIENT, - "SceneGraphComponent::forwardToSceneProviderEventConsumer: trying to send event to local client, but no event handler registered for sceneId " - << event.sceneid); + "SceneGraphComponent::forwardToSceneProviderEventConsumer: trying to send event to local client, but no event handler registered for sceneId {}", + event.sceneid); } } @@ -494,22 +494,22 @@ namespace ramses::internal { if (!m_sceneRendererHandler) { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleInitializeScene: unexpected call because no renderer, scene " << sceneId << " from " << providerID); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleInitializeScene: unexpected call because no renderer, scene {} from {}", sceneId, providerID); return; } - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneActionList: sceneId: " << sceneId << ", by " << providerID); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneActionList: sceneId: {}, by {}", sceneId, providerID); auto it = m_remoteScenes.find(sceneId); if (it == m_remoteScenes.end()) { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneActionList: received for unknown scene, sceneId: " << sceneId << ", by " << providerID); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneActionList: received for unknown scene, sceneId: {}, by {}", sceneId, providerID); return; } if (it->second.provider != providerID) { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneActionList: received from unexpected provider, sceneId: " << sceneId << ", by " << - providerID << " but belongs to " << it->second.provider); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneActionList: received from unexpected provider, sceneId: {}, by {} but belongs to {}", + sceneId, providerID, it->second.provider); return; } @@ -524,31 +524,31 @@ namespace ramses::internal { if (!m_sceneRendererHandler) { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: unexpected call because no renderer, scene " << sceneId << " from " << providerID); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: unexpected call because no renderer, scene {} from {}", sceneId, providerID); return; } auto it = m_remoteScenes.find(sceneId); if (it == m_remoteScenes.end()) { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: received actions for unknown scene " << sceneId << " from " << providerID); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: received actions for unknown scene {} from {}", sceneId, providerID); return; } if (it->second.provider != providerID) { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: received from unexpected provider, sceneId: " << sceneId << ", by " << - providerID << " but belongs to " << it->second.provider); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: received from unexpected provider, sceneId: {}, by {} but belongs to {}", + sceneId, providerID, it->second.provider); return; } if (actionData.empty()) { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: data is empty, sceneId " << sceneId << " from " << providerID); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: data is empty, sceneId {} from {}", sceneId, providerID); return; } SceneUpdateStreamDeserializer* deserializer = it->second.sceneUpdateDeserializer.get(); if (!deserializer) { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: scene was not initialized before sending actions, sceneId " << sceneId << " from " << providerID); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: scene was not initialized before sending actions, sceneId {} from {}", sceneId, providerID); return; } @@ -558,7 +558,7 @@ namespace ramses::internal case SceneUpdateStreamDeserializer::ResultType::Empty: break; case SceneUpdateStreamDeserializer::ResultType::Failed: - LOG_ERROR(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: deserialization failed for scene: " << sceneId << " from provider:" << providerID); + LOG_ERROR(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneUpdate: deserialization failed for scene: {} from provider:{}", sceneId, providerID); // TODO(tobias) handle properly by unsub scene or disconnect participant break; case SceneUpdateStreamDeserializer::ResultType::HasData: @@ -579,12 +579,12 @@ namespace ramses::internal for(const auto& newScene : newScenes) { - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleNewScenesAvailable: sceneId: " << newScene.sceneID << ", name " << newScene.friendlyName <<", by " << providerID << ", featureLevel " << featureLevel); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleNewScenesAvailable: sceneId: {}, name {}, by: {}, featureLevel: {}", newScene.sceneID, newScene.friendlyName, providerID, featureLevel); auto existingSceneIt = m_remoteScenes.find(newScene.sceneID); if (existingSceneIt != m_remoteScenes.end() && existingSceneIt->second.provider == providerID) { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleNewScenesAvailable: duplicate publish of scene: " << newScene.sceneID.getValue() << " @ " << providerID << " name:" << newScene.friendlyName << ". Will unpublish first"); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleNewScenesAvailable: duplicate publish of scene: {} @ {} name:{}. Will unpublish first", newScene.sceneID.getValue(), providerID, newScene.friendlyName); if (m_sceneRendererHandler) m_sceneRendererHandler->handleSceneBecameUnavailable(newScene.sceneID, providerID); m_remoteScenes.erase(newScene.sceneID); @@ -594,7 +594,7 @@ namespace ramses::internal { if (featureLevel == m_featureLevel) { - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleNewScenesAvailable: scene published: " << newScene.sceneID.getValue() << " @ " << providerID << " name:" << newScene.friendlyName << " publicationmode: " << EnumToString(newScene.publicationMode)); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleNewScenesAvailable: scene published: {} @ {} name:{} publicationmode: {}", newScene.sceneID.getValue(), providerID, newScene.friendlyName, EnumToString(newScene.publicationMode)); m_remoteScenes[newScene.sceneID] = ReceivedScene{ newScene, providerID, nullptr }; @@ -604,12 +604,12 @@ namespace ramses::internal else { LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleNewScenesAvailable: ignore publish for scene with mismatched feature level: " - "sceneId: " << newScene.sceneID.getValue() << ", provider: " << providerID << ", name:" << newScene.friendlyName << ", featureLevel: " << featureLevel); + "sceneId: {}, provider: {}, name:{}, featureLevel: {}", newScene.sceneID.getValue(), providerID, newScene.friendlyName, featureLevel); } } else { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleNewScenesAvailable: ignore publish for duplicate scene: " << newScene.sceneID.getValue() << " @ " << providerID << " name:" << newScene.friendlyName); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleNewScenesAvailable: ignore publish for duplicate scene: {} @ {} name: {}", newScene.sceneID.getValue(), providerID, newScene.friendlyName); } } } @@ -618,7 +618,7 @@ namespace ramses::internal { for (const auto& scene : unavailableScenes) { - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleScenesBecameUnavailable: sceneId: " << scene.sceneID << ", name " << scene.friendlyName <<", by " << providerID); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleScenesBecameUnavailable: sceneId: {}, name {}, by {}", scene.sceneID, scene.friendlyName, providerID); auto it = m_remoteScenes.find(scene.sceneID); if (it != m_remoteScenes.end()) @@ -629,14 +629,14 @@ namespace ramses::internal } else { - LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleScenesBecameUnavailable: ignore unpublish for unknown scene: " << scene.sceneID.getValue() << " by " << providerID); + LOG_WARN(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleScenesBecameUnavailable: ignore unpublish for unknown scene: {} by {}", scene.sceneID.getValue(), providerID); } } } void SceneGraphComponent::handleSceneNotAvailable(const SceneId& sceneId, const Guid& providerID) { - LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneNotAvailable: ignoring from sceneId: " << sceneId <<", by " << providerID); + LOG_INFO(CONTEXT_FRAMEWORK, "SceneGraphComponent::handleSceneNotAvailable: ignoring from sceneId: {}, by {}", sceneId, providerID); } const ClientSceneLogicBase* SceneGraphComponent::getClientSceneLogicForScene(SceneId sceneId) const diff --git a/src/framework/internal/Core/TaskFramework/TaskExecutingThread.cpp b/src/framework/internal/Core/TaskFramework/TaskExecutingThread.cpp index 6f1f7cc00..60db2a003 100644 --- a/src/framework/internal/Core/TaskFramework/TaskExecutingThread.cpp +++ b/src/framework/internal/Core/TaskFramework/TaskExecutingThread.cpp @@ -15,7 +15,7 @@ namespace ramses::internal { TaskExecutingThread::TaskExecutingThread(IThreadAliveNotifier& aliveHandler) : m_pBlockingTaskQueue(nullptr) - , m_thread("R_Taskpool_Thrd") + , m_thread("Taskpool_Thrd") , m_aliveHandler(aliveHandler) , m_aliveIdentifier(m_aliveHandler.registerThread()) , m_bThreadStarted(false) diff --git a/src/framework/internal/Core/Utils/AndroidLogger/AndroidLogAppender.cpp b/src/framework/internal/Core/Utils/AndroidLogger/AndroidLogAppender.cpp index 7a39b6b67..651152379 100644 --- a/src/framework/internal/Core/Utils/AndroidLogger/AndroidLogAppender.cpp +++ b/src/framework/internal/Core/Utils/AndroidLogger/AndroidLogAppender.cpp @@ -21,7 +21,7 @@ namespace ramses::internal { android_LogPriority logLevel; - switch(logMessage.getLogLevel()) + switch(logMessage.m_logLevel) { case ELogLevel::Trace: logLevel = ANDROID_LOG_VERBOSE; @@ -47,16 +47,16 @@ namespace ramses::internal } constexpr size_t maxLogSize = 1023; - const std::string& str = logMessage.getStream().data(); + const std::string& str = logMessage.m_message; if (str.size() <= maxLogSize) - __android_log_write(logLevel, logMessage.getContext().getContextName(), str.c_str()); + __android_log_write(logLevel, logMessage.m_context.getContextName(), str.c_str()); else { // create modifyable copy of msg std::string modStr = str; InplaceStringTokenizer::TokenizeToMultilineCStrings(modStr, maxLogSize, '\n', [&](const char* tok) { - __android_log_write(logLevel, logMessage.getContext().getContextName(), tok); + __android_log_write(logLevel, logMessage.m_context.getContextName(), tok); }); } } diff --git a/src/framework/internal/Core/Utils/ConsoleLogAppender.cpp b/src/framework/internal/Core/Utils/ConsoleLogAppender.cpp index ad7239003..9ddc11b3a 100644 --- a/src/framework/internal/Core/Utils/ConsoleLogAppender.cpp +++ b/src/framework/internal/Core/Utils/ConsoleLogAppender.cpp @@ -25,7 +25,7 @@ namespace ramses::internal void ConsoleLogAppender::log(const LogMessage& logMessage) { - if(static_cast(logMessage.getLogLevel()) > static_cast(m_logLevel.load())) + if(static_cast(logMessage.m_logLevel) > static_cast(m_logLevel.load())) return; // TODO(tobias) make static initializer @@ -35,7 +35,7 @@ namespace ramses::internal const char* logLevelColor = nullptr; const char* logLevelStr = nullptr; - switch(logMessage.getLogLevel()) + switch(logMessage.m_logLevel) { case ELogLevel::Trace: logLevelColor = Console::White(); @@ -81,12 +81,12 @@ namespace ramses::internal fmt::print("{}{:%Y%m%d-%H:%M:%S}.{:03}{} | {}{}{} | {}{}{} | {}\n", Console::White(), posix_tm, now % 1000, Console::Default(), logLevelColor, logLevelStr, Console::Default(), - Console::Cyan(), logMessage.getContext().getContextId(), Console::Default(), - logMessage.getStream().data()); + Console::Cyan(), logMessage.m_context.getContextId(), Console::Default(), + logMessage.m_message); } else { - fmt::print("{:%Y%m%d-%H:%M:%S}.{:03} | {} | {} | {}\n", posix_tm, now % 1000, logLevelStr, logMessage.getContext().getContextId(), logMessage.getStream().data()); + fmt::print("{:%Y%m%d-%H:%M:%S}.{:03} | {} | {} | {}\n", posix_tm, now % 1000, logLevelStr, logMessage.m_context.getContextId(), logMessage.m_message); } std::fflush(stdout); diff --git a/src/framework/internal/Core/Utils/File.cpp b/src/framework/internal/Core/Utils/File.cpp index b2295e46a..2ef8b7513 100644 --- a/src/framework/internal/Core/Utils/File.cpp +++ b/src/framework/internal/Core/Utils/File.cpp @@ -94,7 +94,7 @@ namespace ramses::internal std::FILE* handle = std::fopen(m_path.string().c_str(), flags); if (handle == nullptr) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "File::open: fopen {} with flags {} failed, errno is {}", m_path.string(), flags, errno); + LOG_ERROR(CONTEXT_FRAMEWORK, "File::open: fopen {} with flags {} failed, errno is {}", m_path.string(), flags, errno); return false; } @@ -109,7 +109,7 @@ namespace ramses::internal return false; if (std::fflush(m_handle) != 0) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "File::flush: fflush failed for {}, errno is {}", m_path.string(), errno); + LOG_ERROR(CONTEXT_FRAMEWORK, "File::flush: fflush failed for {}, errno is {}", m_path.string(), errno); return false; } return true; @@ -122,7 +122,7 @@ namespace ramses::internal if (std::fclose(m_handle) != 0) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "File::close: fclose failed for {}, errno is {}", m_path.string(), errno); + LOG_ERROR(CONTEXT_FRAMEWORK, "File::close: fclose failed for {}, errno is {}", m_path.string(), errno); return false; } m_handle = nullptr; @@ -152,12 +152,12 @@ namespace ramses::internal if (std::feof(m_handle) != 0) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "File::read: fread attempted to read {} bytes from {}, got only {} due to eof", length, m_path.string(), result); + LOG_ERROR(CONTEXT_FRAMEWORK, "File::read: fread attempted to read {} bytes from {}, got only {} due to eof", length, m_path.string(), result); numBytes = result; return EStatus::Eof; } - LOG_ERROR_P(CONTEXT_FRAMEWORK, "File::read: fread attempted to read {} bytes from {}, got only {} due to read error", length, m_path.string(), result); + LOG_ERROR(CONTEXT_FRAMEWORK, "File::read: fread attempted to read {} bytes from {}, got only {} due to read error", length, m_path.string(), result); return EStatus::Error; } @@ -174,7 +174,7 @@ namespace ramses::internal const size_t result = std::fwrite(buffer, 1, length, m_handle); if (result != length) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "File::write: fwrite attempted to write {} bytes to {} and failed, {} bytes written", length, m_path.string(), result); + LOG_ERROR(CONTEXT_FRAMEWORK, "File::write: fwrite attempted to write {} bytes to {} and failed, {} bytes written", length, m_path.string(), result); return false; } @@ -200,7 +200,7 @@ namespace ramses::internal // NOLINTNEXTLINE(google-runtime-int): long is the API type if (std::fseek(m_handle, static_cast(offset), nativeOrigin) != 0) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "File::seek: fseek attempted to seek to {} bytes from {} of file {} and failed, errno is {}", offset, origin, m_path.string(), errno); + LOG_ERROR(CONTEXT_FRAMEWORK, "File::seek: fseek attempted to seek to {} bytes from {} of file {} and failed, errno is {}", offset, origin, m_path.string(), errno); return false; } @@ -259,7 +259,7 @@ namespace ramses::internal const auto fileSize = std::filesystem::file_size(m_path, ec); if (ec) { - LOG_ERROR_P(CONTEXT_FRAMEWORK, "File::getSizeInBytes: can't get file size for {}, error code is {}", m_path.string(), ec.message()); + LOG_ERROR(CONTEXT_FRAMEWORK, "File::getSizeInBytes: can't get file size for {}, error code is {}", m_path.string(), ec.message()); return false; } size = static_cast(fileSize); diff --git a/src/framework/internal/Core/Utils/Image.cpp b/src/framework/internal/Core/Utils/Image.cpp index 362e53c9e..b81f02e25 100644 --- a/src/framework/internal/Core/Utils/Image.cpp +++ b/src/framework/internal/Core/Utils/Image.cpp @@ -29,14 +29,14 @@ namespace ramses::internal { const unsigned int ret = lodepng::decode(m_data, m_width, m_height, filename); if (ret != 0) - LOG_ERROR(CONTEXT_FRAMEWORK, "Error while loading PNG file: " << filename << " (error " << ret << ": " << lodepng_error_text(ret) << ")"); + LOG_ERROR(CONTEXT_FRAMEWORK, "Error while loading PNG file: {} (error {}: {})", filename, ret, lodepng_error_text(ret)); } void Image::saveToFilePNG(const std::string& filename) const { const unsigned int ret = lodepng::encode(filename, m_data, m_width, m_height); if (ret != 0) - LOG_ERROR(CONTEXT_FRAMEWORK, "Error while saving PNG file: " << filename << " (error " << ret << ": " << lodepng_error_text(ret) << ")"); + LOG_ERROR(CONTEXT_FRAMEWORK, "Error while saving PNG file: {} (error {}: {})", filename, ret, lodepng_error_text(ret)); } bool Image::operator==(const Image& other) const @@ -174,9 +174,8 @@ namespace ramses::internal if (overflow) { - LOG_WARN(CONTEXT_FRAMEWORK, - "Image::getSumOfPixelValues: Overflow of sum of pixel values! The overflown values saturate to max possible positive value for int32_t [=" - << std::numeric_limits::max() << "]"); + LOG_WARN(CONTEXT_FRAMEWORK, "Image::getSumOfPixelValues: Overflow of sum of pixel values! The overflown values saturate to max possible positive value for int32_t [={}]", + std::numeric_limits::max()); } return result; @@ -204,4 +203,11 @@ namespace ramses::internal { return m_data; } + + std::vector Image::getDataAsByte() const + { + std::vector data(m_data.size()); + std::transform(m_data.begin(), m_data.end(), data.begin(), [](uint8_t x) { return static_cast(x); }); + return data; + } } diff --git a/src/framework/internal/Core/Utils/Image.h b/src/framework/internal/Core/Utils/Image.h index 2d600a35e..e4ca7b179 100644 --- a/src/framework/internal/Core/Utils/Image.h +++ b/src/framework/internal/Core/Utils/Image.h @@ -48,6 +48,7 @@ namespace ramses::internal [[nodiscard]] Image createEnlarged(uint32_t width, uint32_t height, std::array fillValue = {0x0, 0x0, 0x0, 0xff}) const; [[nodiscard]] const std::vector& getData() const; + [[nodiscard]] std::vector getDataAsByte() const; bool operator==(const Image& other) const; bool operator!=(const Image& other) const; diff --git a/src/framework/internal/Core/Utils/LogAppenderBase.h b/src/framework/internal/Core/Utils/LogAppenderBase.h index 7a3cbdb1c..a781aec6b 100644 --- a/src/framework/internal/Core/Utils/LogAppenderBase.h +++ b/src/framework/internal/Core/Utils/LogAppenderBase.h @@ -10,7 +10,7 @@ namespace ramses::internal { - class LogMessage; + struct LogMessage; class LogAppenderBase { diff --git a/src/framework/internal/Core/Utils/LogHelper.cpp b/src/framework/internal/Core/Utils/LogHelper.cpp index 387465d28..2b33a8e44 100644 --- a/src/framework/internal/Core/Utils/LogHelper.cpp +++ b/src/framework/internal/Core/Utils/LogHelper.cpp @@ -93,7 +93,7 @@ namespace ramses::internal } else { - LOG_WARN(CONTEXT_FRAMEWORK, "LogHelper::ParseContextFilters: Skip unknown log level '" << logLevelStr << "'"); + LOG_WARN(CONTEXT_FRAMEWORK, "LogHelper::ParseContextFilters: Skip unknown log level '{}'", logLevelStr); } } currentCommandStart = currentCommandEnd + 1; diff --git a/src/framework/internal/Core/Utils/LogMacros.h b/src/framework/internal/Core/Utils/LogMacros.h index 30817acf4..8db739ced 100644 --- a/src/framework/internal/Core/Utils/LogMacros.h +++ b/src/framework/internal/Core/Utils/LogMacros.h @@ -11,6 +11,7 @@ #include "internal/Core/Utils/LogMessage.h" #include "internal/Core/Utils/LogContext.h" #include "internal/Core/Utils/RamsesLogger.h" +#include "internal/PlatformAbstraction/Collections/StringOutputStream.h" #include "internal/PlatformAbstraction/FmtBase.h" namespace ramses::internal @@ -46,59 +47,30 @@ namespace ramses using ramses::internal::CONTEXT_SMOKETEST; } -// LOG_* macros for log message in macro -#define LOG_COMMON(context, logLevel, message) \ - do { \ - if((logLevel) <= (context).getLogLevel()) \ - { \ - ramses::internal::StringOutputStream ramses_log_stream(80); \ - ramses_log_stream << message; /* NOLINT(bugprone-macro-parentheses) */ \ - ramses::internal::GetRamsesLogger().log(ramses::internal::LogMessage((context), (logLevel), ramses_log_stream)); \ - } \ - } while (0) - -#define LOG_TRACE(context, message) \ - LOG_COMMON((context), ramses::ELogLevel::Trace, message) - -#define LOG_INFO(context, message) \ - LOG_COMMON((context), ramses::ELogLevel::Info, message) - -#define LOG_DEBUG(context, message) \ - LOG_COMMON((context), ramses::ELogLevel::Debug, message) - -#define LOG_WARN(context, message) \ - LOG_COMMON((context), ramses::ELogLevel::Warn, message) - -#define LOG_ERROR(context, message) \ - LOG_COMMON((context), ramses::ELogLevel::Error, message) - -#define LOG_FATAL(context, message) \ - LOG_COMMON((context), ramses::ELogLevel::Fatal, message) - // LOG_* macros for log message via printf syntax -#define LOG_COMMON_P(context, logLevel, ...) \ +#define LOG_COMMON(context, logLevel, ...) \ do { \ if((logLevel) <= (context).getLogLevel()) \ - ramses::internal::GetRamsesLogger().log(ramses::internal::LogMessage((context), (logLevel), ramses::internal::StringOutputStream(::fmt::format(__VA_ARGS__)))); \ + ramses::internal::GetRamsesLogger().log(ramses::internal::LogMessage{ (context), (logLevel), ::fmt::format(__VA_ARGS__) }); \ } while (0) -#define LOG_TRACE_P(context, ...) \ - LOG_COMMON_P((context), ramses::ELogLevel::Trace, __VA_ARGS__) +#define LOG_TRACE(context, ...) \ + LOG_COMMON((context), ramses::ELogLevel::Trace, __VA_ARGS__) -#define LOG_INFO_P(context, ...) \ - LOG_COMMON_P((context), ramses::ELogLevel::Info, __VA_ARGS__) +#define LOG_INFO(context, ...) \ + LOG_COMMON((context), ramses::ELogLevel::Info, __VA_ARGS__) -#define LOG_DEBUG_P(context, ...) \ - LOG_COMMON_P((context), ramses::ELogLevel::Debug, __VA_ARGS__) +#define LOG_DEBUG(context, ...) \ + LOG_COMMON((context), ramses::ELogLevel::Debug, __VA_ARGS__) -#define LOG_WARN_P(context, ...) \ - LOG_COMMON_P((context), ramses::ELogLevel::Warn, __VA_ARGS__) +#define LOG_WARN(context, ...) \ + LOG_COMMON((context), ramses::ELogLevel::Warn, __VA_ARGS__) -#define LOG_ERROR_P(context, ...) \ - LOG_COMMON_P((context), ramses::ELogLevel::Error, __VA_ARGS__) +#define LOG_ERROR(context, ...) \ + LOG_COMMON((context), ramses::ELogLevel::Error, __VA_ARGS__) -#define LOG_FATAL_P(context, ...) \ - LOG_COMMON_P((context), ramses::ELogLevel::Fatal, __VA_ARGS__) +#define LOG_FATAL(context, ...) \ + LOG_COMMON((context), ramses::ELogLevel::Fatal, __VA_ARGS__) // LOG_* macros for log message via callable #define LOG_COMMON_F(context, logLevel, callable) \ @@ -107,7 +79,7 @@ namespace ramses { \ ramses::internal::StringOutputStream ramses_log_stream(160); \ callable(ramses_log_stream); \ - ramses::internal::GetRamsesLogger().log(ramses::internal::LogMessage((context), (logLevel), ramses_log_stream)); \ + ramses::internal::GetRamsesLogger().log(ramses::internal::LogMessage{ (context), (logLevel), ramses_log_stream.release() }); \ } \ } while (0) @@ -137,7 +109,7 @@ namespace ramses { \ fmt::memory_buffer ramses_fmtlib_buffer; \ callable(ramses_fmtlib_buffer); \ - ramses::internal::GetRamsesLogger().log(ramses::internal::LogMessage((context), (logLevel), ramses::internal::StringOutputStream(fmt::to_string(ramses_fmtlib_buffer)))); \ + ramses::internal::GetRamsesLogger().log(ramses::internal::LogMessage{ (context), (logLevel), fmt::to_string(ramses_fmtlib_buffer) }); \ } \ } while (0) diff --git a/src/framework/internal/Core/Utils/LogMessage.h b/src/framework/internal/Core/Utils/LogMessage.h index 3e7cfa5ee..ad3ed128d 100644 --- a/src/framework/internal/Core/Utils/LogMessage.h +++ b/src/framework/internal/Core/Utils/LogMessage.h @@ -9,46 +9,16 @@ #pragma once #include "internal/Core/Utils/LogLevel.h" -#include "internal/PlatformAbstraction/Collections/StringOutputStream.h" +#include namespace ramses::internal { class LogContext; - class LogMessage + struct LogMessage { - public: - LogMessage(const LogContext& context, ELogLevel logLevel, const StringOutputStream& stream); - - [[nodiscard]] const StringOutputStream& getStream() const; - [[nodiscard]] const LogContext& getContext() const; - [[nodiscard]] ELogLevel getLogLevel() const; - - private: const LogContext& m_context; - const ELogLevel m_logLevel; - const StringOutputStream& m_outputStream; + ELogLevel m_logLevel; + std::string m_message; }; - - inline LogMessage::LogMessage(const LogContext& context, ELogLevel logLevel, const StringOutputStream& stream) - : m_context(context) - , m_logLevel(logLevel) - , m_outputStream(stream) - { - } - - inline const StringOutputStream& LogMessage::getStream() const - { - return m_outputStream; - } - - inline const LogContext& LogMessage::getContext() const - { - return m_context; - } - - inline ELogLevel LogMessage::getLogLevel() const - { - return m_logLevel; - } } diff --git a/src/framework/internal/Core/Utils/PeriodicLogger.cpp b/src/framework/internal/Core/Utils/PeriodicLogger.cpp index c9d3ba70c..c2f48cd9c 100644 --- a/src/framework/internal/Core/Utils/PeriodicLogger.cpp +++ b/src/framework/internal/Core/Utils/PeriodicLogger.cpp @@ -22,7 +22,7 @@ namespace ramses::internal PeriodicLogger::PeriodicLogger(PlatformLock& frameworkLock, StatisticCollectionFramework& statisticCollection) : m_isRunning(false) , m_periodicLogTimeoutSeconds(0) - , m_thread("R_PerLogger") + , m_thread("PerLogger") , m_frameworkLock(frameworkLock) , m_statisticCollection(statisticCollection) , m_triggerCounter(0) @@ -128,12 +128,10 @@ namespace ramses::internal int64_t steadyDiff = std::chrono::duration_cast(steadyNow - m_previousSteadyTime).count(); int64_t syncDiff = std::chrono::duration_cast(syncNow - m_previousSyncTime).count(); - LOG_INFO(CONTEXT_PERIODIC, "Version: " << ::ramses_sdk::RAMSES_SDK_RAMSES_VERSION << " Hash:" << ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_HASH - << " Commit:" << ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_COUNT << " Type:" << ::ramses_sdk::RAMSES_SDK_CMAKE_BUILD_TYPE - << " Env:" << ::ramses_sdk::RAMSES_SDK_BUILD_ENV_VERSION_INFO_FULL - << " SyncT:" << asMilliseconds(syncNow) << "ms (dtSteady:" << steadyDiff << " - dtSync:" << syncDiff << " -> " << (steadyDiff - syncDiff) << ")" - << " PUp:" << pUp << " RUp:" << rUp - << " RInit:" << m_numberOfRamsesInstancesStartedInProcess.load() << " RParallel:" << m_numberOfRamsesInstancesCurrentlyActive.load()); + LOG_INFO(CONTEXT_PERIODIC, "Version: {} Hash:{} Commit:{} Type:{} Env:{} SyncT:{}ms (dtSteady:{} - dtSync:{} -> {}) PUp:{} RUp:{} RInit:{} RParallel:{}", + ::ramses_sdk::RAMSES_SDK_RAMSES_VERSION, ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_HASH, ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_COUNT, + ::ramses_sdk::RAMSES_SDK_CMAKE_BUILD_TYPE, ::ramses_sdk::RAMSES_SDK_BUILD_ENV_VERSION_INFO_FULL, asMilliseconds(syncNow), + steadyDiff, syncDiff, steadyDiff - syncDiff, pUp, rUp, m_numberOfRamsesInstancesStartedInProcess.load(), m_numberOfRamsesInstancesCurrentlyActive.load()); m_previousSyncTime = syncNow; m_previousSteadyTime = steadyNow; diff --git a/src/framework/internal/Core/Utils/RamsesLogger.cpp b/src/framework/internal/Core/Utils/RamsesLogger.cpp index 1948fdcfb..cbd5bad8b 100644 --- a/src/framework/internal/Core/Utils/RamsesLogger.cpp +++ b/src/framework/internal/Core/Utils/RamsesLogger.cpp @@ -21,6 +21,11 @@ namespace ramses::internal { + thread_local std::string RamsesLogger::PrefixInstance = "R"; + thread_local std::string RamsesLogger::PrefixThread = "main"; + thread_local std::string RamsesLogger::PrefixAdditional; + thread_local std::string RamsesLogger::PrefixCombined = "R.main: "; + RamsesLogger::RamsesLogger() : m_isInitialized(false) , m_fileTransferContext(createContext("File Transfer Context", "FILE")) @@ -126,8 +131,7 @@ namespace ramses::internal LOG_INFO(CONTEXT_FRAMEWORK, "RamsesLogger::initialize: a user logger was added"); } - LOG_INFO(CONTEXT_FRAMEWORK, "Ramses log levels: Contexts " << RamsesLogger::GetLogLevelText(logLevelContexts) << - ", Console " << RamsesLogger::GetLogLevelText(logLevelConsole)); + LOG_INFO(CONTEXT_FRAMEWORK, "Ramses log levels: Contexts {}, Console {}", RamsesLogger::GetLogLevelText(logLevelContexts), RamsesLogger::GetLogLevelText(logLevelConsole)); } void RamsesLogger::applyContextFilterCommand(const std::string& command) @@ -142,16 +146,12 @@ namespace ramses::internal { if (LogContext* ctx = getLogContextById(contextId)) { - LOG_INFO(CONTEXT_FRAMEWORK, contextId << " | " << ctx->getContextName() - << " | " - << static_cast(logLevel) - << " | " - << RamsesLogger::GetLogLevelText(logLevel)); + LOG_INFO(CONTEXT_FRAMEWORK, "{} | {} | {} | {}", contextId, ctx->getContextName(), static_cast(logLevel), RamsesLogger::GetLogLevelText(logLevel)); ctx->setLogLevel(logLevel); } else { - LOG_INFO(CONTEXT_FRAMEWORK, "RamsesLogger::applyContextFilterCommand: unknown contextId " << contextId); + LOG_INFO(CONTEXT_FRAMEWORK, "RamsesLogger::applyContextFilterCommand: unknown contextId {}", contextId); } } @@ -247,7 +247,7 @@ namespace ramses::internal LogContext* ctx = getLogContextById(contextId); if (!ctx) { - LOG_WARN(CONTEXT_RAMSH, "RamsesLogger::dltLogLevelChangeCallback: unknown contextId " << contextId); + LOG_WARN(CONTEXT_RAMSH, "RamsesLogger::dltLogLevelChangeCallback: unknown contextId {}", contextId); return; } @@ -256,15 +256,12 @@ namespace ramses::internal if (currentLogLevel != newLogLevel) { - LOG_INFO(CONTEXT_RAMSH, contextId << " | " << ctx->getContextName() - << " | " - << static_cast(newLogLevel) - << " | " - << GetLogLevelText(newLogLevel) - << " | " - << " Dlt changed log level from " - << GetLogLevelText(currentLogLevel) - ); + LOG_INFO(CONTEXT_RAMSH, "{} | {} | {} | {} | Dlt changed log level from {}", + contextId, + ctx->getContextName(), + static_cast(newLogLevel), + GetLogLevelText(newLogLevel), + GetLogLevelText(currentLogLevel)); ctx->setLogLevel(newLogLevel); } } @@ -279,10 +276,12 @@ namespace ramses::internal return nullptr; } - void RamsesLogger::log(const LogMessage& msg) + void RamsesLogger::log(LogMessage&& msg) { - if (msg.getStream().size() > 0) + if (!msg.m_message.empty()) { + msg.m_message.insert(0, PrefixCombined); + std::lock_guard guard(m_appenderLock); for (auto& appender : m_logAppenders) { @@ -331,4 +330,31 @@ namespace ramses::internal m_logAppenders.push_back(m_userLogAppender.get()); } } + + void RamsesLogger::SetPrefixes(std::string_view instance, std::string_view thread, std::string_view additional) + { + PrefixInstance = instance; + PrefixThread = thread; + PrefixAdditional = additional; + + PrefixCombined.clear(); + if (!PrefixAdditional.empty()) + { + fmt::format_to(std::back_inserter(PrefixCombined), "{}.{}.{}: ", PrefixInstance, PrefixThread, PrefixAdditional); + } + else + { + fmt::format_to(std::back_inserter(PrefixCombined), "{}.{}: ", PrefixInstance, PrefixThread); + } + } + + void RamsesLogger::SetPrefixAdditional(std::string_view additional) + { + SetPrefixes(PrefixInstance, PrefixThread, additional); + } + + const std::string& RamsesLogger::GetPrefixInstance() + { + return PrefixInstance; + } } diff --git a/src/framework/internal/Core/Utils/RamsesLogger.h b/src/framework/internal/Core/Utils/RamsesLogger.h index 9e01e446b..db31b1791 100644 --- a/src/framework/internal/Core/Utils/RamsesLogger.h +++ b/src/framework/internal/Core/Utils/RamsesLogger.h @@ -56,7 +56,7 @@ namespace ramses::internal [[nodiscard]] bool isDltAppenderActive() const; - void log(const LogMessage& msg); + void log(LogMessage&& msg); void applyContextFilterCommand(const std::string& command); [[nodiscard]] std::vector getAllContextsInformation() const; @@ -73,14 +73,22 @@ namespace ramses::internal bool transmit(std::vector&& data, const std::string& filename) const; bool registerInjectionCallback(LogContext& ctx, uint32_t serviceId, int (*callback)(uint32_t serviceId, void* data, uint32_t length)); - static const char* GetLogLevelText(ELogLevel logLevel); - void setLogHandler(const LogHandlerFunc& logHandlerFunc); + static const char* GetLogLevelText(ELogLevel logLevel); + static void SetPrefixes(std::string_view instance, std::string_view thread, std::string_view additional = {}); + static void SetPrefixAdditional(std::string_view additional); + static const std::string& GetPrefixInstance(); + private: static const ELogLevel LogLevelDefault_Contexts = ELogLevel::Info; static const ELogLevel LogLevelDefault_Console = ELogLevel::Info; + static thread_local std::string PrefixInstance; + static thread_local std::string PrefixThread; + static thread_local std::string PrefixAdditional; + static thread_local std::string PrefixCombined; + void applyContextFilter(const std::string& context, ELogLevel logLevel); void dltLogLevelChangeCallback(const std::string& contextId, int logLevelAsInt); diff --git a/src/framework/internal/Core/Utils/ThreadLocalLog.cpp b/src/framework/internal/Core/Utils/ThreadLocalLog.cpp deleted file mode 100644 index d523bff02..000000000 --- a/src/framework/internal/Core/Utils/ThreadLocalLog.cpp +++ /dev/null @@ -1,39 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2021 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "internal/Core/Utils/ThreadLocalLog.h" - -#include - -namespace ramses::internal -{ - namespace TLSPrefix - { - // Some platforms require explicit compile flag to enable TLS, - // isolate TLS in this compilation unit so that this flag - // needs to be enabled only for this single file. - thread_local static int ID = -1; - } - - void ThreadLocalLog::SetPrefix(int prefixId) - { - assert(prefixId != -1); - TLSPrefix::ID = prefixId; - } - - int ThreadLocalLog::GetPrefix() - { - assert(TLSPrefix::ID != -1 && "Thread local log PrefixID must be set"); - return TLSPrefix::ID; - } - - int ThreadLocalLog::GetPrefixUnchecked() - { - return TLSPrefix::ID; - } -} diff --git a/src/framework/internal/Core/Utils/ThreadLocalLog.h b/src/framework/internal/Core/Utils/ThreadLocalLog.h deleted file mode 100644 index 9e8aab4ec..000000000 --- a/src/framework/internal/Core/Utils/ThreadLocalLog.h +++ /dev/null @@ -1,125 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2021 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -#include "internal/Core/Utils/LogMacros.h" - -namespace ramses::internal -{ - class ThreadLocalLog - { - public: - static void SetPrefix(int prefixId); - static int GetPrefix(); - static int GetPrefixUnchecked(); - }; -} - -#define LOG_COMMON_R(context, logLevel, message) \ - LOG_COMMON((context), logLevel, ramses::internal::ThreadLocalLog::GetPrefix() << ": " << message) // NOLINT(bugprone-macro-parentheses) - -#define LOG_TRACE_R(context, message) \ - LOG_COMMON_R(context, ramses::ELogLevel::Trace, message) - -#define LOG_DEBUG_R(context, message) \ - LOG_COMMON_R(context, ramses::ELogLevel::Debug, message) - -#define LOG_INFO_R(context, message) \ - LOG_COMMON_R(context, ramses::ELogLevel::Info, message) - -#define LOG_WARN_R(context, message) \ - LOG_COMMON_R(context, ramses::ELogLevel::Warn, message) - -#define LOG_ERROR_R(context, message) \ - LOG_COMMON_R(context, ramses::ELogLevel::Error, message) - -#define LOG_FATAL_R(context, message) \ - LOG_COMMON_R(context, ramses::ELogLevel::Fatal, message) - - -#define LOG_COMMON_RP(context, logLevel, ...) \ - LOG_COMMON_P((context), logLevel, ::fmt::format("{}: {}", ramses::internal::ThreadLocalLog::GetPrefix(), ::fmt::format(__VA_ARGS__))) - -#define LOG_TRACE_RP(context, ...) \ - LOG_COMMON_RP(context, ramses::ELogLevel::Trace, __VA_ARGS__) - -#define LOG_DEBUG_RP(context, ...) \ - LOG_COMMON_RP(context, ramses::ELogLevel::Debug, __VA_ARGS__) - -#define LOG_INFO_RP(context, ...) \ - LOG_COMMON_RP(context, ramses::ELogLevel::Info, __VA_ARGS__) - -#define LOG_WARN_RP(context, ...) \ - LOG_COMMON_RP(context, ramses::ELogLevel::Warn, __VA_ARGS__) - -#define LOG_ERROR_RP(context, ...) \ - LOG_COMMON_RP(context, ramses::ELogLevel::Error, __VA_ARGS__) - -#define LOG_FATAL_RP(context, ...) \ - LOG_COMMON_RP(context, ramses::ELogLevel::Fatal, __VA_ARGS__) - - -#define LOG_COMMON_RF(context, logLevel, callable) \ - do { \ - if((logLevel) <= (context).getLogLevel()) \ - { \ - ramses::internal::StringOutputStream ramses_log_stream(160); \ - ramses_log_stream << ramses::internal::ThreadLocalLog::GetPrefix() << ": "; \ - callable(ramses_log_stream); \ - ramses::internal::GetRamsesLogger().log(ramses::internal::LogMessage((context), (logLevel), ramses_log_stream)); \ - } \ - } while (0) - -#define LOG_TRACE_RF(context, callable) \ - LOG_COMMON_RF((context), ramses::ELogLevel::Trace, callable) - -#define LOG_INFO_RF(context, callable) \ - LOG_COMMON_RF((context), ramses::ELogLevel::Info, callable) - -#define LOG_DEBUG_RF(context, callable) \ - LOG_COMMON_RF((context), ramses::ELogLevel::Debug, callable) - -#define LOG_WARN_RF(context, callable) \ - LOG_COMMON_RF((context), ramses::ELogLevel::Warn, callable) - -#define LOG_ERROR_RF(context, callable) \ - LOG_COMMON_RF((context), ramses::ELogLevel::Error, callable) - -#define LOG_FATAL_RF(context, callable) \ - LOG_COMMON_RF((context), ramses::ELogLevel::Fatal, callable) - - -#define LOG_COMMON_RPF(context, logLevel, callable) \ - do { \ - if ((logLevel) <= (context).getLogLevel()) \ - { \ - fmt::memory_buffer ramses_fmtlib_buffer; \ - fmt::format_to(std::back_inserter(ramses_fmtlib_buffer), "{}: ", ramses::internal::ThreadLocalLog::GetPrefix()); \ - callable(ramses_fmtlib_buffer); \ - ramses::internal::GetRamsesLogger().log(ramses::internal::LogMessage((context), (logLevel), ramses::internal::StringOutputStream(fmt::to_string(ramses_fmtlib_buffer)))); \ - } \ - } while (0) - -#define LOG_TRACE_RPF(context, callable) \ - LOG_COMMON_RPF((context), ramses::ELogLevel::Trace, callable) - -#define LOG_INFO_RPF(context, callable) \ - LOG_COMMON_RPF((context), ramses::ELogLevel::Info, callable) - -#define LOG_DEBUG_RPF(context, callable) \ - LOG_COMMON_RPF((context), ramses::ELogLevel::Debug, callable) - -#define LOG_WARN_RPF(context, callable) \ - LOG_COMMON_RPF((context), ramses::ELogLevel::Warn, callable) - -#define LOG_ERROR_RPF(context, callable) \ - LOG_COMMON_RPF((context), ramses::ELogLevel::Error, callable) - -#define LOG_FATAL_RPF(context, callable) \ - LOG_COMMON_RPF((context), ramses::ELogLevel::Fatal, callable) diff --git a/src/framework/internal/Core/Utils/ThreadLocalLogForced.h b/src/framework/internal/Core/Utils/ThreadLocalLogForced.h deleted file mode 100644 index 12175af6b..000000000 --- a/src/framework/internal/Core/Utils/ThreadLocalLogForced.h +++ /dev/null @@ -1,64 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2021 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -// Include this file to CPP files where a thread local log (log with prefixed thread ID) must always be used. -// The standard LOG macros are redefined to use the thread local versions. - -#include "internal/Core/Utils/ThreadLocalLog.h" - -#undef LOG_TRACE -#undef LOG_INFO -#undef LOG_DEBUG -#undef LOG_WARN -#undef LOG_ERROR -#undef LOG_FATAL -#undef LOG_TRACE_P -#undef LOG_INFO_P -#undef LOG_DEBUG_P -#undef LOG_WARN_P -#undef LOG_ERROR_P -#undef LOG_FATAL_P -#undef LOG_TRACE_F -#undef LOG_INFO_F -#undef LOG_DEBUG_F -#undef LOG_WARN_F -#undef LOG_ERROR_F -#undef LOG_FATAL_F -#undef LOG_TRACE_PF -#undef LOG_INFO_PF -#undef LOG_DEBUG_PF -#undef LOG_WARN_PF -#undef LOG_ERROR_PF -#undef LOG_FATAL_PF - -#define LOG_TRACE LOG_TRACE_R -#define LOG_INFO LOG_INFO_R -#define LOG_DEBUG LOG_DEBUG_R -#define LOG_WARN LOG_WARN_R -#define LOG_ERROR LOG_ERROR_R -#define LOG_FATAL LOG_FATAL_R -#define LOG_TRACE_P LOG_TRACE_RP -#define LOG_INFO_P LOG_INFO_RP -#define LOG_DEBUG_P LOG_DEBUG_RP -#define LOG_WARN_P LOG_WARN_RP -#define LOG_ERROR_P LOG_ERROR_RP -#define LOG_FATAL_P LOG_FATAL_RP -#define LOG_TRACE_F LOG_TRACE_RF -#define LOG_INFO_F LOG_INFO_RF -#define LOG_DEBUG_F LOG_DEBUG_RF -#define LOG_WARN_F LOG_WARN_RF -#define LOG_ERROR_F LOG_ERROR_RF -#define LOG_FATAL_F LOG_FATAL_RF -#define LOG_TRACE_PF LOG_TRACE_RPF -#define LOG_INFO_PF LOG_INFO_RPF -#define LOG_DEBUG_PF LOG_DEBUG_RPF -#define LOG_WARN_PF LOG_WARN_RPF -#define LOG_ERROR_PF LOG_ERROR_RPF -#define LOG_FATAL_PF LOG_FATAL_RPF diff --git a/src/framework/internal/Core/Utils/UserLogAppender.cpp b/src/framework/internal/Core/Utils/UserLogAppender.cpp index f69d205bf..92a2a160d 100644 --- a/src/framework/internal/Core/Utils/UserLogAppender.cpp +++ b/src/framework/internal/Core/Utils/UserLogAppender.cpp @@ -21,6 +21,6 @@ namespace ramses::internal void UserLogAppender::log(const LogMessage& logMessage) { - m_func(logMessage.getLogLevel(), logMessage.getContext().getContextId(), logMessage.getStream().data()); + m_func(logMessage.m_logLevel, logMessage.m_context.getContextId(), logMessage.m_message); } } diff --git a/src/framework/internal/DltLogAppender/DltAdapterImpl/DltAdapterImpl.cpp b/src/framework/internal/DltLogAppender/DltAdapterImpl/DltAdapterImpl.cpp index cace0d445..1b900eff9 100644 --- a/src/framework/internal/DltLogAppender/DltAdapterImpl/DltAdapterImpl.cpp +++ b/src/framework/internal/DltLogAppender/DltAdapterImpl/DltAdapterImpl.cpp @@ -60,7 +60,7 @@ namespace ramses::internal return false; } - auto* dltContext = static_cast(msg.getContext().getUserData()); + auto* dltContext = static_cast(msg.m_context.getUserData()); if (dltContext == nullptr) { fmt::print(stderr, "DltAdapterImpl::logMessage: missing dlt context\n"); @@ -72,7 +72,7 @@ namespace ramses::internal auto ll = DLT_LOG_OFF; - switch(msg.getLogLevel()) + switch(msg.m_logLevel) { case ELogLevel::Trace: ll = DLT_LOG_VERBOSE; @@ -106,8 +106,8 @@ namespace ramses::internal // 21 bytes are needed for meta-data: 4 (standard header) + 10 (extended header) + 4 (argument type) + 2 (text length) + 1 (0-terminated string) maxLineCapacity -= 30u; //30 subtracted to have some buffer - const char* msgData = msg.getStream().c_str(); - uint32_t msgLength = msg.getStream().size(); + const char* msgData = msg.m_message.c_str(); + uint32_t msgLength = msg.m_message.size(); const char* msgDataEnd = msgData + msgLength; // check if shortcut is possible: short enough line and no linebreaks diff --git a/src/framework/internal/PlatformAbstraction/PlatformThread.h b/src/framework/internal/PlatformAbstraction/PlatformThread.h index 7ddaa7eb5..77bf46f5b 100644 --- a/src/framework/internal/PlatformAbstraction/PlatformThread.h +++ b/src/framework/internal/PlatformAbstraction/PlatformThread.h @@ -9,6 +9,7 @@ #pragma once #include "internal/PlatformAbstraction/Runnable.h" +#include "internal/Core/Utils/RamsesLogger.h" #include #include @@ -45,9 +46,13 @@ namespace ramses::internal private: std::string m_name; - internal::Thread m_thread; + internal::Thread m_thread; std::atomic m_isRunning {false}; Runnable* m_runnable = nullptr; + + // Logger stores global instance name as thread_local, temporary storage here allows assigning it to logger later when the thread starts + // so that all Ramses threads within single RamsesFramework use same global instance name. + std::string m_loggingInstanceName = RamsesLogger::GetPrefixInstance(); }; inline @@ -91,11 +96,13 @@ namespace ramses::internal m_runnable = &runnable; m_isRunning = true; - m_thread = internal::Thread(m_name, [&]() - { - m_runnable->run(); - m_isRunning = false; - }); + m_thread = internal::Thread(fmt::format("R_{}", m_name), [&]() { + // set global instance and thread name to logger + RamsesLogger::SetPrefixes(m_loggingInstanceName, m_name); + + m_runnable->run(); + m_isRunning = false; + }); } inline void PlatformThread::join() diff --git a/src/framework/internal/PlatformAbstraction/synchronized_clock.cpp b/src/framework/internal/PlatformAbstraction/synchronized_clock.cpp index 7ccc2032d..1b2cebd69 100644 --- a/src/framework/internal/PlatformAbstraction/synchronized_clock.cpp +++ b/src/framework/internal/PlatformAbstraction/synchronized_clock.cpp @@ -23,7 +23,7 @@ namespace ramses::internal int fd = open("/dev/ptp0", O_RDONLY); if (fd < 0) { - LOG_WARN(CONTEXT_FRAMEWORK, "PlatformTimePTP::GetClockId: failed to open /dev/ptp0 with error: " << strerror(errno)); + LOG_WARN(CONTEXT_FRAMEWORK, "PlatformTimePTP::GetClockId: failed to open /dev/ptp0 with error: {}", strerror(errno)); return 0; } const int baseClockFd = 3; @@ -33,7 +33,7 @@ namespace ramses::internal struct timespec dummyTs; if (clock_gettime(clockId, &dummyTs) != 0) { - LOG_WARN(CONTEXT_FRAMEWORK, "PlatformTimePTP::GetClockId: clock_gettime failed (fd:" << fd << ", clockId: " << clockId << ") with error: " << strerror(errno)); + LOG_WARN(CONTEXT_FRAMEWORK, "PlatformTimePTP::GetClockId: clock_gettime failed (fd:{}, clockId: {}) with error: {}", fd, clockId, strerror(errno)); return 0; } return clockId; diff --git a/src/framework/internal/Ramsh/Ramsh.cpp b/src/framework/internal/Ramsh/Ramsh.cpp index 090337e77..56ab493c3 100644 --- a/src/framework/internal/Ramsh/Ramsh.cpp +++ b/src/framework/internal/Ramsh/Ramsh.cpp @@ -56,7 +56,7 @@ namespace ramses::internal // check keywords if (command->keywords().empty()) { - LOG_WARN_P(CONTEXT_RAMSH, "Ramsh::add: Command has no keywords"); + LOG_WARN(CONTEXT_RAMSH, "Ramsh::add: Command has no keywords"); return false; } for (const auto& kw : command->keywords()) @@ -71,14 +71,14 @@ namespace ramses::internal }; if (std::find_if(kw.begin(), kw.end(), isValidChar) != kw.end()) { - LOG_WARN_P(CONTEXT_RAMSH, "Ramsh::add: Command keyword '{}' is invalid", kw); + LOG_WARN(CONTEXT_RAMSH, "Ramsh::add: Command keyword '{}' is invalid", kw); return false; } if (!allowOverride) { if (m_commands.find(kw) != m_commands.end()) { - LOG_WARN_P(CONTEXT_RAMSH, "Ramsh::add: Command with keyword '{}' already exists", kw); + LOG_WARN(CONTEXT_RAMSH, "Ramsh::add: Command with keyword '{}' already exists", kw); return false; } } @@ -105,7 +105,7 @@ namespace ramses::internal auto iter = m_commands.find(keyword); if (iter == m_commands.end()) { - LOG_ERROR_P(CONTEXT_RAMSH, "unknown command: '{}'", keyword); + LOG_ERROR(CONTEXT_RAMSH, "unknown command: '{}'", keyword); return false; } @@ -113,15 +113,15 @@ namespace ramses::internal } if (!cmd) { - LOG_ERROR_P(CONTEXT_RAMSH, "command implementation missing: '{}'", keyword); + LOG_ERROR(CONTEXT_RAMSH, "command implementation missing: '{}'", keyword); return false; } - LOG_DEBUG_P(CONTEXT_RAMSH, "triggering cmd '{}'", fmt::join(input, " ")); + LOG_DEBUG(CONTEXT_RAMSH, "triggering cmd '{}'", fmt::join(input, " ")); const bool cmdResult = cmd->executeInput(input); if (!cmdResult) { - LOG_WARN_P(CONTEXT_RAMSH, "cmd '{}' returned false", fmt::join(input, " ")); + LOG_WARN(CONTEXT_RAMSH, "cmd '{}' returned false", fmt::join(input, " ")); } return cmdResult; diff --git a/src/framework/internal/Ramsh/RamshCommandArgumentsDataProvider.h b/src/framework/internal/Ramsh/RamshCommandArgumentsDataProvider.h index 56afeba8f..f180af0e8 100644 --- a/src/framework/internal/Ramsh/RamshCommandArgumentsDataProvider.h +++ b/src/framework/internal/Ramsh/RamshCommandArgumentsDataProvider.h @@ -237,8 +237,7 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RAMSH,"Trying to set default value of argument of type " << typeString() << - " with value of wrong type " << static_cast(TypeName())); + LOG_ERROR(CONTEXT_RAMSH, "Trying to set default value of argument of type {} with value of wrong type {}", typeString(), static_cast(TypeName())); } } @@ -453,8 +452,8 @@ namespace ramses::internal // validate if a valid argument value is returned if(!m_args[index]->getValue(argData,value)) { - LOG_ERROR(CONTEXT_RAMSH,"Missing/Invalid argument " << m_args[index]->keywords() << "!"); - LOG_ERROR(CONTEXT_RAMSH,"Usage: " << m_args[index]->description()); + LOG_ERROR(CONTEXT_RAMSH, "Missing/Invalid argument {}!", m_args[index]->keywords()); + LOG_ERROR(CONTEXT_RAMSH, "Usage: {}", m_args[index]->description()); return false; } diff --git a/src/framework/internal/Ramsh/RamshCommandPrintBuildConfig.cpp b/src/framework/internal/Ramsh/RamshCommandPrintBuildConfig.cpp index 94931b75b..a634da450 100644 --- a/src/framework/internal/Ramsh/RamshCommandPrintBuildConfig.cpp +++ b/src/framework/internal/Ramsh/RamshCommandPrintBuildConfig.cpp @@ -22,18 +22,19 @@ namespace ramses::internal bool RamshCommandPrintBuildConfig::executeInput(const std::vector& /*unused*/) { LOG_INFO(CONTEXT_RAMSH, - "VERSION_STRING = " << ::ramses_sdk::RAMSES_SDK_RAMSES_VERSION << "\n" << - "GIT_COMMIT_COUNT = " << ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_COUNT << "\n" << - "GIT_COMMIT_HASH = " << ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_HASH << "\n" << - "BUILD_TYPE = " << ::ramses_sdk::RAMSES_SDK_CMAKE_BUILD_TYPE << "\n" << - "CXX_COMPILER = " << ::ramses_sdk::RAMSES_SDK_CMAKE_CXX_COMPILER << "\n" << - "CXX_COMPILER_ID = " << ::ramses_sdk::RAMSES_SDK_CMAKE_CXX_COMPILER_ID << "\n" << - "CXX_FLAGS = " << ::ramses_sdk::RAMSES_SDK_CMAKE_CXX_FLAGS << "\n" << - "CXX_FLAGS_DEBUG = " << ::ramses_sdk::RAMSES_SDK_CMAKE_CXX_FLAGS_DEBUG << "\n" << - "CXX_FLAGS_RELEASE = " << ::ramses_sdk::RAMSES_SDK_CMAKE_CXX_FLAGS_RELEASE << "\n" << - "BUILD_SYSTEM_NAME = " << ::ramses_sdk::RAMSES_SDK_CMAKE_SYSTEM_NAME << "\n" << - "CMAKE_VERSION = " << ::ramses_sdk::RAMSES_SDK_CMAKE_VERSION << "\n" << - "BUILD_ENV_INFO = " << ::ramses_sdk::RAMSES_SDK_BUILD_ENV_VERSION_INFO_FULL << "\n" + "VERSION_STRING = {}\nGIT_COMMIT_COUNT = {}\nGIT_COMMIT_HASH = {}\nBUILD_TYPE = {}\nCXX_COMPILER = {}\nCXX_COMPILER_ID = {}\nCXX_FLAGS = {}\nCXX_FLAGS_DEBUG = {}\nCXX_FLAGS_RELEASE = {}\nBUILD_SYSTEM_NAME = {}\nCMAKE_VERSION = {}\nBUILD_ENV_INFO = {}\n", + ::ramses_sdk::RAMSES_SDK_RAMSES_VERSION, + ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_COUNT, + ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_HASH, + ::ramses_sdk::RAMSES_SDK_CMAKE_BUILD_TYPE, + ::ramses_sdk::RAMSES_SDK_CMAKE_CXX_COMPILER, + ::ramses_sdk::RAMSES_SDK_CMAKE_CXX_COMPILER_ID, + ::ramses_sdk::RAMSES_SDK_CMAKE_CXX_FLAGS, + ::ramses_sdk::RAMSES_SDK_CMAKE_CXX_FLAGS_DEBUG, + ::ramses_sdk::RAMSES_SDK_CMAKE_CXX_FLAGS_RELEASE, + ::ramses_sdk::RAMSES_SDK_CMAKE_SYSTEM_NAME, + ::ramses_sdk::RAMSES_SDK_CMAKE_VERSION, + ::ramses_sdk::RAMSES_SDK_BUILD_ENV_VERSION_INFO_FULL ); return true; } diff --git a/src/framework/internal/Ramsh/RamshCommandPrintLogLevels.cpp b/src/framework/internal/Ramsh/RamshCommandPrintLogLevels.cpp index 52a44d657..d4d85dd7a 100644 --- a/src/framework/internal/Ramsh/RamshCommandPrintLogLevels.cpp +++ b/src/framework/internal/Ramsh/RamshCommandPrintLogLevels.cpp @@ -28,7 +28,7 @@ namespace ramses::internal LOG_INFO(CONTEXT_RAMSH,""); LOG_INFO(CONTEXT_RAMSH," Appender Log Levels "); LOG_INFO(CONTEXT_RAMSH,"----------------------------------------"); - LOG_INFO(CONTEXT_RAMSH,"Console | " << static_cast(consoleLogLevel) << " | " << RamsesLogger::GetLogLevelText(consoleLogLevel)); + LOG_INFO(CONTEXT_RAMSH,"Console | {} | {}", static_cast(consoleLogLevel), RamsesLogger::GetLogLevelText(consoleLogLevel)); LOG_INFO(CONTEXT_RAMSH,""); LOG_INFO(CONTEXT_RAMSH," Context Log Levels "); LOG_INFO(CONTEXT_RAMSH,"ID | Name | V | Level"); @@ -36,11 +36,11 @@ namespace ramses::internal for (const auto& info : GetRamsesLogger().getAllContextsInformation()) { - LOG_INFO(CONTEXT_RAMSH, info.id << " | " << info.name - << " | " - << static_cast(info.logLevel) - << " | " - << RamsesLogger::GetLogLevelText(info.logLevel)); + LOG_INFO(CONTEXT_RAMSH, "{} | {} | {} | {}", + info.id, + info.name, + static_cast(info.logLevel), + RamsesLogger::GetLogLevelText(info.logLevel)); } return true; diff --git a/src/framework/internal/Ramsh/RamshCommandSetConsoleLogLevel.cpp b/src/framework/internal/Ramsh/RamshCommandSetConsoleLogLevel.cpp index 5938e0d70..84eae3477 100644 --- a/src/framework/internal/Ramsh/RamshCommandSetConsoleLogLevel.cpp +++ b/src/framework/internal/Ramsh/RamshCommandSetConsoleLogLevel.cpp @@ -19,7 +19,7 @@ namespace ramses::internal //commands to set the log level for console appender registerKeyword("setLogLevelConsole"); registerKeyword("lc"); - description = "Command to set the console log level. Usage: setLogLevelConsole {off | fatal | error | warn | info | debug | trace}"; + description = "Command to set the console log level. Usage: setLogLevelConsole {{off | fatal | error | warn | info | debug | trace}}"; } bool RamshCommandSetConsoleLogLevel::executeInput(const std::vector& input) @@ -32,7 +32,7 @@ namespace ramses::internal return false; - LOG_INFO(CONTEXT_RAMSH, "Logging Console in level: " << RamsesLogger::GetLogLevelText(level)); + LOG_INFO(CONTEXT_RAMSH, "Logging Console in level: {}", RamsesLogger::GetLogLevelText(level)); GetRamsesLogger().setConsoleLogLevel(level); return true; } diff --git a/src/framework/internal/Ramsh/RamshCommandSetContextLogLevel.cpp b/src/framework/internal/Ramsh/RamshCommandSetContextLogLevel.cpp index b8a62c268..edb0b027e 100644 --- a/src/framework/internal/Ramsh/RamshCommandSetContextLogLevel.cpp +++ b/src/framework/internal/Ramsh/RamshCommandSetContextLogLevel.cpp @@ -37,11 +37,11 @@ namespace ramses::internal for (const auto& info : logger.getAllContextsInformation()) { - LOG_INFO(CONTEXT_RAMSH, info.id << " | " << info.name - << " | " - << static_cast(info.logLevel) - << " | " - << RamsesLogger::GetLogLevelText(info.logLevel)); + LOG_INFO(CONTEXT_RAMSH, "{} | {} | {} | {}", + info.id, + info.name, + static_cast(info.logLevel), + RamsesLogger::GetLogLevelText(info.logLevel)); } return true; } diff --git a/src/framework/internal/Ramsh/RamshCommunicationChannelConsole.cpp b/src/framework/internal/Ramsh/RamshCommunicationChannelConsole.cpp index 790dabcfa..3d36175e5 100644 --- a/src/framework/internal/Ramsh/RamshCommunicationChannelConsole.cpp +++ b/src/framework/internal/Ramsh/RamshCommunicationChannelConsole.cpp @@ -35,7 +35,7 @@ namespace ramses::internal : m_ramsh(ramsh) , m_prompt(std::move(prompt)) , m_pausePrompt(false) - , m_checkInputThread("R_Ramsh_Console") + , m_checkInputThread("Ramsh_Console") , m_nextCommandFromHistory(0) , m_interactiveMode(!PlatformEnvironmentVariables::HasEnvVar("DISABLE_RAMSH_INTERACTIVE_MODE")) , m_console(std::move(consoleInput)) diff --git a/src/framework/internal/Ramsh/RamshCommunicationChannelConsoleSignalHandler.cpp b/src/framework/internal/Ramsh/RamshCommunicationChannelConsoleSignalHandler.cpp index e90481764..6627686f5 100644 --- a/src/framework/internal/Ramsh/RamshCommunicationChannelConsoleSignalHandler.cpp +++ b/src/framework/internal/Ramsh/RamshCommunicationChannelConsoleSignalHandler.cpp @@ -52,7 +52,7 @@ namespace ramses::internal auto enumSignal = static_cast(sig); const auto signal = PlatformSignal::SignalToString(enumSignal); - LOG_WARN_P(CONTEXT_RAMSH, "Received signal {}", signal); + LOG_WARN(CONTEXT_RAMSH, "Received signal {}", signal); for (auto c : m_consoles) { c->stopThread(); diff --git a/src/framework/internal/Ramsh/RamshCommunicationChannelDLT.cpp b/src/framework/internal/Ramsh/RamshCommunicationChannelDLT.cpp index 7ed5fa8b3..8f719d575 100644 --- a/src/framework/internal/Ramsh/RamshCommunicationChannelDLT.cpp +++ b/src/framework/internal/Ramsh/RamshCommunicationChannelDLT.cpp @@ -20,8 +20,8 @@ namespace ramses::internal { std::string incoming{static_cast(data), 0, length - 1};//use length to avoid unterminated strings copied to target buffer - LOG_DEBUG(CONTEXT_RAMSH, "Received dlt injection with service id " << sid << ", length is " << length); - LOG_INFO(CONTEXT_RAMSH, "Calling command '" << incoming << "' received from dlt injection"); + LOG_DEBUG(CONTEXT_RAMSH, "Received dlt injection with service id {}, length is {}", sid, length); + LOG_INFO(CONTEXT_RAMSH, "Calling command '{}' received from dlt injection", incoming); RamshCommunicationChannelDLT::GetInstance().processInput(incoming); diff --git a/src/framework/internal/SceneGraph/Scene/ActionCollectingScene.cpp b/src/framework/internal/SceneGraph/Scene/ActionCollectingScene.cpp index 7d316923e..4d2cbde84 100644 --- a/src/framework/internal/SceneGraph/Scene/ActionCollectingScene.cpp +++ b/src/framework/internal/SceneGraph/Scene/ActionCollectingScene.cpp @@ -603,6 +603,12 @@ namespace ramses::internal m_creator.releaseRenderBuffer(handle); } + void ActionCollectingScene::setRenderBufferProperties(RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount) + { + ResourceChangeCollectingScene::setRenderBufferProperties(handle, width, height, sampleCount); + m_creator.setRenderBufferProperties(handle, width, height, sampleCount); + } + void ActionCollectingScene::addRenderTargetRenderBuffer(RenderTargetHandle targetHandle, RenderBufferHandle bufferHandle) { ResourceChangeCollectingScene::addRenderTargetRenderBuffer(targetHandle, bufferHandle); diff --git a/src/framework/internal/SceneGraph/Scene/ActionCollectingScene.h b/src/framework/internal/SceneGraph/Scene/ActionCollectingScene.h index 005caa36b..cf8a75e9a 100644 --- a/src/framework/internal/SceneGraph/Scene/ActionCollectingScene.h +++ b/src/framework/internal/SceneGraph/Scene/ActionCollectingScene.h @@ -141,6 +141,7 @@ namespace ramses::internal // Render buffers RenderBufferHandle allocateRenderBuffer (const RenderBuffer& renderBuffer, RenderBufferHandle handle) override; void releaseRenderBuffer (RenderBufferHandle handle) override; + void setRenderBufferProperties (RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount) override; void addRenderTargetRenderBuffer (RenderTargetHandle targetHandle, RenderBufferHandle bufferHandle) override; // Data buffers diff --git a/src/framework/internal/SceneGraph/Scene/ESceneActionId.h b/src/framework/internal/SceneGraph/Scene/ESceneActionId.h index 839360990..239352c65 100644 --- a/src/framework/internal/SceneGraph/Scene/ESceneActionId.h +++ b/src/framework/internal/SceneGraph/Scene/ESceneActionId.h @@ -133,6 +133,7 @@ namespace ramses::internal AddRenderTargetRenderBuffer, AllocateRenderBuffer, ReleaseRenderBuffer, + SetRenderBufferProperties, // data links AllocateDataSlot, @@ -323,6 +324,7 @@ case ENUMVALUE: return #ENUMVALUE CreateNameForEnumID(ESceneActionId::AddRenderTargetRenderBuffer); CreateNameForEnumID(ESceneActionId::AllocateRenderBuffer); CreateNameForEnumID(ESceneActionId::ReleaseRenderBuffer); + CreateNameForEnumID(ESceneActionId::SetRenderBufferProperties); // data links CreateNameForEnumID(ESceneActionId::AllocateDataSlot); diff --git a/src/framework/internal/SceneGraph/Scene/ResourceChangeCollectingScene.cpp b/src/framework/internal/SceneGraph/Scene/ResourceChangeCollectingScene.cpp index a56ffc46c..7ce3eb356 100644 --- a/src/framework/internal/SceneGraph/Scene/ResourceChangeCollectingScene.cpp +++ b/src/framework/internal/SceneGraph/Scene/ResourceChangeCollectingScene.cpp @@ -131,6 +131,13 @@ namespace ramses::internal m_sceneResourceActions.push_back({ handle.asMemoryHandle(), ESceneResourceAction_DestroyRenderBuffer }); } + void ResourceChangeCollectingScene::setRenderBufferProperties(RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount) + { + TransformationCachedScene::setRenderBufferProperties(handle, width, height, sampleCount); + m_sceneResourceActions.push_back({ handle.asMemoryHandle(), ESceneResourceAction_UpdateRenderBufferProperties }); + m_resourcesChanged = true; + } + BlitPassHandle ResourceChangeCollectingScene::allocateBlitPass(RenderBufferHandle sourceRenderBufferHandle, RenderBufferHandle destinationRenderBufferHandle, BlitPassHandle passHandle /*= BlitPassHandle::Invalid()*/) { const BlitPassHandle newHandle = TransformationCachedScene::allocateBlitPass(sourceRenderBufferHandle, destinationRenderBufferHandle, passHandle); diff --git a/src/framework/internal/SceneGraph/Scene/ResourceChangeCollectingScene.h b/src/framework/internal/SceneGraph/Scene/ResourceChangeCollectingScene.h index 3804a7050..f4cf43765 100644 --- a/src/framework/internal/SceneGraph/Scene/ResourceChangeCollectingScene.h +++ b/src/framework/internal/SceneGraph/Scene/ResourceChangeCollectingScene.h @@ -43,6 +43,7 @@ namespace ramses::internal RenderBufferHandle allocateRenderBuffer(const RenderBuffer& renderBuffer, RenderBufferHandle handle) override; void releaseRenderBuffer(RenderBufferHandle handle) override; + void setRenderBufferProperties(RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount) override; BlitPassHandle allocateBlitPass(RenderBufferHandle sourceRenderBufferHandle, RenderBufferHandle destinationRenderBufferHandle, BlitPassHandle passHandle) override; void releaseBlitPass(BlitPassHandle handle) override; diff --git a/src/framework/internal/SceneGraph/Scene/ResourceChanges.cpp b/src/framework/internal/SceneGraph/Scene/ResourceChanges.cpp index 9e0519f32..991566f7d 100644 --- a/src/framework/internal/SceneGraph/Scene/ResourceChanges.cpp +++ b/src/framework/internal/SceneGraph/Scene/ResourceChanges.cpp @@ -25,58 +25,12 @@ namespace ramses::internal && m_sceneResourceActions.empty(); } - template - void putDataArray(SceneActionCollection& action, const std::vector& dataArray) - { - const auto numElements = static_cast(dataArray.size()); - action.write(numElements); - if (numElements > 0u) - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) TODO(tobias) questionable if correct because ELEMENTTYPE not POD - const auto* rawData = reinterpret_cast(dataArray.data()); - const uint32_t size = numElements * sizeof(ELEMENTTYPE); - action.write(rawData, size); - } - } - - template - void getDataArray(SceneActionCollection::SceneActionReader& action, std::vector& dataArray) - { - uint32_t numElements = 0u; - action.read(numElements); - - if (numElements > 0u) - { - const std::byte* rawData = nullptr; - uint32_t size = 0u; - action.readWithoutCopy(rawData, size); - - dataArray.resize(numElements); - PlatformMemory::Copy(&dataArray.front(), rawData, size); - } - assert(dataArray.size() == numElements); - } - template size_t estimatePutDataArraySize(const std::vector& dataArray) { return sizeof(uint32_t) + sizeof(ELEMENTTYPE) * dataArray.size(); } - void ResourceChanges::putToSceneAction(SceneActionCollection& action) const - { - putDataArray(action, m_resourcesAdded); - putDataArray(action, m_resourcesRemoved); - putDataArray(action, m_sceneResourceActions); - } - - void ResourceChanges::getFromSceneAction(SceneActionCollection::SceneActionReader& action) - { - getDataArray(action, m_resourcesAdded); - getDataArray(action, m_resourcesRemoved); - getDataArray(action, m_sceneResourceActions); - } - size_t ResourceChanges::getPutSizeEstimate() const { return estimatePutDataArraySize(m_resourcesAdded) + diff --git a/src/framework/internal/SceneGraph/Scene/ResourceChanges.h b/src/framework/internal/SceneGraph/Scene/ResourceChanges.h index fd62bbafe..eb372dce6 100644 --- a/src/framework/internal/SceneGraph/Scene/ResourceChanges.h +++ b/src/framework/internal/SceneGraph/Scene/ResourceChanges.h @@ -22,6 +22,7 @@ namespace ramses::internal ESceneResourceAction_CreateRenderBuffer, ESceneResourceAction_DestroyRenderBuffer, + ESceneResourceAction_UpdateRenderBufferProperties, ESceneResourceAction_CreateRenderTarget, ESceneResourceAction_DestroyRenderTarget, @@ -69,11 +70,9 @@ namespace ramses::internal struct ResourceChanges { - void clear(); - [[nodiscard]] bool empty() const; - void putToSceneAction(SceneActionCollection& action) const; - void getFromSceneAction(SceneActionCollection::SceneActionReader& action); - [[nodiscard]] size_t getPutSizeEstimate() const; + void clear(); + [[nodiscard]] bool empty() const; + [[nodiscard]] size_t getPutSizeEstimate() const; ResourceContentHashVector m_resourcesAdded; ResourceContentHashVector m_resourcesRemoved; @@ -98,6 +97,7 @@ namespace ramses::internal "Invalid", "CreateRenderBuffer", "DestroyRenderBuffer", + "UpdateRenderBufferProperties", "CreateRenderTarget", "DestroyRenderTarget", "CreateBlitPass", diff --git a/src/framework/internal/SceneGraph/Scene/Scene.cpp b/src/framework/internal/SceneGraph/Scene/Scene.cpp index 4f29c2235..af317a2b7 100644 --- a/src/framework/internal/SceneGraph/Scene/Scene.cpp +++ b/src/framework/internal/SceneGraph/Scene/Scene.cpp @@ -179,6 +179,16 @@ namespace ramses::internal m_renderBuffers.release(handle); } + template class MEMORYPOOL> + void SceneT::setRenderBufferProperties(RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount) + { + assert(m_renderBuffers.isAllocated(handle)); + auto& rb = *m_renderBuffers.getMemory(handle); + rb.width = width; + rb.height = height; + rb.sampleCount = sampleCount; + } + template class MEMORYPOOL> uint32_t SceneT::getRenderBufferCount() const { diff --git a/src/framework/internal/SceneGraph/Scene/Scene.h b/src/framework/internal/SceneGraph/Scene/Scene.h index f29f02c28..473a5e4d8 100644 --- a/src/framework/internal/SceneGraph/Scene/Scene.h +++ b/src/framework/internal/SceneGraph/Scene/Scene.h @@ -65,10 +65,10 @@ namespace ramses::internal explicit SceneT(const SceneInfo& sceneInfo = SceneInfo()); - void preallocateSceneSize (const SceneSizeInformation& sizeInfo) override; + void preallocateSceneSize (const SceneSizeInformation& sizeInfo) override; - [[nodiscard]] SceneId getSceneId () const final override; - [[nodiscard]] const std::string& getName () const final override; + [[nodiscard]] SceneId getSceneId () const final override; + [[nodiscard]] const std::string& getName () const final override; void setEffectTimeSync(FlushTime::Clock::time_point t) override; [[nodiscard]] FlushTime::Clock::time_point getEffectTimeSync() const override; @@ -76,8 +76,8 @@ namespace ramses::internal // Renderables RenderableHandle allocateRenderable (NodeHandle nodeHandle, RenderableHandle handle) override; void releaseRenderable (RenderableHandle renderableHandle) override; - [[nodiscard]] bool isRenderableAllocated (RenderableHandle renderableHandle) const final override; - [[nodiscard]] uint32_t getRenderableCount () const final override; + [[nodiscard]] bool isRenderableAllocated (RenderableHandle renderableHandle) const final override; + [[nodiscard]] uint32_t getRenderableCount () const final override; void setRenderableDataInstance (RenderableHandle renderableHandle, ERenderableDataSlotType slot, DataInstanceHandle newDataInstance) override; void setRenderableStartIndex (RenderableHandle renderableHandle, uint32_t startIndex) override; void setRenderableIndexCount (RenderableHandle renderableHandle, uint32_t indexCount) override; @@ -85,14 +85,14 @@ namespace ramses::internal void setRenderableVisibility (RenderableHandle renderableHandle, EVisibilityMode visibility) override; void setRenderableInstanceCount (RenderableHandle renderableHandle, uint32_t instanceCount) override; void setRenderableStartVertex (RenderableHandle renderableHandle, uint32_t startVertex) override; - [[nodiscard]] const Renderable& getRenderable (RenderableHandle renderableHandle) const final override; - [[nodiscard]] const RenderableMemoryPool& getRenderables () const; + [[nodiscard]] const Renderable& getRenderable (RenderableHandle renderableHandle) const final override; + [[nodiscard]] const RenderableMemoryPool& getRenderables () const; // Render state RenderStateHandle allocateRenderState (RenderStateHandle stateHandle) override; void releaseRenderState (RenderStateHandle stateHandle) override; - [[nodiscard]] bool isRenderStateAllocated (RenderStateHandle stateHandle) const final override; - [[nodiscard]] uint32_t getRenderStateCount () const final override; + [[nodiscard]] bool isRenderStateAllocated (RenderStateHandle stateHandle) const final override; + [[nodiscard]] uint32_t getRenderStateCount () const final override; void setRenderStateBlendFactors (RenderStateHandle stateHandle, EBlendFactor srcColor, EBlendFactor destColor, EBlendFactor srcAlpha, EBlendFactor destAlpha) override; void setRenderStateBlendOperations (RenderStateHandle stateHandle, EBlendOperation operationColor, EBlendOperation operationAlpha) override; void setRenderStateBlendColor (RenderStateHandle stateHandle, const glm::vec4& color) override; @@ -104,57 +104,57 @@ namespace ramses::internal void setRenderStateStencilFunc (RenderStateHandle stateHandle, EStencilFunc func, uint8_t ref, uint8_t mask) override; void setRenderStateStencilOps (RenderStateHandle stateHandle, EStencilOp sfail, EStencilOp dpfail, EStencilOp dppass) override; void setRenderStateColorWriteMask (RenderStateHandle stateHandle, ColorWriteMask colorMask) override; - [[nodiscard]] const RenderState& getRenderState (RenderStateHandle stateHandle) const final override; - [[nodiscard]] const RenderStateMemoryPool& getRenderStates () const; + [[nodiscard]] const RenderState& getRenderState (RenderStateHandle stateHandle) const final override; + [[nodiscard]] const RenderStateMemoryPool& getRenderStates () const; // Camera CameraHandle allocateCamera (ECameraProjectionType type, NodeHandle nodeHandle, DataInstanceHandle dataInstance, CameraHandle handle) override; void releaseCamera (CameraHandle cameraHandle) override; - [[nodiscard]] bool isCameraAllocated (CameraHandle handle) const final override; - [[nodiscard]] uint32_t getCameraCount () const final override; - [[nodiscard]] const Camera& getCamera (CameraHandle cameraHandle) const final override; - [[nodiscard]] const CameraMemoryPool& getCameras () const; + [[nodiscard]] bool isCameraAllocated (CameraHandle handle) const final override; + [[nodiscard]] uint32_t getCameraCount () const final override; + [[nodiscard]] const Camera& getCamera (CameraHandle cameraHandle) const final override; + [[nodiscard]] const CameraMemoryPool& getCameras () const; // Nodes NodeHandle allocateNode (uint32_t childrenCount, NodeHandle handle) override; void releaseNode (NodeHandle nodeHandle) override; - [[nodiscard]] bool isNodeAllocated (NodeHandle node) const final override; - [[nodiscard]] uint32_t getNodeCount () const final override; - [[nodiscard]] NodeHandle getParent (NodeHandle nodeHandle) const final override; + [[nodiscard]] bool isNodeAllocated (NodeHandle node) const final override; + [[nodiscard]] uint32_t getNodeCount () const final override; + [[nodiscard]] NodeHandle getParent (NodeHandle nodeHandle) const final override; void addChildToNode (NodeHandle parent, NodeHandle child) override; void removeChildFromNode (NodeHandle parent, NodeHandle child) override; - [[nodiscard]] uint32_t getChildCount (NodeHandle parent) const final override; - [[nodiscard]] NodeHandle getChild (NodeHandle parent, uint32_t childNumber) const final override; - [[nodiscard]] const NodeMemoryPool& getNodes () const; + [[nodiscard]] uint32_t getChildCount (NodeHandle parent) const final override; + [[nodiscard]] NodeHandle getChild (NodeHandle parent, uint32_t childNumber) const final override; + [[nodiscard]] const NodeMemoryPool& getNodes () const; // Transformation TransformHandle allocateTransform (NodeHandle nodeHandle, TransformHandle handle) override; void releaseTransform (TransformHandle transform) override; - [[nodiscard]] uint32_t getTransformCount () const final override; - [[nodiscard]] bool isTransformAllocated (TransformHandle transformHandle) const final override; - [[nodiscard]] NodeHandle getTransformNode (TransformHandle handle) const final override; - [[nodiscard]] const glm::vec3& getTranslation (TransformHandle handle) const final override; - [[nodiscard]] const glm::vec4& getRotation (TransformHandle handle) const final override; - [[nodiscard]] ERotationType getRotationType (TransformHandle handle) const final override; - [[nodiscard]] const glm::vec3& getScaling (TransformHandle handle) const final override; + [[nodiscard]] uint32_t getTransformCount () const final override; + [[nodiscard]] bool isTransformAllocated (TransformHandle transformHandle) const final override; + [[nodiscard]] NodeHandle getTransformNode (TransformHandle handle) const final override; + [[nodiscard]] const glm::vec3& getTranslation (TransformHandle handle) const final override; + [[nodiscard]] const glm::vec4& getRotation (TransformHandle handle) const final override; + [[nodiscard]] ERotationType getRotationType (TransformHandle handle) const final override; + [[nodiscard]] const glm::vec3& getScaling (TransformHandle handle) const final override; void setTranslation (TransformHandle handle, const glm::vec3& translation) override; void setRotation (TransformHandle handle, const glm::vec4& rotation, ERotationType rotationType) override; void setScaling (TransformHandle handle, const glm::vec3& scaling) override; - [[nodiscard]] const TransformMemoryPool& getTransforms () const; + [[nodiscard]] const TransformMemoryPool& getTransforms () const; DataLayoutHandle allocateDataLayout (const DataFieldInfoVector& dataFields, const ResourceContentHash& effectHash, DataLayoutHandle handle) override; void releaseDataLayout (DataLayoutHandle layoutHandle) override; - [[nodiscard]] bool isDataLayoutAllocated (DataLayoutHandle layoutHandle) const final override; - [[nodiscard]] uint32_t getDataLayoutCount () const final override; - [[nodiscard]] const DataLayout& getDataLayout (DataLayoutHandle layoutHandle) const final override; - [[nodiscard]] const DataLayoutMemoryPool& getDataLayouts () const; + [[nodiscard]] bool isDataLayoutAllocated (DataLayoutHandle layoutHandle) const final override; + [[nodiscard]] uint32_t getDataLayoutCount () const final override; + [[nodiscard]] const DataLayout& getDataLayout (DataLayoutHandle layoutHandle) const final override; + [[nodiscard]] const DataLayoutMemoryPool& getDataLayouts () const; DataInstanceHandle allocateDataInstance (DataLayoutHandle finishedLayoutHandle, DataInstanceHandle instanceHandle) override; void releaseDataInstance (DataInstanceHandle containerHandle) override; - [[nodiscard]] bool isDataInstanceAllocated (DataInstanceHandle containerHandle) const final override; - [[nodiscard]] uint32_t getDataInstanceCount () const final override; - [[nodiscard]] DataLayoutHandle getLayoutOfDataInstance (DataInstanceHandle containerHandle) const final override; - [[nodiscard]] const DataInstanceMemoryPool& getDataInstances () const; + [[nodiscard]] bool isDataInstanceAllocated (DataInstanceHandle containerHandle) const final override; + [[nodiscard]] uint32_t getDataInstanceCount () const final override; + [[nodiscard]] DataLayoutHandle getLayoutOfDataInstance (DataInstanceHandle containerHandle) const final override; + [[nodiscard]] const DataInstanceMemoryPool& getDataInstances() const; [[nodiscard]] const float* getDataFloatArray (DataInstanceHandle containerHandle, DataFieldHandle field) const final override; [[nodiscard]] const glm::vec2* getDataVector2fArray (DataInstanceHandle containerHandle, DataFieldHandle field) const final override; @@ -218,28 +218,28 @@ namespace ramses::internal // Texture sampler TextureSamplerHandle allocateTextureSampler (const TextureSampler& sampler, TextureSamplerHandle handle) override; void releaseTextureSampler (TextureSamplerHandle handle) override; - [[nodiscard]] bool isTextureSamplerAllocated (TextureSamplerHandle handle) const final override; - [[nodiscard]] uint32_t getTextureSamplerCount () const final override; - [[nodiscard]] const TextureSampler& getTextureSampler (TextureSamplerHandle handle) const final override; - [[nodiscard]] const TextureSamplerMemoryPool& getTextureSamplers () const; + [[nodiscard]] bool isTextureSamplerAllocated (TextureSamplerHandle handle) const final override; + [[nodiscard]] uint32_t getTextureSamplerCount () const final override; + [[nodiscard]] const TextureSampler& getTextureSampler (TextureSamplerHandle handle) const final override; + [[nodiscard]] const TextureSamplerMemoryPool& getTextureSamplers() const; // Render groups RenderGroupHandle allocateRenderGroup (uint32_t renderableCount, uint32_t nestedGroupCount, RenderGroupHandle groupHandle) override; void releaseRenderGroup (RenderGroupHandle groupHandle) override; - [[nodiscard]] bool isRenderGroupAllocated (RenderGroupHandle groupHandle) const final override; - [[nodiscard]] uint32_t getRenderGroupCount () const final override; + [[nodiscard]] bool isRenderGroupAllocated (RenderGroupHandle groupHandle) const final override; + [[nodiscard]] uint32_t getRenderGroupCount () const final override; void addRenderableToRenderGroup (RenderGroupHandle groupHandle, RenderableHandle renderableHandle, int32_t order) override; void removeRenderableFromRenderGroup (RenderGroupHandle groupHandle, RenderableHandle renderableHandle) override; void addRenderGroupToRenderGroup (RenderGroupHandle groupHandleParent, RenderGroupHandle groupHandleChild, int32_t order) override; void removeRenderGroupFromRenderGroup(RenderGroupHandle groupHandleParent, RenderGroupHandle groupHandleChild) override; - [[nodiscard]] const RenderGroup& getRenderGroup (RenderGroupHandle groupHandle) const final override; - [[nodiscard]] const RenderGroupMemoryPool& getRenderGroups () const; + [[nodiscard]] const RenderGroup& getRenderGroup (RenderGroupHandle groupHandle) const final override; + [[nodiscard]] const RenderGroupMemoryPool& getRenderGroups() const; //Render pass RenderPassHandle allocateRenderPass (uint32_t renderGroupCount, RenderPassHandle passHandle) override; void releaseRenderPass (RenderPassHandle passHandle) override; - [[nodiscard]] bool isRenderPassAllocated (RenderPassHandle pass) const final override; - [[nodiscard]] uint32_t getRenderPassCount () const final override; + [[nodiscard]] bool isRenderPassAllocated (RenderPassHandle pass) const final override; + [[nodiscard]] uint32_t getRenderPassCount () const final override; void setRenderPassClearColor (RenderPassHandle passHandle, const glm::vec4& clearColor) override; void setRenderPassClearFlag (RenderPassHandle passHandle, ClearFlags clearFlag) override; void setRenderPassCamera (RenderPassHandle passHandle, CameraHandle cameraHandle) override; @@ -250,93 +250,94 @@ namespace ramses::internal void retriggerRenderPassRenderOnce (RenderPassHandle passHandle) override; void addRenderGroupToRenderPass (RenderPassHandle passHandle, RenderGroupHandle groupHandle, int32_t order) override; void removeRenderGroupFromRenderPass (RenderPassHandle passHandle, RenderGroupHandle groupHandle) override; - [[nodiscard]] const RenderPass& getRenderPass (RenderPassHandle passHandle) const final override; - [[nodiscard]] const RenderPassMemoryPool& getRenderPasses () const; + [[nodiscard]] const RenderPass& getRenderPass (RenderPassHandle passHandle) const final override; + [[nodiscard]] const RenderPassMemoryPool& getRenderPasses() const; //Blit pass BlitPassHandle allocateBlitPass (RenderBufferHandle sourceRenderBufferHandle, RenderBufferHandle destinationRenderBufferHandle, BlitPassHandle passHandle) override; void releaseBlitPass (BlitPassHandle passHandle) override; - [[nodiscard]] bool isBlitPassAllocated (BlitPassHandle passHandle) const final override; - [[nodiscard]] uint32_t getBlitPassCount () const final override; + [[nodiscard]] bool isBlitPassAllocated (BlitPassHandle passHandle) const final override; + [[nodiscard]] uint32_t getBlitPassCount () const final override; void setBlitPassRenderOrder (BlitPassHandle passHandle, int32_t renderOrder) override; void setBlitPassEnabled (BlitPassHandle passHandle, bool isEnabled) override; void setBlitPassRegions (BlitPassHandle passHandle, const PixelRectangle& sourceRegion, const PixelRectangle& destinationRegion) override; - [[nodiscard]] const BlitPass& getBlitPass (BlitPassHandle passHandle) const final override; - [[nodiscard]] const BlitPassMemoryPool& getBlitPasses () const; + [[nodiscard]] const BlitPass& getBlitPass (BlitPassHandle passHandle) const final override; + [[nodiscard]] const BlitPassMemoryPool& getBlitPasses () const; //Pickable object PickableObjectHandle allocatePickableObject (DataBufferHandle geometryHandle, NodeHandle nodeHandle, PickableObjectId id, PickableObjectHandle pickableHandle) override; void releasePickableObject (PickableObjectHandle pickableHandle) override; - [[nodiscard]] bool isPickableObjectAllocated (PickableObjectHandle pickableHandle) const final override; - [[nodiscard]] uint32_t getPickableObjectCount () const final override; + [[nodiscard]] bool isPickableObjectAllocated (PickableObjectHandle pickableHandle) const final override; + [[nodiscard]] uint32_t getPickableObjectCount () const final override; void setPickableObjectId (PickableObjectHandle pickableHandle, PickableObjectId id) override; void setPickableObjectCamera (PickableObjectHandle pickableHandle, CameraHandle cameraHandle) override; void setPickableObjectEnabled (PickableObjectHandle pickableHandle, bool isEnabled) override; - [[nodiscard]] const PickableObject& getPickableObject (PickableObjectHandle pickableHandle) const final override; - [[nodiscard]] const PickableObjectMemoryPool& getPickableObjects () const; + [[nodiscard]] const PickableObject& getPickableObject (PickableObjectHandle pickableHandle) const final override; + [[nodiscard]] const PickableObjectMemoryPool& getPickableObjects() const; // Render targets RenderTargetHandle allocateRenderTarget (RenderTargetHandle targetHandle) override; void releaseRenderTarget (RenderTargetHandle targetHandle) override; - [[nodiscard]] bool isRenderTargetAllocated (RenderTargetHandle targetHandle) const final override; - [[nodiscard]] uint32_t getRenderTargetCount () const final override; + [[nodiscard]] bool isRenderTargetAllocated (RenderTargetHandle targetHandle) const final override; + [[nodiscard]] uint32_t getRenderTargetCount () const final override; void addRenderTargetRenderBuffer (RenderTargetHandle targetHandle, RenderBufferHandle bufferHandle) override; - [[nodiscard]] uint32_t getRenderTargetRenderBufferCount(RenderTargetHandle targetHandle) const final override; - [[nodiscard]] RenderBufferHandle getRenderTargetRenderBuffer (RenderTargetHandle targetHandle, uint32_t bufferIndex) const final override; - [[nodiscard]] const RenderTargetMemoryPool& getRenderTargets () const; + [[nodiscard]] uint32_t getRenderTargetRenderBufferCount(RenderTargetHandle targetHandle) const final override; + [[nodiscard]] RenderBufferHandle getRenderTargetRenderBuffer(RenderTargetHandle targetHandle, uint32_t bufferIndex) const final override; + [[nodiscard]] const RenderTargetMemoryPool& getRenderTargets() const; // Render buffers RenderBufferHandle allocateRenderBuffer (const RenderBuffer& renderBuffer, RenderBufferHandle handle) override; void releaseRenderBuffer (RenderBufferHandle handle) override; - [[nodiscard]] bool isRenderBufferAllocated (RenderBufferHandle handle) const final override; - [[nodiscard]] uint32_t getRenderBufferCount () const final override; - [[nodiscard]] const RenderBuffer& getRenderBuffer (RenderBufferHandle handle) const final override; - [[nodiscard]] const RenderBufferMemoryPool& getRenderBuffers () const; + void setRenderBufferProperties (RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount) override; + [[nodiscard]] bool isRenderBufferAllocated (RenderBufferHandle handle) const final override; + [[nodiscard]] uint32_t getRenderBufferCount () const final override; + [[nodiscard]] const RenderBuffer& getRenderBuffer (RenderBufferHandle handle) const final override; + [[nodiscard]] const RenderBufferMemoryPool& getRenderBuffers() const; // Data buffers DataBufferHandle allocateDataBuffer (EDataBufferType dataBufferType, EDataType dataType, uint32_t maximumSizeInBytes, DataBufferHandle handle) override; void releaseDataBuffer (DataBufferHandle handle) override; - [[nodiscard]] uint32_t getDataBufferCount () const final override; + [[nodiscard]] uint32_t getDataBufferCount () const final override; void updateDataBuffer (DataBufferHandle handle, uint32_t offsetInBytes, uint32_t dataSizeInBytes, const std::byte* data) override; - [[nodiscard]] bool isDataBufferAllocated (DataBufferHandle handle) const final override; - [[nodiscard]] const GeometryDataBuffer& getDataBuffer (DataBufferHandle handle) const final override; - [[nodiscard]] const DataBufferMemoryPool& getDataBuffers () const; + [[nodiscard]] bool isDataBufferAllocated (DataBufferHandle handle) const final override; + [[nodiscard]] const GeometryDataBuffer& getDataBuffer (DataBufferHandle handle) const final override; + [[nodiscard]] const DataBufferMemoryPool& getDataBuffers() const; //Texture buffers TextureBufferHandle allocateTextureBuffer (EPixelStorageFormat textureFormat, const MipMapDimensions& mipMapDimensions, TextureBufferHandle handle) override; void releaseTextureBuffer (TextureBufferHandle handle) override; - [[nodiscard]] bool isTextureBufferAllocated (TextureBufferHandle handle) const final override; - [[nodiscard]] uint32_t getTextureBufferCount () const final override; + [[nodiscard]] bool isTextureBufferAllocated (TextureBufferHandle handle) const final override; + [[nodiscard]] uint32_t getTextureBufferCount () const final override; void updateTextureBuffer (TextureBufferHandle handle, uint32_t mipLevel, uint32_t x, uint32_t y, uint32_t width, uint32_t height, const std::byte* data) override; - [[nodiscard]] const TextureBuffer& getTextureBuffer (TextureBufferHandle handle) const final override; - [[nodiscard]] const TextureBufferMemoryPool& getTextureBuffers () const; + [[nodiscard]] const TextureBuffer& getTextureBuffer (TextureBufferHandle handle) const final override; + [[nodiscard]] const TextureBufferMemoryPool& getTextureBuffers() const; DataSlotHandle allocateDataSlot (const DataSlot& dataSlot, DataSlotHandle handle) override; void releaseDataSlot (DataSlotHandle handle) override; void setDataSlotTexture (DataSlotHandle handle, const ResourceContentHash& texture) override; - [[nodiscard]] bool isDataSlotAllocated (DataSlotHandle handle) const final override; - [[nodiscard]] uint32_t getDataSlotCount () const final override; - [[nodiscard]] const DataSlot& getDataSlot (DataSlotHandle handle) const final override; - [[nodiscard]] const DataSlotMemoryPool& getDataSlots () const; + [[nodiscard]] bool isDataSlotAllocated (DataSlotHandle handle) const final override; + [[nodiscard]] uint32_t getDataSlotCount () const final override; + [[nodiscard]] const DataSlot& getDataSlot (DataSlotHandle handle) const final override; + [[nodiscard]] const DataSlotMemoryPool& getDataSlots () const; SceneReferenceHandle allocateSceneReference (SceneId sceneId, SceneReferenceHandle handle) override; void releaseSceneReference (SceneReferenceHandle handle) override; void requestSceneReferenceState (SceneReferenceHandle handle, RendererSceneState state) override; void requestSceneReferenceFlushNotifications(SceneReferenceHandle handle, bool enable) override; void setSceneReferenceRenderOrder (SceneReferenceHandle handle, int32_t renderOrder) override; - [[nodiscard]] bool isSceneReferenceAllocated (SceneReferenceHandle handle) const final override; - [[nodiscard]] uint32_t getSceneReferenceCount () const final override; - [[nodiscard]] const SceneReference& getSceneReference (SceneReferenceHandle handle) const final override; - [[nodiscard]] const SceneReferenceMemoryPool& getSceneReferences () const; + [[nodiscard]] bool isSceneReferenceAllocated (SceneReferenceHandle handle) const final override; + [[nodiscard]] uint32_t getSceneReferenceCount () const final override; + [[nodiscard]] const SceneReference& getSceneReference (SceneReferenceHandle handle) const final override; + [[nodiscard]] const SceneReferenceMemoryPool& getSceneReferences() const; - [[nodiscard]] SceneSizeInformation getSceneSizeInformation () const final override; + [[nodiscard]] SceneSizeInformation getSceneSizeInformation() const final override; protected: - [[nodiscard]] const TopologyNode& getNode (NodeHandle handle) const; - TextureSampler& getTextureSamplerInternal (TextureSamplerHandle handle); - RenderPass& getRenderPassInternal (RenderPassHandle handle); - RenderGroup& getRenderGroupInternal (RenderGroupHandle handle); - [[nodiscard]] const TopologyTransform& getTransform (TransformHandle handle) const; + [[nodiscard]] const TopologyNode& getNode (NodeHandle handle) const; + TextureSampler& getTextureSamplerInternal (TextureSamplerHandle handle); + RenderPass& getRenderPassInternal (RenderPassHandle handle); + RenderGroup& getRenderGroupInternal (RenderGroupHandle handle); + [[nodiscard]] const TopologyTransform& getTransform (TransformHandle handle) const; private: template diff --git a/src/framework/internal/SceneGraph/Scene/SceneActionApplier.cpp b/src/framework/internal/SceneGraph/Scene/SceneActionApplier.cpp index a85668acd..b23b18ad3 100644 --- a/src/framework/internal/SceneGraph/Scene/SceneActionApplier.cpp +++ b/src/framework/internal/SceneGraph/Scene/SceneActionApplier.cpp @@ -43,12 +43,8 @@ namespace ramses::internal { uint32_t childrenCount = 0u; NodeHandle nodeHandle; - std::string objectName; - uint64_t objectId = 0; action.read(childrenCount); action.read(nodeHandle); - action.read(objectName); - action.read(objectId); AssertHandle(scene.allocateNode(childrenCount, nodeHandle), nodeHandle); break; } @@ -103,12 +99,8 @@ namespace ramses::internal { DataLayoutHandle dataLayout; DataInstanceHandle diHandle; - std::string objectName; - uint64_t objectId = 0; action.read(dataLayout); action.read(diHandle); - action.read(objectName); - action.read(objectId); AssertHandle(scene.allocateDataInstance(dataLayout, diHandle), diHandle); break; } @@ -428,14 +420,10 @@ namespace ramses::internal { uint32_t renderableCount = 0u; uint32_t nestedGroupCount = 0u; - std::string objectName; - uint64_t objectId = 0; RenderGroupHandle renderGroup; action.read(renderableCount); action.read(nestedGroupCount); action.read(renderGroup); - action.read(objectName); - action.read(objectId); AssertHandle(scene.allocateRenderGroup(renderableCount, nestedGroupCount, renderGroup), renderGroup); break; } @@ -677,12 +665,8 @@ namespace ramses::internal { uint32_t renderGroupCount = 0u; RenderPassHandle passHandle; - std::string objectName; - uint64_t objectId = 0; action.read(renderGroupCount); action.read(passHandle); - action.read(objectName); - action.read(objectId); AssertHandle(scene.allocateRenderPass(renderGroupCount, passHandle), passHandle); break; } @@ -806,7 +790,7 @@ namespace ramses::internal case ESceneActionId::SetPickableObjectEnabled: { PickableObjectHandle pickableHandle; - bool isEnabled = false; + bool isEnabled = false; action.read(pickableHandle); action.read(isEnabled); scene.setPickableObjectEnabled(pickableHandle, isEnabled); @@ -817,13 +801,9 @@ namespace ramses::internal BlitPassHandle passHandle; RenderBufferHandle sourceRenderbufferHandle; RenderBufferHandle destinationRenderbufferHandle; - std::string objectName; - uint64_t objectId = 0; action.read(sourceRenderbufferHandle); action.read(destinationRenderbufferHandle); action.read(passHandle); - action.read(objectName); - action.read(objectId); AssertHandle(scene.allocateBlitPass(sourceRenderbufferHandle, destinationRenderbufferHandle, passHandle), passHandle); break; } @@ -873,8 +853,6 @@ namespace ramses::internal { TextureSamplerHandle samplerHandle; TextureSampler sampler; - std::string objectName; - uint64_t objectId = 0; action.read(samplerHandle); action.read(sampler.states.m_addressModeU); @@ -894,9 +872,6 @@ namespace ramses::internal action.read(sampler.contentHandle); } - action.read(objectName); - action.read(objectId); - AssertHandle(scene.allocateTextureSampler(sampler, samplerHandle), samplerHandle); break; } @@ -910,11 +885,7 @@ namespace ramses::internal case ESceneActionId::AllocateRenderTarget: { RenderTargetHandle renderTargetHandle; - std::string objectName; - uint64_t objectId = 0; action.read(renderTargetHandle); - action.read(objectName); - action.read(objectId); AssertHandle(scene.allocateRenderTarget(renderTargetHandle), renderTargetHandle); break; } @@ -939,8 +910,6 @@ namespace ramses::internal RenderBufferHandle handle; RenderBuffer renderBuffer; uint32_t enumInt = 0; - std::string objectName; - uint64_t objectId = 0; action.read(renderBuffer.width); action.read(renderBuffer.height); @@ -950,8 +919,6 @@ namespace ramses::internal action.read(enumInt); renderBuffer.accessMode = static_cast(enumInt); action.read(renderBuffer.sampleCount); - action.read(objectName); - action.read(objectId); AssertHandle(scene.allocateRenderBuffer(renderBuffer, handle), handle); break; } @@ -962,6 +929,19 @@ namespace ramses::internal scene.releaseRenderBuffer(handle); break; } + case ESceneActionId::SetRenderBufferProperties: + { + RenderBufferHandle handle; + uint32_t width = 0u; + uint32_t height = 0u; + uint32_t sampleCount = 0u; + action.read(handle); + action.read(width); + action.read(height); + action.read(sampleCount); + scene.setRenderBufferProperties(handle, width, height, sampleCount); + break; + } case ESceneActionId::AllocateDataSlot: { DataSlotHandle dataSlotHandle; @@ -1020,14 +1000,10 @@ namespace ramses::internal uint32_t dataType = 0; uint32_t maximumSizeInBytes = 0; DataBufferHandle handle; - std::string objectName; - uint64_t objectId = 0; action.read(dataBufferType); action.read(dataType); action.read(maximumSizeInBytes); action.read(handle.asMemoryHandleReference()); - action.read(objectName); - action.read(objectId); AssertHandle(scene.allocateDataBuffer(static_cast(dataBufferType), static_cast(dataType), maximumSizeInBytes, handle), handle); break; } @@ -1057,8 +1033,6 @@ namespace ramses::internal uint32_t mipLevelCount = 0; MipMapDimensions mipMapDimensions; TextureBufferHandle handle; - std::string objectName; - uint64_t objectId = 0; action.read(textureFormat); action.read(mipLevelCount); @@ -1072,8 +1046,6 @@ namespace ramses::internal mipMapDimensions.push_back({ width, height }); } action.read(handle); - action.read(objectName); - action.read(objectId); AssertHandle(scene.allocateTextureBuffer(static_cast(textureFormat), mipMapDimensions, handle), handle); break; @@ -1112,12 +1084,8 @@ namespace ramses::internal { SceneReferenceHandle handle; SceneId sceneId; - std::string objectName; - uint64_t objectId = 0; action.read(handle); action.read(sceneId); - action.read(objectName); - action.read(objectId); AssertHandle(scene.allocateSceneReference(sceneId, handle), handle); break; } diff --git a/src/framework/internal/SceneGraph/Scene/SceneActionCollectionCreator.cpp b/src/framework/internal/SceneGraph/Scene/SceneActionCollectionCreator.cpp index ee53e2694..9f7c24924 100644 --- a/src/framework/internal/SceneGraph/Scene/SceneActionCollectionCreator.cpp +++ b/src/framework/internal/SceneGraph/Scene/SceneActionCollectionCreator.cpp @@ -208,8 +208,6 @@ namespace ramses::internal collection.beginWriteSceneAction(ESceneActionId::AllocateDataInstance); collection.write(layoutHandle); collection.write(dataInstanceHandle); - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseTransform(TransformHandle transform) @@ -230,8 +228,6 @@ namespace ramses::internal collection.beginWriteSceneAction(ESceneActionId::AllocateNode); collection.write(childrenCount); collection.write(handle); - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseNode(NodeHandle nodeHandle) @@ -449,8 +445,6 @@ namespace ramses::internal collection.write(renderableCount); collection.write(nestedGroupCount); collection.write(groupHandle); - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseRenderGroup(RenderGroupHandle groupHandle) @@ -494,8 +488,6 @@ namespace ramses::internal collection.beginWriteSceneAction(ESceneActionId::AllocateRenderPass); collection.write(renderGroupCount); collection.write(handle); - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseRenderPass(RenderPassHandle handle) @@ -603,8 +595,6 @@ namespace ramses::internal collection.write(sourceRenderBufferHandle); collection.write(destinationRenderBufferHandle); collection.write(passHandle); - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseBlitPass(BlitPassHandle passHandle) @@ -676,8 +666,6 @@ namespace ramses::internal { collection.write(sampler.contentHandle); } - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseTextureSampler(TextureSamplerHandle handle) @@ -690,8 +678,6 @@ namespace ramses::internal { collection.beginWriteSceneAction(ESceneActionId::AllocateRenderTarget); collection.write(handle); - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseRenderTarget(RenderTargetHandle handle) @@ -716,8 +702,6 @@ namespace ramses::internal collection.write(static_cast(renderBuffer.format)); collection.write(static_cast(renderBuffer.accessMode)); collection.write(renderBuffer.sampleCount); - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseRenderBuffer(RenderBufferHandle handle) @@ -726,6 +710,15 @@ namespace ramses::internal collection.write(handle); } + void SceneActionCollectionCreator::setRenderBufferProperties(RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount) + { + collection.beginWriteSceneAction(ESceneActionId::SetRenderBufferProperties); + collection.write(handle); + collection.write(width); + collection.write(height); + collection.write(sampleCount); + } + void SceneActionCollectionCreator::allocateDataBuffer(EDataBufferType dataBufferType, EDataType dataType, uint32_t maximumSizeInBytes, DataBufferHandle handle) { collection.beginWriteSceneAction(ESceneActionId::AllocateDataBuffer); @@ -733,8 +726,6 @@ namespace ramses::internal collection.write(static_cast(dataType)); collection.write(maximumSizeInBytes); collection.write(handle); - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseDataBuffer(DataBufferHandle handle) @@ -762,8 +753,6 @@ namespace ramses::internal collection.write(size.height); } collection.write(handle); - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseTextureBuffer(TextureBufferHandle handle) @@ -814,8 +803,6 @@ namespace ramses::internal collection.beginWriteSceneAction(ESceneActionId::AllocateSceneReference); collection.write(handle); collection.write(sceneId); - collection.write(std::string{}); - collection.write(uint64_t{}); } void SceneActionCollectionCreator::releaseSceneReference(SceneReferenceHandle handle) @@ -941,5 +928,4 @@ namespace ramses::internal collection.write(sizeInfo.pickableObjectCount); collection.write(sizeInfo.sceneReferenceCount); } - } diff --git a/src/framework/internal/SceneGraph/Scene/SceneActionCollectionCreator.h b/src/framework/internal/SceneGraph/Scene/SceneActionCollectionCreator.h index 303c1e6f2..0ea6bda48 100644 --- a/src/framework/internal/SceneGraph/Scene/SceneActionCollectionCreator.h +++ b/src/framework/internal/SceneGraph/Scene/SceneActionCollectionCreator.h @@ -170,6 +170,7 @@ namespace ramses::internal // Render buffers void allocateRenderBuffer(const RenderBuffer& renderBuffer, RenderBufferHandle handle); void releaseRenderBuffer(RenderBufferHandle handle); + void setRenderBufferProperties(RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount); // Data buffers void allocateDataBuffer(EDataBufferType dataBufferType, EDataType dataType, uint32_t maximumSizeInBytes, DataBufferHandle handle); diff --git a/src/framework/internal/SceneGraph/SceneAPI/IScene.h b/src/framework/internal/SceneGraph/SceneAPI/IScene.h index 9d1e8c482..47fd25ac3 100644 --- a/src/framework/internal/SceneGraph/SceneAPI/IScene.h +++ b/src/framework/internal/SceneGraph/SceneAPI/IScene.h @@ -276,6 +276,7 @@ namespace ramses::internal // Render buffers virtual RenderBufferHandle allocateRenderBuffer (const RenderBuffer& renderBuffer, RenderBufferHandle handle) = 0; virtual void releaseRenderBuffer (RenderBufferHandle handle) = 0; + virtual void setRenderBufferProperties (RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount) = 0; [[nodiscard]] virtual bool isRenderBufferAllocated (RenderBufferHandle handle) const = 0; [[nodiscard]] virtual uint32_t getRenderBufferCount () const = 0; [[nodiscard]] virtual const RenderBuffer& getRenderBuffer (RenderBufferHandle handle) const = 0; diff --git a/src/framework/internal/SceneGraph/SceneAPI/RenderBuffer.h b/src/framework/internal/SceneGraph/SceneAPI/RenderBuffer.h index 010e5d550..ac002fcba 100644 --- a/src/framework/internal/SceneGraph/SceneAPI/RenderBuffer.h +++ b/src/framework/internal/SceneGraph/SceneAPI/RenderBuffer.h @@ -14,30 +14,6 @@ namespace ramses::internal { struct RenderBuffer { - RenderBuffer() = default; - RenderBuffer(uint32_t _width, uint32_t _height, EPixelStorageFormat _format, ERenderBufferAccessMode _accessMode, uint32_t _sampleCount) - : width(_width) - , height(_height) - , format(_format) - , accessMode(_accessMode) - , sampleCount(_sampleCount) - { - } - - bool operator==(const RenderBuffer& other) const - { - return format == other.format - && width == other.width - && height == other.height - && accessMode == other.accessMode - && sampleCount == other.sampleCount; - } - - bool operator!=(const RenderBuffer& other) const - { - return !this->operator==(other); - } - uint32_t width = 0u; uint32_t height = 0u; EPixelStorageFormat format = EPixelStorageFormat::Invalid; diff --git a/src/framework/internal/SceneGraph/SceneUtils/DataInstanceHelper.h b/src/framework/internal/SceneGraph/SceneUtils/DataInstanceHelper.h index 5ceb47d39..94c9259bb 100644 --- a/src/framework/internal/SceneGraph/SceneUtils/DataInstanceHelper.h +++ b/src/framework/internal/SceneGraph/SceneUtils/DataInstanceHelper.h @@ -8,9 +8,9 @@ #pragma once -#include "internal/SceneGraph/SceneAPI/Handles.h" #include "impl/DataTypesImpl.h" - +#include "internal/SceneGraph/SceneAPI/Handles.h" +#include "internal/SceneGraph/SceneUtils/ISceneDataArrayAccessor.h" #include "internal/PlatformAbstraction/VariantWrapper.h" namespace ramses::internal @@ -37,5 +37,16 @@ namespace ramses::internal public: static void GetInstanceFieldData(const IScene& scene, DataInstanceHandle dataInstance, DataFieldHandle dataField, DataInstanceValueVariant& value); static void SetInstanceFieldData(IScene& scene, DataInstanceHandle dataInstance, DataFieldHandle dataField, const DataInstanceValueVariant& value); + + template + static const T& GetReferencedData(const IScene& scene, DataInstanceHandle dataInstance, DataFieldHandle dataField = DataFieldHandle{ 0u }); }; + + template + const T& DataInstanceHelper::GetReferencedData(const IScene& scene, DataInstanceHandle dataInstance, DataFieldHandle dataField) + { + const auto dataRefHandle = scene.getDataReference(dataInstance, dataField); + const T* dataArray = ISceneDataArrayAccessor::GetDataArray(&scene, dataRefHandle, DataFieldHandle{ 0u }); + return *dataArray; + } } diff --git a/src/framework/internal/Watchdog/PlatformWatchdog.cpp b/src/framework/internal/Watchdog/PlatformWatchdog.cpp index 9858ca5e0..bf40f7a06 100644 --- a/src/framework/internal/Watchdog/PlatformWatchdog.cpp +++ b/src/framework/internal/Watchdog/PlatformWatchdog.cpp @@ -37,7 +37,7 @@ namespace ramses::internal { if (nullptr != m_watchdogCallback) { - LOG_TRACE(CONTEXT_FRAMEWORK, "notify watchdog from thread " << EnumToString(m_thread)); + LOG_TRACE(CONTEXT_FRAMEWORK, "notify watchdog from thread {}", EnumToString(m_thread)); m_watchdogCallback->notifyThread(m_thread); } m_lastNotificationTime = timeNow; diff --git a/src/ramses-cli/include/ramses-cli.h b/src/ramses-cli/include/ramses-cli.h index 7307f7500..050f8f5cc 100644 --- a/src/ramses-cli/include/ramses-cli.h +++ b/src/ramses-cli/include/ramses-cli.h @@ -150,6 +150,6 @@ namespace ramses is >> a; config.setClearColor({r, g, b, a}); return !is.fail() && (is.rdbuf()->in_avail() == 0); - }, "set clear color (rgba)"); + }, "set clear color (rgba), e.g. 1,0,0,1"); } } diff --git a/src/renderer/CMakeLists.txt b/src/renderer/CMakeLists.txt index 396dc980c..8b7b79933 100644 --- a/src/renderer/CMakeLists.txt +++ b/src/renderer/CMakeLists.txt @@ -18,4 +18,5 @@ createModule( impl/*.cpp DEPENDENCIES Platform + ramses-framework ) diff --git a/src/renderer/impl/BinaryShaderCacheImpl.cpp b/src/renderer/impl/BinaryShaderCacheImpl.cpp index 22c2bd0db..0add4b1c7 100644 --- a/src/renderer/impl/BinaryShaderCacheImpl.cpp +++ b/src/renderer/impl/BinaryShaderCacheImpl.cpp @@ -95,14 +95,14 @@ namespace ramses::internal ramses::internal::File file(filePath); if (!file.exists()) { - LOG_WARN(CONTEXT_RENDERER, "BinaryShaderCacheImpl::loadFromFile: file does not exist: " << filePath); + LOG_WARN(CONTEXT_RENDERER, "BinaryShaderCacheImpl::loadFromFile: file does not exist: {}", filePath); return false; } BinaryFileInputStream fileInputStream(file); if (EStatus::Ok != fileInputStream.getState()) { - LOG_WARN(CONTEXT_RENDERER, "BinaryShaderCacheImpl::loadFromFile: failed to load file: " << filePath << " errorstate: " << fileInputStream.getState()); + LOG_WARN(CONTEXT_RENDERER, "BinaryShaderCacheImpl::loadFromFile: failed to load file: {} errorstate: {}", filePath, fileInputStream.getState()); return false; } @@ -130,7 +130,7 @@ namespace ramses::internal if (fileHeader.transportVersion != RAMSES_TRANSPORT_PROTOCOL_VERSION_MAJOR) { LOG_WARN(CONTEXT_RENDERER, - "BinaryShaderCacheImpl::loadFromFile: File version " << fileHeader.transportVersion << " did not match the program version " << RAMSES_TRANSPORT_PROTOCOL_VERSION_MAJOR << " - cache needs to be repopulated and saved again"); + "BinaryShaderCacheImpl::loadFromFile: File version {} did not match the program version {} - cache needs to be repopulated and saved again", fileHeader.transportVersion, RAMSES_TRANSPORT_PROTOCOL_VERSION_MAJOR); return false; } @@ -164,7 +164,7 @@ namespace ramses::internal ResourceContentHash effectId; if (!deserializeBinaryShader(inputStream, effectId, binaryShader.data, binaryShader.format)) { - LOG_WARN(CONTEXT_RENDERER, "BinaryShaderCacheImpl::loadFromFile: Deserialization failed, abort loading at " << index << " of " << numBinaryShaders); + LOG_WARN(CONTEXT_RENDERER, "BinaryShaderCacheImpl::loadFromFile: Deserialization failed, abort loading at {} of {}", index, numBinaryShaders); return false; } @@ -205,7 +205,7 @@ namespace ramses::internal else { LOG_WARN(CONTEXT_RENDERER, - "BinaryShaderCacheImpl::saveToFile: failed to open " << filePath); + "BinaryShaderCacheImpl::saveToFile: failed to open {}", filePath); } } @@ -214,7 +214,7 @@ namespace ramses::internal { if (!success) { - LOG_WARN(CONTEXT_RENDERER, "BinaryShaderCache: Failed to upload binary shader from cache for effect id: " << effectHash); + LOG_WARN(CONTEXT_RENDERER, "BinaryShaderCache: Failed to upload binary shader from cache for effect id: {}", effectHash); } } diff --git a/src/renderer/impl/CommandDispatchingThread.cpp b/src/renderer/impl/CommandDispatchingThread.cpp index a9655cc59..639902619 100644 --- a/src/renderer/impl/CommandDispatchingThread.cpp +++ b/src/renderer/impl/CommandDispatchingThread.cpp @@ -19,20 +19,20 @@ namespace ramses::internal , m_commandBuffer{ commandBuffer } , m_watchdog{ watchdog } , m_aliveIdentifier{ watchdog.registerThread() } - , m_thread{ "R_RendererThrd" } + , m_thread{ "RndDispatchThrd" } { - LOG_INFO(CONTEXT_RENDERER, "Main renderer thread starting"); + LOG_INFO(CONTEXT_RENDERER, "Renderer dispatcher thread starting"); m_thread.start(*this); - LOG_INFO(CONTEXT_RENDERER, "Main renderer thread started"); + LOG_INFO(CONTEXT_RENDERER, "Renderer dispatcher thread started"); } CommandDispatchingThread::~CommandDispatchingThread() { - LOG_INFO(CONTEXT_RENDERER, "Main renderer thread stopping"); + LOG_INFO(CONTEXT_RENDERER, "Renderer dispatcher thread stopping"); m_thread.cancel(); m_commandBuffer.interruptBlockingSwapCommands(); m_thread.join(); - LOG_INFO(CONTEXT_RENDERER, "Main renderer thread stopped"); + LOG_INFO(CONTEXT_RENDERER, "Renderer dispatcher thread stopped"); m_watchdog.unregisterThread(m_aliveIdentifier); } diff --git a/src/renderer/impl/RamsesRendererImpl.cpp b/src/renderer/impl/RamsesRendererImpl.cpp index ce4f7db74..3a2757343 100644 --- a/src/renderer/impl/RamsesRendererImpl.cpp +++ b/src/renderer/impl/RamsesRendererImpl.cpp @@ -137,7 +137,7 @@ namespace ramses::internal const auto it = m_displayFramebuffers.find(displayId); if (it == m_displayFramebuffers.cend()) { - LOG_ERROR(CONTEXT_RENDERER, "RamsesRenderer::getDisplayFramebuffer: there is no display with ID " << displayId); + LOG_ERROR(CONTEXT_RENDERER, "RamsesRenderer::getDisplayFramebuffer: there is no display with ID {}", displayId); return displayBufferId_t::Invalid(); } return it->second; @@ -583,7 +583,7 @@ namespace ramses::internal bool RamsesRendererImpl::logRendererInfo() { - m_pendingRendererCommands.push_back(RendererCommand::LogInfo{ ERendererLogTopic::All, true, {} }); + m_pendingRendererCommands.push_back(RendererCommand::LogInfo{ ERendererLogTopic::All, true, {}, false, false, ELoopMode::UpdateAndRender, {} }); return true; } diff --git a/src/renderer/impl/RendererFactory.cpp b/src/renderer/impl/RendererFactory.cpp index 6b904b0d3..7b1c7aab2 100644 --- a/src/renderer/impl/RendererFactory.cpp +++ b/src/renderer/impl/RendererFactory.cpp @@ -22,7 +22,8 @@ namespace ramses::internal bool RendererFactory::RegisterRendererFactory() { - FrameworkFactoryRegistry::GetInstance().registerRendererFactory(std::make_unique()); + UniquePtrWithDeleter rendererFactory(new RendererFactory, [](IRendererFactory* rendererFactory_) { delete rendererFactory_; }); + FrameworkFactoryRegistry::GetInstance().registerRendererFactory(std::move(rendererFactory)); return true; } } diff --git a/src/renderer/impl/RendererSceneControlImpl.cpp b/src/renderer/impl/RendererSceneControlImpl.cpp index cc67907bb..948f6ce3b 100644 --- a/src/renderer/impl/RendererSceneControlImpl.cpp +++ b/src/renderer/impl/RendererSceneControlImpl.cpp @@ -25,7 +25,7 @@ namespace ramses::internal bool RendererSceneControlImpl::setSceneState(sceneId_t sceneId, RendererSceneState state) { - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControl::setSceneState: scene " << sceneId << " " << EnumToString(state)); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControl::setSceneState: scene {} {}", sceneId, EnumToString(state)); if (state == RendererSceneState::Unavailable) { @@ -49,7 +49,7 @@ namespace ramses::internal bool RendererSceneControlImpl::setSceneMapping(sceneId_t sceneId, displayId_t displayId) { - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControl::setSceneMapping: scene " << sceneId << " display " << displayId); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControl::setSceneMapping: scene {} display {}", sceneId, displayId); auto& sceneInfo = m_sceneInfos[sceneId]; if (sceneInfo.currState >= RendererSceneState::Ready || sceneInfo.targetState >= RendererSceneState::Ready) @@ -69,7 +69,7 @@ namespace ramses::internal bool RendererSceneControlImpl::setSceneDisplayBufferAssignment(sceneId_t sceneId, displayBufferId_t displayBuffer, int32_t sceneRenderOrder) { - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControl::setSceneDisplayBufferAssignment: scene " << sceneId << " displayBuffer " << displayBuffer << " renderOrder " << sceneRenderOrder); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControl::setSceneDisplayBufferAssignment: scene {} displayBuffer {} renderOrder {}", sceneId, displayBuffer, sceneRenderOrder); if (!m_sceneInfos[sceneId].mappingSet) { diff --git a/src/renderer/internal/Platform/Android/Window_Android.cpp b/src/renderer/internal/Platform/Android/Window_Android.cpp index 726543734..3d0bc9aab 100644 --- a/src/renderer/internal/Platform/Android/Window_Android.cpp +++ b/src/renderer/internal/Platform/Android/Window_Android.cpp @@ -7,7 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/RendererLib/DisplayConfig.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/Warnings.h" #include "internal/RendererLib/PlatformInterface/IWindowEventHandler.h" diff --git a/src/renderer/internal/Platform/CMakeLists.txt b/src/renderer/internal/Platform/CMakeLists.txt index a5d5a2c4b..056c23611 100644 --- a/src/renderer/internal/Platform/CMakeLists.txt +++ b/src/renderer/internal/Platform/CMakeLists.txt @@ -87,7 +87,7 @@ createModule( OpenGL/*.h OpenGL/*.cpp ${PLATFORM_SOURCES} - DEPENDENCIES ramses-renderer-lib + DEPENDENCIES ramses-renderer-internal OpenGL ${PLATFORM_LIBS} diff --git a/src/renderer/internal/Platform/Device_EGL_Extension/Device_EGL_Extension.cpp b/src/renderer/internal/Platform/Device_EGL_Extension/Device_EGL_Extension.cpp index 05b1eda2d..c80507382 100644 --- a/src/renderer/internal/Platform/Device_EGL_Extension/Device_EGL_Extension.cpp +++ b/src/renderer/internal/Platform/Device_EGL_Extension/Device_EGL_Extension.cpp @@ -49,7 +49,7 @@ namespace ramses::internal m_drmRenderNodeFD = open(m_renderNode.c_str(), O_RDWR); if (m_drmRenderNodeFD < 0) { - LOG_ERROR_P(CONTEXT_RENDERER, "Device_EGL_Extension::init(): failed to open render node \"{}\"!", m_renderNode); + LOG_ERROR(CONTEXT_RENDERER, "Device_EGL_Extension::init(): failed to open render node \"{}\"!", m_renderNode); return false; } @@ -75,10 +75,10 @@ namespace ramses::internal const bool isBufferFormatSupported = (gbm_device_is_format_supported(m_gbmDevice, bufferFormat, bufferUsage) != 0); if(!isBufferFormatSupported) { - LOG_ERROR_P(CONTEXT_RENDERER, "Device_EGL_Extension::createDmaRenderBuffer(): buffer format \"{}\" is not supported! Buffer creation will probably fail!", bufferFormat); + LOG_ERROR(CONTEXT_RENDERER, "Device_EGL_Extension::createDmaRenderBuffer(): buffer format \"{}\" is not supported! Buffer creation will probably fail!", bufferFormat); } else - LOG_INFO_P(CONTEXT_RENDERER, "Device_EGL_Extension::createDmaRenderBuffer(): buffer format \"{}\" is supported", bufferFormat); + LOG_INFO(CONTEXT_RENDERER, "Device_EGL_Extension::createDmaRenderBuffer(): buffer format \"{}\" is supported", bufferFormat); const auto gbmBufferObject = gbm_bo_create(m_gbmDevice, width, height, bufferFormat, bufferUsage); if(gbmBufferObject == nullptr) @@ -127,13 +127,13 @@ namespace ramses::internal const auto eglImage = m_eglExtensionProcs.eglCreateImageKHR(EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, nullptr, eglImageCreationAttribs.data()); if (eglImage == EGL_NO_IMAGE) { - LOG_ERROR_P(CONTEXT_RENDERER, "Device_EGL_Extension::createDmaRenderBuffer(): failed to create EGL Image, EGL error: {}! [width: {}, height: {}, format: {}, usage: {}, modifiers: {}, FD :{}, stride: {}]", eglGetError(), width, height, bufferFormat, bufferUsage, modifiers.getValue(), bufferFD, bufferStride); + LOG_ERROR(CONTEXT_RENDERER, "Device_EGL_Extension::createDmaRenderBuffer(): failed to create EGL Image, EGL error: {}! [width: {}, height: {}, format: {}, usage: {}, modifiers: {}, FD :{}, stride: {}]", eglGetError(), width, height, bufferFormat, bufferUsage, modifiers.getValue(), bufferFD, bufferStride); close(bufferFD); gbm_bo_destroy(gbmBufferObject); return {}; } - LOG_INFO_P(CONTEXT_RENDERER, "Device_EGL_Extension::createDmaRenderBuffer(): DMA render buffer created succesfully [width: {}, height: {}, stride: {}, format: {}, FD :{}, EGL image :{}]", width, height, bufferStride, bufferFormat, bufferFD, eglImage); + LOG_INFO(CONTEXT_RENDERER, "Device_EGL_Extension::createDmaRenderBuffer(): DMA render buffer created succesfully [width: {}, height: {}, stride: {}, format: {}, FD :{}, EGL image :{}]", width, height, bufferStride, bufferFormat, bufferFD, eglImage); GLuint glTexAddress = 0u; glGenTextures(1, &glTexAddress); @@ -159,7 +159,7 @@ namespace ramses::internal { const auto& resource = m_resourceMapper.getResourceAs(handle); - LOG_INFO_P(CONTEXT_RENDERER, "Device_EGL_Extension::destroyDmaRenderBuffer(): destroy DMA render buffer [FD :{}, EGL image :{}]", resource.getFD(), resource.getEGLImage()); + LOG_INFO(CONTEXT_RENDERER, "Device_EGL_Extension::destroyDmaRenderBuffer(): destroy DMA render buffer [FD :{}, EGL image :{}]", resource.getFD(), resource.getEGLImage()); m_eglExtensionProcs.eglDestroyImageKHR(resource.getEGLImage()); close(resource.getFD()); gbm_bo_destroy(resource.getGBMBufferObject()); diff --git a/src/renderer/internal/Platform/EGL/Context_EGL.cpp b/src/renderer/internal/Platform/EGL/Context_EGL.cpp index 6b49d60e6..a560934f9 100644 --- a/src/renderer/internal/Platform/EGL/Context_EGL.cpp +++ b/src/renderer/internal/Platform/EGL/Context_EGL.cpp @@ -7,7 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/Platform/EGL/Context_EGL.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace @@ -78,7 +78,7 @@ namespace ramses::internal if(nullptr != sharedContext) { EGLContext contextHandleToShare = sharedContext->m_eglSurfaceData.eglContext; - LOG_DEBUG(CONTEXT_RENDERER, "Context_EGL::Context_EGL Sharing new context with existing context: " << contextHandleToShare); + LOG_DEBUG(CONTEXT_RENDERER, "Context_EGL::Context_EGL Sharing new context with existing context: {}", contextHandleToShare); m_eglSurfaceData.eglSharedContext = contextHandleToShare; } } @@ -136,34 +136,34 @@ namespace ramses::internal LOG_INFO(CONTEXT_RENDERER, "Context_EGL::~Context_EGL calling eglDestroySurface"); if (!eglDestroySurface(m_eglSurfaceData.eglDisplay, m_eglSurfaceData.eglSurface)) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::destroy eglDestroySurface failed. Error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::destroy eglDestroySurface failed. Error code: {}", eglGetError()); } #else - LOG_INFO(CONTEXT_RENDERER, "Context_EGL::~Context_EGL calling eglDestroySurface if !isSharedContext:" << isSharedContext); + LOG_INFO(CONTEXT_RENDERER, "Context_EGL::~Context_EGL calling eglDestroySurface if !isSharedContext:{}", isSharedContext); if (!isSharedContext && (eglDestroySurface(m_eglSurfaceData.eglDisplay, m_eglSurfaceData.eglSurface) == EGL_FALSE)) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::destroy eglDestroySurface failed. Error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::destroy eglDestroySurface failed. Error code: {}", eglGetError()); } #endif LOG_INFO(CONTEXT_RENDERER, "Context_EGL::~Context_EGL calling eglDestroyContext"); if (eglDestroyContext(m_eglSurfaceData.eglDisplay, m_eglSurfaceData.eglContext) == EGL_FALSE) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::destroy eglDestroyContext failed. Error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::destroy eglDestroyContext failed. Error code: {}", eglGetError()); } #ifdef __ANDROID__ LOG_INFO(CONTEXT_RENDERER, "Context_EGL::~Context_EGL calling eglReleaseThread"); if (!eglReleaseThread()) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL: eglReleaseThread failed! Error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL: eglReleaseThread failed! Error code: {}", eglGetError()); } #endif LOG_DEBUG(CONTEXT_RENDERER, "Context_EGL::~Context_EGL calling eglTerminate"); if (!isSharedContext && (eglTerminate(m_eglSurfaceData.eglDisplay) == EGL_FALSE)) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::terminateEGLDisplayIfNotUsedAnymore eglTerminate() failed! Error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::terminateEGLDisplayIfNotUsedAnymore eglTerminate() failed! Error code: {}", eglGetError()); } } else @@ -189,7 +189,7 @@ namespace ramses::internal const auto success = eglMakeCurrent(m_eglSurfaceData.eglDisplay, m_eglSurfaceData.eglSurface, m_eglSurfaceData.eglSurface, m_eglSurfaceData.eglContext); if (success != EGL_TRUE) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::enable Error: eglMakeCurrent() failed. Error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::enable Error: eglMakeCurrent() failed. Error code: {}", eglGetError()); return false; } @@ -205,7 +205,7 @@ namespace ramses::internal const auto success = eglMakeCurrent(m_eglSurfaceData.eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); if (success != EGL_TRUE) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::disable Error: eglMakeCurrent() failed. Error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL::disable Error: eglMakeCurrent() failed. Error code: {}", eglGetError()); return false; } } @@ -235,7 +235,7 @@ namespace ramses::internal if (EGL_NO_DISPLAY == m_eglSurfaceData.eglDisplay) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglGetDisplay with arg: " << m_nativeDisplay << " returned EGL_NO_DISPLAY"); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglGetDisplay with arg: {} returned EGL_NO_DISPLAY", m_nativeDisplay); return false; } @@ -255,7 +255,7 @@ namespace ramses::internal EGLint iMinorVersion = 0; if (eglInitialize(m_eglSurfaceData.eglDisplay, &iMajorVersion, &iMinorVersion) == EGL_FALSE) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglInitialize() with error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglInitialize() with error code: {}", eglGetError()); return false; } @@ -268,12 +268,12 @@ namespace ramses::internal if (nullptr != contextExtensionsNativeString) { - LOG_INFO(CONTEXT_RENDERER, "Context_EGL::init(): EGL extensions: " << contextExtensionsNativeString); + LOG_INFO(CONTEXT_RENDERER, "Context_EGL::init(): EGL extensions: {}", contextExtensionsNativeString); parseContextExtensions(contextExtensionsNativeString); } else { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed: Could not get EGL extensions string. No context extensions are loaded. Error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed: Could not get EGL extensions string. No context extensions are loaded. Error code: {}", eglGetError()); } return true; @@ -283,7 +283,7 @@ namespace ramses::internal { if (eglBindAPI(EGL_OPENGL_ES_API) == EGL_FALSE) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglBindAPI() with error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglBindAPI() with error code: {}", eglGetError()); return false; } @@ -302,7 +302,7 @@ namespace ramses::internal return; } - LOG_INFO(CONTEXT_RENDERER, "Context_EGL: found: " << configCountResult << " EGL configurations"); + LOG_INFO(CONTEXT_RENDERER, "Context_EGL: found: {} EGL configurations", configCountResult); for(EGLint i = 0; i < configCountResult; ++i) { EGLint surfaceType = 0; @@ -327,17 +327,8 @@ namespace ramses::internal eglGetConfigAttrib(m_eglSurfaceData.eglDisplay, configsResult[i], EGL_STENCIL_SIZE, &stencilSize); eglGetConfigAttrib(m_eglSurfaceData.eglDisplay, configsResult[i], EGL_SAMPLES, &sampleCount); - LOG_INFO(CONTEXT_RENDERER, "Context_EGL: Config idx: " << i - << ", SURFACE_TYPE: " << surfaceType - << ", RENDERABLE_TYPE: " << renderableType - << ", BUFFER_SIZE: " << bufferSize - << ", RED_SIZE: " << redSize - << ", GREEN_SIZE: " << greenSize - << ", BLUE_SIZE: " << blueSize - << ", ALPHA_SIZE: " << alphaSize - << ", DEPTH_SIZE: " << depthSize - << ", STENCIL_SIZE: " << stencilSize - << ", EGL_SAMPLES: " << sampleCount); + LOG_INFO(CONTEXT_RENDERER, "Context_EGL: Config idx: {}, SURFACE_TYPE: {}, RENDERABLE_TYPE: {}, BUFFER_SIZE: {}, RED_SIZE: {}, GREEN_SIZE: {}, BLUE_SIZE: {}, ALPHA_SIZE: {}, DEPTH_SIZE: {}, STENCIL_SIZE: {}, EGL_SAMPLES: {}", + i, surfaceType, renderableType, bufferSize, redSize, greenSize, blueSize, alphaSize, depthSize, stencilSize, sampleCount); } } @@ -375,11 +366,11 @@ namespace ramses::internal const auto name = renderableTypeName(value); if (name != nullptr) { - LOG_ERROR_P(CONTEXT_RENDERER, "There is no EGL configuration that supports EGL_RENDERABLE_TYPE: {} (0x{:x})", name, value); + LOG_ERROR(CONTEXT_RENDERER, "There is no EGL configuration that supports EGL_RENDERABLE_TYPE: {} (0x{:x})", name, value); } else { - LOG_ERROR_P(CONTEXT_RENDERER, "There is no EGL configuration that supports EGL_RENDERABLE_TYPE: 0x{:x}", value); + LOG_ERROR(CONTEXT_RENDERER, "There is no EGL configuration that supports EGL_RENDERABLE_TYPE: 0x{:x}", value); } } break; @@ -424,11 +415,11 @@ namespace ramses::internal const auto* name = surfaceAttributeName(key); if (name != nullptr) { - LOG_ERROR_P(CONTEXT_RENDERER, "{}(0x{:x}): {}", name, key, value); + LOG_ERROR(CONTEXT_RENDERER, "{}(0x{:x}): {}", name, key, value); } else { - LOG_ERROR_P(CONTEXT_RENDERER, "0x{:x}: {}", key, value); + LOG_ERROR(CONTEXT_RENDERER, "0x{:x}: {}", key, value); } m_surfaceAttributes += 2; } @@ -438,7 +429,7 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglChooseConfig() with error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglChooseConfig() with error code: {}", eglGetError()); } eglTerminate(m_eglSurfaceData.eglDisplay); @@ -463,12 +454,13 @@ namespace ramses::internal auto logOnFailure = [&](bool condition, const char* paramName){ if(!condition) { - LOG_WARN(CONTEXT_RENDERER, "Context_EGL eglChooseConfig(): The chosen config does not have requested value for param: " << *configParamToQuery - << (paramName == nullptr? "" : "[") - << (paramName == nullptr? "" : paramName) - << (paramName == nullptr? "" : "]") - << ", requested value: " << configParamRequestedValue - << ", actual value: " << configParamActualValue); + LOG_WARN(CONTEXT_RENDERER, "Context_EGL eglChooseConfig(): The chosen config does not have requested value for param: {}{}{}{}, requested value: {}, actual value: {}", + *configParamToQuery, + paramName == nullptr ? "" : "[", + paramName == nullptr ? "" : paramName, + paramName == nullptr ? "" : "]", + configParamRequestedValue, + configParamActualValue); } }; @@ -503,7 +495,7 @@ namespace ramses::internal if (!m_eglSurfaceData.eglSurface) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglCreateWindowSurface() with error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglCreateWindowSurface() with error code: {}", eglGetError()); eglTerminate(m_eglSurfaceData.eglDisplay); return false; } @@ -528,7 +520,7 @@ namespace ramses::internal if (!m_eglSurfaceData.eglSurface) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglCreatePbufferSurface() with error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglCreatePbufferSurface() with error code: {}", eglGetError()); eglTerminate(m_eglSurfaceData.eglDisplay); return false; } @@ -547,7 +539,7 @@ namespace ramses::internal if (!m_eglSurfaceData.eglContext) { - LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglCreateContext() with error code: " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "Context_EGL initialization failed at eglCreateContext() with error code: {}", eglGetError()); eglDestroySurface(m_eglSurfaceData.eglDisplay, m_eglSurfaceData.eglSurface); eglTerminate(m_eglSurfaceData.eglDisplay); return false; diff --git a/src/renderer/internal/Platform/EGL/Platform_EGL.h b/src/renderer/internal/Platform/EGL/Platform_EGL.h index 9cbdf4cfc..773fdf4ed 100644 --- a/src/renderer/internal/Platform/EGL/Platform_EGL.h +++ b/src/renderer/internal/Platform/EGL/Platform_EGL.h @@ -13,7 +13,7 @@ #include "internal/RendererLib/DisplayConfig.h" #include "internal/Platform/EGL/Context_EGL.h" #include "internal/Platform/OpenGL/Device_GL.h" -#include "internal/Core/Utils/ThreadLocalLog.h" +#include "internal/Core/Utils/LogMacros.h" #include #ifdef DEVICE_EGL_EXTENSION_SUPPORTED @@ -50,7 +50,7 @@ namespace ramses::internal m_glesMinorVersion = minor; break; } - LOG_ERROR_RP( + LOG_ERROR( CONTEXT_RENDERER, "Context_EGL::init(): Failed to create GLES 3.{} context. Ramses will crash if any scene uses GLES 3.{} features.", minor, minor); } } @@ -132,7 +132,7 @@ namespace ramses::internal if (context->init()) { - LOG_INFO_RP(CONTEXT_RENDERER, "Context_EGL::init(): EGL 3.{} context creation succeeded (swap interval:{})", minorVersion, swapInterval); + LOG_INFO(CONTEXT_RENDERER, "Context_EGL::init(): EGL 3.{} context creation succeeded (swap interval:{})", minorVersion, swapInterval); return context; } diff --git a/src/renderer/internal/Platform/OpenGL/DebugOutput.cpp b/src/renderer/internal/Platform/OpenGL/DebugOutput.cpp index 3800c76af..c5cab772b 100644 --- a/src/renderer/internal/Platform/OpenGL/DebugOutput.cpp +++ b/src/renderer/internal/Platform/OpenGL/DebugOutput.cpp @@ -10,7 +10,7 @@ #include "internal/RendererLib/PlatformInterface/IContext.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include #include @@ -45,35 +45,24 @@ namespace ramses::internal { assert(userParam); - // NOTE (tobias) work around case where callback is called from another thread - // despite requesting synchronous dispatch via GL_DEBUG_OUTPUT_SYNCHRONOUS. This - // can happen when the driver is bugger or does not support synchronous operation. - // Prevent assert on log by ensuring there is always a valig TLS log prefix but - // set it to a very clear invalid value. - if (ThreadLocalLog::GetPrefixUnchecked() == -1) - { - ThreadLocalLog::SetPrefix(-2); - LOG_WARN(CONTEXT_RENDERER, "Detected broken OpenGL driver ignoring GL_DEBUG_OUTPUT_SYNCHRONOUS!"); - } - switch (type) { case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR: case GL_DEBUG_TYPE_ERROR: - LOG_ERROR(CONTEXT_RENDERER, "OpenGL error: " << message); + LOG_ERROR(CONTEXT_RENDERER, "OpenGL error: {}", message); *(const_cast(static_cast(userParam))) = true; break; case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR: case GL_DEBUG_TYPE_PORTABILITY: case GL_DEBUG_TYPE_PERFORMANCE: - LOG_WARN(CONTEXT_RENDERER, "OpenGL warning: " << message); + LOG_WARN(CONTEXT_RENDERER, "OpenGL warning: {}", message); break; case GL_DEBUG_TYPE_MARKER: case GL_DEBUG_TYPE_PUSH_GROUP: case GL_DEBUG_TYPE_POP_GROUP: case GL_DEBUG_TYPE_OTHER: default: - LOG_TRACE(CONTEXT_RENDERER, "OpenGL info: " << message); + LOG_TRACE(CONTEXT_RENDERER, "OpenGL info: {}", message); } } diff --git a/src/renderer/internal/Platform/OpenGL/Device_GL.cpp b/src/renderer/internal/Platform/OpenGL/Device_GL.cpp index 5bd7a42b3..59dd7602f 100644 --- a/src/renderer/internal/Platform/OpenGL/Device_GL.cpp +++ b/src/renderer/internal/Platform/OpenGL/Device_GL.cpp @@ -24,7 +24,7 @@ #include "internal/RendererLib/PlatformInterface/IDeviceExtension.h" #include "internal/SceneGraph/Resource/EffectResource.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/TextureMathUtils.h" #include "internal/PlatformAbstraction/PlatformStringUtils.h" #include "internal/PlatformAbstraction/Macros.h" @@ -115,16 +115,16 @@ namespace ramses::internal const char* tmp = nullptr; tmp = reinterpret_cast(glGetString(GL_VENDOR)); - LOG_INFO(CONTEXT_RENDERER, "Device_GL::init: OpenGL vendor is " << tmp); + LOG_INFO(CONTEXT_RENDERER, "Device_GL::init: OpenGL vendor is {}", tmp); tmp = reinterpret_cast(glGetString(GL_RENDERER)); - LOG_INFO(CONTEXT_RENDERER, " OpenGL renderer is " << tmp); + LOG_INFO(CONTEXT_RENDERER, " OpenGL renderer is {}", tmp); tmp = reinterpret_cast(glGetString(GL_VERSION)); - LOG_INFO(CONTEXT_RENDERER, " OpenGL version is " << tmp); + LOG_INFO(CONTEXT_RENDERER, " OpenGL version is {}", tmp); tmp = reinterpret_cast(glGetString(GL_SHADING_LANGUAGE_VERSION)); - LOG_INFO(CONTEXT_RENDERER, " GLSL version " << tmp); + LOG_INFO(CONTEXT_RENDERER, " GLSL version {}", tmp); loadOpenGLExtensions(); queryDeviceDependentFeatures(); @@ -150,7 +150,7 @@ namespace ramses::internal assert(m_activeIndexArraySizeBytes != 0 && m_activeIndexArrayElementSizeBytes != 0); if (m_activeIndexArraySizeBytes < (startOffset + elementCount) * m_activeIndexArrayElementSizeBytes) { - LOG_ERROR_P(CONTEXT_RENDERER, "Device_GL::drawIndexedTriangles: index buffer access out of bounds " + LOG_ERROR(CONTEXT_RENDERER, "Device_GL::drawIndexedTriangles: index buffer access out of bounds " "[drawStartOffset={} drawElementCount={} IndexBufferElementCount={}]", startOffset, elementCount, m_activeIndexArraySizeBytes / m_activeIndexArrayElementSizeBytes); return; @@ -330,7 +330,7 @@ namespace ramses::internal { if (width > m_limits.getMaxViewportWidth() || height > m_limits.getMaxViewportHeight()) { - LOG_WARN_P(CONTEXT_RENDERER, "Device_GL::setViewport: viewport size out of bounds " + LOG_WARN(CONTEXT_RENDERER, "Device_GL::setViewport: viewport size out of bounds " "[width={} height={}], clamping to [maxW={} maxH={}]", width, height, m_limits.getMaxViewportWidth(), m_limits.getMaxViewportHeight()); } @@ -588,7 +588,7 @@ namespace ramses::internal const GLHandle texID = getTextureAddress(handle); assert(texID != InvalidGLHandle); assert(data != nullptr); - LOG_DEBUG(CONTEXT_RENDERER, "Device_GL::uploadStreamTexture2D: texid: " << texID << " width: " << width << " height: " << height << " format: " << EnumToString(format) << " textureSwizzle: " << EnumToString(swizzle[0]) << "," << EnumToString(swizzle[1]) << "," << EnumToString(swizzle[2]) << "," << EnumToString(swizzle[3])); + LOG_DEBUG(CONTEXT_RENDERER, "Device_GL::uploadStreamTexture2D: texid: {}, width: {}, height: {}, format: {}, textureSwizzle: {},{},{},{}", texID, width, height, EnumToString(format), EnumToString(swizzle[0]), EnumToString(swizzle[1]), EnumToString(swizzle[2]), EnumToString(swizzle[3])); glBindTexture(GL_TEXTURE_2D, texID); @@ -616,7 +616,7 @@ namespace ramses::internal if (!m_limits.isTextureFormatAvailable(textureFormat)) { - LOG_ERROR(CONTEXT_RENDERER, "Device_GL::createGLInternalTextureInfo: Unsupported texture format " << EnumToString(textureFormat)); + LOG_ERROR(CONTEXT_RENDERER, "Device_GL::createGLInternalTextureInfo: Unsupported texture format {}", EnumToString(textureFormat)); assert(false && "Device_GL::createGLInternalTextureInfo unsupported texture format"); } @@ -633,7 +633,7 @@ namespace ramses::internal auto maxNumSamples = static_cast(maxNumSamplesGL); if (numSamples > maxNumSamples) { - LOG_WARN_P(CONTEXT_RENDERER, "Device_GL: clamping requested MSAA sample count {} " + LOG_WARN(CONTEXT_RENDERER, "Device_GL: clamping requested MSAA sample count {} " "to {}, a maximum number of samples supported by device for this format.", numSamples, maxNumSamples); numSamples = maxNumSamples; } @@ -918,7 +918,7 @@ namespace ramses::internal { m_textureSamplerObjectsCache[samplerStatesHash] = uploadTextureSampler(samplerStates); it = m_textureSamplerObjectsCache.find(samplerStatesHash); - LOG_INFO(CONTEXT_RENDERER, "Device_GL::activateTextureSamplerObject: cached new sampler object, total count: " << m_textureSamplerObjectsCache.size()); + LOG_INFO(CONTEXT_RENDERER, "Device_GL::activateTextureSamplerObject: cached new sampler object, total count: {}", m_textureSamplerObjectsCache.size()); } activateTextureSampler(it->second, field); @@ -956,7 +956,7 @@ namespace ramses::internal if (renderBuffers.size() > m_limits.getMaximumDrawBuffers()) { - LOG_ERROR_P(CONTEXT_RENDERER, "Device_GL::uploadRenderTarget failed: this device supports at most {} render buffers attached to render target, requested {}.", + LOG_ERROR(CONTEXT_RENDERER, "Device_GL::uploadRenderTarget failed: this device supports at most {} render buffers attached to render target, requested {}.", m_limits.getMaximumDrawBuffers(), renderBuffers.size()); return DeviceResourceHandle::Invalid(); } @@ -982,7 +982,7 @@ namespace ramses::internal const GLenum FBOstatus = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (FBOstatus != GL_FRAMEBUFFER_COMPLETE) { - LOG_ERROR(CONTEXT_RENDERER, "Device_GL::createRenderTargetComponents Framebuffer status not complete! GL error code: " << FBOstatus); + LOG_ERROR(CONTEXT_RENDERER, "Device_GL::createRenderTargetComponents Framebuffer status not complete! GL error code: {}", FBOstatus); return DeviceResourceHandle::Invalid(); } glDrawBuffers(static_cast(colorBuffers.size()), colorBuffers.data()); @@ -1157,7 +1157,7 @@ namespace ramses::internal if (!vertexInputAddress.isValid()) { //In case attribute is optimized out by shader compiler, e.g., because it is unused - LOG_DEBUG_P(CONTEXT_RENDERER, "Device_GL::allocateVertexArray could not find attrib location for field: {}. Field will be ignored in vertex array.", vb.field); + LOG_DEBUG(CONTEXT_RENDERER, "Device_GL::allocateVertexArray could not find attrib location for field: {}. Field will be ignored in vertex array.", vb.field); continue; } @@ -1251,7 +1251,7 @@ namespace ramses::internal { return std::make_unique(shader, programInfo); } - LOG_ERROR(CONTEXT_RENDERER, "Device_GL::uploadShader: shader upload failed: " << debugErrorLog); + LOG_ERROR(CONTEXT_RENDERER, "Device_GL::uploadShader: shader upload failed: {}", debugErrorLog); return nullptr; } @@ -1268,10 +1268,10 @@ namespace ramses::internal if (uploadSuccessful) { - LOG_DEBUG(CONTEXT_SMOKETEST, "Device_GL::uploadShader: renderer successfully uploaded binary shader for effect " << shader.getName()); + LOG_DEBUG(CONTEXT_SMOKETEST, "Device_GL::uploadShader: renderer successfully uploaded binary shader for effect {}", shader.getName()); return m_resourceMapper.registerResource(std::make_unique(shader, programInfo)); } - LOG_INFO(CONTEXT_RENDERER, "Device_GL::uploadShader: renderer failed to upload binary shader for effect " << shader.getName() << ". Error was: " << debugErrorLog); + LOG_INFO(CONTEXT_RENDERER, "Device_GL::uploadShader: renderer failed to upload binary shader for effect {}. Error was: {}", shader.getName(), debugErrorLog); return DeviceResourceHandle::Invalid(); } @@ -1280,7 +1280,7 @@ namespace ramses::internal binaryShader.clear(); const auto& shaderProgramGL = m_resourceMapper.getResourceAs(handle); - LOG_TRACE(CONTEXT_RENDERER, "Device_GL::getBinaryShader: retrieving shader binary for effect with handle " << handle.asMemoryHandle()); + LOG_TRACE(CONTEXT_RENDERER, "Device_GL::getBinaryShader: retrieving shader binary for effect with handle {}", handle.asMemoryHandle()); return shaderProgramGL.getBinaryInfo(binaryShader, binaryShaderFormat); } @@ -1338,7 +1338,7 @@ namespace ramses::internal } else { - LOG_DEBUG(CONTEXT_RENDERER, "Device_GL::activateTexture could not find uniform location for field :" << field.asMemoryHandle() << ")."); + LOG_DEBUG(CONTEXT_RENDERER, "Device_GL::activateTexture could not find uniform location for field :{}).", field.asMemoryHandle()); } } @@ -1514,7 +1514,7 @@ namespace ramses::internal const GLenum errorStatus = glGetError(); if (GL_NO_ERROR != errorStatus) { - LOG_ERROR(CONTEXT_RENDERER, "Device_GL::validateDeviceStatusHealthy: GL Error detected :" << errorStatus); + LOG_ERROR(CONTEXT_RENDERER, "Device_GL::validateDeviceStatusHealthy: GL Error detected :{}", errorStatus); return false; } diff --git a/src/renderer/internal/Platform/OpenGL/ShaderGPUResource_GL.cpp b/src/renderer/internal/Platform/OpenGL/ShaderGPUResource_GL.cpp index 36822b65e..23f34cd54 100644 --- a/src/renderer/internal/Platform/OpenGL/ShaderGPUResource_GL.cpp +++ b/src/renderer/internal/Platform/OpenGL/ShaderGPUResource_GL.cpp @@ -9,7 +9,7 @@ #include "internal/Platform/OpenGL/ShaderGPUResource_GL.h" #include "internal/Platform/OpenGL/Device_GL_platform.h" #include "internal/SceneGraph/Resource/EffectResource.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -103,7 +103,7 @@ namespace ramses::internal const GLInputLocation inputLocation(address); if (!inputLocation.isValid()) { - LOG_WARN(CONTEXT_RENDERER, "ShaderGPUResource_GL::loadAttributeLocation: glGetAttribLocation for effect '" << effect.getName() << "' for attribute '" << varName << "' failed"); + LOG_WARN(CONTEXT_RENDERER, "ShaderGPUResource_GL::loadAttributeLocation: glGetAttribLocation for effect '{}' for attribute '{}' failed", effect.getName(), varName); } return inputLocation; @@ -116,7 +116,7 @@ namespace ramses::internal const GLInputLocation inputLocation(address); if (!inputLocation.isValid()) { - LOG_WARN(CONTEXT_RENDERER, "ShaderGPUResource_GL::loadUniformLocation: for effect '" << effect.getName() << "' for uniform '" << varName << "' failed"); + LOG_WARN(CONTEXT_RENDERER, "ShaderGPUResource_GL::loadUniformLocation: for effect '{}' for uniform '{}' failed", effect.getName(), varName); } return inputLocation; @@ -129,7 +129,7 @@ namespace ramses::internal if (sizeInBytes <= 0) { - LOG_WARN_P(CONTEXT_RENDERER, "ShaderGPUResource_GL::getBinaryInfo: invalid binary shader size ({}) retrieved from device.", sizeInBytes); + LOG_WARN(CONTEXT_RENDERER, "ShaderGPUResource_GL::getBinaryInfo: invalid binary shader size ({}) retrieved from device.", sizeInBytes); return false; } diff --git a/src/renderer/internal/Platform/OpenGL/ShaderUploader_GL.cpp b/src/renderer/internal/Platform/OpenGL/ShaderUploader_GL.cpp index 998759483..8e0e8a2f0 100644 --- a/src/renderer/internal/Platform/OpenGL/ShaderUploader_GL.cpp +++ b/src/renderer/internal/Platform/OpenGL/ShaderUploader_GL.cpp @@ -11,7 +11,7 @@ #include "internal/SceneGraph/Resource/EffectResource.h" #include "internal/Platform/OpenGL/ShaderProgramInfo.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "absl/strings/str_split.h" namespace ramses::internal @@ -41,13 +41,13 @@ namespace ramses::internal bool ShaderUploader_GL::UploadShaderProgramFromSource(const EffectResource& effect, ShaderProgramInfo& programShaderInfoOut, std::string& debugErrorLog) { - LOG_DEBUG(CONTEXT_RENDERER, "ShaderUploader_GL::UploadShaderProgramFromSource: compiling shaders for effect " << effect.getName()); + LOG_DEBUG(CONTEXT_RENDERER, "ShaderUploader_GL::UploadShaderProgramFromSource: compiling shaders for effect {}", effect.getName()); const GLHandle vertexShaderHandle = CompileShaderStage(effect.getVertexShader(), GL_VERTEX_SHADER, debugErrorLog); if (InvalidGLHandle == vertexShaderHandle) { - LOG_ERROR(CONTEXT_RENDERER, "ShaderUploader_GL::UploadShaderProgramFromSource: vertex shader failed to compile " << debugErrorLog); + LOG_ERROR(CONTEXT_RENDERER, "ShaderUploader_GL::UploadShaderProgramFromSource: vertex shader failed to compile {}", debugErrorLog); return false; } @@ -55,7 +55,7 @@ namespace ramses::internal if (InvalidGLHandle == fragmentShaderHandle) { - LOG_ERROR(CONTEXT_RENDERER, "ShaderUploader_GL::UploadShaderProgramFromSource: fragment shader failed to compile " << debugErrorLog); + LOG_ERROR(CONTEXT_RENDERER, "ShaderUploader_GL::UploadShaderProgramFromSource: fragment shader failed to compile {}", debugErrorLog); glDeleteShader(vertexShaderHandle); return false; } @@ -68,7 +68,7 @@ namespace ramses::internal if (InvalidGLHandle == geometryShaderHandle) { - LOG_ERROR(CONTEXT_RENDERER, "ShaderUploader_GL::UploadShaderProgramFromSource: geometry shader failed to compile " << debugErrorLog); + LOG_ERROR(CONTEXT_RENDERER, "ShaderUploader_GL::UploadShaderProgramFromSource: geometry shader failed to compile {}", debugErrorLog); glDeleteShader(vertexShaderHandle); glDeleteShader(fragmentShaderHandle); return false; @@ -198,7 +198,7 @@ namespace ramses::internal uint32_t lineNumber = 1; for (const auto& line : absl::StrSplit(source, '\n')) { - LOG_ERROR(CONTEXT_RENDERER, "Device_Base::PrintShaderSourceWithLineNumbers: L" << lineNumber << ": " << line); + LOG_ERROR(CONTEXT_RENDERER, "Device_Base::PrintShaderSourceWithLineNumbers: L{}: {}", lineNumber, line); ++lineNumber; } } diff --git a/src/renderer/internal/Platform/PlatformFactory.cpp b/src/renderer/internal/Platform/PlatformFactory.cpp index af6b0de4d..8b53c163d 100644 --- a/src/renderer/internal/Platform/PlatformFactory.cpp +++ b/src/renderer/internal/Platform/PlatformFactory.cpp @@ -9,7 +9,7 @@ #include "internal/Platform/PlatformFactory.h" #include "internal/RendererLib/DisplayConfig.h" #include "internal/RendererLib/RendererConfig.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #if defined(ramses_sdk_ENABLE_WINDOW_TYPE_WINDOWS) #include "internal/Platform/Windows/Platform_Windows_WGL.h" diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/EmbeddedCompositor_Wayland.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/EmbeddedCompositor_Wayland.cpp index c12b6fb6e..31a5a3bc7 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/EmbeddedCompositor_Wayland.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/EmbeddedCompositor_Wayland.cpp @@ -19,7 +19,7 @@ #include "internal/Platform/EGL/Context_EGL.h" #include "internal/RendererLib/DisplayConfig.h" #include "internal/RendererLib/RendererLogContext.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/Warnings.h" #include "internal/PlatformAbstraction/PlatformTime.h" #include @@ -107,7 +107,7 @@ namespace ramses::internal WaylandIviSurfaceIdSet EmbeddedCompositor_Wayland::dispatchUpdatedStreamTextureSourceIds() { - LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::dispatchUpdatedStreamTextureSourceIds(): count of pending updates for dispatching :" << m_updatedStreamTextureSourceIds.size()); + LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::dispatchUpdatedStreamTextureSourceIds(): count of pending updates for dispatching :{}", m_updatedStreamTextureSourceIds.size()); WaylandIviSurfaceIdSet result = m_updatedStreamTextureSourceIds; m_updatedStreamTextureSourceIds.clear(); return result; @@ -162,7 +162,7 @@ namespace ramses::internal void EmbeddedCompositor_Wayland::addWaylandSurface(IWaylandSurface& waylandSurface) { m_surfaces.push_back(&waylandSurface); - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::addWaylandSurface: Client created surface. Count surfaces :" << m_surfaces.size()); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::addWaylandSurface: Client created surface. Count surfaces :{}", m_surfaces.size()); } void EmbeddedCompositor_Wayland::removeWaylandSurface(IWaylandSurface& waylandSurface) @@ -180,14 +180,14 @@ namespace ramses::internal } } - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::removeWaylandSurface() Client destroyed surface, showing fallback texture for " << waylandSurface.getIviSurfaceId() - << ". Count surfaces :" << m_surfaces.size()); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::removeWaylandSurface() Client destroyed surface, showing fallback texture for {}. Count surfaces :{}", + waylandSurface.getIviSurfaceId(), m_surfaces.size()); } void EmbeddedCompositor_Wayland::addWaylandCompositorConnection(IWaylandCompositorConnection& waylandCompositorConnection) { m_compositorConnections.put(&waylandCompositorConnection); - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::addWaylandCompositorConnection: embedded-compositing connection created. Count connections :" << m_compositorConnections.size()); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::addWaylandCompositorConnection: embedded-compositing connection created. Count connections :{}", m_compositorConnections.size()); } IWaylandSurface* EmbeddedCompositor_Wayland::findWaylandSurfaceByIviSurfaceId(WaylandIviSurfaceId iviSurfaceId) const @@ -227,8 +227,8 @@ namespace ramses::internal IWaylandSurface* waylandClientSurface = findWaylandSurfaceByIviSurfaceId(streamTextureSourceId); assert(nullptr != waylandClientSurface); - LOG_DEBUG(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::uploadCompositingContentForStreamTexture() " << streamTextureSourceId); - LOG_INFO(CONTEXT_SMOKETEST, "embedded-compositing client surface found for existing streamtexture: " << streamTextureSourceId); + LOG_DEBUG(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::uploadCompositingContentForStreamTexture() {}", streamTextureSourceId); + LOG_INFO(CONTEXT_SMOKETEST, "embedded-compositing client surface found for existing streamtexture: {}", streamTextureSourceId); UploadCompositingContentForWaylandSurface(waylandClientSurface, textureHandle, textureUploadingAdapter); return waylandClientSurface->getNumberOfCommitedFrames(); @@ -253,7 +253,7 @@ namespace ramses::internal std::byte dummyData { 0u }; textureUploadingAdapter.uploadTexture2D(textureHandle, 1u, 1u, EPixelStorageFormat::R8, &dummyData, swizzle); - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::uploadCompositingContentForWaylandSurface(): resetting swizzle for " << waylandSurface->getIviSurfaceId()); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::uploadCompositingContentForWaylandSurface(): resetting swizzle for {}", waylandSurface->getIviSurfaceId()); } if (nullptr != sharedMemoryBufferData) @@ -391,8 +391,8 @@ namespace ramses::internal const bool removed = m_compositorConnections.remove(&waylandCompositorConnection); assert(removed); - LOG_INFO(CONTEXT_SMOKETEST, "EmbeddedCompositor_Wayland::removeWaylandCompositorConnection: embedded-compositing connection removed. Count connections :" - << m_compositorConnections.size() << ", was removed " << removed); + LOG_INFO(CONTEXT_SMOKETEST, "EmbeddedCompositor_Wayland::removeWaylandCompositorConnection: embedded-compositing connection removed. Count connections :{}, was removed {}", + m_compositorConnections.size(), removed); } void EmbeddedCompositor_Wayland::removeFromUpdatedStreamTextureSourceIds(WaylandIviSurfaceId id) @@ -412,7 +412,7 @@ namespace ramses::internal void EmbeddedCompositor_Wayland::addToUpdatedStreamTextureSourceIds(WaylandIviSurfaceId id) { - LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::addToUpdatedStreamTextureSourceIds: new texture data for stream texture with " << id); + LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Wayland::addToUpdatedStreamTextureSourceIds: new texture data for stream texture with {}", id); m_updatedStreamTextureSourceIds.insert(id); if (m_knownStreamTextureSoruceIds.count(id) == 0u) diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabuf.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabuf.cpp index 02c59a8e8..ebccaad28 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabuf.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabuf.cpp @@ -8,7 +8,7 @@ // ------------------------------------------------------------------------- #include "internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabuf.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include @@ -130,7 +130,7 @@ namespace ramses::internal m_numPlanes++; - LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufBufferData::setPlaneData(): plane data is set successfully, no. planes :" << m_numPlanes); + LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufBufferData::setPlaneData(): plane data is set successfully, no. planes :{}", m_numPlanes); } int32_t LinuxDmabufBufferData::getWidth() diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufConnection.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufConnection.cpp index e34b97ea2..a59274515 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufConnection.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufConnection.cpp @@ -19,7 +19,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufConnection.h" #include "internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufParams.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/Warnings.h" namespace ramses::internal @@ -37,20 +37,20 @@ namespace ramses::internal if (m_resource) { - LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufConnection::LinuxDmabufConnection(): DMA BUF interface is now provided " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufConnection::LinuxDmabufConnection(): DMA BUF interface is now provided {}", m_clientCredentials); m_resource->setImplementation(&m_dmabufInterface, this, ResourceDestroyedCallback); } else { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufConnection::LinuxDmabufConnection(): Could not create wayland resource " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufConnection::LinuxDmabufConnection(): Could not create wayland resource {}", m_clientCredentials); client.postNoMemory(); } } LinuxDmabufConnection::~LinuxDmabufConnection() { - LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufConnection::~LinuxDmabufConnection(): Connection destroyed " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufConnection::~LinuxDmabufConnection(): Connection destroyed {}", m_clientCredentials); if (nullptr != m_resource) { diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufParams.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufParams.cpp index 865235f50..2636b704f 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufParams.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufParams.cpp @@ -18,7 +18,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufParams.h" #include "internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabufBuffer.h" #include "internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabuf.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/Warnings.h" #include @@ -40,20 +40,20 @@ namespace ramses::internal if (nullptr != m_resource) { - LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufParams::LinuxDmabufParams(): DMA Params created " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufParams::LinuxDmabufParams(): DMA Params created {}", m_clientCredentials); m_resource->setImplementation(&m_paramsInterface, this, ResourceDestroyedCallback); } else { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::LinuxDmabufParams(): Could not create wayland resource " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::LinuxDmabufParams(): Could not create wayland resource {}", m_clientCredentials); client.postNoMemory(); } } LinuxDmabufParams::~LinuxDmabufParams() { - LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufParams::~LinuxDmabufParams(): DMA Params destroyed " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufParams::~LinuxDmabufParams(): DMA Params destroyed {}", m_clientCredentials); if (nullptr != m_resource) { @@ -118,9 +118,8 @@ namespace ramses::internal void LinuxDmabufParams::addPlane(int32_t fd, uint32_t index, uint32_t offset, uint32_t stride, uint32_t modifier_hi, uint32_t modifier_lo) { - LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufParams::addPlane(): fd : " << fd - << ", index :" << index << ", offset :" << offset << ", stride :" << stride << ", modifier_hi :" << modifier_hi << ", modifier_lo :" << modifier_lo - << " " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufParams::addPlane(): fd : {}, index :{}, offset: {}, stride :{}, modifier_hi :{}, modifier_lo :{} {}", + fd, index, offset, stride, modifier_hi, modifier_lo, m_clientCredentials); if (nullptr == m_data) { @@ -133,8 +132,7 @@ namespace ramses::internal if (index >= LinuxDmabufBufferData::MAX_DMABUF_PLANES) { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::addPlane(): failed to add plane data because index [=" << index - << "] is bigger than or equal to max no. of planes [=" << LinuxDmabufBufferData::MAX_DMABUF_PLANES << "]"); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::addPlane(): failed to add plane data because index [={}] is bigger than or equal to max no. of planes [={}]", index, LinuxDmabufBufferData::MAX_DMABUF_PLANES); StringOutputStream message; message << "plane index " << index << " is too high"; @@ -145,7 +143,7 @@ namespace ramses::internal if (m_data->isPlaneDataSet(index)) { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::addPlane(): failed to add plane data because plane data is already set [for index :" << index << "]"); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::addPlane(): failed to add plane data because plane data is already set [for index :{}]", index); StringOutputStream message; message << "a dmabuf has already been added for plane " << index; @@ -181,8 +179,7 @@ namespace ramses::internal { if (m_data->getNumPlanes() < 1) { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : " << bufferId - << "] because params has no planes set"); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : {}] because params has no planes set", bufferId); m_resource->postError(ZWP_LINUX_BUFFER_PARAMS_V1_ERROR_INCOMPLETE, "no dmabuf has been added to the params"); @@ -195,8 +192,8 @@ namespace ramses::internal { if (!m_data->isPlaneDataSet(i)) { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : " << bufferId - << "] because plane : " << i << " has no data set"); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : {}] because plane : {} has no data set", + bufferId, i); StringOutputStream message; message << "no dmabuf has been added for plane " << i; @@ -215,8 +212,8 @@ namespace ramses::internal if (width < 1 || height < 1) { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : " << bufferId - << "] because of invalid width(" << width << ") or height(" << height << ")"); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : {}] because of invalid width({}) or height({})", + bufferId, width, height); StringOutputStream message; message << "invalid width " << width << " or height " << height; @@ -235,8 +232,7 @@ namespace ramses::internal // Validate internal consistency of user-supplied geometry info if (offset + stride > UINT32_MAX) { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : " << bufferId - << "] because of size overflow of offset+stride for plane :" << i); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : {}] because of size overflow of offset+stride for plane :{}", bufferId, i); StringOutputStream message; message << "size overflow for plane " << i; @@ -249,8 +245,7 @@ namespace ramses::internal if (i == 0 && offset + stride * m_data->getHeight() > UINT32_MAX) { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : " << bufferId - << "] because of size overflow for plane :" << i); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : {}] because of size overflow for plane :", bufferId, i); StringOutputStream message; message << "size overflow for plane " << i; @@ -274,8 +269,7 @@ namespace ramses::internal if (offset >= uSize) { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : " << bufferId - << "] because of invalid offset for plane :" << i); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : {}] because of invalid offset for plane :{}", bufferId, i); StringOutputStream message; message << "invalid offset " << offset << " for plane " << i; @@ -288,8 +282,7 @@ namespace ramses::internal if (offset + stride > uSize) { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : " << bufferId - << "] because of invalid offset+stride for plane :" << i); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : {}] because of invalid offset+stride for plane :{}", bufferId, i); StringOutputStream message; message << "invalid stride " << offset << " for plane " << i; @@ -304,8 +297,7 @@ namespace ramses::internal // we can't enforce this generically. if (0 == i && offset + stride * m_data->getHeight() > uSize) { - LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : " << bufferId - << "] because of invalid stride or height for plane :" << i); + LOG_ERROR(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): failed to create buffer [id : {}] because of invalid stride or height for plane :{}", bufferId, i); StringOutputStream message; message << "invalid buffer stride or height for plane " << i; @@ -334,7 +326,7 @@ namespace ramses::internal bufferWaylandResource->setImplementation(&LinuxDmabufBuffer::m_bufferInterface, m_data, BufferDestroyCallback); m_data = nullptr; - LOG_INFO_P(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): bufferId:{} w:{} h:{} format:{} flags:{} res:{} {}", + LOG_INFO(CONTEXT_RENDERER, "LinuxDmabufParams::createBuffer(): bufferId:{} w:{} h:{} format:{} flags:{} res:{} {}", bufferId, width, height, format, flags, static_cast(bufferNativeWaylandResource), m_clientCredentials); // Announce the resulting buffer to the client diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/TextureUploadingAdapter_Wayland.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/TextureUploadingAdapter_Wayland.cpp index e06251b44..0bb4ef63b 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/TextureUploadingAdapter_Wayland.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/TextureUploadingAdapter_Wayland.cpp @@ -15,7 +15,7 @@ #include "linux-dmabuf-unstable-v1-server-protocol.h" #include "internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabuf.h" #include "internal/RendererLib/PlatformInterface/IDevice.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/Warnings.h" namespace ramses::internal @@ -82,7 +82,7 @@ namespace ramses::internal { LOG_ERROR(CONTEXT_RENDERER, "eglQueryWaylandBufferWL(EGL_HEIGHT) failed"); } - LOG_DEBUG_P(CONTEXT_RENDERER, "TextureUploadingAdapter_Wayland::uploadTextureFromWaylandResource: w:{} h:{} format:{} ({})", + LOG_DEBUG(CONTEXT_RENDERER, "TextureUploadingAdapter_Wayland::uploadTextureFromWaylandResource: w:{} h:{} format:{} ({})", textureWidth, textureHeight, textureFormat, m_waylandEglExtensionProcs.getTextureFormatName(textureFormat)); } @@ -131,9 +131,8 @@ namespace ramses::internal { const auto modifierFormat = modifier & 0x00ffffffffffffffULL; const auto modifierVendor = modifier >> 56; - LOG_WARN(CONTEXT_RENDERER, "TextureUploadingAdapter_Wayland::importDmabufToEglImage: DMA buf has unsupported modifier set (will be ignored)! modifier=" << modifier - << ", vendor=" << modifierVendor - << ", format=" << modifierFormat); + LOG_WARN(CONTEXT_RENDERER, "TextureUploadingAdapter_Wayland::importDmabufToEglImage: DMA buf has unsupported modifier set (will be ignored)! modifier={}, vendor={}, format={}", + modifier, modifierVendor, modifierFormat); } POP_DISABLE_C_STYLE_CAST_WARNING @@ -151,7 +150,7 @@ namespace ramses::internal // NOLINTNEXTLINE(hicpp-signed-bitwise) if ((dmabuf->getFlags() & ~ZWP_LINUX_BUFFER_PARAMS_V1_FLAGS_Y_INVERT) != 0u) { - LOG_ERROR(CONTEXT_RENDERER, "TextureUploadingAdapter_Wayland::importDmabufToEglImage: DMA buf has unsupported flags=" << dmabuf->getFlags() << "! Creating EGL image failed!"); + LOG_ERROR(CONTEXT_RENDERER, "TextureUploadingAdapter_Wayland::importDmabufToEglImage: DMA buf has unsupported flags={}! Creating EGL image failed!", dmabuf->getFlags()); return nullptr; } @@ -250,12 +249,11 @@ namespace ramses::internal EGLImage eglImage = m_waylandEglExtensionProcs.eglCreateImageKHR(nullptr, EGL_LINUX_DMA_BUF_EXT, nullptr, attribs.data()); if (EGL_NO_IMAGE == eglImage) { - LOG_ERROR(CONTEXT_RENDERER, "TextureUploadingAdapter_Wayland::importDmabufToEglImage: Creating EGL image failed width egl error code : " << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "TextureUploadingAdapter_Wayland::importDmabufToEglImage: Creating EGL image failed width egl error code : {}", eglGetError()); return nullptr; } - LOG_INFO(CONTEXT_RENDERER, "TextureUploadingAdapter_Wayland::importDmabufToEglImage: egl image [=" << eglImage - << "] created succesffully [W :" << dmabuf->getWidth() << ", H :" << dmabuf->getHeight() << "]"); + LOG_INFO(CONTEXT_RENDERER, "TextureUploadingAdapter_Wayland::importDmabufToEglImage: egl image [={}] created succesffully [W :{}, H :{}]", eglImage, dmabuf->getWidth(), dmabuf->getHeight()); return new DmabufEglImage(*this, eglImage, GL_TEXTURE_EXTERNAL_OES); } @@ -301,7 +299,7 @@ namespace ramses::internal { if (EGL_NO_IMAGE != m_eglImage) { - LOG_INFO(CONTEXT_RENDERER, "DmabufEglImage::~DmabufEglImage: destroying egl image [=" << m_eglImage << "]"); + LOG_INFO(CONTEXT_RENDERER, "DmabufEglImage::~DmabufEglImage: destroying egl image [={}]", m_eglImage); m_parent.m_waylandEglExtensionProcs.eglDestroyImageKHR(m_eglImage); } } diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandBuffer.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandBuffer.cpp index b70c4fcf3..8fd2d046f 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandBuffer.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandBuffer.cpp @@ -11,7 +11,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/LinuxDmabuf.h" #include "internal/Platform/Wayland/EmbeddedCompositor/IEmbeddedCompositor_Wayland.h" #include "internal/Platform/Wayland/WaylandEGLExtensionProcs.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/Warnings.h" #include "internal/RendererLib/RendererLogContext.h" #include @@ -41,7 +41,7 @@ namespace ramses::internal void WaylandBuffer::ClientBufferDestroyed(wl_listener* listener, [[maybe_unused]] void* data) { - LOG_DEBUG(CONTEXT_RENDERER, "WaylandBuffer::ClientBufferDestroyed data: " << data); + LOG_DEBUG(CONTEXT_RENDERER, "WaylandBuffer::ClientBufferDestroyed data: {}", data); WaylandBuffer* buffer(nullptr); diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandCompositorConnection.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandCompositorConnection.cpp index c76248175..88e471591 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandCompositorConnection.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandCompositorConnection.cpp @@ -12,7 +12,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandRegion.h" #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandClient.h" #include "internal/Platform/Wayland/EmbeddedCompositor/INativeWaylandResource.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal @@ -28,11 +28,11 @@ namespace ramses::internal if (nullptr != m_resource) { m_resource->setImplementation(&m_compositorInterface, this, ResourceDestroyedCallback); - LOG_INFO(CONTEXT_RENDERER, "WaylandCompositorConnection::WaylandCompositorConnection(): Compositor interface is now provided " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandCompositorConnection::WaylandCompositorConnection(): Compositor interface is now provided {}", m_clientCredentials); } else { - LOG_ERROR(CONTEXT_RENDERER, "WaylandCompositorConnection::WaylandCompositorConnection(): could not create wayland resource " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "WaylandCompositorConnection::WaylandCompositorConnection(): could not create wayland resource {}", m_clientCredentials); client.postNoMemory(); } } @@ -44,7 +44,7 @@ namespace ramses::internal WaylandCompositorConnection::~WaylandCompositorConnection() { - LOG_INFO(CONTEXT_RENDERER, "WaylandCompositorConnection::~WaylandCompositorConnection Connection destroyed " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandCompositorConnection::~WaylandCompositorConnection Connection destroyed {}", m_clientCredentials); m_embeddedCompositor.removeWaylandCompositorConnection(*this); if (nullptr != m_resource) diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandCompositorGlobal.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandCompositorGlobal.cpp index 53c795993..1b6f76ab1 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandCompositorGlobal.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandCompositorGlobal.cpp @@ -13,7 +13,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/IWaylandDisplay.h" #include "internal/Platform/Wayland/EmbeddedCompositor/IWaylandGlobal.h" #include "internal/PlatformAbstraction/PlatformMath.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandDisplay.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandDisplay.cpp index 385540edd..774c94bf9 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandDisplay.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandDisplay.cpp @@ -10,7 +10,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandCompositorConnection.h" #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandGlobal.h" #include "internal/PlatformAbstraction/PlatformEnvironmentVariables.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include #include #include @@ -106,8 +106,8 @@ namespace ramses::internal { LOG_ERROR(CONTEXT_RENDERER, "WaylandDisplay::addSocketToDisplayWithName(): Failed to add wayland display on embedded " - "compositor socket :" - << socketName << " !"); + "compositor socket :{} !", + socketName); return false; } @@ -115,22 +115,22 @@ namespace ramses::internal if (!ApplyGroupToEmbeddedCompositingSocket(socketFullPath, socketGroupName)) { LOG_ERROR(CONTEXT_RENDERER, - "WaylandDisplay::addSocketToDisplayWithName(): Failed to set group '" << socketGroupName << "' on embedded compositor socket :" - << socketName << " !"); + "WaylandDisplay::addSocketToDisplayWithName(): Failed to set group '{}' on embedded compositor socket :{} !", + socketGroupName, socketName); return false; } if (!ApplyPermissionsToEmbeddedCompositingSocket(socketFullPath, socketPermissions)) { LOG_ERROR(CONTEXT_RENDERER, - "WaylandDisplay::addSocketToDisplayWithName(): Failed to set permissions " << socketPermissions << " on embedded compositor socket :" - << socketName << " !"); + "WaylandDisplay::addSocketToDisplayWithName(): Failed to set permissions {} on embedded compositor socket :{} !", + socketPermissions, socketName); return false; } LOG_INFO(CONTEXT_RENDERER, - "WaylandDisplay::addSocketToDisplayWithName(): Added wayland display on embedded compositor socket :" - << socketName << " !"); + "WaylandDisplay::addSocketToDisplayWithName(): Added wayland display on embedded compositor socket :{} !", + socketName); return true; } @@ -159,16 +159,16 @@ namespace ramses::internal { LOG_ERROR(CONTEXT_RENDERER, "WaylandDisplay::ApplyGroupToEmbeddedCompositingSocket(): Could not " - "get group file entry for group name :" - << socketGroupName << ". Error :" << status); + "get group file entry for group name :{}. Error :{}", + socketGroupName, status); return false; } if (nullptr == permissionGroupResult) { LOG_ERROR(CONTEXT_RENDERER, "WaylandDisplay::ApplyGroupToEmbeddedCompositingSocket(): Could not " - "find group for socket with group name :" - << socketGroupName); + "find group for socket with group name :{}", + socketGroupName); return false; } @@ -179,15 +179,15 @@ namespace ramses::internal { LOG_ERROR(CONTEXT_RENDERER, "WaylandDisplay::ApplyGroupToEmbeddedCompositingSocket(): Could not " - "set group :" - << socketGroupName << " on :" << socketFullPath - << ". Error:" << strerror(errno)); + "set group :{} on :{}. Error:{}", + socketGroupName, socketFullPath, + strerror(errno)); return false; } LOG_INFO(CONTEXT_RENDERER, "WaylandDisplay::ApplyGroupToEmbeddedCompositingSocket(): Successfully set " - "group :" - << socketGroupName << " on socket :" << socketFullPath); + "group :{} on socket :{}", + socketGroupName, socketFullPath); // .lock file const int chownStatusLockfile = chown(fullSocketLockFilePath.c_str(), -1, groupID); @@ -195,15 +195,15 @@ namespace ramses::internal { LOG_ERROR(CONTEXT_RENDERER, "WaylandDisplay::::ApplyGroupToEmbeddedCompositingSocket(): Could not " - "set group :" - << socketGroupName << " on :" << fullSocketLockFilePath - << ". Error:" << strerror(errno)); + "set group :{} on :{}. Error:{}", + socketGroupName, fullSocketLockFilePath, + strerror(errno)); return false; } LOG_INFO(CONTEXT_RENDERER, "WaylandDisplay::::ApplyGroupToEmbeddedCompositingSocket(): Successfully " - "set group :" - << socketGroupName << " on :" << fullSocketLockFilePath); + "set group :{} on :{}", + socketGroupName, fullSocketLockFilePath); } return true; } @@ -217,14 +217,13 @@ namespace ramses::internal if (0 != ::chmod(socketFullPath.c_str(), socketPermissions)) { LOG_ERROR(CONTEXT_RENDERER, - "WaylandDisplay::ApplyPermissionsToEmbeddedCompositingSocket(): Could not set permissions: " - << socketPermissions << " on :" << socketFullPath - << ". Error:" << strerror(errno)); + "WaylandDisplay::ApplyPermissionsToEmbeddedCompositingSocket(): Could not set permissions: {} on :{}. Error:{}", + socketPermissions, socketFullPath, strerror(errno)); return false; } LOG_INFO(CONTEXT_RENDERER, - "WaylandDisplay::ApplyPermissionsToEmbeddedCompositingSocket(): Successfully set permissions: " - << socketPermissions << " on socket :" << socketFullPath); + "WaylandDisplay::ApplyPermissionsToEmbeddedCompositingSocket(): Successfully set permissions: {} on socket :{}", + socketPermissions, socketFullPath); return true; } diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVIApplicationConnection.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVIApplicationConnection.cpp index 9146fe4fc..ed61e474f 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVIApplicationConnection.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVIApplicationConnection.cpp @@ -10,7 +10,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandSurface.h" #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandIVISurface.h" #include "internal/Platform/Wayland/EmbeddedCompositor/NativeWaylandResource.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal @@ -27,20 +27,20 @@ namespace ramses::internal m_resource = client.resourceCreate(&ivi_application_interface, static_cast(version), id); if (m_resource) { - LOG_INFO(CONTEXT_RENDERER, "WaylandIVIApplicationConnection::WaylandIVIApplicationConnection(): ivi application interface is now provided " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandIVIApplicationConnection::WaylandIVIApplicationConnection(): ivi application interface is now provided {}", m_clientCredentials); m_resource->setImplementation(&m_iviApplicationInterface, this, ResourceDestroyedCallback); } else { - LOG_ERROR(CONTEXT_RENDERER, "WaylandIVIApplicationConnection::WaylandIVIApplicationConnection(): Could not create wayland resource " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "WaylandIVIApplicationConnection::WaylandIVIApplicationConnection(): Could not create wayland resource {}", m_clientCredentials); client.postNoMemory(); } } WaylandIVIApplicationConnection::~WaylandIVIApplicationConnection() { - LOG_INFO(CONTEXT_RENDERER, "WaylandIVIApplicationConnection::~WaylandIVIApplicationConnection Connection destroyed " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandIVIApplicationConnection::~WaylandIVIApplicationConnection Connection destroyed {}", m_clientCredentials); if (m_resource) { @@ -72,7 +72,7 @@ namespace ramses::internal INativeWaylandResource& surfaceResource, uint32_t id) { - LOG_INFO(CONTEXT_RENDERER, "WaylandIVIApplicationConnection::iviApplicationIVISurfaceCreate " << iviId); + LOG_INFO(CONTEXT_RENDERER, "WaylandIVIApplicationConnection::iviApplicationIVISurfaceCreate {}", iviId); auto* clientSurface = reinterpret_cast(surfaceResource.getUserData()); @@ -103,8 +103,7 @@ namespace ramses::internal uint32_t id) { const WaylandIviSurfaceId iviSurfaceId{iviId}; - LOG_INFO(CONTEXT_RENDERER, - "WaylandIVIApplicationConnection::IVIApplicationIVISurfaceCreateCallback " << iviSurfaceId << " id:" << id); + LOG_INFO(CONTEXT_RENDERER, "WaylandIVIApplicationConnection::IVIApplicationIVISurfaceCreateCallback {} id:{}", iviSurfaceId, id); auto* iviApplicationConnection = static_cast(wl_resource_get_user_data(iviApplicationConnectionResource)); WaylandClient waylandClient(client); diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVIApplicationGlobal.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVIApplicationGlobal.cpp index 5ef0f3356..c5a28253d 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVIApplicationGlobal.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVIApplicationGlobal.cpp @@ -12,7 +12,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandIVIApplicationConnection.h" #include "internal/Platform/Wayland/EmbeddedCompositor/IWaylandGlobal.h" #include "internal/PlatformAbstraction/PlatformMath.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVISurface.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVISurface.cpp index 32f8d18bb..0132ff41e 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVISurface.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandIVISurface.cpp @@ -12,7 +12,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/INativeWaylandResource.h" #include "internal/Platform/Wayland/EmbeddedCompositor/IWaylandSurface.h" #include "internal/Platform/Wayland/EmbeddedCompositor/IWaylandClient.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -30,8 +30,8 @@ namespace ramses::internal if (surface->hasIviSurface()) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandIVISurface::WaylandIVISurface: failed creating: " << iviSurfaceId - << ". The wayland surface already has a surface with " << surface->getIviSurfaceId() << "attached! " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "WaylandIVISurface::WaylandIVISurface: failed creating: {}. The wayland surface already has a surface with {}attached! {}", + iviSurfaceId, surface->getIviSurfaceId(), m_clientCredentials); iviApplicationConnectionResource.postError(IVI_APPLICATION_ERROR_IVI_ID, "surface already has a ivi-surface"); } @@ -42,8 +42,7 @@ namespace ramses::internal m_resource = client.resourceCreate(&ivi_surface_interface, iviApplicationConnectionResource.getVersion(), id); if (nullptr != m_resource) { - LOG_INFO(CONTEXT_RENDERER, "WaylandIVISurface::WaylandIVISurface: created successfully: " << iviSurfaceId - << " " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandIVISurface::WaylandIVISurface: created successfully: {} {}", iviSurfaceId, m_clientCredentials); m_resource->setImplementation(&m_iviSurfaceInterface, this, ResourceDestroyedCallback); m_surface = surface; @@ -56,8 +55,8 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "WaylandIVISurface::WaylandIVISurface: failed creating " << iviSurfaceId - << ". Failed creating wayland resource " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "WaylandIVISurface::WaylandIVISurface: failed creating {}. Failed creating wayland resource {}", + iviSurfaceId, m_clientCredentials); client.postNoMemory(); } } @@ -66,9 +65,9 @@ namespace ramses::internal const auto credentialsForOtherClient = m_compositor.findSurfaceForStreamTexture(iviSurfaceId).getClientCredentials(); - LOG_ERROR(CONTEXT_RENDERER, "WaylandIVISurface::WaylandIVISurface: failed creating " << iviSurfaceId - << " for " << m_clientCredentials - << ". A wayland surface already exists with same ivi-surface id for " << credentialsForOtherClient); + LOG_ERROR(CONTEXT_RENDERER, + "WaylandIVISurface::WaylandIVISurface: failed creating {} for {}. A wayland surface already exists with same ivi-surface id for {}", + iviSurfaceId, m_clientCredentials, credentialsForOtherClient); iviApplicationConnectionResource.postError(IVI_APPLICATION_ERROR_IVI_ID, "ivi-id is already in use"); } @@ -82,8 +81,7 @@ namespace ramses::internal WaylandIVISurface::~WaylandIVISurface() { - LOG_INFO(CONTEXT_RENDERER, "WaylandIVISurface::~WaylandIVISurface " << m_iviSurfaceId - << " " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandIVISurface::~WaylandIVISurface {} {}", m_iviSurfaceId, m_clientCredentials); if (m_surface != nullptr) { @@ -120,7 +118,7 @@ namespace ramses::internal void WaylandIVISurface::resourceDestroyed() { - LOG_INFO(CONTEXT_RENDERER, "WaylandIVISurface::resourceDestroyed " << m_iviSurfaceId); + LOG_INFO(CONTEXT_RENDERER, "WaylandIVISurface::resourceDestroyed {}", m_iviSurfaceId); // wl_resource is destroyed outside by the Wayland library, so m_resource looses the ownership of the // Wayland resource, so that we don't call wl_resource_destroy. diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandOutputConnection.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandOutputConnection.cpp index a1139f730..d150381ed 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandOutputConnection.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandOutputConnection.cpp @@ -9,7 +9,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandOutputConnection.h" #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandClient.h" #include "internal/Platform/Wayland/EmbeddedCompositor/INativeWaylandResource.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include #include @@ -27,13 +27,13 @@ namespace ramses::internal if (nullptr != m_resource) { m_resource->setImplementation(&m_outputInterface, this, ResourceDestroyedCallback); - LOG_INFO(CONTEXT_RENDERER, "WaylandOutputConnection::WaylandOutputConnection(): Output interface is now provided " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandOutputConnection::WaylandOutputConnection(): Output interface is now provided {}", m_clientCredentials); sendOutputParams(version); } else { - LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputConnection::WaylandOutputConnection(): could not create wayland resource " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputConnection::WaylandOutputConnection(): could not create wayland resource {}", m_clientCredentials); client.postNoMemory(); } } @@ -66,7 +66,7 @@ namespace ramses::internal WaylandOutputConnection::~WaylandOutputConnection() { - LOG_INFO(CONTEXT_RENDERER, "WaylandOutputConnection::~WaylandOutputConnection(): Connection destroyed " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandOutputConnection::~WaylandOutputConnection(): Connection destroyed {}", m_clientCredentials); if (m_resource) { diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandOutputGlobal.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandOutputGlobal.cpp index 4bbbe92b1..8a6480384 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandOutputGlobal.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandOutputGlobal.cpp @@ -11,7 +11,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandClient.h" #include "internal/Platform/Wayland/EmbeddedCompositor/IWaylandDisplay.h" #include "internal/Platform/Wayland/EmbeddedCompositor/IWaylandGlobal.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandRegion.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandRegion.cpp index 97cbce108..14e7fdd56 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandRegion.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandRegion.cpp @@ -10,7 +10,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandClient.h" #include "internal/Platform/Wayland/EmbeddedCompositor/INativeWaylandResource.h" #include "internal/Platform/Wayland/EmbeddedCompositor/IEmbeddedCompositor_Wayland.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -62,13 +62,12 @@ namespace ramses::internal void WaylandRegion::regionAdd([[maybe_unused]] IWaylandClient& client, int32_t x, int32_t y, int32_t width, int32_t height) { - LOG_TRACE(CONTEXT_RENDERER, "WaylandRegion::regionAdd x: " << x << " y: " << y << " width: " << width << " height: " << height); + LOG_TRACE(CONTEXT_RENDERER, "WaylandRegion::regionAdd x: {} y: {} width: {} height: {}", x, y, width, height); } void WaylandRegion::regionSubtract([[maybe_unused]] IWaylandClient& client, int32_t x, int32_t y, int32_t width, int32_t height) { - LOG_TRACE(CONTEXT_RENDERER, - "WaylandRegion::regionSubtract x: " << x << " y: " << y << " width: " << width << " height: " << height); + LOG_TRACE(CONTEXT_RENDERER, "WaylandRegion::regionSubtract x: {} y: {} width: {} height: {}", x, y, width, height); } void WaylandRegion::RegionDestroyCallback([[maybe_unused]] wl_client* client, wl_resource* regionResource) diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellConnection.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellConnection.cpp index 13d287fc9..086bdb3d4 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellConnection.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellConnection.cpp @@ -11,7 +11,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/IWaylandShellConnection.h" #include "internal/Platform/Wayland/EmbeddedCompositor/NativeWaylandResource.h" #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandClient.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal @@ -19,7 +19,7 @@ namespace ramses::internal WaylandShellConnection::WaylandShellConnection(IWaylandClient& client, uint32_t version, uint32_t id) : m_clientCredentials(client.getCredentials()) { - LOG_INFO(CONTEXT_RENDERER, "WaylandShellConnection::WaylandShellConnection Connection created " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandShellConnection::WaylandShellConnection Connection created {}", m_clientCredentials); m_resource = client.resourceCreate(&wl_shell_interface, static_cast(version), id); if (m_resource) @@ -28,14 +28,14 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "WaylandShellConnection::WaylandShellConnection(): Could not create wayland resource " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "WaylandShellConnection::WaylandShellConnection(): Could not create wayland resource {}", m_clientCredentials); client.postNoMemory(); } } WaylandShellConnection::~WaylandShellConnection() { - LOG_INFO(CONTEXT_RENDERER, "WaylandShellConnection::~WaylandShellConnection Connection destroyed " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandShellConnection::~WaylandShellConnection Connection destroyed {}", m_clientCredentials); if (nullptr != m_resource) { diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellGlobal.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellGlobal.cpp index f12a992fc..1a9f61263 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellGlobal.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellGlobal.cpp @@ -12,7 +12,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandClient.h" #include "internal/Platform/Wayland/EmbeddedCompositor/IWaylandGlobal.h" #include "internal/PlatformAbstraction/PlatformMath.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellSurface.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellSurface.cpp index 090293337..246919ebd 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellSurface.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandShellSurface.cpp @@ -9,7 +9,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandShellSurface.h" #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandClient.h" #include "internal/Platform/Wayland/EmbeddedCompositor/NativeWaylandResource.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal @@ -17,7 +17,7 @@ namespace ramses::internal WaylandShellSurface::WaylandShellSurface(IWaylandClient& client, INativeWaylandResource& shellConnectionResource, uint32_t id, IWaylandSurface& surface) : m_clientCredentials(client.getCredentials()) { - LOG_INFO(CONTEXT_RENDERER, "WaylandShellSurface::WaylandShellSurface " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandShellSurface::WaylandShellSurface {}", m_clientCredentials); m_resource = client.resourceCreate(&wl_shell_surface_interface, shellConnectionResource.getVersion(), id); if (nullptr != m_resource) @@ -26,14 +26,13 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "WaylandShellSurface::WaylandShellSurface(): Could not create wayland resource " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "WaylandShellSurface::WaylandShellSurface(): Could not create wayland resource {}", m_clientCredentials); client.postNoMemory(); } if (surface.hasShellSurface()) { - LOG_ERROR(CONTEXT_RENDERER, - "WaylandShellSurface::WaylandShellSurface The surface already has a shell-surface attached " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "WaylandShellSurface::WaylandShellSurface The surface already has a shell-surface attached {}", m_clientCredentials); shellConnectionResource.postError(WL_SHELL_ERROR_ROLE, "surface already has a shell-surface"); } else @@ -50,7 +49,7 @@ namespace ramses::internal WaylandShellSurface::~WaylandShellSurface() { - LOG_INFO(CONTEXT_RENDERER, "WaylandShellSurface::~WaylandShellSurface " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandShellSurface::~WaylandShellSurface {}", m_clientCredentials); if (nullptr != m_surface) { @@ -182,7 +181,7 @@ namespace ramses::internal void WaylandShellSurface::shellSurfaceSetTitle([[maybe_unused]] IWaylandClient& client, const char* title) { - LOG_INFO(CONTEXT_RENDERER, "WaylandShellSurface::shellSurfaceSetTitle title: " << title); + LOG_INFO(CONTEXT_RENDERER, "WaylandShellSurface::shellSurfaceSetTitle title: {}", title); if (m_surface == nullptr) { diff --git a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandSurface.cpp b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandSurface.cpp index 36e7fd543..a9a480102 100644 --- a/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandSurface.cpp +++ b/src/renderer/internal/Platform/Wayland/EmbeddedCompositor/WaylandSurface.cpp @@ -15,7 +15,7 @@ #include "internal/Platform/Wayland/EmbeddedCompositor/IWaylandBuffer.h" #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandCallbackResource.h" #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandBufferResource.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal @@ -24,18 +24,18 @@ namespace ramses::internal : m_compositor(compositor) , m_clientCredentials(client.getCredentials()) { - LOG_DEBUG(CONTEXT_RENDERER, "WaylandSurface::WaylandSurface " << m_clientCredentials); + LOG_DEBUG(CONTEXT_RENDERER, "WaylandSurface::WaylandSurface {}", m_clientCredentials); m_surfaceResource = client.resourceCreate(&wl_surface_interface, version, id); if (m_surfaceResource != nullptr) { - LOG_INFO(CONTEXT_RENDERER, "WaylandSurface::WaylandSurface: created successfully " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandSurface::WaylandSurface: created successfully {}", m_clientCredentials); m_surfaceResource->setImplementation(&m_surfaceInterface, this, ResourceDestroyedCallback); } else { - LOG_ERROR(CONTEXT_RENDERER, "WaylandSurface::WaylandSurface Could not create wayland resource " << m_clientCredentials); + LOG_ERROR(CONTEXT_RENDERER, "WaylandSurface::WaylandSurface Could not create wayland resource {}", m_clientCredentials); client.postNoMemory(); } @@ -44,7 +44,7 @@ namespace ramses::internal WaylandSurface::~WaylandSurface() { - LOG_INFO(CONTEXT_RENDERER, "WaylandSurface::~WaylandSurface: wayland surface destroyed " << m_clientCredentials); + LOG_INFO(CONTEXT_RENDERER, "WaylandSurface::~WaylandSurface: wayland surface destroyed {}", m_clientCredentials); unsetBufferFromSurface(); m_compositor.removeWaylandSurface(*this); @@ -97,7 +97,7 @@ namespace ramses::internal const auto width = res.getWidth(); const auto height = res.getHeight(); auto* wlres = res.getLowLevelHandle(); - LOG_COMMON_RP(CONTEXT_RENDERER, level, "WaylandSurface::surfaceAttach{}: {} shm:{} x:{} y:{} w:{} h:{} res:{}", + LOG_COMMON(CONTEXT_RENDERER, level, "WaylandSurface::surfaceAttach{}: {} shm:{} x:{} y:{} w:{} h:{} res:{}", stage, getIviSurfaceId(), isShm, x, y, width, height, static_cast(wlres)); } } @@ -207,8 +207,7 @@ namespace ramses::internal LOG_TRACE(CONTEXT_RENDERER, "WaylandSurface::surfaceDetach"); LOG_TRACE(CONTEXT_RENDERER, - "WaylandSurface::surfaceAttach: remove current pending buffer from surface with title " - << getSurfaceTitle() << ", " << getIviSurfaceId()); + "WaylandSurface::surfaceAttach: remove current pending buffer from surface with title {}, {}", getSurfaceTitle(), getIviSurfaceId()); m_pendingBuffer = nullptr; m_removeBufferOnNextCommit = true; @@ -253,7 +252,7 @@ namespace ramses::internal LOG_TRACE(CONTEXT_RENDERER, "WaylandSurface::surfaceCommit"); LOG_TRACE(CONTEXT_RENDERER, - "WaylandSurface::surfaceCommit: handling commit message for surface " << getIviSurfaceId()); + "WaylandSurface::surfaceCommit: handling commit message for surface {}", getIviSurfaceId()); // Transfers pending callbacks to list of frame_callbacks. for(const auto& callback : m_pendingCallbacks) @@ -265,7 +264,7 @@ namespace ramses::internal if (m_pendingBuffer) { LOG_TRACE(CONTEXT_RENDERER, - "WaylandSurface::surfaceCommit: new texture data for surface " << getIviSurfaceId()); + "WaylandSurface::surfaceCommit: new texture data for surface {}", getIviSurfaceId()); setBufferToSurface(*m_pendingBuffer); m_pendingBuffer = nullptr; } @@ -275,8 +274,8 @@ namespace ramses::internal { LOG_TRACE( CONTEXT_RENDERER, - "WaylandSurface::surfaceCommit: remove buffer from surface " << getIviSurfaceId() - << " because triggered by earlier empty attachsurface"); + "WaylandSurface::surfaceCommit: remove buffer from surface {} because triggered by earlier empty attachsurface", + getIviSurfaceId()); unsetBufferFromSurface(); } } @@ -424,7 +423,7 @@ namespace ramses::internal else { LOG_TRACE(CONTEXT_RENDERER, - "WaylandSurface::setBufferToSurface client provides content for surface " << getIviSurfaceId()); + "WaylandSurface::setBufferToSurface client provides content for surface {}", getIviSurfaceId()); } setWaylandBuffer(&buffer); @@ -433,7 +432,7 @@ namespace ramses::internal void WaylandSurface::unsetBufferFromSurface() { LOG_TRACE(CONTEXT_RENDERER, - "WaylandSurface::unsetBufferFromSurface: removing buffer used for surface " << getIviSurfaceId()); + "WaylandSurface::unsetBufferFromSurface: removing buffer used for surface {}", getIviSurfaceId()); if (m_buffer) { @@ -475,7 +474,7 @@ namespace ramses::internal if (m_buffer == &buffer) { LOG_TRACE(CONTEXT_RENDERER, - "WaylandSurface::bufferDestroyed(): destroying buffer for surface: " << getIviSurfaceId()); + "WaylandSurface::bufferDestroyed(): destroying buffer for surface: {}", getIviSurfaceId()); unsetBufferFromSurface(); } @@ -483,7 +482,7 @@ namespace ramses::internal if (m_pendingBuffer == &buffer) { LOG_TRACE(CONTEXT_RENDERER, - "WaylandSurface::bufferDestroyed(): destroying pending buffer for surface: " << getIviSurfaceId()); + "WaylandSurface::bufferDestroyed(): destroying pending buffer for surface: {}", getIviSurfaceId()); m_pendingBuffer = nullptr; } } diff --git a/src/renderer/internal/Platform/Wayland/IVI/Platform_Wayland_IVI_EGL_ES_3_0.cpp b/src/renderer/internal/Platform/Wayland/IVI/Platform_Wayland_IVI_EGL_ES_3_0.cpp index f7aa0e115..a6f3dd23e 100644 --- a/src/renderer/internal/Platform/Wayland/IVI/Platform_Wayland_IVI_EGL_ES_3_0.cpp +++ b/src/renderer/internal/Platform/Wayland/IVI/Platform_Wayland_IVI_EGL_ES_3_0.cpp @@ -11,7 +11,7 @@ #include "internal/Platform/Wayland/IVI/SystemCompositorController/SystemCompositorController_Wayland_IVI.h" #include "internal/RendererLib/RendererConfig.h" #include "internal/RendererLib/DisplayConfig.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { diff --git a/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/IVIControllerScreen.cpp b/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/IVIControllerScreen.cpp index c7a6111d4..7559964cd 100644 --- a/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/IVIControllerScreen.cpp +++ b/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/IVIControllerScreen.cpp @@ -24,7 +24,7 @@ namespace ramses::internal IVIControllerScreen::~IVIControllerScreen() { - LOG_INFO(CONTEXT_RENDERER, "IVIControllerSurface::~IVIControllerSurface screen-id: " << m_screenId); + LOG_INFO(CONTEXT_RENDERER, "IVIControllerSurface::~IVIControllerSurface screen-id: {}", m_screenId); ivi_controller_screen_destroy(&m_controllerScreen); } diff --git a/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/IVIControllerSurface.cpp b/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/IVIControllerSurface.cpp index 6e40fff55..e3fda70d6 100644 --- a/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/IVIControllerSurface.cpp +++ b/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/IVIControllerSurface.cpp @@ -20,7 +20,7 @@ namespace ramses::internal , m_iviId(iviId) , m_systemCompositorController(systemCompositorController) { - LOG_INFO(CONTEXT_RENDERER, "IVIControllerSurface::IVIControllerSurface: " << m_iviId); + LOG_INFO(CONTEXT_RENDERER, "IVIControllerSurface::IVIControllerSurface: {}", m_iviId); if (nullptr != m_controllerSurface) { @@ -35,7 +35,7 @@ namespace ramses::internal IVIControllerSurface::~IVIControllerSurface() { - LOG_INFO(CONTEXT_RENDERER, "IVIControllerSurface::~IVIControllerSurface: " << m_iviId); + LOG_INFO(CONTEXT_RENDERER, "IVIControllerSurface::~IVIControllerSurface: {}", m_iviId); if (nullptr != m_controllerSurface) { @@ -125,7 +125,7 @@ namespace ramses::internal { IVIControllerSurface& controllerSurface = *static_cast(data); LOG_INFO(CONTEXT_RENDERER, - "IVIControllerSurface::HandleVisibilityCallback " << controllerSurface.m_iviId << " visibility: " << visibility); + "IVIControllerSurface::HandleVisibilityCallback {} visibility: {}", controllerSurface.m_iviId, visibility); } void IVIControllerSurface::HandleOpacityCallBack(void* data, [[maybe_unused]] ivi_controller_surface* iviControllerSurface, wl_fixed_t opacity) @@ -133,7 +133,7 @@ namespace ramses::internal IVIControllerSurface& controllerSurface = *static_cast(data); LOG_INFO(CONTEXT_RENDERER, - "IVIControllerSurface::HandleOpacityCallBack " << controllerSurface.m_iviId << " opacity: " << opacity); + "IVIControllerSurface::HandleOpacityCallBack {} opacity: {}", controllerSurface.m_iviId, opacity); } void IVIControllerSurface::HandleSourceRectangleCallback( @@ -142,8 +142,7 @@ namespace ramses::internal IVIControllerSurface& controllerSurface = *static_cast(data); LOG_INFO(CONTEXT_RENDERER, - "IVIControllerSurface::HandleSourceRectangleCallback " - << controllerSurface.m_iviId << " x: " << x << " y: " << y << " width: " << width << " height: " << height); + "IVIControllerSurface::HandleSourceRectangleCallback {} x: {} y: {} width: {} height: {}", controllerSurface.m_iviId, x, y, width, height); } void IVIControllerSurface::HandleDestinationRectangleCallback( @@ -152,8 +151,7 @@ namespace ramses::internal IVIControllerSurface& controllerSurface = *static_cast(data); LOG_INFO(CONTEXT_RENDERER, - "IVIControllerSurface::HandleDestinationRectangleCallback " - << controllerSurface.m_iviId << " x: " << x << " y: " << y << " width: " << width << " height: " << height); + "IVIControllerSurface::HandleDestinationRectangleCallback {} x: {} y: {} width: {} height: ", controllerSurface.m_iviId, x, y, width, height); } void IVIControllerSurface::HandleConfigurationCallback(void* data, [[maybe_unused]] ivi_controller_surface* iviControllerSurface, int32_t width, int32_t height) @@ -161,8 +159,7 @@ namespace ramses::internal IVIControllerSurface& controllerSurface = *static_cast(data); LOG_INFO(CONTEXT_RENDERER, - "IVIControllerSurface::HandleConfigurationCallback " << controllerSurface.m_iviId << " width: " - << width << " height: " << height); + "IVIControllerSurface::HandleConfigurationCallback {} width: {} height: {}", controllerSurface.m_iviId, width, height); } void IVIControllerSurface::HandleOrientationCallback(void* data, [[maybe_unused]] ivi_controller_surface* iviControllerSurface, int32_t orientation) @@ -170,8 +167,7 @@ namespace ramses::internal IVIControllerSurface& controllerSurface = *static_cast(data); LOG_INFO(CONTEXT_RENDERER, - "IVIControllerSurface::HandleOrientationCallback " << controllerSurface.m_iviId - << " orientation: " << orientation); + "IVIControllerSurface::HandleOrientationCallback {} orientation: {}", controllerSurface.m_iviId, orientation); } void IVIControllerSurface::HandlePixelformatCallback(void* data, [[maybe_unused]] ivi_controller_surface* iviControllerSurface, int32_t pixelformat) @@ -179,15 +175,14 @@ namespace ramses::internal IVIControllerSurface& controllerSurface = *static_cast(data); LOG_INFO(CONTEXT_RENDERER, - "IVIControllerSurface::HandlePixelformatCallback " << controllerSurface.m_iviId - << " pixelformat: " << pixelformat); + "IVIControllerSurface::HandlePixelformatCallback {} pixelformat: {}", controllerSurface.m_iviId, pixelformat); } void IVIControllerSurface::HandleLayerCallback(void* data, [[maybe_unused]] ivi_controller_surface* iviControllerSurface, [[maybe_unused]] ivi_controller_layer* layer) { IVIControllerSurface& controllerSurface = *static_cast(data); - LOG_INFO(CONTEXT_RENDERER, "IVIControllerSurface::HandleLayerCallback: surface " << controllerSurface.m_iviId << " added to layer"); + LOG_INFO(CONTEXT_RENDERER, "IVIControllerSurface::HandleLayerCallback: surface {} added to layer", controllerSurface.m_iviId); } void IVIControllerSurface::HandleStatsCallback(void* data, @@ -201,16 +196,15 @@ namespace ramses::internal IVIControllerSurface& controllerSurface = *static_cast(data); LOG_INFO(CONTEXT_RENDERER, - "IVIControllerSurface::HandleStatsCallback " - << controllerSurface.m_iviId << " redrawCount: " << redrawCount << " frameCount: " << frameCount - << " updateCount: " << updateCount << " pid: " << pid << " processName: " << processName); + "IVIControllerSurface::HandleStatsCallback {} redrawCount: {} frameCount: {} updateCount: {} pid: {} processName: {}", + controllerSurface.m_iviId, redrawCount, frameCount, updateCount, pid, processName); } void IVIControllerSurface::HandleDestroyedCallback(void* data, [[maybe_unused]] ivi_controller_surface* iviControllerSurface) { IVIControllerSurface& controllerSurface = *static_cast(data); - LOG_INFO(CONTEXT_RENDERER, "IVIControllerSurface::HandleDestroyedCallback " << controllerSurface.m_iviId); + LOG_INFO(CONTEXT_RENDERER, "IVIControllerSurface::HandleDestroyedCallback {}", controllerSurface.m_iviId); SystemCompositorController_Wayland_IVI& systemCompositorController = controllerSurface.m_systemCompositorController; systemCompositorController.deleteControllerSurface(controllerSurface); @@ -221,7 +215,6 @@ namespace ramses::internal IVIControllerSurface& controllerSurface = *static_cast(data); LOG_INFO(CONTEXT_RENDERER, - "IVIControllerSurface::HandleContentCallback " << controllerSurface.m_iviId - << " contentState: " << contentState); + "IVIControllerSurface::HandleContentCallback {} contentState: {}", controllerSurface.m_iviId, contentState); } } diff --git a/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/SystemCompositorController_Wayland_IVI.cpp b/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/SystemCompositorController_Wayland_IVI.cpp index 5c8a9d49d..5a1926760 100644 --- a/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/SystemCompositorController_Wayland_IVI.cpp +++ b/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/SystemCompositorController_Wayland_IVI.cpp @@ -26,7 +26,7 @@ namespace ramses::internal SystemCompositorController_Wayland_IVI::SystemCompositorController_Wayland_IVI(std::string_view waylandDisplay) : m_waylandDisplay(waylandDisplay) { - LOG_INFO(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::SystemCompositorController_Wayland_IVI (" << waylandDisplay << ")"); + LOG_INFO(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::SystemCompositorController_Wayland_IVI ({})", waylandDisplay); } SystemCompositorController_Wayland_IVI::~SystemCompositorController_Wayland_IVI() @@ -136,8 +136,7 @@ namespace ramses::internal bool SystemCompositorController_Wayland_IVI::setSurfaceVisibility(WaylandIviSurfaceId surfaceId, bool visibility) { LOG_INFO(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::setSurfaceVisibility " - << surfaceId << " visibility: " << visibility); + "SystemCompositorController_Wayland_IVI::setSurfaceVisibility {} visibility: {}", surfaceId, visibility); IVIControllerSurface& controllerSurface = getOrCreateControllerSurface(surfaceId); controllerSurface.setVisibility(visibility); @@ -149,7 +148,7 @@ namespace ramses::internal bool SystemCompositorController_Wayland_IVI::setSurfaceOpacity(WaylandIviSurfaceId surfaceId, float opacity) { LOG_INFO(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::setOpacity " << surfaceId << " opacity: " << opacity); + "SystemCompositorController_Wayland_IVI::setOpacity {} opacity: {}", surfaceId, opacity); IVIControllerSurface& controllerSurface = getOrCreateControllerSurface(surfaceId); @@ -165,9 +164,8 @@ namespace ramses::internal WaylandIviSurfaceId surfaceId, int32_t x, int32_t y, int32_t width, int32_t height) { LOG_INFO(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::setSurfaceDestinationRectangle " - << surfaceId << " position: (" << x << ", " << y << ", " << width << ", " << height - << ")"); + "SystemCompositorController_Wayland_IVI::setSurfaceDestinationRectangle {}: position: ({}, {}, {}, {})", + surfaceId, x, y, width, height); IVIControllerSurface& controllerSurface = getOrCreateControllerSurface(surfaceId); @@ -186,8 +184,8 @@ namespace ramses::internal // expect single screen if (m_controllerScreens.size() != 1) { - LOG_WARN(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::screenshot fileName " << fileName << " for screenId " << screenIviId << - " failed because found " << m_controllerScreens.size() << " screens"); + LOG_WARN(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::screenshot fileName {} for screenId {} failed because found {} screens", + fileName, screenIviId, m_controllerScreens.size()); return false; } screen = m_controllerScreens.begin()->get(); @@ -202,8 +200,7 @@ namespace ramses::internal } if (!screen) { - LOG_WARN(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::screenshot fileName " << fileName << " for screenId " << screenIviId << - " failed because sceenId not found"); + LOG_WARN(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::screenshot fileName {} for screenId {} failed because sceenId not found", fileName, screenIviId); return false; } } @@ -214,8 +211,7 @@ namespace ramses::internal // ensure that all compositor operations have finished wl_display_roundtrip(m_display); - LOG_INFO(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::screenshot: Saved screenshot for screen " - << screen->getScreenId() << " as " << fileName); + LOG_INFO(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::screenshot: Saved screenshot for screen {} as {}", screen->getScreenId(), fileName); return true; } @@ -224,7 +220,7 @@ namespace ramses::internal WaylandIviLayerId layerId) { LOG_INFO(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::addSurfaceToLayer " << surfaceId << " " << layerId); + "SystemCompositorController_Wayland_IVI::addSurfaceToLayer {} {}", surfaceId, layerId); // Workaround for bug in compositor, create a new ivi_controller_layer here, otherwise the surface list of the // layer can get wrong, when another application has also changed it in the meantime. @@ -232,7 +228,7 @@ namespace ramses::internal if (nullptr == controllerLayer) { LOG_ERROR(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::addSurfaceToLayer ivi_controller_layer_create failed, " << layerId); + "SystemCompositorController_Wayland_IVI::addSurfaceToLayer ivi_controller_layer_create failed, {}", layerId); return false; } @@ -260,7 +256,7 @@ namespace ramses::internal WaylandIviLayerId layerId) { LOG_INFO(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::removeSurfaceFromLayer " << surfaceId << " " << layerId); + "SystemCompositorController_Wayland_IVI::removeSurfaceFromLayer {} {}", surfaceId, layerId); // Workaround for bug in compositor, create a new ivi_controller_layer here, otherwise the surface list of the // layer can get wrong, when another application has also changed it in the meantime. @@ -268,8 +264,7 @@ namespace ramses::internal if (nullptr == controllerLayer) { LOG_ERROR(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::removeSurfaceFromLayer ivi_controller_layer_create " - "failed " << layerId); + "SystemCompositorController_Wayland_IVI::removeSurfaceFromLayer ivi_controller_layer_create failed {}", layerId); return false; } @@ -277,7 +272,7 @@ namespace ramses::internal if (nullptr == controllerSurface) { LOG_ERROR(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::removeSurfaceFromLayer " << surfaceId << " does not exist!"); + "SystemCompositorController_Wayland_IVI::removeSurfaceFromLayer {} does not exist!", surfaceId); return false; } @@ -302,14 +297,14 @@ namespace ramses::internal bool SystemCompositorController_Wayland_IVI::destroySurface(WaylandIviSurfaceId surfaceId) { LOG_INFO(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::destroySurface " << surfaceId); + "SystemCompositorController_Wayland_IVI::destroySurface {}", surfaceId); IVIControllerSurface* controllerSurface = getControllerSurface(surfaceId); if (nullptr == controllerSurface) { LOG_ERROR(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::destroySurface " << surfaceId << " does not exist!"); + "SystemCompositorController_Wayland_IVI::destroySurface {} does not exist!", surfaceId); return false; } controllerSurface->destroy(); @@ -322,8 +317,7 @@ namespace ramses::internal bool SystemCompositorController_Wayland_IVI::setLayerVisibility(WaylandIviLayerId layerId, bool visibility) { LOG_INFO(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::setLayerVisibility " - << layerId << " visibility: " << visibility); + "SystemCompositorController_Wayland_IVI::setLayerVisibility {} visibility: {}", layerId, visibility); // Workaround for bug in compositor, create a new ivi_controller_layer here, otherwise the surface list of the // layer can get wrong, when another application has also changed it in the meantime. @@ -331,8 +325,7 @@ namespace ramses::internal if (nullptr == controllerLayer) { LOG_ERROR(CONTEXT_RENDERER, - "SystemCompositorController_Wayland_IVI::setLayerVisibility ivi_controller_layer_create " - "failed, " << layerId); + "SystemCompositorController_Wayland_IVI::setLayerVisibility ivi_controller_layer_create failed, {}", layerId); return false; } @@ -387,7 +380,7 @@ namespace ramses::internal if (nullptr == nativeControllerSurface) { - LOG_ERROR(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::getOrCreateControllerSurface " << iviId); + LOG_ERROR(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::getOrCreateControllerSurface {}", iviId); } controllerSurface = new IVIControllerSurface(nativeControllerSurface, iviId, *this); @@ -423,11 +416,11 @@ namespace ramses::internal uint32_t id_screen, ivi_controller_screen* nativeControllerScreen) { - LOG_INFO(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::iviControllerHandleScreen Detected ivi-screen: " << id_screen); + LOG_INFO(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::iviControllerHandleScreen Detected ivi-screen: {}", id_screen); if (nullptr != getControllerScreen(id_screen)) { - LOG_ERROR(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::iviControllerHandleScreen Screen with id " << id_screen << " already registered!"); + LOG_ERROR(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::iviControllerHandleScreen Screen with id {} already registered!", id_screen); assert(false); return; } @@ -445,13 +438,13 @@ namespace ramses::internal // NOLINTNEXTLINE(readability-convert-member-functions-to-static) void SystemCompositorController_Wayland_IVI::iviControllerHandleLayer([[maybe_unused]] ivi_controller* controller, [[maybe_unused]] uint32_t id_layer) { - LOG_INFO(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::iviControllerHandleLayer Detected " << WaylandIviLayerId(id_layer)); + LOG_INFO(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::iviControllerHandleLayer Detected {}", WaylandIviLayerId(id_layer)); } void SystemCompositorController_Wayland_IVI::iviControllerHandleSurface([[maybe_unused]] ivi_controller* controller, uint32_t iviID) { const WaylandIviSurfaceId surfaceId{iviID}; - LOG_INFO(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::iviControllerHandleSurface Detected " << surfaceId); + LOG_INFO(CONTEXT_RENDERER, "SystemCompositorController_Wayland_IVI::iviControllerHandleSurface Detected {}", surfaceId); getOrCreateControllerSurface(surfaceId); } diff --git a/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/WaylandOutput.cpp b/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/WaylandOutput.cpp index 24222174a..b35e80214 100644 --- a/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/WaylandOutput.cpp +++ b/src/renderer/internal/Platform/Wayland/IVI/SystemCompositorController/WaylandOutput.cpp @@ -28,14 +28,14 @@ namespace ramses::internal // GENIVI uses the proxy-id of an wl_output as it's screen-id. m_screenId = wl_proxy_get_id(reinterpret_cast(m_output)); - LOG_INFO(CONTEXT_RENDERER, "WaylandOutput::WaylandOutput screen-id: " << m_screenId); + LOG_INFO(CONTEXT_RENDERER, "WaylandOutput::WaylandOutput screen-id: {}", m_screenId); wl_output_add_listener(m_output, &m_outputListener, this); } WaylandOutput::~WaylandOutput() { - LOG_INFO(CONTEXT_RENDERER, "WaylandOutput::~WaylandOutput screen-id: " << m_screenId); + LOG_INFO(CONTEXT_RENDERER, "WaylandOutput::~WaylandOutput screen-id: {}", m_screenId); if (nullptr != m_output) { @@ -48,9 +48,8 @@ namespace ramses::internal if (0 != (flags & WL_OUTPUT_MODE_CURRENT)) { LOG_INFO(CONTEXT_RENDERER, - "WaylandOutput::outputHandleMode screen-id: " << m_screenId - << " resolution: " << width << " x " << height - << " refresh rate: " << refresh); + "WaylandOutput::outputHandleMode screen-id: {} resolution: {} x {} refresh rate: {}", + m_screenId, width, height, refresh); } } diff --git a/src/renderer/internal/Platform/Wayland/IVI/Window_Wayland_IVI.cpp b/src/renderer/internal/Platform/Wayland/IVI/Window_Wayland_IVI.cpp index 385a33619..cb186a9e6 100644 --- a/src/renderer/internal/Platform/Wayland/IVI/Window_Wayland_IVI.cpp +++ b/src/renderer/internal/Platform/Wayland/IVI/Window_Wayland_IVI.cpp @@ -7,7 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/Platform/Wayland/IVI/Window_Wayland_IVI.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "ivi-application-client-protocol.h" namespace ramses::internal @@ -46,7 +46,7 @@ namespace ramses::internal bool Window_Wayland_IVI::createSurface() { - LOG_INFO(CONTEXT_RENDERER, "Window_Wayland_IVI::createSurface ivi id: " << m_waylandIviSurfaceID.getValue()); + LOG_INFO(CONTEXT_RENDERER, "Window_Wayland_IVI::createSurface ivi id: {}", m_waylandIviSurfaceID.getValue()); if (m_iviApplicationRegistry == nullptr) { diff --git a/src/renderer/internal/Platform/Wayland/InputHandling_Wayland.cpp b/src/renderer/internal/Platform/Wayland/InputHandling_Wayland.cpp index aebafdabe..a8feef86a 100644 --- a/src/renderer/internal/Platform/Wayland/InputHandling_Wayland.cpp +++ b/src/renderer/internal/Platform/Wayland/InputHandling_Wayland.cpp @@ -7,7 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/Platform/Wayland/InputHandling_Wayland.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/Warnings.h" #include @@ -161,7 +161,7 @@ namespace ramses::internal } break; default: - LOG_WARN(CONTEXT_RENDERER, "unhandled wayland axis event " << axis); + LOG_WARN(CONTEXT_RENDERER, "unhandled wayland axis event {}", axis); } } @@ -226,7 +226,7 @@ namespace ramses::internal inputHandling.m_windowEventHandler.onKeyEvent(EKeyEvent::Pressed, inputHandling.m_keyModifiers, ramsesKeyCode); break; default: - LOG_WARN(CONTEXT_RENDERER, "unhandled wayland keyboard handle key event: " << state_w); + LOG_WARN(CONTEXT_RENDERER, "unhandled wayland keyboard handle key event: {}", state_w); } } diff --git a/src/renderer/internal/Platform/Wayland/Logger_Wayland.cpp b/src/renderer/internal/Platform/Wayland/Logger_Wayland.cpp index 2da049085..d751e113f 100644 --- a/src/renderer/internal/Platform/Wayland/Logger_Wayland.cpp +++ b/src/renderer/internal/Platform/Wayland/Logger_Wayland.cpp @@ -7,7 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/Platform/Wayland/Logger_Wayland.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include #include #include @@ -21,13 +21,13 @@ namespace ramses::internal void WaylandClientLog(const char* fmt, va_list ap) { std::vsnprintf(buffer.data(), buffer.size(), fmt, ap); - LOG_ERROR(CONTEXT_RENDERER, "Logger_Wayland::ClientLog: " << buffer.data()); + LOG_ERROR(CONTEXT_RENDERER, "Logger_Wayland::ClientLog: {}", buffer.data()); } void WaylandServerLog(const char* fmt, va_list ap) { std::vsnprintf(buffer.data(), buffer.size(), fmt, ap); - LOG_ERROR(CONTEXT_RENDERER, "Logger_Wayland::ServerLog: " << buffer.data()); + LOG_ERROR(CONTEXT_RENDERER, "Logger_Wayland::ServerLog: {}", buffer.data()); } } diff --git a/src/renderer/internal/Platform/Wayland/Platform_Wayland_EGL.cpp b/src/renderer/internal/Platform/Wayland/Platform_Wayland_EGL.cpp index f32be18b4..c4ff05d27 100644 --- a/src/renderer/internal/Platform/Wayland/Platform_Wayland_EGL.cpp +++ b/src/renderer/internal/Platform/Wayland/Platform_Wayland_EGL.cpp @@ -13,7 +13,7 @@ #include "internal/RendererLib/PlatformBase/EmbeddedCompositor_Dummy.h" #include "internal/Platform/Wayland/EmbeddedCompositor/EmbeddedCompositor_Wayland.h" #include "internal/Platform/Wayland/EmbeddedCompositor/TextureUploadingAdapter_Wayland.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { diff --git a/src/renderer/internal/Platform/Wayland/WaylandEGLExtensionProcs.cpp b/src/renderer/internal/Platform/Wayland/WaylandEGLExtensionProcs.cpp index b5d60ac13..9aee8ca13 100644 --- a/src/renderer/internal/Platform/Wayland/WaylandEGLExtensionProcs.cpp +++ b/src/renderer/internal/Platform/Wayland/WaylandEGLExtensionProcs.cpp @@ -7,7 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/Platform/Wayland/WaylandEGLExtensionProcs.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/StringUtils.h" #include @@ -98,7 +98,7 @@ namespace ramses::internal { return true; } - LOG_INFO(CONTEXT_RENDERER, "WaylandEGLExtensionProcs::CheckExtensionAvailable Extension " << extensionName << " not supported!"); + LOG_INFO(CONTEXT_RENDERER, "WaylandEGLExtensionProcs::CheckExtensionAvailable Extension {} not supported!", extensionName); return false; } diff --git a/src/renderer/internal/Platform/Wayland/WaylandEnvironmentUtils.cpp b/src/renderer/internal/Platform/Wayland/WaylandEnvironmentUtils.cpp index 4d3949f6e..62ad8736d 100644 --- a/src/renderer/internal/Platform/Wayland/WaylandEnvironmentUtils.cpp +++ b/src/renderer/internal/Platform/Wayland/WaylandEnvironmentUtils.cpp @@ -62,11 +62,11 @@ namespace ramses::internal const File socketFile(socketFullPath); if (socketFile.exists()) { - LOG_INFO(CONTEXT_RENDERER, "WaylandEnvironmentUtils::LogEnvironmentState: Socket file " << socketFullPath << " exists."); + LOG_INFO(CONTEXT_RENDERER, "WaylandEnvironmentUtils::LogEnvironmentState: Socket file {} exists.", socketFullPath); } else { - LOG_WARN(CONTEXT_RENDERER, "WaylandEnvironmentUtils::LogEnvironmentState: Socket file " << socketFullPath << " does not exist."); + LOG_WARN(CONTEXT_RENDERER, "WaylandEnvironmentUtils::LogEnvironmentState: Socket file {} does not exist.", socketFullPath); } } @@ -113,10 +113,8 @@ namespace ramses::internal const bool waylandDisplayFoundInEnvironmentVars = PlatformEnvironmentVariables::get("WAYLAND_DISPLAY", waylandDisplayEnvironmentVar); const bool waylandSocketFoundInEnvironmentVars = PlatformEnvironmentVariables::get("WAYLAND_SOCKET", waylandSocketEnvironmentVar); - LOG_INFO(CONTEXT_RENDERER, "WaylandEnvironmentUtils::LogEnvironmentState: Wayland display set on display config=" << waylandDisplayName - << ", XDG_RUNTIME_DIR=" << xdgPathEnvironmentVar - << ", WAYLAND_DISPLAY=" << waylandDisplayEnvironmentVar - << ", WAYLAND_SOCKET=" << waylandSocketEnvironmentVar); + LOG_INFO(CONTEXT_RENDERER, "WaylandEnvironmentUtils::LogEnvironmentState: Wayland display set on display config={}, XDG_RUNTIME_DIR={}, WAYLAND_DISPLAY={}, WAYLAND_SOCKET={}", + waylandDisplayName, xdgPathEnvironmentVar, waylandDisplayEnvironmentVar, waylandSocketEnvironmentVar); if (!waylandDisplayName.empty()) { diff --git a/src/renderer/internal/Platform/Wayland/Window_Wayland.cpp b/src/renderer/internal/Platform/Wayland/Window_Wayland.cpp index 7c89e5793..121c18b4a 100644 --- a/src/renderer/internal/Platform/Wayland/Window_Wayland.cpp +++ b/src/renderer/internal/Platform/Wayland/Window_Wayland.cpp @@ -7,7 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/Platform/Wayland/Window_Wayland.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Platform/Wayland/WaylandEnvironmentUtils.h" #include "internal/RendererLib/DisplayConfig.h" #include @@ -225,7 +225,7 @@ namespace ramses::internal pollfd pollFileDescriptor = {m_wlContext.displayFD, POLLIN, 0}; if (poll(&pollFileDescriptor, 1u, static_cast(pollTime.count())) == -1) { - LOG_ERROR(CONTEXT_RENDERER, "Window_Wayland::dispatchWaylandDisplayEvents: error in poll :" << std::strerror(errno)); + LOG_ERROR(CONTEXT_RENDERER, "Window_Wayland::dispatchWaylandDisplayEvents: error in poll :{}", std::strerror(errno)); assert(false); return; } diff --git a/src/renderer/internal/Platform/Wayland/WlShell/Window_Wayland_Shell.cpp b/src/renderer/internal/Platform/Wayland/WlShell/Window_Wayland_Shell.cpp index d590ba0c5..bd7b7888b 100644 --- a/src/renderer/internal/Platform/Wayland/WlShell/Window_Wayland_Shell.cpp +++ b/src/renderer/internal/Platform/Wayland/WlShell/Window_Wayland_Shell.cpp @@ -7,7 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/Platform/Wayland/WlShell/Window_Wayland_Shell.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { diff --git a/src/renderer/internal/Platform/Windows/Context_WGL.cpp b/src/renderer/internal/Platform/Windows/Context_WGL.cpp index 1348788e2..327697378 100644 --- a/src/renderer/internal/Platform/Windows/Context_WGL.cpp +++ b/src/renderer/internal/Platform/Windows/Context_WGL.cpp @@ -9,7 +9,7 @@ #include "internal/Platform/Windows/Context_WGL.h" #include "internal/Platform/Windows/HiddenWindow.h" #include "internal/Platform/Windows/Window_Windows.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -55,7 +55,7 @@ namespace ramses::internal if (0 == m_wglContextHandle) { uint32_t error = GetLastError(); - LOG_ERROR(CONTEXT_RENDERER, "wglCreateContextAttribsARB failed, returned context handle is 0. GetLastError returned error code " << error); + LOG_ERROR(CONTEXT_RENDERER, "wglCreateContextAttribsARB failed, returned context handle is 0. GetLastError returned error code {}", error); return false; } @@ -163,7 +163,7 @@ namespace ramses::internal if (!valid || numFormats == 0) { - LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat() m_ext.procs.wglChoosePixelFormatARB failed. valid = " << valid << ", numFormats = " << numFormats); + LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat() m_ext.procs.wglChoosePixelFormatARB failed. valid = {}, numFormats = {}", valid, numFormats); return false; } @@ -186,27 +186,23 @@ namespace ramses::internal return false; } - LOG_INFO(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: OpenGL pixel format: " - << "COLOR_BITS :" << resultAttribs[0] - << ", ALPHA_BITS :" << resultAttribs[1] - << ", DEPTH_BITS :" << resultAttribs[2] - << ", STENCIL_BITS :" << resultAttribs[3] - << ", SAMPLE_COUNT :" << resultAttribs[4]); + LOG_INFO(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: OpenGL pixel format: COLOR_BITS:{}, ALPHA_BITS :{}, DEPTH_BITS : {}, STENCIL_BITS :{}, SAMPLE_COUNT : ", + resultAttribs[0], resultAttribs[1], resultAttribs[2], resultAttribs[3], resultAttribs[4]); if (resultAttribs[0] != colorBits) - LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: could not get Requested pixel format. actual COLOR_BITS :" << resultAttribs[0] << " vs requested :" << colorBits); + LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: could not get Requested pixel format. actual COLOR_BITS :{} vs requested :{}", resultAttribs[0], colorBits); if (resultAttribs[1] != alphaBits) - LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: could not get Requested pixel format. actual ALPHA_BITS :" << resultAttribs[1] << " vs requested :" << alphaBits); + LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: could not get Requested pixel format. actual ALPHA_BITS :{} vs requested :{}", resultAttribs[1], alphaBits); if (resultAttribs[2] != depthBits) - LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: could not get Requested pixel format. actual DEPTH_BITS :" << resultAttribs[2] << " vs requested :" << depthBits); + LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: could not get Requested pixel format. actual DEPTH_BITS :{} vs requested :{}", resultAttribs[2], depthBits); if (resultAttribs[3] != stencilBits) - LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: could not get Requested pixel format. actual STENCIL_BITS :" << resultAttribs[3] << " vs requested :" << stencilBits); + LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: could not get Requested pixel format. actual STENCIL_BITS :{} vs requested :{}", resultAttribs[3], stencilBits); if (resultAttribs[4] != sampleCount) - LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: could not get Requested pixel format. actual SAMPLE_COUNT :" << resultAttribs[4] << " vs requested :" << sampleCount); + LOG_WARN(CONTEXT_RENDERER, "Context_WGL::initCustomPixelFormat: could not get Requested pixel format. actual SAMPLE_COUNT :{} vs requested :{}", resultAttribs[4], sampleCount); // This code is very misleading - it looks like setting up a surface pixel format // but it doesn't, the data is actually unused diff --git a/src/renderer/internal/Platform/Windows/HiddenWindow.cpp b/src/renderer/internal/Platform/Windows/HiddenWindow.cpp index 0af616565..31571975d 100644 --- a/src/renderer/internal/Platform/Windows/HiddenWindow.cpp +++ b/src/renderer/internal/Platform/Windows/HiddenWindow.cpp @@ -8,7 +8,7 @@ #include "windows.h" #include "internal/Platform/Windows/HiddenWindow.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { diff --git a/src/renderer/internal/Platform/Windows/Platform_Windows_WGL.cpp b/src/renderer/internal/Platform/Windows/Platform_Windows_WGL.cpp index 37b804145..34cb87ed6 100644 --- a/src/renderer/internal/Platform/Windows/Platform_Windows_WGL.cpp +++ b/src/renderer/internal/Platform/Windows/Platform_Windows_WGL.cpp @@ -12,7 +12,7 @@ #include "internal/Platform/Windows/Window_Windows.h" #include "internal/RendererLib/PlatformBase/EmbeddedCompositor_Dummy.h" #include "internal/RendererLib/DisplayConfig.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -70,7 +70,7 @@ namespace ramses::internal m_contextConfig = contextConfig; break; } - LOG_ERROR_P(CONTEXT_RENDERER, "Windows_WGL::createContext failed: {}. Ramses will crash if any scene uses features of this version.", GetVersionString(contextConfig)); + LOG_ERROR(CONTEXT_RENDERER, "Windows_WGL::createContext failed: {}. Ramses will crash if any scene uses features of this version.", GetVersionString(contextConfig)); } return m_context != nullptr; } @@ -130,7 +130,7 @@ namespace ramses::internal if (context->init()) { - LOG_INFO_P(CONTEXT_RENDERER, "Windows_WGL::createContext: {}", GetVersionString(contextConfig)); + LOG_INFO(CONTEXT_RENDERER, "Windows_WGL::createContext: {}", GetVersionString(contextConfig)); return context; } diff --git a/src/renderer/internal/Platform/Windows/WglExtensions.cpp b/src/renderer/internal/Platform/Windows/WglExtensions.cpp index 1391003f5..cdc66af51 100644 --- a/src/renderer/internal/Platform/Windows/WglExtensions.cpp +++ b/src/renderer/internal/Platform/Windows/WglExtensions.cpp @@ -64,7 +64,7 @@ namespace ramses::internal const char* contextExtensionsNativeString = procs.wglGetExtensionsStringARB(hiddenWindow.displayHandle); if (0 != contextExtensionsNativeString) { - LOG_INFO(CONTEXT_RENDERER, "WglExtensions::WglExtensions: " << contextExtensionsNativeString); + LOG_INFO(CONTEXT_RENDERER, "WglExtensions::WglExtensions: {}", contextExtensionsNativeString); Context_Base::ParseContextExtensionsHelper(contextExtensionsNativeString, m_extensionNames); } else diff --git a/src/renderer/internal/Platform/Windows/Window_Windows.cpp b/src/renderer/internal/Platform/Windows/Window_Windows.cpp index ca258e992..b820d0866 100644 --- a/src/renderer/internal/Platform/Windows/Window_Windows.cpp +++ b/src/renderer/internal/Platform/Windows/Window_Windows.cpp @@ -10,7 +10,7 @@ #include "internal/RendererLib/PlatformInterface/IWindowEventHandler.h" #include "internal/RendererLib/DisplayConfig.h" #include "internal/RendererLib/Enums/EKeyModifier.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/PlatformAbstraction/Collections/Guid.h" #include "fmt/format.h" #include @@ -269,7 +269,7 @@ namespace ramses::internal setFullscreen(m_fullscreen); - LOG_INFO(CONTEXT_RENDERER, "Surface_Windows::Surface_Windows: created window '" << getTitle() << "', size = " << getWidth() << "x" << getHeight() << ", posx = " << getPosX() << ", posy = " << getPosY()); + LOG_INFO(CONTEXT_RENDERER, "Surface_Windows::Surface_Windows: created window '{}', size = {}x{}, posx = {}, posy = {}", getTitle(), getWidth(), getHeight(), getPosX(), getPosY()); return true; } @@ -294,11 +294,11 @@ namespace ramses::internal if (messageBuffer) { - LOG_ERROR(CONTEXT_RENDERER, "Windows API error: " << messageBuffer); + LOG_ERROR(CONTEXT_RENDERER, "Windows API error: {}", messageBuffer); } else { - LOG_ERROR(CONTEXT_RENDERER, "Windows API error ID: " << errorMessageID); + LOG_ERROR(CONTEXT_RENDERER, "Windows API error ID: {}", errorMessageID); } //Free the buffer. @@ -370,7 +370,7 @@ namespace ramses::internal const bool keyReleased = WM_KEYUP == windowsMsg || WM_SYSKEYUP == windowsMsg; if (!keyPressed && !keyReleased) { - LOG_WARN(CONTEXT_RENDERER, "invalid handle key event: " << windowsMsg); + LOG_WARN(CONTEXT_RENDERER, "invalid handle key event: {}", windowsMsg); return; } diff --git a/src/renderer/internal/Platform/X11/Window_X11.cpp b/src/renderer/internal/Platform/X11/Window_X11.cpp index a63ddf85b..69330ed8a 100644 --- a/src/renderer/internal/Platform/X11/Window_X11.cpp +++ b/src/renderer/internal/Platform/X11/Window_X11.cpp @@ -8,7 +8,7 @@ #include "internal/Platform/X11/Window_X11.h" #include "internal/RendererLib/DisplayConfig.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/Warnings.h" #include @@ -212,7 +212,7 @@ namespace ramses::internal { m_X11WindowData.window = m_userProvidedWindowHandle.getValue(); - LOG_INFO(CONTEXT_RENDERER, "Window_X11::init from existing X11 window: " << m_X11WindowData.window); + LOG_INFO(CONTEXT_RENDERER, "Window_X11::init from existing X11 window: {}", m_X11WindowData.window); m_X11WindowData.display = XOpenDisplay(nullptr); if (!m_X11WindowData.display) @@ -260,7 +260,7 @@ namespace ramses::internal // update window size in global config, if required const int32_t displayWidth = XDisplayWidth(m_X11WindowData.display, m_X11WindowData.screen); const int32_t displayHeight = XDisplayHeight(m_X11WindowData.display, m_X11WindowData.screen); - LOG_DEBUG(CONTEXT_RENDERER, "Screen size is " << displayWidth << " by " << displayHeight << " pixels"); + LOG_DEBUG(CONTEXT_RENDERER, "Screen size is {} by {} pixels", displayWidth, displayHeight); if (m_fullscreen) { m_width = displayWidth; @@ -366,7 +366,7 @@ namespace ramses::internal // set window title XStoreName(m_X11WindowData.display, m_X11WindowData.window, m_windowName.c_str()); - LOG_INFO(CONTEXT_RENDERER, "Created X11 Window, size " << m_width << " by " << m_height << " pixels"); + LOG_INFO(CONTEXT_RENDERER, "Created X11 Window, size {} by {} pixels", m_width, m_height); return true; } @@ -578,7 +578,7 @@ namespace ramses::internal } break; default: - LOG_DEBUG(CONTEXT_RENDERER, "Other X11 event received, type " << event.type); + LOG_DEBUG(CONTEXT_RENDERER, "Other X11 event received, type {}", event.type); break; } } diff --git a/src/renderer/internal/Platform/iOS/Window_iOS.mm b/src/renderer/internal/Platform/iOS/Window_iOS.mm index bfdb0fd08..fd57cb798 100644 --- a/src/renderer/internal/Platform/iOS/Window_iOS.mm +++ b/src/renderer/internal/Platform/iOS/Window_iOS.mm @@ -8,7 +8,7 @@ #include "internal/Platform/iOS/Window_iOS.h" #include "internal/RendererLib/DisplayConfig.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/Warnings.h" #include "QuartzCore/CAMetalLayer.h" diff --git a/src/renderer/internal/RendererLib/AsyncEffectUploader.cpp b/src/renderer/internal/RendererLib/AsyncEffectUploader.cpp index 83093c16c..c82dfd7ac 100644 --- a/src/renderer/internal/RendererLib/AsyncEffectUploader.cpp +++ b/src/renderer/internal/RendererLib/AsyncEffectUploader.cpp @@ -15,18 +15,18 @@ #include "internal/RendererLib/PlatformInterface/IPlatform.h" #include "internal/SceneGraph/Resource/EffectResource.h" #include "internal/Watchdog/IThreadAliveNotifier.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal { - AsyncEffectUploader::AsyncEffectUploader(IPlatform& platform, IRenderBackend& renderBackend, IThreadAliveNotifier& notifier, int logPrefixID) + AsyncEffectUploader::AsyncEffectUploader(IPlatform& platform, IRenderBackend& renderBackend, IThreadAliveNotifier& notifier, DisplayHandle display) : m_platform(platform) , m_renderBackend(renderBackend) - , m_thread{ fmt::format("R_EffUpload{}", logPrefixID) } + , m_thread{ fmt::format("EffUpload{}", display) } , m_notifier(notifier) , m_aliveIdentifier(notifier.registerThread()) - , m_logPrefixID{ logPrefixID } + , m_displayHandle{ display } { } @@ -93,7 +93,7 @@ namespace ramses::internal m_effectsToUpload.swap(effectsToUpload); } - LOG_TRACE(CONTEXT_RENDERER, "AsyncEffectUploader::uploadEffectsOrWait: will upload: " << effectsToUpload.size() << ", uploaded in cache:" << m_effectsUploadedCache.size()); + LOG_TRACE(CONTEXT_RENDERER, "AsyncEffectUploader::uploadEffectsOrWait: will upload: {}, uploaded in cache:{}", effectsToUpload.size(), m_effectsUploadedCache.size()); std::chrono::microseconds maxShaderUploadTime{ 0u }; std::chrono::microseconds totalShaderUploadTime{ 0u }; @@ -108,7 +108,7 @@ namespace ramses::internal } const auto& effectHash = effectRes->getHash(); - LOG_INFO(CONTEXT_RENDERER, "AsyncEffectUploader uploading: " << effectHash); + LOG_INFO(CONTEXT_RENDERER, "AsyncEffectUploader uploading: {}", effectHash); assert(std::find_if(std::cbegin(m_effectsUploadedCache), std::cend(m_effectsUploadedCache), [&effectHash](const auto& u) {return effectHash == u.first; }) == m_effectsUploadedCache.cend()); m_notifier.notifyAlive(m_aliveIdentifier); @@ -128,9 +128,8 @@ namespace ramses::internal if (!effectsToUpload.empty()) { - LOG_INFO(CONTEXT_RENDERER, "AsyncEffectUploader " << effectsToUpload.size() << " uploaded in " - << totalShaderUploadTime.count() << " us (" - << "Max: " << maxShaderUploadTime.count() << " us " << effectWithMaxUploadTime << ")"); + LOG_INFO(CONTEXT_RENDERER, "AsyncEffectUploader {} uploaded in {} us (Max: {} us {})", + effectsToUpload.size(), totalShaderUploadTime.count(), maxShaderUploadTime.count(), effectWithMaxUploadTime); #if defined(_WIN32) // Workaround for bug https://github.com/COVESA/ramses/issues/61 @@ -160,9 +159,8 @@ namespace ramses::internal if (!effectsToUpload.empty() || !uploadedResourcesOut.empty()) { - LOG_INFO(CONTEXT_RENDERER, "AsyncEffectUploader newToUpload: " << effectsToUpload.size() - << ", totalPending: " << totalEffectsToUpload - << ", uploaded: " << uploadedResourcesOut.size()); + LOG_INFO(CONTEXT_RENDERER, "AsyncEffectUploader newToUpload: {}, totalPending: {}, uploaded: {}", + effectsToUpload.size(), totalEffectsToUpload, uploadedResourcesOut.size()); } if (!effectsToUpload.empty()) @@ -173,8 +171,6 @@ namespace ramses::internal void AsyncEffectUploader::run() { - ThreadLocalLog::SetPrefix(m_logPrefixID); - LOG_INFO(CONTEXT_RENDERER, "AsyncEffectUploader creating render backend for resource uploading"); auto resourceUploadRenderBackend = m_platform.createResourceUploadRenderBackend(); if (!resourceUploadRenderBackend) diff --git a/src/renderer/internal/RendererLib/AsyncEffectUploader.h b/src/renderer/internal/RendererLib/AsyncEffectUploader.h index cb1169db7..907c68845 100644 --- a/src/renderer/internal/RendererLib/AsyncEffectUploader.h +++ b/src/renderer/internal/RendererLib/AsyncEffectUploader.h @@ -31,7 +31,7 @@ namespace ramses::internal class AsyncEffectUploader : private Runnable { public: - AsyncEffectUploader(IPlatform& platform, IRenderBackend& renderBackend, IThreadAliveNotifier& notifier, int logPrefixID); + AsyncEffectUploader(IPlatform& platform, IRenderBackend& renderBackend, IThreadAliveNotifier& notifier, DisplayHandle display); ~AsyncEffectUploader() override; bool createResourceUploadRenderBackendAndStartThread(); @@ -58,8 +58,8 @@ namespace ramses::internal std::promise m_creationSuccess; IThreadAliveNotifier& m_notifier; - const uint64_t m_aliveIdentifier; + const uint64_t m_aliveIdentifier; - const int m_logPrefixID; + const DisplayHandle m_displayHandle; }; } diff --git a/src/renderer/internal/RendererLib/CMakeLists.txt b/src/renderer/internal/RendererLib/CMakeLists.txt index 4614a5a5e..fbb628d02 100644 --- a/src/renderer/internal/RendererLib/CMakeLists.txt +++ b/src/renderer/internal/RendererLib/CMakeLists.txt @@ -12,36 +12,36 @@ file(GLOB_RECURSE *.cpp) createModule( - NAME ramses-renderer-lib + NAME ramses-renderer-internal TYPE STATIC_LIBRARY ENABLE_INSTALL OFF INCLUDE_PATHS ${PROJECT_SOURCE_DIR}/src/renderer SRC_FILES ${RAMSES_RENDERER_LIB_FILES} DEPENDENCIES ramses-api - ramses-framework + ramses-framework-internal ) if(ramses-sdk_ENABLE_WINDOW_TYPE_WINDOWS) - target_compile_definitions(ramses-renderer-lib PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_WINDOWS) + target_compile_definitions(ramses-renderer-internal PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_WINDOWS) endif() if(ramses-sdk_ENABLE_WINDOW_TYPE_X11) - target_compile_definitions(ramses-renderer-lib PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_X11) + target_compile_definitions(ramses-renderer-internal PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_X11) endif() if(ramses-sdk_ENABLE_WINDOW_TYPE_ANDROID) - target_compile_definitions(ramses-renderer-lib PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_ANDROID) + target_compile_definitions(ramses-renderer-internal PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_ANDROID) endif() if(ramses-sdk_ENABLE_WINDOW_TYPE_IOS) - target_compile_definitions(ramses-renderer-lib PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_IOS) + target_compile_definitions(ramses-renderer-internal PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_IOS) endif() if(ramses-sdk_ENABLE_WINDOW_TYPE_WAYLAND_IVI) - target_compile_definitions(ramses-renderer-lib PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_WAYLAND_IVI) + target_compile_definitions(ramses-renderer-internal PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_WAYLAND_IVI) endif() if(ramses-sdk_ENABLE_WINDOW_TYPE_WAYLAND_WL_SHELL) - target_compile_definitions(ramses-renderer-lib PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_WAYLAND_WL_SHELL) + target_compile_definitions(ramses-renderer-internal PUBLIC ramses_sdk_ENABLE_WINDOW_TYPE_WAYLAND_WL_SHELL) endif() diff --git a/src/renderer/internal/RendererLib/DataReferenceLinkManager.cpp b/src/renderer/internal/RendererLib/DataReferenceLinkManager.cpp index b5999dd2b..276fa2ece 100644 --- a/src/renderer/internal/RendererLib/DataReferenceLinkManager.cpp +++ b/src/renderer/internal/RendererLib/DataReferenceLinkManager.cpp @@ -10,7 +10,7 @@ #include "internal/RendererLib/RendererScenes.h" #include "internal/RendererLib/DataLinkUtils.h" #include "internal/SceneGraph/SceneUtils/DataInstanceHelper.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -41,7 +41,7 @@ namespace ramses::internal const EDataType consumerDataType = DataLinkUtils::GetSlotDataReferenceType(consumerSceneId, consumerSlotHandle, m_scenes); if (providerDataType != consumerDataType) { - LOG_ERROR(CONTEXT_RENDERER, "Renderer::createDataLink failed: data types of provider (Scene:" << providerSceneId << ") and consumer (Scene: " << consumerSceneId << ") do not match!"); + LOG_ERROR(CONTEXT_RENDERER, "Renderer::createDataLink failed: data types of provider (Scene:{}) and consumer (Scene: {}) do not match!", providerSceneId, consumerSceneId); return false; } diff --git a/src/renderer/internal/RendererLib/DisplayDispatcher.cpp b/src/renderer/internal/RendererLib/DisplayDispatcher.cpp index b6bf57a60..74dcd2981 100644 --- a/src/renderer/internal/RendererLib/DisplayDispatcher.cpp +++ b/src/renderer/internal/RendererLib/DisplayDispatcher.cpp @@ -9,7 +9,7 @@ #include "internal/RendererLib/DisplayDispatcher.h" #include "internal/RendererLib/RendererCommandBuffer.h" #include "internal/RendererLib/RendererCommandUtils.h" -#include "internal/Core/Utils/ThreadLocalLog.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -39,13 +39,13 @@ namespace ramses::internal return !std::holds_alternative(c) && !std::holds_alternative(c); }); if (logCommands) - LOG_INFO_P(CONTEXT_RENDERER, "DisplayDispatcher: dispatching {} commands (only other than scene update commands will be logged)", cmds.size()); + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher: dispatching {} commands (only other than scene update commands will be logged)", cmds.size()); std::lock_guard lock{ m_displaysAccessLock }; for (auto&& cmd : cmds) { if (logCommands && !std::holds_alternative(cmd)) - LOG_INFO_P(CONTEXT_RENDERER, "DisplayDispatcher: dispatching command [{}]", RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher: dispatching command [{}]", RendererCommandUtils::ToString(cmd)); preprocessCommand(cmd); dispatchCommand(std::move(cmd)); @@ -61,7 +61,7 @@ namespace ramses::internal if (++m_cmdDispatchLoopsSinceLastEventDispatch > 300) { - LOG_WARN_P(CONTEXT_RENDERER, "DisplayDispatcher: detected no renderer events dispatched in more than {} loops, this could result in wrong behavior!" + LOG_WARN(CONTEXT_RENDERER, "DisplayDispatcher: detected no renderer events dispatched in more than {} loops, this could result in wrong behavior!" " Use RamsesRenderer::dispatchEvents regularly to avoid this problem.", m_cmdDispatchLoopsSinceLastEventDispatch); m_cmdDispatchLoopsSinceLastEventDispatch = 0; // do not spam } @@ -75,7 +75,7 @@ namespace ramses::internal { const auto frameCounter = display.second.displayThread->getFrameCounter(); if (display.second.lastFrameCounter == frameCounter) - LOG_WARN_P(CONTEXT_RENDERER, "Display {} potentially stuck at trace ID {}", display.first, display.second.displayBundle->traceId().load()); + LOG_WARN(CONTEXT_RENDERER, "Display {} potentially stuck at trace ID {}", display.first, display.second.displayBundle->traceId().load()); display.second.lastFrameCounter = frameCounter; } } @@ -88,8 +88,8 @@ namespace ramses::internal assert(std::all_of(m_displays.cbegin(), m_displays.cend(), [](const auto& d) { return !d.second.displayThread; })); for (auto& display : m_displays) { - // in non-threaded mode overwrite the TLS log prefix before each display update - ThreadLocalLog::SetPrefix(static_cast(display.first.asMemoryHandle())); + // in non-threaded mode use additional log prefix for each display update + RamsesLogger::SetPrefixAdditional(fmt::format("Display{}", display.first)); // avoid unnecessary context switch if running only single display if (m_displays.size() > 1u || m_forceContextEnableNextLoop) @@ -97,11 +97,12 @@ namespace ramses::internal display.second.displayBundle->doOneLoop(m_loopMode, sleepTime); } + RamsesLogger::SetPrefixAdditional({}); m_forceContextEnableNextLoop = false; } - void DisplayDispatcher::preprocessCommand(const RendererCommand::Variant& cmd) + void DisplayDispatcher::preprocessCommand(RendererCommand::Variant& cmd) { if (std::holds_alternative(cmd)) { @@ -130,11 +131,11 @@ namespace ramses::internal { return RendererCommandUtils::Copy(c); }); - LOG_INFO_P(CONTEXT_RENDERER, "DisplayDispatcher: pushing {} stashed broadcast commands to newly created display {}", stashedCommands.size(), displayHandle); + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher: pushing {} stashed broadcast commands to newly created display {}", stashedCommands.size(), displayHandle); m_displays[displayHandle].displayBundle->pushAndConsumeCommands(stashedCommands); // push commands stashed for this specific display (e.g. set scene state) - LOG_INFO_P(CONTEXT_RENDERER, "DisplayDispatcher: pushing {} stashed commands to newly created display {}", m_stashedCommandsForNewDisplays[displayHandle].size(), displayHandle); + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher: pushing {} stashed commands to newly created display {}", m_stashedCommandsForNewDisplays[displayHandle].size(), displayHandle); m_displays[displayHandle].displayBundle->pushAndConsumeCommands(m_stashedCommandsForNewDisplays[displayHandle]); m_stashedCommandsForNewDisplays.erase(displayHandle); } @@ -152,7 +153,7 @@ namespace ramses::internal if (!m_sceneDisplayTrackerForCommands.determineDisplayFromRendererCommand(cmd)->isValid()) { const auto refScene = std::get(cmd).info.sceneID; - LOG_INFO_P(CONTEXT_RENDERER, "DisplayDispatcher: missing scene {} display ownership when processing {}, assuming a referenced scene.", refScene, RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher: missing scene {} display ownership when processing {}, assuming a referenced scene.", refScene, RendererCommandUtils::ToString(cmd)); for (const auto& display : m_displays) { const auto& displayBundle = *display.second.displayBundle; @@ -160,26 +161,34 @@ namespace ramses::internal if (masterScene.isValid()) { const auto masterDisplay = m_sceneDisplayTrackerForCommands.getSceneOwnership(masterScene); - LOG_INFO_P(CONTEXT_RENDERER, "DisplayDispatcher: found master scene {} for referenced scene {} when processing {}, setting display ownership to display {}", + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher: found master scene {} for referenced scene {} when processing {}, setting display ownership to display {}", masterScene, refScene, RendererCommandUtils::ToString(cmd), masterDisplay); m_sceneDisplayTrackerForCommands.setSceneOwnership(refScene, masterDisplay); } } if (!m_sceneDisplayTrackerForCommands.getSceneOwnership(refScene).isValid()) { - LOG_ERROR_P(CONTEXT_RENDERER, "DisplayDispatcher: could not find master scene for referenced scene {} when processing {}", refScene, RendererCommandUtils::ToString(cmd)); + LOG_ERROR(CONTEXT_RENDERER, "DisplayDispatcher: could not find master scene for referenced scene {} when processing {}", refScene, RendererCommandUtils::ToString(cmd)); } } } + else if (std::holds_alternative(cmd)) + { + // fill in global renderer info to be logged by displays + auto& logCmd = std::get(cmd); + logCmd.displaysThreaded = m_threadedDisplays; + logCmd.displaysThreadsRunning = m_displayThreadsUpdating; + logCmd.rendererLoopMode = m_loopMode; + } } DisplayDispatcher::Display DisplayDispatcher::createDisplayBundle(DisplayHandle displayHandle, const DisplayConfig& dispConfig) { Display bundle; - LOG_INFO_P(CONTEXT_RENDERER, "DisplayDispatcher: creating platform for display {}", displayHandle); + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher: creating platform for display {}", displayHandle); bundle.platform = m_platformFactory->createPlatform(m_rendererConfig, dispConfig); - LOG_INFO_P(CONTEXT_RENDERER, "DisplayDispatcher: creating display bundle of components for display {}", displayHandle); + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher: creating display bundle of components for display {}", displayHandle); bundle.displayBundle = DisplayBundleShared{ std::make_unique( displayHandle, m_rendererSceneSender, @@ -189,7 +198,7 @@ namespace ramses::internal }; if (m_threadedDisplays) { - LOG_INFO_P(CONTEXT_RENDERER, "DisplayDispatcher: creating update/render thread for display {}", displayHandle); + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher: creating update/render thread for display {}", displayHandle); bundle.displayThread = std::make_unique(bundle.displayBundle, displayHandle, m_notifier); } @@ -208,13 +217,13 @@ namespace ramses::internal { // Special case for commands that are to be dispatched only after their corresponding display is created, therefore cannot fail. // This makes it possible that scene mapping/state can be set before display is even created. - LOG_INFO_P(CONTEXT_RENDERER, "DisplayDispatcher cannot dispatch command yet, display does not exist, will dispatch when display created. Command=[{}]", RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher cannot dispatch command yet, display does not exist, will dispatch when display created. Command=[{}]", RendererCommandUtils::ToString(cmd)); m_stashedCommandsForNewDisplays[*cmdDisplay].push_back(std::move(cmd)); } else { // cannot dispatch, generate fail event - LOG_ERROR_P(CONTEXT_RENDERER, "DisplayDispatcher cannot dispatch command, display unknown. Command=[{}]", RendererCommandUtils::ToString(cmd)); + LOG_ERROR(CONTEXT_RENDERER, "DisplayDispatcher cannot dispatch command, display unknown. Command=[{}]", RendererCommandUtils::ToString(cmd)); auto failEvent = RendererCommandUtils::GenerateFailEventForCommand(cmd); if (failEvent.eventType != ERendererEventType::Invalid) { @@ -234,7 +243,17 @@ namespace ramses::internal { // command is to be broadcast, dispatch a copy to each display for (auto& display : m_displays) - display.second.pendingCommands.push_back(RendererCommandUtils::Copy(cmd)); + { + auto cmdCopy = RendererCommandUtils::Copy(cmd); + + if (std::holds_alternative(cmdCopy)) + { + // fill displays framerate, it is available only here in dispatcher and displayThread but not display components + std::get(cmdCopy).minFrameTime = (m_minFrameDurationsPerDisplay.count(display.first) != 0u ? m_minFrameDurationsPerDisplay[display.first] : DefaultMinFrameDuration); + } + + display.second.pendingCommands.push_back(std::move(cmdCopy)); + } RendererCommandUtils::AddAndConsolidateCommandToStash(std::move(cmd), m_stashedBroadcastCommandsForNewDisplays); } @@ -315,7 +334,7 @@ namespace ramses::internal } else { - LOG_INFO_P(CONTEXT_RENDERER, + LOG_INFO(CONTEXT_RENDERER, "DisplayDispatcher::dispatchSceneControlEvents: filtering scene state change event from non-owner display {}, scene {} change state to {}.", display.first, evt.sceneId, diff --git a/src/renderer/internal/RendererLib/DisplayDispatcher.h b/src/renderer/internal/RendererLib/DisplayDispatcher.h index 284a3c1d0..20a10fadd 100644 --- a/src/renderer/internal/RendererLib/DisplayDispatcher.h +++ b/src/renderer/internal/RendererLib/DisplayDispatcher.h @@ -62,7 +62,7 @@ namespace ramses::internal [[nodiscard]] bool hasSystemCompositorController() const; protected: - void preprocessCommand(const RendererCommand::Variant& cmd); + void preprocessCommand(RendererCommand::Variant& cmd); void dispatchCommand(RendererCommand::Variant&& cmd); [[nodiscard]] bool isSceneStateChangeEmittedFromOwningDisplay(SceneId sceneId, DisplayHandle emittingDisplay) const; diff --git a/src/renderer/internal/RendererLib/DisplayEventHandler.cpp b/src/renderer/internal/RendererLib/DisplayEventHandler.cpp index 569690b2a..3f5a1e167 100644 --- a/src/renderer/internal/RendererLib/DisplayEventHandler.cpp +++ b/src/renderer/internal/RendererLib/DisplayEventHandler.cpp @@ -11,7 +11,7 @@ #include "internal/RendererLib/PlatformInterface/IWindowEventHandler.h" #include "internal/RendererLib/Enums/EKeyModifier.h" #include "internal/RendererLib/RendererEventCollector.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -27,8 +27,8 @@ namespace ramses::internal void DisplayEventHandler::onKeyEvent(EKeyEvent event, KeyModifiers modifiers, EKeyCode keyCode) { - LOG_TRACE(CONTEXT_RENDERER, "DisplayController::onKeyEvent: [display: " << m_displayHandle.asMemoryHandle() << - "; eventType: " << EnumToString(event) << "; modifiers: " << KeyModifierToString(modifiers) << "; key: " << EnumToString(keyCode) << "]"); + LOG_TRACE(CONTEXT_RENDERER, "DisplayController::onKeyEvent: [display: {}; eventType: {}; modifiers: {}; key: {}]", + m_displayHandle.asMemoryHandle(), EnumToString(event), KeyModifierToString(modifiers), EnumToString(keyCode)); // collect renderer event KeyEvent keyEvent; @@ -40,8 +40,7 @@ namespace ramses::internal void DisplayEventHandler::onMouseEvent(EMouseEvent event, int32_t posX, int32_t posY) { - LOG_TRACE(CONTEXT_RENDERER, "DisplayController::onMouseEvent: [display: " << m_displayHandle.asMemoryHandle() << - "; eventType: " << EnumToString(event) << "; posX: " << posX << "; posY: " << posY << "]"); + LOG_TRACE(CONTEXT_RENDERER, "DisplayController::onMouseEvent: [display: {}; eventType: {}; posX: {}; posY: {}]", m_displayHandle.asMemoryHandle(), EnumToString(event), posX, posY); // collect renderer event MouseEvent mouseEvent; @@ -53,7 +52,7 @@ namespace ramses::internal void DisplayEventHandler::onClose() { - LOG_TRACE(CONTEXT_RENDERER, "DisplayController::onClose: [displayId: " << m_displayHandle.asMemoryHandle() << "]"); + LOG_TRACE(CONTEXT_RENDERER, "DisplayController::onClose: [displayId: {}]", m_displayHandle.asMemoryHandle()); m_eventCollector.addDisplayEvent(ERendererEventType::WindowClosed, m_displayHandle); } diff --git a/src/renderer/internal/RendererLib/DisplayThread.cpp b/src/renderer/internal/RendererLib/DisplayThread.cpp index d8d52adf6..fd30cb8fe 100644 --- a/src/renderer/internal/RendererLib/DisplayThread.cpp +++ b/src/renderer/internal/RendererLib/DisplayThread.cpp @@ -8,14 +8,14 @@ #include "internal/RendererLib/DisplayThread.h" #include "internal/RendererLib/DisplayBundle.h" -#include "internal/Core/Utils/ThreadLocalLog.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { DisplayThread::DisplayThread(DisplayBundleShared displayBundle, DisplayHandle displayHandle, IThreadAliveNotifier& notifier) : m_displayHandle{ displayHandle } , m_display{ std::move(displayBundle) } - , m_thread{ fmt::format("R_DispThrd{}", displayHandle) } + , m_thread{ GetThreadName(displayHandle) } , m_notifier{ notifier } , m_aliveIdentifier{ notifier.registerThread() } { @@ -25,14 +25,14 @@ namespace ramses::internal { if (m_thread.isRunning()) { - LOG_INFO_P(CONTEXT_RENDERER, "{}: DisplayThread stopping", m_displayHandle); + LOG_INFO(CONTEXT_RENDERER, "{} stopping", GetThreadName(m_displayHandle)); { std::lock_guard lock{ m_lock }; m_thread.cancel(); m_sleepConditionVar.notify_one(); } m_thread.join(); - LOG_INFO_P(CONTEXT_RENDERER, "{}: DisplayThread stopped", m_displayHandle); + LOG_INFO(CONTEXT_RENDERER, "{} stopped", GetThreadName(m_displayHandle)); } m_notifier.unregisterThread(m_aliveIdentifier); } @@ -41,12 +41,12 @@ namespace ramses::internal { if (!m_thread.isRunning()) { - LOG_INFO_P(CONTEXT_RENDERER, "{}: DisplayThread starting", m_displayHandle); + LOG_INFO(CONTEXT_RENDERER, "{} starting", GetThreadName(m_displayHandle)); m_thread.start(*this); - LOG_INFO_P(CONTEXT_RENDERER, "{}: DisplayThread started", m_displayHandle); + LOG_INFO(CONTEXT_RENDERER, "{} started", GetThreadName(m_displayHandle)); } - LOG_INFO_P(CONTEXT_RENDERER, "{}: DisplayThread start update", m_displayHandle); + LOG_INFO(CONTEXT_RENDERER, "{} start update", GetThreadName(m_displayHandle)); std::lock_guard lock{ m_lock }; m_isUpdating = true; m_sleepConditionVar.notify_one(); @@ -54,29 +54,27 @@ namespace ramses::internal void DisplayThread::stopUpdating() { - LOG_INFO_P(CONTEXT_RENDERER, "{}: DisplayThread stop update", m_displayHandle); + LOG_INFO(CONTEXT_RENDERER, "{} stop update", GetThreadName(m_displayHandle)); std::lock_guard lock{ m_lock }; m_isUpdating = false; } void DisplayThread::setLoopMode(ELoopMode loopMode) { - LOG_INFO_P(CONTEXT_RENDERER, "{}: DisplayThread loop mode set to {}", m_displayHandle, loopMode == ELoopMode::UpdateAndRender ? "UpdateAndRender" : "UpdateOnly"); + LOG_INFO(CONTEXT_RENDERER, "{} loop mode set to {}", GetThreadName(m_displayHandle), loopMode == ELoopMode::UpdateAndRender ? "UpdateAndRender" : "UpdateOnly"); std::lock_guard lock{ m_lock }; m_loopMode = loopMode; } void DisplayThread::setMinFrameDuration(std::chrono::microseconds minLoopPeriod) { - LOG_INFO_P(CONTEXT_RENDERER, "DisplayThread min frame duration set to {} us", minLoopPeriod.count()); + LOG_INFO(CONTEXT_RENDERER, "{} min frame duration set to {} us", GetThreadName(m_displayHandle), minLoopPeriod.count()); std::lock_guard lock{ m_lock }; m_minFrameDuration = minLoopPeriod; } void DisplayThread::run() { - ThreadLocalLog::SetPrefix(static_cast(m_displayHandle.asMemoryHandle())); - std::chrono::milliseconds lastLoopSleepTime{ 0u }; while (!isCancelRequested()) { @@ -120,10 +118,15 @@ namespace ramses::internal } // release display before thread exit, it might contain platform components that need to be deinitialized in same thread - LOG_INFO_RP(CONTEXT_RENDERER, "DisplayThread releasing display bundle components"); + LOG_INFO(CONTEXT_RENDERER, "releasing display bundle components"); m_display.destroy(); } + std::string DisplayThread::GetThreadName(DisplayHandle display) + { + return fmt::format("DispThrd{}", display); + } + std::chrono::milliseconds DisplayThread::SleepToControlFramerate(std::chrono::microseconds loopDuration, std::chrono::microseconds minimumFrameDuration) { std::chrono::milliseconds sleepTime{ 0 }; diff --git a/src/renderer/internal/RendererLib/DisplayThread.h b/src/renderer/internal/RendererLib/DisplayThread.h index bb0978b20..bb49d90f3 100644 --- a/src/renderer/internal/RendererLib/DisplayThread.h +++ b/src/renderer/internal/RendererLib/DisplayThread.h @@ -50,6 +50,7 @@ namespace ramses::internal { m_bundle->reset(); } + private: std::shared_ptr> m_bundle; }; @@ -82,6 +83,7 @@ namespace ramses::internal private: void run() override; + static std::string GetThreadName(DisplayHandle display); static std::chrono::milliseconds SleepToControlFramerate(std::chrono::microseconds loopDuration, std::chrono::microseconds minimumFrameDuration); const DisplayHandle m_displayHandle; diff --git a/src/renderer/internal/RendererLib/EmbeddedCompositingManager.cpp b/src/renderer/internal/RendererLib/EmbeddedCompositingManager.cpp index 38875e3aa..548413914 100644 --- a/src/renderer/internal/RendererLib/EmbeddedCompositingManager.cpp +++ b/src/renderer/internal/RendererLib/EmbeddedCompositingManager.cpp @@ -10,7 +10,7 @@ #include "internal/RendererLib/PlatformInterface/IDevice.h" #include "internal/RendererLib/PlatformInterface/IEmbeddedCompositor.h" #include "internal/RendererLib/PlatformInterface/ITextureUploadingAdapter.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -26,13 +26,13 @@ namespace ramses::internal auto streamTextureInfoIt = m_streamTextureSourceInfoMap.find(source); if (m_streamTextureSourceInfoMap.end() == streamTextureInfoIt) { - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingManager::refStream: Creating new stream texture with: " << source); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingManager::refStream: Creating new stream texture with: {}", source); createStreamTexture(source); streamTextureInfoIt = m_streamTextureSourceInfoMap.find(source); } streamTextureInfoIt->value.refs++; - LOG_INFO_P(CONTEXT_RENDERER, "EmbeddedCompositingManager::refStream adding reference to stream texture {}. Total refs: {}", source, streamTextureInfoIt->value.refs); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingManager::refStream adding reference to stream texture {}. Total refs: {}", source, streamTextureInfoIt->value.refs); } void EmbeddedCompositingManager::unrefStream(WaylandIviSurfaceId source) @@ -43,11 +43,11 @@ namespace ramses::internal // remove stream buffer reference assert(streamTextureSourceInfo->refs > 0); streamTextureSourceInfo->refs--; - LOG_INFO_P(CONTEXT_RENDERER, "EmbeddedCompositingManager::unrefStream removing reference to stream texture {}. Total refs: {}", source, streamTextureSourceInfo->refs); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingManager::unrefStream removing reference to stream texture {}. Total refs: {}", source, streamTextureSourceInfo->refs); if (streamTextureSourceInfo->refs == 0) { - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingManager::unrefStream: Destroying no more referenced stream texture with " << source); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingManager::unrefStream: Destroying no more referenced stream texture with {}", source); destroyStreamTexture(source); } } @@ -140,7 +140,7 @@ namespace ramses::internal if (m_embeddedCompositor.isContentAvailableForStreamTexture(source)) { - LOG_DEBUG(CONTEXT_RENDERER, "EmbeddedCompositingManager::uploadStreamTexture Content available for stream texture " << source); + LOG_DEBUG(CONTEXT_RENDERER, "EmbeddedCompositingManager::uploadStreamTexture Content available for stream texture {}", source); m_embeddedCompositor.uploadCompositingContentForStreamTexture(source, streamTextureSourceInfo.compositedTextureHandle, m_textureUploadingAdapter); } } diff --git a/src/renderer/internal/RendererLib/IRendererResourceManager.h b/src/renderer/internal/RendererLib/IRendererResourceManager.h index d00f2db8d..9ec1c56c1 100644 --- a/src/renderer/internal/RendererLib/IRendererResourceManager.h +++ b/src/renderer/internal/RendererLib/IRendererResourceManager.h @@ -38,12 +38,13 @@ namespace ramses::internal virtual void unreferenceResourcesForScene (SceneId sceneId, const ResourceContentHashVector& resources) = 0; virtual void provideResourceData(const ManagedResource& mr) = 0; - [[nodiscard]] virtual bool hasResourcesToBeUploaded() const = 0; + [[nodiscard]] virtual bool hasResourcesToBeUploaded() const = 0; virtual void uploadAndUnloadPendingResources() = 0; // Scene resources virtual void uploadRenderTargetBuffer(RenderBufferHandle renderBufferHandle, SceneId sceneId, const RenderBuffer& renderBuffer) = 0; virtual void unloadRenderTargetBuffer(RenderBufferHandle renderBufferHandle, SceneId sceneId) = 0; + virtual void updateRenderTargetBufferProperties(RenderBufferHandle renderBufferHandle, SceneId sceneId, const RenderBuffer& renderBuffer) = 0; virtual void uploadRenderTarget(RenderTargetHandle renderTarget, const RenderBufferHandleVector& rtBufferHandles, SceneId sceneId) = 0; virtual void unloadRenderTarget(RenderTargetHandle renderTarget, SceneId sceneId) = 0; diff --git a/src/renderer/internal/RendererLib/IRendererSceneUpdater.h b/src/renderer/internal/RendererLib/IRendererSceneUpdater.h index f0cbe0f6c..d0d57f793 100644 --- a/src/renderer/internal/RendererLib/IRendererSceneUpdater.h +++ b/src/renderer/internal/RendererLib/IRendererSceneUpdater.h @@ -9,6 +9,7 @@ #pragma once #include "internal/RendererLib/Types.h" +#include "internal/RendererLib/RendererCommands.h" #include "internal/SceneGraph/SceneAPI/SceneId.h" #include "internal/SceneGraph/SceneAPI/TextureEnums.h" #include "internal/SceneGraph/SceneAPI/DataSlot.h" @@ -51,7 +52,7 @@ namespace ramses::internal virtual void setLimitFlushesForceApply(size_t limitForPendingFlushesForceApply) = 0; virtual void setLimitFlushesForceUnsubscribe(size_t limitForPendingFlushesForceUnsubscribe) = 0; virtual void setSkippingOfUnmodifiedScenes(bool enable) = 0; - virtual void logRendererInfo(ERendererLogTopic topic, bool verbose, NodeHandle nodeFilter) const = 0; + virtual void logRendererInfo(const RendererCommand::LogInfo& cmd) const = 0; virtual ~IRendererSceneUpdater() = default; }; diff --git a/src/renderer/internal/RendererLib/LinkManagerBase.cpp b/src/renderer/internal/RendererLib/LinkManagerBase.cpp index e7cc21bcc..2ce2f35d5 100644 --- a/src/renderer/internal/RendererLib/LinkManagerBase.cpp +++ b/src/renderer/internal/RendererLib/LinkManagerBase.cpp @@ -9,7 +9,7 @@ #include "internal/RendererLib/LinkManagerBase.h" #include "internal/RendererLib/RendererScenes.h" #include "internal/RendererLib/DataLinkUtils.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -50,13 +50,13 @@ namespace ramses::internal if (m_sceneLinks.hasLinkedProvider(consumerSceneId, consumerSlotHandle)) { - LOG_ERROR(CONTEXT_RENDERER, "LinkManagerBase::createDataLink failed: consumer slot (Scene: " << consumerSceneId << ") already has a data link assigned!"); + LOG_ERROR(CONTEXT_RENDERER, "LinkManagerBase::createDataLink failed: consumer slot (Scene: {}) already has a data link assigned!", consumerSceneId); return false; } if (!m_dependencyChecker.addDependency(providerSceneId, consumerSceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "LinkManagerBase::createDataLink failed: cyclic link dependency detected! (Provider scene: " << providerSceneId << ", consumer scene: " << consumerSceneId << ")"); + LOG_ERROR(CONTEXT_RENDERER, "LinkManagerBase::createDataLink failed: cyclic link dependency detected! (Provider scene: {}, consumer scene: {})", providerSceneId, consumerSceneId); return false; } @@ -73,7 +73,7 @@ namespace ramses::internal if (!m_sceneLinks.hasLinkedProvider(consumerSceneId, consumerSlotHandle)) { - LOG_ERROR(CONTEXT_RENDERER, "LinkManagerBase::removeDataLink failed: consumer slot is not linked! (Consumer scene: " << consumerSceneId << ")"); + LOG_ERROR(CONTEXT_RENDERER, "LinkManagerBase::removeDataLink failed: consumer slot is not linked! (Consumer scene: {})", consumerSceneId); return false; } diff --git a/src/renderer/internal/RendererLib/PendingSceneResourcesUtils.cpp b/src/renderer/internal/RendererLib/PendingSceneResourcesUtils.cpp index da874faeb..9f04e0db7 100644 --- a/src/renderer/internal/RendererLib/PendingSceneResourcesUtils.cpp +++ b/src/renderer/internal/RendererLib/PendingSceneResourcesUtils.cpp @@ -33,8 +33,16 @@ namespace ramses::internal wasCanceledOut = RemoveSceneResourceActionIfContained(currentActionsInOut, sceneResourceAction.handle, ESceneResourceAction_CreateRenderTarget); break; case ESceneResourceAction_DestroyRenderBuffer: + //remove all update actions first + while (RemoveSceneResourceActionIfContained(currentActionsInOut, sceneResourceAction.handle, ESceneResourceAction_UpdateRenderBufferProperties)) + { + } wasCanceledOut = RemoveSceneResourceActionIfContained(currentActionsInOut, sceneResourceAction.handle, ESceneResourceAction_CreateRenderBuffer); break; + case ESceneResourceAction_UpdateRenderBufferProperties: + //add update action if update action does not already exist + wasCanceledOut = ContainsSceneResourceAction(currentActionsInOut, sceneResourceAction.handle, ESceneResourceAction_UpdateRenderBufferProperties); + break; case ESceneResourceAction_DestroyBlitPass: wasCanceledOut = RemoveSceneResourceActionIfContained(currentActionsInOut, sceneResourceAction.handle, ESceneResourceAction_CreateBlitPass); break; @@ -97,6 +105,9 @@ namespace ramses::internal case ESceneResourceAction_DestroyRenderBuffer: resourceManager.unloadRenderTargetBuffer(RenderBufferHandle(handle), scene.getSceneId()); break; + case ESceneResourceAction_UpdateRenderBufferProperties: + resourceManager.updateRenderTargetBufferProperties(RenderBufferHandle{ handle }, scene.getSceneId(), scene.getRenderBuffer(RenderBufferHandle{ handle })); + break; case ESceneResourceAction_CreateBlitPass: SceneResourceUploader::UploadBlitPassRenderTargets(scene, BlitPassHandle(handle), resourceManager); break; @@ -144,14 +155,11 @@ namespace ramses::internal bool PendingSceneResourcesUtils::RemoveSceneResourceActionIfContained(SceneResourceActionVector& actions, MemoryHandle handle, ESceneResourceAction action) { - for (auto actionIter = actions.begin(); actionIter != actions.end(); ++actionIter) + auto it = std::find(actions.begin(), actions.end(), SceneResourceAction{ handle, action }); + if (it != actions.end()) { - if (actionIter->handle == handle && - actionIter->action == action) - { - actions.erase(actionIter); - return true; - } + actions.erase(it); + return true; } return false; @@ -159,15 +167,6 @@ namespace ramses::internal bool PendingSceneResourcesUtils::ContainsSceneResourceAction(const SceneResourceActionVector& actions, MemoryHandle handle, ESceneResourceAction action) { - for (const auto& a : actions) - { - if (a.handle == handle && - a.action == action) - { - return true; - } - } - - return false; + return std::find(actions.cbegin(), actions.cend(), SceneResourceAction{ handle, action }) != actions.cend(); } } diff --git a/src/renderer/internal/RendererLib/PlatformBase/EmbeddedCompositor_Dummy.cpp b/src/renderer/internal/RendererLib/PlatformBase/EmbeddedCompositor_Dummy.cpp index d1eead518..b03cfe49b 100644 --- a/src/renderer/internal/RendererLib/PlatformBase/EmbeddedCompositor_Dummy.cpp +++ b/src/renderer/internal/RendererLib/PlatformBase/EmbeddedCompositor_Dummy.cpp @@ -10,7 +10,7 @@ #include "internal/RendererLib/RendererLogContext.h" #include "internal/RendererLib/PlatformInterface/ITextureUploadingAdapter.h" #include "internal/RendererLib/Types.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -26,7 +26,7 @@ namespace ramses::internal uint32_t EmbeddedCompositor_Dummy::uploadCompositingContentForStreamTexture(WaylandIviSurfaceId streamTextureSourceId, [[maybe_unused]] DeviceResourceHandle textureHandle, [[maybe_unused]] ITextureUploadingAdapter& textureUploadingAdapter) { - LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Dummy::uploadCompositingContentForStreamTexture: " << streamTextureSourceId.getValue()); + LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Dummy::uploadCompositingContentForStreamTexture: {}", streamTextureSourceId.getValue()); return 0; } @@ -38,21 +38,21 @@ namespace ramses::internal bool EmbeddedCompositor_Dummy::isContentAvailableForStreamTexture(WaylandIviSurfaceId streamTextureSourceId) const { - LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Dummy::isContentAvailableForStreamTexture: streamTextureSourceId: " << streamTextureSourceId.getValue()); + LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Dummy::isContentAvailableForStreamTexture: streamTextureSourceId: {}", streamTextureSourceId.getValue()); return false; } uint64_t EmbeddedCompositor_Dummy::getNumberOfCommitedFramesForWaylandIviSurfaceSinceBeginningOfTime(WaylandIviSurfaceId waylandSurfaceId) const { - LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Dummy::getNumberOfCommitedFramesForWaylandIviSurfaceSinceBeginningOfTime: waylandSurfaceId: " << waylandSurfaceId.getValue()); + LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Dummy::getNumberOfCommitedFramesForWaylandIviSurfaceSinceBeginningOfTime: waylandSurfaceId: {}", waylandSurfaceId.getValue()); return 0; } bool EmbeddedCompositor_Dummy::isBufferAttachedToWaylandIviSurface(WaylandIviSurfaceId waylandSurfaceId) const { LOG_TRACE(CONTEXT_RENDERER, - "EmbeddedCompositor_Dummy::isBufferAttachedToWaylandIviSurface: waylandSurfaceId: " - << waylandSurfaceId.getValue()); + "EmbeddedCompositor_Dummy::isBufferAttachedToWaylandIviSurface: waylandSurfaceId: {}", + waylandSurfaceId.getValue()); return false; } @@ -64,13 +64,13 @@ namespace ramses::internal bool EmbeddedCompositor_Dummy::hasSurfaceForStreamTexture(WaylandIviSurfaceId streamTextureSourceId) const { - LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Dummy::hasSurfaceForStreamTexture: streamTextureSourceId: " << streamTextureSourceId.getValue()); + LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Dummy::hasSurfaceForStreamTexture: streamTextureSourceId: {}", streamTextureSourceId.getValue()); return false; } std::string EmbeddedCompositor_Dummy::getTitleOfWaylandIviSurface(WaylandIviSurfaceId waylandSurfaceId) const { - LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Dummy::getTitleOfWaylandIviSurface: streamTextureSourceId: " << waylandSurfaceId.getValue()); + LOG_TRACE(CONTEXT_RENDERER, "EmbeddedCompositor_Dummy::getTitleOfWaylandIviSurface: streamTextureSourceId: {}", waylandSurfaceId.getValue()); return {}; } diff --git a/src/renderer/internal/RendererLib/PlatformBase/Platform_Base.cpp b/src/renderer/internal/RendererLib/PlatformBase/Platform_Base.cpp index 223153be8..fecf52f4f 100644 --- a/src/renderer/internal/RendererLib/PlatformBase/Platform_Base.cpp +++ b/src/renderer/internal/RendererLib/PlatformBase/Platform_Base.cpp @@ -19,7 +19,7 @@ #include "internal/RendererLib/DisplayConfig.h" #include "internal/RendererLib/PlatformBase/TextureUploadingAdapter_Base.h" #include "internal/RendererLib/PlatformBase/EmbeddedCompositor_Dummy.h" -#include "internal/Core/Utils/ThreadLocalLog.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -52,21 +52,21 @@ namespace ramses::internal { if (m_rendererConfig.getSystemCompositorControlEnabled() && !createSystemCompositorController()) { - LOG_ERROR_R(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: will not create render backend components because system compositor controller creation failed"); + LOG_ERROR(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: will not create render backend components because system compositor controller creation failed"); return nullptr; } assert(!m_window); if (!createWindow(displayConfig, windowEventHandler)) { - LOG_ERROR_R(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: window creation failed"); + LOG_ERROR(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: window creation failed"); return nullptr; } assert(!m_context); if (!createContext(displayConfig)) { - LOG_ERROR_R(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: context creation failed"); + LOG_ERROR(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: context creation failed"); m_window.reset(); return nullptr; } @@ -76,7 +76,7 @@ namespace ramses::internal assert(!m_deviceExtension); if(!createDeviceExtension(displayConfig)) { - LOG_ERROR_R(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: device extension creation failed"); + LOG_ERROR(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: device extension creation failed"); m_window.reset(); m_context.reset(); return nullptr; @@ -85,7 +85,7 @@ namespace ramses::internal assert(!m_device); if (!createDevice()) { - LOG_ERROR_R(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: device creation failed"); + LOG_ERROR(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: device creation failed"); m_deviceExtension.reset(); m_context->disable(); m_context.reset(); @@ -96,7 +96,7 @@ namespace ramses::internal assert(!m_embeddedCompositor); if (!createEmbeddedCompositor(displayConfig)) { - LOG_ERROR_R(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: embedded compositor creation failed"); + LOG_ERROR(CONTEXT_RENDERER, "Platform_Base:createRenderBackend: embedded compositor creation failed"); m_device.reset(); m_deviceExtension.reset(); m_context->disable(); @@ -144,14 +144,14 @@ namespace ramses::internal assert(!m_contextUploading); if (!createContextUploading()) { - LOG_ERROR_R(CONTEXT_RENDERER, "Platform_Base:createResourceUploadRenderBackend: context creation failed"); + LOG_ERROR(CONTEXT_RENDERER, "Platform_Base:createResourceUploadRenderBackend: context creation failed"); return nullptr; } m_contextUploading->enable(); if (!createDeviceUploading()) { - LOG_ERROR_R(CONTEXT_RENDERER, "Platform_Base:createResourceUploadRenderBackend: device creation failed"); + LOG_ERROR(CONTEXT_RENDERER, "Platform_Base:createResourceUploadRenderBackend: device creation failed"); m_contextUploading->disable(); m_contextUploading.reset(); return nullptr; diff --git a/src/renderer/internal/RendererLib/PlatformBase/RendererLimits.cpp b/src/renderer/internal/RendererLib/PlatformBase/RendererLimits.cpp index 8d50eaefa..fe21762ae 100644 --- a/src/renderer/internal/RendererLib/PlatformBase/RendererLimits.cpp +++ b/src/renderer/internal/RendererLib/PlatformBase/RendererLimits.cpp @@ -7,7 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/RendererLib/PlatformBase/RendererLimits.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -90,17 +90,17 @@ namespace ramses::internal void RendererLimits::logLimits() const { LOG_INFO(CONTEXT_RENDERER, "Rendering device features and limits:"); - LOG_INFO(CONTEXT_RENDERER, " - maximum number of texture units: " << m_maximumTextureUnits); - LOG_INFO(CONTEXT_RENDERER, " - maximum number of MSAA samples: " << m_maximumSamples); - LOG_INFO(CONTEXT_RENDERER, " - maximum number of anisotropy samples: " << m_maximumAnisotropy); - LOG_INFO(CONTEXT_RENDERER, " - maximum viewport size: " << m_maxViewportWidth << " x " << m_maxViewportHeight); - LOG_INFO(CONTEXT_RENDERER, " - maximum number of FBO draw buffers: " << m_maximumDrawBuffers); - LOG_INFO(CONTEXT_RENDERER, " - external textures supported: " << m_externalTextureExtensionSupported); - - LOG_INFO(CONTEXT_RENDERER, " - supported texture formats: " << m_availableTextureFormats.size()); + LOG_INFO(CONTEXT_RENDERER, " - maximum number of texture units: {}", m_maximumTextureUnits); + LOG_INFO(CONTEXT_RENDERER, " - maximum number of MSAA samples: {}", m_maximumSamples); + LOG_INFO(CONTEXT_RENDERER, " - maximum number of anisotropy samples: {}", m_maximumAnisotropy); + LOG_INFO(CONTEXT_RENDERER, " - maximum viewport size: {} x {}", m_maxViewportWidth, m_maxViewportHeight); + LOG_INFO(CONTEXT_RENDERER, " - maximum number of FBO draw buffers: {}", m_maximumDrawBuffers); + LOG_INFO(CONTEXT_RENDERER, " - external textures supported: {}", m_externalTextureExtensionSupported); + + LOG_INFO(CONTEXT_RENDERER, " - supported texture formats: {}", m_availableTextureFormats.size()); for(const auto& texture : m_availableTextureFormats) { - LOG_DEBUG(CONTEXT_RENDERER, " " << EnumToString(texture)); + LOG_DEBUG(CONTEXT_RENDERER, " {}", EnumToString(texture)); } } } diff --git a/src/renderer/internal/RendererLib/PlatformBase/Window_Base.cpp b/src/renderer/internal/RendererLib/PlatformBase/Window_Base.cpp index 0997a8c3a..b2fc92330 100644 --- a/src/renderer/internal/RendererLib/PlatformBase/Window_Base.cpp +++ b/src/renderer/internal/RendererLib/PlatformBase/Window_Base.cpp @@ -11,7 +11,7 @@ #include "internal/RendererLib/DisplayConfig.h" #include "internal/RendererLib/PlatformInterface/IWindowEventHandler.h" #include "internal/Core/Utils/LogMacros.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { diff --git a/src/renderer/internal/RendererLib/RamshCommands/AssignScene.cpp b/src/renderer/internal/RendererLib/RamshCommands/AssignScene.cpp index 6f15ad247..c13b5c190 100644 --- a/src/renderer/internal/RendererLib/RamshCommands/AssignScene.cpp +++ b/src/renderer/internal/RendererLib/RamshCommands/AssignScene.cpp @@ -68,7 +68,7 @@ namespace ramses::internal if (positionals.size() != 1) { - LOG_ERROR_P(CONTEXT_RAMSH, "None or too many arguments provided: {}", positionals.size()); + LOG_ERROR(CONTEXT_RAMSH, "None or too many arguments provided: {}", positionals.size()); return false; } @@ -76,7 +76,7 @@ namespace ramses::internal ArgumentConverter::tryConvert(positionals[0], sceneId.getReference()); if (!sceneId.isValid()) { - LOG_ERROR_P(CONTEXT_RAMSH, "Invalid SceneId: {}", positionals[0]); + LOG_ERROR(CONTEXT_RAMSH, "Invalid SceneId: {}", positionals[0]); return false; } cmdMap.scene = sceneId; diff --git a/src/renderer/internal/RendererLib/RamshCommands/CreateOffscreenBuffer.cpp b/src/renderer/internal/RendererLib/RamshCommands/CreateOffscreenBuffer.cpp index 4af50774f..92561fbf7 100644 --- a/src/renderer/internal/RendererLib/RamshCommands/CreateOffscreenBuffer.cpp +++ b/src/renderer/internal/RendererLib/RamshCommands/CreateOffscreenBuffer.cpp @@ -23,7 +23,7 @@ namespace ramses::internal { if (input.size() != 5) { - LOG_ERROR_P(CONTEXT_RAMSH, "None or too many arguments provided: {}", input.size() - 1); + LOG_ERROR(CONTEXT_RAMSH, "None or too many arguments provided: {}", input.size() - 1); return false; } ramses::internal::RendererCommand::CreateOffscreenBuffer cmd{}; @@ -32,12 +32,12 @@ namespace ramses::internal cmd.sampleCount = 0; if (!ArgumentConverter::tryConvert(input[1], cmd.display.asMemoryHandleReference())) { - LOG_ERROR_P(CONTEXT_RAMSH, "Invalid display id: {}", input[1]); + LOG_ERROR(CONTEXT_RAMSH, "Invalid display id: {}", input[1]); return false; } if (!ArgumentConverter::tryConvert(input[2], cmd.offscreenBuffer.asMemoryHandleReference())) { - LOG_ERROR_P(CONTEXT_RAMSH, "Invalid buffer id: {}", input[2]); + LOG_ERROR(CONTEXT_RAMSH, "Invalid buffer id: {}", input[2]); return false; } diff --git a/src/renderer/internal/RendererLib/RamshCommands/LogRendererInfo.cpp b/src/renderer/internal/RendererLib/RamshCommands/LogRendererInfo.cpp index 545c4219a..aead67e37 100644 --- a/src/renderer/internal/RendererLib/RamshCommands/LogRendererInfo.cpp +++ b/src/renderer/internal/RendererLib/RamshCommands/LogRendererInfo.cpp @@ -37,7 +37,7 @@ namespace ramses::internal if (!etopic.has_value()) return false; - m_rendererCommandBuffer.enqueueCommand(ramses::internal::RendererCommand::LogInfo{ *etopic, verbose, NodeHandle(nodeHandleFilter) }); + m_rendererCommandBuffer.enqueueCommand(ramses::internal::RendererCommand::LogInfo{ *etopic, verbose, NodeHandle(nodeHandleFilter), false, false, ELoopMode::UpdateAndRender, {} }); return true; } diff --git a/src/renderer/internal/RendererLib/RamshCommands/Screenshot.cpp b/src/renderer/internal/RendererLib/RamshCommands/Screenshot.cpp index 6fa2bd7fb..2809717aa 100644 --- a/src/renderer/internal/RendererLib/RamshCommands/Screenshot.cpp +++ b/src/renderer/internal/RendererLib/RamshCommands/Screenshot.cpp @@ -76,7 +76,7 @@ namespace ramses::internal { continue; } - LOG_ERROR_P(CONTEXT_RAMSH, "Unknown option: {}", arg); + LOG_ERROR(CONTEXT_RAMSH, "Unknown option: {}", arg); return false; } } diff --git a/src/renderer/internal/RendererLib/RamshCommands/SetClearColor.cpp b/src/renderer/internal/RendererLib/RamshCommands/SetClearColor.cpp index 7ebb91677..61b925908 100644 --- a/src/renderer/internal/RendererLib/RamshCommands/SetClearColor.cpp +++ b/src/renderer/internal/RendererLib/RamshCommands/SetClearColor.cpp @@ -58,7 +58,7 @@ namespace ramses::internal if (positionals.size() != 5) { - LOG_ERROR_P(CONTEXT_RAMSH, "None or too many arguments provided: {}", positionals.size()); + LOG_ERROR(CONTEXT_RAMSH, "None or too many arguments provided: {}", positionals.size()); return false; } diff --git a/src/renderer/internal/RendererLib/RamshCommands/SetSceneState.cpp b/src/renderer/internal/RendererLib/RamshCommands/SetSceneState.cpp index bc67af98c..9675a4fba 100644 --- a/src/renderer/internal/RendererLib/RamshCommands/SetSceneState.cpp +++ b/src/renderer/internal/RendererLib/RamshCommands/SetSceneState.cpp @@ -25,7 +25,7 @@ namespace ramses::internal { if (sceneState >= 4) { - LOG_ERROR_P(CONTEXT_RAMSH, "Invalid scene state: {}", sceneState); + LOG_ERROR(CONTEXT_RAMSH, "Invalid scene state: {}", sceneState); return false; } m_rendererCommandBuffer.enqueueCommand(ramses::internal::RendererCommand::SetSceneState{ SceneId{sceneId}, static_cast(sceneState) }); diff --git a/src/renderer/internal/RendererLib/Renderer.cpp b/src/renderer/internal/RendererLib/Renderer.cpp index b05f125d6..6782507c5 100644 --- a/src/renderer/internal/RendererLib/Renderer.cpp +++ b/src/renderer/internal/RendererLib/Renderer.cpp @@ -22,7 +22,7 @@ #include "internal/RendererLib/DisplayEventHandler.h" #include "internal/RendererLib/SceneExpirationMonitor.h" #include "internal/RendererLib/PlatformBase/Platform_Base.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal @@ -399,14 +399,14 @@ namespace ramses::internal if (RendererInterruptState::IsInterrupted(interruptState)) { m_rendererInterruptState = RendererInterruptState{ displayBuffer, sceneId, interruptState }; - LOG_TRACE(CONTEXT_PROFILING, "Renderer::renderToInterruptibleOffscreenBuffers interrupted rendering to OB " << displayBuffer.asMemoryHandle() << ", scene " << sceneId.getValue()); + LOG_TRACE(CONTEXT_PROFILING, "Renderer::renderToInterruptibleOffscreenBuffers interrupted rendering to OB {}, scene {}", displayBuffer.asMemoryHandle(), sceneId.getValue()); m_statistics.offscreenBufferInterrupted(displayBuffer); break; } m_rendererInterruptState = RendererInterruptState{}; onSceneWasRendered(scene); - LOG_TRACE(CONTEXT_PROFILING, "Renderer::renderToInterruptibleOffscreenBuffers scene fully rendered to interruptible OB " << displayBuffer.asMemoryHandle() << ", scene " << sceneId.getValue()); + LOG_TRACE(CONTEXT_PROFILING, "Renderer::renderToInterruptibleOffscreenBuffers scene fully rendered to interruptible OB {}, scene {}", displayBuffer.asMemoryHandle(), sceneId.getValue()); } if (m_rendererInterruptState.isInterrupted()) @@ -416,7 +416,7 @@ namespace ramses::internal m_displayController->getRenderBackend().getDevice().swapDoubleBufferedRenderTarget(displayBuffer); m_statistics.offscreenBufferSwapped(displayBuffer, true); - LOG_TRACE(CONTEXT_PROFILING, "Renderer::renderToInterruptibleOffscreenBuffers interruptible OB " << displayBuffer.asMemoryHandle() << " swapped"); + LOG_TRACE(CONTEXT_PROFILING, "Renderer::renderToInterruptibleOffscreenBuffers interruptible OB {} swapped", displayBuffer.asMemoryHandle()); //re-render framebuffer in next frame to reflect (finished!) changes in OB m_displayBuffersSetup.setDisplayBufferToBeRerendered(m_frameBufferDeviceHandle, true); @@ -612,7 +612,7 @@ namespace ramses::internal { assert(hasDisplayController()); if (m_screenshots.count(renderTargetHandle) != 0u) - LOG_WARN(CONTEXT_RENDERER, "Renderer::scheduleScreenshot: will overwrite previous screenshot request that was not executed yet (buffer=" << renderTargetHandle << ")"); + LOG_WARN(CONTEXT_RENDERER, "Renderer::scheduleScreenshot: will overwrite previous screenshot request that was not executed yet (buffer={})", renderTargetHandle); m_screenshots[renderTargetHandle] = std::move(screenshot); diff --git a/src/renderer/internal/RendererLib/RendererCommandExecutor.cpp b/src/renderer/internal/RendererLib/RendererCommandExecutor.cpp index 66f67c1ac..9ffe22ecf 100644 --- a/src/renderer/internal/RendererLib/RendererCommandExecutor.cpp +++ b/src/renderer/internal/RendererLib/RendererCommandExecutor.cpp @@ -18,7 +18,7 @@ #include "internal/RendererLib/PlatformInterface/IDisplayController.h" #include "internal/RendererLib/RendererEventCollector.h" #include "internal/Core/Utils/Image.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -43,7 +43,7 @@ namespace ramses::internal return !std::holds_alternative(cmd) && !std::holds_alternative(cmd); }); if (numCommandsToLog > 0) - LOG_INFO_P(CONTEXT_RENDERER, "RendererCommandExecutor executing {} commands, {} commands will be logged, rest is flush/sceneupdate commands", m_tmpCommands.size(), numCommandsToLog); + LOG_INFO(CONTEXT_RENDERER, "RendererCommandExecutor executing {} commands, {} commands will be logged, rest is flush/sceneupdate commands", m_tmpCommands.size(), numCommandsToLog); for (auto& cmd : m_tmpCommands) std::visit(*this, cmd); @@ -51,32 +51,32 @@ namespace ramses::internal void RendererCommandExecutor::operator()(const RendererCommand::ScenePublished& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleScenePublished(cmd.scene, cmd.publicationMode); } void RendererCommandExecutor::operator()(const RendererCommand::SceneUnpublished& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleSceneUnpublished(cmd.scene); } void RendererCommandExecutor::operator()(const RendererCommand::ReceiveScene& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleSceneReceived(cmd.info); } void RendererCommandExecutor::operator()(RendererCommand::UpdateScene& cmd) { // log debug only to reduce spam - LOG_DEBUG(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_DEBUG(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleSceneUpdate(cmd.scene, std::move(cmd.updateData)); } void RendererCommandExecutor::operator()(const RendererCommand::SetSceneState& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneControlLogic.setSceneState(cmd.scene, cmd.state); } @@ -87,122 +87,122 @@ namespace ramses::internal void RendererCommandExecutor::operator()(const RendererCommand::SetSceneDisplayBufferAssignment& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneControlLogic.setSceneDisplayBufferAssignment(cmd.scene, cmd.buffer, cmd.renderOrder); } void RendererCommandExecutor::operator()(const RendererCommand::LinkData& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleSceneDataLinkRequest(cmd.providerScene, cmd.providerData, cmd.consumerScene, cmd.consumerData); } void RendererCommandExecutor::operator()(const RendererCommand::LinkOffscreenBuffer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleBufferToSceneDataLinkRequest(cmd.providerBuffer, cmd.consumerScene, cmd.consumerData); } void RendererCommandExecutor::operator()(const RendererCommand::LinkStreamBuffer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleBufferToSceneDataLinkRequest(cmd.providerBuffer, cmd.consumerScene, cmd.consumerData); } void RendererCommandExecutor::operator()(const RendererCommand::LinkExternalBuffer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleBufferToSceneDataLinkRequest(cmd.providerBuffer, cmd.consumerScene, cmd.consumerData); } void RendererCommandExecutor::operator()(const RendererCommand::UnlinkData& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleDataUnlinkRequest(cmd.consumerScene, cmd.consumerData); } void RendererCommandExecutor::operator()(const RendererCommand::PickEvent& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handlePickEvent(cmd.scene, cmd.coordsNormalizedToBufferSize); } void RendererCommandExecutor::operator()(const RendererCommand::CreateDisplay& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.createDisplayContext(cmd.config, cmd.binaryShaderCache); } void RendererCommandExecutor::operator()(const RendererCommand::DestroyDisplay& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.destroyDisplayContext(); } void RendererCommandExecutor::operator()(const RendererCommand::CreateOffscreenBuffer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleBufferCreateRequest(cmd.offscreenBuffer, cmd.width, cmd.height, cmd.sampleCount, cmd.interruptible, cmd.depthStencilBufferType); } void RendererCommandExecutor::operator()(const RendererCommand::CreateDmaOffscreenBuffer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleDmaBufferCreateRequest(cmd.offscreenBuffer, cmd.width, cmd.height, cmd.dmaBufferFourccFormat, cmd.dmaBufferUsageFlags, cmd.dmaBufferModifiers); } void RendererCommandExecutor::operator()(const RendererCommand::DestroyOffscreenBuffer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); const bool succeeded = m_sceneUpdater.handleBufferDestroyRequest(cmd.offscreenBuffer); m_rendererEventCollector.addOBEvent((succeeded ? ERendererEventType::OffscreenBufferDestroyed : ERendererEventType::OffscreenBufferDestroyFailed), cmd.offscreenBuffer, cmd.display, -1, 0u); } void RendererCommandExecutor::operator()(const RendererCommand::CreateStreamBuffer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleBufferCreateRequest(cmd.streamBuffer, cmd.source); } void RendererCommandExecutor::operator()(const RendererCommand::DestroyStreamBuffer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleBufferDestroyRequest(cmd.streamBuffer); } void RendererCommandExecutor::operator()(const RendererCommand::CreateExternalBuffer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleExternalBufferCreateRequest(cmd.externalBuffer); } void RendererCommandExecutor::operator()(const RendererCommand::DestroyExternalBuffer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleExternalBufferDestroyRequest(cmd.externalBuffer); } void RendererCommandExecutor::operator()(const RendererCommand::SetClearFlags& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleSetClearFlags(cmd.offscreenBuffer, cmd.clearFlags); } void RendererCommandExecutor::operator()(const RendererCommand::SetClearColor& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleSetClearColor(cmd.offscreenBuffer, cmd.clearColor); } void RendererCommandExecutor::operator()(const RendererCommand::SetExterallyOwnedWindowSize& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.handleSetExternallyOwnedWindowSize(cmd.width, cmd.height); } void RendererCommandExecutor::operator()(RendererCommand::ReadPixels& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); ScreenshotInfo screenshot; screenshot.rectangle = { cmd.offsetX, cmd.offsetY, cmd.width, cmd.height }; screenshot.filename = std::move(cmd.filename); @@ -213,80 +213,80 @@ namespace ramses::internal void RendererCommandExecutor::operator()(const RendererCommand::SetSkippingOfUnmodifiedBuffers& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.setSkippingOfUnmodifiedScenes(cmd.enable); } void RendererCommandExecutor::operator()(const RendererCommand::LogStatistics& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); LOG_INFO_F(CONTEXT_RENDERER, ([&](StringOutputStream& sos) { m_renderer.getStatistics().writeStatsToStream(sos); })); LOG_INFO_F(CONTEXT_RENDERER, ([&](StringOutputStream& sos) { m_renderer.getProfilerStatistics().writeLongestFrameTimingsToStream(sos); })); } void RendererCommandExecutor::operator()(const RendererCommand::LogInfo& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); - m_sceneUpdater.logRendererInfo(cmd.topic, cmd.verbose, cmd.nodeFilter); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); + m_sceneUpdater.logRendererInfo(cmd); } void RendererCommandExecutor::operator()(const RendererCommand::SCListIviSurfaces& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_renderer.systemCompositorListIviSurfaces(); } void RendererCommandExecutor::operator()(const RendererCommand::SCSetIviSurfaceVisibility& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_renderer.systemCompositorSetIviSurfaceVisibility(cmd.surface, cmd.visibility); } void RendererCommandExecutor::operator()(const RendererCommand::SCSetIviSurfaceOpacity& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_renderer.systemCompositorSetIviSurfaceOpacity(cmd.surface, cmd.opacity); } void RendererCommandExecutor::operator()(const RendererCommand::SCSetIviSurfaceDestRectangle& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_renderer.systemCompositorSetIviSurfaceDestRectangle(cmd.surface, cmd.x, cmd.y, cmd.width, cmd.height); } void RendererCommandExecutor::operator()(const RendererCommand::SCScreenshot& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_renderer.systemCompositorScreenshot(cmd.filename, cmd.screenId); } void RendererCommandExecutor::operator()(const RendererCommand::SCAddIviSurfaceToIviLayer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); std::ignore = m_renderer.systemCompositorAddIviSurfaceToIviLayer(cmd.surface, cmd.layer); } void RendererCommandExecutor::operator()(const RendererCommand::SCSetIviLayerVisibility& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_renderer.systemCompositorSetIviLayerVisibility(cmd.layer, cmd.visibility); } void RendererCommandExecutor::operator()(const RendererCommand::SCRemoveIviSurfaceFromIviLayer& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_renderer.systemCompositorRemoveIviSurfaceFromIviLayer(cmd.surface, cmd.layer); } void RendererCommandExecutor::operator()(const RendererCommand::SCDestroyIviSurface& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_renderer.systemCompositorDestroyIviSurface(cmd.surface); } void RendererCommandExecutor::operator()(const RendererCommand::SetLimits_FrameBudgets& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_frameTimer.setSectionTimeBudget(EFrameTimerSectionBudget::SceneResourcesUpload, cmd.limitForSceneResourcesUploadMicrosec); m_frameTimer.setSectionTimeBudget(EFrameTimerSectionBudget::ResourcesUpload, cmd.limitForResourcesUploadMicrosec); m_frameTimer.setSectionTimeBudget(EFrameTimerSectionBudget::OffscreenBufferRender, cmd.limitForOffscreenBufferRenderMicrosec); @@ -294,19 +294,19 @@ namespace ramses::internal void RendererCommandExecutor::operator()(const RendererCommand::SetLimits_FlushesForceApply& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.setLimitFlushesForceApply(cmd.limitForPendingFlushesForceApply); } void RendererCommandExecutor::operator()(const RendererCommand::SetLimits_FlushesForceUnsubscribe& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); m_sceneUpdater.setLimitFlushesForceUnsubscribe(cmd.limitForPendingFlushesForceUnsubscribe); } void RendererCommandExecutor::operator()(const RendererCommand::ConfirmationEcho& cmd) { - LOG_INFO(CONTEXT_RENDERER, " - executing " << RendererCommandUtils::ToString(cmd)); - LOG_INFO(CONTEXT_RAMSH, "confirmation: " << cmd.text); + LOG_INFO(CONTEXT_RENDERER, " - executing {}", RendererCommandUtils::ToString(cmd)); + LOG_INFO(CONTEXT_RAMSH, "confirmation: {}", cmd.text); } } diff --git a/src/renderer/internal/RendererLib/RendererCommands.h b/src/renderer/internal/RendererLib/RendererCommands.h index 7ec1ca037..3d0d335ca 100644 --- a/src/renderer/internal/RendererLib/RendererCommands.h +++ b/src/renderer/internal/RendererLib/RendererCommands.h @@ -222,6 +222,10 @@ namespace ramses::internal ERendererLogTopic topic = ERendererLogTopic::All; bool verbose = false; NodeHandle nodeFilter; + bool displaysThreaded = false; + bool displaysThreadsRunning = false; + ELoopMode rendererLoopMode = ELoopMode::UpdateAndRender; + std::chrono::microseconds minFrameTime; }; struct SCListIviSurfaces diff --git a/src/renderer/internal/RendererLib/RendererEventCollector.cpp b/src/renderer/internal/RendererLib/RendererEventCollector.cpp index b1299ce6e..0bd39f44b 100644 --- a/src/renderer/internal/RendererLib/RendererEventCollector.cpp +++ b/src/renderer/internal/RendererLib/RendererEventCollector.cpp @@ -7,7 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/RendererLib/RendererEventCollector.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -38,7 +38,7 @@ namespace ramses::internal void RendererEventCollector::addDisplayEvent(ERendererEventType eventType, DisplayHandle displayHandle, const DisplayConfig& config) { - LOG_INFO(CONTEXT_RENDERER, eventType << " display=" << displayHandle); + LOG_INFO(CONTEXT_RENDERER, "{} display={}", eventType, displayHandle); RendererEvent event(eventType); event.displayHandle = displayHandle; @@ -48,7 +48,7 @@ namespace ramses::internal void RendererEventCollector::addReadPixelsEvent(ERendererEventType eventType, DisplayHandle displayHandle, OffscreenBufferHandle offscreenBufferHandle, std::vector&& pixelData) { - LOG_INFO(CONTEXT_RENDERER, eventType << " display=" << displayHandle); + LOG_INFO(CONTEXT_RENDERER, "{} display = {}", eventType, displayHandle); RendererEvent event(eventType); event.displayHandle = displayHandle; @@ -72,7 +72,7 @@ namespace ramses::internal void RendererEventCollector::addSceneExpirationEvent(ERendererEventType eventType, SceneId sceneId) { - LOG_INFO(CONTEXT_RENDERER, eventType << " sceneId=" << sceneId); + LOG_INFO(CONTEXT_RENDERER, "{} sceneId={}", eventType, sceneId); RendererEvent event(eventType); event.sceneId = sceneId; @@ -81,7 +81,7 @@ namespace ramses::internal void RendererEventCollector::addDataLinkEvent(ERendererEventType eventType, SceneId providerSceneId, SceneId consumerSceneId, DataSlotId providerdataId, DataSlotId consumerdataId) { - LOG_INFO(CONTEXT_RENDERER, eventType << " providerSceneId=" << providerSceneId << " providerDataId=" << providerdataId.getValue() << " consumerSceneId=" << consumerSceneId << " consumerDataId=" << consumerdataId.getValue()); + LOG_INFO(CONTEXT_RENDERER, "{} providerSceneId={} providerDataId={} consumerSceneId={} consumerDataId={}", eventType, providerSceneId, providerdataId.getValue(), consumerSceneId, consumerdataId.getValue()); RendererEvent event(eventType); event.providerSceneId = providerSceneId; @@ -93,7 +93,7 @@ namespace ramses::internal void RendererEventCollector::addBufferEvent(ERendererEventType eventType, OffscreenBufferHandle providerBuffer, SceneId consumerSceneId, DataSlotId consumerdataId) { - LOG_INFO(CONTEXT_RENDERER, eventType << " consumerSceneId=" << consumerSceneId.getValue() << " consumerDataId=" << consumerdataId.getValue() << " offscreenBufferHandle=" << providerBuffer); + LOG_INFO(CONTEXT_RENDERER, "{} consumerSceneId={} consumerDataId={} offscreenBufferHandle={}", eventType, consumerSceneId.getValue(), consumerdataId.getValue(), providerBuffer); RendererEvent event(eventType); event.offscreenBuffer = providerBuffer; @@ -104,7 +104,7 @@ namespace ramses::internal void RendererEventCollector::addBufferEvent(ERendererEventType eventType, StreamBufferHandle providerBuffer, SceneId consumerSceneId, DataSlotId consumerdataId) { - LOG_INFO(CONTEXT_RENDERER, eventType << " consumerSceneId=" << consumerSceneId.getValue() << " consumerDataId=" << consumerdataId.getValue() << " streamBufferHandle=" << providerBuffer); + LOG_INFO(CONTEXT_RENDERER, "{} consumerSceneId={} consumerDataId={} streamBufferHandle={}", eventType, consumerSceneId.getValue(), consumerdataId.getValue(), providerBuffer); RendererEvent event(eventType); event.streamBuffer = providerBuffer; @@ -115,7 +115,7 @@ namespace ramses::internal void RendererEventCollector::addBufferEvent(ERendererEventType eventType, ExternalBufferHandle providerBuffer, SceneId consumerSceneId, DataSlotId consumerdataId) { - LOG_INFO(CONTEXT_RENDERER, eventType << " consumerSceneId=" << consumerSceneId.getValue() << " consumerDataId=" << consumerdataId.getValue() << " externalBufferHandle=" << providerBuffer); + LOG_INFO(CONTEXT_RENDERER, "{} consumerSceneId = {} consumerDataId = {} externalBufferHandle = {}", eventType, consumerSceneId.getValue(), consumerdataId.getValue(), providerBuffer); RendererEvent event(eventType); event.externalBuffer = providerBuffer; @@ -136,7 +136,7 @@ namespace ramses::internal void RendererEventCollector::addOBEvent(ERendererEventType eventType, OffscreenBufferHandle buffer, DisplayHandle display, int dmaBufferFD, uint32_t dmaBufferStride) { - LOG_INFO(CONTEXT_RENDERER, eventType << " display=" << display << " bufferHandle=" << buffer << " dmaBufferFD=" << dmaBufferFD << " dmaBufferStride=" << dmaBufferStride); + LOG_INFO(CONTEXT_RENDERER, "{} display={} bufferHandle={} dmaBufferFD={} dmaBufferStride={}", eventType, display, buffer, dmaBufferFD, dmaBufferStride); RendererEvent event(eventType); event.offscreenBuffer = buffer; @@ -148,7 +148,7 @@ namespace ramses::internal void RendererEventCollector::addSceneFlushEvent(ERendererEventType eventType, SceneId sceneId, SceneVersionTag sceneVersionTag) { - LOG_TRACE(CONTEXT_RENDERER, eventType << " sceneId=" << sceneId.getValue() << " sceneVersionTag=" << sceneVersionTag.getValue()); + LOG_TRACE(CONTEXT_RENDERER, "{} sceneId={} sceneVersionTag={}", eventType, sceneId.getValue(), sceneVersionTag.getValue()); RendererEvent event(eventType); event.sceneId = sceneId; @@ -190,7 +190,7 @@ namespace ramses::internal void RendererEventCollector::addStreamSourceEvent(ERendererEventType eventType, WaylandIviSurfaceId streamSourceId) { - LOG_INFO(CONTEXT_RENDERER, eventType << " streamSource=" << streamSourceId); + LOG_INFO(CONTEXT_RENDERER, "{} streamSource={}", eventType, streamSourceId); RendererEvent event(eventType); event.streamSourceId = streamSourceId; diff --git a/src/renderer/internal/RendererLib/RendererFrameworkLogic.cpp b/src/renderer/internal/RendererLib/RendererFrameworkLogic.cpp index 489b8a0c2..6e4694926 100644 --- a/src/renderer/internal/RendererLib/RendererFrameworkLogic.cpp +++ b/src/renderer/internal/RendererLib/RendererFrameworkLogic.cpp @@ -37,11 +37,11 @@ namespace ramses::internal void RendererFrameworkLogic::handleNewSceneAvailable(const SceneInfo& newScene, const Guid& providerID) { - LOG_INFO(CONTEXT_RENDERER, "RendererFrameworkLogic::handleNewScenesAvailable: scene published: " << newScene.sceneID << " @ " << providerID << " name:" << newScene.friendlyName << " publicationmode: " << EnumToString(newScene.publicationMode)); + LOG_INFO(CONTEXT_RENDERER, "RendererFrameworkLogic::handleNewScenesAvailable: scene published: {} @ {} name:{} publicationmode: {}", newScene.sceneID, providerID, newScene.friendlyName, EnumToString(newScene.publicationMode)); if (m_sceneClients.contains(newScene.sceneID)) { - LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::handleNewScenesAvailable: ignore already published scene: " << newScene.sceneID << " @ " << providerID << " name:" << newScene.friendlyName << " publicationmode: " << EnumToString(newScene.publicationMode)); + LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::handleNewScenesAvailable: ignore already published scene: {} @ {} name:{} publicationmode: {}", newScene.sceneID, providerID, newScene.friendlyName, EnumToString(newScene.publicationMode)); return; } m_sceneClients.put(newScene.sceneID, std::make_pair(providerID, newScene.friendlyName)); @@ -50,7 +50,7 @@ namespace ramses::internal void RendererFrameworkLogic::handleSceneBecameUnavailable(const SceneId& unavailableScene, const Guid& providerID) { - LOG_INFO(CONTEXT_RENDERER, "RendererFrameworkLogic::handleSceneBecameUnavailable: scene unpublished: " << unavailableScene << " by " << providerID); + LOG_INFO(CONTEXT_RENDERER, "RendererFrameworkLogic::handleSceneBecameUnavailable: scene unpublished: {} by {}", unavailableScene, providerID); assert(m_sceneClients.contains(unavailableScene)); m_sceneClients.remove(unavailableScene); @@ -59,7 +59,7 @@ namespace ramses::internal void RendererFrameworkLogic::handleInitializeScene(const SceneInfo& sceneInfo, const Guid& providerID) { - LOG_INFO(CONTEXT_RENDERER, "RendererFrameworkLogic::handleInitializeScene: " << sceneInfo.sceneID << " by " << providerID); + LOG_INFO(CONTEXT_RENDERER, "RendererFrameworkLogic::handleInitializeScene: {} by {}", sceneInfo.sceneID, providerID); assert(m_sceneClients.contains(sceneInfo.sceneID)); m_rendererCommands.enqueueCommand(RendererCommand::ReceiveScene{ sceneInfo }); @@ -76,7 +76,7 @@ namespace ramses::internal auto it = m_sceneClients.find(sceneId); if (it == m_sceneClients.end()) { - LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendSubscribeScene: can't send subscribe scene " << sceneId << " because provider unknown"); + LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendSubscribeScene: can't send subscribe scene {} because provider unknown", sceneId); return; } m_sceneGraphConsumerComponent.subscribeScene(it->value.first, sceneId); @@ -88,7 +88,7 @@ namespace ramses::internal auto it = m_sceneClients.find(sceneId); if (it == m_sceneClients.end()) { - LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendUnsubscribeScene: can't send subscribe scene " << sceneId << " because provider unknown"); + LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendUnsubscribeScene: can't send subscribe scene {} because provider unknown", sceneId); return; } m_sceneGraphConsumerComponent.unsubscribeScene(it->value.first, sceneId); @@ -105,11 +105,11 @@ namespace ramses::internal auto it = m_sceneClients.find(masterScene); if (it == m_sceneClients.end()) { - LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendSceneStateChanged: can't send scene state changed event for scene " << masterScene << " because provider unknown"); + LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendSceneStateChanged: can't send scene state changed event for scene {} because provider unknown", masterScene); return; } - LOG_INFO_P(CONTEXT_FRAMEWORK, + LOG_INFO(CONTEXT_FRAMEWORK, "RendererFrameworkLogic::sendSceneStateChanged: sending scene state changed event (state {} / master {} / reffed {}) to {}", EnumToString(newState), masterScene, referencedScene, it->value.first); m_sceneGraphConsumerComponent.sendSceneReferenceEvent(it->value.first, event); @@ -126,11 +126,11 @@ namespace ramses::internal auto it = m_sceneClients.find(masterScene); if (it == m_sceneClients.end()) { - LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendSceneFlushed: can't send scene state changed event for scene " << masterScene << " because provider unknown"); + LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendSceneFlushed: can't send scene state changed event for scene {} because provider unknown", masterScene); return; } - LOG_INFO_P(CONTEXT_FRAMEWORK, + LOG_INFO(CONTEXT_FRAMEWORK, "RendererFrameworkLogic::sendSceneFlushed: sending scene flushed event (tag {} / master {} / reffed {}) to {}", tag, masterScene, referencedScene, it->value.first); m_sceneGraphConsumerComponent.sendSceneReferenceEvent(it->value.first, event); @@ -150,11 +150,11 @@ namespace ramses::internal auto it = m_sceneClients.find(masterScene); if (it == m_sceneClients.end()) { - LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendDataLinked: can't send scene state changed event for scene " << masterScene << " because provider unknown"); + LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendDataLinked: can't send scene state changed event for scene {} because provider unknown", masterScene); return; } - LOG_INFO_P(CONTEXT_FRAMEWORK, + LOG_INFO(CONTEXT_FRAMEWORK, "RendererFrameworkLogic::sendDataLinked: sending data linked event (master {} / providerScene {} / provider {} / consumerScene {} / consumer {} / success {}) to {}", masterScene, providerScene, provider, consumerScene, consumer, success, it->value.first); m_sceneGraphConsumerComponent.sendSceneReferenceEvent(it->value.first, event); @@ -172,11 +172,11 @@ namespace ramses::internal auto it = m_sceneClients.find(masterScene); if (it == m_sceneClients.end()) { - LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendDataUnlinked: can't send scene state changed event for scene " << masterScene << " because provider unknown"); + LOG_WARN(CONTEXT_RENDERER, "RendererFrameworkLogic::sendDataUnlinked: can't send scene state changed event for scene {} because provider unknown", masterScene); return; } - LOG_INFO_P(CONTEXT_FRAMEWORK, + LOG_INFO(CONTEXT_FRAMEWORK, "RendererFrameworkLogic::sendDataLinked: sending data linked event (master {} / consumerScene {} / consumer {} / success {}) to {}", masterScene, consumerScene, consumer, success, it->value.first); m_sceneGraphConsumerComponent.sendSceneReferenceEvent(it->value.first, event); diff --git a/src/renderer/internal/RendererLib/RendererLogger.cpp b/src/renderer/internal/RendererLib/RendererLogger.cpp index 5604fb56f..7a5bf0117 100644 --- a/src/renderer/internal/RendererLib/RendererLogger.cpp +++ b/src/renderer/internal/RendererLib/RendererLogger.cpp @@ -33,7 +33,7 @@ #include "internal/RendererLib/RenderExecutorLogger.h" #include "internal/RendererLib/RendererEventCollector.h" #include "internal/RendererLib/PlatformBase/DeviceResourceMapper.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -63,11 +63,11 @@ namespace ramses::internal } } - void RendererLogger::LogTopic(const RendererSceneUpdater& updater, ERendererLogTopic topic, bool verbose, NodeHandle nodeHandleFilter) + void RendererLogger::LogTopic(const RendererSceneUpdater& updater, const RendererCommand::LogInfo& cmd) { - RendererLogContext context(verbose ? ERendererLogLevelFlag_Details : ERendererLogLevelFlag_Info); - context.setNodeHandleFilter(nodeHandleFilter); - switch (topic) + RendererLogContext context(cmd.verbose ? ERendererLogLevelFlag_Details : ERendererLogLevelFlag_Info); + context.setNodeHandleFilter(cmd.nodeFilter); + switch (cmd.topic) { case ERendererLogTopic::Displays: LogDisplays(updater, context); @@ -106,13 +106,13 @@ namespace ramses::internal LogEventQueue(updater, context); break; case ERendererLogTopic::PeriodicLog: - LogPeriodicInfo(updater); + LogPeriodicInfo(updater, cmd); break; default: - context << "Log topic " << topic << " not found!" << RendererLogContext::NewLine; + context << "Log topic " << cmd.topic << " not found!" << RendererLogContext::NewLine; break; } - if (topic != ERendererLogTopic::PeriodicLog) + if (cmd.topic != ERendererLogTopic::PeriodicLog) { Log(CONTEXT_RENDERER, context); } @@ -1037,15 +1037,21 @@ namespace ramses::internal EndSection("RENDERER EVENTS", context); } - void RendererLogger::LogPeriodicInfo(const RendererSceneUpdater& updater) + void RendererLogger::LogPeriodicInfo(const RendererSceneUpdater& updater, const RendererCommand::LogInfo& cmd) { LOG_INFO_F(CONTEXT_PERIODIC, ([&](StringOutputStream& sos) { sos.reserve(2048); + sos << "Display: threaded=" << cmd.displaysThreaded + << " dispThreadsRunning=" << cmd.displaysThreadsRunning + << " loopMode=" << (cmd.rendererLoopMode == ELoopMode::UpdateAndRender ? "UpdAndRnd" : "UpdOnly") + << " targetFPS=" << std::round(1000000.0 / cmd.minFrameTime.count()) + << " skub=" << updater.m_skipUnmodifiedScenes; + SceneIdVector knownSceneIds; updater.m_sceneStateExecutor.m_scenesStateInfo.getKnownSceneIds(knownSceneIds); - sos << "Renderer: " << knownSceneIds.size() << " scene(s):"; + sos << "\n" << knownSceneIds.size() << " scene(s):"; for(const auto& sceneId : knownSceneIds) { const ESceneState sceneState = updater.m_sceneStateExecutor.getSceneState(sceneId); @@ -1088,8 +1094,7 @@ namespace ramses::internal sos << "\nTime budgets:" << " sceneResourceUpload " << int64_t(updater.m_frameTimer.getTimeBudgetForSection(EFrameTimerSectionBudget::SceneResourcesUpload).count()) << "us" << " resourceUpload " << int64_t(updater.m_frameTimer.getTimeBudgetForSection(EFrameTimerSectionBudget::ResourcesUpload).count()) << "us" - << " obRender " << int64_t(updater.m_frameTimer.getTimeBudgetForSection(EFrameTimerSectionBudget::OffscreenBufferRender).count()) << "us" - << " skub=" << updater.m_skipUnmodifiedScenes; + << " obRender " << int64_t(updater.m_frameTimer.getTimeBudgetForSection(EFrameTimerSectionBudget::OffscreenBufferRender).count()) << "us"; sos << "\n"; updater.m_renderer.getProfilerStatistics().writeLongestFrameTimingsToStream(sos); sos << "\n"; diff --git a/src/renderer/internal/RendererLib/RendererLogger.h b/src/renderer/internal/RendererLib/RendererLogger.h index f260ba7ec..4c0222044 100644 --- a/src/renderer/internal/RendererLib/RendererLogger.h +++ b/src/renderer/internal/RendererLib/RendererLogger.h @@ -15,6 +15,7 @@ #include "internal/SceneGraph/SceneAPI/EDataType.h" #include "internal/SceneGraph/SceneAPI/EDataSlotType.h" #include "internal/RendererLib/Types.h" +#include "internal/RendererLib/RendererCommands.h" #include #include @@ -33,7 +34,7 @@ namespace ramses::internal { public: RendererLogger() = delete; - static void LogTopic(const RendererSceneUpdater& updater, ERendererLogTopic topic, bool verbose, NodeHandle nodeHandleFilter = NodeHandle::Invalid()); + static void LogTopic(const RendererSceneUpdater& updater, const RendererCommand::LogInfo& cmd); private: static void LogSceneStates(const RendererSceneUpdater& updater, RendererLogContext& context); @@ -47,7 +48,7 @@ namespace ramses::internal static void LogLinks(const RendererScenes& scenes, RendererLogContext& context); static void LogEmbeddedCompositor(const RendererSceneUpdater& updater, RendererLogContext& context); static void LogEventQueue(const RendererSceneUpdater& updater, RendererLogContext& context); - static void LogPeriodicInfo(const RendererSceneUpdater& updater); + static void LogPeriodicInfo(const RendererSceneUpdater& updater, const RendererCommand::LogInfo& cmd); static void LogReferencedScenes(const RendererSceneUpdater& updater, RendererLogContext& context); static void LogProvider(const RendererScenes& scenes, RendererLogContext& context, const RendererCachedScene& scene, const DataSlotHandle slotHandle, bool asLinked = false); diff --git a/src/renderer/internal/RendererLib/RendererPeriodicLogSupplier.cpp b/src/renderer/internal/RendererLib/RendererPeriodicLogSupplier.cpp index 4b76630c6..daff4da8b 100644 --- a/src/renderer/internal/RendererLib/RendererPeriodicLogSupplier.cpp +++ b/src/renderer/internal/RendererLib/RendererPeriodicLogSupplier.cpp @@ -26,6 +26,7 @@ namespace ramses::internal void RendererPeriodicLogSupplier::triggerLogMessageForPeriodicLog() { - m_commandBuffer.enqueueCommand(RendererCommand::LogInfo{ ERendererLogTopic::PeriodicLog, false, {} }); + // periodic log renderer info stored in the command will be filled with actual values when dispatching the command + m_commandBuffer.enqueueCommand(RendererCommand::LogInfo{ ERendererLogTopic::PeriodicLog, false, {}, false, false, ELoopMode::UpdateAndRender, {} }); } } diff --git a/src/renderer/internal/RendererLib/RendererResourceManager.cpp b/src/renderer/internal/RendererLib/RendererResourceManager.cpp index 3dacfcac8..90db0eceb 100644 --- a/src/renderer/internal/RendererLib/RendererResourceManager.cpp +++ b/src/renderer/internal/RendererLib/RendererResourceManager.cpp @@ -17,7 +17,7 @@ #include "internal/SceneGraph/SceneAPI/EDataBufferType.h" #include "internal/Components/ManagedResource.h" #include "internal/SceneGraph/Resource/ResourceInfo.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/TextureMathUtils.h" #include "internal/Core/Utils/LogMacros.h" #include @@ -306,7 +306,7 @@ namespace ramses::internal void RendererResourceManager::uploadRenderTargetBuffer(RenderBufferHandle renderBufferHandle, SceneId sceneId, const RenderBuffer& renderBuffer) { const uint32_t memSize = renderBuffer.width * renderBuffer.height * GetTexelSizeFromFormat(renderBuffer.format) * std::max(1u, renderBuffer.sampleCount); - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::uploadRenderTargetBuffer sceneId={} handle={} {}x{} {} samples={} estimatedSize={}KB", sceneId, renderBufferHandle, + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::uploadRenderTargetBuffer sceneId={} handle={} {}x{} {} samples={} estimatedSize={}KB", sceneId, renderBufferHandle, renderBuffer.width, renderBuffer.height, EnumToString(renderBuffer.format), renderBuffer.sampleCount, memSize/1024); RendererSceneResourceRegistry& sceneResources = getSceneResourceRegistry(sceneId); @@ -319,13 +319,13 @@ namespace ramses::internal std::ignore = device.isDeviceStatusHealthy(); } - sceneResources.addRenderBuffer(renderBufferHandle, deviceHandle, memSize, ERenderBufferAccessMode::WriteOnly == renderBuffer.accessMode); + sceneResources.addRenderBuffer(renderBufferHandle, deviceHandle, memSize, renderBuffer); m_stats.sceneResourceUploaded(sceneId, memSize); } void RendererResourceManager::unloadRenderTargetBuffer(RenderBufferHandle renderBufferHandle, SceneId sceneId) { - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::unloadRenderTargetBuffer sceneId={} handle={}", sceneId, renderBufferHandle); + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::unloadRenderTargetBuffer sceneId={} handle={}", sceneId, renderBufferHandle); assert(m_sceneResourceRegistryMap.contains(sceneId)); RendererSceneResourceRegistry& sceneResources = *m_sceneResourceRegistryMap.get(sceneId); @@ -335,6 +335,25 @@ namespace ramses::internal sceneResources.removeRenderBuffer(renderBufferHandle); } + void RendererResourceManager::updateRenderTargetBufferProperties(RenderBufferHandle renderBufferHandle, SceneId sceneId, const RenderBuffer& renderBuffer) + { + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::updateRenderTargetBufferProperties sceneId={} handle={} {}x{} {} samples={}", sceneId, renderBufferHandle, + renderBuffer.width, renderBuffer.height, EnumToString(renderBuffer.format), renderBuffer.sampleCount); + + assert(m_sceneResourceRegistryMap.contains(sceneId)); + RendererSceneResourceRegistry& sceneResources = *m_sceneResourceRegistryMap.get(sceneId); + + const RenderBuffer& uploadedRenderBufferProperties = sceneResources.getRenderBufferProperties(renderBufferHandle); + if (renderBuffer.width != uploadedRenderBufferProperties.width || + renderBuffer.height != uploadedRenderBufferProperties.height || + renderBuffer.sampleCount != uploadedRenderBufferProperties.sampleCount || + renderBuffer.format != uploadedRenderBufferProperties.format || + renderBuffer.accessMode != uploadedRenderBufferProperties.accessMode) + { + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceManager::updateRenderTargetBufferProperties changing properties of RenderBuffer which is already uploaded is not supported!"); + } + } + void RendererResourceManager::uploadRenderTarget(RenderTargetHandle renderTarget, const RenderBufferHandleVector& rtBufferHandles, SceneId sceneId) { LOG_INFO_PF(CONTEXT_RENDERER, ([&](auto& out) { @@ -364,7 +383,7 @@ namespace ramses::internal void RendererResourceManager::unloadRenderTarget(RenderTargetHandle renderTarget, SceneId sceneId) { - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::unloadRenderTarget sceneId={} handle={}", sceneId, renderTarget); + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::unloadRenderTarget sceneId={} handle={}", sceneId, renderTarget); assert(m_sceneResourceRegistryMap.contains(sceneId)); RendererSceneResourceRegistry& sceneResources = *m_sceneResourceRegistryMap.get(sceneId); @@ -386,7 +405,7 @@ namespace ramses::internal offscreenBufferDesc.m_colorBufferHandle[0] = device.uploadDmaRenderBuffer(width, height, dmaBufferFourccFormat, dmaBufferUsageFlags, dmaBufferModifiers); offscreenBufferDesc.m_estimatedVRAMUsage = width * height * GetTexelSizeFromFormat(EPixelStorageFormat::RGBA8); - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::uploadDmaOffscreenBuffer handle={} {}x{} fourccFormat={} usage={} modifier={} estimatedSize(RGBA8)={}KB", bufferHandle, + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::uploadDmaOffscreenBuffer handle={} {}x{} fourccFormat={} usage={} modifier={} estimatedSize(RGBA8)={}KB", bufferHandle, width, height, dmaBufferFourccFormat.getValue(), dmaBufferUsageFlags.getValue(), dmaBufferModifiers.getValue(), offscreenBufferDesc.m_estimatedVRAMUsage / 1024); offscreenBufferDesc.m_renderTargetHandle[0] = device.uploadRenderTarget({ offscreenBufferDesc.m_colorBufferHandle[0] }); @@ -424,7 +443,7 @@ namespace ramses::internal } offscreenBufferDesc.m_estimatedVRAMUsage = width * height * std::max(1u, sampleCount) * texelSize; - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::uploadOffscreenBuffer handle={} {}x{} samples={} interruptible={} depthType={} estimatedSize={}KB", bufferHandle, + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::uploadOffscreenBuffer handle={} {}x{} samples={} interruptible={} depthType={} estimatedSize={}KB", bufferHandle, width, height, sampleCount, isDoubleBuffered, depthStencilBufferType, offscreenBufferDesc.m_estimatedVRAMUsage / 1024); DeviceHandleVector bufferDeviceHandles; @@ -456,7 +475,7 @@ namespace ramses::internal void RendererResourceManager::unloadOffscreenBuffer(OffscreenBufferHandle bufferHandle) { - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::unloadOffscreenBuffer handle={}", bufferHandle); + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::unloadOffscreenBuffer handle={}", bufferHandle); assert(m_offscreenBuffers.isAllocated(bufferHandle)); IDevice& device = m_renderBackend.getDevice(); @@ -489,7 +508,7 @@ namespace ramses::internal void RendererResourceManager::uploadStreamBuffer(StreamBufferHandle bufferHandle, WaylandIviSurfaceId source) { - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::uploadStreamBuffer handle={} source={}", bufferHandle, source); + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::uploadStreamBuffer handle={} source={}", bufferHandle, source); assert(!m_streamBuffers.isAllocated(bufferHandle)); m_streamBuffers.allocate(bufferHandle); @@ -503,7 +522,7 @@ namespace ramses::internal void RendererResourceManager::unloadStreamBuffer(StreamBufferHandle bufferHandle) { - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::unloadStreamBuffer handle={}", bufferHandle); + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::unloadStreamBuffer handle={}", bufferHandle); assert(m_streamBuffers.isAllocated(bufferHandle)); const auto source = *m_streamBuffers.getMemory(bufferHandle); @@ -519,13 +538,13 @@ namespace ramses::internal void RendererResourceManager::uploadExternalBuffer(ExternalBufferHandle bufferHandle) { - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::uploadExternalBuffer handle={}", bufferHandle); + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::uploadExternalBuffer handle={}", bufferHandle); IDevice& device = m_renderBackend.getDevice(); if (!device.isExternalTextureExtensionSupported()) { - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::uploadExternalBuffer failed uploading handle={} because extension not supported on device", bufferHandle); + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::uploadExternalBuffer failed uploading handle={} because extension not supported on device", bufferHandle); return; } @@ -537,7 +556,7 @@ namespace ramses::internal void RendererResourceManager::unloadExternalBuffer(ExternalBufferHandle bufferHandle) { - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::unloadExternalBuffer handle={}", bufferHandle); + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::unloadExternalBuffer handle={}", bufferHandle); assert(m_externalBuffers.isAllocated(bufferHandle)); const auto deviceHandle = *m_externalBuffers.getMemory(bufferHandle); @@ -548,7 +567,7 @@ namespace ramses::internal void RendererResourceManager::uploadBlitPassRenderTargets(BlitPassHandle blitPass, RenderBufferHandle sourceRenderBuffer, RenderBufferHandle destinationRenderBuffer, SceneId sceneId) { - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::uploadBlitPassRenderTargets sceneId={} handle={} srcBufferHandle={} dstBufferHandle={}", sceneId, blitPass, sourceRenderBuffer, destinationRenderBuffer); + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::uploadBlitPassRenderTargets sceneId={} handle={} srcBufferHandle={} dstBufferHandle={}", sceneId, blitPass, sourceRenderBuffer, destinationRenderBuffer); assert(blitPass.isValid()); assert(sourceRenderBuffer.isValid()); @@ -578,7 +597,7 @@ namespace ramses::internal void RendererResourceManager::unloadBlitPassRenderTargets(BlitPassHandle blitPass, SceneId sceneId) { - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::unloadBlitPassRenderTargets sceneId={} handle={}", sceneId, blitPass); + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::unloadBlitPassRenderTargets sceneId={} handle={}", sceneId, blitPass); assert(m_sceneResourceRegistryMap.contains(sceneId)); RendererSceneResourceRegistry& sceneResources = *m_sceneResourceRegistryMap.get(sceneId); @@ -618,7 +637,7 @@ namespace ramses::internal assert(deviceHandle.isValid()); if (!deviceHandle.isValid()) { - LOG_ERROR_P(CONTEXT_RENDERER, "RendererResourceManager::uploadDataBuffer sceneId={} handle={} dataType={} size={} failed to allocate data buffer, this is fatal...", + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceManager::uploadDataBuffer sceneId={} handle={} dataType={} size={} failed to allocate data buffer, this is fatal...", sceneId, dataBufferHandle, EnumToString(dataType), dataSizeInBytes); std::ignore = device.isDeviceStatusHealthy(); } @@ -693,7 +712,7 @@ namespace ramses::internal RendererSceneResourceRegistry& sceneResources = getSceneResourceRegistry(sceneId); const uint32_t totalSizeInBytes = TextureMathUtils::GetTotalMemoryUsedByMipmappedTexture(GetTexelSizeFromFormat(textureFormat), width, height, 1u, mipLevelCount); - LOG_INFO_P(CONTEXT_RENDERER, "RendererResourceManager::uploadTextureBuffer sceneId={} handle={} {}x{} format={} mips={} estimatedSize={}KB", sceneId, textureBufferHandle, + LOG_INFO(CONTEXT_RENDERER, "RendererResourceManager::uploadTextureBuffer sceneId={} handle={} {}x{} format={} mips={} estimatedSize={}KB", sceneId, textureBufferHandle, width, height, EnumToString(textureFormat), mipLevelCount, totalSizeInBytes / 1024); IDevice& device = m_renderBackend.getDevice(); @@ -701,7 +720,7 @@ namespace ramses::internal assert(deviceHandle.isValid()); if (!deviceHandle.isValid()) { - LOG_ERROR_P(CONTEXT_RENDERER, "RendererResourceManager::uploadTextureBuffer failed to allocate texture buffer, this is fatal..."); + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceManager::uploadTextureBuffer failed to allocate texture buffer, this is fatal..."); std::ignore = device.isDeviceStatusHealthy(); } @@ -752,7 +771,7 @@ namespace ramses::internal assert(deviceHandle.isValid()); if (!deviceHandle.isValid()) { - LOG_ERROR_P(CONTEXT_RENDERER, "RendererResourceManager::uploadVertexArray sceneId={} renderableHandle={} failed to allocate vertex array, this is fatal...", + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceManager::uploadVertexArray sceneId={} renderableHandle={} failed to allocate vertex array, this is fatal...", sceneId, renderableHandle); std::ignore = device.isDeviceStatusHealthy(); } diff --git a/src/renderer/internal/RendererLib/RendererResourceManager.h b/src/renderer/internal/RendererLib/RendererResourceManager.h index ced296267..cbbdb9792 100644 --- a/src/renderer/internal/RendererLib/RendererResourceManager.h +++ b/src/renderer/internal/RendererLib/RendererResourceManager.h @@ -46,7 +46,7 @@ namespace ramses::internal void unreferenceResourcesForScene (SceneId sceneId, const ResourceContentHashVector& resources) override; void provideResourceData(const ManagedResource& mr) override; - [[nodiscard]] bool hasResourcesToBeUploaded() const override; + [[nodiscard]] bool hasResourcesToBeUploaded() const override; void uploadAndUnloadPendingResources() override; [[nodiscard]] DeviceResourceHandle getResourceDeviceHandle(const ResourceContentHash& hash) const override; @@ -60,6 +60,7 @@ namespace ramses::internal void uploadRenderTargetBuffer(RenderBufferHandle renderBufferHandle, SceneId sceneId, const RenderBuffer& renderBuffer) override; void unloadRenderTargetBuffer(RenderBufferHandle renderBufferHandle, SceneId sceneId) override; + void updateRenderTargetBufferProperties(RenderBufferHandle renderBufferHandle, SceneId sceneId, const RenderBuffer& renderBuffer) override; void uploadRenderTarget(RenderTargetHandle renderTarget, const RenderBufferHandleVector& rtBufferHandles, SceneId sceneId) override; void unloadRenderTarget(RenderTargetHandle renderTarget, SceneId sceneId) override; diff --git a/src/renderer/internal/RendererLib/RendererResourceRegistry.cpp b/src/renderer/internal/RendererLib/RendererResourceRegistry.cpp index 4abe604d1..2ef488079 100644 --- a/src/renderer/internal/RendererLib/RendererResourceRegistry.cpp +++ b/src/renderer/internal/RendererLib/RendererResourceRegistry.cpp @@ -7,16 +7,16 @@ // ------------------------------------------------------------------------- #include "internal/RendererLib/RendererResourceRegistry.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { void RendererResourceRegistry::registerResource(const ResourceContentHash& hash) { - LOG_TRACE(CONTEXT_RENDERER, "RendererResourceRegistry::registerResource Registering resource #" << hash); + LOG_TRACE(CONTEXT_RENDERER, "RendererResourceRegistry::registerResource Registering resource #{}", hash); if (m_resources.contains(hash)) { - LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::registerResource Resource already registered! #" << hash << " (" << getResourceDescriptor(hash).type << " : " << getResourceDescriptor(hash).status << ")"); + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::registerResource Resource already registered! #{} ({} : {})", hash, getResourceDescriptor(hash).type, getResourceDescriptor(hash).status); assert(false); return; } @@ -29,17 +29,17 @@ namespace ramses::internal void RendererResourceRegistry::unregisterResource(const ResourceContentHash& hash) { - LOG_TRACE(CONTEXT_RENDERER, "RendererResourceRegistry::unregisterResource Unregistering resource #" << hash); + LOG_TRACE(CONTEXT_RENDERER, "RendererResourceRegistry::unregisterResource Unregistering resource #{}", hash); if (!m_resources.contains(hash)) { - LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::unregisterResource Resource not registered! #" << hash); + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::unregisterResource Resource not registered! #{}", hash); assert(false); return; } const auto& rd = *m_resources.get(hash); if (!rd.sceneUsage.empty()) { - LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::unregisterResource Resource is still being referenced by one or more scenes! #" << hash); + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::unregisterResource Resource is still being referenced by one or more scenes! #{}", hash); assert(false); return; } @@ -58,10 +58,10 @@ namespace ramses::internal void RendererResourceRegistry::addResourceRef(const ResourceContentHash& hash, SceneId sceneId) { - LOG_TRACE(CONTEXT_RENDERER, "RendererResourceRegistry::addResourceRef for scene (" << sceneId << ") resource #" << hash); + LOG_TRACE(CONTEXT_RENDERER, "RendererResourceRegistry::addResourceRef for scene ({}) resource #{}", sceneId, hash); if (!m_resources.contains(hash)) { - LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::addResourceRef Resource not registered! #" << hash); + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::addResourceRef Resource not registered! #{}", hash); assert(false); return; } @@ -75,10 +75,10 @@ namespace ramses::internal void RendererResourceRegistry::removeResourceRef(const ResourceContentHash& hash, SceneId sceneId) { - LOG_TRACE(CONTEXT_RENDERER, "RendererResourceRegistry::removeResourceRef for scene (" << sceneId << ") resource #" << hash); + LOG_TRACE(CONTEXT_RENDERER, "RendererResourceRegistry::removeResourceRef for scene ({}) resource #{}", sceneId, hash); if (!m_resources.contains(hash)) { - LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::removeResourceRef Resource not registered! #" << hash); + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::removeResourceRef Resource not registered! #{}", hash); assert(false); return; } @@ -86,7 +86,7 @@ namespace ramses::internal ResourceDescriptor& rd = *m_resources.get(hash); if (!contains_c(rd.sceneUsage, sceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::removeResourceRef Resource not referenced by scene (" << sceneId << ")! #" << hash); + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::removeResourceRef Resource not referenced by scene ({})! #{}", sceneId, hash); assert(false); return; } @@ -113,7 +113,7 @@ namespace ramses::internal const auto res = m_resources.get(hash); if (res == nullptr) { - LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::getResourceDescriptor Resource not registered! #" << hash); + LOG_ERROR(CONTEXT_RENDERER, "RendererResourceRegistry::getResourceDescriptor Resource not registered! #{}", hash); assert(false); static const ResourceDescriptor DummyRD = {}; return DummyRD; @@ -167,7 +167,7 @@ namespace ramses::internal { assert(m_resources.contains(hash)); ResourceDescriptor& rd = *m_resources.get(hash); - LOG_TRACE(CONTEXT_RENDERER, "RendererResourceRegistry::setResourceStatus resource " << hash << " status change: " << rd.status << " -> " << status); + LOG_TRACE(CONTEXT_RENDERER, "RendererResourceRegistry::setResourceStatus resource {} status change: {} -> {}", hash, rd.status, status); assert(ValidateStatusChange(rd.status, status)); updateCachedLists(hash, rd.status, status); diff --git a/src/renderer/internal/RendererLib/RendererSceneControlLogic.cpp b/src/renderer/internal/RendererLib/RendererSceneControlLogic.cpp index 352068cb2..d917035bc 100644 --- a/src/renderer/internal/RendererLib/RendererSceneControlLogic.cpp +++ b/src/renderer/internal/RendererLib/RendererSceneControlLogic.cpp @@ -9,7 +9,7 @@ #include "internal/RendererLib/RendererSceneControlLogic.h" #include "internal/RendererLib/IRendererSceneStateControl.h" #include "internal/RendererLib/RendererEvent.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -98,7 +98,7 @@ namespace ramses::internal case ESceneStateInternal::Mapped: case ESceneStateInternal::MappedAndAssigned: case ESceneStateInternal::Rendered: - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating subscribe to scene with id: " << sceneId); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating subscribe to scene with id: {}", sceneId); m_sceneStateControl.handleSceneSubscriptionRequest(sceneId); sceneInfo.lastCommandWaitigForReply = ESceneStateCommand::Subscribe; break; @@ -116,13 +116,13 @@ namespace ramses::internal case ESceneStateInternal::Rendered: { assert(m_scenesInfo.count(sceneId) > 0); - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating mapping of scene " << sceneId); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating mapping of scene {}", sceneId); m_sceneStateControl.handleSceneMappingRequest(sceneId); sceneInfo.lastCommandWaitigForReply = ESceneStateCommand::Map; break; } case ESceneStateInternal::Published: - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating unsubscribe of scene with id: " << sceneId); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating unsubscribe of scene with id: {}", sceneId); m_sceneStateControl.handleSceneUnsubscriptionRequest(sceneId, false); sceneInfo.lastCommandWaitigForReply = ESceneStateCommand::Unsubscribe; break; @@ -140,7 +140,7 @@ namespace ramses::internal break; case ESceneStateInternal::Subscribed: case ESceneStateInternal::Published: - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating unmap of scene with id: " << sceneId); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating unmap of scene with id: {}", sceneId); m_sceneStateControl.handleSceneUnmappingRequest(sceneId); sceneInfo.lastCommandWaitigForReply = ESceneStateCommand::Unmap; break; @@ -154,13 +154,13 @@ namespace ramses::internal switch (targetSceneState) { case ESceneStateInternal::Rendered: - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating show of scene with id: " << sceneId); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating show of scene with id: {}", sceneId); m_sceneStateControl.handleSceneShowRequest(sceneId); sceneInfo.lastCommandWaitigForReply = ESceneStateCommand::Show; break; case ESceneStateInternal::Subscribed: case ESceneStateInternal::Published: - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating unmap of scene with id: " << sceneId); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating unmap of scene with id: {}", sceneId); m_sceneStateControl.handleSceneUnmappingRequest(sceneId); sceneInfo.lastCommandWaitigForReply = ESceneStateCommand::Unmap; break; @@ -176,7 +176,7 @@ namespace ramses::internal case ESceneStateInternal::MappedAndAssigned: case ESceneStateInternal::Subscribed: case ESceneStateInternal::Published: - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating hide of scene with id: " << sceneId); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic initiating hide of scene with id: {}", sceneId); m_sceneStateControl.handleSceneHideRequest(sceneId); sceneInfo.lastCommandWaitigForReply = ESceneStateCommand::Hide; break; @@ -211,7 +211,7 @@ namespace ramses::internal const RendererSceneState newState = GetSceneStateFromInternal(state); sceneInfo.currentState = state; - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic received scene state change: scene " << sceneId << " is in state " << EnumToString(newState) << " (internal " << int(state) << ")"); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic received scene state change: scene {} is in state {} (internal {})", sceneId, EnumToString(newState), int(state)); if (currState != newState) { LOG_INFO_F(CONTEXT_RENDERER, ([&](StringOutputStream& sos) @@ -245,7 +245,7 @@ namespace ramses::internal //another request, other than display manager, or broken state if (getLastSceneStateCommandWaitingForReply(sceneId) != ESceneStateCommand::Subscribe) { - LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received subscription event but did not ask for one, ignoring unexpected state change event for scene " << sceneId); + LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received subscription event but did not ask for one, ignoring unexpected state change event for scene {}", sceneId); return; } m_scenesInfo[sceneId].lastCommandWaitigForReply = ESceneStateCommand::None; @@ -256,7 +256,7 @@ namespace ramses::internal setCurrentSceneState(sceneId, ESceneStateInternal::Subscribed); break; case EventResult::Failed: - LOG_ERROR_P(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneSubscribed failed for scene {}, will retry.", sceneId); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneSubscribed failed for scene {}, will retry.", sceneId); break; case EventResult::Indirect: default: @@ -273,7 +273,7 @@ namespace ramses::internal { if (getLastSceneStateCommandWaitingForReply(sceneId) != ESceneStateCommand::Unsubscribe) { - LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received unsubscription event but did not ask for one, ignoring unexpected state change event for scene " << sceneId); + LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received unsubscription event but did not ask for one, ignoring unexpected state change event for scene {}", sceneId); return; } m_scenesInfo[sceneId].lastCommandWaitigForReply = ESceneStateCommand::None; @@ -289,7 +289,7 @@ namespace ramses::internal setCurrentSceneState(sceneId, ESceneStateInternal::Published); break; case EventResult::Failed: - LOG_ERROR_P(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneUnsubscribed failed for scene {}, will retry.", sceneId); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneUnsubscribed failed for scene {}, will retry.", sceneId); goToTargetState(sceneId); break; default: @@ -302,7 +302,7 @@ namespace ramses::internal //another request, other than display manager, or broken state if (getLastSceneStateCommandWaitingForReply(sceneId) != ESceneStateCommand::Map) { - LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received map event but did not ask for one, ignoring unexpected state change event for scene " << sceneId); + LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received map event but did not ask for one, ignoring unexpected state change event for scene {}", sceneId); return; } m_scenesInfo[sceneId].lastCommandWaitigForReply = ESceneStateCommand::None; @@ -313,7 +313,7 @@ namespace ramses::internal setCurrentSceneState(sceneId, ESceneStateInternal::Mapped); break; case EventResult::Failed: - LOG_ERROR_P(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneMapped failed for scene {}, will retry.", sceneId); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneMapped failed for scene {}, will retry.", sceneId); break; case EventResult::Indirect: default: @@ -330,7 +330,7 @@ namespace ramses::internal { if (getLastSceneStateCommandWaitingForReply(sceneId) != ESceneStateCommand::Unmap) { - LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received unmap event but did not ask for one, ignoring unexpected state change event for scene " << sceneId); + LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received unmap event but did not ask for one, ignoring unexpected state change event for scene {}", sceneId); return; } m_scenesInfo[sceneId].lastCommandWaitigForReply = ESceneStateCommand::None; @@ -343,7 +343,7 @@ namespace ramses::internal // after unmap, we always need to continue to unsubscribed, before we can continue to a potentially different target state if (getLastSceneStateCommandWaitingForReply(sceneId) == ESceneStateCommand::None) { - LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic continuing to unsubscribe after unmap regardless of target state of scene with id: " << sceneId); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneControlLogic continuing to unsubscribe after unmap regardless of target state of scene with id: {}", sceneId); m_sceneStateControl.handleSceneUnsubscriptionRequest(sceneId, false); SceneInfo& sceneInfo = m_scenesInfo[sceneId]; sceneInfo.lastCommandWaitigForReply = ESceneStateCommand::Unsubscribe; @@ -353,7 +353,7 @@ namespace ramses::internal setCurrentSceneState(sceneId, ESceneStateInternal::Subscribed); break; case EventResult::Failed: - LOG_ERROR_P(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneUnmapped failed for scene {}, will retry.", sceneId); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneUnmapped failed for scene {}, will retry.", sceneId); goToTargetState(sceneId); break; default: @@ -366,7 +366,7 @@ namespace ramses::internal //another request, other than display manager, or broken state if (getLastSceneStateCommandWaitingForReply(sceneId) != ESceneStateCommand::Show) { - LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received show event but did not ask for one, ignoring unexpected state change event for scene " << sceneId); + LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received show event but did not ask for one, ignoring unexpected state change event for scene {}", sceneId); return; } m_scenesInfo[sceneId].lastCommandWaitigForReply = ESceneStateCommand::None; @@ -377,7 +377,7 @@ namespace ramses::internal setCurrentSceneState(sceneId, ESceneStateInternal::Rendered); break; case EventResult::Failed: - LOG_ERROR_P(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneShown failed for scene {}, will retry.", sceneId); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneShown failed for scene {}, will retry.", sceneId); break; case EventResult::Indirect: default: @@ -394,7 +394,7 @@ namespace ramses::internal { if (getLastSceneStateCommandWaitingForReply(sceneId) != ESceneStateCommand::Hide) { - LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received hide event but did not ask for one, ignoring unexpected state change event for scene " << sceneId); + LOG_WARN(CONTEXT_RENDERER, "RendererSceneControlLogic - received hide event but did not ask for one, ignoring unexpected state change event for scene {}", sceneId); return; } m_scenesInfo[sceneId].lastCommandWaitigForReply = ESceneStateCommand::None; @@ -410,7 +410,7 @@ namespace ramses::internal setCurrentSceneState(sceneId, ESceneStateInternal::MappedAndAssigned); break; case EventResult::Failed: - LOG_ERROR_P(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneHidden failed for scene {}, will retry.", sceneId); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneControlLogic::sceneHidden failed for scene {}, will retry.", sceneId); goToTargetState(sceneId); break; default: diff --git a/src/renderer/internal/RendererLib/RendererSceneResourceRegistry.cpp b/src/renderer/internal/RendererLib/RendererSceneResourceRegistry.cpp index 9ee30ae94..221d9cda2 100644 --- a/src/renderer/internal/RendererLib/RendererSceneResourceRegistry.cpp +++ b/src/renderer/internal/RendererLib/RendererSceneResourceRegistry.cpp @@ -22,10 +22,10 @@ namespace ramses::internal assert(m_vertexArrays.size() == 0u); } - void RendererSceneResourceRegistry::addRenderBuffer(RenderBufferHandle handle, DeviceResourceHandle deviceHandle, uint32_t size, bool writeOnly) + void RendererSceneResourceRegistry::addRenderBuffer(RenderBufferHandle handle, DeviceResourceHandle deviceHandle, uint32_t size, const RenderBuffer& properties) { assert(!m_renderBuffers.contains(handle)); - m_renderBuffers.put(handle, { deviceHandle, size, writeOnly }); + m_renderBuffers.put(handle, { deviceHandle, size, properties }); } void RendererSceneResourceRegistry::removeRenderBuffer(RenderBufferHandle handle) @@ -46,6 +46,12 @@ namespace ramses::internal return m_renderBuffers.get(handle)->size; } + const RenderBuffer& RendererSceneResourceRegistry::getRenderBufferProperties(RenderBufferHandle handle) const + { + assert(m_renderBuffers.contains(handle)); + return m_renderBuffers.get(handle)->renderBufferProperties; + } + void RendererSceneResourceRegistry::getAllRenderBuffers(RenderBufferHandleVector& renderBuffers) const { assert(renderBuffers.empty()); @@ -224,14 +230,14 @@ namespace ramses::internal case ESceneResourceType_RenderBuffer_WriteOnly: for (const auto& rbEntry : m_renderBuffers) { - if(rbEntry.value.writeOnly) + if(rbEntry.value.renderBufferProperties.accessMode == ERenderBufferAccessMode::WriteOnly) result += rbEntry.value.size; } break; case ESceneResourceType_RenderBuffer_ReadWrite: for (const auto& rbEntry : m_renderBuffers) { - if (!rbEntry.value.writeOnly) + if (rbEntry.value.renderBufferProperties.accessMode == ERenderBufferAccessMode::ReadWrite) result += rbEntry.value.size; } break; diff --git a/src/renderer/internal/RendererLib/RendererSceneResourceRegistry.h b/src/renderer/internal/RendererLib/RendererSceneResourceRegistry.h index 4ee4f36ec..7ee8c00c5 100644 --- a/src/renderer/internal/RendererLib/RendererSceneResourceRegistry.h +++ b/src/renderer/internal/RendererLib/RendererSceneResourceRegistry.h @@ -14,6 +14,7 @@ #include "internal/SceneGraph/SceneAPI/TextureEnums.h" #include "internal/SceneGraph/SceneAPI/EDataBufferType.h" #include "internal/PlatformAbstraction/Collections/HashMap.h" +#include "internal/SceneGraph/SceneAPI/RenderBuffer.h" namespace ramses::internal { @@ -32,27 +33,28 @@ namespace ramses::internal RendererSceneResourceRegistry(); ~RendererSceneResourceRegistry(); - void addRenderBuffer (RenderBufferHandle handle, DeviceResourceHandle deviceHandle, uint32_t size, bool writeOnly); - void removeRenderBuffer (RenderBufferHandle handle); - [[nodiscard]] DeviceResourceHandle getRenderBufferDeviceHandle (RenderBufferHandle handle) const; - [[nodiscard]] uint32_t getRenderBufferByteSize (RenderBufferHandle handle) const; - void getAllRenderBuffers (RenderBufferHandleVector& renderBuffers) const; - - void addRenderTarget (RenderTargetHandle handle, DeviceResourceHandle deviceHandle); - void removeRenderTarget (RenderTargetHandle handle); - [[nodiscard]] DeviceResourceHandle getRenderTargetDeviceHandle (RenderTargetHandle handle) const; - void getAllRenderTargets (RenderTargetHandleVector& renderTargets) const; - - void addBlitPass (BlitPassHandle handle, DeviceResourceHandle srcRenderTargetDeviceHandle, DeviceResourceHandle dstRenderTargetDeviceHandle); - void removeBlitPass (BlitPassHandle handle); - void getBlitPassDeviceHandles (BlitPassHandle handle, DeviceResourceHandle& srcRenderTargetDeviceHandle, DeviceResourceHandle& dstRenderTargetDeviceHandle) const; - void getAllBlitPasses (BlitPassHandleVector& blitPasses) const; - - void addDataBuffer (DataBufferHandle handle, DeviceResourceHandle deviceHandle, EDataBufferType dataBufferType, uint32_t size); - void removeDataBuffer (DataBufferHandle handle); - [[nodiscard]] DeviceResourceHandle getDataBufferDeviceHandle (DataBufferHandle handle) const; - [[nodiscard]] EDataBufferType getDataBufferType (DataBufferHandle handle) const; - void getAllDataBuffers (DataBufferHandleVector& dataBuffers) const; + void addRenderBuffer (RenderBufferHandle handle, DeviceResourceHandle deviceHandle, uint32_t size, const RenderBuffer& properties); + void removeRenderBuffer (RenderBufferHandle handle); + [[nodiscard]] DeviceResourceHandle getRenderBufferDeviceHandle (RenderBufferHandle handle) const; + [[nodiscard]] uint32_t getRenderBufferByteSize (RenderBufferHandle handle) const; + [[nodiscard]] const RenderBuffer& getRenderBufferProperties (RenderBufferHandle handle) const; + void getAllRenderBuffers (RenderBufferHandleVector& renderBuffers) const; + + void addRenderTarget (RenderTargetHandle handle, DeviceResourceHandle deviceHandle); + void removeRenderTarget (RenderTargetHandle handle); + [[nodiscard]] DeviceResourceHandle getRenderTargetDeviceHandle (RenderTargetHandle handle) const; + void getAllRenderTargets (RenderTargetHandleVector& renderTargets) const; + + void addBlitPass (BlitPassHandle handle, DeviceResourceHandle srcRenderTargetDeviceHandle, DeviceResourceHandle dstRenderTargetDeviceHandle); + void removeBlitPass (BlitPassHandle handle); + void getBlitPassDeviceHandles (BlitPassHandle handle, DeviceResourceHandle& srcRenderTargetDeviceHandle, DeviceResourceHandle& dstRenderTargetDeviceHandle) const; + void getAllBlitPasses (BlitPassHandleVector& blitPasses) const; + + void addDataBuffer (DataBufferHandle handle, DeviceResourceHandle deviceHandle, EDataBufferType dataBufferType, uint32_t size); + void removeDataBuffer (DataBufferHandle handle); + [[nodiscard]] DeviceResourceHandle getDataBufferDeviceHandle (DataBufferHandle handle) const; + [[nodiscard]] EDataBufferType getDataBufferType (DataBufferHandle handle) const; + void getAllDataBuffers (DataBufferHandleVector& dataBuffers) const; void addTextureBuffer (TextureBufferHandle handle, DeviceResourceHandle deviceHandle, EPixelStorageFormat format, uint32_t size); void removeTextureBuffer (TextureBufferHandle handle); @@ -61,12 +63,12 @@ namespace ramses::internal [[nodiscard]] uint32_t getTextureBufferByteSize (TextureBufferHandle handle) const; void getAllTextureBuffers (TextureBufferHandleVector& textureBuffers) const; - void addVertexArray(RenderableHandle renderableHandle, DeviceResourceHandle deviceHandle); - void removeVertexArray(RenderableHandle renderableHandle); - [[nodiscard]] DeviceResourceHandle getVertexArrayDeviceHandle(RenderableHandle renderableHandle) const; - void getAllVertexArrayRenderables(RenderableVector& vertexArrayRenderables) const; + void addVertexArray(RenderableHandle renderableHandle, DeviceResourceHandle deviceHandle); + void removeVertexArray(RenderableHandle renderableHandle); + [[nodiscard]] DeviceResourceHandle getVertexArrayDeviceHandle(RenderableHandle renderableHandle) const; + void getAllVertexArrayRenderables(RenderableVector& vertexArrayRenderables) const; - [[nodiscard]] uint32_t getSceneResourceMemoryUsage(ESceneResourceType resourceType) const; + [[nodiscard]] uint32_t getSceneResourceMemoryUsage(ESceneResourceType resourceType) const; private: struct TextureBufferEntry @@ -80,7 +82,7 @@ namespace ramses::internal { DeviceResourceHandle deviceHandle; uint32_t size = 0u; - bool writeOnly = false; + RenderBuffer renderBufferProperties; }; struct BlitPassEntry @@ -102,7 +104,7 @@ namespace ramses::internal using DataBufferMap = HashMap; using TextureBufferMap = HashMap; using TextureSamplerMap = HashMap; - using VertexArrayMap = HashMap; + using VertexArrayMap = HashMap; RenderBufferMap m_renderBuffers; RenderTargetMap m_renderTargets; diff --git a/src/renderer/internal/RendererLib/RendererSceneUpdater.cpp b/src/renderer/internal/RendererLib/RendererSceneUpdater.cpp index 6f8d13fef..10bbcad68 100644 --- a/src/renderer/internal/RendererLib/RendererSceneUpdater.cpp +++ b/src/renderer/internal/RendererLib/RendererSceneUpdater.cpp @@ -29,14 +29,14 @@ #include "internal/RendererLib/SceneReferenceLogic.h" #include "internal/RendererLib/ResourceUploader.h" #include "internal/RendererLib/RendererEventCollector.h" +#include "internal/RendererLib/SceneResourceUploader.h" #include "internal/Components/FlushTimeInformation.h" #include "internal/Components/SceneUpdate.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/Image.h" #include "internal/PlatformAbstraction/PlatformTime.h" #include "internal/PlatformAbstraction/Macros.h" #include -#include "internal/RendererLib/SceneResourceUploader.h" namespace ramses::internal { @@ -80,7 +80,7 @@ namespace ramses::internal { ESceneState sceneState = m_sceneStateExecutor.getSceneState(sceneId); - LOG_TRACE_P(CONTEXT_RENDERER, "RendererSceneUpdater::handleSceneUpdate: for sceneId {}, flushCounter {}, sceneState {}", + LOG_TRACE(CONTEXT_RENDERER, "RendererSceneUpdater::handleSceneUpdate: for sceneId {}, flushCounter {}, sceneState {}", sceneId, sceneUpdate.flushInfos.flushCounter, EnumToString(sceneState)); if (sceneState == ESceneState::SubscriptionPending) @@ -100,7 +100,7 @@ namespace ramses::internal } else { - LOG_ERROR_P(CONTEXT_RENDERER, "RendererSceneUpdater::handleSceneActions could not apply scene actions because scene {} is neither subscribed nor mapped", sceneId); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleSceneActions could not apply scene actions because scene {} is neither subscribed nor mapped", sceneId); } } @@ -117,7 +117,7 @@ namespace ramses::internal IRenderBackend& renderBackend = displayController.getRenderBackend(); IEmbeddedCompositingManager& embeddedCompositingManager = displayController.getEmbeddedCompositingManager(); - m_asyncEffectUploader = std::make_unique(m_platform, renderBackend, m_notifier, static_cast(m_display.asMemoryHandle())); + m_asyncEffectUploader = std::make_unique(m_platform, renderBackend, m_notifier, m_display); if (!m_asyncEffectUploader->createResourceUploadRenderBackendAndStartThread()) { m_renderer.destroyDisplayContext(); @@ -132,7 +132,7 @@ namespace ramses::internal m_rendererEventCollector.addDisplayEvent(ERendererEventType::DisplayCreated, m_display); - LOG_INFO_P(CONTEXT_RENDERER, "Created display: {}x{}{} MSAA{}", + LOG_INFO(CONTEXT_RENDERER, "Created display: {}x{}{} MSAA{}", displayController.getDisplayWidth(), displayController.getDisplayHeight(), (displayConfig.getFullscreenState() ? " fullscreen" : ""), displayConfig.getAntialiasingSampleCount()); } @@ -295,15 +295,15 @@ namespace ramses::internal void RendererSceneUpdater::logTooManyFlushesAndUnsubscribeIfRemoteScene(SceneId sceneId, std::size_t numPendingFlushes) { - LOG_ERROR(CONTEXT_RENDERER, "Scene " << sceneId << " has " << numPendingFlushes << " pending flushes," - << " force applying pending flushes seems to have been interrupted too often and the renderer has no way to catch up without potentially blocking other scenes." - << " Possible causes: too many flushes queued and couldn't be applied (even force-applied); or renderer thread was stopped or stalled," - << " e.g. because of taking screenshots, and couldn't process the flushes."); + LOG_ERROR(CONTEXT_RENDERER, "Scene {} has {} pending flushes," + " force applying pending flushes seems to have been interrupted too often and the renderer has no way to catch up without potentially blocking other scenes." + " Possible causes: too many flushes queued and couldn't be applied (even force-applied); or renderer thread was stopped or stalled," + " e.g. because of taking screenshots, and couldn't process the flushes.", sceneId, numPendingFlushes); if (m_sceneStateExecutor.getScenePublicationMode(sceneId) != EScenePublicationMode::LocalOnly) { - LOG_ERROR(CONTEXT_RENDERER, "Force unsubscribing scene " << sceneId << " to avoid risk of running out of memory!" - << " Any incoming data for the scene will be ignored till the scene is re-subscribed."); + LOG_ERROR(CONTEXT_RENDERER, "Force unsubscribing scene {} to avoid risk of running out of memory!" + " Any incoming data for the scene will be ignored till the scene is re-subscribed.", sceneId); // Unsubscribe scene as 'indirect' because it is not triggered by user handleSceneUnsubscriptionRequest(sceneId, true); } @@ -312,7 +312,7 @@ namespace ramses::internal // Don't force-ubsubscribe local scenes // Local client is responsible for his own scene - should not spam the renderer with flushes, or if he does // and renderer goes out of memory -> it is possible to fix on client side in the local case - LOG_ERROR(CONTEXT_RENDERER, "Because scene " << sceneId << " is a local scene, it will not be forcefully ubsubscribed. Beware of possible out-of-memory errors!"); + LOG_ERROR(CONTEXT_RENDERER, "Because scene {} is a local scene, it will not be forcefully ubsubscribed. Beware of possible out-of-memory errors!", sceneId); } } @@ -365,7 +365,7 @@ namespace ramses::internal })); if (!sceneUpdate.flushInfos.resourceChanges.empty()) { - LOG_TRACE(CONTEXT_RENDERER, sceneUpdate.flushInfos.resourceChanges); + LOG_TRACE(CONTEXT_RENDERER, ::fmt::to_string(sceneUpdate.flushInfos.resourceChanges)); } PendingSceneResourcesUtils::ConsolidateSceneResourceActions(resourceChanges.m_sceneResourceActions, pendingData.sceneResourceActions); @@ -544,7 +544,7 @@ namespace ramses::internal const auto numPendingFlushes = getNumberOfPendingNonEmptyFlushes(sceneID); if (numPendingFlushes > m_maximumPendingFlushes) { - LOG_ERROR(CONTEXT_RENDERER, "Force applying pending flushes! Scene " << sceneID << " has " << numPendingFlushes << " pending flushes, renderer cannot catch up with resource updates."); + LOG_ERROR(CONTEXT_RENDERER, "Force applying pending flushes! Scene {} has {} pending flushes, renderer cannot catch up with resource updates.", sceneID, numPendingFlushes); logMissingResources(stagingInfo.pendingData, sceneID); canApplyFlushes = true; @@ -576,7 +576,7 @@ namespace ramses::internal rendererScene.setActiveShaderAnimation(false); if (pendingFlush.timeInfo.isEffectTimeSync) { - LOG_INFO_P(CONTEXT_RENDERER, "EffectTimeSync: {} for scene: {}", + LOG_INFO(CONTEXT_RENDERER, "EffectTimeSync: {} for scene: {}", std::chrono::time_point_cast(pendingFlush.timeInfo.internalTimestamp).time_since_epoch().count(), rendererScene.getSceneId()); rendererScene.setEffectTimeSync(pendingFlush.timeInfo.internalTimestamp); @@ -585,8 +585,7 @@ namespace ramses::internal if (pendingFlush.versionTag.isValid()) { - LOG_DEBUG(CONTEXT_SMOKETEST, "Named flush applied on scene " << rendererScene.getSceneId() << - " with sceneVersionTag " << pendingFlush.versionTag); + LOG_DEBUG(CONTEXT_SMOKETEST, "Named flush applied on scene {} with sceneVersionTag {}", rendererScene.getSceneId(), pendingFlush.versionTag); m_rendererEventCollector.addSceneFlushEvent(ERendererEventType::SceneFlushed, sceneID, pendingFlush.versionTag); } stagingInfo.lastAppliedVersionTag = pendingFlush.versionTag; @@ -788,8 +787,8 @@ namespace ramses::internal // mapping a scene needs re-request of all its resources at the new resource manager if (!markClientAndSceneResourcesForReupload(sceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "Failed to upload all scene resources within time budget (" << m_frameTimer.getTimeBudgetForSection(EFrameTimerSectionBudget::SceneResourcesUpload).count() << " us)." - << " Reduce amount of scene resources or use client resources instead! Scene " << sceneId << " will be force unsubscribed!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed to upload all scene resources within time budget ({} us). Reduce amount of scene resources or use client resources instead! Scene {} will be force unsubscribed!", + m_frameTimer.getTimeBudgetForSection(EFrameTimerSectionBudget::SceneResourcesUpload).count(), sceneId); scenesToForceUnsubscribe.push_back(sceneId); } } @@ -837,7 +836,7 @@ namespace ramses::internal const auto& pendingFlushes = m_rendererScenes.getStagingInfo(sceneId).pendingData.pendingFlushes; if (!pendingFlushes.empty()) { - LOG_ERROR(CONTEXT_RENDERER, "Scene " << sceneId << " - expected no pending flushes at this point"); + LOG_ERROR(CONTEXT_RENDERER, "Scene {} - expected no pending flushes at this point", sceneId); assert(pendingFlushes.size() > m_maximumPendingFlushes); } } @@ -897,7 +896,7 @@ namespace ramses::internal const auto numPendingFlushes = getNumberOfPendingNonEmptyFlushes(sceneId); if (numPendingFlushes > m_maximumPendingFlushes) { - LOG_ERROR(CONTEXT_RENDERER, "Force mapping scene " << sceneId << " due to " << numPendingFlushes << " pending flushes, renderer cannot catch up with resource updates."); + LOG_ERROR(CONTEXT_RENDERER, "Force mapping scene {} due to {} pending flushes, renderer cannot catch up with resource updates.", sceneId, numPendingFlushes); const auto usedResources = m_displayResourceManager->getResourcesInUseByScene(sceneId); if (usedResources) logMissingResources(*usedResources, sceneId); @@ -911,8 +910,8 @@ namespace ramses::internal // Scene might already have broken resources in it before mapping and then new flushes won't be blocked // therefore this additional time-based criteria for force mapping. // It is still error but it is not necessary to block on it forever. - LOG_ERROR(CONTEXT_RENDERER, "Force mapping scene " << sceneId << " due to " << totalWaitingTime.count() - << " ms waiting time to be mapped, renderer cannot catch up with resource updates or scene has broken resources."); + LOG_ERROR(CONTEXT_RENDERER, "Force mapping scene {} due to {} ms waiting time to be mapped, renderer cannot catch up with resource updates or scene has broken resources.", + sceneId, totalWaitingTime.count()); return true; } @@ -923,11 +922,11 @@ namespace ramses::internal { const SceneActionCollection& actionsForScene = flushInfo.sceneActions; const uint32_t numActions = actionsForScene.numberOfActions(); - LOG_TRACE(CONTEXT_PROFILING, " RendererSceneUpdater::applySceneActions start applying scene actions [count:" << numActions << "] for scene with id " << scene.getSceneId()); + LOG_TRACE(CONTEXT_PROFILING, " RendererSceneUpdater::applySceneActions start applying scene actions [count:{}] for scene with id {}", numActions, scene.getSceneId()); SceneActionApplier::ApplyActionsOnScene(scene, actionsForScene); - LOG_TRACE(CONTEXT_PROFILING, " RendererSceneUpdater::applySceneActions finished applying scene actions for scene with id " << scene.getSceneId()); + LOG_TRACE(CONTEXT_PROFILING, " RendererSceneUpdater::applySceneActions finished applying scene actions for scene with id {}", scene.getSceneId()); } void RendererSceneUpdater::destroyScene(SceneId sceneID) @@ -991,7 +990,7 @@ namespace ramses::internal if (!sceneResourceActions.empty()) { if (sceneResourcesByteSize > 0u) - LOG_INFO(CONTEXT_RENDERER, "Applying scene resources gathered from scene " << sceneId << ", " << sceneResourceActions.size() << " actions, " << sceneResourcesByteSize << " bytes"); + LOG_INFO(CONTEXT_RENDERER, "Applying scene resources gathered from scene {}, {} actions, {} bytes", sceneId, sceneResourceActions.size(), sceneResourcesByteSize); // enable time measuring and interrupting of upload only if scene is remote const bool sceneIsRemote = (m_sceneStateExecutor.getScenePublicationMode(sceneId) != EScenePublicationMode::LocalOnly); @@ -1004,7 +1003,7 @@ namespace ramses::internal ResourceUtils::GetAllResourcesFromScene(resourcesUsedInScene, scene); if (!resourcesUsedInScene.empty()) { - LOG_INFO(CONTEXT_RENDERER, "Marking " << resourcesUsedInScene.size() << " client resources as used by scene " << sceneId); + LOG_INFO(CONTEXT_RENDERER, "Marking {} client resources as used by scene {}", resourcesUsedInScene.size(), sceneId); // compare actual 'in-use' list with 'to be uploaded for mapping' list // the only case these do not contain same elements is re-map case (other than first mapping) @@ -1023,10 +1022,10 @@ namespace ramses::internal ResourceContentHashVector resourcesToReference; std::set_difference(resourcesUsedInScene.cbegin(), resourcesUsedInScene.cend(), providedHashes.cbegin(), providedHashes.cend(), std::back_inserter(resourcesToReference)); resourceManager.referenceResourcesForScene(sceneId, resourcesToReference); - LOG_INFO_P(CONTEXT_RENDERER, "Out of {} resources used in scene {} there are {} resources that are not ready to be provided and uploaded unless already cached.", resourcesUsedInScene.size(), sceneId, resourcesToReference.size()); + LOG_INFO(CONTEXT_RENDERER, "Out of {} resources used in scene {} there are {} resources that are not ready to be provided and uploaded unless already cached.", resourcesUsedInScene.size(), sceneId, resourcesToReference.size()); } else - LOG_INFO_P(CONTEXT_RENDERER, "All resources used in scene {} are ready to be provided and uploaded.", sceneId); + LOG_INFO(CONTEXT_RENDERER, "All resources used in scene {} are ready to be provided and uploaded.", sceneId); } return true; @@ -1162,7 +1161,7 @@ namespace ramses::internal IRendererResourceManager& resourceManager = *m_displayResourceManager; if (resourceManager.getOffscreenBufferDeviceHandle(buffer).isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleBufferCreateRequest an offscreen buffer with the same ID (" << buffer << ") already exists!"); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleBufferCreateRequest an offscreen buffer with the same ID ({}) already exists!", buffer); } else { @@ -1171,7 +1170,7 @@ namespace ramses::internal m_renderer.resetRenderInterruptState(); m_renderer.registerOffscreenBuffer(deviceHandle, width, height, isDoubleBuffered); - LOG_INFO_P(CONTEXT_RENDERER, "Created offscreen buffer {} (device handle {}): {}x{} {}", buffer, deviceHandle, width, height, (isDoubleBuffered ? " interruptible" : "")); + LOG_INFO(CONTEXT_RENDERER, "Created offscreen buffer {} (device handle {}): {}x{} {}", buffer, deviceHandle, width, height, (isDoubleBuffered ? " interruptible" : "")); success = true; } } @@ -1196,7 +1195,7 @@ namespace ramses::internal IRendererResourceManager& resourceManager = *m_displayResourceManager; if (resourceManager.getOffscreenBufferDeviceHandle(buffer).isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleDmaBufferCreateRequest an offscreen buffer with the same ID (" << buffer << ") already exists!"); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleDmaBufferCreateRequest an offscreen buffer with the same ID ({}) already exists!", buffer); } else { @@ -1205,7 +1204,7 @@ namespace ramses::internal m_renderer.resetRenderInterruptState(); m_renderer.registerOffscreenBuffer(deviceHandle, width, height, false); - LOG_INFO_P(CONTEXT_RENDERER, "Created DMA offscreen buffer {} (device handle {}): {}x{}", buffer, deviceHandle, width, height); + LOG_INFO(CONTEXT_RENDERER, "Created DMA offscreen buffer {} (device handle {}): {}x{}", buffer, deviceHandle, width, height); dmaBufferFD = resourceManager.getDmaOffscreenBufferFD(buffer); dmaBufferStride = resourceManager.getDmaOffscreenBufferStride(buffer); success = true; @@ -1230,7 +1229,7 @@ namespace ramses::internal const auto bufferDeviceHandle = resourceManager.getOffscreenBufferDeviceHandle(buffer); if (!bufferDeviceHandle.isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleBufferDestroyRequest could not find buffer with ID " << buffer); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleBufferDestroyRequest could not find buffer with ID {}", buffer); return false; } @@ -1240,7 +1239,7 @@ namespace ramses::internal const auto sceneDisplayBuffer = m_renderer.getBufferSceneIsAssignedTo(sceneId); if (sceneDisplayBuffer == bufferDeviceHandle) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleBufferDestroyRequest cannot destroy buffer " << buffer << ", there is one or more scenes assigned to it, unmap or reassign them first."); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleBufferDestroyRequest cannot destroy buffer {}, there is one or more scenes assigned to it, unmap or reassign them first.", buffer); return false; } } @@ -1269,14 +1268,14 @@ namespace ramses::internal if (deviceHandle.isValid()) { const uint32_t glTexId = resourceManager.getExternalBufferGlId(buffer); - LOG_INFO_P(CONTEXT_RENDERER, "Created external buffer {} (device handle {}, GL id: {})", buffer, deviceHandle, glTexId); + LOG_INFO(CONTEXT_RENDERER, "Created external buffer {} (device handle {}, GL id: {})", buffer, deviceHandle, glTexId); m_rendererEventCollector.addExternalBufferEvent(ERendererEventType::ExternalBufferCreated, m_display, buffer, glTexId); return true; } } - LOG_ERROR_P(CONTEXT_RENDERER, "Failed creating external buffer {}", buffer); + LOG_ERROR(CONTEXT_RENDERER, "Failed creating external buffer {}", buffer); m_rendererEventCollector.addExternalBufferEvent(ERendererEventType::ExternalBufferCreateFailed, m_display, buffer, 0u); return false; @@ -1295,7 +1294,7 @@ namespace ramses::internal const auto bufferDeviceHandle = resourceManager.getExternalBufferDeviceHandle(buffer); if (!bufferDeviceHandle.isValid()) { - LOG_ERROR_P(CONTEXT_RENDERER, "RendererSceneUpdater::handleExternalBufferDestroyRequest could not find external buffer {}", buffer); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleExternalBufferDestroyRequest could not find external buffer {}", buffer); } else { @@ -1324,14 +1323,14 @@ namespace ramses::internal IRendererResourceManager& resourceManager = *m_displayResourceManager; if (resourceManager.getStreamBufferDeviceHandle(buffer).isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleBufferCreateRequest a stream buffer with the same ID (" << buffer << ") already exists!"); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleBufferCreateRequest a stream buffer with the same ID ({}) already exists!", buffer); return false; } resourceManager.uploadStreamBuffer(buffer, source); const DeviceResourceHandle deviceHandle = resourceManager.getStreamBufferDeviceHandle(buffer); - LOG_INFO(CONTEXT_RENDERER, "Created stream buffer " << buffer << " (device handle " << deviceHandle << ")"); + LOG_INFO(CONTEXT_RENDERER, "Created stream buffer {} (device handle {})", buffer, deviceHandle); return true; } @@ -1348,7 +1347,7 @@ namespace ramses::internal IRendererResourceManager& resourceManager = *m_displayResourceManager; if (!resourceManager.getStreamBufferDeviceHandle(buffer).isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleBufferDestroyRequest could not find stream buffer with ID " << buffer); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleBufferDestroyRequest could not find stream buffer with ID {}", buffer); return false; } @@ -1372,7 +1371,7 @@ namespace ramses::internal bufferDeviceHandle = m_displayResourceManager->getOffscreenBufferDeviceHandle(buffer); if (!bufferDeviceHandle.isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleSetClearEnabled cannot enable/disable clear for unknown offscreen buffer " << buffer); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleSetClearEnabled cannot enable/disable clear for unknown offscreen buffer {}", buffer); return; } } @@ -1397,7 +1396,7 @@ namespace ramses::internal bufferDeviceHandle = m_displayResourceManager->getOffscreenBufferDeviceHandle(buffer); if (!bufferDeviceHandle.isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleSetClearColor cannot set clear color for unknown offscreen buffer " << buffer); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleSetClearColor cannot set clear color for unknown offscreen buffer {}", buffer); return; } } @@ -1456,7 +1455,7 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::readPixels failed, requested buffer does not exist : " << buffer << " !"); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::readPixels failed, requested buffer does not exist : {} !", buffer); readPixelsFailed = true; } } @@ -1477,7 +1476,7 @@ namespace ramses::internal { if (!m_renderer.hasDisplayController() || !m_rendererScenes.hasScene(sceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleSceneDisplayBufferAssignmentRequest cannot assign scene " << sceneId << " to a display buffer, display invalid or scene is not mapped."); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleSceneDisplayBufferAssignmentRequest cannot assign scene {} to a display buffer, display invalid or scene is not mapped.", sceneId); return false; } @@ -1487,7 +1486,7 @@ namespace ramses::internal const DeviceResourceHandle bufferDeviceHandle = (buffer.isValid() ? resourceManager.getOffscreenBufferDeviceHandle(buffer) : m_renderer.getDisplayController().getDisplayBuffer()); if (!bufferDeviceHandle.isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleSceneDisplayBufferAssignmentRequest cannot assign scene to render buffer, buffer " << buffer << " not found on this display."); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handleSceneDisplayBufferAssignmentRequest cannot assign scene to render buffer, buffer {} not found on this display.", buffer); return false; } @@ -1511,7 +1510,7 @@ namespace ramses::internal { if (m_sceneStateExecutor.getSceneState(providerSceneId) < ESceneState::Mapped) { - LOG_ERROR(CONTEXT_RENDERER, "Renderer::createDataLink failed: provider scene providing a texture must be fully mapped before linking! (Provider scene: " << providerSceneId << ") (Consumer scene: " << consumerSceneId << ")"); + LOG_ERROR(CONTEXT_RENDERER, "Renderer::createDataLink failed: provider scene providing a texture must be fully mapped before linking! (Provider scene: {}) (Consumer scene: {})", providerSceneId, consumerSceneId); m_rendererEventCollector.addDataLinkEvent(ERendererEventType::SceneDataLinkFailed, providerSceneId, consumerSceneId, providerId, consumerId); return; } @@ -1528,7 +1527,7 @@ namespace ramses::internal { if (!m_renderer.hasDisplayController() || !m_rendererScenes.hasScene(consumerSceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "Link offscreen buffer to consumer scene " << consumerSceneId << " failed, invalid display or scene not mapped."); + LOG_ERROR(CONTEXT_RENDERER, "Link offscreen buffer to consumer scene {} failed, invalid display or scene not mapped.", consumerSceneId); m_rendererEventCollector.addBufferEvent(ERendererEventType::SceneDataBufferLinkFailed, buffer, consumerSceneId, consumerId); return; } @@ -1537,7 +1536,7 @@ namespace ramses::internal const IRendererResourceManager& resourceManager = *m_displayResourceManager; if (!resourceManager.getOffscreenBufferDeviceHandle(buffer).isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "Link offscreen buffer failed: offscreen buffer " << buffer << " has to exist on the same display where the consumer scene " << consumerSceneId << " is mapped!"); + LOG_ERROR(CONTEXT_RENDERER, "Link offscreen buffer failed: offscreen buffer {} has to exist on the same display where the consumer scene {} is mapped!", buffer, consumerSceneId); m_rendererEventCollector.addBufferEvent(ERendererEventType::SceneDataBufferLinkFailed, buffer, consumerSceneId, consumerId); return; } @@ -1551,7 +1550,7 @@ namespace ramses::internal { if (!m_renderer.hasDisplayController() || !m_rendererScenes.hasScene(consumerSceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "Link stream buffer to consumer scene " << consumerSceneId << " failed, invalid display or scene not mapped."); + LOG_ERROR(CONTEXT_RENDERER, "Link stream buffer to consumer scene {} failed, invalid display or scene not mapped.", consumerSceneId); m_rendererEventCollector.addBufferEvent(ERendererEventType::SceneDataBufferLinkFailed, buffer, consumerSceneId, consumerId); return; } @@ -1565,7 +1564,7 @@ namespace ramses::internal { if (!m_renderer.hasDisplayController() || !m_rendererScenes.hasScene(consumerSceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "Link external buffer to consumer scene " << consumerSceneId << " failed, invalid display or scene not mapped."); + LOG_ERROR(CONTEXT_RENDERER, "Link external buffer to consumer scene {} failed, invalid display or scene not mapped.", consumerSceneId); m_rendererEventCollector.addBufferEvent(ERendererEventType::SceneDataBufferLinkFailed, buffer, consumerSceneId, consumerId); return; } @@ -1574,7 +1573,7 @@ namespace ramses::internal const IRendererResourceManager& resourceManager = *m_displayResourceManager; if (!resourceManager.getExternalBufferDeviceHandle(buffer).isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "Link external buffer failed: external buffer " << buffer << " has to exist on the same display where the consumer scene " << consumerSceneId << " is mapped!"); + LOG_ERROR(CONTEXT_RENDERER, "Link external buffer failed: external buffer {} has to exist on the same display where the consumer scene {} is mapped!", buffer, consumerSceneId); m_rendererEventCollector.addBufferEvent(ERendererEventType::SceneDataBufferLinkFailed, buffer, consumerSceneId, consumerId); return; } @@ -1596,7 +1595,7 @@ namespace ramses::internal const auto bufferHandle = m_renderer.getBufferSceneIsAssignedTo(sceneId); if (!m_rendererScenes.hasScene(sceneId) || !bufferHandle.isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handlePickEvent could not process pick event for scene " << sceneId << " which is not assigned to any display buffer."); + LOG_ERROR(CONTEXT_RENDERER, "RendererSceneUpdater::handlePickEvent could not process pick event for scene {} which is not assigned to any display buffer.", sceneId); return; } @@ -1630,9 +1629,9 @@ namespace ramses::internal m_maximumPendingFlushesToKillScene = limitForPendingFlushesForceUnsubscribe; } - void RendererSceneUpdater::logRendererInfo(ERendererLogTopic topic, bool verbose, NodeHandle nodeFilter) const + void RendererSceneUpdater::logRendererInfo(const RendererCommand::LogInfo& cmd) const { - RendererLogger::LogTopic(*this, topic, verbose, nodeFilter); + RendererLogger::LogTopic(*this, cmd); } void RendererSceneUpdater::setSkippingOfUnmodifiedScenes(bool enable) @@ -1864,16 +1863,16 @@ namespace ramses::internal // is converted to layout normally used in image files (top-down) const Image bitmap(screenshot.rectangle.width, screenshot.rectangle.height, screenshot.pixelData.cbegin(), screenshot.pixelData.cend(), true); bitmap.saveToFilePNG(screenshot.filename); - LOG_INFO(CONTEXT_RENDERER, "RendererSceneUpdater::processScreenshotResults: screenshot successfully saved to file: " << screenshot.filename); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneUpdater::processScreenshotResults: screenshot successfully saved to file: {}", screenshot.filename); if (screenshot.sendViaDLT) { if (GetRamsesLogger().transmitFile(screenshot.filename, false)) { - LOG_INFO(CONTEXT_RENDERER, "RendererSceneUpdater::processScreenshotResults: started dlt file transfer: " << screenshot.filename); + LOG_INFO(CONTEXT_RENDERER, "RendererSceneUpdater::processScreenshotResults: started dlt file transfer: {}", screenshot.filename); } else { - LOG_WARN(CONTEXT_RENDERER, "RendererSceneUpdater::processScreenshotResults: screenshot file could not send via dlt: " << screenshot.filename); + LOG_WARN(CONTEXT_RENDERER, "RendererSceneUpdater::processScreenshotResults: screenshot file could not send via dlt: {}", screenshot.filename); } } } diff --git a/src/renderer/internal/RendererLib/RendererSceneUpdater.h b/src/renderer/internal/RendererLib/RendererSceneUpdater.h index fb3e2cbea..41f46eb7a 100644 --- a/src/renderer/internal/RendererLib/RendererSceneUpdater.h +++ b/src/renderer/internal/RendererLib/RendererSceneUpdater.h @@ -84,7 +84,7 @@ namespace ramses::internal void setLimitFlushesForceApply(size_t limitForPendingFlushesForceApply) override; void setLimitFlushesForceUnsubscribe(size_t limitForPendingFlushesForceUnsubscribe) override; void setSkippingOfUnmodifiedScenes(bool enable) override; - void logRendererInfo(ERendererLogTopic topic, bool verbose, NodeHandle nodeFilter) const override; + void logRendererInfo(const RendererCommand::LogInfo& cmd) const override; // IRendererSceneStateControl void handleSceneSubscriptionRequest (SceneId sceneId) override; diff --git a/src/renderer/internal/RendererLib/RendererStatistics.cpp b/src/renderer/internal/RendererLib/RendererStatistics.cpp index f7e3f0fae..ec4dd790e 100644 --- a/src/renderer/internal/RendererLib/RendererStatistics.cpp +++ b/src/renderer/internal/RendererLib/RendererStatistics.cpp @@ -23,7 +23,7 @@ namespace ramses::internal uint32_t RendererStatistics::getDrawCallsPerFrame() const { - return m_frameNumber <= 0 ? 0u : m_drawCalls / m_frameNumber; + return m_frameNumber <= 0 ? 0u : std::lround(static_cast(m_drawCalls.sum) / static_cast(m_frameNumber)); } void RendererStatistics::sceneRendered(SceneId sceneId) @@ -182,7 +182,7 @@ namespace ramses::internal } m_frameNumber++; - m_drawCalls += drawCalls; + m_drawCalls.update(drawCalls); m_lastFrameTick = currTick; } @@ -199,7 +199,7 @@ namespace ramses::internal { m_timeBase = PlatformTime::GetMillisecondsMonotonic(); m_frameNumber = 0; - m_drawCalls = 0u; + m_drawCalls.reset(); m_frameDurationMin = std::numeric_limits::max(); m_frameDurationMax = 0u; m_resourcesUploaded = 0u; @@ -261,7 +261,7 @@ namespace ramses::internal str << "Avg framerate: " << getFps() << " FPS" " [minFrameTime " << m_frameDurationMin << "us" << ", maxFrameTime " << m_frameDurationMax << "us]" << - ", drawcallsPerFrame " << getDrawCallsPerFrame() << + ", drawCalls (" << m_drawCalls.minValue << "/" << m_drawCalls.maxValue << "/" << getDrawCallsPerFrame() << ")" << ", numFrames " << m_frameNumber; if (m_resourcesUploaded > 0u) str << ", resUploaded " << m_resourcesUploaded << " (" << m_resourcesBytesUploaded << " B)"; diff --git a/src/renderer/internal/RendererLib/RendererStatistics.h b/src/renderer/internal/RendererLib/RendererStatistics.h index 7b2b4a9e9..127e7218c 100644 --- a/src/renderer/internal/RendererLib/RendererStatistics.h +++ b/src/renderer/internal/RendererLib/RendererStatistics.h @@ -58,7 +58,7 @@ namespace ramses::internal private: int32_t m_frameNumber = 0; uint64_t m_timeBase = PlatformTime::GetMillisecondsMonotonic(); - uint32_t m_drawCalls = 0u; + SummaryEntry m_drawCalls; uint64_t m_lastFrameTick = 0u; uint32_t m_frameDurationMin = std::numeric_limits::max(); uint32_t m_frameDurationMax = 0u; diff --git a/src/renderer/internal/RendererLib/ResourceCachedScene.cpp b/src/renderer/internal/RendererLib/ResourceCachedScene.cpp index a1911dfce..16f2b7673 100644 --- a/src/renderer/internal/RendererLib/ResourceCachedScene.cpp +++ b/src/renderer/internal/RendererLib/ResourceCachedScene.cpp @@ -9,7 +9,7 @@ #include "internal/RendererLib/ResourceCachedScene.h" #include "internal/RendererLib/IResourceDeviceHandleAccessor.h" #include "internal/RendererLib/TextureLinkCachedScene.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { diff --git a/src/renderer/internal/RendererLib/ResourceUploader.cpp b/src/renderer/internal/RendererLib/ResourceUploader.cpp index 5ce89fc3e..2d67b4c5d 100644 --- a/src/renderer/internal/RendererLib/ResourceUploader.cpp +++ b/src/renderer/internal/RendererLib/ResourceUploader.cpp @@ -14,7 +14,7 @@ #include "internal/RendererLib/PlatformInterface/IBinaryShaderCache.h" #include "internal/RendererLib/PlatformInterface/IDevice.h" #include "internal/RendererLib/PlatformInterface/IRenderBackend.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/TextureMathUtils.h" #include "internal/Components/ManagedResource.h" #include "internal/RendererLib/ResourceDescriptor.h" @@ -167,7 +167,7 @@ namespace ramses::internal DeviceResourceHandle ResourceUploader::queryBinaryShaderCache(IRenderBackend& renderBackend, const EffectResource& effect, ResourceContentHash hash) { - LOG_TRACE(CONTEXT_RENDERER, "ResourceUploader::queryBinaryShaderCacheAndUploadEffect: effectid:" << effect.getHash()); + LOG_TRACE(CONTEXT_RENDERER, "ResourceUploader::queryBinaryShaderCacheAndUploadEffect: effectid:{}", effect.getHash()); IDevice& device = renderBackend.getDevice(); if (!m_binaryShaderCache) @@ -219,7 +219,7 @@ namespace ramses::internal m_binaryShaderCache->storeBinaryShader(hash, sceneid, &binaryShader.front(), static_cast(binaryShader.size()), format); } else - LOG_WARN_P(CONTEXT_RENDERER, "ResourceUploader::storeShaderInBinaryShaderCache: failed to retrieve binary shader from device, shader cannot be stored in cache (deviceHandle={} hash={} sceneId={})", deviceHandle, hash, sceneid); + LOG_WARN(CONTEXT_RENDERER, "ResourceUploader::storeShaderInBinaryShaderCache: failed to retrieve binary shader from device, shader cannot be stored in cache (deviceHandle={} hash={} sceneId={})", deviceHandle, hash, sceneid); } } diff --git a/src/renderer/internal/RendererLib/ResourceUploadingManager.cpp b/src/renderer/internal/RendererLib/ResourceUploadingManager.cpp index 26a4159d0..9c1bdc724 100644 --- a/src/renderer/internal/RendererLib/ResourceUploadingManager.cpp +++ b/src/renderer/internal/RendererLib/ResourceUploadingManager.cpp @@ -15,7 +15,7 @@ #include "internal/RendererLib/PlatformInterface/IRenderBackend.h" #include "internal/RendererLib/PlatformInterface/IEmbeddedCompositingManager.h" #include "internal/RendererLib/PlatformInterface/IDevice.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/PlatformAbstraction/PlatformTime.h" #include "internal/SceneGraph/Resource/EffectResource.h" #include @@ -101,7 +101,7 @@ namespace ramses::internal const auto& hash = e.first; if (!m_resources.containsResource(hash)) { - LOG_ERROR(CONTEXT_RENDERER, "ResourceUploadingManager::syncEffects unexpected effect uploaded, will be ignored because it does not exist in resource registry #" << hash); + LOG_ERROR(CONTEXT_RENDERER, "ResourceUploadingManager::syncEffects unexpected effect uploaded, will be ignored because it does not exist in resource registry #{}", hash); assert(false); continue; } @@ -109,7 +109,7 @@ namespace ramses::internal const auto resourceStatus = m_resources.getResourceStatus(hash); if (resourceStatus != EResourceStatus::ScheduledForUpload) { - LOG_ERROR(CONTEXT_RENDERER, "ResourceUploadingManager::syncEffects unexpected effect uploaded, will be ignored because is not in state scheduled for upload #" << hash << " (status :" << resourceStatus << ")"); + LOG_ERROR(CONTEXT_RENDERER, "ResourceUploadingManager::syncEffects unexpected effect uploaded, will be ignored because is not in state scheduled for upload #{} (status :{})", hash, resourceStatus); assert(false); continue; } @@ -128,7 +128,7 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "ResourceUploadingManager::syncEffects failed to upload effect #" << hash); + LOG_ERROR(CONTEXT_RENDERER, "ResourceUploadingManager::syncEffects failed to upload effect #{}", hash); m_resources.setResourceBroken(hash); } } @@ -154,8 +154,8 @@ namespace ramses::internal { const auto numUploaded = i + 1; const auto numRemaining = resourcesToUpload.size() - numUploaded; - LOG_INFO(CONTEXT_RENDERER, "ResourceUploadingManager::uploadResources: Interrupt: Exceeded time for resource upload (uploaded " << numUploaded << " resources of size " << sizeUploaded - << " B, remaining " << numRemaining << " resources to upload). dt " << sectionDuration.count() << "ms"); + LOG_INFO(CONTEXT_RENDERER, "ResourceUploadingManager::uploadResources: Interrupt: Exceeded time for resource upload (uploaded {} resources of size {} B, remaining {} resources to upload). dt {}ms", + numUploaded, sizeUploaded, numRemaining, sectionDuration.count()); LOG_INFO_F(CONTEXT_RENDERER, [&](StringOutputStream& logger) { logger << "Remaining resources in queue to upload:"; @@ -177,7 +177,7 @@ namespace ramses::internal { assert(rd.resource); assert(!rd.deviceHandle.isValid()); - LOG_TRACE(CONTEXT_PROFILING, " ResourceUploadingManager::uploadResource upload resource of type " << EnumToString(rd.type)); + LOG_TRACE(CONTEXT_PROFILING, " ResourceUploadingManager::uploadResource upload resource of type {}", EnumToString(rd.type)); const IResource* pResource = rd.resource.get(); // decompress resource if needed @@ -199,7 +199,7 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "ResourceUploadingManager::uploadResource failed to upload resource #" << rd.hash << " (" << EnumToString(rd.type) << ")"); + LOG_ERROR(CONTEXT_RENDERER, "ResourceUploadingManager::uploadResource failed to upload resource #{} ({})", rd.hash, EnumToString(rd.type)); m_resources.setResourceBroken(rd.hash); } } @@ -219,8 +219,8 @@ namespace ramses::internal assert(rd.status == EResourceStatus::Uploaded); assert(m_resourceSizes.contains(rd.hash)); - LOG_TRACE(CONTEXT_PROFILING, " ResourceUploadingManager::unloadResource delete resource of type " << EnumToString(rd.type)); - LOG_TRACE(CONTEXT_RENDERER, "ResourceUploadingManager::unloadResource Unloading resource #" << rd.hash); + LOG_TRACE(CONTEXT_PROFILING, " ResourceUploadingManager::unloadResource delete resource of type {}", EnumToString(rd.type)); + LOG_TRACE(CONTEXT_RENDERER, "ResourceUploadingManager::unloadResource Unloading resource #{}", rd.hash); m_uploader->unloadResource(m_renderBackend, rd.type, rd.hash, rd.deviceHandle); auto resSizeIt = m_resourceSizes.find(rd.hash); @@ -228,7 +228,7 @@ namespace ramses::internal m_resourceTotalUploadedSize -= resSizeIt->value; m_resourceSizes.remove(resSizeIt); - LOG_TRACE(CONTEXT_RENDERER, "ResourceUploadingManager::unloadResource Removing resource descriptor for resource #" << rd.hash); + LOG_TRACE(CONTEXT_RENDERER, "ResourceUploadingManager::unloadResource Removing resource descriptor for resource #{}", rd.hash); m_resources.unregisterResource(rd.hash); } diff --git a/src/renderer/internal/RendererLib/SceneExpirationMonitor.cpp b/src/renderer/internal/RendererLib/SceneExpirationMonitor.cpp index 1d4ff8cc7..f2a29e0c5 100644 --- a/src/renderer/internal/RendererLib/SceneExpirationMonitor.cpp +++ b/src/renderer/internal/RendererLib/SceneExpirationMonitor.cpp @@ -12,7 +12,7 @@ #include "internal/RendererLib/RendererEventCollector.h" #include "internal/SceneGraph/Scene/SceneActionApplier.h" #include "internal/PlatformAbstraction/PlatformTime.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -34,7 +34,7 @@ namespace ramses::internal { if (m_monitoredScenes.count(sceneId) == 0) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneExpirationMonitor: expiration monitoring for scene {} enabled", sceneId); + LOG_INFO(CONTEXT_RENDERER, "SceneExpirationMonitor: expiration monitoring for scene {} enabled", sceneId); m_eventCollector.addSceneExpirationEvent(ERendererEventType::SceneExpirationMonitoringEnabled, sceneId); } @@ -45,7 +45,7 @@ namespace ramses::internal } else if (m_monitoredScenes.count(sceneId) != 0) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneExpirationMonitor: expiration monitoring for scene {} disabled, last state expired={}", sceneId, m_monitoredScenes[sceneId].inExpiredState); + LOG_INFO(CONTEXT_RENDERER, "SceneExpirationMonitor: expiration monitoring for scene {} disabled, last state expired={}", sceneId, m_monitoredScenes[sceneId].inExpiredState); m_eventCollector.addSceneExpirationEvent(ERendererEventType::SceneExpirationMonitoringDisabled, sceneId); m_monitoredScenes.erase(sceneId); } @@ -102,9 +102,10 @@ namespace ramses::internal if (expDelayRendered > FlushTime::Clock::milliseconds::zero()) { const uint64_t expirationTimestamp = std::chrono::duration_cast(timestamps.expirationTSOfRenderedScene.ts.time_since_epoch()).count(); - LOG_ERROR(CONTEXT_RENDERER, "SceneExpirationMonitor: Content of rendered scene " << sceneId << " is expired (version tag of rendered scene " << timestamps.expirationTSOfRenderedScene.tag << "). " - << "Expiration time stamp " << expirationTimestamp << " ms, " << "expired by " << expDelayRendered.count() << " ms. " - << "Internal flush index " << timestamps.expirationTSOfRenderedScene.internalIndex); + LOG_ERROR(CONTEXT_RENDERER, "SceneExpirationMonitor: Content of rendered scene {} is expired (version tag of rendered scene {}). " + "Expiration time stamp {} ms, expired by {} ms. " + "Internal flush index {}", + sceneId, timestamps.expirationTSOfRenderedScene.tag, expirationTimestamp, expDelayRendered.count(), timestamps.expirationTSOfRenderedScene.internalIndex); expired = true; } } @@ -115,9 +116,10 @@ namespace ramses::internal if (expDelayApplied > FlushTime::Clock::milliseconds::zero()) { const uint64_t expirationTimestamp = std::chrono::duration_cast(timestamps.expirationTSOfLastAppliedFlush.ts.time_since_epoch()).count(); - LOG_ERROR(CONTEXT_RENDERER, "SceneExpirationMonitor: Flush applied to scene " << sceneId << " is expired (version tag of applied flush " << timestamps.expirationTSOfLastAppliedFlush.tag << "). " - << "Expiration time stamp " << expirationTimestamp << " ms, " << "expired by " << expDelayApplied.count() << " ms." - << "Internal flush index " << timestamps.expirationTSOfLastAppliedFlush.internalIndex); + LOG_ERROR(CONTEXT_RENDERER, "SceneExpirationMonitor: Flush applied to scene {} is expired (version tag of applied flush {}). " + "Expiration time stamp {} ms, expired by {} ms." + "Internal flush index {}", + sceneId, timestamps.expirationTSOfLastAppliedFlush.tag, expirationTimestamp, expDelayApplied.count(), timestamps.expirationTSOfLastAppliedFlush.internalIndex); expired = true; } } @@ -139,20 +141,22 @@ namespace ramses::internal if (lastPendingFlushExpired) { - LOG_ERROR(CONTEXT_RENDERER, "SceneExpirationMonitor: Latest pending flush of scene " << sceneId << " is expired (version tag of this flush " << lastPendingFlush.versionTag << "). " - << "Expiration time stamp " << expirationTimestampPendingFlush << " ms, " - << "expired by " << expDelayPending.count() << " ms. " - << "Timestamp of flush creation on client side: " << internalTimestampPendingFlush << " ms. " - << "Internal flush index " << lastPendingFlush.flushIndex << ". " - << "There is " << pendingFlushes.size() << " pending flushes in total, only latest was checked."); + LOG_ERROR(CONTEXT_RENDERER, "SceneExpirationMonitor: Latest pending flush of scene {} is expired (version tag of this flush {}). " + "Expiration time stamp {} ms, " + "expired by {} ms. " + "Timestamp of flush creation on client side: {} ms. " + "Internal flush index {}. " + "There is {} pending flushes in total, only latest was checked.", + sceneId, lastPendingFlush.versionTag, expirationTimestampPendingFlush, expDelayPending.count(), internalTimestampPendingFlush, lastPendingFlush.flushIndex, pendingFlushes.size()); expired = true; } else if (expired) { - LOG_ERROR(CONTEXT_RENDERER, "SceneExpirationMonitor: for the expired scene " << sceneId << " there is pending flush which is not expired " - << "Expiration time stamp " << expirationTimestampPendingFlush << " ms, timestamp of flush creation on client side: " << internalTimestampPendingFlush << " ms. " - << "Internal flush index " << timestamps.expirationTSOfLastAppliedFlush.internalIndex << ". " - << "There is " << pendingFlushes.size() << " pending flushes in total, only latest was checked."); + LOG_ERROR(CONTEXT_RENDERER, "SceneExpirationMonitor: for the expired scene {} there is pending flush which is not expired." + "Expiration time stamp {} ms, timestamp of flush creation on client side: {} ms. " + "Internal flush index {}. " + "There is {} pending flushes in total, only latest was checked.", + sceneId, expirationTimestampPendingFlush, internalTimestampPendingFlush, timestamps.expirationTSOfLastAppliedFlush.internalIndex, pendingFlushes.size()); } LOG_INFO_F(CONTEXT_RENDERER, ([&](StringOutputStream& logStream) @@ -165,7 +169,7 @@ namespace ramses::internal } } else if (expired) - LOG_ERROR(CONTEXT_RENDERER, "SceneExpirationMonitor: there are no pending flushes for the expired scene " << sceneId); + LOG_ERROR(CONTEXT_RENDERER, "SceneExpirationMonitor: there are no pending flushes for the expired scene {}", sceneId); checkAndTriggerExpirationEvent(sceneId, timestamps, expired); @@ -179,7 +183,7 @@ namespace ramses::internal { if (m_monitoredScenes.erase(sceneId) != 0) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneExpirationMonitor: expiration monitoring for scene {} disabled because scene was unsubscribed from renderer", sceneId); + LOG_INFO(CONTEXT_RENDERER, "SceneExpirationMonitor: expiration monitoring for scene {} disabled because scene was unsubscribed from renderer", sceneId); m_eventCollector.addSceneExpirationEvent(ERendererEventType::SceneExpirationMonitoringDisabled, sceneId); } } diff --git a/src/renderer/internal/RendererLib/SceneLinksManager.cpp b/src/renderer/internal/RendererLib/SceneLinksManager.cpp index 564bbc50e..c807ad7f7 100644 --- a/src/renderer/internal/RendererLib/SceneLinksManager.cpp +++ b/src/renderer/internal/RendererLib/SceneLinksManager.cpp @@ -10,7 +10,7 @@ #include "internal/RendererLib/RendererScenes.h" #include "internal/RendererLib/DataLinkUtils.h" #include "internal/RendererLib/RendererEventCollector.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" namespace ramses::internal { @@ -27,14 +27,14 @@ namespace ramses::internal { if (!m_rendererScenes.hasScene(providerSceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createDataLink failed: provider scene " << providerSceneId << " is not known to the renderer!"); + LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createDataLink failed: provider scene {} is not known to the renderer!", providerSceneId); m_rendererEventCollector.addDataLinkEvent(ERendererEventType::SceneDataLinkFailed, providerSceneId, consumerSceneId, providerId, consumerId); return; } if (!m_rendererScenes.hasScene(consumerSceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createDataLink failed: consumer scene " << consumerSceneId << " is not known to the renderer!"); + LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createDataLink failed: consumer scene {} is not known to the renderer!", consumerSceneId); m_rendererEventCollector.addDataLinkEvent(ERendererEventType::SceneDataLinkFailed, providerSceneId, consumerSceneId, providerId, consumerId); return; } @@ -44,14 +44,14 @@ namespace ramses::internal if (!providerSlotHandle.isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createDataLink failed: provider data id " << providerId << " is invalid! (Provider scene: " << providerSceneId << ")"); + LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createDataLink failed: provider data id {} is invalid! (Provider scene: {})", providerId, providerSceneId); m_rendererEventCollector.addDataLinkEvent(ERendererEventType::SceneDataLinkFailed, providerSceneId, consumerSceneId, providerId, consumerId); return; } if (!consumerSlotHandle.isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createDataLink failed: consumer data id " << consumerId << " is invalid! (Consumer scene: " << consumerSceneId << ")"); + LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createDataLink failed: consumer data id {} is invalid! (Consumer scene: {})", consumerId, consumerSceneId); m_rendererEventCollector.addDataLinkEvent(ERendererEventType::SceneDataLinkFailed, providerSceneId, consumerSceneId, providerId, consumerId); return; } @@ -77,7 +77,7 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createDataLink failed: data slot type mismatch, provider and consumer slot types must match! (Provider scene: " << providerSceneId << ", consumer scene: " << consumerSceneId << ")"); + LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createDataLink failed: data slot type mismatch, provider and consumer slot types must match! (Provider scene: {}, consumer scene: {})", providerSceneId, consumerSceneId); } m_rendererEventCollector.addDataLinkEvent((linkSuccess ? ERendererEventType::SceneDataLinked : ERendererEventType::SceneDataLinkFailed), providerSceneId, consumerSceneId, providerId, consumerId); @@ -106,7 +106,7 @@ namespace ramses::internal const DataSlotHandle consumerSlotHandle = DataLinkUtils::GetDataSlotHandle(consumerSceneId, consumerId, m_rendererScenes); if (!consumerSlotHandle.isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createBufferLink failed: consumer data id is invalid! (consumer scene: " << consumerSceneId << ")"); + LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createBufferLink failed: consumer data id is invalid! (consumer scene: {})", consumerSceneId); m_rendererEventCollector.addBufferEvent(ERendererEventType::SceneDataBufferLinkFailed, providerBuffer, consumerSceneId, consumerId); return; } @@ -114,7 +114,7 @@ namespace ramses::internal const EDataSlotType consumerSlotType = DataLinkUtils::GetDataSlot(consumerSceneId, consumerSlotHandle, m_rendererScenes).type; if (consumerSlotType != EDataSlotType::TextureConsumer) { - LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createBufferLink failed: consumer data " << consumerId << " refers to a slot that is not of texture type! (consumer scene: " << consumerSceneId << ")"); + LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::createBufferLink failed: consumer data {} refers to a slot that is not of texture type! (consumer scene: {})", consumerId, consumerSceneId); m_rendererEventCollector.addBufferEvent(ERendererEventType::SceneDataBufferLinkFailed, providerBuffer, consumerSceneId, consumerId); return; } @@ -130,7 +130,7 @@ namespace ramses::internal { if (!m_rendererScenes.hasScene(consumerSceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::removeDataLink failed: consumer scene " << consumerSceneId << " is not known to the renderer!"); + LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::removeDataLink failed: consumer scene {} is not known to the renderer!", consumerSceneId); m_rendererEventCollector.addDataLinkEvent(ERendererEventType::SceneDataUnlinkFailed, SceneId(0u), consumerSceneId, DataSlotId(0u), consumerId); return; } @@ -139,7 +139,7 @@ namespace ramses::internal if (!consumerSlotHandle.isValid()) { - LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::removeDataLink failed: consumer data id " << consumerId << " is invalid!"); + LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::removeDataLink failed: consumer data id {} is invalid!", consumerId); m_rendererEventCollector.addDataLinkEvent(ERendererEventType::SceneDataUnlinkFailed, SceneId(0u), consumerSceneId, DataSlotId(0u), consumerId); return; } @@ -162,7 +162,7 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::removeDataLink failed: given slot " << consumerSlotHandle << " is not a consumer slot or there was no link!"); + LOG_ERROR(CONTEXT_RENDERER, "SceneLinksManager::removeDataLink failed: given slot {} is not a consumer slot or there was no link!", consumerSlotHandle); m_rendererEventCollector.addDataLinkEvent(ERendererEventType::SceneDataUnlinkFailed, SceneId(0u), consumerSceneId, DataSlotId(0u), consumerId); return; } diff --git a/src/renderer/internal/RendererLib/SceneReferenceLogic.cpp b/src/renderer/internal/RendererLib/SceneReferenceLogic.cpp index 7a58fca91..b0c797acd 100644 --- a/src/renderer/internal/RendererLib/SceneReferenceLogic.cpp +++ b/src/renderer/internal/RendererLib/SceneReferenceLogic.cpp @@ -12,7 +12,7 @@ #include "internal/RendererLib/IRendererSceneUpdater.h" #include "internal/RendererLib/SceneReferenceOwnership.h" #include "internal/RendererLib/IRendererSceneEventSender.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include namespace ramses::internal @@ -51,7 +51,7 @@ namespace ramses::internal const auto masterSceneId = findMasterSceneForReferencedScene(evt.sceneId); if (masterSceneId.isValid()) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: sending event scene reference (master {} / ref {}) state changed to {}", masterSceneId, evt.sceneId, EnumToString(evt.state)); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: sending event scene reference (master {} / ref {}) state changed to {}", masterSceneId, evt.sceneId, EnumToString(evt.state)); m_eventSender.sendSceneStateChanged(masterSceneId, evt.sceneId, evt.state); if (evt.state == RendererSceneState::Unavailable) { @@ -66,7 +66,7 @@ namespace ramses::internal const auto masterSceneId = findMasterSceneForReferencedScene(evt.sceneId); if (masterSceneId.isValid() && m_masterScenes[masterSceneId].sceneReferencesWithFlushNotification.count(evt.sceneId) != 0) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: sending event scene reference (master {} / ref {}) flushed with version {}", masterSceneId, evt.sceneId, evt.sceneVersionTag); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: sending event scene reference (master {} / ref {}) flushed with version {}", masterSceneId, evt.sceneId, evt.sceneVersionTag); m_eventSender.sendSceneFlushed(masterSceneId, evt.sceneId, evt.sceneVersionTag); } return masterSceneId.isValid(); @@ -81,7 +81,7 @@ namespace ramses::internal if (masterSceneId.isValid()) { const bool status = (evt.eventType == ERendererEventType::SceneDataLinked); - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: sending event scene reference data linked to master {} (providerScene:dataId -> consumerSceneId:dataId) {}:{} -> {}:{} STATUS={}", + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: sending event scene reference data linked to master {} (providerScene:dataId -> consumerSceneId:dataId) {}:{} -> {}:{} STATUS={}", masterSceneId, evt.providerSceneId, evt.providerdataId, evt.consumerSceneId, evt.consumerdataId, status); m_eventSender.sendDataLinked(masterSceneId, evt.providerSceneId, evt.providerdataId, evt.consumerSceneId, evt.consumerdataId, status); } @@ -97,7 +97,7 @@ namespace ramses::internal if (masterSceneId.isValid()) { const bool status = (evt.eventType == ERendererEventType::SceneDataUnlinked); - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: sending event scene reference data unlinked to master {} consumerSceneId:dataId {}:{} STATUS={}", + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: sending event scene reference data unlinked to master {} consumerSceneId:dataId {}:{} STATUS={}", masterSceneId, evt.consumerSceneId, evt.consumerdataId, status); m_eventSender.sendDataUnlinked(masterSceneId, evt.consumerSceneId, evt.consumerdataId, status); } @@ -111,11 +111,11 @@ namespace ramses::internal auto logExpirationMsg = [](SceneId master, SceneId evtScene, const char* msg) { if (master != evtScene) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: received event scene reference (master {} / ref {}) {}", master, evtScene, msg); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: received event scene reference (master {} / ref {}) {}", master, evtScene, msg); } else { - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: received event master scene {} {}", master, msg); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: received event master scene {} {}", master, msg); } }; auto masterSceneId = findMasterSceneForReferencedScene(evt.sceneId); @@ -204,10 +204,10 @@ namespace ramses::internal const auto oldMaster = findMasterSceneForReferencedScene(refSceneId); if (oldMaster.isValid()) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic::updateReferencedScenes: discarding old scene reference ownership (master {} / ref {})", oldMaster, refSceneId); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic::updateReferencedScenes: discarding old scene reference ownership (master {} / ref {})", oldMaster, refSceneId); m_masterScenes[oldMaster].sceneReferences.erase(refSceneId); } - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic::updateReferencedScenes: new scene reference ownership (master {} / ref {})", masterSceneId, refSceneId); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic::updateReferencedScenes: new scene reference ownership (master {} / ref {})", masterSceneId, refSceneId); masterSceneInfo.sceneReferences[refSceneId] = handle; m_sharedOwnership.setOwner(refSceneId, masterSceneId); @@ -224,7 +224,7 @@ namespace ramses::internal const int toBeRequestedRefRenderOrder = masterRenderOrder + refData.renderOrder; if (refOB != masterOB || refRenderOrder != toBeRequestedRefRenderOrder) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic::updateReferencedScenes: setting assignment/renderOrder (master {} / ref {}) to buffer {}, renderOrder {}", + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic::updateReferencedScenes: setting assignment/renderOrder (master {} / ref {}) to buffer {}, renderOrder {}", masterSceneId, refSceneId, masterOB, toBeRequestedRefRenderOrder); m_sceneLogic.setSceneDisplayBufferAssignment(refSceneId, masterOB, toBeRequestedRefRenderOrder); } @@ -235,7 +235,7 @@ namespace ramses::internal const auto stateToRequest = std::min(refData.requestedState, masterTargetState); if (refTargetState != stateToRequest) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic::updateReferencedScenes: setting state (master {} / ref {}) to {}", masterSceneId, refSceneId, EnumToString(stateToRequest)); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic::updateReferencedScenes: setting state (master {} / ref {}) to {}", masterSceneId, refSceneId, EnumToString(stateToRequest)); m_sceneLogic.setSceneState(refSceneId, stateToRequest); } } @@ -254,7 +254,7 @@ namespace ramses::internal const auto& refSceneStagingInfo = m_rendererScenes.getStagingInfo(refSceneId); if (refSceneStagingInfo.lastAppliedVersionTag.isValid()) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: flush notifications enabled, sending last applied scene reference (master {} / ref {}) version {}", masterSceneId, refSceneId, refSceneStagingInfo.lastAppliedVersionTag); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: flush notifications enabled, sending last applied scene reference (master {} / ref {}) version {}", masterSceneId, refSceneId, refSceneStagingInfo.lastAppliedVersionTag); m_eventSender.sendSceneFlushed(masterSceneId, refSceneId, refSceneStagingInfo.lastAppliedVersionTag); } } @@ -274,13 +274,13 @@ namespace ramses::internal auto& masterInfo = masterScene.second; if (!m_rendererScenes.hasScene(masterScene.first) && !masterInfo.destroyed) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: master scene {} destroyed, cleaning up its referenced scenes", masterScene.first); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: master scene {} destroyed, cleaning up its referenced scenes", masterScene.first); // unsubscribe any scene referenced by destroyed master scene for (const auto& sceneRefIt : masterInfo.sceneReferences) { const auto sceneRefId = sceneRefIt.first; constexpr auto cleanupState = RendererSceneState::Available; - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: cleaning up (master {} / ref {}) by setting state to {}", masterScene.first, sceneRefId, EnumToString(cleanupState)); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: cleaning up (master {} / ref {}) by setting state to {}", masterScene.first, sceneRefId, EnumToString(cleanupState)); m_sceneLogic.setSceneState(sceneRefId, cleanupState); } masterInfo.pendingActions.clear(); @@ -314,7 +314,7 @@ namespace ramses::internal for (const auto& releasedRef : releasedRefs) { const auto sceneRefId = releasedRef.first; - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: reference to scene (master {} / ref {}) released", masterSceneId, sceneRefId); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: reference to scene (master {} / ref {}) released", masterSceneId, sceneRefId); // remove from master info lists masterInfo.sceneReferences.erase(sceneRefId); @@ -327,7 +327,7 @@ namespace ramses::internal { if (action.providerScene == refHandle || action.consumerScene == refHandle) { - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: erasing pending scene reference action for released reference (master {} / ref {}) actionType={}", masterSceneId, sceneRefId, action.type); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: erasing pending scene reference action for released reference (master {} / ref {}) actionType={}", masterSceneId, sceneRefId, action.type); return true; } return false; @@ -360,14 +360,14 @@ namespace ramses::internal { const auto providerSceneId = (action.providerScene.isValid() ? masterScene.getSceneReference(action.providerScene).sceneId : masterSceneId); const auto consumerSceneId = (action.consumerScene.isValid() ? masterScene.getSceneReference(action.consumerScene).sceneId : masterSceneId); - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: executing data link for master scene {} (providerScene:dataId -> consumerSceneId:dataId) {}:{} -> {}:{}", masterSceneId, providerSceneId, action.providerId, consumerSceneId, action.consumerId); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: executing data link for master scene {} (providerScene:dataId -> consumerSceneId:dataId) {}:{} -> {}:{}", masterSceneId, providerSceneId, action.providerId, consumerSceneId, action.consumerId); m_sceneUpdater.handleSceneDataLinkRequest(providerSceneId, action.providerId, consumerSceneId, action.consumerId); break; } case SceneReferenceActionType::UnlinkData: { const auto consumerSceneId = (action.consumerScene.isValid() ? masterScene.getSceneReference(action.consumerScene).sceneId : masterSceneId); - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: executing data unlink for master scene {} (consumerSceneId:dataId) {}:{}", masterSceneId, consumerSceneId, action.consumerId); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: executing data unlink for master scene {} (consumerSceneId:dataId) {}:{}", masterSceneId, consumerSceneId, action.consumerId); m_sceneUpdater.handleDataUnlinkRequest(consumerSceneId, action.consumerId); break; } @@ -391,7 +391,7 @@ namespace ramses::internal { events.push_back({ ERendererEventType::SceneExpirationMonitoringEnabled, masterSceneId }); masterInfo.consolidatedExpirationState = ExpirationState::MonitoringEnabled; - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: reporting master scene {} as enabled for expiration monitoring", masterSceneId); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: reporting master scene {} as enabled for expiration monitoring", masterSceneId); } // #2 check enabled/expired -> disabled @@ -400,7 +400,7 @@ namespace ramses::internal { events.push_back({ ERendererEventType::SceneExpirationMonitoringDisabled, masterSceneId }); masterInfo.consolidatedExpirationState = ExpirationState::MonitoringDisabled; - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: reporting master scene {} as disabled for expiration monitoring", masterSceneId); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: reporting master scene {} as disabled for expiration monitoring", masterSceneId); } // #3 check enabled -> expired @@ -409,7 +409,7 @@ namespace ramses::internal { events.push_back({ ERendererEventType::SceneExpired, masterSceneId }); masterInfo.consolidatedExpirationState = ExpirationState::Expired; - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: reporting master scene {} as expired", masterSceneId); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: reporting master scene {} as expired", masterSceneId); } // #4 check expired -> recovered @@ -418,7 +418,7 @@ namespace ramses::internal { events.push_back({ ERendererEventType::SceneRecoveredFromExpiration, masterSceneId }); masterInfo.consolidatedExpirationState = ExpirationState::MonitoringEnabled; - LOG_INFO_P(CONTEXT_RENDERER, "SceneReferenceLogic: reporting master scene {} as recovered from expiration", masterSceneId); + LOG_INFO(CONTEXT_RENDERER, "SceneReferenceLogic: reporting master scene {} as recovered from expiration", masterSceneId); } } diff --git a/src/renderer/internal/RendererLib/SceneStateExecutor.cpp b/src/renderer/internal/RendererLib/SceneStateExecutor.cpp index c6aa539d7..7fc6863ca 100644 --- a/src/renderer/internal/RendererLib/SceneStateExecutor.cpp +++ b/src/renderer/internal/RendererLib/SceneStateExecutor.cpp @@ -11,7 +11,7 @@ #include "internal/RendererLib/RendererScenes.h" #include "internal/Components/ISceneGraphConsumerComponent.h" #include "internal/RendererLib/RendererEventCollector.h" -#include "internal/Core/Utils/ThreadLocalLogForced.h" +#include "internal/Core/Utils/LogMacros.h" #include "internal/PlatformAbstraction/Macros.h" #include "internal/RendererLib/IRendererSceneEventSender.h" @@ -29,7 +29,7 @@ namespace ramses::internal assert(checkIfCanBePublished(sceneId)); m_scenesStateInfo.addScene(sceneId, mode); m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::ScenePublished, sceneId); - LOG_INFO(CONTEXT_RENDERER, "Scene "<< sceneId << " is in state PUBLISHED"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state PUBLISHED", sceneId); } void SceneStateExecutor::setSubscriptionRequested(SceneId sceneId) @@ -37,14 +37,14 @@ namespace ramses::internal assert(checkIfCanBeSubscriptionRequested(sceneId)); m_rendererSceneEventSender.sendSubscribeScene(sceneId); m_scenesStateInfo.setSceneState(sceneId, ESceneState::SubscriptionRequested); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state SUBSCRIPTION REQUESTED"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state SUBSCRIPTION REQUESTED", sceneId); } void SceneStateExecutor::setSubscriptionPending(SceneId sceneId) { assert(checkIfCanBeSubscriptionPending(sceneId)); m_scenesStateInfo.setSceneState(sceneId, ESceneState::SubscriptionPending); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state SUBSCRIPTION PENDING caused by SCENE RECEIVED"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state SUBSCRIPTION PENDING caused by SCENE RECEIVED", sceneId); } void SceneStateExecutor::setSubscribed(SceneId sceneId) @@ -52,7 +52,7 @@ namespace ramses::internal assert(checkIfCanBeSubscribed(sceneId)); m_scenesStateInfo.setSceneState(sceneId, ESceneState::Subscribed); m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneSubscribed, sceneId); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state SUBSCRIBED caused by SCENE FLUSH"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state SUBSCRIBED caused by SCENE FLUSH", sceneId); } void SceneStateExecutor::rollBackToUnsubscribedAndTriggerIndirectEvents(ESceneState sceneState, SceneId sceneId) @@ -109,11 +109,11 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "SceneStateExecutor::setSceneUnpublished Failed unpublish for scene with id :" << sceneId << " because state is inconsistent (state is " << EnumToString(sceneState) << ")!"); + LOG_ERROR(CONTEXT_RENDERER, "SceneStateExecutor::setSceneUnpublished Failed unpublish for scene with id :{} because state is inconsistent (state is {})!", sceneId, EnumToString(sceneState)); assert(false); } - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state UNPUBLISHED, scene was in state " << EnumToString(sceneState)); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state UNPUBLISHED, scene was in state {}", sceneId, EnumToString(sceneState)); } void SceneStateExecutor::setUnsubscribed(SceneId sceneId, bool indirect) @@ -132,21 +132,21 @@ namespace ramses::internal m_scenesStateInfo.setSceneState(sceneId, ESceneState::Published); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state PUBLISHED caused by command UNSUBSCRIBE (indirect: " << indirect << ")"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state PUBLISHED caused by command UNSUBSCRIBE (indirect: {})", sceneId, indirect); } void SceneStateExecutor::setMapRequested(SceneId sceneId) { assert(canBeMapRequested(sceneId)); m_scenesStateInfo.setSceneState(sceneId, ESceneState::MapRequested); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state MAP REQUESTED"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state MAP REQUESTED", sceneId); } void SceneStateExecutor::setMappingAndUploading(SceneId sceneId) { assert(canBeMappingAndUploading(sceneId)); m_scenesStateInfo.setSceneState(sceneId, ESceneState::MappingAndUploading); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state MAPPING_AND_UPLOADING"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state MAPPING_AND_UPLOADING", sceneId); } void SceneStateExecutor::setMapped(SceneId sceneId) @@ -154,7 +154,7 @@ namespace ramses::internal assert(checkIfCanBeMapped(sceneId)); m_scenesStateInfo.setSceneState(sceneId, ESceneState::Mapped); m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneMapped, sceneId); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state MAPPED caused by command MAP"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state MAPPED caused by command MAP", sceneId); } void SceneStateExecutor::setUnmapped(SceneId sceneId) @@ -162,14 +162,14 @@ namespace ramses::internal assert(canBeUnmapped(sceneId)); m_scenesStateInfo.setSceneState(sceneId, ESceneState::Subscribed); m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneUnmapped, sceneId); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state SUBSCRIBED caused by command UNMAP"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state SUBSCRIBED caused by command UNMAP", sceneId); } void SceneStateExecutor::setRenderedRequested(SceneId sceneId) { assert(canBeRenderedRequested(sceneId)); m_scenesStateInfo.setSceneState(sceneId, ESceneState::RenderRequested); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state RENDERED_REQUESTED"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state RENDERED_REQUESTED", sceneId); } void SceneStateExecutor::setRendered(SceneId sceneId) @@ -177,7 +177,7 @@ namespace ramses::internal assert(canBeShown(sceneId)); m_scenesStateInfo.setSceneState(sceneId, ESceneState::Rendered); m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneShown, sceneId); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state RENDERED caused by command SHOW"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state RENDERED caused by command SHOW", sceneId); } void SceneStateExecutor::setHidden(SceneId sceneId) @@ -185,7 +185,7 @@ namespace ramses::internal assert(canBeHidden(sceneId)); m_scenesStateInfo.setSceneState(sceneId, ESceneState::Mapped); m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneHidden, sceneId); - LOG_INFO(CONTEXT_RENDERER, "Scene " << sceneId << " is in state MAPPED caused by command HIDE"); + LOG_INFO(CONTEXT_RENDERER, "Scene {} is in state MAPPED caused by command HIDE", sceneId); } ESceneState SceneStateExecutor::getSceneState(SceneId sceneId) const @@ -215,7 +215,7 @@ namespace ramses::internal return true; } - LOG_ERROR(CONTEXT_RENDERER, "Failed publication of scene with id :" << sceneId << " because scene with this id has already been published!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed publication of scene with id :{} because scene with this id has already been published!", sceneId); return false; } @@ -229,11 +229,11 @@ namespace ramses::internal return true; } - LOG_ERROR(CONTEXT_RENDERER, "Failed unpublish for scene with id :" << sceneId << " because state is inconsistent!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed unpublish for scene with id :{} because state is inconsistent!", sceneId); } else { - LOG_ERROR(CONTEXT_RENDERER, "Failed unpublish for scene with id :" << sceneId << " because it was not published!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed unpublish for scene with id :{} because it was not published!", sceneId); } return false; @@ -243,7 +243,7 @@ namespace ramses::internal { if (!canBeSubscriptionRequested(sceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "Failed subscription request for scene with id :" << sceneId << " because it was not in published state!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed subscription request for scene with id :{} because it was not in published state!", sceneId); m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneSubscribeFailed, sceneId); return false; } @@ -255,7 +255,7 @@ namespace ramses::internal { if (!canBeUnsubscribed(sceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "Failed to unsubscribe from scene with id :" << sceneId << " because it is not in the subscribed/subscribing state!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed to unsubscribe from scene with id :{} because it is not in the subscribed/subscribing state!", sceneId); m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneUnsubscribeFailed, sceneId); return false; } @@ -269,12 +269,12 @@ namespace ramses::internal { if (getSceneState(sceneId) == ESceneState::MapRequested || getSceneState(sceneId) == ESceneState::MappingAndUploading) { - LOG_ERROR(CONTEXT_RENDERER, "Failed to map scene with id :" << sceneId << " because renderer is already mapping the scene"); + LOG_ERROR(CONTEXT_RENDERER, "Failed to map scene with id :{} because renderer is already mapping the scene", sceneId); } else { m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneMapFailed, sceneId); - LOG_ERROR(CONTEXT_RENDERER, "Failed to map scene with id :" << sceneId << " because scene is not in subscribed state or display does not exist (state is " << EnumToString(getSceneState(sceneId)) << ")!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed to map scene with id :{} because scene is not in subscribed state or display does not exist (state is {})!", sceneId, EnumToString(getSceneState(sceneId))); } return false; } @@ -287,7 +287,7 @@ namespace ramses::internal if (!canBeMapped(sceneId)) { m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneMapFailed, sceneId); - LOG_ERROR(CONTEXT_RENDERER, "Failed map for scene with id :" << sceneId << " because scene is not in mapping_and_uploading state (state is " << EnumToString(getSceneState(sceneId)) << ")!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed map for scene with id :{} because scene is not in mapping_and_uploading state (state is {})!", sceneId, EnumToString(getSceneState(sceneId))); return false; } @@ -298,7 +298,7 @@ namespace ramses::internal { if (!canBeUnmapped(sceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "Failed unmap for scene with id :" << sceneId.getValue() << " because it is not in mapped or mapping state (state is " << EnumToString(getSceneState(sceneId)) << ")!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed unmap for scene with id :{} because it is not in mapped or mapping state (state is {})!", sceneId.getValue(), EnumToString(getSceneState(sceneId))); m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneUnmapFailed, sceneId); return false; } @@ -311,7 +311,7 @@ namespace ramses::internal if (!canBeRenderedRequested(sceneId)) { m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneShowFailed, sceneId); - LOG_ERROR(CONTEXT_RENDERER, "Failed show for scene with id :" << sceneId << " because scene is not in mapped state (state is " << EnumToString(getSceneState(sceneId)) << ")!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed show for scene with id :{} because scene is not in mapped state (state is {})!", sceneId, EnumToString(getSceneState(sceneId))); return false; } @@ -323,7 +323,7 @@ namespace ramses::internal if (!canBeShown(sceneId)) { m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneShowFailed, sceneId); - LOG_ERROR(CONTEXT_RENDERER, "Failed show for scene with id :" << sceneId << " because scene is not in mapped state (state is " << EnumToString(getSceneState(sceneId)) << ")!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed show for scene with id :{} because scene is not in mapped state (state is {})!", sceneId, EnumToString(getSceneState(sceneId))); return false; } @@ -334,7 +334,7 @@ namespace ramses::internal { if (!canBeHidden(sceneId)) { - LOG_ERROR(CONTEXT_RENDERER, "Failed hiding scene with id :" << sceneId << " because it is not in a shown state (state is " << EnumToString(getSceneState(sceneId)) << ")!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed hiding scene with id :{} because it is not in a shown state (state is {})!", sceneId, EnumToString(getSceneState(sceneId))); m_rendererEventCollector.addInternalSceneEvent(ERendererEventType::SceneHideFailed, sceneId); return false; } @@ -350,11 +350,11 @@ namespace ramses::internal { return true; } - LOG_ERROR(CONTEXT_RENDERER, "Failed to receive scene with id " << sceneId << " because scene arrived before!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed to receive scene with id {} because scene arrived before!", sceneId); } else { - LOG_ERROR(CONTEXT_RENDERER, "Failed to receive scene with id " << sceneId << " because it is not known to the renderer!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed to receive scene with id {} because it is not known to the renderer!", sceneId); } return false; @@ -368,11 +368,11 @@ namespace ramses::internal { return true; } - LOG_ERROR(CONTEXT_RENDERER, "Failed to subscribe scene with id " << sceneId << " because scene is in wrong state " << EnumToString(m_scenesStateInfo.getSceneState(sceneId)) << "!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed to subscribe scene with id {} because scene is in wrong state {}!", sceneId, EnumToString(m_scenesStateInfo.getSceneState(sceneId))); } else { - LOG_ERROR(CONTEXT_RENDERER, "Failed to subscribe scene with id " << sceneId << " because it is not known to the renderer!"); + LOG_ERROR(CONTEXT_RENDERER, "Failed to subscribe scene with id {} because it is not known to the renderer!", sceneId); } return false; @@ -386,7 +386,7 @@ namespace ramses::internal return true; } - LOG_WARN(CONTEXT_RENDERER, "Subscription request for scene with id :" << sceneId << " might fail because scene is in state " << EnumToString(m_scenesStateInfo.getSceneState(sceneId))); + LOG_WARN(CONTEXT_RENDERER, "Subscription request for scene with id :{} might fail because scene is in state {}", sceneId, EnumToString(m_scenesStateInfo.getSceneState(sceneId))); return false; } @@ -402,13 +402,13 @@ namespace ramses::internal case ESceneState::Subscribed: return true; default: - LOG_WARN(CONTEXT_RENDERER, "Unsubscribe scene with id :" << sceneId << " might fail because scene is in state " << EnumToString(currentSceneState)); + LOG_WARN(CONTEXT_RENDERER, "Unsubscribe scene with id :{} might fail because scene is in state {}", sceneId, EnumToString(currentSceneState)); break; } } else { - LOG_WARN(CONTEXT_RENDERER, "Unsubscribe scene with id :" << sceneId << " might fail because scene was not published!"); + LOG_WARN(CONTEXT_RENDERER, "Unsubscribe scene with id :{} might fail because scene was not published!", sceneId); } return false; @@ -422,11 +422,11 @@ namespace ramses::internal { return true; } - LOG_WARN(CONTEXT_RENDERER, "Map scene with id " << sceneId << " might fail because the display seems invalid!"); + LOG_WARN(CONTEXT_RENDERER, "Map scene with id :{} might fail because the display seems invalid!", sceneId); } else { - LOG_WARN(CONTEXT_RENDERER, "Map scene with id :" << sceneId << " might fail because scene is not in subscribed state!"); + LOG_WARN(CONTEXT_RENDERER, "Map scene with id :{} might fail because scene is not in subscribed state!", sceneId); } return false; @@ -452,7 +452,7 @@ namespace ramses::internal return true; } - LOG_WARN(CONTEXT_RENDERER, "Unmap scene with id :" << sceneId << " might fail because scene is not in mapped or mapping state (state is " << EnumToString(getSceneState(sceneId)) << ")"); + LOG_WARN(CONTEXT_RENDERER, "Unmap scene with id :{} might fail because scene is not in mapped or mapping state (state is {})", sceneId, EnumToString(getSceneState(sceneId))); return false; } @@ -463,7 +463,7 @@ namespace ramses::internal return true; } - LOG_WARN(CONTEXT_RENDERER, "Show scene with id :" << sceneId << " might fail because scene is not in mapped state (state is " << EnumToString(getSceneState(sceneId)) << ")"); + LOG_WARN(CONTEXT_RENDERER, "Show scene with id :{} might fail because scene is not in mapped state (state is {})", sceneId, EnumToString(getSceneState(sceneId))); return false; } @@ -474,7 +474,7 @@ namespace ramses::internal return true; } - LOG_WARN(CONTEXT_RENDERER, "Show scene with id :" << sceneId << " might fail because scene is not in rendered requested state (state is " << EnumToString(getSceneState(sceneId)) << ")"); + LOG_WARN(CONTEXT_RENDERER, "Show scene with id :{} might fail because scene is not in rendered requested state(state is{})", sceneId, EnumToString(getSceneState(sceneId))); return false; } @@ -486,7 +486,7 @@ namespace ramses::internal return true; } - LOG_WARN(CONTEXT_RENDERER, "Hide scene with id :" << sceneId << " might fail because scene is not in rendered state (state is " << EnumToString(getSceneState(sceneId)) << ")!"); + LOG_WARN(CONTEXT_RENDERER, "Hide scene with id :{} might fail because scene is not in rendered state (state is {})!", sceneId, EnumToString(getSceneState(sceneId))); return false; } diff --git a/src/shared-lib/CMakeLists.txt b/src/shared-lib/CMakeLists.txt index d675128c2..662b6b589 100644 --- a/src/shared-lib/CMakeLists.txt +++ b/src/shared-lib/CMakeLists.txt @@ -41,36 +41,29 @@ endif() set(RENDERER_SOURCES ${PROJECT_SOURCE_DIR}/src/renderer/impl/*.cpp) -if (ramses-sdk_BUILD_FULL_SHARED_LIB) - createModuleWithRenderer( - NAME ramses-shared-lib - TYPE ${LIB_TYPE} - ENABLE_INSTALL ON - SRC_FILES ${HEADLESS_SOURCES} - ${RENDERER_SOURCES} - DEPENDENCIES ramses-client +# build shared library without renderer +createModule( + NAME ramses-shared-lib-headless + TYPE ${LIB_TYPE} + ENABLE_INSTALL ON + SRC_FILES ${HEADLESS_SOURCES} ) - target_link_libraries(ramses-shared-lib PUBLIC glm::glm) - if(${LIB_TYPE} STREQUAL "SHARED_LIBRARY") - target_compile_definitions(ramses-shared-lib PUBLIC RAMSES_LINK_SHARED_EXPORT) - endif() +target_link_libraries(ramses-shared-lib-headless PUBLIC glm::glm) +target_link_libraries(ramses-shared-lib-headless PRIVATE ramses-client-internal) +target_link_libraries(ramses-shared-lib-headless INTERFACE ramses-api) +if(${LIB_TYPE} STREQUAL "SHARED_LIBRARY") + target_compile_definitions(ramses-shared-lib-headless PUBLIC RAMSES_LINK_SHARED_EXPORT) endif() -if (ramses-sdk_BUILD_HEADLESS_SHARED_LIB) - - # build shared library without renderer +if (ramses-sdk_BUILD_FULL_SHARED_LIB) createModule( - NAME ramses-shared-lib-headless + NAME ramses-shared-lib TYPE ${LIB_TYPE} ENABLE_INSTALL ON - SRC_FILES ${HEADLESS_SOURCES} - DEPENDENCIES ramses-client - ) + SRC_FILES ${RENDERER_SOURCES} + DEPENDENCIES Platform + ) - target_link_libraries(ramses-shared-lib-headless PUBLIC glm::glm) - target_link_libraries(ramses-shared-lib-headless INTERFACE ramses-api) - if(${LIB_TYPE} STREQUAL "SHARED_LIBRARY") - target_compile_definitions(ramses-shared-lib-headless PUBLIC RAMSES_LINK_SHARED_EXPORT) - endif() + target_link_libraries(ramses-shared-lib PUBLIC ramses-shared-lib-headless) endif() diff --git a/tests/benchmarks/logic/serialization.cpp b/tests/benchmarks/logic/serialization.cpp index 88641a2d2..81e940927 100644 --- a/tests/benchmarks/logic/serialization.cpp +++ b/tests/benchmarks/logic/serialization.cpp @@ -53,9 +53,7 @@ namespace ramses } } - SaveFileConfig configNoValidation; - configNoValidation.setValidationEnabled(false); - std::ignore = setup.m_scene.saveToFile(fileName, configNoValidation); + std::ignore = setup.m_scene.saveToFile(fileName, {}); std::ifstream fileStream(std::string(fileName), std::ifstream::binary); fileStream.seekg(0, std::ios::end); diff --git a/tests/integration/CMakeLists.txt b/tests/integration/CMakeLists.txt index a8bffde58..3ba6658fe 100644 --- a/tests/integration/CMakeLists.txt +++ b/tests/integration/CMakeLists.txt @@ -13,6 +13,6 @@ add_subdirectory(smoke-tests) add_subdirectory(resource-stress-tests) add_subdirectory(render-backend-tests) -if(ramses-sdk_ENABLE_LOGIC AND ramses-sdk_USE_IMAGEMAGICK AND ramses-sdk_BUILD_FULL_SHARED_LIB) - add_subdirectory(logic-viewer-tests) +if(ramses-sdk_ENABLE_LOGIC AND ramses-sdk_USE_IMAGEMAGICK) + add_subdirectory(viewer-tests) endif() diff --git a/tests/integration/render-backend-tests/PlatformTest.cpp b/tests/integration/render-backend-tests/PlatformTest.cpp index 531249c10..2d699e2e4 100644 --- a/tests/integration/render-backend-tests/PlatformTest.cpp +++ b/tests/integration/render-backend-tests/PlatformTest.cpp @@ -18,7 +18,6 @@ #include "internal/Platform/PlatformFactory.h" #include "internal/RendererLib/PlatformInterface/IPlatform.h" #include "internal/SceneGraph/Resource/EffectResource.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include "impl/DisplayConfigImpl.h" #include "RendererTestUtils.h" #include @@ -46,9 +45,6 @@ namespace ramses::internal auto dispConfig = RendererTestUtils::CreateTestDisplayConfig(0u); platform = platformFactory.createPlatform(rendererConfig, dispConfig.impl().getInternalDisplayConfig()); assert(platform); - - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); } protected: @@ -263,9 +259,6 @@ namespace ramses::internal std::thread resourceUploadThread([&]() { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(2); - IResourceUploadRenderBackend* resourceUploadRenderBackend = createResourceUploadRenderBackend(); if (!resourceUploadRenderBackend) { @@ -294,9 +287,6 @@ namespace ramses::internal std::thread resourceUploadThread([&]() { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(2); - IResourceUploadRenderBackend* resourceUploadRenderBackend = createResourceUploadRenderBackend(); if (!resourceUploadRenderBackend) { @@ -333,9 +323,6 @@ namespace ramses::internal std::thread resourceUploadThread([&]() { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(2); - IResourceUploadRenderBackend* resourceUploadRenderBackend = createResourceUploadRenderBackend(); if (!resourceUploadRenderBackend) { @@ -370,9 +357,6 @@ namespace ramses::internal std::thread resourceUploadThread([&]() { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(2); - IResourceUploadRenderBackend* resourceUploadRenderBackend = createResourceUploadRenderBackend(); if (!resourceUploadRenderBackend) { @@ -416,9 +400,6 @@ namespace ramses::internal std::thread resourceUploadThread([&]() { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(2); - IResourceUploadRenderBackend* resourceUploadRenderBackend = createResourceUploadRenderBackend(); if (!resourceUploadRenderBackend) { @@ -462,9 +443,6 @@ namespace ramses::internal std::thread resourceUploadThread([&]() { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(2); - IResourceUploadRenderBackend* resourceUploadRenderBackend = createResourceUploadRenderBackend(); if (!resourceUploadRenderBackend) { diff --git a/tests/integration/render-backend-tests/main.cpp b/tests/integration/render-backend-tests/main.cpp index 00615eaa5..503914ec1 100644 --- a/tests/integration/render-backend-tests/main.cpp +++ b/tests/integration/render-backend-tests/main.cpp @@ -10,7 +10,6 @@ #include "ramses/framework/RamsesFrameworkConfig.h" #include "RendererTestUtils.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include "ramses-cli.h" int main(int argc, char* argv[]) @@ -36,8 +35,5 @@ int main(int argc, char* argv[]) CLI11_PARSE(cli, argc, argv); ramses::internal::RendererTestUtils::SetDefaultConfigForAllTests(rendererConfig, displayConfig); - // set log prefix for all tests - ramses::internal::ThreadLocalLog::SetPrefix(1); - return RUN_ALL_TESTS(); } diff --git a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/EmbeddedCompositingTestsFramework.cpp b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/EmbeddedCompositingTestsFramework.cpp index 5d3770fd8..67c136480 100644 --- a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/EmbeddedCompositingTestsFramework.cpp +++ b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/EmbeddedCompositingTestsFramework.cpp @@ -80,14 +80,14 @@ namespace ramses::internal const IEmbeddedCompositor& embeddedCompositor = getEmbeddedCompositor(displayIdx); IEmbeddedCompositingManager& embeddedCompositorManager = getEmbeddedCompositorManager(displayIdx); - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForContentOnStreamTexture() " << iviSurface); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForContentOnStreamTexture() {}", iviSurface); while (!embeddedCompositor.isContentAvailableForStreamTexture(iviSurface)) { embeddedCompositorManager.processClientRequests(); } - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForContentOnStreamTexture(): content found on " << iviSurface); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForContentOnStreamTexture(): content found on {}", iviSurface); } void EmbeddedCompositingTestsFramework::waitForUnavailablilityOfContentOnStreamTexture(WaylandIviSurfaceId iviSurface) @@ -95,14 +95,14 @@ namespace ramses::internal const IEmbeddedCompositor& embeddedCompositor = getEmbeddedCompositor(); IEmbeddedCompositingManager& embeddedCompositorManager = getEmbeddedCompositorManager(); - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForUnavailablilityOfContentFromStreamTexture() " << iviSurface); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForUnavailablilityOfContentFromStreamTexture() {}", iviSurface); while (embeddedCompositor.isContentAvailableForStreamTexture(iviSurface)) { embeddedCompositorManager.processClientRequests(); } - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForUnavailablilityOfContentFromStreamTexture(): no content on " << iviSurface); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForUnavailablilityOfContentFromStreamTexture(): no content on {}", iviSurface); } bool EmbeddedCompositingTestsFramework::waitUntilNumberOfCommitedFramesForIviSurface(WaylandIviSurfaceId iviSurface, uint64_t numberOfComittedBuffers, uint32_t timeoutMilliseconds) @@ -110,7 +110,7 @@ namespace ramses::internal const IEmbeddedCompositor& embeddedCompositor = getEmbeddedCompositor(); IEmbeddedCompositingManager& embeddedCompositingManager = getEmbeddedCompositorManager(); - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitUntilNumberOfCommitedBuffersForIviSurface(): waiting for number of commited buffers for " << iviSurface << " reaching " << numberOfComittedBuffers); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitUntilNumberOfCommitedBuffersForIviSurface(): waiting for number of commited buffers for {} reaching {}", iviSurface, numberOfComittedBuffers); const uint64_t startTime = PlatformTime::GetMillisecondsMonotonic(); while (embeddedCompositor.getNumberOfCommitedFramesForWaylandIviSurfaceSinceBeginningOfTime(iviSurface) != numberOfComittedBuffers) @@ -120,11 +120,11 @@ namespace ramses::internal const auto timeElapsed = static_cast(PlatformTime::GetMillisecondsMonotonic() - startTime); if(timeElapsed > timeoutMilliseconds) { - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitUntilNumberOfCommitedFramesForIviSurfaceWithTimeout(): timed out after " << timeElapsed << " ms"); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitUntilNumberOfCommitedFramesForIviSurfaceWithTimeout(): timed out after {} ms", timeElapsed); return false; } } - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitUntilNumberOfCommitedBuffersForIviSurface(): number of commited buffers for " << iviSurface << " is " << embeddedCompositor.getNumberOfCommitedFramesForWaylandIviSurfaceSinceBeginningOfTime(iviSurface)); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitUntilNumberOfCommitedBuffersForIviSurface(): number of commited buffers for {} is {}", iviSurface, embeddedCompositor.getNumberOfCommitedFramesForWaylandIviSurfaceSinceBeginningOfTime(iviSurface)); return true; } @@ -144,7 +144,7 @@ namespace ramses::internal const IEmbeddedCompositor& embeddedCompositor = getEmbeddedCompositor(displayIdx); IEmbeddedCompositingManager& embeddedCompositingManager = getEmbeddedCompositorManager(displayIdx); - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitUntilNumberOfCompositorConnections(): waiting for number of connections reaching " << numberOfConnections); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitUntilNumberOfCompositorConnections(): waiting for number of connections reaching {}", numberOfConnections); while (embeddedCompositor.getNumberOfCompositorConnections() != numberOfConnections) { @@ -157,7 +157,7 @@ namespace ramses::internal } } - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitUntilNumberOfCompositorConnections(): number of compositor connections is " << numberOfConnections); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitUntilNumberOfCompositorConnections(): number of compositor connections is {}", numberOfConnections); } void EmbeddedCompositingTestsFramework::waitForBufferAttachedToIviSurface(WaylandIviSurfaceId iviSurface) @@ -167,7 +167,7 @@ namespace ramses::internal LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForBufferAttachedToIviSurface(): waiting for " - "buffer attached to " << iviSurface); + "buffer attached to {}", iviSurface); while (!embeddedCompositor.isBufferAttachedToWaylandIviSurface(iviSurface)) { @@ -184,7 +184,7 @@ namespace ramses::internal LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForNoBufferAttachedToIviSurface(): waiting for " - "no buffer attached to " << iviSurface); + "no buffer attached to {}", iviSurface); while (embeddedCompositor.isBufferAttachedToWaylandIviSurface(iviSurface)) { @@ -204,28 +204,28 @@ namespace ramses::internal { const IEmbeddedCompositor& embeddedCompositor = getEmbeddedCompositor(); - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForSurfaceAvailableForStreamTexture() " << iviSurface); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForSurfaceAvailableForStreamTexture() {}", iviSurface); while (!embeddedCompositor.hasSurfaceForStreamTexture(iviSurface)) { getTestRenderer().doOneLoop(); } - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForSurfaceAvailableForStreamTexture(): surface available for " << iviSurface); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForSurfaceAvailableForStreamTexture(): surface available for {}", iviSurface); } void EmbeddedCompositingTestsFramework::waitForSurfaceUnavailableForStreamTexture(WaylandIviSurfaceId iviSurface) { const IEmbeddedCompositor& embeddedCompositor = getEmbeddedCompositor(); - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForSurfaceUnavailableForStreamTexture() " << iviSurface); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForSurfaceUnavailableForStreamTexture() {}", iviSurface); while (embeddedCompositor.hasSurfaceForStreamTexture(iviSurface)) { getTestRenderer().doOneLoop(); } - LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForSurfaceUnavailableForStreamTexture(): surface unavailable for " << iviSurface); + LOG_INFO(CONTEXT_RENDERER, "EmbeddedCompositingTestsFramework::waitForSurfaceUnavailableForStreamTexture(): surface unavailable for {}", iviSurface); } bool EmbeddedCompositingTestsFramework::waitForStreamSurfaceAvailabilityChange(WaylandIviSurfaceId iviSurface, bool available) diff --git a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/NamedPipe.h b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/NamedPipe.h index 55d33b0ea..a62eacada 100644 --- a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/NamedPipe.h +++ b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/NamedPipe.h @@ -44,7 +44,7 @@ namespace ramses::internal { if (::mkfifo(m_pipeName.c_str(), 0666) != 0) { - LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::NamedPipe mkfifo for pipe " << pipeName << " failed with errno: " << getSystemErrorStatus() << "!"); + LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::NamedPipe mkfifo for pipe {} failed with errno: {}!", pipeName, getSystemErrorStatus()); } } } @@ -57,7 +57,7 @@ namespace ramses::internal ~NamedPipe() { - LOG_INFO(CONTEXT_RENDERER, "NamedPipe::~NamedPipe closing pipe [name=" << m_pipeName << ", FD=" << m_pipeFileDescriptor << ", createPipe=" << m_createPipe << "]"); + LOG_INFO(CONTEXT_RENDERER, "NamedPipe::~NamedPipe closing pipe [name={}, FD={}, createPipe={}]", m_pipeName, m_pipeFileDescriptor, m_createPipe); if(m_createPipe) { ::close(m_pipeFileDescriptor); @@ -74,7 +74,7 @@ namespace ramses::internal if (m_pipeFileDescriptor == -1) { - LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::open open failed for pipe " << m_pipeName << " with errno: " << getSystemErrorStatus() << "!"); + LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::open open failed for pipe {} with errno: {}!", m_pipeName, getSystemErrorStatus()); } } @@ -90,7 +90,7 @@ namespace ramses::internal if(-1 == writtenBytesCount ) { - LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::write write failed for pipe " << m_pipeName << " with errno: " << getSystemErrorStatus() << "!"); + LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::write write failed for pipe {} with errno: {}!", m_pipeName, getSystemErrorStatus()); return false; } @@ -139,7 +139,7 @@ namespace ramses::internal if (0 == bytesRead) { - LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::ReadExactBytesFromPipe read failed for pipe " << m_pipeName << " bytesRead: " << bytesRead << " with errno: " << getSystemErrorStatus() << "!"); + LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::ReadExactBytesFromPipe read failed for pipe {} bytesRead: {} with errno: {}!", m_pipeName, bytesRead, getSystemErrorStatus()); return EReadFromPipeStatus_Closed; } @@ -167,11 +167,11 @@ namespace ramses::internal { continue; } - LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::ReadExactBytesFromPipe read failed for pipe " << m_pipeName << " bytesRead: " << bytesRead << " with errno: " << readErrorStatus << "!"); + LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::ReadExactBytesFromPipe read failed for pipe {} bytesRead: {} with errno: {}!", m_pipeName, bytesRead, readErrorStatus); return EReadFromPipeStatus_Empty; } - LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::ReadExactBytesFromPipe read failed for pipe " << m_pipeName << " bytesRead: " << bytesRead << " with errno: " << readErrorStatus << "!"); + LOG_ERROR(CONTEXT_RENDERER, "NamedPipe::ReadExactBytesFromPipe read failed for pipe {} bytesRead: {} with errno: {}!", m_pipeName, bytesRead, readErrorStatus); return EReadFromPipeStatus_Failure; } } diff --git a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestForkerApplication.cpp b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestForkerApplication.cpp index 03123959c..8f7720a64 100644 --- a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestForkerApplication.cpp +++ b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestForkerApplication.cpp @@ -46,7 +46,7 @@ namespace ramses::internal LOG_ERROR(CONTEXT_RENDERER, "TestForkerApplication::handleIncomingMessage request pipe closed, stopping forker application"); return false; case EReadFromPipeStatus_Failure: - LOG_ERROR(CONTEXT_RENDERER, "TestForkerApplication::handleIncomingMessage request pipe error " << NamedPipe::getSystemErrorStatus() << ", stopping"); + LOG_ERROR(CONTEXT_RENDERER, "TestForkerApplication::handleIncomingMessage request pipe error {}, stopping", NamedPipe::getSystemErrorStatus()); return false; case EReadFromPipeStatus_Empty: return true; diff --git a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestForkingController.cpp b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestForkingController.cpp index 9a2e7d74b..936bc4780 100644 --- a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestForkingController.cpp +++ b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestForkingController.cpp @@ -38,21 +38,21 @@ namespace ramses::internal void TestForkingController::startTestApplication(uint32_t testAppIdx) { - LOG_INFO(CONTEXT_RENDERER, "TestForkingController::startApplication starting test application :" << testAppIdx); + LOG_INFO(CONTEXT_RENDERER, "TestForkingController::startApplication starting test application :{}", testAppIdx); assert(testAppIdx < m_testPipes.size()); sendForkRequest(testAppIdx); } void TestForkingController::waitForTestApplicationExit(uint32_t testAppIdx) { - LOG_INFO(CONTEXT_RENDERER, "TestForkingController::waitForTestApplicationExit waiting for test application to exit :" << testAppIdx); + LOG_INFO(CONTEXT_RENDERER, "TestForkingController::waitForTestApplicationExit waiting for test application to exit :{}", testAppIdx); assert(testAppIdx < m_testPipes.size()); sendWaitForExitRequest(testAppIdx); } void TestForkingController::sendMessageToTestApplication(const BinaryOutputStream& os, uint32_t testAppIdx) { - LOG_INFO(CONTEXT_RENDERER, "TestForkingController::sendMessageToTestApplication :" << testAppIdx); + LOG_INFO(CONTEXT_RENDERER, "TestForkingController::sendMessageToTestApplication :{}", testAppIdx); assert(testAppIdx < m_testPipes.size()); const auto dataSize = static_cast(os.getSize()); @@ -111,7 +111,7 @@ namespace ramses::internal if (!m_testToForkerPipe.write(&message, sizeof(ETestForkerApplicationMessage)) || !m_testToForkerPipe.write(&testAppIdx, sizeof(testAppIdx))) { - LOG_ERROR(CONTEXT_RENDERER, "TestForkingController::sendForkRequest error " << NamedPipe::getSystemErrorStatus() << " when wrinting fork request pipe"); + LOG_ERROR(CONTEXT_RENDERER, "TestForkingController::sendForkRequest error {} when wrinting fork request pipe", NamedPipe::getSystemErrorStatus()); } } @@ -122,7 +122,7 @@ namespace ramses::internal if (!m_testToForkerPipe.write(&message, sizeof(ETestForkerApplicationMessage)) || !m_testToForkerPipe.write(&testAppIdx, sizeof(testAppIdx))) { - LOG_ERROR(CONTEXT_RENDERER, "TestForkingController::sendWaitForExitRequest error " << NamedPipe::getSystemErrorStatus() << " when writing wait for test application exit pipe"); + LOG_ERROR(CONTEXT_RENDERER, "TestForkingController::sendWaitForExitRequest error {} when writing wait for test application exit pipe", NamedPipe::getSystemErrorStatus()); } } @@ -134,7 +134,7 @@ namespace ramses::internal if (!m_testToForkerPipe.write(&message, sizeof(ETestForkerApplicationMessage)) || !m_testToForkerPipe.write(&testAppIdx, sizeof(testAppIdx))) { - LOG_ERROR(CONTEXT_RENDERER, "TestForkingController::killTestApplication error " << NamedPipe::getSystemErrorStatus()); + LOG_ERROR(CONTEXT_RENDERER, "TestForkingController::killTestApplication error {}", NamedPipe::getSystemErrorStatus()); } } } diff --git a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestSignalHandler.cpp b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestSignalHandler.cpp index d2e6aefa8..c75156a55 100644 --- a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestSignalHandler.cpp +++ b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/EmbeddedCompositingTestFramework/TestSignalHandler.cpp @@ -30,7 +30,7 @@ namespace ramses::internal void TestSignalHandler::HandleSignalCallback(int32_t signal) { - LOG_ERROR(CONTEXT_RENDERER, "SignalHandler::HandleSignalCallback() Received signal " << PlatformSignal::SignalToString(static_cast(signal)) << " In Process :[" << ProcessName << "]! Sending signal to process group ..."); + LOG_ERROR(CONTEXT_RENDERER, "SignalHandler::HandleSignalCallback() Received signal {} In Process :[{}]! Sending signal to process group ...", PlatformSignal::SignalToString(static_cast(signal)), ProcessName); //send same signal to process group kill(0, signal); } diff --git a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/SharedMemoryBufferTests.cpp b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/SharedMemoryBufferTests.cpp index 7c95a0cd5..d4b02986e 100644 --- a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/SharedMemoryBufferTests.cpp +++ b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/SharedMemoryBufferTests.cpp @@ -25,12 +25,12 @@ namespace ramses::internal ++callbacks; if (available) { - LOG_INFO_P(CONTEXT_RENDERER, "stream available: {}", streamId.getValue()); + LOG_INFO(CONTEXT_RENDERER, "stream available: {}", streamId.getValue()); availableStreams.insert(streamId); } else { - LOG_INFO_P(CONTEXT_RENDERER, "stream unavailable: {}", streamId.getValue()); + LOG_INFO(CONTEXT_RENDERER, "stream unavailable: {}", streamId.getValue()); availableStreams.erase(streamId); } } @@ -121,7 +121,7 @@ namespace ramses::internal testFramework.dispatchRendererEvents(handler, handler); if (handler.availableStreams.empty()) { - LOG_ERROR_P(CONTEXT_RENDERER, "Test surface {} is unavailable", surfaceId.getValue()); + LOG_ERROR(CONTEXT_RENDERER, "Test surface {} is unavailable", surfaceId.getValue()); testResultValue = false; } else @@ -134,7 +134,7 @@ namespace ramses::internal testFramework.dispatchRendererEvents(handler, handler); if (handler.availableStreams.count(iviSurface) != 1 || handler.callbacks == callbacks) { - LOG_ERROR_P(CONTEXT_RENDERER, "Stream surface {} is unavailable after reattach", surfaceId.getValue()); + LOG_ERROR(CONTEXT_RENDERER, "Stream surface {} is unavailable after reattach", surfaceId.getValue()); testResultValue = false; } } @@ -634,7 +634,7 @@ namespace ramses::internal if (numberOfAllocatedSHMBuffer != expectedNumberOfAllocatedSHMBuffer) { - LOG_ERROR(CONTEXT_RENDERER, "SharedMemoryBufferTests::RenderAndCheckOneSharedMemoryFrame Number of allocated SHM buffers " << numberOfAllocatedSHMBuffer << " does not match expected value " << expectedNumberOfAllocatedSHMBuffer <<"!"); + LOG_ERROR(CONTEXT_RENDERER, "SharedMemoryBufferTests::RenderAndCheckOneSharedMemoryFrame Number of allocated SHM buffers {} does not match expected value {}!", numberOfAllocatedSHMBuffer, expectedNumberOfAllocatedSHMBuffer); return false; } return true; @@ -659,7 +659,7 @@ namespace ramses::internal if (bufferFreeState != expectedBufferFreeState) { - LOG_ERROR(CONTEXT_RENDERER, "SharedMemoryBufferTests::CheckFreeBufferState Expected buffer free state: " << expectedBufferFreeState << " does not match actual buffer free state: " << bufferFreeState); + LOG_ERROR(CONTEXT_RENDERER, "SharedMemoryBufferTests::CheckFreeBufferState Expected buffer free state: {} does not match actual buffer free state: {}", expectedBufferFreeState, bufferFreeState); return false; } return true; diff --git a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/SingleStreamTextureTests.cpp b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/SingleStreamTextureTests.cpp index 32dccb537..86e93291a 100644 --- a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/SingleStreamTextureTests.cpp +++ b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/SingleStreamTextureTests.cpp @@ -710,7 +710,7 @@ namespace ramses::internal if (outputString.rfind(expectedLogBuf.str(), 0) != 0) { - LOG_ERROR(CONTEXT_RENDERER, "SingleStreamTextureTests::runEmbeddedCompositingTestCase Wrong log output: " << outputString.c_str()); + LOG_ERROR(CONTEXT_RENDERER, "SingleStreamTextureTests::runEmbeddedCompositingTestCase Wrong log output: {}", outputString.c_str()); testResultValue = false; } @@ -781,12 +781,12 @@ namespace ramses::internal { testResult &= testFramework.waitUntilNumberOfCommitedFramesForIviSurface(waylandSurfaceIviId, frameIndex + 1); - LOG_INFO(CONTEXT_RENDERER, "SingleStreamTextureTests::RenderFramesOnTestApplicationAndTakeScreenshots(): taking screenshot for frame with index: " << frameIndex); + LOG_INFO(CONTEXT_RENDERER, "SingleStreamTextureTests::RenderFramesOnTestApplicationAndTakeScreenshots(): taking screenshot for frame with index: {}", frameIndex); const std::string& screenshotName = screenshotFiles[frameIndex % triangleColorCount]; if(!testFramework.renderAndCompareScreenshot(screenshotName)) { - LOG_ERROR(CONTEXT_RENDERER, "SingleStreamTextureTests::RenderFramesOnTestApplicationAndTakeScreenshots(): test failed for screenshot for frame with index: " << frameIndex); + LOG_ERROR(CONTEXT_RENDERER, "SingleStreamTextureTests::RenderFramesOnTestApplicationAndTakeScreenshots(): test failed for screenshot for frame with index: {}", frameIndex); testResult = false; } } diff --git a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/WaylandOutputTests.cpp b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/WaylandOutputTests.cpp index 24a177064..f80077c4c 100644 --- a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/WaylandOutputTests.cpp +++ b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestCases/WaylandOutputTests.cpp @@ -128,22 +128,22 @@ namespace ramses::internal if(modeActuallyReceived != expectMode) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputTests::CheckWaylandOutputParams: expected mode received :" << expectMode - << ", actual mode received :" << modeActuallyReceived); + LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputTests::CheckWaylandOutputParams: expected mode received :{}, actual mode received :{}", + expectMode, modeActuallyReceived); success = false; } if(scaleActuallyReceived != expectScale) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputTests::CheckWaylandOutputParams: expected scale received :" << expectScale - << ", actual scale received :" << scaleActuallyReceived); + LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputTests::CheckWaylandOutputParams: expected scale received :{}, actual scale received :{}", + expectScale, scaleActuallyReceived); success = false; } if(doneActuallyReceived != expectDone) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputTests::CheckWaylandOutputParams: expected done received :" << expectDone - << ", actual done received :" << doneActuallyReceived); + LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputTests::CheckWaylandOutputParams: expected done received :{}, actual done received :{}", + expectDone, doneActuallyReceived); success = false; } @@ -174,13 +174,19 @@ namespace ramses::internal || waylandOutputParams.subpixel != subpixelExpected || waylandOutputParams.transform != transformExpected) { LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputTests::CheckWaylandOutputParams: wrong values received" - << ": x = " << waylandOutputParams.x << " (expected = " << xExpected << ")" - << ", y = " << waylandOutputParams.y << " (expected = " << yExpected << ")" - << ", physical_width = " << waylandOutputParams.physicalWidth << " (expected = " << physicalWidthExpected << ")" - << ", physical_height = " << waylandOutputParams.physicalHeight << " (expected = " << physicalHeightExpected<< ")" - << ", subpixel format = " << waylandOutputParams.subpixel << " (expected = " << subpixelExpected<< ")" - << ", transform = " << waylandOutputParams.transform << " (expected = " << transformExpected<< ")" - ); + ": x = {} (expected = {})" + ", y = {} (expected = {})" + ", physical_width = {} (expected = {})" + ", physical_height = {} (expected = {})" + ", subpixel format = {} (expected = {})" + ", transform = {} (expected = {})", + waylandOutputParams.x, xExpected, + waylandOutputParams.y, yExpected, + waylandOutputParams.physicalWidth, physicalWidthExpected, + waylandOutputParams.physicalHeight, physicalHeightExpected, + waylandOutputParams.subpixel, subpixelExpected, + waylandOutputParams.transform, transformExpected + ); return false; } @@ -199,11 +205,15 @@ namespace ramses::internal || waylandOutputParams.refreshRate != refreshExpected) { LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputTests::CheckWaylandOutputParams: wrong values received" - << ": flags = " << waylandOutputParams.modeFlags << " (expected = " << flagsExpected << ")" - << ": width = " << waylandOutputParams.width << " (expected = " << expectedWidth << ")" - << ": height = " << waylandOutputParams.height << " (expected = " << expectedHeight << ")" - << ": refresh = " << waylandOutputParams.refreshRate << " (expected = " << refreshExpected << ")" - ); + ": flags = {} (expected = {})" + ": width = {} (expected = {})" + ": height = {} (expected = {})" + ": refresh = {} (expected = {})", + waylandOutputParams.modeFlags, flagsExpected, + waylandOutputParams.width, expectedWidth, + waylandOutputParams.height, expectedHeight, + waylandOutputParams.refreshRate, refreshExpected + ); return false; } @@ -218,8 +228,8 @@ namespace ramses::internal if(waylandOutputParams.factor != factorExpected) { LOG_ERROR(CONTEXT_RENDERER, "WaylandOutputTests::CheckWaylandOutputParams: wrong values received" - << ": factor = " << waylandOutputParams.factor << " (expected = " << factorExpected << ")" - ); + ": factor = {} (expected = {})", waylandOutputParams.factor, factorExpected + ); return false; } diff --git a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestWaylandApplication/TestWaylandApplication.cpp b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestWaylandApplication/TestWaylandApplication.cpp index dc3614901..1618c2679 100644 --- a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestWaylandApplication/TestWaylandApplication.cpp +++ b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestWaylandApplication/TestWaylandApplication.cpp @@ -137,7 +137,7 @@ namespace ramses::internal bis >> surfaceId.getReference() >> width >> height >> swapInterval >> useEGL; - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message create surface size " << width << "/" << height << " swap interval " << swapInterval); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message create surface size {}/{} swap interval {}", width, height, swapInterval); bool bSuccess = m_waylandHandler.createWindow(surfaceId, width, height, swapInterval, useEGL); if (!bSuccess) @@ -154,7 +154,7 @@ namespace ramses::internal bis >> surfaceId.getReference() >> shellSurfaceId.getReference(); - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message create shell surface for surface with id " << surfaceId.getValue()); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message create shell surface for surface with id {}", surfaceId.getValue()); m_waylandHandler.createShellSurface(surfaceId, shellSurfaceId); return true; } @@ -165,8 +165,8 @@ namespace ramses::internal bis >> shellSurfaceId.getReference(); LOG_INFO(CONTEXT_RENDERER, - "TestWaylandApplication::handleIncomingMessages(): received message destroy shell surface with id " - << shellSurfaceId.getValue()); + "TestWaylandApplication::handleIncomingMessages(): received message destroy shell surface with id {}", + shellSurfaceId.getValue()); m_waylandHandler.destroyShellSurface(shellSurfaceId); return true; } @@ -177,7 +177,7 @@ namespace ramses::internal bis >> shellSurfaceId.getReference() >> title; - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message set shell surface title for shell surface with id " << shellSurfaceId.getValue() << " title: " << title); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message set shell surface title for shell surface with id {} title: {}", shellSurfaceId.getValue(), title); m_waylandHandler.setShellSurfaceTitle(shellSurfaceId, title); return true; } @@ -189,8 +189,8 @@ namespace ramses::internal LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message set shell surface dummy values " - "surface with id " - << surfaceId.getValue()); + "surface with id {}", + surfaceId.getValue()); m_waylandHandler.setShellSurfaceDummyValues(surfaceId, shellSurfaceId); return true; } @@ -200,7 +200,7 @@ namespace ramses::internal bis >> surfaceId.getReference(); - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message destroy surface with id " << surfaceId.getValue()); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message destroy surface with id {}", surfaceId.getValue()); m_waylandHandler.destroyWindow(surfaceId); return true; } @@ -210,7 +210,7 @@ namespace ramses::internal bis >> surfaceId.getReference(); - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message destroy ivi-surface for surface with id " << surfaceId.getValue()); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message destroy ivi-surface for surface with id {}", surfaceId.getValue()); m_waylandHandler.destroyIVISurface(surfaceId); return true; } @@ -221,7 +221,7 @@ namespace ramses::internal bis >> surfaceId.getReference() >> surfaceIviId.getReference(); - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message create ivi-surface for surface with id " << surfaceId.getValue() << " " << surfaceIviId); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message create ivi-surface for surface with id {} {}", surfaceId.getValue(), surfaceIviId); m_waylandHandler.createIVISurface(surfaceId, surfaceIviId); return true; } @@ -232,7 +232,7 @@ namespace ramses::internal bis >> surfaceId.getReference() >> useCallback; - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message render one frame to egl buffer on surface with id " << surfaceId.getValue()); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message render one frame to egl buffer on surface with id {}", surfaceId.getValue()); renderFrameToEGLBuffer(surfaceId, useCallback); return true; } @@ -243,7 +243,7 @@ namespace ramses::internal bis >> surfaceId.getReference() >> useCallback; - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message render one frame to shraed memory buffer on surface with id " << surfaceId.getValue()); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message render one frame to shraed memory buffer on surface with id {}", surfaceId.getValue()); renderFrameToSharedMemoryBuffer(surfaceId, useCallback); return true; } @@ -255,9 +255,8 @@ namespace ramses::internal bis >> surfaceId.getReference() >> commit; LOG_INFO(CONTEXT_RENDERER, - "TestWaylandApplication::handleIncomingMessages(): received message attach buffer " - "with id " - << surfaceId.getValue()); + "TestWaylandApplication::handleIncomingMessages(): received message attach buffer with id {}", + surfaceId.getValue()); attachBuffer(surfaceId, commit); return true; } @@ -269,9 +268,8 @@ namespace ramses::internal bis >> surfaceId.getReference() >> count; LOG_INFO(CONTEXT_RENDERER, - "TestWaylandApplication::handleIncomingMessages(): received message reattach buffer " - "with id " - << surfaceId.getValue()); + "TestWaylandApplication::handleIncomingMessages(): received message reattach buffer with id {}", + surfaceId.getValue()); reattachBuffer(surfaceId, count); return true; } @@ -290,7 +288,7 @@ namespace ramses::internal bis >> surfaceId.getReference() >> width >> height; - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message change size for surface with id " << surfaceId.getValue() << " to " << width << "*" << height); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message change size for surface with id {} to {}*{}", surfaceId.getValue(), width, height); m_waylandHandler.resizeWindow(surfaceId, width, height); return true; } @@ -302,7 +300,7 @@ namespace ramses::internal setTriangleColor(static_cast(triangleColor)); - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message set triangle color " << static_cast(triangleColor)); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message set triangle color {}", static_cast(triangleColor)); return true; } case ETestWaylandApplicationMessage::AdditionalConnectToEmbeddedCompositor: @@ -318,7 +316,7 @@ namespace ramses::internal bis >> surfaceId.getReference(); - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message detach buffer from surface with id " << surfaceId.getValue()); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message detach buffer from surface with id {}", surfaceId.getValue()); detachBufferFromSurface(surfaceId); return true; } @@ -338,7 +336,7 @@ namespace ramses::internal bis >> surfaceId1.getReference() >> surfaceId2.getReference() >> useCallback; - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message render one frame to two surfaces with ivi id's " << surfaceId1.getValue() << ", " << surfaceId2.getValue()); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message render one frame to two surfaces with ivi id's {}, {}", surfaceId1.getValue(), surfaceId2.getValue()); renderFrameToTwoSurfaces(surfaceId1, surfaceId2, useCallback); return true; } @@ -354,7 +352,7 @@ namespace ramses::internal sendAnswerToTestFramework(isBufferFree); if (buffer >= m_waylandHandler.getNumberOfAllocatedSHMBuffer()) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::getIsSHMBufferFree buffer: " << buffer << " does not exist !"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::getIsSHMBufferFree buffer: {} does not exist !", buffer); return false; } @@ -377,7 +375,7 @@ namespace ramses::internal { uint32_t protocolVersion = 0u; bis >> protocolVersion; - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message set required wayland output version :" << protocolVersion); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::handleIncomingMessages(): received message set required wayland output version :{}", protocolVersion); m_waylandHandler.setRequiredWaylandOutputVersion(protocolVersion); @@ -451,7 +449,7 @@ namespace ramses::internal uint32_t height = 0; m_waylandHandler.getWindowSize(surfaceId, width, height); SHMBuffer* buffer = m_waylandHandler.getFreeSHMBuffer(width, height); - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::renderFrameToSharedMemoryBuffer render to SHMBuffer with id " << buffer->getId()); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::renderFrameToSharedMemoryBuffer render to SHMBuffer with id {}", buffer->getId()); SHMTriangleDrawer triangleDrawer(m_triangleColor); triangleDrawer.draw(buffer); @@ -471,7 +469,7 @@ namespace ramses::internal m_waylandHandler.getWindowSize(surfaceId, width, height); SHMBuffer* buffer = m_waylandHandler.getFreeSHMBuffer(width, height); LOG_INFO(CONTEXT_RENDERER, - "TestWaylandApplication::attachBuffer: attaching buffer" << buffer->getId()); + "TestWaylandApplication::attachBuffer: attaching buffer{}", buffer->getId()); m_waylandHandler.attachBuffer(surfaceId, *buffer, commit); } @@ -483,7 +481,7 @@ namespace ramses::internal m_waylandHandler.getWindowSize(surfaceId, width, height); SHMBuffer* buffer = m_waylandHandler.getFreeSHMBuffer(width, height); LOG_INFO(CONTEXT_RENDERER, - "TestWaylandApplication::reattachBuffer: attaching buffer" << buffer->getId()); + "TestWaylandApplication::reattachBuffer: attaching buffer{}", buffer->getId()); m_waylandHandler.reattachBuffer(surfaceId, *buffer, count); } @@ -506,7 +504,7 @@ namespace ramses::internal } SHMBuffer* buffer = m_waylandHandler.getFreeSHMBuffer(width1, height2); - LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::renderFrame render to SHMBuffer with id " << buffer->getId()); + LOG_INFO(CONTEXT_RENDERER, "TestWaylandApplication::renderFrame render to SHMBuffer with id {}", buffer->getId()); SHMTriangleDrawer triangleDrawer(m_triangleColor); triangleDrawer.draw(buffer); diff --git a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestWaylandApplication/WaylandHandler.cpp b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestWaylandApplication/WaylandHandler.cpp index 33ca6c808..82de76b6c 100644 --- a/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestWaylandApplication/WaylandHandler.cpp +++ b/tests/integration/renderer-tests/embedded-compositing-rendering-tests/TestWaylandApplication/WaylandHandler.cpp @@ -248,7 +248,7 @@ namespace ramses::internal assert(nullptr != wayland.display); egldisplay = eglGetDisplay(static_cast(wayland.display)); - LOG_INFO(CONTEXT_RENDERER, "WaylandHandler::setupEGL(): Display: " << egldisplay); + LOG_INFO(CONTEXT_RENDERER, "WaylandHandler::setupEGL(): Display: {}", egldisplay); if (!m_usesSharedDisplay) { @@ -256,13 +256,13 @@ namespace ramses::internal EGLint minor = 0; if (eglInitialize(egldisplay, &major, &minor) != EGL_TRUE) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::setupEGL(): eglInitialize failed with code :" << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::setupEGL(): eglInitialize failed with code :{}", eglGetError()); return false; } - LOG_INFO(CONTEXT_RENDERER, "WaylandHandler::setupEGL(): EGL version: " << major << "." << minor); + LOG_INFO(CONTEXT_RENDERER, "WaylandHandler::setupEGL(): EGL version: {}.{}", major, minor); if (eglBindAPI(EGL_OPENGL_ES_API) != EGL_TRUE) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::setupEGL(): eglBindAPI with code :" << eglGetError()); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::setupEGL(): eglBindAPI with code :{}", eglGetError()); return false; } } @@ -285,7 +285,7 @@ namespace ramses::internal void WaylandHandler::registry_handle_global(void *data, struct wl_registry *registry, uint32_t name, const char *interface, uint32_t versionProvidedByCompositor) { - LOG_INFO(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): binding interface: " << interface << " version: " << versionProvidedByCompositor); + LOG_INFO(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): binding interface: {} version: {}", interface, versionProvidedByCompositor); auto* waylandHandler = static_cast(data); @@ -293,7 +293,7 @@ namespace ramses::internal { if(waylandHandler->wayland.compositor) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: " << interface << " already bound!"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: {} already bound!", interface); assert(false); } @@ -303,7 +303,7 @@ namespace ramses::internal { if(waylandHandler->wayland.shell) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: " << interface << " already bound!"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: {} already bound!", interface); assert(false); } @@ -313,7 +313,7 @@ namespace ramses::internal { if(waylandHandler->wayland.seat) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: " << interface << " already bound!"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: {} already bound!", interface); assert(false); } @@ -323,7 +323,7 @@ namespace ramses::internal { if(waylandHandler->wayland.ivi_app) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: " << interface << " already bound!"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: {} already bound!", interface); assert(false); } @@ -333,7 +333,7 @@ namespace ramses::internal { if(waylandHandler->wayland.shm) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: " << interface << " already bound!"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: {} already bound!", interface); assert(false); } @@ -343,7 +343,7 @@ namespace ramses::internal { if(waylandHandler->wayland.output) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: " << interface << " already bound!"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): interface: {} already bound!", interface); abort(); } @@ -352,8 +352,8 @@ namespace ramses::internal const uint32_t maximumExpectedProtocolVersion = 3u; if(versionProvidedByCompositor > maximumExpectedProtocolVersion) { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): wl_output version provied by compositor: " << versionProvidedByCompositor - << " while maximum expected version is: " << maximumExpectedProtocolVersion <<"!"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): wl_output version provied by compositor: {}" + " while maximum expected version is: {}!", versionProvidedByCompositor, maximumExpectedProtocolVersion); abort(); } @@ -369,7 +369,7 @@ namespace ramses::internal } else { - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): unhandled interface: " << interface << " !"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::registry_handle_global(): unhandled interface: {} !", interface); assert(false); } } @@ -587,7 +587,7 @@ namespace ramses::internal if (iviSurface == nullptr) { LOG_ERROR(CONTEXT_RENDERER, - "WaylandHandler::createIVISurface(): Failed to create " << iviSurfaceId); + "WaylandHandler::createIVISurface(): Failed to create {}", iviSurfaceId); assert(false); } else @@ -835,7 +835,7 @@ namespace ramses::internal wl_output_add_listener(wayland.output, &m_waylandOutputListenerV3, this); break; default: - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::addWaylandOutputListener: unsupported protocol version :" << m_requiredWaylandOutputVersion); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::addWaylandOutputListener: unsupported protocol version :{}", m_requiredWaylandOutputVersion); abort(); } } @@ -867,7 +867,7 @@ namespace ramses::internal { return *i->value; } - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::getWindow Window with id: " << surfaceId.getValue() << " not found !"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::getWindow Window with id: {} not found !", surfaceId.getValue()); assert(false); static TestWaylandWindow dummyWindow; return dummyWindow; @@ -880,7 +880,7 @@ namespace ramses::internal { return *(i->value); } - LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::getShellSurface Shell surface with id: " << shellSurfaceId.getValue() << " not found !"); + LOG_ERROR(CONTEXT_RENDERER, "WaylandHandler::getShellSurface Shell surface with id: {} not found !", shellSurfaceId.getValue()); assert(false); wl_shell_surface* nullShellSurface(nullptr); return static_cast(*nullShellSurface); diff --git a/tests/integration/renderer-tests/renderer-lifecycle-tests/ExternalWindowTests.cpp b/tests/integration/renderer-tests/renderer-lifecycle-tests/ExternalWindowTests.cpp index 4c8194f1d..3aa394a2a 100644 --- a/tests/integration/renderer-tests/renderer-lifecycle-tests/ExternalWindowTests.cpp +++ b/tests/integration/renderer-tests/renderer-lifecycle-tests/ExternalWindowTests.cpp @@ -12,7 +12,6 @@ #include "ramses/renderer/DisplayConfig.h" #include "impl/DisplayConfigImpl.h" #include "internal/RendererLib/PlatformInterface/IWindowEventHandler.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #ifdef ramses_sdk_ENABLE_WINDOW_TYPE_WINDOWS #include "internal/Platform/Windows/Window_Windows.h" @@ -74,12 +73,10 @@ namespace ramses::internal dispConfig.setWindowRectangle(WindowX, WindowY, WindowWidth, WindowHeight); #ifdef ramses_sdk_ENABLE_WINDOW_TYPE_WINDOWS - ThreadLocalLog::SetPrefix(1); Window_Windows window(dispConfigExternalWindow.impl().getInternalDisplayConfig(), dummyEventHandler, 1); ASSERT_TRUE(window.init()); dispConfig.setWindowsWindowHandle(window.getNativeWindowHandle()); #elif ramses_sdk_ENABLE_WINDOW_TYPE_X11 - ThreadLocalLog::SetPrefix(1); Window_X11 window(dispConfigExternalWindow.impl().getInternalDisplayConfig(), dummyEventHandler, 1); ASSERT_TRUE(window.init()); dispConfig.setX11WindowHandle(X11WindowHandle{window.getNativeWindowHandle()}); diff --git a/tests/integration/renderer-tests/renderer-test-framework/RendererTestsFramework.cpp b/tests/integration/renderer-tests/renderer-test-framework/RendererTestsFramework.cpp index 26afbeb2a..e34876dbf 100644 --- a/tests/integration/renderer-tests/renderer-test-framework/RendererTestsFramework.cpp +++ b/tests/integration/renderer-tests/renderer-test-framework/RendererTestsFramework.cpp @@ -320,7 +320,7 @@ namespace ramses::internal if (!comparisonResult && saveDiffOnError) { assert(m_activeTestCase != nullptr); - LOG_ERROR(ramses::internal::CONTEXT_RENDERER, "Screenshot comparison failed for rendering test case: " << m_activeTestCase->m_name << " -> expected screenshot: " << expectedImageName); + LOG_ERROR(CONTEXT_RENDERER, "Screenshot comparison failed for rendering test case: {} -> expected screenshot: {}", m_activeTestCase->m_name, expectedImageName); } return comparisonResult; @@ -536,7 +536,7 @@ namespace ramses::internal for(const auto& testCase : m_testCases) { - LOG_INFO(ramses::internal::CONTEXT_RENDERER, "====== Running rendering test case: " << testCase->m_name << " ======"); + LOG_INFO(CONTEXT_RENDERER, "====== Running rendering test case: {} ======", testCase->m_name); fmt::print("======\nRunning rendering test case: {}\n======\n", testCase->m_name); fflush(stdout); @@ -546,7 +546,7 @@ namespace ramses::internal } else { - LOG_ERROR(ramses::internal::CONTEXT_RENDERER, "Renderer/display initialization failed for rendering test case: " << testCase->m_name); + LOG_ERROR(CONTEXT_RENDERER, "Renderer/display initialization failed for rendering test case: {}", testCase->m_name); testResult = false; } diff --git a/tests/integration/resource-stress-tests/DynamicQuad_Resources.cpp b/tests/integration/resource-stress-tests/DynamicQuad_Resources.cpp index d8b9c6236..4390c8767 100644 --- a/tests/integration/resource-stress-tests/DynamicQuad_Resources.cpp +++ b/tests/integration/resource-stress-tests/DynamicQuad_Resources.cpp @@ -78,19 +78,19 @@ namespace ramses::internal const uint32_t textureWidth = 64; const uint32_t textureHeight = 32; - std::unique_ptr rawData(new uint8_t[textureWidth * textureHeight * 3]); // NOLINT(modernize-avoid-c-arrays) + MipLevelData rawData(textureWidth * textureHeight * 3); for (uint32_t x = 0; x < textureWidth; ++x) { for (uint32_t y = 0; y < textureHeight; ++y) { - rawData[3 * (y * textureWidth + x) + 0] = static_cast(TestRandom::Get(0, 255)); - rawData[3 * (y * textureWidth + x) + 1] = static_cast(TestRandom::Get(0, 255)); - rawData[3 * (y * textureWidth + x) + 2] = static_cast(TestRandom::Get(0, 255)); + rawData[3 * (y * textureWidth + x) + 0] = static_cast(TestRandom::Get(0, 255)); + rawData[3 * (y * textureWidth + x) + 1] = static_cast(TestRandom::Get(0, 255)); + rawData[3 * (y * textureWidth + x) + 2] = static_cast(TestRandom::Get(0, 255)); } } - const std::vector textureData{ MipLevelData(textureWidth * textureHeight * 3, rawData.get()) }; + const std::vector textureData{ rawData }; resources.texture = m_scene.createTexture2D(ramses::ETextureFormat::RGB8, textureWidth, textureHeight, textureData, false, {}); resources.textureSampler = m_scene.createTextureSampler( diff --git a/tests/integration/resource-stress-tests/DynamicQuad_SceneResources.cpp b/tests/integration/resource-stress-tests/DynamicQuad_SceneResources.cpp index 631e0141d..7548cc7ac 100644 --- a/tests/integration/resource-stress-tests/DynamicQuad_SceneResources.cpp +++ b/tests/integration/resource-stress-tests/DynamicQuad_SceneResources.cpp @@ -110,16 +110,16 @@ namespace ramses::internal m_vertexPos->updateData(0u, 4, vertexPositionsData.data()); m_texCoords->updateData(0u, 4, vertexTexcoordsData.data()); - std::vector rawData; + std::vector rawData; rawData.resize(DynamicTextureWidth * DynamicTextureHeight * 3); for (uint32_t x = 0; x < DynamicTextureWidth; ++x) { for (uint32_t y = 0; y < DynamicTextureHeight; ++y) { - rawData[3 * (y * DynamicTextureWidth + x) + 0] = static_cast(TestRandom::Get(128, 255)); - rawData[3 * (y * DynamicTextureWidth + x) + 1] = 0u; - rawData[3 * (y * DynamicTextureWidth + x) + 2] = static_cast(TestRandom::Get(0, 128)); + rawData[3 * (y * DynamicTextureWidth + x) + 0] = std::byte{ static_cast(TestRandom::Get(128, 255)) }; + rawData[3 * (y * DynamicTextureWidth + x) + 1] = std::byte{ 0 }; + rawData[3 * (y * DynamicTextureWidth + x) + 2] = std::byte{ static_cast(TestRandom::Get(0, 128)) }; } } diff --git a/tests/integration/resource-stress-tests/ResourceStressTests.cpp b/tests/integration/resource-stress-tests/ResourceStressTests.cpp index 2238c6bca..f59caf1e8 100644 --- a/tests/integration/resource-stress-tests/ResourceStressTests.cpp +++ b/tests/integration/resource-stress-tests/ResourceStressTests.cpp @@ -86,7 +86,7 @@ namespace ramses::internal if (m_testConfig.durationEachTestSeconds < MinDurationPerTestSeconds[testToRun]) { - LOG_ERROR(CONTEXT_SMOKETEST, "Test " << EnumToString(testToRun) << " has too short execution time! Aborting test and marking as failed..."); + LOG_ERROR(CONTEXT_SMOKETEST, "Test {} has too short execution time! Aborting test and marking as failed...", EnumToString(testToRun)); return -1; } @@ -323,11 +323,11 @@ namespace ramses::internal if (testResult != 0) { - LOG_ERROR(CONTEXT_SMOKETEST, "Test " << EnumToString(testToRun) << " finished with errors."); + LOG_ERROR(CONTEXT_SMOKETEST, "Test {} finished with errors.", EnumToString(testToRun)); } else { - LOG_DEBUG(CONTEXT_SMOKETEST, "Test " << EnumToString(testToRun) << " finished successfully."); + LOG_DEBUG(CONTEXT_SMOKETEST, "Test {} finished successfully.", EnumToString(testToRun)); } return testResult; } diff --git a/tests/integration/test-content/CMakeLists.txt b/tests/integration/test-content/CMakeLists.txt index 459cc1c40..c402fdcfd 100644 --- a/tests/integration/test-content/CMakeLists.txt +++ b/tests/integration/test-content/CMakeLists.txt @@ -17,5 +17,5 @@ createModule( RESOURCE_FOLDERS res DEPENDENCIES ramses-client ramses-framework - ramses-renderer-lib + ramses-renderer-internal ) diff --git a/tests/integration/test-content/CubeTextureScene.cpp b/tests/integration/test-content/CubeTextureScene.cpp index 3daacb7ba..e766db900 100644 --- a/tests/integration/test-content/CubeTextureScene.cpp +++ b/tests/integration/test-content/CubeTextureScene.cpp @@ -133,20 +133,13 @@ namespace ramses::internal ramses::internal::Image imageNZ; imageNZ.loadFromFilePNG("res/ramses-test-client-cube-nz.png"); - const std::vector mipLevelData{ CubeMipLevelData( - static_cast(imagePX.getData().size()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imagePX.getData().data()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imageNX.getData().data()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imagePY.getData().data()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imageNY.getData().data()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imagePZ.getData().data()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imageNZ.getData().data())) }; + const std::vector mipLevelData{{ + imagePX.getDataAsByte(), + imageNX.getDataAsByte(), + imagePY.getDataAsByte(), + imageNY.getDataAsByte(), + imagePZ.getDataAsByte(), + imageNZ.getDataAsByte()} }; return m_scene.createTextureCube(ramses::ETextureFormat::RGBA8, imageNY.getWidth(), mipLevelData, false); } @@ -166,33 +159,27 @@ namespace ramses::internal ramses::internal::Image imageNZ; imageNZ.loadFromFilePNG("res/ramses-test-client-cube-nz.png"); - const std::vector mipLevelData{ CubeMipLevelData( - static_cast(imagePX.getData().size()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imagePX.getData().data()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imageNX.getData().data()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imagePY.getData().data()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imageNY.getData().data()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imagePZ.getData().data()), - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) - reinterpret_cast(imageNZ.getData().data())) }; + const std::vector mipLevelData{ { + imagePX.getDataAsByte(), + imageNX.getDataAsByte(), + imagePY.getDataAsByte(), + imageNY.getDataAsByte(), + imagePZ.getDataAsByte(), + imageNZ.getDataAsByte()} }; return m_scene.createTextureCube(ramses::ETextureFormat::RGBA8, imageNY.getWidth(), mipLevelData, false, bgraSwizzle); } case EState_Float: { // 2x2 texture with RGB + white. - const float texture[] = {1.0f, 0.0f, 0.0f, - 0.0f, 1.0f, 0.0f, - 0.0f, 0.0f, 1.0f, - 1.0f, 1.0f, 1.0f}; - - const auto* texturePtr = reinterpret_cast(texture); - const std::vector mipLevelData{ CubeMipLevelData(sizeof(texture), texturePtr, texturePtr, texturePtr, texturePtr, texturePtr, texturePtr) }; + const std::array texture = {1.0f, 0.0f, 0.0f, + 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 1.0f, + 1.0f, 1.0f, 1.0f}; + + const auto* texturePtr = reinterpret_cast(texture.data()); + std::vector textureBytes(texturePtr, texturePtr + texture.size() * sizeof(texture[0])); + const std::vector mipLevelData{ {textureBytes, textureBytes, textureBytes, textureBytes, textureBytes, textureBytes} }; return m_scene.createTextureCube(ramses::ETextureFormat::RGB32F, 2, mipLevelData, false); } diff --git a/tests/integration/test-content/FileLoadingScene.cpp b/tests/integration/test-content/FileLoadingScene.cpp index 83a33f521..2fd3b5df2 100644 --- a/tests/integration/test-content/FileLoadingScene.cpp +++ b/tests/integration/test-content/FileLoadingScene.cpp @@ -115,9 +115,7 @@ namespace ramses::internal AddTriangles(*scene, *renderGroup); - SaveFileConfig config; - config.setValidationEnabled(false); - [[maybe_unused]] auto status = scene->saveToFile(folder + "/tempfile.ramses", config); + [[maybe_unused]] auto status = scene->saveToFile(folder + "/tempfile.ramses", {}); client.destroy(*scene); } diff --git a/tests/integration/test-content/MultiTypeLinkScene.cpp b/tests/integration/test-content/MultiTypeLinkScene.cpp index ccde8a0eb..83e97a783 100644 --- a/tests/integration/test-content/MultiTypeLinkScene.cpp +++ b/tests/integration/test-content/MultiTypeLinkScene.cpp @@ -75,8 +75,7 @@ namespace ramses::internal scene.createTransformationDataConsumer(*groupNode, TransformationConsumerId); - const std::array pxData{ {0xff, 0x0, 0x0, 0xff} }; - std::vector mipLevelData{ MipLevelData(4, pxData.data()) }; + std::vector mipLevelData{ {std::byte{0xff}, std::byte{0x0}, std::byte{0x0}, std::byte{0xff}} }; const ramses::Texture2D& texture = *m_scene.createTexture2D(ramses::ETextureFormat::RGBA8, 1u, 1u, mipLevelData, false, {}); const ramses::TextureSampler& sampler = createSampler(texture); SetSampler(appearance2, sampler); @@ -93,8 +92,7 @@ namespace ramses::internal providerNode->setTranslation({ 1.5f, -2.f, 5.f }); scene.createTransformationDataProvider(*providerNode, TransformationProviderId); - const std::array pxData{ { 0x0, 0xff, 0x0, 0xff } }; - const std::vector mipLevelData{ MipLevelData(4, pxData.data()) }; + const std::vector mipLevelData{ { std::byte{0x0}, std::byte{0xff}, std::byte{0x0}, std::byte{0xff} } }; const ramses::Texture2D& texture = *m_scene.createTexture2D(ramses::ETextureFormat::RGBA8, 1u, 1u, mipLevelData, false, {}); const ramses::TextureSampler& sampler = createSampler(texture); SetSampler(appearance2, sampler); diff --git a/tests/integration/test-content/TestScenes/Texture2DFormatScene.h b/tests/integration/test-content/TestScenes/Texture2DFormatScene.h index acc00b470..ba432e0f4 100644 --- a/tests/integration/test-content/TestScenes/Texture2DFormatScene.h +++ b/tests/integration/test-content/TestScenes/Texture2DFormatScene.h @@ -61,4 +61,16 @@ namespace ramses::internal static const std::vector& GetTextureFormatAndData(EState state, ramses::ETextureFormat& format, uint32_t& width, uint32_t& height, ramses::TextureSwizzle& swizzle); }; + + template + inline std::vector convertToBytes(const T* data, size_t len) { + const auto* dataByte = reinterpret_cast(data); + std::vector bytes(dataByte, dataByte + len * sizeof(T)); + return bytes; + } + + template + inline std::vector convertToBytes(const std::vector& data) { + return convertToBytes(data.data(), data.size()); + } } diff --git a/tests/integration/test-content/TestScenes/TextureCubeAnisotropicTextureFilteringScene.h b/tests/integration/test-content/TestScenes/TextureCubeAnisotropicTextureFilteringScene.h index b6021e432..75e017dd2 100644 --- a/tests/integration/test-content/TestScenes/TextureCubeAnisotropicTextureFilteringScene.h +++ b/tests/integration/test-content/TestScenes/TextureCubeAnisotropicTextureFilteringScene.h @@ -45,6 +45,6 @@ namespace ramses::internal float y); static uint32_t GetNextLargerPowerOf2Exponent(uint32_t value); - static void FillMipLevelData(uint8_t* data, uint32_t resolution, uint32_t level); + static void FillMipLevelData(std::byte* data, uint32_t resolution, uint32_t level); }; } diff --git a/tests/integration/test-content/Texture2DAnisotropicTextureFilteringScene.cpp b/tests/integration/test-content/Texture2DAnisotropicTextureFilteringScene.cpp index c20301f7a..34c2f32e7 100644 --- a/tests/integration/test-content/Texture2DAnisotropicTextureFilteringScene.cpp +++ b/tests/integration/test-content/Texture2DAnisotropicTextureFilteringScene.cpp @@ -39,27 +39,23 @@ namespace ramses::internal { createOrthoCamera(); - const uint8_t rgb8_level0[] = { - 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, - 0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0xff, 0x00 + const MipLevelData rgb8_level0 = { + std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, std::byte{0xff}, std::byte{0x00} }; - const uint8_t rgb8_level1[] = { - 0xff, 0x00, 0x00, 0xff, 0x00, 0x00, - 0xff, 0x00, 0x00, 0xff, 0x00, 0x00 + const MipLevelData rgb8_level1 = { + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, std::byte{0x00} }; - const uint8_t rgb8_level2[] = { - 0x00, 0x00, 0xff + const MipLevelData rgb8_level2 = { + std::byte{0x00}, std::byte{0x00}, std::byte{0xff} }; - const std::vector mipLevelData = { - ramses::MipLevelData(sizeof(rgb8_level0), rgb8_level0), - ramses::MipLevelData(sizeof(rgb8_level1), rgb8_level1), - ramses::MipLevelData(sizeof(rgb8_level2), rgb8_level2) - }; + const std::vector mipLevelData = { rgb8_level0, rgb8_level1, rgb8_level2 }; ramses::Effect* effect(getTestEffect("ramses-test-client-textured")); diff --git a/tests/integration/test-content/Texture2DCompressedMipMapScene.cpp b/tests/integration/test-content/Texture2DCompressedMipMapScene.cpp index 32a82ce32..a5fd2adbe 100644 --- a/tests/integration/test-content/Texture2DCompressedMipMapScene.cpp +++ b/tests/integration/test-content/Texture2DCompressedMipMapScene.cpp @@ -30,13 +30,17 @@ namespace ramses::internal { createOrthoCamera(); - const uint8_t dataLevel0[] = {0x7e, 0x80, 0x4, 0x7f, 0x0, 0x7, 0xe0, 0x0,0x81, 0x7e, 0x4, 0x2, 0xfe, 0x0, 0x1f, 0xc0, 0x80, 0x81, 0xfb, 0x82, 0x1, 0xf8, 0x0, 0x3f, 0xf8, 0xf8, 0xf8, 0x2, 0x0, 0x0, 0x0, 0x0}; + const std::vector dataLevel0 = { + std::byte{0x7e}, std::byte{0x80}, std::byte{0x4}, std::byte{0x7f}, std::byte{0x0}, std::byte{0x7}, std::byte{0xe0}, std::byte{0x0}, + std::byte{0x81}, std::byte{0x7e}, std::byte{0x4}, std::byte{0x2}, std::byte{0xfe}, std::byte{0x0}, std::byte{0x1f}, std::byte{0xc0}, + std::byte{0x80}, std::byte{0x81}, std::byte{0xfb}, std::byte{0x82}, std::byte{0x1}, std::byte{0xf8}, std::byte{0x0}, std::byte{0x3f}, + std::byte{0xf8}, std::byte{0xf8}, std::byte{0xf8}, std::byte{0x2}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0} }; // 8x8: red, green, blue, white - const uint8_t dataLevel1[] = {0x7e, 0x80, 0x4, 0x7f, 0x0, 0x7, 0xe0, 0x0}; + const std::vector dataLevel1 = { std::byte{0x7e}, std::byte{0x80}, std::byte{0x4}, std::byte{0x7f}, std::byte{0x0}, std::byte{0x7}, std::byte{0xe0}, std::byte{0x0} }; // 4x4: red - const std::vector mipLevelData = { MipLevelData{ 32u, dataLevel0 }, MipLevelData{ 8u, dataLevel1 } }; + const std::vector mipLevelData = { dataLevel0, dataLevel1 }; const ramses::Texture2D* texture = m_scene.createTexture2D( ramses::ETextureFormat::ETC2RGB, m_textureWidth, m_textureHeight, diff --git a/tests/integration/test-content/Texture2DFormatScene.cpp b/tests/integration/test-content/Texture2DFormatScene.cpp index 84776475f..b44863d21 100644 --- a/tests/integration/test-content/Texture2DFormatScene.cpp +++ b/tests/integration/test-content/Texture2DFormatScene.cpp @@ -24,203 +24,203 @@ To test the texture data format and the sampling we use a simple 2x2 texture. */ -const uint16_t rgba4Data[] = +const std::vector rgba4Data = { 0xf00f, 0x0f0f, 0x00ff, 0xfff7 }; -const std::vector mipLevelData_rgba4{ ramses::MipLevelData(sizeof(rgba4Data), reinterpret_cast(rgba4Data)) }; +const std::vector mipLevelData_rgba4{ ramses::internal::convertToBytes(rgba4Data) }; -const uint16_t rgba5551Data[] = +const std::vector rgba5551Data = { 0xf801, 0x07c1, 0x003f, 0xfffe }; -const std::vector mipLevelData_rgba5551{ ramses::MipLevelData(sizeof(rgba5551Data), reinterpret_cast(rgba5551Data)) }; +const std::vector mipLevelData_rgba5551{ ramses::internal::convertToBytes(rgba5551Data) }; -const uint8_t rgba8Data[] = +const std::vector rgba8Data = { - 0xff, 0x00, 0x00, 0xff, - 0x00, 0xff, 0x00, 0xff, - 0x00, 0x00, 0xff, 0xff, - 0xff, 0xff, 0xff, 0x7f + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, + std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, std::byte{0xff}, + std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, std::byte{0xff}, + std::byte{0xff}, std::byte{0xff}, std::byte{0xff}, std::byte{0x7f} }; -const std::vector mipLevelData_rgba8{ ramses::MipLevelData(sizeof(rgba8Data), reinterpret_cast(rgba8Data)) }; +const std::vector mipLevelData_rgba8{ rgba8Data }; -const uint16_t rgba565Data[] = +const std::vector rgba565Data = { 0xf800, 0x07e0, 0x001f, 0xffff }; -const std::vector mipLevelData_rgba565{ ramses::MipLevelData(sizeof(rgba565Data), reinterpret_cast(rgba565Data)) }; +const std::vector mipLevelData_rgba565{ ramses::internal::convertToBytes(rgba565Data) }; -const uint8_t rgb8Data[] = +const std::vector rgb8Data = { - 0xff, 0x00, 0x00, - 0x00, 0xff, 0x00, - 0x00, 0x00, 0xff, - 0xff, 0xff, 0xff + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, + std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, + std::byte{0xff}, std::byte{0xff}, std::byte{0xff} }; -const std::vector mipLevelData_rgb8{ ramses::MipLevelData(sizeof(rgb8Data), reinterpret_cast(rgb8Data)) }; +const std::vector mipLevelData_rgb8{ rgb8Data }; -const uint8_t rg8Data[] = +const std::vector rg8Data = { - 0xff, 0x3f, // 1.00, 0.25 - 0xff, 0x7f, // 1.00, 0.50 - 0x7f, 0xbf, // 0.50, 0.75 - 0x7f, 0x3f + std::byte{0xff}, std::byte{0x3f}, // 1.00, 0.25 + std::byte{0xff}, std::byte{0x7f}, // 1.00, 0.50 + std::byte{0x7f}, std::byte{0xbf}, // 0.50, 0.75 + std::byte{0x7f}, std::byte{0x3f} }; // 0.50, 0.25 -const std::vector mipLevelData_rg8{ ramses::MipLevelData(sizeof(rg8Data), reinterpret_cast(rg8Data)) }; +const std::vector mipLevelData_rg8{ rg8Data }; -const uint8_t r8Data[] = +const std::vector r8Data = { - 0xff, // 1.00 - 0xbf, // 0.75 - 0x7f, // 0.50 - 0x3f + std::byte{0xff}, // 1.00 + std::byte{0xbf}, // 0.75 + std::byte{0x7f}, // 0.50 + std::byte{0x3f} }; // 0.25 -const std::vector mipLevelData_r8{ ramses::MipLevelData(sizeof(r8Data), reinterpret_cast(r8Data)) }; +const std::vector mipLevelData_r8{ r8Data }; -const uint8_t bgr8Data[] = +const std::vector bgr8Data = { - 0x00, 0x00, 0xff, - 0x00, 0xff, 0x00, - 0xff, 0x00, 0x00, - 0xff, 0xff, 0xff + std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, + std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, + std::byte{0xff}, std::byte{0xff}, std::byte{0xff} }; -const std::vector mipLevelData_bgr8{ ramses::MipLevelData(sizeof(bgr8Data), reinterpret_cast(bgr8Data)) }; +const std::vector mipLevelData_bgr8{ bgr8Data }; -const uint8_t bgra8Data[] = +const std::vector bgra8Data = { - 0x00, 0x00, 0xff, 0xff, - 0x00, 0xff, 0x00, 0xff, - 0xff, 0x00, 0x00, 0xff, - 0xff, 0xff, 0xff, 0x7f + std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, std::byte{0xff}, + std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, std::byte{0xff}, + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, + std::byte{0xff}, std::byte{0xff}, std::byte{0xff}, std::byte{0x7f} }; -const std::vector mipLevelData_bgra8{ ramses::MipLevelData(sizeof(bgra8Data), reinterpret_cast(bgra8Data)) }; +const std::vector mipLevelData_bgra8{ bgra8Data }; -const uint64_t ETC2RGB[] = +const std::vector ETC2RGB = { 0xefee1f11fd7fbb7b }; -const std::vector mipLevelData_etc2rgb{ ramses::MipLevelData(sizeof(ETC2RGB), reinterpret_cast(ETC2RGB)) }; +const std::vector mipLevelData_etc2rgb{ ramses::internal::convertToBytes(ETC2RGB) }; -const uint64_t ETC2RGBA[] = +const std::vector ETC2RGBA = { 0xefee1f11fd7fbb7b, 0xefee0f00efcaf004 }; -const std::vector mipLevelData_etc2rgba{ ramses::MipLevelData(sizeof(ETC2RGBA), reinterpret_cast(ETC2RGBA)) }; +const std::vector mipLevelData_etc2rgba{ ramses::internal::convertToBytes(ETC2RGBA) }; -const uint8_t r16fData[] = // Value (sign, exponent, fraction) +const std::vector r16fData = // Value (sign, exponent, fraction) { - 0x0, 0x3C, // 1.0 (0 01111 0000000000) - 0x0, 0x38, // 0.50 (0 01110 0000000000) - 0x0, 0x34, // 0.25 (0 01101 0000000000) - 0x0, 0x0 // 1.0 (0 00000 0000000000) + std::byte{0x0}, std::byte{0x3C}, // 1.0 (0 01111 0000000000) + std::byte{0x0}, std::byte{0x38}, // 0.50 (0 01110 0000000000) + std::byte{0x0}, std::byte{0x34}, // 0.25 (0 01101 0000000000) + std::byte{0x0}, std::byte{0x0} // 1.0 (0 00000 0000000000) }; -const std::vector mipLevelData_r16fData{ ramses::MipLevelData(sizeof(r16fData), reinterpret_cast(r16fData)) }; +const std::vector mipLevelData_r16fData{ r16fData }; -const float r32fData[] = +const std::vector r32fData = { 1.0f, 0.5f, 0.25f, 0.0f }; -const std::vector mipLevelData_r32fData{ ramses::MipLevelData(sizeof(r32fData), reinterpret_cast(r32fData)) }; +const std::vector mipLevelData_r32fData{ ramses::internal::convertToBytes(r32fData) }; // 4x4 block with various colors encoded as ASTC 4x4 RGBA -const uint8_t astcRGBA4x4Data[] = +const std::vector astcRGBA4x4Data = { - 0xDE, 0x69, 0x1C, 0x10, 0x05, 0x42, 0x0B, 0x82, 0x20, 0x00, 0x15, 0x00, 0x00, 0x04, 0x00, 0x60 + std::byte{0xDE}, std::byte{0x69}, std::byte{0x1C}, std::byte{0x10}, std::byte{0x05}, std::byte{0x42}, std::byte{0x0B}, std::byte{0x82}, std::byte{0x20}, std::byte{0x00}, std::byte{0x15}, std::byte{0x00}, std::byte{0x00}, std::byte{0x04}, std::byte{0x00}, std::byte{0x60} }; -const std::vector mipLevelData_astcRGBA4x4Data{ ramses::MipLevelData(sizeof(astcRGBA4x4Data), reinterpret_cast(astcRGBA4x4Data)) }; +const std::vector mipLevelData_astcRGBA4x4Data{ astcRGBA4x4Data }; // Similar as above, but now encoded as SRGBA -const uint8_t astcSRGB_Alpha4x4Data[] = +const std::vector astcSRGB_Alpha4x4Data = { - 0xDE, 0x09, 0x2C, 0x50, 0x00, 0x02, 0x0A, 0x82, 0x20, 0x00, 0x0B, 0x00, 0xA0, 0xC7, 0x02, 0xF8 + std::byte{0xDE}, std::byte{0x09}, std::byte{0x2C}, std::byte{0x50}, std::byte{0x00}, std::byte{0x02}, std::byte{0x0A}, std::byte{0x82}, std::byte{0x20}, std::byte{0x00}, std::byte{0x0B}, std::byte{0x00}, std::byte{0xA0}, std::byte{0xC7}, std::byte{0x02}, std::byte{0xF8} }; -const std::vector mipLevelData_astcSRGB_Alpha_4x4Data{ ramses::MipLevelData(sizeof(astcSRGB_Alpha4x4Data), reinterpret_cast(astcSRGB_Alpha4x4Data)) }; +const std::vector mipLevelData_astcSRGB_Alpha_4x4Data{ ramses::internal::convertToBytes(astcSRGB_Alpha4x4Data) }; -const uint8_t rg16fData[] = +const std::vector rg16fData = { - 0x0, 0x3C, 0x0, 0x0, // 1, 0 - 0x0, 0x0, 0x0, 0x3C, // 0, 1 - 0x0, 0x0, 0x0, 0x0, // 0, 0 - 0x0, 0x3C, 0x0, 0x3C // 1, 1 + std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x0}, // 1, 0 + std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x3C}, // 0, 1 + std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, // 0, 0 + std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x3C} // 1, 1 }; -const std::vector mipLevelData_rg16fData{ ramses::MipLevelData(sizeof(rg16fData), reinterpret_cast(rg16fData)) }; +const std::vector mipLevelData_rg16fData{ rg16fData }; -const float rg32fData[] = +const std::vector rg32fData = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f }; -const std::vector mipLevelData_rg32fData{ ramses::MipLevelData(sizeof(rg32fData), reinterpret_cast(rg32fData)) }; +const std::vector mipLevelData_rg32fData{ ramses::internal::convertToBytes(rg32fData) }; -const uint8_t rgb16fData[] = +const std::vector rgb16fData = { - 0x0, 0x3C, 0x0, 0x0, 0x0, 0x0, // 1, 0, 0 - 0x0, 0x0, 0x0, 0x3C, 0x0, 0x0, // 0, 1, 0 - 0x0, 0x0, 0x0, 0x0, 0x0, 0x3C, // 0, 0, 1 - 0x0, 0x3C, 0x0, 0x3C, 0x0, 0x3C // 1, 1, 1 + std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, // 1, 0, 0 + std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x0}, // 0, 1, 0 + std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x3C}, // 0, 0, 1 + std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x3C} // 1, 1, 1 }; -const std::vector mipLevelData_rgb16fData{ ramses::MipLevelData(sizeof(rgb16fData), reinterpret_cast(rgb16fData)) }; +const std::vector mipLevelData_rgb16fData{ ramses::internal::convertToBytes(rgb16fData) }; -const float rgb32fData[] = +const std::vector rgb32fData = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f }; -const std::vector mipLevelData_rgb32fData{ ramses::MipLevelData(sizeof(rgb32fData), reinterpret_cast(rgb32fData)) }; +const std::vector mipLevelData_rgb32fData{ ramses::internal::convertToBytes(rgb32fData) }; -const uint8_t rgba16fData[] = +const std::vector rgba16fData = { - 0x0, 0x3C, 0x0, 0x0, 0x0, 0x0, 0x0, 0x3C, // 1, 0, 0, 1 - 0x0, 0x0, 0x0, 0x3C, 0x0, 0x0, 0x0, 0x3C, // 0, 1, 0, 1 - 0x0, 0x0, 0x0, 0x0, 0x0, 0x3C, 0x0, 0x3C, // 0, 0, 1, 1 - 0x0, 0x3C, 0x0, 0x3C, 0x0, 0x3C, 0x0, 0x3C // 1, 1, 1, 1 + std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x3C}, // 1, 0, 0, 1 + std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x3C}, // 0, 1, 0, 1 + std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x3C}, // 0, 0, 1, 1 + std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x3C}, std::byte{0x0}, std::byte{0x3C} // 1, 1, 1, 1 }; -const std::vector mipLevelData_rgba16fData{ ramses::MipLevelData(sizeof(rgba16fData), reinterpret_cast(rgba16fData)) }; +const std::vector mipLevelData_rgba16fData{ rgba16fData }; -const float rgba32fData[] = +const std::vector rgba32fData = { 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; -const std::vector mipLevelData_rgba32fData{ ramses::MipLevelData(sizeof(rgba32fData), reinterpret_cast(rgba32fData)) }; +const std::vector mipLevelData_rgba32fData{ ramses::internal::convertToBytes(rgba32fData) }; -const uint8_t srgb8Data[] = +const std::vector srgb8Data = { - 0x88, 0x00, 0x00, - 0x00, 0x88, 0x00, - 0x00, 0x00, 0x88, - 0x88, 0x88, 0x88 + std::byte{0x88}, std::byte{0x00}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x88}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x00}, std::byte{0x88}, + std::byte{0x88}, std::byte{0x88}, std::byte{0x88} }; -const std::vector mipLevelData_srgb8Data{ ramses::MipLevelData(sizeof(srgb8Data), reinterpret_cast(srgb8Data)) }; +const std::vector mipLevelData_srgb8Data{ srgb8Data }; -const uint8_t srgb8a8Data[] = +const std::vector srgb8a8Data = { - 0x88, 0x00, 0x00, 0x88, - 0x00, 0x88, 0x00, 0x88, - 0x00, 0x00, 0x88, 0x88, - 0x88, 0x88, 0x88, 0xff + std::byte{0x88}, std::byte{0x00}, std::byte{0x00}, std::byte{0x88}, + std::byte{0x00}, std::byte{0x88}, std::byte{0x00}, std::byte{0x88}, + std::byte{0x00}, std::byte{0x00}, std::byte{0x88}, std::byte{0x88}, + std::byte{0x88}, std::byte{0x88}, std::byte{0x88}, std::byte{0xff} }; -const std::vector mipLevelData_srgb8a8Data{ ramses::MipLevelData(sizeof(srgb8a8Data), reinterpret_cast(srgb8a8Data)) }; +const std::vector mipLevelData_srgb8a8Data{ srgb8a8Data }; const std::vector mipLevelData_null; diff --git a/tests/integration/test-content/Texture2DGenerateMipMapScene.cpp b/tests/integration/test-content/Texture2DGenerateMipMapScene.cpp index cfd073563..1095dbc01 100644 --- a/tests/integration/test-content/Texture2DGenerateMipMapScene.cpp +++ b/tests/integration/test-content/Texture2DGenerateMipMapScene.cpp @@ -149,45 +149,43 @@ namespace ramses::internal const uint32_t idx_blue = pixelCount * 2; const uint32_t idx_white = pixelCount * 3; - auto* rgba8_level0 = new uint8_t[pixelCount * 4]; + ramses::MipLevelData rgba8_level0(pixelCount * 4); for (uint32_t pixel = 0u; pixel < pixelCount; pixel++) { const uint32_t idx = pixel * 4; if (idx < idx_green) { //red - rgba8_level0[idx] = 0xff; - rgba8_level0[idx + 1] = 0x00; - rgba8_level0[idx + 2] = 0x00; + rgba8_level0[idx] = static_cast(0xff); + rgba8_level0[idx + 1] = static_cast(0x00); + rgba8_level0[idx + 2] = static_cast(0x00); } else if (idx < idx_blue) { //green - rgba8_level0[idx] = 0x00; - rgba8_level0[idx + 1] = 0xff; - rgba8_level0[idx + 2] = 0x00; + rgba8_level0[idx] = static_cast(0x00); + rgba8_level0[idx + 1] = static_cast(0xff); + rgba8_level0[idx + 2] = static_cast(0x00); } else if (idx < idx_white) { //blue - rgba8_level0[idx] = 0x00; - rgba8_level0[idx + 1] = 0x00; - rgba8_level0[idx + 2] = 0xff; + rgba8_level0[idx] = static_cast(0x00); + rgba8_level0[idx + 1] = static_cast(0x00); + rgba8_level0[idx + 2] = static_cast(0xff); } else { //white - rgba8_level0[idx] = 0xff; - rgba8_level0[idx + 1] = 0xff; - rgba8_level0[idx + 2] = 0xff; + rgba8_level0[idx] = static_cast(0xff); + rgba8_level0[idx + 1] = static_cast(0xff); + rgba8_level0[idx + 2] = static_cast(0xff); } // opacity - rgba8_level0[idx + 3] = 0xff - transparency; + rgba8_level0[idx + 3] = static_cast(0xffu - transparency); } - const std::vector mipLevelData = { - ramses::MipLevelData(width*height*4u*sizeof(uint8_t), rgba8_level0) - }; + const std::vector mipLevelData = { rgba8_level0 }; ramses::Texture2D* texture = m_scene.createTexture2D( ramses::ETextureFormat::RGBA8, @@ -202,8 +200,6 @@ namespace ramses::internal ramses::ETextureSamplingMethod::Nearest, *texture); - delete[] rgba8_level0; - return sampler; } } diff --git a/tests/integration/test-content/Texture2DSamplingScene.cpp b/tests/integration/test-content/Texture2DSamplingScene.cpp index b0de5657f..792408e89 100644 --- a/tests/integration/test-content/Texture2DSamplingScene.cpp +++ b/tests/integration/test-content/Texture2DSamplingScene.cpp @@ -36,27 +36,23 @@ namespace ramses::internal const auto enumState = static_cast(state); - const uint8_t rgb8_level0[] = { - 0xff,0xff,0xff, 0xff,0xff,0xff, 0x00,0x00,0x00, 0x00,0x00,0x00, - 0xff,0xff,0xff, 0xff,0xff,0xff, 0x00,0x00,0x00, 0x00,0x00,0x00, - 0xff,0x00,0x00, 0xff,0x00,0x00, 0x00,0x00,0xff, 0x00,0x00,0xff, - 0xff,0x00,0x00, 0xff,0x00,0x00, 0x00,0x00,0xff, 0x00,0x00,0xff, + const MipLevelData rgb8_level0 = { + std::byte{0xff},std::byte{0xff},std::byte{0xff}, std::byte{0xff},std::byte{0xff},std::byte{0xff}, std::byte{0x00},std::byte{0x00},std::byte{0x00}, std::byte{0x00},std::byte{0x00},std::byte{0x00}, + std::byte{0xff},std::byte{0xff},std::byte{0xff}, std::byte{0xff},std::byte{0xff},std::byte{0xff}, std::byte{0x00},std::byte{0x00},std::byte{0x00}, std::byte{0x00},std::byte{0x00},std::byte{0x00}, + std::byte{0xff},std::byte{0x00},std::byte{0x00}, std::byte{0xff},std::byte{0x00},std::byte{0x00}, std::byte{0x00},std::byte{0x00},std::byte{0xff}, std::byte{0x00},std::byte{0x00},std::byte{0xff}, + std::byte{0xff},std::byte{0x00},std::byte{0x00}, std::byte{0xff},std::byte{0x00},std::byte{0x00}, std::byte{0x00},std::byte{0x00},std::byte{0xff}, std::byte{0x00},std::byte{0x00},std::byte{0xff}, }; - const uint8_t rgb8_level1[] = { - 0xff,0xff,0x00, 0x00,0x00,0xff, - 0xff,0xff,0x00, 0x00,0x00,0xff + const MipLevelData rgb8_level1 = { + std::byte{0xff},std::byte{0xff},std::byte{0x00}, std::byte{0x00},std::byte{0x00},std::byte{0xff}, + std::byte{0xff},std::byte{0xff},std::byte{0x00}, std::byte{0x00},std::byte{0x00},std::byte{0xff} }; - const uint8_t rgb8_level2[] = { - 0x00,0xff,0x00 + const MipLevelData rgb8_level2 = { + std::byte{0x00},std::byte{0xff},std::byte{0x00} }; - const std::vector mipLevelData = { - ramses::MipLevelData(sizeof(rgb8_level0), rgb8_level0), - ramses::MipLevelData(sizeof(rgb8_level1), rgb8_level1), - ramses::MipLevelData(sizeof(rgb8_level2), rgb8_level2) - }; + const std::vector mipLevelData = { rgb8_level0, rgb8_level1, rgb8_level2 }; ramses::Texture2D* texture = m_scene.createTexture2D( ramses::ETextureFormat::RGB8, diff --git a/tests/integration/test-content/Texture3DScene.cpp b/tests/integration/test-content/Texture3DScene.cpp index f82ab4966..3b7cea67e 100644 --- a/tests/integration/test-content/Texture3DScene.cpp +++ b/tests/integration/test-content/Texture3DScene.cpp @@ -36,38 +36,34 @@ namespace ramses::internal ramses::vec3f{ 1.0f, 1.0f, 0.0f }}; m_vertexPositions = m_scene.createArrayResource(4u, vertexPositionsArray.data()); - const uint8_t rgb8Data_0[] = { - 0xff, 0x00, 0x00, - 0xff, 0x00, 0x00, - 0xff, 0x00, 0x00, - 0xff, 0x00, 0x00, - 0x00, 0xff, 0x00, - 0x00, 0xff, 0x00, - 0x00, 0xff, 0x00, - 0x00, 0xff, 0x00, - 0x00, 0x00, 0xff, - 0x00, 0x00, 0xff, - 0x00, 0x00, 0xff, - 0x00, 0x00, 0xff, - 0x00, 0xff, 0xff, - 0x00, 0xff, 0xff, - 0x00, 0xff, 0xff, - 0x00, 0xff, 0xff }; - - const uint8_t rgb8Data_1[] = { - 0xff, 0x00, 0x00, - 0x00, 0xff, 0x00, + const MipLevelData rgb8Data_0 = { + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, + std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, + std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, + std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, + std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, + std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, + std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, + std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, + std::byte{0x00}, std::byte{0x00}, std::byte{0xff}, + std::byte{0x00}, std::byte{0xff}, std::byte{0xff}, + std::byte{0x00}, std::byte{0xff}, std::byte{0xff}, + std::byte{0x00}, std::byte{0xff}, std::byte{0xff}, + std::byte{0x00}, std::byte{0xff}, std::byte{0xff} }; + + const MipLevelData rgb8Data_1 = { + std::byte{0xff}, std::byte{0x00}, std::byte{0x00}, + std::byte{0x00}, std::byte{0xff}, std::byte{0x00}, }; - const uint8_t rgb8Data_2[] = { - 0xff, 0xff, 0x00, + const MipLevelData rgb8Data_2 = { + std::byte{0xff}, std::byte{0xff}, std::byte{0x00}, }; - const std::vector mipLevelData = { - ramses::MipLevelData(sizeof(rgb8Data_0), rgb8Data_0), - ramses::MipLevelData(sizeof(rgb8Data_1), rgb8Data_1), - ramses::MipLevelData(sizeof(rgb8Data_2), rgb8Data_2) - }; + const std::vector mipLevelData = { rgb8Data_0, rgb8Data_1, rgb8Data_2 }; m_texture = m_scene.createTexture3D( ramses::ETextureFormat::RGB8, diff --git a/tests/integration/test-content/TextureBufferScene.cpp b/tests/integration/test-content/TextureBufferScene.cpp index 3d350f53e..c5c60ac56 100644 --- a/tests/integration/test-content/TextureBufferScene.cpp +++ b/tests/integration/test-content/TextureBufferScene.cpp @@ -87,39 +87,45 @@ namespace ramses::internal void TextureBufferScene::setState(uint32_t state) { + auto toByteVector = [](std::initializer_list values) { + std::vector vec(values.size()); + std::transform(values.begin(), values.end(), vec.begin(), [](auto v) { return std::byte{ v }; }); + return vec; + }; + // Gradients of monochrome texels in different colors - const uint8_t rgba_1x1_red[] = { 255, 0, 0, 255 }; - const uint8_t rgba_2x2_yellow[] = + const auto rgba_1x1_red = toByteVector({ 255, 0, 0, 255 }); + const auto rgba_2x2_yellow = toByteVector( { 64 , 64, 0, 255 , 128, 128, 0, 255, 192, 192, 0, 255 , 255, 255, 0, 255 - }; - const uint8_t rgba_2x2_green[] = + }); + const auto rgba_2x2_green = toByteVector( { 0, 64 , 0, 255 , 0, 128, 0, 255, 0, 192, 0, 255 , 0, 255, 0, 255 - }; - const uint8_t rgba_4x4_blue[] = { + }); + const auto rgba_4x4_blue = toByteVector({ 0, 0, 16 , 255 , 0, 0, 32 , 255 , 0, 0, 48 , 255 , 0, 0, 64 , 255, 0, 0, 80 , 255 , 0, 0, 96 , 255 , 0, 0, 112, 255 , 0, 0, 128, 255, 0, 0, 144, 255 , 0, 0, 160, 255 , 0, 0, 176, 255 , 0, 0, 192, 255, - 0, 0, 208, 255 , 0, 0, 224, 255 , 0, 0, 240, 255 , 0, 0, 255, 255 }; - const uint8_t rgba_4x4_red[] = { + 0, 0, 208, 255 , 0, 0, 224, 255 , 0, 0, 240, 255 , 0, 0, 255, 255 }); + const auto rgba_4x4_red = toByteVector({ 16 , 0, 0, 255 , 32 , 0, 0, 255 , 48 , 0, 0, 255 , 64 , 0, 0, 255, 80 , 0, 0, 255 , 96 , 0, 0, 255 , 112, 0, 0, 255 , 128, 0, 0, 255, 144, 0, 0, 255 , 160, 0, 0, 255 , 176, 0, 0, 255 , 192, 0, 0, 255, - 208, 0, 0, 255 , 224, 0, 0, 255 , 240, 0, 0, 255 , 255, 0, 0, 255 }; + 208, 0, 0, 255 , 224, 0, 0, 255 , 240, 0, 0, 255 , 255, 0, 0, 255 }); // same, but in RG8 format - const uint8_t rg_1x1_black[] = { 0, 0 }; - const uint8_t rg_2x2_green[] = { + const auto rg_1x1_black = toByteVector({ 0, 0 }); + const auto rg_2x2_green = toByteVector({ 0, 64, 0, 128, - 0, 192, 0, 255 }; - const uint8_t rg_4x4_red[] = { + 0, 192, 0, 255 }); + const auto rg_4x4_red = toByteVector({ 16 , 0 , 32 , 0 ,48 , 0 , 64 , 0, 80 , 0 , 96 , 0 ,112, 0 , 128, 0, 144, 0 , 160, 0 ,176, 0 , 192, 0, - 208, 0 , 224, 0 ,240, 0 , 255, 0 }; + 208, 0 , 224, 0 ,240, 0 , 255, 0 }); const ramses::TextureSampler* sampler = nullptr; int32_t mipToFetch = -1; @@ -131,7 +137,7 @@ namespace ramses::internal { assert(m_textureBuffer == nullptr); m_textureBuffer = m_scene.createTexture2DBuffer(ramses::ETextureFormat::RGBA8, 4u, 4u, 1); - m_textureBuffer->updateData(0, 0, 0, 4, 4, rgba_4x4_blue); + m_textureBuffer->updateData(0, 0, 0, 4, 4, rgba_4x4_blue.data()); sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Nearest_MipMapNearest, ramses::ETextureSamplingMethod::Nearest, *m_textureBuffer); mipToFetch = 0; break; @@ -140,9 +146,9 @@ namespace ramses::internal { assert(m_textureBuffer == nullptr); m_textureBuffer = m_scene.createTexture2DBuffer(ramses::ETextureFormat::RGBA8, 4u, 4u, 3); - m_textureBuffer->updateData(0, 0, 0, 4, 4, rgba_4x4_blue); - m_textureBuffer->updateData(1, 0, 0, 2, 2, rgba_2x2_green); - m_textureBuffer->updateData(2, 0, 0, 1, 1, rgba_1x1_red); + m_textureBuffer->updateData(0, 0, 0, 4, 4, rgba_4x4_blue.data()); + m_textureBuffer->updateData(1, 0, 0, 2, 2, rgba_2x2_green.data()); + m_textureBuffer->updateData(2, 0, 0, 1, 1, rgba_1x1_red.data()); sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Nearest_MipMapNearest, ramses::ETextureSamplingMethod::Nearest, *m_textureBuffer); break; } @@ -150,25 +156,25 @@ namespace ramses::internal { assert(m_textureBuffer == nullptr); m_textureBuffer = m_scene.createTexture2DBuffer(ramses::ETextureFormat::RGBA8, 4u, 4u, 1); - m_textureBuffer->updateData(0, 0, 0, 4, 4, rgba_4x4_blue); + m_textureBuffer->updateData(0, 0, 0, 4, 4, rgba_4x4_blue.data()); sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Nearest_MipMapNearest, ramses::ETextureSamplingMethod::Nearest, *m_textureBuffer); // update - m_textureBuffer->updateData(0, 1, 1, 2, 2, rgba_2x2_green); + m_textureBuffer->updateData(0, 1, 1, 2, 2, rgba_2x2_green.data()); mipToFetch = 0; break; } case EState_PartialUpdate1: assert(m_textureBuffer); - m_textureBuffer->updateData(0, 1, 1, 2, 2, rgba_2x2_yellow); + m_textureBuffer->updateData(0, 1, 1, 2, 2, rgba_2x2_yellow.data()); sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Nearest_MipMapNearest, ramses::ETextureSamplingMethod::Nearest, *m_textureBuffer); mipToFetch = 0; break; case EState_PartialUpdate2: assert(m_textureBuffer); - m_textureBuffer->updateData(0, 1, 1, 1, 1, rgba_1x1_red); - m_textureBuffer->updateData(0, 1, 2, 1, 1, rgba_1x1_red); + m_textureBuffer->updateData(0, 1, 1, 1, 1, rgba_1x1_red.data()); + m_textureBuffer->updateData(0, 1, 2, 1, 1, rgba_1x1_red.data()); sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Nearest_MipMapNearest, ramses::ETextureSamplingMethod::Nearest, *m_textureBuffer); mipToFetch = 0; break; @@ -176,13 +182,13 @@ namespace ramses::internal { assert(m_textureBuffer == nullptr); m_textureBuffer = m_scene.createTexture2DBuffer(ramses::ETextureFormat::RGBA8, 4u, 4u, 3); - m_textureBuffer->updateData(0, 0, 0, 4, 4, rgba_4x4_blue); - m_textureBuffer->updateData(1, 0, 0, 2, 2, rgba_2x2_green); - m_textureBuffer->updateData(2, 0, 0, 1, 1, rgba_1x1_red); + m_textureBuffer->updateData(0, 0, 0, 4, 4, rgba_4x4_blue.data()); + m_textureBuffer->updateData(1, 0, 0, 2, 2, rgba_2x2_green.data()); + m_textureBuffer->updateData(2, 0, 0, 1, 1, rgba_1x1_red.data()); sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Nearest_MipMapNearest, ramses::ETextureSamplingMethod::Nearest, *m_textureBuffer); // update - m_textureBuffer->updateData(1, 1, 1, 1, 1, rgba_1x1_red); + m_textureBuffer->updateData(1, 1, 1, 1, 1, rgba_1x1_red.data()); mipToFetch = 1; break; @@ -191,21 +197,20 @@ namespace ramses::internal { assert(m_textureBuffer == nullptr); m_textureBuffer = m_scene.createTexture2DBuffer(ramses::ETextureFormat::RG8, 4u, 4u, 3); - m_textureBuffer->updateData(0, 0, 0, 4, 4, rg_4x4_red); - m_textureBuffer->updateData(1, 0, 0, 2, 2, rg_2x2_green); - m_textureBuffer->updateData(2, 0, 0, 1, 1, rg_1x1_black); + m_textureBuffer->updateData(0, 0, 0, 4, 4, rg_4x4_red.data()); + m_textureBuffer->updateData(1, 0, 0, 2, 2, rg_2x2_green.data()); + m_textureBuffer->updateData(2, 0, 0, 1, 1, rg_1x1_black.data()); sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Nearest_MipMapNearest, ramses::ETextureSamplingMethod::Nearest, *m_textureBuffer); // update - m_textureBuffer->updateData(1, 1, 1, 1, 1, rg_1x1_black); + m_textureBuffer->updateData(1, 1, 1, 1, 1, rg_1x1_black.data()); mipToFetch = 1; break; } case EState_ClientTextureResource_RGBA8: { - const ramses::MipLevelData mip2x2(sizeof(rgba_2x2_green), rgba_2x2_green); - const std::vector mips = { mip2x2 }; + const std::vector mips = { rgba_2x2_green }; m_clientTexture = m_scene.createTexture2D(ramses::ETextureFormat::RGBA8, 2u, 2u, mips); sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Nearest_MipMapNearest, ramses::ETextureSamplingMethod::Nearest, *m_clientTexture); mipToFetch = 0; @@ -223,7 +228,7 @@ namespace ramses::internal { assert(nullptr != m_textureBuffer); sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Nearest_MipMapNearest, ramses::ETextureSamplingMethod::Nearest, *m_textureBuffer); - m_textureBuffer->updateData(0, 0, 0, 4, 4, rgba_4x4_red); + m_textureBuffer->updateData(0, 0, 0, 4, 4, rgba_4x4_red.data()); mipToFetch = 0; break; } diff --git a/tests/integration/test-content/TextureCubeAnisotropicTextureFilteringScene.cpp b/tests/integration/test-content/TextureCubeAnisotropicTextureFilteringScene.cpp index 366c5c52c..11e98f70e 100644 --- a/tests/integration/test-content/TextureCubeAnisotropicTextureFilteringScene.cpp +++ b/tests/integration/test-content/TextureCubeAnisotropicTextureFilteringScene.cpp @@ -36,7 +36,7 @@ namespace ramses::internal { - void TextureCubeAnisotropicTextureFilteringScene::FillMipLevelData(uint8_t* data, uint32_t resolution, uint32_t level) + void TextureCubeAnisotropicTextureFilteringScene::FillMipLevelData(std::byte* data, uint32_t resolution, uint32_t level) { switch (level) { @@ -46,39 +46,39 @@ namespace ramses::internal { for (uint32_t x = 0; x < resolution / 4; x++) { - *data++ = 0x00; - *data++ = 0x00; - *data++ = 0xff; + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); + *data++ = static_cast(0xff); - *data++ = 0x00; - *data++ = 0xff; - *data++ = 0x00; + *data++ = static_cast(0x00); + *data++ = static_cast(0xff); + *data++ = static_cast(0x00); - *data++ = 0x00; - *data++ = 0x00; - *data++ = 0x00; + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); - *data++ = 0x00; - *data++ = 0x00; - *data++ = 0x00; + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); } for (uint32_t x = 0; x < resolution / 4; x++) { - *data++ = 0x00; - *data++ = 0x00; - *data++ = 0x00; + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); - *data++ = 0x00; - *data++ = 0x00; - *data++ = 0x00; + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); - *data++ = 0x00; - *data++ = 0x00; - *data++ = 0xff; + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); + *data++ = static_cast(0xff); - *data++ = 0x00; - *data++ = 0xff; - *data++ = 0x00; + *data++ = static_cast(0x00); + *data++ = static_cast(0xff); + *data++ = static_cast(0x00); } } break; @@ -90,9 +90,9 @@ namespace ramses::internal { for (uint32_t x = 0; x < resolution; x++) { - *data++ = 0xff; - *data++ = 0x00; - *data++ = 0x00; + *data++ = static_cast(0xff); + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); } } break; @@ -103,9 +103,9 @@ namespace ramses::internal { for (uint32_t x = 0; x < resolution; x++) { - *data++ = 0x00; - *data++ = 0x00; - *data++ = 0xff; + *data++ = static_cast(0x00); + *data++ = static_cast(0x00); + *data++ = static_cast(0xff); } } break; @@ -129,18 +129,16 @@ namespace ramses::internal { const uint32_t resolution = textureResolution >> i; const uint32_t levelSize = resolution * resolution * 3; - auto* rgb8_data = new uint8_t[levelSize]; - FillMipLevelData(rgb8_data, resolution, i); - - mipLevelData.emplace_back(CubeMipLevelData( - levelSize, - reinterpret_cast(rgb8_data), - reinterpret_cast(rgb8_data), - reinterpret_cast(rgb8_data), - reinterpret_cast(rgb8_data), - reinterpret_cast(rgb8_data), - reinterpret_cast(rgb8_data) - )); + MipLevelData rgb8_data(levelSize); + FillMipLevelData(rgb8_data.data(), resolution, i); + + mipLevelData.emplace_back(CubeMipLevelData{ + rgb8_data, + rgb8_data, + rgb8_data, + rgb8_data, + rgb8_data, + rgb8_data }); } ramses::Effect* effect(getTestEffect("ramses-test-client-textured-cube")); @@ -179,10 +177,6 @@ namespace ramses::internal mipLevelData, false); - for (auto& data : mipLevelData) - { - delete[] data.m_dataNX; - } mipLevelData.clear(); std::optional textureInput = effect->findUniformInput("u_texture"); diff --git a/tests/integration/test-content/TextureLinkScene.cpp b/tests/integration/test-content/TextureLinkScene.cpp index d69dc5c93..4c4d960c0 100644 --- a/tests/integration/test-content/TextureLinkScene.cpp +++ b/tests/integration/test-content/TextureLinkScene.cpp @@ -88,8 +88,7 @@ namespace ramses::internal case DATA_PROVIDER_LARGE: case DATA_PROVIDER: { - const std::array pxData{ {0xff, 0x0, 0x0, 0xff} }; - const std::vector mipLevelData{ MipLevelData(4, pxData.data()) }; + const std::vector mipLevelData{ { std::byte{0xff}, std::byte{0x0}, std::byte{0x0}, std::byte{0xff} } }; const ramses::Texture2D& texture = *m_scene.createTexture2D(ramses::ETextureFormat::RGBA8, 1u, 1u, mipLevelData, false, {}, "ProviderTexture"); const ramses::TextureSampler& sampler = createSampler(texture); SetSampler(appearance1, sampler); @@ -100,8 +99,7 @@ namespace ramses::internal break; case DATA_CONSUMER: { - const std::array pxData{ { 0x0, 0xff, 0x0, 0xff } }; - const std::vector mipLevelData{ MipLevelData(4, pxData.data()) }; + const std::vector mipLevelData{ { std::byte{0x0}, std::byte{0xff}, std::byte{0x0}, std::byte{0xff} } }; const ramses::Texture2D& texture = *m_scene.createTexture2D(ramses::ETextureFormat::RGBA8, 1u, 1u, mipLevelData, false, {}, "ConsumerTexture"); const ramses::TextureSampler& sampler = createSampler(texture); SetSampler(appearance1, sampler); @@ -142,8 +140,7 @@ namespace ramses::internal case DATA_CONSUMER_AND_PROVIDER_LARGE: case DATA_CONSUMER_AND_PROVIDER: { - const std::array pxData{ { 0x0, 0x0, 0xff, 0xff } }; - const std::vector mipLevelData{ MipLevelData(4, pxData.data()) }; + const std::vector mipLevelData{ { std::byte{0x0}, std::byte{0x0}, std::byte{0xff}, std::byte{0xff} } }; const ramses::Texture2D& texture = *m_scene.createTexture2D(ramses::ETextureFormat::RGBA8, 1u, 1u, mipLevelData, false, {}, "ConsumerProviderTexture"); const ramses::TextureSampler& sampler1 = createSampler(texture); const ramses::TextureSampler& sampler2 = createSampler(texture); diff --git a/tests/integration/test-content/TextureSamplerScene.cpp b/tests/integration/test-content/TextureSamplerScene.cpp index 63e5e927f..572b1f644 100644 --- a/tests/integration/test-content/TextureSamplerScene.cpp +++ b/tests/integration/test-content/TextureSamplerScene.cpp @@ -31,12 +31,12 @@ namespace ramses::internal TextureSamplerScene::TextureSamplerScene(ramses::Scene& scene, uint32_t state, const glm::vec3& cameraPosition) : IntegrationScene(scene, cameraPosition) { - const uint8_t rgb8[] = + std::vector rgb8 = { - 0xff,0xff,0xff, 0x00,0x00,0x00, - 0xff,0x00,0x00, 0x00,0x00,0xff, + std::byte{0xff},std::byte{0xff},std::byte{0xff}, std::byte{0x00},std::byte{0x00},std::byte{0x00}, + std::byte{0xff},std::byte{0x00},std::byte{0x00}, std::byte{0x00},std::byte{0x00},std::byte{0xff} }; - const std::vector mipLevelData = { MipLevelData{ sizeof(rgb8), rgb8 } }; + const std::vector mipLevelData = { rgb8 }; if (state == EState::EState_ClientTexture) { @@ -46,7 +46,7 @@ namespace ramses::internal else if (state == EState::EState_TextureBuffer) { ramses::Texture2DBuffer* texture = m_scene.createTexture2DBuffer(ramses::ETextureFormat::RGB8, 2, 2, 1); - texture->updateData(0, 0, 0, 2, 2, rgb8); + texture->updateData(0, 0, 0, 2, 2, rgb8.data()); m_sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Repeat, ramses::ETextureAddressMode::Repeat, ramses::ETextureSamplingMethod::Nearest, ramses::ETextureSamplingMethod::Nearest, *texture); } @@ -93,18 +93,18 @@ namespace ramses::internal void TextureSamplerScene::setState(uint32_t state) { - const uint8_t rgb8[] = + std::vector rgb8 = { - 0xff,0xff,0xff, 0xff,0x00,0xff, 0x00,0xff,0x00, - 0x00,0xff,0xff, 0xff,0xff,0x00, 0x00,0x00,0x00, - 0xff,0x00,0x00, 0xff,0x00,0xff, 0x00,0x00,0xff + std::byte{0xff},std::byte{0xff},std::byte{0xff}, std::byte{0xff},std::byte{0x00},std::byte{0xff}, std::byte{0x00},std::byte{0xff},std::byte{0x00}, + std::byte{0x00},std::byte{0xff},std::byte{0xff}, std::byte{0xff},std::byte{0xff},std::byte{0x00}, std::byte{0x00},std::byte{0x00},std::byte{0x00}, + std::byte{0xff},std::byte{0x00},std::byte{0x00}, std::byte{0xff},std::byte{0x00},std::byte{0xff}, std::byte{0x00},std::byte{0x00},std::byte{0xff} }; switch (state) { case EState::EState_SetClientTexture: { - const std::vector mipLevelData = { MipLevelData{ sizeof(rgb8), rgb8 } }; + const std::vector mipLevelData = { rgb8 }; const ramses::Texture2D* texture = m_scene.createTexture2D(ramses::ETextureFormat::RGB8, 3, 3, mipLevelData, false); m_sampler->setTextureData(*texture); break; @@ -112,7 +112,7 @@ namespace ramses::internal case EState::EState_SetTextureBuffer: { ramses::Texture2DBuffer* texture = m_scene.createTexture2DBuffer(ramses::ETextureFormat::RGB8, 3, 3, 1); - texture->updateData(0, 0, 0, 3, 3, rgb8); + texture->updateData(0, 0, 0, 3, 3, rgb8.data()); m_sampler->setTextureData(*texture); break; } @@ -137,7 +137,7 @@ namespace ramses::internal case EState_SetTextureSampler: { - const std::vector mipLevelData = { MipLevelData{ sizeof(rgb8), rgb8 } }; + const std::vector mipLevelData = { rgb8 }; const ramses::Texture2D* texture = m_scene.createTexture2D(ramses::ETextureFormat::RGB8, 3, 3, mipLevelData, false); m_sampler = m_scene.createTextureSampler(ramses::ETextureAddressMode::Repeat, ramses::ETextureAddressMode::Repeat, ramses::ETextureSamplingMethod::Nearest, ramses::ETextureSamplingMethod::Nearest, *texture); diff --git a/tests/integration/logic-viewer-tests/CMakeLists.txt b/tests/integration/viewer-tests/CMakeLists.txt similarity index 81% rename from tests/integration/logic-viewer-tests/CMakeLists.txt rename to tests/integration/viewer-tests/CMakeLists.txt index fff4f956e..48c3cc5f5 100644 --- a/tests/integration/logic-viewer-tests/CMakeLists.txt +++ b/tests/integration/viewer-tests/CMakeLists.txt @@ -13,22 +13,22 @@ if(NOT ImageMagick_FOUND) endif() createModule( - NAME ramses-logic-viewer-gui-test + NAME ramses-viewer-gui-test TYPE BINARY ENABLE_INSTALL ${ramses-sdk_ENABLE_INSTALL} - INCLUDE_PATHS ${PROJECT_SOURCE_DIR}/tools/ramses-logic-viewer + INCLUDE_PATHS ${PROJECT_SOURCE_DIR}/tools/ramses-viewer ${PROJECT_SOURCE_DIR}/tests/unittests/client/logic/shared SRC_FILES LogicViewerAppTest.cpp RESOURCE_FOLDERS res PUBLIC_DEFINES MAGICK_COMPARE="${ImageMagick_compare_EXECUTABLE}" - DEPENDENCIES ramses-logic-viewer-gui-lib - ramses-shared-lib + DEPENDENCIES ramses-viewer-gui-lib + ramses-renderer ramses-gmock ramses-gmock-main ) MakeTestFromTarget( - TARGET ramses-logic-viewer-gui-test + TARGET ramses-viewer-gui-test SUFFIX RNDSANDWICHTEST_SWRAST) diff --git a/tests/integration/logic-viewer-tests/LogicViewerAppTest.cpp b/tests/integration/viewer-tests/LogicViewerAppTest.cpp similarity index 59% rename from tests/integration/logic-viewer-tests/LogicViewerAppTest.cpp rename to tests/integration/viewer-tests/LogicViewerAppTest.cpp index 02bfd7d92..68eff4e8e 100644 --- a/tests/integration/logic-viewer-tests/LogicViewerAppTest.cpp +++ b/tests/integration/viewer-tests/LogicViewerAppTest.cpp @@ -7,10 +7,10 @@ // ------------------------------------------------------------------------- #include "ramses-sdk-build-config.h" -#include "LogicViewerGuiApp.h" -#include "LogicViewerHeadlessApp.h" +#include "ViewerGuiApp.h" +#include "ViewerHeadlessApp.h" #include "LogicViewer.h" -#include "LogicViewerSettings.h" +#include "ViewerSettings.h" #include "gmock/gmock.h" #include "RamsesTestUtils.h" #include "WithTempDirectory.h" @@ -29,6 +29,7 @@ #include "ramses/client/logic/LuaInterface.h" #include "ramses/client/logic/LuaScript.h" #include "ramses/client/logic/SkinBinding.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/ramses-client.h" #include "ImguiClientHelper.h" #include "fmt/format.h" @@ -85,6 +86,10 @@ const auto defaultLuaFile = R"(function default() rlogic.meshNodeBindings["myMeshNode"]["IN"]["instanceCount"].value = 1 --Anchor points --Skin bindings + --RenderBuffer bindings + rlogic.renderBufferBindings["myRenderBuffer"]["IN"]["width"].value = 1 + rlogic.renderBufferBindings["myRenderBuffer"]["IN"]["height"].value = 2 + rlogic.renderBufferBindings["myRenderBuffer"]["IN"]["sampleCount"].value = 3 end @@ -109,13 +114,12 @@ end )"; const auto iniFile = R"( -[Window][Logic Viewer (FeatureLevel 01)] +[Window][LogicEngine[10]] Pos=0,0 Size=540,720 Collapsed=0 -[LogicViewerGui][Settings] -ShowWindow=1 +[ramses-viewer][Settings] ShowInterfaces=1 ShowScripts=1 ShowAnimationNodes=1 @@ -127,7 +131,6 @@ ShowLinkedInputs=1 ShowOutputs=1 LuaPreferObjectIds=0 LuaPreferIdentifiers=0 -ShowDisplaySettings=0 )"; class UI @@ -143,91 +146,20 @@ class UI const int32_t hline = 4; const int32_t yMiddle = padding + fontHeight / 2; // half height of a button - void setup(const ramses::LogicViewerSettings* settings) + void setup(const ramses::internal::ViewerSettings* settings) { m_settings = settings; } - [[nodiscard]] int32_t interfaces() const + [[nodiscard]] int32_t updateReport() const { // there's an extra line in the view section if update report is enabled const bool showUpdateReport = m_settings ? m_settings->showUpdateReport : false; return 86 + yMiddle + (showUpdateReport ? 20 : 0); } - [[nodiscard]] int32_t scripts() const - { - return interfaces() + buttonHeight; - } - - [[nodiscard]] int32_t animationNodes() const - { - return scripts() + buttonHeight; - } - - [[nodiscard]] int32_t timerNodes() const - { - return animationNodes() + buttonHeight; - } - - [[nodiscard]] int32_t dataArrays() const - { - return timerNodes() + buttonHeight; - } - - [[nodiscard]] int32_t appearanceBindings() const - { - return dataArrays() + buttonHeight; - } - - [[nodiscard]] int32_t nodeBindings() const - { - return appearanceBindings() + buttonHeight; - } - - [[nodiscard]] int32_t cameraBindings() const - { - return nodeBindings() + buttonHeight; - } - - [[nodiscard]] int32_t renderPassBindings() const - { - return cameraBindings() + buttonHeight; - } - - [[nodiscard]] int32_t renderGroupBindings() const - { - return renderPassBindings() + buttonHeight; - } - - [[nodiscard]] int32_t meshNodeBindings() const - { - return renderGroupBindings() + buttonHeight; - } - - [[nodiscard]] int32_t anchorPoints() const - { - return meshNodeBindings() + buttonHeight; - } - - [[nodiscard]] int32_t skinBindings() const - { - return anchorPoints() + buttonHeight; - } - - [[nodiscard]] int32_t displaySettings() const - { - const bool showUpdateReport = m_settings ? m_settings->showUpdateReport : false; - return updateReport() + (showUpdateReport ? buttonHeight : 0); - } - - [[nodiscard]] int32_t updateReport() const - { - return skinBindings() + buttonHeight; - } - private: - const ramses::LogicViewerSettings* m_settings = nullptr; + const ramses::internal::ViewerSettings* m_settings = nullptr; }; std::string rtrim(const std::string& str) @@ -239,6 +171,7 @@ std::string rtrim(const std::string& str) namespace ramses::internal { + const char* const emptySceneFile = "ALogicViewerAppTestEmptyScene.ramses"; const char* const ramsesFile = "ALogicViewerAppTest.ramses"; const char* const luaFile = "ALogicViewerAppTest.lua"; @@ -291,6 +224,7 @@ namespace ramses::internal { setupLogic(); [[maybe_unused]] auto status = m_scene.scene->saveToFile(ramsesFile, {}); + [[maybe_unused]] auto status2 = m_emptyScene->saveToFile(emptySceneFile, {}); auto handler = [&](ELogLevel level, std::string_view context, std::string_view msg) { m_log.add(level, context, msg); }; ramses::RamsesFramework::SetLogHandler(handler); } @@ -386,8 +320,8 @@ namespace ramses::internal rgElements.addElement(*m_scene.meshNode, "myMeshNode"); engine.createRenderGroupBinding(*m_scene.renderGroup, rgElements, "myRenderGroup"); engine.createMeshNodeBinding(*m_scene.meshNode, "myMeshNode"); - engine.createTimerNode("myTimer"); + engine.createRenderBufferBinding(*m_scene.renderBuffer, "myRenderBuffer"); ramses::DataArray* animTimestamps = engine.createDataArray(std::vector{ 0.f, 0.5f, 1.f, 1.5f }); // will be interpreted as seconds ramses::DataArray* animKeyframes = engine.createDataArray(std::vector{ {0.f, 0.f, 0.f}, {0.f, 0.f, 180.f}, {0.f, 0.f, 100.f}, {0.f, 0.f, 360.f} }); @@ -402,13 +336,17 @@ namespace ramses::internal engine.update(); } - void createApp(const std::vector& argsList = {}) + [[nodiscard]] int createApp(const std::vector& argsList = {}) { std::vector args; args.resize(argsList.size()); std::transform(argsList.begin(), argsList.end(), args.begin(), [](const auto& str) { return str.c_str(); }); args.insert(args.begin(), "viewer"); // 1st is executable name to comply with standard application args - m_app = std::make_unique(static_cast(args.size()), args.data()); + m_cli = std::make_unique(); + m_app = std::make_unique(); + m_app->registerOptions(*m_cli); + CLI11_PARSE(*m_cli, static_cast(args.size()), args.data()); + return 0; } [[nodiscard]] bool runUntil(const std::string& message) @@ -495,16 +433,18 @@ namespace ramses::internal protected: WithTempDirectory m_withTempDirectory; RamsesTestSetup m_ramses; - TriangleTestScene m_scene = {m_ramses.createTriangleTestScene()}; + TriangleTestScene m_scene = m_ramses.createTriangleTestScene(ramses::sceneId_t(1)); + Scene* m_emptyScene = m_ramses.createScene(ramses::sceneId_t(2)); LogHandler m_log; + std::unique_ptr m_cli; std::unique_ptr m_app; }; - class ALogicViewerGuiApp : public ALogicViewerAppBase, public ::testing::Test + class ALogicViewerGuiApp : public ALogicViewerAppBase, public ::testing::Test { }; - class ALogicViewerHeadlessApp : public ALogicViewerAppBase, public ::testing::Test + class ALogicViewerHeadlessApp : public ALogicViewerAppBase, public ::testing::Test { }; @@ -513,18 +453,19 @@ namespace ramses::internal { }; - using LogicViewerAppTypes = ::testing::Types< LogicViewerGuiApp, LogicViewerHeadlessApp>; + using LogicViewerAppTypes = ::testing::Types< ViewerGuiApp, ViewerHeadlessApp>; TYPED_TEST_SUITE(ALogicViewerApp_T, LogicViewerAppTypes); - class ALogicViewerAppUIBase : public ALogicViewerAppBase + class ALogicViewerAppUIBase : public ALogicViewerAppBase { public: void setup(std::string_view ini, std::vector args = {}) { SaveFile(ini, "imgui.ini"); args.emplace_back(ramsesFile); - this->createApp(args); + EXPECT_EQ(0, this->createApp(args)); + EXPECT_EQ(ViewerApp::ExitCode::Ok, m_app->setup()); ui.setup(m_app->getSettings()); ImGui::GetIO().GetClipboardTextFn = GetClipboardText; @@ -541,6 +482,7 @@ namespace ramses::internal EXPECT_TRUE(m_app->doOneLoop()); imgui->mouseEvent(ramses::displayId_t(0), ramses::EMouseEvent::LeftButtonUp, x, y); EXPECT_TRUE(m_app->doOneLoop()); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); // give some time to render return m_app->doOneLoop(); } @@ -552,6 +494,7 @@ namespace ramses::internal EXPECT_TRUE(m_app->doOneLoop()); imgui->mouseEvent(ramses::displayId_t(0), ramses::EMouseEvent::RightButtonUp, x, y); EXPECT_TRUE(m_app->doOneLoop()); + std::this_thread::sleep_for(std::chrono::milliseconds(20)); // give some time to render return m_app->doOneLoop(); } @@ -609,7 +552,7 @@ namespace ramses::internal ALogicViewerAppUI() { // use --offscreen to get screenshots without ui - setup(iniFile, {"--offscreen"}); + setup(iniFile, {"--gui=on"}); } }; @@ -627,64 +570,46 @@ namespace ramses::internal EXPECT_EQ("143262", str); // image differences } - TYPED_TEST(ALogicViewerApp_T, nullparameter) - { - TypeParam app(0, nullptr); - EXPECT_EQ(-1, app.run()); - EXPECT_EQ(-1, app.exitCode()); - } - TYPED_TEST(ALogicViewerApp_T, emptyParam) { - this->createApp(); - EXPECT_EQ(static_cast(CLI::ExitCodes::RequiredError), this->m_app->run()); - EXPECT_EQ(static_cast(CLI::ExitCodes::RequiredError), this->m_app->exitCode()); + EXPECT_EQ(static_cast(CLI::ExitCodes::RequiredError), this->createApp()); } TYPED_TEST(ALogicViewerApp_T, version) { testing::internal::CaptureStdout(); - this->createApp({ "--version" }); + EXPECT_EQ(0, this->createApp({ "--version" })); EXPECT_THAT(testing::internal::GetCapturedStdout(), testing::StartsWith(ramses_sdk::RAMSES_SDK_RAMSES_VERSION)); - EXPECT_EQ(0, this->m_app->run()); } TYPED_TEST(ALogicViewerApp_T, ramsesFileDoesNotExist) { testing::internal::CaptureStderr(); - this->createApp({ "notExisting.ramses" }); - EXPECT_EQ(static_cast(CLI::ExitCodes::ValidationError), this->m_app->run()); + EXPECT_EQ(static_cast(CLI::ExitCodes::ValidationError), this->createApp({"notExisting.ramses"})); EXPECT_THAT(testing::internal::GetCapturedStderr(), testing::HasSubstr("File does not exist: notExisting.ramses")); } TYPED_TEST(ALogicViewerApp_T, luaFileDoesNotExist) { testing::internal::CaptureStderr(); - this->createApp({ ramsesFile, "notExisting.lua" }); - EXPECT_EQ(static_cast(CLI::ExitCodes::ValidationError), this->m_app->run()); + EXPECT_EQ(static_cast(CLI::ExitCodes::ValidationError), this->createApp({ ramsesFile, "notExisting.lua" })); EXPECT_THAT(testing::internal::GetCapturedStderr(), testing::HasSubstr("File does not exist: notExisting.lua")); } TYPED_TEST(ALogicViewerApp_T, writeDefaultLuaConfiguration) { - this->createApp({ "--write-config", ramsesFile }); - auto* viewer = this->m_app->getViewer(); - ASSERT_TRUE(viewer != nullptr); - EXPECT_EQ(Result(), viewer->update()); - EXPECT_EQ(0, this->m_app->run()); + EXPECT_EQ(0, this->createApp({ "--write-config", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, this->m_app->run()); EXPECT_TRUE(fs::exists(luaFile)); std::ifstream str(luaFile); std::string genfile((std::istreambuf_iterator(str)), std::istreambuf_iterator()); EXPECT_EQ(defaultLuaFile, genfile); } - TYPED_TEST(ALogicViewerApp_T, writeDefaultLuaConfigurationHeadless) + TEST_F(ALogicViewerGuiApp, writeDefaultLuaConfigurationHeadless) { - this->createApp({ "--write-config", "--headless", ramsesFile }); - auto* viewer = this->m_app->getViewer(); - ASSERT_TRUE(viewer != nullptr); - EXPECT_EQ(Result(), viewer->update()); - EXPECT_EQ(0, this->m_app->run()); + EXPECT_EQ(0, this->createApp({ "--write-config", "--headless", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, this->m_app->run()); EXPECT_TRUE(fs::exists(luaFile)); std::ifstream str(luaFile); std::string genfile((std::istreambuf_iterator(str)), std::istreambuf_iterator()); @@ -693,11 +618,8 @@ namespace ramses::internal TYPED_TEST(ALogicViewerApp_T, writeDefaultLuaConfigurationToOtherFile) { - this->createApp({ "--write-config=foobar.lua", ramsesFile }); - auto* viewer = this->m_app->getViewer(); - ASSERT_TRUE(viewer != nullptr); - EXPECT_EQ(Result(), viewer->update()); - EXPECT_EQ(0, this->m_app->run()); + EXPECT_EQ(0, this->createApp({ "--write-config=foobar.lua", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, this->m_app->run()); EXPECT_TRUE(fs::exists("foobar.lua")); std::ifstream str("foobar.lua"); std::string genfile((std::istreambuf_iterator(str)), std::istreambuf_iterator()); @@ -706,7 +628,8 @@ namespace ramses::internal TEST_F(ALogicViewerGuiApp, runInteractive) { - createApp({ ramsesFile }); + EXPECT_EQ(0, createApp({ ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, m_app->setup()); EXPECT_TRUE(runUntil("is in state RENDERED caused by command SHOW")); EXPECT_TRUE(m_app->doOneLoop()); EXPECT_TRUE(m_app->doOneLoop()); @@ -714,27 +637,37 @@ namespace ramses::internal auto imgui = m_app->getImguiClientHelper(); imgui->windowClosed(ramses::displayId_t()); EXPECT_FALSE(m_app->doOneLoop()); - EXPECT_EQ(0, m_app->exitCode()); } - TEST_F(ALogicViewerHeadlessApp, runInteractive) + TEST_F(ALogicViewerGuiApp, runInteractiveWithEmptyScene) { - createApp({ ramsesFile }); + EXPECT_EQ(0, createApp({ emptySceneFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, m_app->setup()); + EXPECT_TRUE(runUntil("is in state RENDERED caused by command SHOW")); + EXPECT_TRUE(m_app->doOneLoop()); + EXPECT_TRUE(m_app->doOneLoop()); + EXPECT_TRUE(m_app->doOneLoop()); + auto imgui = m_app->getImguiClientHelper(); + imgui->windowClosed(ramses::displayId_t()); EXPECT_FALSE(m_app->doOneLoop()); - EXPECT_EQ(-1, m_app->run()); + } + + TEST_F(ALogicViewerHeadlessApp, runInteractive) + { + EXPECT_EQ(0, createApp({ ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, m_app->run()); } TYPED_TEST(ALogicViewerApp_T, exec_luaFileMissing) { // implicit filename testing::internal::CaptureStderr(); - this->createApp({ "--exec=test_default", ramsesFile }); - EXPECT_EQ(static_cast(LogicViewerApp::ExitCode::ErrorLoadLua), this->m_app->run()); + EXPECT_EQ(0, this->createApp({ "--exec=test_default", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::ErrorLoadLua, this->m_app->run()); EXPECT_THAT(testing::internal::GetCapturedStderr(), testing::HasSubstr("cannot open ALogicViewerAppTest.lua: No such file or directory")); // explicit filename testing::internal::CaptureStderr(); - this->createApp({ "--exec=test_default", "--lua=NotExistingLuaFile.lua", ramsesFile }); - EXPECT_EQ(static_cast(CLI::ExitCodes::ValidationError), this->m_app->run()); + EXPECT_EQ(static_cast(CLI::ExitCodes::ValidationError), this->createApp({ "--exec=test_default", "--lua=NotExistingLuaFile.lua", ramsesFile })); EXPECT_THAT(testing::internal::GetCapturedStderr(), testing::HasSubstr("File does not exist: NotExistingLuaFile.lua")); } @@ -748,8 +681,8 @@ namespace ramses::internal rlogic.screenshot("test_yellow.png") end )"); - createApp({ "--exec=test_default", ramsesFile }); - EXPECT_EQ(0, m_app->run()); + EXPECT_EQ(0, createApp({ "--exec=test_default", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, m_app->run()); EXPECT_TRUE(CompareImage("test_red.png", "ALogicViewerApp_red.png")); EXPECT_TRUE(CompareImage("test_yellow.png", "ALogicViewerApp_yellow.png")); } @@ -763,8 +696,8 @@ namespace ramses::internal rlogic.appearanceBindings.myAppearance.IN.green.value = 1 rlogic.screenshot("test_yellow.png") )"); - this->createApp({ "--exec=test_default", ramsesFile }); - EXPECT_EQ(static_cast(LogicViewerApp::ExitCode::ErrorLoadLua), this->m_app->run()); + EXPECT_EQ(0, this->createApp({ "--exec=test_default", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::ErrorLoadLua, this->m_app->run()); } TEST_F(ALogicViewerGuiApp, exec_lua_function) @@ -775,9 +708,9 @@ namespace ramses::internal rlogic.screenshot(filename) end )"); - createApp({ R"(--exec-lua=test_default('almost_yellow.png', 0.9))", ramsesFile }); - EXPECT_EQ(0, m_app->run()); - auto appearance = m_app->getViewer()->getLogic().findObject("myAppearance"); + EXPECT_EQ(0, createApp({ R"(--exec-lua=test_default('almost_yellow.png', 0.9))", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, m_app->run()); + auto appearance = m_app->getLogicViewer()->getLogic().findObject("myAppearance"); ASSERT_TRUE(appearance != nullptr); auto prop = appearance->getInputs()->getChild("green"); ASSERT_TRUE(prop != nullptr); @@ -787,9 +720,9 @@ namespace ramses::internal TYPED_TEST(ALogicViewerApp_T, exec_lua_code) { - this->createApp({ R"(--exec-lua=rlogic.appearanceBindings.myAppearance.IN.green.value = 0.44)", ramsesFile }); - EXPECT_EQ(0, this->m_app->run()); - auto appearance = this->m_app->getViewer()->getLogic().template findObject("myAppearance"); + EXPECT_EQ(0, this->createApp({ R"(--exec-lua=rlogic.appearanceBindings.myAppearance.IN.green.value = 0.44)", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, this->m_app->run()); + auto appearance = this->m_app->getLogicViewer()->getLogic().template findObject("myAppearance"); ASSERT_TRUE(appearance != nullptr); auto prop = appearance->getInputs()->getChild("green"); ASSERT_TRUE(prop != nullptr); @@ -799,27 +732,27 @@ namespace ramses::internal TYPED_TEST(ALogicViewerApp_T, exec_lua_error) { testing::internal::CaptureStderr(); - this->createApp({ R"(--exec-lua=rlogic.appearanceBindings.myAppearance.IN.green = 0.44)", ramsesFile }); + EXPECT_EQ(0, this->createApp({ R"(--exec-lua=rlogic.appearanceBindings.myAppearance.IN.green = 0.44)", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::ErrorLoadLua, this->m_app->run()); EXPECT_THAT(testing::internal::GetCapturedStderr(), testing::HasSubstr("sol: cannot set (new_index) into this object")); - EXPECT_EQ(static_cast(LogicViewerApp::ExitCode::ErrorLoadLua), this->m_app->run()); } TEST_F(ALogicViewerGuiApp, exec_lua_headless) { - createApp({ R"(--exec-lua=rlogic.appearanceBindings.myAppearance.IN.green.value = 0.24)", "--headless", ramsesFile }); - ASSERT_EQ(0, m_app->run()); - auto appearance = m_app->getViewer()->getLogic().findObject("myAppearance"); + EXPECT_EQ(0, createApp({ R"(--exec-lua=rlogic.appearanceBindings.myAppearance.IN.green.value = 0.24)", "--headless", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, m_app->run()); + auto appearance = m_app->getLogicViewer()->getLogic().findObject("myAppearance"); ASSERT_TRUE(appearance != nullptr); auto prop = appearance->getInputs()->getChild("green"); ASSERT_TRUE(prop != nullptr); EXPECT_FLOAT_EQ(0.24f, prop->get().value()); } - TYPED_TEST(ALogicViewerApp_T, exec_lua_screenshot_headless) + TEST_F(ALogicViewerGuiApp, exec_lua_screenshot_headless) { testing::internal::CaptureStderr(); - this->createApp({ R"(--exec-lua=rlogic.screenshot("screenshot.png"))", "--headless", ramsesFile }); - EXPECT_EQ(static_cast(LogicViewerApp::ExitCode::ErrorLoadLua), this->m_app->run()); + EXPECT_EQ(0, this->createApp({ R"(--exec-lua=rlogic.screenshot("screenshot.png"))", "--headless", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::ErrorLoadLua, this->m_app->run()); EXPECT_THAT(testing::internal::GetCapturedStderr(), testing::HasSubstr("No screenshots available in current configuration")); } @@ -832,9 +765,10 @@ namespace ramses::internal rlogic.appearanceBindings.myAppearance.IN.green.value = 1 rlogic.screenshot("test_yellow.png") )"); - createApp({ ramsesFile }); + EXPECT_EQ(0, createApp({ ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, m_app->setup()); EXPECT_TRUE(runUntil("is in state RENDERED caused by command SHOW")); - EXPECT_THAT(m_app->getViewer()->getLastResult().getMessage(), testing::HasSubstr("ALogicViewerAppTest.lua:7: 'end' expected")); + EXPECT_THAT(m_app->getLogicViewer()->getLastResult().getMessage(), testing::HasSubstr("ALogicViewerAppTest.lua:7: 'end' expected")); EXPECT_TRUE(m_app->doOneLoop()); EXPECT_TRUE(m_app->doOneLoop()); // does not terminate @@ -848,8 +782,8 @@ namespace ramses::internal rlogic.screenshot("test_red.png") end )"); - createApp({ "--exec=test_default", ramsesFile }); - EXPECT_EQ(0, m_app->run()); + EXPECT_EQ(0, createApp({ "--exec=test_default", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, m_app->run()); EXPECT_TRUE(CompareImage("test_red.png", "ALogicViewerApp_red.png")); } @@ -861,165 +795,15 @@ namespace ramses::internal rlogic.screenshot("test_red.png") end )"); - createApp({ "--exec=test_default", "--width", "500", "--height", "700", ramsesFile }); - EXPECT_EQ(0, m_app->run()); + EXPECT_EQ(0, createApp({ "--exec=test_default", "--width", "500", "--height", "700", ramsesFile })); + EXPECT_EQ(ViewerApp::ExitCode::Ok, m_app->run()); EXPECT_TRUE(CompareImage("test_red.png", "ALogicViewerApp_red_500x700.png")); } - TEST_F(ALogicViewerAppUI, modifyInterfaceInput) - { - const int32_t mouseX = 100; - EXPECT_TRUE(click(mouseX, ui.interfaces())); - EXPECT_TRUE(click(mouseX, ui.interfaces() + ui.smallButtonHeight)); - EXPECT_TRUE(dragX(mouseX, mouseX + 30, ui.interfaces() + ui.buttonHeight + 2 * ui.smallButtonHeight)); - - auto* script = m_app->getViewer()->getLogic().findObject("myScript"); - ASSERT_TRUE(script != nullptr); - auto* prop = script->getOutputs()->getChild("paramVec3f"); - ASSERT_TRUE(prop != nullptr); - const auto value = prop->get().value(); - EXPECT_FLOAT_EQ(0.f, value[0]); - EXPECT_FLOAT_EQ(0.f, value[1]); - EXPECT_FLOAT_EQ(3.f, value[2]); - } - - TEST_F(ALogicViewerAppUI, modifyScript) - { - const int32_t mouseX = 100; - EXPECT_TRUE(click(mouseX, ui.scripts())); - EXPECT_TRUE(click(mouseX, ui.scripts() + 2 * ui.smallButtonHeight)); - EXPECT_TRUE(dragX(mouseX, mouseX + 30, ui.animationNodes() + ui.buttonHeight + 4 * ui.smallButtonHeight)); - - auto* script = m_app->getViewer()->getLogic().findObject("allTypesScript"); - ASSERT_TRUE(script != nullptr); - auto* prop = script->getOutputs()->getChild("paramFloat"); - ASSERT_TRUE(prop != nullptr); - EXPECT_FLOAT_EQ(3.f, prop->get().value()); - } - - TEST_F(ALogicViewerAppUI, modifyAnimation) - { - const int32_t mouseX = 100; - EXPECT_TRUE(click(mouseX, ui.animationNodes())); - EXPECT_TRUE(click(mouseX, ui.animationNodes() + ui.smallButtonHeight)); - EXPECT_TRUE(dragX(mouseX, mouseX + 10, ui.animationNodes() + ui.buttonHeight + 4 * ui.smallButtonHeight)); - - auto* animation = m_app->getViewer()->getLogic().findObject("myAnimation"); - ASSERT_TRUE(animation != nullptr); - auto* prop = animation->getInputs()->getChild("progress"); - ASSERT_TRUE(prop != nullptr); - EXPECT_FLOAT_EQ(1.f, prop->get().value()); - } - - TEST_F(ALogicViewerAppUI, modifyTimer) - { - const int32_t mouseX = 100; - EXPECT_TRUE(click(mouseX, ui.timerNodes())); - EXPECT_TRUE(click(mouseX, ui.timerNodes() + ui.smallButtonHeight)); - EXPECT_TRUE(dragX(mouseX, mouseX + 30, ui.timerNodes() + ui.buttonHeight + 2 * ui.smallButtonHeight)); - - auto* timer = m_app->getViewer()->getLogic().findObject("myTimer"); - ASSERT_TRUE(timer != nullptr); - auto* prop = timer->getInputs()->getChild("ticker_us"); - ASSERT_TRUE(prop != nullptr); - EXPECT_EQ(3, prop->get().value()); - } - - TEST_F(ALogicViewerAppUI, modifyAppearance) - { - const int32_t mouseX = 100; - EXPECT_TRUE(click(mouseX, ui.appearanceBindings())); - EXPECT_TRUE(click(mouseX, ui.appearanceBindings() + ui.smallButtonHeight)); - EXPECT_TRUE(dragX(mouseX, mouseX + 10, ui.appearanceBindings() + ui.buttonHeight + 3 * ui.smallButtonHeight)); - - auto* appearance = m_app->getViewer()->getLogic().findObject("myAppearance"); - ASSERT_TRUE(appearance != nullptr); - auto* prop = appearance->getInputs()->getChild("green"); - ASSERT_TRUE(prop != nullptr); - EXPECT_FLOAT_EQ(1.f, prop->get().value()); - } - - TEST_F(ALogicViewerAppUI, modifyNodeBinding) - { - const int32_t mouseX = 100; - EXPECT_TRUE(click(mouseX, ui.nodeBindings())); - EXPECT_TRUE(click(mouseX, ui.nodeBindings() + ui.smallButtonHeight)); - EXPECT_TRUE(dragX(mouseX, mouseX + 20, ui.nodeBindings() + 2 * ui.buttonHeight + 5 * ui.smallButtonHeight)); - - auto* node = m_app->getViewer()->getLogic().findObject("myNode"); - ASSERT_TRUE(node != nullptr); - auto* prop = node->getInputs()->getChild("translation"); - ASSERT_TRUE(prop != nullptr); - const auto value = prop->get().value(); - EXPECT_FLOAT_EQ(2.f, value[0]); - EXPECT_FLOAT_EQ(0.f, value[1]); - EXPECT_FLOAT_EQ(0.f, value[2]); - } - - TEST_F(ALogicViewerAppUI, modifyCameraBinding) - { - const int32_t mouseX = 100; - EXPECT_TRUE(click(mouseX, ui.cameraBindings())); - EXPECT_TRUE(click(mouseX, ui.cameraBindings() + ui.smallButtonHeight)); - EXPECT_TRUE(click(mouseX, ui.cameraBindings() + 4 * ui.smallButtonHeight)); - EXPECT_TRUE(dragX(mouseX, mouseX - 30, ui.cameraBindings() + 3 * ui.buttonHeight + 4 * ui.smallButtonHeight)); - - auto* camera = m_app->getViewer()->getLogic().findObject("myCamera"); - ASSERT_TRUE(camera != nullptr); - auto* prop = camera->getInputs()->getChild("viewport"); - ASSERT_TRUE(prop != nullptr); - prop = prop->getChild("width"); - ASSERT_TRUE(prop != nullptr); - EXPECT_EQ(797, prop->get().value()); - } - - TEST_F(ALogicViewerAppUI, modifyRenderPass) - { - const int32_t mouseX = 100; - EXPECT_TRUE(click(mouseX, ui.renderPassBindings())); - EXPECT_TRUE(click(mouseX, ui.renderPassBindings() + ui.smallButtonHeight)); - EXPECT_TRUE(dragX(mouseX, mouseX + 30, ui.renderPassBindings() + 2 * ui.buttonHeight + 3 * ui.smallButtonHeight)); - - auto* renderPass = m_app->getViewer()->getLogic().findObject("myRenderPass"); - ASSERT_TRUE(renderPass != nullptr); - auto* prop = renderPass->getInputs()->getChild("renderOrder"); - ASSERT_TRUE(prop != nullptr); - EXPECT_EQ(3, prop->get().value()); - } - - TEST_F(ALogicViewerAppUI, modifyRenderGroup) - { - const int32_t mouseX = 100; - EXPECT_TRUE(click(mouseX, ui.renderGroupBindings())); - EXPECT_TRUE(click(mouseX, ui.renderGroupBindings() + ui.smallButtonHeight)); - EXPECT_TRUE(click(mouseX, ui.renderGroupBindings() + 4 * ui.smallButtonHeight)); - EXPECT_TRUE(dragX(mouseX, mouseX + 30, ui.renderGroupBindings() + ui.buttonHeight + 4 * ui.smallButtonHeight)); - - auto* renderGroup = m_app->getViewer()->getLogic().findObject("myRenderGroup"); - ASSERT_TRUE(renderGroup != nullptr); - auto* prop = renderGroup->getInputs()->getChild("renderOrders")->getChild("myMeshNode"); - ASSERT_TRUE(prop != nullptr); - EXPECT_EQ(3, prop->get().value()); - } - - TEST_F(ALogicViewerAppUI, modifyMeshNode) - { - const int32_t mouseX = 100; - EXPECT_TRUE(click(mouseX, ui.meshNodeBindings())); - EXPECT_TRUE(click(mouseX, ui.meshNodeBindings() + ui.smallButtonHeight)); - EXPECT_TRUE(dragX(mouseX, mouseX + 30, ui.meshNodeBindings() + 4 * ui.smallButtonHeight)); - - auto* meshNode = m_app->getViewer()->getLogic().findObject("myMeshNode"); - ASSERT_TRUE(meshNode != nullptr); - auto* prop = meshNode->getInputs()->getChild("vertexOffset"); - ASSERT_TRUE(prop != nullptr); - EXPECT_EQ(3, prop->get().value()); - } - TEST_F(ALogicViewerAppUI, reloadConfiguration) { const int32_t xFile = 25; - auto* script = m_app->getViewer()->getLogic().findObject("allTypesScript"); + auto* script = m_app->getLogicViewer()->getLogic().findObject("allTypesScript"); ASSERT_TRUE(script != nullptr); auto* prop = script->getOutputs()->getChild("paramString"); ASSERT_TRUE(prop != nullptr); @@ -1037,72 +821,25 @@ namespace ramses::internal EXPECT_EQ("World", prop->get().value()); SaveFile(R"(rlogic.scripts.allTypesScript.IN.paramString.value = "Foo")"); - EXPECT_TRUE(contextMenuSelect(700, 350, 1)); + EXPECT_TRUE(contextMenuSelect(700, 350, 8)); EXPECT_EQ("Foo", prop->get().value()); } - TEST_F(ALogicViewerAppUI, clipboard) + TEST_F(ALogicViewerAppUI, reloadConfigurationWithHiddenUI) { - const int32_t mouseX = 100; - EXPECT_TRUE(contextMenuSelect(mouseX, ui.interfaces())); - EXPECT_EQ(R"(rlogic.interfaces["myInterface"]["IN"]["paramFloat"].value = 0)", rtrim(ImGui::GetClipboardText())); - - EXPECT_TRUE(contextMenuSelect(mouseX, ui.scripts())); - EXPECT_EQ(R"(rlogic.scripts["allTypesScript"]["IN"]["paramBool"].value = false -rlogic.scripts["allTypesScript"]["IN"]["paramFloat"].value = 0 -rlogic.scripts["allTypesScript"]["IN"]["paramInt32"].value = 0 -rlogic.scripts["allTypesScript"]["IN"]["paramInt64"].value = 0 -rlogic.scripts["allTypesScript"]["IN"]["paramString"].value = '' -rlogic.scripts["allTypesScript"]["IN"]["paramVec2f"].value = { 0, 0 } -rlogic.scripts["allTypesScript"]["IN"]["paramVec2i"].value = { 0, 0 } -rlogic.scripts["allTypesScript"]["IN"]["paramVec3f"].value = { 0, 0, 0 } -rlogic.scripts["allTypesScript"]["IN"]["paramVec3i"].value = { 0, 0, 0 } -rlogic.scripts["allTypesScript"]["IN"]["paramVec4f"].value = { 0, 0, 0, 0 } -rlogic.scripts["allTypesScript"]["IN"]["paramVec4i"].value = { 0, 0, 0, 0 } -rlogic.scripts["allTypesScript"]["IN"]["struct"]["nested"]["data1"].value = '' -rlogic.scripts["allTypesScript"]["IN"]["struct"]["nested"]["data2"].value = 0)", rtrim(ImGui::GetClipboardText())); - - EXPECT_TRUE(contextMenuSelect(mouseX, ui.animationNodes())); - EXPECT_EQ(R"(rlogic.animationNodes["myAnimation"]["IN"]["progress"].value = 0)", rtrim(ImGui::GetClipboardText())); - - EXPECT_TRUE(contextMenuSelect(mouseX, ui.timerNodes())); - EXPECT_EQ(R"(rlogic.timerNodes["myTimer"]["IN"]["ticker_us"].value = 0)", rtrim(ImGui::GetClipboardText())); - - EXPECT_TRUE(contextMenuSelect(mouseX, ui.appearanceBindings())); - EXPECT_EQ(R"(rlogic.appearanceBindings["myAppearance"]["IN"]["green"].value = 0 -rlogic.appearanceBindings["myAppearance"]["IN"]["blue"].value = 0)", rtrim(ImGui::GetClipboardText())); - - EXPECT_TRUE(contextMenuSelect(mouseX, ui.nodeBindings())); - EXPECT_EQ(R"(rlogic.nodeBindings["myNode"]["IN"]["visibility"].value = true -rlogic.nodeBindings["myNode"]["IN"]["translation"].value = { 0, 0, 0 } -rlogic.nodeBindings["myNode"]["IN"]["scaling"].value = { 1, 1, 1 } -rlogic.nodeBindings["myNode"]["IN"]["enabled"].value = true)", rtrim(ImGui::GetClipboardText())); - - EXPECT_TRUE(contextMenuSelect(mouseX, ui.cameraBindings())); - EXPECT_EQ(R"(rlogic.cameraBindings["myCamera"]["IN"]["viewport"]["offsetX"].value = 0 -rlogic.cameraBindings["myCamera"]["IN"]["viewport"]["offsetY"].value = 0 -rlogic.cameraBindings["myCamera"]["IN"]["viewport"]["width"].value = 800 -rlogic.cameraBindings["myCamera"]["IN"]["viewport"]["height"].value = 800 -rlogic.cameraBindings["myCamera"]["IN"]["frustum"]["nearPlane"].value = 0.1 -rlogic.cameraBindings["myCamera"]["IN"]["frustum"]["farPlane"].value = 100 -rlogic.cameraBindings["myCamera"]["IN"]["frustum"]["fieldOfView"].value = 20 -rlogic.cameraBindings["myCamera"]["IN"]["frustum"]["aspectRatio"].value = 1)", rtrim(ImGui::GetClipboardText())); - - EXPECT_TRUE(contextMenuSelect(mouseX, ui.renderPassBindings())); - EXPECT_EQ(R"(rlogic.renderPassBindings["myRenderPass"]["IN"]["enabled"].value = true -rlogic.renderPassBindings["myRenderPass"]["IN"]["renderOrder"].value = 0 -rlogic.renderPassBindings["myRenderPass"]["IN"]["clearColor"].value = { 0, 0, 0, 1 } -rlogic.renderPassBindings["myRenderPass"]["IN"]["renderOnce"].value = false)", rtrim(ImGui::GetClipboardText())); - - EXPECT_TRUE(contextMenuSelect(mouseX, ui.renderGroupBindings())); - EXPECT_EQ(R"(rlogic.renderGroupBindings["myRenderGroup"]["IN"]["renderOrders"]["myMeshNode"].value = 0)", - rtrim(ImGui::GetClipboardText())); - - EXPECT_TRUE(contextMenuSelect(mouseX, ui.meshNodeBindings())); - EXPECT_EQ(R"(rlogic.meshNodeBindings["myMeshNode"]["IN"]["vertexOffset"].value = 0 -rlogic.meshNodeBindings["myMeshNode"]["IN"]["indexOffset"].value = 0 -rlogic.meshNodeBindings["myMeshNode"]["IN"]["indexCount"].value = 3 -rlogic.meshNodeBindings["myMeshNode"]["IN"]["instanceCount"].value = 1)", rtrim(ImGui::GetClipboardText())); + auto* settings = m_app->getSettings(); + settings->showGui = false; + auto* script = m_app->getLogicViewer()->getLogic().findObject("allTypesScript"); + ASSERT_TRUE(script != nullptr); + auto* prop = script->getOutputs()->getChild("paramString"); + ASSERT_TRUE(prop != nullptr); + + SaveFile(R"(rlogic.scripts.allTypesScript.IN.paramString.value = "Hello")"); + EXPECT_TRUE(m_app->doOneLoop()); + EXPECT_EQ("", prop->get().value()); // not reloaded automatically + + EXPECT_TRUE(keyPress(ramses::EKeyCode_F5)); // reload configuration + EXPECT_EQ("Hello", prop->get().value()); } TEST_F(ALogicViewerAppUI, changeView) @@ -1134,24 +871,24 @@ rlogic.meshNodeBindings["myMeshNode"]["IN"]["instanceCount"].value = 1)", rtrim( )"); EXPECT_TRUE(keyPress(ramses::EKeyCode_F5)); // reload configuration - EXPECT_EQ(2u, m_app->getViewer()->getViewCount()); - EXPECT_EQ(1u, m_app->getViewer()->getCurrentView()); - EXPECT_EQ(Result(), m_app->getViewer()->call("screenshot")); + EXPECT_EQ(2u, m_app->getLogicViewer()->getViewCount()); + EXPECT_EQ(1u, m_app->getLogicViewer()->getCurrentView()); + EXPECT_EQ(Result(), m_app->getLogicViewer()->call("screenshot")); EXPECT_TRUE(CompareImage("screenshot.png", "ALogicViewerApp_red.png")); EXPECT_TRUE(keyPress(ramses::EKeyCode_Right)); // next view - EXPECT_EQ(2u, m_app->getViewer()->getCurrentView()); - EXPECT_EQ(Result(), m_app->getViewer()->call("screenshot")); + EXPECT_EQ(2u, m_app->getLogicViewer()->getCurrentView()); + EXPECT_EQ(Result(), m_app->getLogicViewer()->call("screenshot")); EXPECT_TRUE(CompareImage("screenshot.png", "ALogicViewerApp_yellow.png")); // Modify the "blue" input 0 -> 1 EXPECT_TRUE(dragX(100, 100 + 10, ui.titleBar + 2 * ui.buttonHeight + 2 * ui.smallButtonHeight + ui.yMiddle)); - EXPECT_EQ(Result(), m_app->getViewer()->call("screenshot")); + EXPECT_EQ(Result(), m_app->getLogicViewer()->call("screenshot")); EXPECT_TRUE(CompareImage("screenshot.png", "ALogicViewerApp_white.png")); EXPECT_TRUE(keyPress(ramses::EKeyCode_Left)); // previous view - EXPECT_EQ(1u, m_app->getViewer()->getCurrentView()); - EXPECT_EQ(Result(), m_app->getViewer()->call("screenshot")); + EXPECT_EQ(1u, m_app->getLogicViewer()->getCurrentView()); + EXPECT_EQ(Result(), m_app->getLogicViewer()->call("screenshot")); EXPECT_TRUE(CompareImage("screenshot.png", "ALogicViewerApp_red.png")); } @@ -1160,75 +897,26 @@ rlogic.meshNodeBindings["myMeshNode"]["IN"]["instanceCount"].value = 1)", rtrim( const int xSettings = 75; auto* settings = m_app->getSettings(); - EXPECT_TRUE(settings->showWindow); - EXPECT_TRUE(contextMenuSelect(700, 350)); - EXPECT_FALSE(settings->showWindow); - EXPECT_TRUE(keyPress(ramses::EKeyCode_F11)); - EXPECT_TRUE(settings->showWindow); - - EXPECT_FALSE(settings->showDisplaySettings); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 12 * ui.smallButtonHeight + 3 * ui.hline + ui.yMiddle)); - EXPECT_TRUE(settings->showDisplaySettings); + EXPECT_TRUE(settings->showLogicWindow); + EXPECT_TRUE(contextMenuSelect(700, 350, 2)); + EXPECT_FALSE(settings->showLogicWindow); + EXPECT_TRUE(contextMenuSelect(700, 350, 2)); + EXPECT_TRUE(settings->showLogicWindow); EXPECT_FALSE(settings->luaPreferObjectIds); EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 11 * ui.smallButtonHeight + 3 * ui.hline + ui.yMiddle)); + EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 2 * ui.smallButtonHeight + 3 * ui.hline + ui.yMiddle)); EXPECT_TRUE(settings->luaPreferObjectIds); EXPECT_FALSE(settings->luaPreferIdentifiers); EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 10 * ui.smallButtonHeight + 3 * ui.hline + ui.yMiddle)); + EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 1 * ui.smallButtonHeight + 3 * ui.hline + ui.yMiddle)); EXPECT_TRUE(settings->luaPreferIdentifiers); - EXPECT_TRUE(settings->showOutputs); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 9 * ui.smallButtonHeight + 2 * ui.hline + ui.yMiddle)); - EXPECT_FALSE(settings->showOutputs); - - EXPECT_TRUE(settings->showLinkedInputs); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 8 * ui.smallButtonHeight + 2 * ui.hline + ui.yMiddle)); - EXPECT_FALSE(settings->showLinkedInputs); - EXPECT_FALSE(settings->showUpdateReport); EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 7 * ui.smallButtonHeight + ui.hline + ui.yMiddle)); + EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 0 * ui.smallButtonHeight + ui.hline + ui.yMiddle)); EXPECT_TRUE(settings->showUpdateReport); - - EXPECT_TRUE(settings->showRamsesBindings); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 6 * ui.smallButtonHeight + ui.hline + ui.yMiddle)); - EXPECT_FALSE(settings->showRamsesBindings); - - EXPECT_TRUE(settings->showDataArrays); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 5 * ui.smallButtonHeight + ui.hline + ui.yMiddle)); - EXPECT_FALSE(settings->showDataArrays); - - EXPECT_TRUE(settings->showTimerNodes); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 4 * ui.smallButtonHeight + ui.hline + ui.yMiddle)); - EXPECT_FALSE(settings->showTimerNodes); - - EXPECT_TRUE(settings->showAnimationNodes); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 3 * ui.smallButtonHeight + ui.hline + ui.yMiddle)); - EXPECT_FALSE(settings->showAnimationNodes); - - EXPECT_TRUE(settings->showScripts); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 2 * ui.smallButtonHeight + ui.hline + ui.yMiddle)); - EXPECT_FALSE(settings->showScripts); - - EXPECT_TRUE(settings->showInterfaces); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + 1 * ui.smallButtonHeight + ui.hline + ui.yMiddle)); - EXPECT_FALSE(settings->showInterfaces); - - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(xSettings, ui.titleBar + ui.buttonHeight + ui.yMiddle)); - EXPECT_FALSE(settings->showWindow); } class ALogicViewerAppUIClearColor : public ALogicViewerAppUIBase, public ::testing::TestWithParam @@ -1238,11 +926,11 @@ rlogic.meshNodeBindings["myMeshNode"]["IN"]["instanceCount"].value = 1)", rtrim( { if (GetParam()) { - setup(iniFile, { "--offscreen", "--clear-color", "0", "0", "0.5", "1" }); + setup(iniFile, {"--gui", "on", "--clear", "0,0,0.5,1"}); } else { - setup(iniFile, { "--clear-color", "0", "0", "0.5", "1" }); + setup(iniFile, { "--clear", "0,0,0.5,1" }); } } }; @@ -1265,47 +953,22 @@ rlogic.meshNodeBindings["myMeshNode"]["IN"]["instanceCount"].value = 1)", rtrim( EXPECT_TRUE(keyPress(ramses::EKeyCode_F5)); // reload configuration EXPECT_TRUE(keyPress(ramses::EKeyCode_F11)); // hide UI - EXPECT_EQ(Result(), m_app->getViewer()->call("screenshot")); + EXPECT_EQ(Result(), m_app->getLogicViewer()->call("screenshot")); EXPECT_TRUE(CompareImage("screenshot.png", "ALogicViewerApp_clearColorCmdLine.png", 0.5f)); // increased tolerance due to some platforms being 1/255 off covering large area (as background) } - TEST_P(ALogicViewerAppUIClearColor, changeClearColor) - { - SaveFile(R"( - function screenshot() - rlogic.screenshot("screenshot.png") - end - )"); - EXPECT_TRUE(keyPress(ramses::EKeyCode_F5)); // reload configuration - - const int mouseX = 75; - // show display settings - EXPECT_TRUE(click(mouseX, ui.titleBar + ui.yMiddle)); - EXPECT_TRUE(click(mouseX, ui.titleBar + ui.buttonHeight + 12 * ui.smallButtonHeight + 3 * ui.hline + ui.yMiddle)); - EXPECT_TRUE(m_app->getSettings()->showDisplaySettings); - // change clear color - const int displaySettingsY = ui.displaySettings() - ui.buttonHeight; - EXPECT_TRUE(click(mouseX, displaySettingsY)); - EXPECT_TRUE(dragX(mouseX + 50, mouseX + 55, displaySettingsY + ui.buttonHeight)); - EXPECT_TRUE(keyPress(ramses::EKeyCode_F11)); // hide UI - - EXPECT_EQ(Result(), m_app->getViewer()->call("screenshot")); - EXPECT_TRUE(CompareImage("screenshot.png", "ALogicViewerApp_clearColor.png", 0.5f)); // increased tolerance due to some platforms being 1/255 off covering large area (as background) - } - class ALogicViewerAppUIUpdateReport : public ALogicViewerAppUIBase, public ::testing::Test { }; TEST_F(ALogicViewerAppUIUpdateReport, updateReport) { - setup(R"([Window][Logic Viewer (FeatureLevel 01)] + setup(R"([Window][LogicEngine[10]] Pos=0,0 Size=540,720 Collapsed=0 -[LogicViewerGui][Settings] -ShowWindow=1 +[ramses-viewer][Settings] ShowInterfaces=1 ShowScripts=1 ShowAnimationNodes=1 @@ -1317,30 +980,28 @@ ShowLinkedInputs=1 ShowOutputs=1 LuaPreferObjectIds=0 LuaPreferIdentifiers=0 -ShowDisplaySettings=0)"); +)"); const int32_t mouseX = 100; EXPECT_TRUE(click(mouseX, ui.updateReport())); EXPECT_TRUE(click(mouseX, ui.updateReport() + 2 * ui.buttonHeight + 7 * ui.smallButtonHeight + ui.hline)); EXPECT_TRUE(click(mouseX, ui.updateReport() + 2 * ui.buttonHeight + 6 * ui.smallButtonHeight + ui.hline)); - const auto& report = m_app->getViewer()->getUpdateReport(); + const auto& report = m_app->getLogicViewer()->getUpdateReport(); // set update interval to 1 to avoid random test failures // (only the longest update is reported for an interval) EXPECT_EQ(60u, report.getInterval()); EXPECT_TRUE(dragX(mouseX, mouseX - 120, ui.updateReport() + 2 * ui.buttonHeight)); EXPECT_EQ(1u, report.getInterval()); + EXPECT_EQ(12, report.getNodesExecuted().size() + report.getNodesSkippedExecution().size()); - EXPECT_EQ(1, report.getNodesExecuted().size()); - EXPECT_EQ(10, report.getNodesSkippedExecution().size()); - - auto* interface = m_app->getViewer()->getLogic().findObject("myInterface"); + auto* interface = m_app->getLogicViewer()->getLogic().findObject("myInterface"); ASSERT_TRUE(interface != nullptr); auto* prop = interface->getInputs()->getChild("paramFloat"); ASSERT_TRUE(prop != nullptr); prop->set(2.1f); EXPECT_TRUE(m_app->doOneLoop()); EXPECT_EQ(4, report.getNodesExecuted().size()); - EXPECT_EQ(7, report.getNodesSkippedExecution().size()); + EXPECT_EQ(8, report.getNodesSkippedExecution().size()); } } diff --git a/tests/integration/logic-viewer-tests/res/ALogicViewerApp_clearColor.png b/tests/integration/viewer-tests/res/ALogicViewerApp_clearColor.png similarity index 100% rename from tests/integration/logic-viewer-tests/res/ALogicViewerApp_clearColor.png rename to tests/integration/viewer-tests/res/ALogicViewerApp_clearColor.png diff --git a/tests/integration/logic-viewer-tests/res/ALogicViewerApp_clearColorCmdLine.png b/tests/integration/viewer-tests/res/ALogicViewerApp_clearColorCmdLine.png similarity index 100% rename from tests/integration/logic-viewer-tests/res/ALogicViewerApp_clearColorCmdLine.png rename to tests/integration/viewer-tests/res/ALogicViewerApp_clearColorCmdLine.png diff --git a/tests/integration/logic-viewer-tests/res/ALogicViewerApp_red.png b/tests/integration/viewer-tests/res/ALogicViewerApp_red.png similarity index 100% rename from tests/integration/logic-viewer-tests/res/ALogicViewerApp_red.png rename to tests/integration/viewer-tests/res/ALogicViewerApp_red.png diff --git a/tests/integration/logic-viewer-tests/res/ALogicViewerApp_red_500x700.png b/tests/integration/viewer-tests/res/ALogicViewerApp_red_500x700.png similarity index 100% rename from tests/integration/logic-viewer-tests/res/ALogicViewerApp_red_500x700.png rename to tests/integration/viewer-tests/res/ALogicViewerApp_red_500x700.png diff --git a/tests/integration/logic-viewer-tests/res/ALogicViewerApp_white.png b/tests/integration/viewer-tests/res/ALogicViewerApp_white.png similarity index 100% rename from tests/integration/logic-viewer-tests/res/ALogicViewerApp_white.png rename to tests/integration/viewer-tests/res/ALogicViewerApp_white.png diff --git a/tests/integration/logic-viewer-tests/res/ALogicViewerApp_yellow.png b/tests/integration/viewer-tests/res/ALogicViewerApp_yellow.png similarity index 100% rename from tests/integration/logic-viewer-tests/res/ALogicViewerApp_yellow.png rename to tests/integration/viewer-tests/res/ALogicViewerApp_yellow.png diff --git a/tests/unittests/client/AppearanceTest.cpp b/tests/unittests/client/AppearanceTest.cpp index da2033cb8..14442e80e 100644 --- a/tests/unittests/client/AppearanceTest.cpp +++ b/tests/unittests/client/AppearanceTest.cpp @@ -63,8 +63,7 @@ namespace ramses::internal info.input = sharedTestState->effect->findUniformInput("texture2dInput"); EXPECT_TRUE(info.input.has_value()); - const uint8_t data[] = { 1, 2, 3 }; - const std::vector mipData{ MipLevelData(3u, data) }; + const std::vector mipData{ { std::byte{1}, std::byte{2}, std::byte{3} } }; Texture2D* texture = sharedTestState->getScene().createTexture2D(ETextureFormat::RGB8, 1u, 1u, mipData, false); EXPECT_TRUE(texture != nullptr); info.texture2D = texture; @@ -93,8 +92,7 @@ namespace ramses::internal info.input = sharedTestState->effect->findUniformInput("texture3dInput"); EXPECT_TRUE(info.input.has_value()); - const uint8_t data[] = { 1, 2, 3 }; - const std::vector mipData{ MipLevelData(3u, data) }; + const std::vector mipData{ { std::byte{1}, std::byte{2}, std::byte{3} } }; Texture3D* texture = sharedTestState->getScene().createTexture3D(ETextureFormat::RGB8, 1u, 1u, 1u, mipData, false); EXPECT_TRUE(texture != nullptr); info.texture3D = texture; @@ -109,8 +107,8 @@ namespace ramses::internal info.input = sharedTestState->effect->findUniformInput("textureCubeInput"); EXPECT_TRUE(info.input.has_value()); - const std::byte data[] = { std::byte{1}, std::byte{2}, std::byte{3} }; - std::vector mipData{ CubeMipLevelData(3u, data, data, data, data, data, data) }; + const std::vector data = { std::byte{1}, std::byte{2}, std::byte{3} }; + std::vector mipData{ { data, data, data, data, data, data } }; TextureCube* texture = sharedTestState->getScene().createTextureCube(ETextureFormat::RGB8, 1u, mipData, false); EXPECT_TRUE(texture != nullptr); info.textureCube = texture; @@ -346,8 +344,7 @@ namespace ramses::internal const auto optUniform = sharedTestState->effect->findUniformInput("integerInput"); ASSERT_TRUE(optUniform.has_value()); - const uint8_t texData[] = { 1, 2, 3 }; - const std::vector mipData{ MipLevelData(3u, texData) }; + const std::vector mipData{ { std::byte{1}, std::byte{2}, std::byte{3} } }; Texture2D* texture = sharedTestState->getScene().createTexture2D(ETextureFormat::RGB8, 1u, 1u, mipData, false); ASSERT_TRUE(texture != nullptr); @@ -365,8 +362,7 @@ namespace ramses::internal const auto optUniform = sharedTestState->effect->findUniformInput("texture2dInput"); ASSERT_TRUE(optUniform.has_value()); - const uint8_t texData[] = { 1, 2, 3 }; - const std::vector mipData{ MipLevelData(3u, texData) }; + const std::vector mipData{ { std::byte{1}, std::byte{2}, std::byte{3} } }; ramses::Scene& anotherScene = *sharedTestState->getClient().createScene(sceneId_t(1u)); Texture2D* texture = anotherScene.createTexture2D(ETextureFormat::RGB8, 1u, 1u, mipData, false); @@ -385,8 +381,7 @@ namespace ramses::internal const auto optUniform = sharedTestState->effect->findUniformInput("texture2dInput"); ASSERT_TRUE(optUniform.has_value()); - const uint8_t texData[] = { 1, 2, 3 }; - const std::vector mipData{ MipLevelData(3u, texData) }; + const std::vector mipData{ { std::byte{1}, std::byte{2}, std::byte{3} } }; Texture2D* texture = sharedTestState->getScene().createTexture2D(ETextureFormat::RGB8, 1u, 1u, mipData, false); ASSERT_TRUE(texture != nullptr); ramses::TextureSampler* textureSampler = sharedTestState->getScene().createTextureSampler(ETextureAddressMode::Clamp, ETextureAddressMode::Clamp, ETextureSamplingMethod::Nearest, ETextureSamplingMethod::Linear, *texture); @@ -935,8 +930,7 @@ namespace ramses::internal const auto optUniform = sharedTestState->effect->findUniformInput("texture2dInput"); ASSERT_TRUE(optUniform.has_value()); - const uint8_t texData[] = { 1, 2, 3 }; - const std::vector mipData{ MipLevelData(3u, texData) }; + const std::vector mipData{ { std::byte{1}, std::byte{2}, std::byte{3} } }; Texture2D* texture = sharedTestState->getScene().createTexture2D(ETextureFormat::RGB8, 1u, 1u, mipData, false); ASSERT_TRUE(texture != nullptr); @@ -980,8 +974,8 @@ namespace ramses::internal const auto optUniform = sharedTestState->effect->findUniformInput("textureCubeInput"); ASSERT_TRUE(optUniform.has_value()); - const std::byte texData[] = { std::byte{1}, std::byte{2}, std::byte{3} }; - std::vector mipData{ CubeMipLevelData(3u, texData, texData, texData, texData, texData, texData) }; + const std::vector texData = { std::byte{1}, std::byte{2}, std::byte{3} }; + std::vector mipData{ { texData, texData, texData, texData, texData, texData } }; TextureCube* texture = sharedTestState->getScene().createTextureCube(ETextureFormat::RGB8, 1u, mipData, false); ASSERT_TRUE(texture != nullptr); diff --git a/tests/unittests/client/BlitPassTest.cpp b/tests/unittests/client/BlitPassTest.cpp index a6ef0c66a..95b175bde 100644 --- a/tests/unittests/client/BlitPassTest.cpp +++ b/tests/unittests/client/BlitPassTest.cpp @@ -171,4 +171,50 @@ namespace ramses::internal blitpass.validate(report); EXPECT_TRUE(report.hasError()); } + + TEST_F(ABlitPass, failsValidationIfBlitRegionInvalidAfterRenderBufferSizeChanged) + { + EXPECT_TRUE(blitpass.setBlittingRegion(0u, 0u, 0u, 0u, 10u, 10u)); + ValidationReport report; + blitpass.validate(report); + EXPECT_FALSE(report.hasIssue()); + + // make source RB too small + EXPECT_TRUE(sourceRenderBuffer.impl().setProperties(9u, 100u, 0u)); + + report.clear(); + blitpass.validate(report); + ASSERT_TRUE(report.hasError()); + EXPECT_EQ(&blitpass, report.getIssues().front().object); + EXPECT_EQ(EIssueType::Error, report.getIssues().front().type); + EXPECT_EQ("blitpass blit region out of source or destination buffer size", report.getIssues().front().message); + + EXPECT_TRUE(sourceRenderBuffer.impl().setProperties(100u, 9u, 0u)); + report.clear(); + blitpass.validate(report); + EXPECT_TRUE(report.hasError()); + + // make big enough again + EXPECT_TRUE(sourceRenderBuffer.impl().setProperties(100u, 100u, 0u)); + report.clear(); + blitpass.validate(report); + EXPECT_FALSE(report.hasError()); + + // make dest RB too small + EXPECT_TRUE(destinationRenderBuffer.impl().setProperties(9u, 100u, 0u)); + report.clear(); + blitpass.validate(report); + EXPECT_TRUE(report.hasError()); + + EXPECT_TRUE(destinationRenderBuffer.impl().setProperties(100u, 9u, 0u)); + report.clear(); + blitpass.validate(report); + EXPECT_TRUE(report.hasError()); + + // make big enough again + EXPECT_TRUE(destinationRenderBuffer.impl().setProperties(100u, 100u, 0u)); + report.clear(); + blitpass.validate(report); + EXPECT_FALSE(report.hasError()); + } } diff --git a/tests/unittests/client/CameraTest.cpp b/tests/unittests/client/CameraTest.cpp index 109a19baf..5626887c9 100644 --- a/tests/unittests/client/CameraTest.cpp +++ b/tests/unittests/client/CameraTest.cpp @@ -258,13 +258,13 @@ namespace ramses::internal EXPECT_TRUE(this->camera->bindFrustumPlanes(*do1, *do2)); EXPECT_TRUE(this->camera->isFrustumPlanesBound()); - EXPECT_EQ(do1->impl().getDataReference(), this->camera->impl().getFrustrumPlanesHandle()); - EXPECT_EQ(do2->impl().getDataReference(), this->camera->impl().getFrustrumNearFarPlanesHandle()); + EXPECT_EQ(do1->impl().getDataReference(), this->camera->impl().getFrustumPlanesHandle()); + EXPECT_EQ(do2->impl().getDataReference(), this->camera->impl().getFrustumNearFarPlanesHandle()); EXPECT_TRUE(this->camera->unbindFrustumPlanes()); EXPECT_FALSE(this->camera->isFrustumPlanesBound()); - EXPECT_NE(do1->impl().getDataReference(), this->camera->impl().getFrustrumPlanesHandle()); - EXPECT_NE(do2->impl().getDataReference(), this->camera->impl().getFrustrumNearFarPlanesHandle()); + EXPECT_NE(do1->impl().getDataReference(), this->camera->impl().getFrustumPlanesHandle()); + EXPECT_NE(do2->impl().getDataReference(), this->camera->impl().getFrustumNearFarPlanesHandle()); } TYPED_TEST(ACamera, getsReferencedViewportValuesWhenBound) diff --git a/tests/unittests/client/CreationHelper.cpp b/tests/unittests/client/CreationHelper.cpp index 110e10970..2242463a3 100644 --- a/tests/unittests/client/CreationHelper.cpp +++ b/tests/unittests/client/CreationHelper.cpp @@ -124,20 +124,20 @@ namespace ramses::internal } template <> Texture2D* CreationHelper::createObjectOfType(std::string_view name) { - std::array data = { 0u }; - const std::vector mipLevelData{ MipLevelData(static_cast(data.size()), data.data()) }; + std::vector data(4, std::byte{ 0u }); + const std::vector mipLevelData{ data }; return m_scene->createTexture2D(ETextureFormat::RGBA8, 1u, 1u, mipLevelData, false, {}, name); } template <> Texture3D* CreationHelper::createObjectOfType(std::string_view name) { - std::array data = { 0u }; - const std::vector mipLevelData{ MipLevelData(static_cast(data.size()), data.data()) }; + std::vector data(32, std::byte{ 0u }); + const std::vector mipLevelData{ data }; return m_scene->createTexture3D(ETextureFormat::RGBA8, 1u, 2u, 4u, mipLevelData, false, name); } template <> TextureCube* CreationHelper::createObjectOfType(std::string_view name) { - std::byte data[4] = { std::byte{0u} }; // NOLINT(modernize-avoid-c-arrays) - std::vector mipLevelData{ CubeMipLevelData(sizeof(data), data, data, data, data, data, data) }; + std::vector data(4, std::byte{ 0u }); + std::vector mipLevelData{ {data, data, data, data, data, data} }; return m_scene->createTextureCube(ETextureFormat::RGBA8, 1u, mipLevelData, false, {}, name); } template <> ArrayResource* CreationHelper::createObjectOfType(std::string_view name) @@ -164,8 +164,8 @@ namespace ramses::internal template <> ramses::TextureSampler* CreationHelper::createObjectOfType(std::string_view name) { - std::array data = { 0u }; - const std::vector mipLevelData{ MipLevelData(static_cast(data.size()), data.data()) }; + std::vector data(4, std::byte{ 0u }); + const std::vector mipLevelData{ data }; Texture2D* texture = m_scene->createTexture2D(ETextureFormat::RGBA8, 1u, 1u, mipLevelData, false, {}, "texture"); return m_scene->createTextureSampler(ETextureAddressMode::Clamp, ETextureAddressMode::Mirror, ETextureSamplingMethod::Linear, ETextureSamplingMethod::Nearest, *texture, 1u, name); } diff --git a/tests/unittests/client/RamsesUtilsTest.cpp b/tests/unittests/client/RamsesUtilsTest.cpp index 8ab343d37..707d370ae 100644 --- a/tests/unittests/client/RamsesUtilsTest.cpp +++ b/tests/unittests/client/RamsesUtilsTest.cpp @@ -328,34 +328,77 @@ namespace ramses::internal } size_t mipMapCount = 0u; - MipLevelData* mipData = RamsesUtils::GenerateMipMapsTexture2D(width, height, pixelSize, data, mipMapCount); + auto* mipData = RamsesUtils::GenerateMipMapsTexture2D(width, height, pixelSize, data, mipMapCount); EXPECT_TRUE(mipData); EXPECT_EQ(4u, mipMapCount); // mip sizes - EXPECT_EQ(32u, mipData[0].m_size); - EXPECT_EQ(8u, mipData[1].m_size); - EXPECT_EQ(2u, mipData[2].m_size); - EXPECT_EQ(1u, mipData[3].m_size); - - // original data has been copied - EXPECT_NE(data, mipData[0].m_data); + EXPECT_EQ(32u, (*mipData)[0].size()); + EXPECT_EQ(8u, (*mipData)[1].size()); + EXPECT_EQ(2u, (*mipData)[2].size()); + EXPECT_EQ(1u, (*mipData)[3].size()); // mip level 1 - EXPECT_EQ(std::byte{15u}, mipData[0].m_data[14]); + EXPECT_EQ(std::byte{15u}, (*mipData)[0][14]); // mip level 2 - EXPECT_EQ(std::byte{3u}, mipData[1].m_data[0]); - EXPECT_EQ(std::byte{29u}, mipData[1].m_data[7]); + EXPECT_EQ(std::byte{3u}, (*mipData)[1][0]); + EXPECT_EQ(std::byte{29u}, (*mipData)[1][7]); // mip level 3 - EXPECT_EQ(std::byte{8u}, mipData[2].m_data[0]); - EXPECT_EQ(std::byte{24u}, mipData[2].m_data[1]); + EXPECT_EQ(std::byte{8u}, (*mipData)[2][0]); + EXPECT_EQ(std::byte{24u}, (*mipData)[2][1]); // mip level 4 - EXPECT_EQ(std::byte{16u}, mipData[3].m_data[0]); + EXPECT_EQ(std::byte{16u}, (*mipData)[3][0]); + + RamsesUtils::DeleteGeneratedMipMaps(mipData); + EXPECT_FALSE(mipData); + } + + TEST_F(ARamsesUtilsTest, doesNotGenerateMipMapsForTexture2DWithNonPow2Width) + { + const uint8_t pixelSize = 1u; + const uint32_t width = 3u; + const uint32_t height = 8u; + const size_t dataSize = width * height * pixelSize; + std::vector data(dataSize); + for (uint8_t i = 0; i < dataSize; i++) + { + data[i] = std::byte(i + 1u); + } + + size_t mipMapCount = 0u; + auto mipData = RamsesUtils::GenerateMipMapsTexture2D(width, height, pixelSize, data.data(), mipMapCount); + EXPECT_TRUE(mipData); + ASSERT_EQ(1u, mipMapCount); + + EXPECT_EQ(data, (*mipData)[0]); - RamsesUtils::DeleteGeneratedMipMaps(mipData, mipMapCount); + RamsesUtils::DeleteGeneratedMipMaps(mipData); + EXPECT_FALSE(mipData); + } + + TEST_F(ARamsesUtilsTest, doesNotGenerateMipMapsForTexture2DWithNonPow2Height) + { + const uint8_t pixelSize = 1u; + const uint32_t width = 4u; + const uint32_t height = 7u; + const size_t dataSize = width * height * pixelSize; + std::vector data(dataSize); + for (uint8_t i = 0; i < dataSize; i++) + { + data[i] = std::byte(i + 1u); + } + + size_t mipMapCount = 0u; + auto mipData = RamsesUtils::GenerateMipMapsTexture2D(width, height, pixelSize, data.data(), mipMapCount); + EXPECT_TRUE(mipData); + ASSERT_EQ(1u, mipMapCount); + + EXPECT_EQ(data, (*mipData)[0]); + + RamsesUtils::DeleteGeneratedMipMaps(mipData); EXPECT_FALSE(mipData); } @@ -372,39 +415,36 @@ namespace ramses::internal } size_t mipMapCount = 0u; - MipLevelData* mipData = RamsesUtils::GenerateMipMapsTexture2D(width, height, pixelSize, data, mipMapCount); + auto mipData = RamsesUtils::GenerateMipMapsTexture2D(width, height, pixelSize, data, mipMapCount); EXPECT_TRUE(mipData); EXPECT_EQ(4u, mipMapCount); // mip sizes - EXPECT_EQ(64u, mipData[0].m_size); - EXPECT_EQ(16u, mipData[1].m_size); - EXPECT_EQ(4u, mipData[2].m_size); - EXPECT_EQ(2u, mipData[3].m_size); - - // original data has been copied - EXPECT_NE(data, mipData[0].m_data); + EXPECT_EQ(64u, (*mipData)[0].size()); + EXPECT_EQ(16u, (*mipData)[1].size()); + EXPECT_EQ(4u, (*mipData)[2].size()); + EXPECT_EQ(2u, (*mipData)[3].size()); // mip level 1 - EXPECT_EQ(std::byte{15u}, mipData[0].m_data[28]); + EXPECT_EQ(std::byte{15u}, (*mipData)[0][28]); // mip level 2 - EXPECT_EQ(std::byte{5u}, mipData[1].m_data[0]); - EXPECT_EQ(std::byte{37u}, mipData[1].m_data[1]); - EXPECT_EQ(std::byte{27u}, mipData[1].m_data[14]); - EXPECT_EQ(std::byte{59u}, mipData[1].m_data[15]); + EXPECT_EQ(std::byte{5u}, (*mipData)[1][0]); + EXPECT_EQ(std::byte{37u}, (*mipData)[1][1]); + EXPECT_EQ(std::byte{27u}, (*mipData)[1][14]); + EXPECT_EQ(std::byte{59u}, (*mipData)[1][15]); // mip level 3 - EXPECT_EQ(std::byte{14u}, mipData[2].m_data[0]); - EXPECT_EQ(std::byte{46u}, mipData[2].m_data[1]); - EXPECT_EQ(std::byte{18u}, mipData[2].m_data[2]); - EXPECT_EQ(std::byte{50u}, mipData[2].m_data[3]); + EXPECT_EQ(std::byte{14u}, (*mipData)[2][0]); + EXPECT_EQ(std::byte{46u}, (*mipData)[2][1]); + EXPECT_EQ(std::byte{18u}, (*mipData)[2][2]); + EXPECT_EQ(std::byte{50u}, (*mipData)[2][3]); // mip level 4 - EXPECT_EQ(std::byte{16u}, mipData[3].m_data[0]); - EXPECT_EQ(std::byte{48u}, mipData[3].m_data[1]); + EXPECT_EQ(std::byte{16u}, (*mipData)[3][0]); + EXPECT_EQ(std::byte{48u}, (*mipData)[3][1]); - RamsesUtils::DeleteGeneratedMipMaps(mipData, mipMapCount); + RamsesUtils::DeleteGeneratedMipMaps(mipData); EXPECT_FALSE(mipData); } @@ -420,48 +460,40 @@ namespace ramses::internal } size_t mipMapCount = 0u; - CubeMipLevelData* mipData = RamsesUtils::GenerateMipMapsTextureCube(width, height, pixelSize, data, mipMapCount); + auto mipData = RamsesUtils::GenerateMipMapsTextureCube(width, height, pixelSize, data, mipMapCount); EXPECT_TRUE(mipData); EXPECT_EQ(3u, mipMapCount); // mip sizes - EXPECT_EQ(16u, mipData[0].m_faceDataSize); - EXPECT_EQ(4u, mipData[1].m_faceDataSize); - EXPECT_EQ(1u, mipData[2].m_faceDataSize); - - // original data has been copied - EXPECT_NE(&data[0], mipData[0].m_dataPX); - EXPECT_NE(&data[16], mipData[0].m_dataNX); - EXPECT_NE(&data[32], mipData[0].m_dataPY); - EXPECT_NE(&data[48], mipData[0].m_dataNY); - EXPECT_NE(&data[64], mipData[0].m_dataPZ); - EXPECT_NE(&data[80], mipData[0].m_dataNZ); + EXPECT_EQ(16u, (*mipData)[0].m_dataPX.size()); + EXPECT_EQ(4u, (*mipData)[1].m_dataPX.size()); + EXPECT_EQ(1u, (*mipData)[2].m_dataPX.size()); // mip level 1 - EXPECT_EQ(std::byte{11u}, mipData[0].m_dataPX[10]); - EXPECT_EQ(std::byte{27u}, mipData[0].m_dataNX[10]); - EXPECT_EQ(std::byte{43u}, mipData[0].m_dataPY[10]); - EXPECT_EQ(std::byte{59u}, mipData[0].m_dataNY[10]); - EXPECT_EQ(std::byte{75u}, mipData[0].m_dataPZ[10]); - EXPECT_EQ(std::byte{91u}, mipData[0].m_dataNZ[10]); + EXPECT_EQ(std::byte{11u}, (*mipData)[0].m_dataPX[10]); + EXPECT_EQ(std::byte{27u}, (*mipData)[0].m_dataNX[10]); + EXPECT_EQ(std::byte{43u}, (*mipData)[0].m_dataPY[10]); + EXPECT_EQ(std::byte{59u}, (*mipData)[0].m_dataNY[10]); + EXPECT_EQ(std::byte{75u}, (*mipData)[0].m_dataPZ[10]); + EXPECT_EQ(std::byte{91u}, (*mipData)[0].m_dataNZ[10]); // mip level 2 - EXPECT_EQ(std::byte{5u}, mipData[1].m_dataPX[1]); - EXPECT_EQ(std::byte{21u}, mipData[1].m_dataNX[1]); - EXPECT_EQ(std::byte{37u}, mipData[1].m_dataPY[1]); - EXPECT_EQ(std::byte{53u}, mipData[1].m_dataNY[1]); - EXPECT_EQ(std::byte{69u}, mipData[1].m_dataPZ[1]); - EXPECT_EQ(std::byte{85u}, mipData[1].m_dataNZ[1]); + EXPECT_EQ(std::byte{5u}, (*mipData)[1].m_dataPX[1]); + EXPECT_EQ(std::byte{21u}, (*mipData)[1].m_dataNX[1]); + EXPECT_EQ(std::byte{37u}, (*mipData)[1].m_dataPY[1]); + EXPECT_EQ(std::byte{53u}, (*mipData)[1].m_dataNY[1]); + EXPECT_EQ(std::byte{69u}, (*mipData)[1].m_dataPZ[1]); + EXPECT_EQ(std::byte{85u}, (*mipData)[1].m_dataNZ[1]); // mip level 3 - EXPECT_EQ(std::byte{8u}, mipData[2].m_dataPX[0]); - EXPECT_EQ(std::byte{24u}, mipData[2].m_dataNX[0]); - EXPECT_EQ(std::byte{40u}, mipData[2].m_dataPY[0]); - EXPECT_EQ(std::byte{56u}, mipData[2].m_dataNY[0]); - EXPECT_EQ(std::byte{72u}, mipData[2].m_dataPZ[0]); - EXPECT_EQ(std::byte{88u}, mipData[2].m_dataNZ[0]); - - RamsesUtils::DeleteGeneratedMipMaps(mipData, mipMapCount); + EXPECT_EQ(std::byte{8u}, (*mipData)[2].m_dataPX[0]); + EXPECT_EQ(std::byte{24u}, (*mipData)[2].m_dataNX[0]); + EXPECT_EQ(std::byte{40u}, (*mipData)[2].m_dataPY[0]); + EXPECT_EQ(std::byte{56u}, (*mipData)[2].m_dataNY[0]); + EXPECT_EQ(std::byte{72u}, (*mipData)[2].m_dataPZ[0]); + EXPECT_EQ(std::byte{88u}, (*mipData)[2].m_dataNZ[0]); + + RamsesUtils::DeleteGeneratedMipMaps(mipData); EXPECT_FALSE(mipData); } diff --git a/tests/unittests/client/RenderBufferTest.cpp b/tests/unittests/client/RenderBufferTest.cpp index 7c347e021..381602082 100644 --- a/tests/unittests/client/RenderBufferTest.cpp +++ b/tests/unittests/client/RenderBufferTest.cpp @@ -155,4 +155,33 @@ namespace ramses::internal renderBuffer->validate(report); EXPECT_FALSE(report.hasIssue()); } + + TEST_F(RenderBufferTest, canChangeProperties) + { + ramses::RenderBuffer* renderBuffer = m_scene.createRenderBuffer(400u, 400u, ERenderBufferFormat::Depth24, ERenderBufferAccessMode::ReadWrite); + ASSERT_TRUE(renderBuffer != nullptr); + + EXPECT_TRUE(renderBuffer->impl().setProperties(1u, 2u, 3u)); + EXPECT_FALSE(framework.getLastError()); + + EXPECT_EQ(1u, renderBuffer->getWidth()); + EXPECT_EQ(2u, renderBuffer->getHeight()); + EXPECT_EQ(3u, renderBuffer->getSampleCount()); + EXPECT_EQ(ERenderBufferFormat::Depth24, renderBuffer->getBufferFormat()); + EXPECT_EQ(ERenderBufferAccessMode::ReadWrite, renderBuffer->getAccessMode()); + } + + TEST_F(RenderBufferTest, failsToChangePropertiesIfInvalidValue) + { + ramses::RenderBuffer* renderBuffer = m_scene.createRenderBuffer(400u, 400u, ERenderBufferFormat::Depth24, ERenderBufferAccessMode::ReadWrite); + ASSERT_TRUE(renderBuffer != nullptr); + + EXPECT_FALSE(renderBuffer->impl().setProperties(0u, 2u, 3u)); + EXPECT_FALSE(renderBuffer->impl().setProperties(1u, 0u, 3u)); + auto err = framework.getLastError(); + ASSERT_TRUE(err); + EXPECT_EQ(renderBuffer, err->object); + EXPECT_EQ(EIssueType::Error, err->type); + EXPECT_EQ("RenderBuffer::setProperties: width and height cannot be zero", err->message); + } } diff --git a/tests/unittests/client/RenderTargetTest.cpp b/tests/unittests/client/RenderTargetTest.cpp index c032d830d..54161719d 100644 --- a/tests/unittests/client/RenderTargetTest.cpp +++ b/tests/unittests/client/RenderTargetTest.cpp @@ -38,6 +38,10 @@ namespace ramses::internal EXPECT_TRUE(m_internalScene.isRenderTargetAllocated(rtHandle)); ASSERT_EQ(1u, m_internalScene.getRenderTargetRenderBufferCount(rtHandle)); EXPECT_EQ(rb.impl().getRenderBufferHandle(), m_internalScene.getRenderTargetRenderBuffer(rtHandle, 0u)); + + ValidationReport report; + renderTarget->validate(report); + EXPECT_FALSE(report.hasIssue()); } TEST_F(ARenderTarget, failsToCreateUsingInvalidRenderTargetDescription) @@ -47,4 +51,68 @@ namespace ramses::internal const ramses::RenderTarget* renderTarget = m_scene.createRenderTarget(invalidRtDesc, "RenderTarget"); EXPECT_TRUE(renderTarget == nullptr); } + + TEST_F(ARenderTarget, validatesWithErrorIfMismatchingRenderBufferProperties) + { + ramses::RenderBuffer& rb1 = *m_scene.createRenderBuffer(16u, 8u, ERenderBufferFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 2u); + ramses::RenderBuffer& rb2 = *m_scene.createRenderBuffer(16u, 8u, ERenderBufferFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 2u); + RenderTargetDescription rtDesc; + rtDesc.addRenderBuffer(rb1); + rtDesc.addRenderBuffer(rb2); + + const ramses::RenderTarget* renderTarget = m_scene.createRenderTarget(rtDesc, "rt"); + ASSERT_TRUE(renderTarget != nullptr); + + ValidationReport report; + renderTarget->validate(report); + EXPECT_FALSE(report.hasIssue()); + + // change rb1 properties + EXPECT_TRUE(rb1.impl().setProperties(1u, 8u, 2u)); + report.clear(); + renderTarget->validate(report); + ASSERT_TRUE(report.hasError()); + EXPECT_EQ(renderTarget, report.getIssues().front().object); + EXPECT_EQ(EIssueType::Error, report.getIssues().front().type); + EXPECT_EQ("RenderTarget uses render buffers with mismatching resolution and/or sample count. This RenderTarget cannot be used and attempt to flush scene will fail.", + report.getIssues().front().message); + + EXPECT_TRUE(rb1.impl().setProperties(16u, 1u, 2u)); + report.clear(); + renderTarget->validate(report); + EXPECT_TRUE(report.hasError()); + + EXPECT_TRUE(rb1.impl().setProperties(16u, 8u, 1u)); + report.clear(); + renderTarget->validate(report); + EXPECT_TRUE(report.hasError()); + + // reset to valid properties + EXPECT_TRUE(rb1.impl().setProperties(16u, 8u, 2u)); + report.clear(); + renderTarget->validate(report); + EXPECT_FALSE(report.hasError()); + + // change rb2 properties + EXPECT_TRUE(rb2.impl().setProperties(1u, 8u, 2u)); + report.clear(); + renderTarget->validate(report); + EXPECT_TRUE(report.hasError()); + + EXPECT_TRUE(rb2.impl().setProperties(16u, 1u, 2u)); + report.clear(); + renderTarget->validate(report); + EXPECT_TRUE(report.hasError()); + + EXPECT_TRUE(rb2.impl().setProperties(16u, 8u, 1u)); + report.clear(); + renderTarget->validate(report); + EXPECT_TRUE(report.hasError()); + + // reset to valid properties + EXPECT_TRUE(rb2.impl().setProperties(16u, 8u, 2u)); + report.clear(); + renderTarget->validate(report); + EXPECT_FALSE(report.hasError()); + } } diff --git a/tests/unittests/client/ResourceTest.cpp b/tests/unittests/client/ResourceTest.cpp index 0e02634ce..98521e572 100644 --- a/tests/unittests/client/ResourceTest.cpp +++ b/tests/unittests/client/ResourceTest.cpp @@ -59,8 +59,7 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureAndDestroyManually) { - const uint8_t data[4 * 10 * 12] = {}; - const std::vector mipLevelData{ MipLevelData(sizeof(data), data) }; + const std::vector mipLevelData = { std::vector(4 * 10 * 12) }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 10, 12, mipLevelData, false, {}, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_TRUE(m_scene.destroy(*texture)); @@ -68,18 +67,17 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureWithMipMaps) { - const uint8_t data[2 * 2 * 4] = {}; + const std::vector data(2 * 2 * 4); std::vector mipLevelData; - mipLevelData.emplace_back(2 * 2 * 4, data); - mipLevelData.emplace_back(1 * 1 * 4, data); + mipLevelData.emplace_back(data); + mipLevelData.emplace_back(data.begin(), data.begin() + 1 * 1 * 4); Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 2, 2, mipLevelData, false, {}, "name"); ASSERT_TRUE(nullptr != texture); } TEST_F(AResourceTestClient, createTextureAndCheckWidthHeight) { - const uint8_t data[4 * 10 * 12] = {}; - const std::vector mipLevelData{ MipLevelData(sizeof(data), data) }; + const std::vector mipLevelData{ std::vector(4 * 10 * 12) }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 10, 12, mipLevelData, false, {}, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_EQ(10u, texture->getWidth()); @@ -88,8 +86,7 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureAndCheckFormat) { - const uint8_t data[3 * 10 * 12] = {}; - const std::vector mipLevelData{ MipLevelData(sizeof(data), data) }; + const std::vector mipLevelData{ std::vector(3 * 10 * 12) }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGB8, 10, 12, mipLevelData, false, {}, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_EQ(ETextureFormat::RGB8, texture->getTextureFormat()); @@ -97,8 +94,7 @@ namespace ramses::internal TEST_F(AResourceTestClient, createsTextureWithDefaultSwizzle) { - const uint8_t data[3 * 10 * 12] = {}; - const std::vector mipLevelData{ MipLevelData(sizeof(data), data) }; + const std::vector mipLevelData{ std::vector(3 * 10 * 12) }; TextureSwizzle swizzle; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGB8, 10, 12, mipLevelData, false, swizzle, "name"); ASSERT_TRUE(nullptr != texture); @@ -111,8 +107,7 @@ namespace ramses::internal TEST_F(AResourceTestClient, createsTextureWithNonDefaultSwizzle) { TextureSwizzle swizzle = { ETextureChannelColor::Blue, ETextureChannelColor::Alpha, ETextureChannelColor::Red, ETextureChannelColor::Green }; - const uint8_t data[3 * 10 * 12] = {}; - const std::vector mipLevelData{ MipLevelData(sizeof(data), data) }; + const std::vector mipLevelData{ std::vector(3 * 10 * 12) }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGB8, 10, 12, mipLevelData, false, swizzle, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_EQ(swizzle.channelRed, texture->getTextureSwizzle().channelRed); @@ -123,11 +118,11 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureWithProvidedMipsButNotFullChain) { - const uint8_t data[4 * 4 * 4] = {}; + const std::vector data(4 * 4 * 4); std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data); - mipLevelData.emplace_back(2 * 2 * 4, data); + mipLevelData.emplace_back(data); + mipLevelData.emplace_back(data.begin(), data.begin() + 2 * 2 * 4); Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 4u, 4u, mipLevelData, false, {}, "name"); ASSERT_TRUE(nullptr != texture); @@ -135,54 +130,29 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureWithMoreMipsThanExpected) { - const uint8_t data[1] = {}; + const std::vector data(1); - std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data); - mipLevelData.emplace_back(static_cast(sizeof(data)), data); + std::vector mipLevelData{ data, data }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 1u, 1u, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } - TEST_F(AResourceTestClient, createTextureWithNullMipMapData) - { - const uint8_t data[4 * 4 * 4] = {}; - const uint8_t* dataNullPtr{nullptr}; - - std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), dataNullPtr); - - Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 4u, 4u, mipLevelData, false, {}, "name"); - EXPECT_EQ(nullptr, texture); - } - TEST_F(AResourceTestClient, createTextureWithZeroSizeMipMapData) { - const uint8_t data[4 * 4 * 4] = {}; - - std::vector mipLevelData; - mipLevelData.emplace_back(0u, data); + std::vector mipLevelData{ {} }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 4u, 4u, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } - TEST_F(AResourceTestClient, createTextureWithNullOrZeroSizeLowerMipMapData) + TEST_F(AResourceTestClient, createTextureWithZeroSizeLowerMipMapData) { - const uint8_t data[2 * 2 * 4] = {}; - const uint8_t* dataNullPtr{nullptr}; - { - std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data); - mipLevelData.emplace_back(0u, data); - Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 2u, 2u, mipLevelData, false, {}, "name"); - EXPECT_EQ(nullptr, texture); - } + const std::vector data(2 * 2 * 4); { std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data); - mipLevelData.emplace_back(static_cast(sizeof(data)), dataNullPtr); + mipLevelData.emplace_back(data); + mipLevelData.emplace_back(0u); Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 2u, 2u, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } @@ -190,33 +160,31 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureWithWrongSizeOfLowerMipMapData) { - const uint8_t data[2 * 2 * 4] = {}; + const std::vector data(2 * 2 * 4); std::vector mipLevelData; - mipLevelData.emplace_back(2 * 2 * 4, data); - mipLevelData.emplace_back(1 * 1 * 2, data); + mipLevelData.emplace_back(data); + mipLevelData.emplace_back(data.begin(), data.begin() + 1 * 1 * 2); Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 2u, 2u, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } TEST_F(AResourceTestClient, createTextureOfZeroSize) { - const uint8_t data[4 * 10 * 12] = {}; - const std::vector mipLevelData{ MipLevelData(sizeof(data), data) }; + const std::vector mipLevelData{ std::vector(4 * 10 * 12) }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 0, 0, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } TEST_F(AResourceTestClient, createTextureWithNoMipData) { - std::vector < MipLevelData> mipLevelData; + std::vector mipLevelData; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 1, 1, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } TEST_F(AResourceTestClient, createTextureWithoutName) { - const uint8_t data[4 * 10 * 12] = {}; - const std::vector mipLevelData{ MipLevelData(sizeof(data), data) }; + const std::vector mipLevelData{ std::vector(4 * 10 * 12) }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 10, 12, mipLevelData, false, {}, {}); ASSERT_TRUE(nullptr != texture); EXPECT_TRUE(texture->getName().empty()); @@ -224,8 +192,7 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureCheckHashIsValid) { - const uint8_t data[4 * 10 * 12] = {}; - const std::vector mipLevelData{ MipLevelData(sizeof(data), data) }; + const std::vector mipLevelData{ std::vector(4 * 10 * 12) }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 10, 12, mipLevelData, false, {}, "name"); ASSERT_TRUE(nullptr != texture); @@ -235,16 +202,16 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureCheckHashIsUnique) { - uint8_t data[4 * 10 * 12] = {}; - data[20] = 48; - const std::vector mipLevelData{ MipLevelData(sizeof(data), data) }; + std::vector data(4 * 10 * 12); + data[20] = std::byte{ 48 }; + const std::vector mipLevelData{ data }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 10, 12, mipLevelData, false, {}, "name"); ASSERT_TRUE(nullptr != texture); const ramses::internal::ResourceContentHash hash = texture->impl().getLowlevelResourceHash(); - uint8_t data2[4 * 10 * 12] = {}; - data[20] = 42; - const std::vector mipLevelData2{ MipLevelData(sizeof(data2), data2) }; + std::vector data2(4 * 10 * 12); + data[20] = std::byte{ 42 }; + const std::vector mipLevelData2{ data2 }; Texture2D* texture2 = m_scene.createTexture2D(ETextureFormat::RGBA8, 10, 12, mipLevelData2, false, {}, "name"); ASSERT_TRUE(nullptr != texture2); @@ -253,15 +220,15 @@ namespace ramses::internal } template - std::array make_byte_array(Ts&&... args) noexcept + std::vector make_byte_vector(Ts&&... args) noexcept { return {std::byte(std::forward(args))...}; } TEST_F(AResourceTestClient, createTextureRGBA_AndCheckTexels) { - const auto data = make_byte_array(1, 2, 3, 4, 5, 6, 7, 8); - const std::vector mipLevelData{ MipLevelData(static_cast(data.size()), data.data()) }; + const auto data = make_byte_vector(1, 2, 3, 4, 5, 6, 7, 8); + const std::vector mipLevelData{ data }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGBA8, 2, 1, mipLevelData, false, {}, {}); ASSERT_TRUE(nullptr != texture); ramses::internal::ManagedResource res = getCreatedResource(texture->impl().getLowlevelResourceHash()); @@ -272,8 +239,8 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureRGB_AndCheckTexels) { - const auto data = make_byte_array(1, 2, 3, 4, 5, 6); - const std::vector mipLevelData{ MipLevelData(static_cast(data.size()), data.data()) }; + const auto data = make_byte_vector(1, 2, 3, 4, 5, 6); + const std::vector mipLevelData{ data }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGB8, 2, 1, mipLevelData, false, {}, {}); ASSERT_TRUE(nullptr != texture); @@ -285,17 +252,17 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureRGBWithMips_AndCheckTexels) { - const auto data0 = make_byte_array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); - const auto data1 = make_byte_array(13, 14, 15); - const std::vector mipLevelData = { MipLevelData{ static_cast(data0.size()), data0.data() }, MipLevelData{ static_cast(data1.size()), data1.data() } }; + const auto data0 = make_byte_vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); + const auto data1 = make_byte_vector(13, 14, 15); + const std::vector mipLevelData = { data0, data1 }; const Texture2D* texture = m_scene.createTexture2D(ETextureFormat::RGB8, 2, 2, mipLevelData, false, {}, {}); ASSERT_TRUE(nullptr != texture); const ramses::internal::ManagedResource res = getCreatedResource(texture->impl().getLowlevelResourceHash()); - ASSERT_EQ(sizeof(data0) + sizeof(data1), res->getDecompressedDataSize()); - EXPECT_EQ(data0, res->getResourceData().span().subspan(0, sizeof(data0))); - EXPECT_EQ(data1, res->getResourceData().span().subspan(sizeof(data0))); + ASSERT_EQ(data0.size() + data1.size(), res->getDecompressedDataSize()); + EXPECT_EQ(data0, res->getResourceData().span().subspan(0, data0.size())); + EXPECT_EQ(data1, res->getResourceData().span().subspan(data0.size())); } //############################################################## @@ -304,8 +271,8 @@ namespace ramses::internal TEST_F(AResourceTestClient, createCubeTextureAndDestroyManually) { - const std::byte data[4 * 10 * 10] = {}; - std::vector mipLevelData = { CubeMipLevelData(sizeof(data), data, data, data, data, data, data) }; + const std::vector data(4 * 10 * 10); + std::vector mipLevelData = { { data, data, data, data, data, data } }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 10, mipLevelData, false); ASSERT_TRUE(nullptr != texture); EXPECT_TRUE(m_scene.destroy(*texture)); @@ -313,18 +280,19 @@ namespace ramses::internal TEST_F(AResourceTestClient, createCubeTextureWithMipMaps) { - const std::byte data[2 * 2 * 4] = {}; + const std::vector data1(2 * 2 * 4); + const std::vector data2(1 * 1 * 4); std::vector mipLevelData; - mipLevelData.emplace_back(2 * 2 * 4, data, data, data, data, data, data); - mipLevelData.emplace_back(1 * 1 * 4, data, data, data, data, data, data); + mipLevelData.emplace_back(CubeMipLevelData{ data1, data1, data1, data1, data1, data1 }); + mipLevelData.emplace_back(CubeMipLevelData{ data2, data2, data2, data2, data2, data2 }); TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 2, mipLevelData, false, {}, "name"); ASSERT_TRUE(nullptr != texture); } TEST_F(AResourceTestClient, createCubeTextureAndCheckWidthHeight) { - const std::byte data[4 * 10 * 10] = {}; - std::vector mipLevelData = { CubeMipLevelData(sizeof(data), data, data, data, data, data, data) }; + const std::vector data(4 * 10 * 10); + std::vector mipLevelData = { {data, data, data, data, data, data} }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 10, mipLevelData, false, {}, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_EQ(10u, texture->getSize()); @@ -332,8 +300,8 @@ namespace ramses::internal TEST_F(AResourceTestClient, createCubeTextureAndCheckFormat) { - const std::byte data[3 * 10 * 10] = {}; - std::vector mipLevelData = { CubeMipLevelData(sizeof(data), data, data, data, data, data, data) }; + const std::vector data(4 * 10 * 10); + std::vector mipLevelData = { {data, data, data, data, data, data} }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGB8, 10, mipLevelData, false, {}, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_EQ(ETextureFormat::RGB8, texture->getTextureFormat()); @@ -342,8 +310,8 @@ namespace ramses::internal TEST_F(AResourceTestClient, createsCubeTextureWithDefaultSwizzle) { TextureSwizzle swizzle; - const std::byte data[4 * 10 * 10] = {}; - std::vector mipLevelData = { CubeMipLevelData(sizeof(data), data, data, data, data, data, data) }; + const std::vector data(4 * 10 * 10); + std::vector mipLevelData = { {data, data, data, data, data, data} }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 10, mipLevelData, false, swizzle, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_EQ(ETextureChannelColor::Red, swizzle.channelRed); @@ -355,8 +323,8 @@ namespace ramses::internal TEST_F(AResourceTestClient, createsCubeTextureWithNonDefaultSwizzle) { TextureSwizzle swizzle = { ETextureChannelColor::Blue, ETextureChannelColor::Alpha, ETextureChannelColor::Red, ETextureChannelColor::Green }; - const std::byte data[4 * 10 * 10] = {}; - std::vector mipLevelData = { CubeMipLevelData(sizeof(data), data, data, data, data, data, data) }; + const std::vector data(4 * 10 * 10); + std::vector mipLevelData = { {data, data, data, data, data, data} }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 10, mipLevelData, false, swizzle, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_EQ(swizzle.channelRed, texture->getTextureSwizzle().channelRed); @@ -367,20 +335,12 @@ namespace ramses::internal TEST_F(AResourceTestClient, createCubeTextureOfZeroSize) { - const std::byte data[4 * 10 * 10] = {}; - std::vector mipLevelData = { CubeMipLevelData(sizeof(data), data, data, data, data, data, data) }; + const std::vector data(4 * 10 * 10); + std::vector mipLevelData = { {data, data, data, data, data, data} }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 0, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } - TEST_F(AResourceTestClient, createCubeTextureOfZeroDataSize) - { - const std::byte data[4 * 10 * 10] = {}; - std::vector mipLevelData = { CubeMipLevelData(0, data, data, data, data, data, data) }; - TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 10, mipLevelData, false, {}, "name"); - EXPECT_EQ(nullptr, texture); - } - TEST_F(AResourceTestClient, createCubeTextureWithNoMipData) { std::vector mipLevelData; @@ -390,8 +350,8 @@ namespace ramses::internal TEST_F(AResourceTestClient, createCubeTextureWithoutName) { - const std::byte data[4 * 10 * 10] = {}; - std::vector mipLevelData = { CubeMipLevelData(sizeof(data), data, data, data, data, data, data) }; + const std::vector data(4 * 10 * 10); + std::vector mipLevelData = { {data, data, data, data, data, data} }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 10, mipLevelData, false, {}, {}); ASSERT_TRUE(nullptr != texture); EXPECT_TRUE(texture->getName().empty()); @@ -399,51 +359,49 @@ namespace ramses::internal TEST_F(AResourceTestClient, createCubeTextureRGBA_AndCheckTexels) { - const auto dataArray = make_byte_array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); - const auto* data = dataArray.data(); - std::vector mipLevelData = { CubeMipLevelData(static_cast(dataArray.size()), data, data, data, data, data, data) }; + const auto data = make_byte_vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + std::vector mipLevelData = { { data, data, data, data, data, data } }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 2, mipLevelData, false); ASSERT_TRUE(nullptr != texture); ramses::internal::ManagedResource res = getCreatedResource(texture->impl().getLowlevelResourceHash()); - ASSERT_EQ(dataArray.size() * 6u, res->getDecompressedDataSize()); + ASSERT_EQ(data.size() * 6u, res->getDecompressedDataSize()); for (uint32_t i = 0u; i < 6u; ++i) - EXPECT_EQ(dataArray, res->getResourceData().span().subspan(i*dataArray.size(), dataArray.size())); + EXPECT_EQ(data, res->getResourceData().span().subspan(i* data.size(), data.size())); } TEST_F(AResourceTestClient, createCubeTextureRGB_AndCheckTexels) { - const auto dataArray = make_byte_array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); - const auto* data = dataArray.data(); - std::vector mipLevelData = { CubeMipLevelData(static_cast(dataArray.size()), data, data, data, data, data, data) }; + const auto data = make_byte_vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); + std::vector mipLevelData = { { data, data, data, data, data, data } }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGB8, 2, mipLevelData, false); ASSERT_TRUE(nullptr != texture); ramses::internal::ManagedResource res = getCreatedResource(texture->impl().getLowlevelResourceHash()); - ASSERT_EQ(dataArray.size() * 6u, res->getDecompressedDataSize()); + ASSERT_EQ(data.size() * 6u, res->getDecompressedDataSize()); for (uint32_t i = 0u; i < 6u; ++i) - EXPECT_EQ(dataArray, res->getResourceData().span().subspan(i*dataArray.size(), dataArray.size())); + EXPECT_EQ(data, res->getResourceData().span().subspan(i* data.size(), data.size())); } TEST_F(AResourceTestClient, createCubeTextureRGBWithPerFaceDataAndMips_AndCheckTexels) { - const auto data0px = make_byte_array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); - const auto data1px = make_byte_array(13, 14, 15); - const auto data0nx = make_byte_array(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120); - const auto data1nx = make_byte_array(130, 140, 150); - const auto data0py = make_byte_array(11, 21, 31, 41, 51, 61, 71, 81, 91, 101, 111, 121); - const auto data1py = make_byte_array(131, 141, 151); - const auto data0ny = make_byte_array(12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122); - const auto data1ny = make_byte_array(132, 142, 152); - const auto data0pz = make_byte_array(13, 23, 33, 43, 53, 63, 73, 83, 93, 103, 113, 123 ); - const auto data1pz = make_byte_array(133, 143, 153); - const auto data0nz = make_byte_array(14, 24, 34, 44, 54, 64, 74, 84, 94, 104, 114, 124 ); - const auto data1nz = make_byte_array(134, 144, 154); + const auto data0px = make_byte_vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); + const auto data1px = make_byte_vector(13, 14, 15); + const auto data0nx = make_byte_vector(10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120); + const auto data1nx = make_byte_vector(130, 140, 150); + const auto data0py = make_byte_vector(11, 21, 31, 41, 51, 61, 71, 81, 91, 101, 111, 121); + const auto data1py = make_byte_vector(131, 141, 151); + const auto data0ny = make_byte_vector(12, 22, 32, 42, 52, 62, 72, 82, 92, 102, 112, 122); + const auto data1ny = make_byte_vector(132, 142, 152); + const auto data0pz = make_byte_vector(13, 23, 33, 43, 53, 63, 73, 83, 93, 103, 113, 123 ); + const auto data1pz = make_byte_vector(133, 143, 153); + const auto data0nz = make_byte_vector(14, 24, 34, 44, 54, 64, 74, 84, 94, 104, 114, 124 ); + const auto data1nz = make_byte_vector(134, 144, 154); std::vector mipLevelData = { - CubeMipLevelData{ static_cast(data0px.size()), data0px.data(), data0nx.data(), data0py.data(), data0ny.data(), data0pz.data(), data0nz.data() }, - CubeMipLevelData{ static_cast(data1px.size()), data1px.data(), data1nx.data(), data1py.data(), data1ny.data(), data1pz.data(), data1nz.data() } + CubeMipLevelData{ data0px, data0nx, data0py, data0ny, data0pz, data0nz }, + CubeMipLevelData{ data1px, data1nx, data1py, data1ny, data1pz, data1nz } }; const TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGB8, 2u, mipLevelData, false, {}, {}); ASSERT_TRUE(nullptr != texture); @@ -487,11 +445,12 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureCubeWithProvidedMipsButNotFullChain) { - const std::byte data[4 * 4 * 4] = {}; + const std::vector data1(4 * 4 * 4); + const std::vector data2(2 * 2 * 4); std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data, data, data, data, data, data); - mipLevelData.emplace_back(2 * 2 * 4, data, data, data, data, data, data); + mipLevelData.emplace_back(CubeMipLevelData{ data1, data1, data1, data1, data1, data1 }); + mipLevelData.emplace_back(CubeMipLevelData{ data2, data2, data2, data2, data2, data2 }); TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 4u, mipLevelData, false, {}, "name"); EXPECT_NE(nullptr, texture); @@ -499,52 +458,52 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureCubeWithMoreMipsThanExpected) { - const std::byte data[1] = {}; + const std::vector data(1); std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data, data, data, data, data, data); - mipLevelData.emplace_back(static_cast(sizeof(data)), data, data, data, data, data, data); + mipLevelData.emplace_back(CubeMipLevelData{ data, data, data, data, data, data }); + mipLevelData.emplace_back(CubeMipLevelData{ data, data, data, data, data, data }); TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 1u, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } - TEST_F(AResourceTestClient, createTextureCubeWithNullMipMapData) + TEST_F(AResourceTestClient, createTextureCubeWithEmptyMipMapData) { - const std::byte data[4 * 4 * 4] = {}; + const std::vector data(4 * 4 * 4); - std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data, data, nullptr, data, data, data); + std::vector mipLevelData{ { data, data, {}, data, data, data } }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 4u, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } - TEST_F(AResourceTestClient, createTextureCubeWithZeroSizeMipMapData) + TEST_F(AResourceTestClient, createTextureCubeWithMipMapDataOfDiffSize) { - const std::byte data[4 * 4 * 4] = {}; + const std::vector data(4 * 4 * 4); + const std::vector data1(1); - std::vector mipLevelData; - mipLevelData.emplace_back(0u, data, data, data, data, data, data); + std::vector mipLevelData{ { data, data, data1, data, data, data } }; TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 4u, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } - TEST_F(AResourceTestClient, createTextureCubeWithNullOrZeroSizeLowerMipMapData) + TEST_F(AResourceTestClient, createTextureCubeWithZeroSizeMipMapData) { - const std::byte data[2 * 2 * 4] = {}; - { - std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data, data, data, data, data, data); - mipLevelData.emplace_back(0u, data, data, data, data, data, data); - TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 2u, mipLevelData, false, {}, "name"); - EXPECT_EQ(nullptr, texture); - } + std::vector mipLevelData{ { {}, {}, {}, {}, {}, {} } }; + + TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 4u, mipLevelData, false, {}, "name"); + EXPECT_EQ(nullptr, texture); + } + + TEST_F(AResourceTestClient, createTextureCubeWithZeroSizeLowerMipMapData) + { + const std::vector data(2 * 2 * 4); { std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data, data, data, data, data, data); - mipLevelData.emplace_back(static_cast(sizeof(data)), data, data, data, data, nullptr, data); + mipLevelData.emplace_back(CubeMipLevelData{ data, data, data, data, data, data }); + mipLevelData.emplace_back(CubeMipLevelData{ {}, {}, {}, {}, {}, {} }); TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 2u, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } @@ -552,10 +511,11 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTextureCubeWithWrongSizeOfLowerMipMapData) { - const std::byte data[2 * 2 * 4] = {}; + const std::vector data(2 * 2 * 4); + const std::vector data2(1 * 1 * 2); std::vector mipLevelData; - mipLevelData.emplace_back(2 * 2 * 4, data, data, data, data, data, data); - mipLevelData.emplace_back(1 * 1 * 2, data, data, data, data, data, data); + mipLevelData.emplace_back(CubeMipLevelData{ data, data, data, data, data, data }); + mipLevelData.emplace_back(CubeMipLevelData{ data2, data2, data2, data2, data2, data2 }); TextureCube* texture = m_scene.createTextureCube(ETextureFormat::RGBA8, 2u, mipLevelData, false, {}, "name"); EXPECT_EQ(nullptr, texture); } @@ -566,8 +526,7 @@ namespace ramses::internal TEST_F(AResourceTestClient, create3DTextureAndDestroyManually) { - const uint8_t data[4 * 10 * 12 * 14] = {}; - const std::vector mipLevelData{ MipLevelData(static_cast(sizeof(data)), data) }; + const std::vector mipLevelData{ std::vector(4 * 10 * 12 * 14) }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 10, 12, 14, mipLevelData, false, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_TRUE(m_scene.destroy(*texture)); @@ -575,18 +534,17 @@ namespace ramses::internal TEST_F(AResourceTestClient, create3DTextureWithMipMaps) { - const uint8_t data[2 * 2 * 2 * 4] = {}; + const std::vector data(2 * 2 * 2 * 4); std::vector mipLevelData; - mipLevelData.emplace_back(2 * 2 * 2 * 4, data); - mipLevelData.emplace_back(1 * 1 * 1 * 4, data); + mipLevelData.emplace_back(data); + mipLevelData.emplace_back(data.begin(), data.begin() + 1 * 1 * 1 * 4); Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 2u, 2u, 2u, mipLevelData, false, "name"); ASSERT_TRUE(nullptr != texture); } TEST_F(AResourceTestClient, create3DTextureAndCheckWidthHeightDepth) { - const uint8_t data[4 * 10 * 12 * 14] = {}; - const std::vector mipLevelData{ MipLevelData(static_cast(sizeof(data)), data) }; + const std::vector mipLevelData{ std::vector(4 * 10 * 12 * 14) }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 10, 12, 14, mipLevelData, false, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_EQ(10u, texture->getWidth()); @@ -596,8 +554,7 @@ namespace ramses::internal TEST_F(AResourceTestClient, create3DTextureAndCheckFormat) { - const uint8_t data[3 * 10 * 12 * 14] = {}; - const std::vector mipLevelData{ MipLevelData(static_cast(sizeof(data)), data) }; + const std::vector mipLevelData{ std::vector(3 * 10 * 12 * 14) }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGB8, 10, 12, 14, mipLevelData, false, "name"); ASSERT_TRUE(nullptr != texture); EXPECT_EQ(ETextureFormat::RGB8, texture->getTextureFormat()); @@ -605,8 +562,8 @@ namespace ramses::internal TEST_F(AResourceTestClient, create3DTextureOfZeroSize) { - const uint8_t data[4 * 10 * 12 * 14] = {}; - const std::vector mipLevelData{ MipLevelData(static_cast(sizeof(data)), data) }; + const std::vector data(4 * 10 * 12 * 14); + const std::vector mipLevelData{ data }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 0, 0, 0, mipLevelData, false, "name"); EXPECT_EQ(nullptr, texture); } @@ -620,8 +577,7 @@ namespace ramses::internal TEST_F(AResourceTestClient, create3DTextureWithoutName) { - const uint8_t data[4 * 10 * 12 * 14] = {}; - const std::vector mipLevelData{ MipLevelData(static_cast(sizeof(data)), data) }; + const std::vector mipLevelData{ std::vector(4 * 10 * 12 * 14) }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 10, 12, 14, mipLevelData, false, {}); ASSERT_TRUE(nullptr != texture); EXPECT_TRUE(texture->getName().empty()); @@ -629,8 +585,7 @@ namespace ramses::internal TEST_F(AResourceTestClient, create3DTextureCheckHashIsValid) { - const uint8_t data[4 * 10 * 12 * 14] = {}; - const std::vector mipLevelData{ MipLevelData(static_cast(sizeof(data)), data) }; + const std::vector mipLevelData{ std::vector(4 * 10 * 12 * 14) }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 10, 12, 14, mipLevelData, false, "name"); ASSERT_TRUE(nullptr != texture); @@ -640,16 +595,16 @@ namespace ramses::internal TEST_F(AResourceTestClient, create3DTextureCheckHashIsUnique) { - uint8_t data[4 * 10 * 12 * 14] = {}; - data[20] = 48; - const std::vector mipLevelData1{ MipLevelData(static_cast(sizeof(data)), data) }; + std::vector data(4 * 10 * 12 * 14); + data[20] = std::byte{ 48 }; + const std::vector mipLevelData1{ data }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 10, 12, 14, mipLevelData1, false, "name"); ASSERT_TRUE(nullptr != texture); const ramses::internal::ResourceContentHash hash = texture->impl().getLowlevelResourceHash(); - uint8_t data2[4 * 10 * 12 * 14] = {}; - data[20] = 42; - const std::vector mipLevelData2{ MipLevelData(sizeof(data2), data2) }; + std::vector data2(4 * 10 * 12 * 14); + data[20] = std::byte{ 42 }; + const std::vector mipLevelData2{ data2 }; Texture3D* texture2 = m_scene.createTexture3D(ETextureFormat::RGBA8, 10, 12, 14, mipLevelData2, false, "name"); ASSERT_TRUE(nullptr != texture2); @@ -659,8 +614,8 @@ namespace ramses::internal TEST_F(AResourceTestClient, create3DTextureRGBA_AndCheckTexels) { - const auto data = make_byte_array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); - const std::vector mipLevelData{ MipLevelData(static_cast(data.size()), data.data()) }; + const auto data = make_byte_vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + const std::vector mipLevelData{ data }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 2, 1, 2, mipLevelData, false, {}); ASSERT_TRUE(nullptr != texture); @@ -672,8 +627,8 @@ namespace ramses::internal TEST_F(AResourceTestClient, create3DTextureRGB_AndCheckTexels) { - const auto data = make_byte_array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); - const std::vector mipLevelData{ MipLevelData(static_cast(data.size()), data.data()) }; + const auto data = make_byte_vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12); + const std::vector mipLevelData{ MipLevelData(data) }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGB8, 2, 1, 2, mipLevelData, false, {}); ASSERT_TRUE(nullptr != texture); @@ -685,9 +640,9 @@ namespace ramses::internal TEST_F(AResourceTestClient, create3DTextureRGBWithMips_AndCheckTexels) { - const auto data0 = make_byte_array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120); - const auto data1 = make_byte_array(13, 14, 15); - const std::vector mipLevelData = { MipLevelData{ static_cast(data0.size()), data0.data() }, MipLevelData{ static_cast(data1.size()), data1.data() } }; + const auto data0 = make_byte_vector(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120); + const auto data1 = make_byte_vector(13, 14, 15); + const std::vector mipLevelData = { data0, data1 }; const Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGB8, 2u, 2u, 2u, mipLevelData, false, {}); ASSERT_TRUE(nullptr != texture); @@ -700,11 +655,11 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTexture3DWithProvidedMipsButNotFullChain) { - const uint8_t data[4 * 4 * 4 * 4] = {}; + const std::vector data(4 * 4 * 4 * 4); std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data); - mipLevelData.emplace_back(2 * 2 * 2 * 4, data); + mipLevelData.emplace_back(data); + mipLevelData.emplace_back(data.begin(), data.begin() + 2 * 2 * 2 * 4); Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 4u, 4u, 4u, mipLevelData, false, "name"); EXPECT_NE(nullptr, texture); @@ -712,75 +667,42 @@ namespace ramses::internal TEST_F(AResourceTestClient, createTexture3DWithMoreMipsThanExpected) { - const uint8_t data[1] = {}; + const std::vector data(1); std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data); - mipLevelData.emplace_back(static_cast(sizeof(data)), data); + mipLevelData.emplace_back(data); + mipLevelData.emplace_back(data); Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 1u, 1u, 1u, mipLevelData, false, "name"); EXPECT_EQ(nullptr, texture); } - TEST_F(AResourceTestClient, create3DTextureWithNullMipMapData) - { - const uint8_t data[2 * 2 * 2 * 4] = {}; - const uint8_t* dataNullPtr{nullptr}; - - std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), dataNullPtr); - - Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 2u, 2u, 2u, mipLevelData, false, "name"); - EXPECT_EQ(nullptr, texture); - } - TEST_F(AResourceTestClient, create3DTextureWithZeroSizeMipMapData) { - const uint8_t data[2 * 2 * 2 * 4] = {}; - - std::vector mipLevelData; - mipLevelData.emplace_back(0, data); + std::vector mipLevelData{ {} }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 2u, 2u, 2u, mipLevelData, false, "name"); EXPECT_EQ(nullptr, texture); } - TEST_F(AResourceTestClient, create3DTextureWithNullOrZeroSizeLowerMipMapData) + TEST_F(AResourceTestClient, create3DTextureWithZeroSizeLowerMipMapData) { - const uint8_t data[2 * 2 * 2 * 4] = {}; - const uint8_t* dataNullPtr{nullptr}; + const std::vector data(2 * 2 * 2 * 4); { std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data); - mipLevelData.emplace_back(0u, data); + mipLevelData.emplace_back(data); + mipLevelData.emplace_back(0u); Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 2u, 2u, 2u, mipLevelData, false, "name"); EXPECT_EQ(nullptr, texture); } - { - std::vector mipLevelData; - mipLevelData.emplace_back(static_cast(sizeof(data)), data); - mipLevelData.emplace_back(static_cast(sizeof(data)), dataNullPtr); - Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 2u, 2u, 2u, mipLevelData, false, "name"); - EXPECT_EQ(nullptr, texture); - } - } - - TEST_F(AResourceTestClient, create3DTextureWithWrongSizeOfLowerMipMapData) - { - const uint8_t data[2 * 2 * 2 * 4] = {}; - std::vector mipLevelData; - mipLevelData.emplace_back(2 * 2 * 2 * 4, data); - mipLevelData.emplace_back(1 * 1 * 1 * 2, data); - Texture3D* texture = m_scene.createTexture3D(ETextureFormat::RGBA8, 2u, 2u, 2u, mipLevelData, false, "name"); - EXPECT_EQ(nullptr, texture); } TEST_F(AResourceTestClient, create3DTextureWithCompressedFormatCanBeCreatedWithArbitraryNonZeroDataSize) { - const uint8_t data[2 * 2 * 2 * 4] = {}; + const std::vector data(2 * 2 * 2 * 4); std::vector mipLevelData; - mipLevelData.emplace_back(1, data); - mipLevelData.emplace_back(1, data); + mipLevelData.emplace_back(data.begin(), data.begin() + 1); + mipLevelData.emplace_back(data.begin(), data.begin() + 1); Texture3D* texture = m_scene.createTexture3D(ETextureFormat::ASTC_RGBA_4x4, 2u, 2u, 2u, mipLevelData, false, "name"); EXPECT_TRUE(nullptr != texture); } diff --git a/tests/unittests/client/ScenePersistationTest.cpp b/tests/unittests/client/ScenePersistationTest.cpp index e411de401..618b0d0aa 100644 --- a/tests/unittests/client/ScenePersistationTest.cpp +++ b/tests/unittests/client/ScenePersistationTest.cpp @@ -99,8 +99,8 @@ namespace ramses::internal }); EXPECT_NE(nullptr, m_clientForLoading.loadSceneFromFile("someTemporaryFile.ram", {})); ramses::RamsesFramework::SetLogHandler(nullptr); - EXPECT_THAT(logs, Contains("Metadata: 'foo-bar-baz'")); - EXPECT_THAT(logs, Contains("Exporter version: 1.2.3 (file format version 7)")); + EXPECT_THAT(logs, Contains("R.main: Metadata: 'foo-bar-baz'")); + EXPECT_THAT(logs, Contains("R.main: Exporter version: 1.2.3 (file format version 7)")); } TEST_F(ASceneLoadedFromFile, loadedSceneHasReferenceToClientAndFrameworkAndMatchingFeaturelevel) @@ -604,7 +604,6 @@ namespace ramses::internal const Effect& loadedEffect = loadedGeometry->getEffect(); EXPECT_EQ(effect->getResourceId(), loadedEffect.getResourceId()); EXPECT_EQ(effect->impl().getLowlevelResourceHash(), loadedEffect.impl().getLowlevelResourceHash()); - EXPECT_EQ(effect->impl().getObjectRegistryHandle(), loadedEffect.impl().getObjectRegistryHandle()); EXPECT_EQ(4u, loadedEffect.getAttributeInputCount()); std::optional attributeInputOut = loadedEffect.findAttributeInput("a_position"); EXPECT_TRUE(attributeInputOut.has_value()); @@ -909,10 +908,7 @@ namespace ramses::internal } EXPECT_EQ(srcRenderBuffer->impl().getRenderBufferHandle(), loadedBlitPass->getSourceRenderBuffer().impl().getRenderBufferHandle()); - EXPECT_EQ(srcRenderBuffer->impl().getObjectRegistryHandle(), loadedBlitPass->getSourceRenderBuffer().impl().getObjectRegistryHandle()); - EXPECT_EQ(dstRenderBuffer->impl().getRenderBufferHandle(), loadedBlitPass->getDestinationRenderBuffer().impl().getRenderBufferHandle()); - EXPECT_EQ(dstRenderBuffer->impl().getObjectRegistryHandle(), loadedBlitPass->getDestinationRenderBuffer().impl().getObjectRegistryHandle()); } TEST_F(ASceneLoadedFromFile, canReadWritePickableObject) @@ -952,10 +948,7 @@ namespace ramses::internal EXPECT_EQ(pickableCamera->impl().getCameraHandle(), pickableObjectInternal.cameraHandle); EXPECT_EQ(geometryBuffer->impl().getDataBufferHandle(), loadedPickableObject->getGeometryBuffer().impl().getDataBufferHandle()); - EXPECT_EQ(geometryBuffer->impl().getObjectRegistryHandle(), loadedPickableObject->getGeometryBuffer().impl().getObjectRegistryHandle()); - EXPECT_EQ(pickableCamera->impl().getCameraHandle(), loadedPickableObject->getCamera()->impl().getCameraHandle()); - EXPECT_EQ(pickableCamera->impl().getObjectRegistryHandle(), loadedPickableObject->getCamera()->impl().getObjectRegistryHandle()); } TEST_F(ASceneLoadedFromFile, canReadWriteRenderBuffer) @@ -1057,8 +1050,8 @@ namespace ramses::internal TEST_F(ASceneLoadedFromFile, canReadWriteTexture2DBuffer) { Texture2DBuffer& buffer = *m_scene.createTexture2DBuffer(ETextureFormat::RGBA8, 3, 4, 2, "textureBuffer"); - buffer.updateData(0, 0, 0, 2, 2, std::array{ {12, 23, 34, 56} }.data()); - buffer.updateData(1, 0, 0, 1, 1, std::array{ {78} }.data()); + buffer.updateData(0, 0, 0, 2, 2, UnsafeTestMemoryHelpers::ConvertToBytes({12, 23, 34, 56})); + buffer.updateData(1, 0, 0, 1, 1, UnsafeTestMemoryHelpers::ConvertToBytes({78})); doWriteReadCycle(); @@ -1241,8 +1234,8 @@ namespace ramses::internal const ETextureAddressMode wrapVMode = ETextureAddressMode::Repeat; const ETextureSamplingMethod minSamplingMethod = ETextureSamplingMethod::Linear_MipMapNearest; const ETextureSamplingMethod magSamplingMethod = ETextureSamplingMethod::Linear; - const uint8_t data[4] = { 0u }; - const std::vector mipLevelData{ MipLevelData(sizeof(data), data) }; + const std::vector data(4, std::byte{ 0u }); + const std::vector mipLevelData{ data }; Texture2D* texture = this->m_scene.createTexture2D(ETextureFormat::RGBA8, 1u, 1u, mipLevelData, false, {}, "texture"); auto* sampler = this->m_scene.createTextureSampler(wrapUMode, wrapVMode, minSamplingMethod, magSamplingMethod, *texture, 8u, "sampler"); diff --git a/tests/unittests/client/ScenePersistationTest.h b/tests/unittests/client/ScenePersistationTest.h index f50b6fc8c..bdd157190 100644 --- a/tests/unittests/client/ScenePersistationTest.h +++ b/tests/unittests/client/ScenePersistationTest.h @@ -108,9 +108,7 @@ namespace ramses::internal void checkSceneFile(const char* filename) { std::vector buffer; - SaveFileConfigImpl config; - config.setValidationEnabled(false); - EXPECT_TRUE(m_scene.impl().serialize(buffer, config)); + EXPECT_TRUE(m_scene.impl().serialize(buffer, {})); EXPECT_FALSE(buffer.empty()); ramses::internal::File f(filename); @@ -129,7 +127,6 @@ namespace ramses::internal { SaveFileConfig config; config.setCompressionEnabled(withCompression); - config.setValidationEnabled(false); ASSERT_TRUE(m_scene.saveToFile("someTemporaryFile.ram", config)); checkSceneFile("someTemporaryFile.ram"); diff --git a/tests/unittests/client/ScenePersistationThreadedTest.cpp b/tests/unittests/client/ScenePersistationThreadedTest.cpp index 9e677a183..99b0d6c6a 100644 --- a/tests/unittests/client/ScenePersistationThreadedTest.cpp +++ b/tests/unittests/client/ScenePersistationThreadedTest.cpp @@ -46,9 +46,7 @@ namespace ramses::internal Scene* scene = CreateScene(client, sceneId); ASSERT_TRUE(scene != nullptr); - SaveFileConfig config; - config.setValidationEnabled(false); - ASSERT_TRUE(scene->saveToFile(sceneFilename, config)); + ASSERT_TRUE(scene->saveToFile(sceneFilename, {})); } private: diff --git a/tests/unittests/client/SceneTest.cpp b/tests/unittests/client/SceneTest.cpp index 6dbc794cd..83c2a1a65 100644 --- a/tests/unittests/client/SceneTest.cpp +++ b/tests/unittests/client/SceneTest.cpp @@ -22,7 +22,13 @@ #include "ramses/client/OrthographicCamera.h" #include "ramses/client/PerspectiveCamera.h" #include "ramses/client/ArrayBuffer.h" +#include "ramses/client/RenderBuffer.h" +#include "ramses/client/RenderTargetDescription.h" +#include "ramses/client/RenderTarget.h" #include "ramses/client/logic/TimerNode.h" +#include "ramses/client/logic/LuaScript.h" +#include "ramses/client/logic/Property.h" +#include "ramses/client/logic/NodeBinding.h" #include "ramses/client/ramses-utils.h" #include "ramses/framework/EDataType.h" @@ -33,6 +39,7 @@ #include "impl/BlitPassImpl.h" #include "impl/TextureSamplerImpl.h" #include "impl/Texture2DImpl.h" +#include "impl/RenderBufferImpl.h" #include "impl/SceneConfigImpl.h" #include "ClientTestUtils.h" #include "SimpleSceneTopology.h" @@ -308,8 +315,7 @@ namespace ramses::internal { ramses::Scene& anotherScene(*client.createScene(SceneConfig(sceneId_t{ 0xf00 }))); { - const uint8_t data[] = { 1, 2, 3 }; - const std::vector mipData({ MipLevelData(3u, data) }); + const std::vector mipData{ { std::byte{1}, std::byte{2}, std::byte{3} } }; Texture2D* texture = anotherScene.createTexture2D(ETextureFormat::RGB8, 1u, 1u, mipData, false); ASSERT_TRUE(texture != nullptr); @@ -317,8 +323,11 @@ namespace ramses::internal EXPECT_TRUE(nullptr == textureSampler); } { - const uint8_t data[1 * 2 * 2 * 4] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 }; - std::vector mipLevelData({ MipLevelData(sizeof(data), data) }); + const MipLevelData data = { + std::byte{1}, std::byte{2}, std::byte{3}, std::byte{4}, std::byte{5}, std::byte{6}, std::byte{7}, std::byte{8}, + std::byte{9}, std::byte{10}, std::byte{11}, std::byte{12}, std::byte{13}, std::byte{14}, std::byte{15}, std::byte{16} }; + ASSERT_TRUE(data.size() == 1 * 2 * 2 * 4); + std::vector mipLevelData{ data }; Texture3D* texture = anotherScene.createTexture3D(ETextureFormat::RGBA8, 2, 1, 2, mipLevelData, false, {}); ASSERT_TRUE(nullptr != texture); @@ -326,8 +335,8 @@ namespace ramses::internal EXPECT_TRUE(nullptr == textureSampler); } { - const std::byte data[4 * 10 * 10] = {}; - std::vector mipLevelData{ CubeMipLevelData(sizeof(data), data, data, data, data, data, data) }; + const std::vector data(4 * 10 * 10); + std::vector mipLevelData{ { data, data, data, data, data, data } }; TextureCube* texture = anotherScene.createTextureCube(ETextureFormat::RGBA8, 10, mipLevelData, false); ASSERT_TRUE(nullptr != texture); @@ -930,8 +939,7 @@ namespace ramses::internal RamsesFrameworkConfig config{EFeatureLevel_Latest}; RamsesFramework anotherFramework{config}; ramses::Scene& anotherScene(*client.createScene(SceneConfig(sceneId_t{ 0xf00 }))); - uint8_t data = 0u; - const std::vector mipData{ MipLevelData(1u, &data) }; + const std::vector mipData{ { std::byte{ 0u } } }; const Texture2D* texture = anotherScene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData, false); ASSERT_TRUE(nullptr != texture); @@ -941,8 +949,7 @@ namespace ramses::internal TEST_F(AScene, reportsErrorWhenCreateTextureConsumerWithSamplerFromAnotherScene) { ramses::Scene& anotherScene = *client.createScene(SceneConfig(sceneId_t(12u))); - uint8_t data = 0u; - const std::vector mipData{ MipLevelData(1u, &data) }; + const std::vector mipData{ { std::byte{ 0u } } }; Texture2D* texture = anotherScene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData, false); ASSERT_TRUE(nullptr != texture); @@ -983,8 +990,7 @@ namespace ramses::internal { EXPECT_EQ(0u, m_scene.impl().getIScene().getDataSlotCount()); - uint8_t data = 0u; - const std::vector mipData{ MipLevelData(1u, &data) }; + const std::vector mipData{ { std::byte{ 0u } } }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData, false); ASSERT_TRUE(nullptr != texture); @@ -1002,13 +1008,11 @@ namespace ramses::internal { EXPECT_EQ(0u, m_scene.impl().getIScene().getDataSlotCount()); - uint8_t data1 = 0u; - const std::vector mipData1{ MipLevelData(1u, &data1) }; + const std::vector mipData1{ { std::byte{ 0u } } }; Texture2D* texture1 = m_scene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData1, false); ASSERT_TRUE(nullptr != texture1); - uint8_t data2 = 1u; - const std::vector mipData2{ MipLevelData(1u, &data2) }; + const std::vector mipData2{ { std::byte{ 1u } } }; Texture2D* texture2 = m_scene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData2, false); ASSERT_TRUE(nullptr != texture2); @@ -1027,8 +1031,7 @@ namespace ramses::internal { EXPECT_EQ(0u, m_scene.impl().getIScene().getDataSlotCount()); - uint8_t data = 0u; - const std::vector mipData{ MipLevelData(1u, &data) }; + const std::vector mipData{ { std::byte{0u} } }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData, false); ASSERT_TRUE(nullptr != texture); @@ -1088,8 +1091,7 @@ namespace ramses::internal { EXPECT_EQ(0u, m_scene.impl().getIScene().getDataSlotCount()); - uint8_t data = 0u; - const std::vector mipData{ MipLevelData(1u, &data) }; + const std::vector mipData{ { std::byte{ 0u } } }; Texture3D* texture = m_scene.createTexture3D(ETextureFormat::R8, 1u, 1u, 1u, mipData, false); ASSERT_TRUE(nullptr != texture); @@ -1101,8 +1103,7 @@ namespace ramses::internal TEST_F(AScene, removesDataSlotsOfTextureSamplerOnDestruction) { - uint8_t data = 0u; - const std::vector mipData{ MipLevelData(1u, &data) }; + const std::vector mipData{ { std::byte{ 0u } } }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData, false); ASSERT_TRUE(nullptr != texture); @@ -1122,8 +1123,7 @@ namespace ramses::internal TEST_F(AScene, canNotCreateMoreThanOneConsumerForATextureSampler) { - uint8_t data = 0u; - const std::vector mipData{ MipLevelData(1u, &data) }; + const std::vector mipData{ { std::byte{ 0u } } }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData, false); ASSERT_TRUE(nullptr != texture); @@ -1157,8 +1157,7 @@ namespace ramses::internal TEST_F(AScene, canNotCreateMoreThanOneProviderForATexture) { - uint8_t data = 0u; - const std::vector mipData{ MipLevelData(1u, &data) }; + const std::vector mipData{ { std::byte{ 0u } } }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData, false); ASSERT_TRUE(nullptr != texture); @@ -1168,8 +1167,7 @@ namespace ramses::internal TEST_F(AScene, canNotCreateMoreThanOneTextureConsumerOrProviderWithTheSameId) { - uint8_t data = 0u; - const std::vector mipData{ MipLevelData(1u, &data) }; + const std::vector mipData{ { std::byte{ 0u } } }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData, false); ASSERT_TRUE(nullptr != texture); Texture2D* texture2 = m_scene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData, false); @@ -1191,8 +1189,7 @@ namespace ramses::internal TEST_F(AScene, canNotUpdateTextureProviderWhichWasNotCreatedBefore) { - uint8_t data = 0u; - const std::vector mipData{ MipLevelData(1u, &data) }; + const std::vector mipData{ { std::byte{ 0u } } }; Texture2D* texture = m_scene.createTexture2D(ETextureFormat::R8, 1u, 1u, mipData, false); ASSERT_TRUE(nullptr != texture); @@ -1723,4 +1720,202 @@ namespace ramses::internal // only one remaining scene object with test name EXPECT_EQ(logicObject, m_scene.findObject("test")); } + + TEST_F(AScene, willFailFlushIfRenderTargetInvalid) + { + const auto rb1 = m_scene.createRenderBuffer(1u, 2u, ERenderBufferFormat::R16F, ERenderBufferAccessMode::ReadWrite, 3u); + const auto rb2 = m_scene.createRenderBuffer(1u, 2u, ERenderBufferFormat::R16F, ERenderBufferAccessMode::ReadWrite, 3u); + EXPECT_TRUE(m_scene.flush()); + + RenderTargetDescription desc; + EXPECT_TRUE(desc.addRenderBuffer(*rb1)); + EXPECT_TRUE(desc.addRenderBuffer(*rb2)); + const auto rt = m_scene.createRenderTarget(desc); + EXPECT_TRUE(m_scene.flush()); + + // simulate RB properties changed, there is currently no direct public API (only RenderBufferBinding via LogicEngine) + EXPECT_TRUE(rb2->impl().setProperties(1u, 1u, 1u)); + + EXPECT_FALSE(m_scene.flush()); + const auto err = framework.getLastError(); + ASSERT_TRUE(err); + EXPECT_EQ(rt, err->object); + EXPECT_EQ("Scene::flush: Flushing scene failed: RenderTarget uses render buffers with mismatching resolution and/or sample count." + " This RenderTarget cannot be used and attempt to flush scene will fail.", err->message); + + // back to matching values + EXPECT_TRUE(rb2->impl().setProperties(1u, 2u, 3u)); + EXPECT_TRUE(m_scene.flush()); + } + + TEST_F(AScene, willFailFlushIfBlitPassInvalid) + { + const auto rb1 = m_scene.createRenderBuffer(1u, 2u, ERenderBufferFormat::R16F, ERenderBufferAccessMode::ReadWrite, 3u); + const auto rb2 = m_scene.createRenderBuffer(1u, 2u, ERenderBufferFormat::R16F, ERenderBufferAccessMode::ReadWrite, 3u); + EXPECT_TRUE(m_scene.flush()); + + const auto bp = m_scene.createBlitPass(*rb1, *rb2); + EXPECT_TRUE(m_scene.flush()); + + // simulate RB properties changed, there is currently no direct public API (only RenderBufferBinding via LogicEngine) + EXPECT_TRUE(rb2->impl().setProperties(1u, 1u, 1u)); + + EXPECT_FALSE(m_scene.flush()); + const auto err = framework.getLastError(); + ASSERT_TRUE(err); + EXPECT_EQ(bp, err->object); + EXPECT_EQ("Scene::flush: Flushing scene failed: blitpass blit region out of source or destination buffer size", err->message); + + // back to matching values + EXPECT_TRUE(rb2->impl().setProperties(1u, 2u, 3u)); + EXPECT_TRUE(m_scene.flush()); + } + + TEST_F(AScene, failedFlushDoesNotSendChanges) + { + // create valid RT and flush + const auto rb1 = m_scene.createRenderBuffer(1u, 2u, ERenderBufferFormat::R16F, ERenderBufferAccessMode::ReadWrite, 3u); + const auto rb2 = m_scene.createRenderBuffer(1u, 2u, ERenderBufferFormat::R16F, ERenderBufferAccessMode::ReadWrite, 3u); + RenderTargetDescription desc; + EXPECT_TRUE(desc.addRenderBuffer(*rb1)); + EXPECT_TRUE(desc.addRenderBuffer(*rb2)); + m_scene.createRenderTarget(desc); + EXPECT_TRUE(m_scene.flush()); + + // publis scene to initiate sending of actions + { + EXPECT_CALL(sceneActionsCollector, handleNewSceneAvailable(_, _)); + EXPECT_TRUE(m_scene.publish(ramses::EScenePublicationMode::LocalOnly)); + // first flush sends scene init + EXPECT_CALL(sceneActionsCollector, handleInitializeScene(_, _)); + // send update + EXPECT_CALL(sceneActionsCollector, handleSceneUpdate_rvr(_, _, _)).Times(1u); + EXPECT_TRUE(m_scene.flush()); + } + + // simulate invalid RT so that next flush fails + EXPECT_TRUE(rb2->impl().setProperties(1u, 1u, 1u)); + + // no action sent due to failed flush + EXPECT_CALL(sceneActionsCollector, handleSceneUpdate_rvr(_, _, _)).Times(0u); + EXPECT_FALSE(m_scene.flush()); + + // fix invalid RT so flush succeeds + EXPECT_TRUE(rb2->impl().setProperties(1u, 2u, 3u)); + // now changes are sent + EXPECT_CALL(sceneActionsCollector, handleSceneUpdate_rvr(_, _, _)).Times(1u); + EXPECT_TRUE(m_scene.flush()); + + EXPECT_CALL(sceneActionsCollector, handleSceneBecameUnavailable(_, _)); + } + + TEST_F(AScene, failsToSaveToFileIfFlushFails) + { + // simulate invalid RT so that flush fails + const auto rb1 = m_scene.createRenderBuffer(1u, 2u, ERenderBufferFormat::R16F, ERenderBufferAccessMode::ReadWrite, 3u); + const auto rb2 = m_scene.createRenderBuffer(1u, 2u, ERenderBufferFormat::R16F, ERenderBufferAccessMode::ReadWrite, 3u); + RenderTargetDescription desc; + EXPECT_TRUE(desc.addRenderBuffer(*rb1)); + EXPECT_TRUE(desc.addRenderBuffer(*rb2)); + m_scene.createRenderTarget(desc); + EXPECT_TRUE(m_scene.flush()); + EXPECT_TRUE(rb2->impl().setProperties(1u, 1u, 1u)); // mismatching RBs + EXPECT_FALSE(m_scene.flush()); + + EXPECT_FALSE(m_scene.saveToFile("will_not_write")); + const auto err = framework.getLastError(); + ASSERT_TRUE(err); + EXPECT_EQ(&m_scene, err->object); + EXPECT_EQ("Scene::saveToFile failed due to failed scene flush: Scene::flush: Flushing scene failed: RenderTarget uses render buffers with mismatching resolution and/or sample count." + " This RenderTarget cannot be used and attempt to flush scene will fail.", err->message); + + // fix invalid RT so flush succeeds + EXPECT_TRUE(rb2->impl().setProperties(1u, 2u, 3u)); + EXPECT_TRUE(m_scene.saveToFile("tmp.ramses")); + } + + TEST_F(AScene, failsToSaveToFileIfLogicEngineUpdateFails) + { + const std::string_view srcCode = R"( + function interface(IN,OUT) + IN.target = Type:Bool() + OUT.source = Type:Bool() + end + function run(IN,OUT) + error("This will die") + end + )"; + + // simulate error in script so that update fails + auto logic = m_scene.createLogicEngine(); + LuaConfig config; + config.addStandardModuleDependency(EStandardModule::Base); + auto script = logic->createLuaScript(srcCode, config); + EXPECT_FALSE(logic->update()); + + EXPECT_FALSE(m_scene.saveToFile("will_not_write")); + const auto err = framework.getLastError(); + ASSERT_TRUE(err); + EXPECT_EQ(logic, err->object); + EXPECT_EQ("Scene::saveToFile failed due to failed logic engine update: [string \"RL_lua_script\"]:7:" + " This will die\nstack traceback:\n\t[C]: in function 'error'\n\t[string \"RL_lua_script\"]:7: in function <[string \"RL_lua_script\"]:6>", err->message); + + // destroy invalid script so update succeeds + EXPECT_TRUE(logic->destroy(*script)); + EXPECT_TRUE(m_scene.saveToFile("tmp.ramses")); + } + + TEST_F(ASceneWithContent, sceneIsFlushedBeforeSavingAndHierarchicalVisibilityIsAppliedToSavedFile) + { + // set root invisible and flush so all children are invisible + EXPECT_TRUE(m_vis1.setVisibility(EVisibilityMode::Invisible)); + EXPECT_TRUE(m_scene.flush()); + EXPECT_EQ(m_mesh1a.impl().getFlattenedVisibility(), EVisibilityMode::Invisible); + EXPECT_EQ(m_mesh1b.impl().getFlattenedVisibility(), EVisibilityMode::Invisible); + + // destroying root will make children visible again, dont flush, only save to file + EXPECT_TRUE(m_scene.destroy(m_vis1)); + EXPECT_TRUE(m_scene.saveToFile("tmp.ramses")); + // hierchical visibility was applied, children are now visible + EXPECT_EQ(m_mesh1a.impl().getFlattenedVisibility(), EVisibilityMode::Visible); + EXPECT_EQ(m_mesh1b.impl().getFlattenedVisibility(), EVisibilityMode::Visible); + + // same state (visible children) was saved to file + EXPECT_TRUE(client.destroy(m_scene)); + auto loadedScene = client.loadSceneFromFile("tmp.ramses"); + ASSERT_TRUE(loadedScene); + EXPECT_EQ(loadedScene->findObject("mesh1a")->impl().getFlattenedVisibility(), EVisibilityMode::Visible); + EXPECT_EQ(loadedScene->findObject("mesh1b")->impl().getFlattenedVisibility(), EVisibilityMode::Visible); + } + + TEST_F(AScene, logicEngineIsUpdatedBeforeSaving) + { + auto node = m_scene.createNode("boundNode"); + auto logic = m_scene.createLogicEngine(); + auto binding = logic->createNodeBinding(*node); + EXPECT_TRUE(binding->getInputs()->getChild("translation")->set(glm::vec3{ 1, 2, 3 })); + EXPECT_TRUE(logic->update()); + glm::vec3 nodeTr; + EXPECT_TRUE(node->getTranslation(nodeTr)); + EXPECT_EQ(glm::vec3(1, 2, 3), nodeTr); + + // now set translation via binding to new value but with no update + EXPECT_TRUE(binding->getInputs()->getChild("translation")->set(glm::vec3{ 111, 222, 333 })); + // no change in node + EXPECT_TRUE(node->getTranslation(nodeTr)); + EXPECT_EQ(glm::vec3(1, 2, 3), nodeTr); + + // saving should update logic + EXPECT_TRUE(m_scene.saveToFile("tmp.ramses")); + // now node changed + EXPECT_TRUE(node->getTranslation(nodeTr)); + EXPECT_EQ(glm::vec3(111, 222, 333), nodeTr); + + // same state (node with new values) was saved to file + EXPECT_TRUE(client.destroy(m_scene)); + auto loadedScene = client.loadSceneFromFile("tmp.ramses"); + ASSERT_TRUE(loadedScene); + EXPECT_TRUE(loadedScene->findObject("boundNode")->getTranslation(nodeTr)); + EXPECT_EQ(glm::vec3(111, 222, 333), nodeTr); + } } diff --git a/tests/unittests/client/Texture2DBufferTest.cpp b/tests/unittests/client/Texture2DBufferTest.cpp index 52a8d2c0f..42d99f8c5 100644 --- a/tests/unittests/client/Texture2DBufferTest.cpp +++ b/tests/unittests/client/Texture2DBufferTest.cpp @@ -88,7 +88,7 @@ namespace ramses::internal const ramses::internal::TextureBufferHandle textureBufferHandle = textureBuffer.impl().getTextureBufferHandle(); // update mipLevel = 0 - EXPECT_TRUE(textureBuffer.updateData(0, 0, 0, 2, 2, std::array{ {12, 23, 34, 56} }.data())); + EXPECT_TRUE(textureBuffer.updateData(0, 0, 0, 2, 2, UnsafeTestMemoryHelpers::ConvertToBytes({12, 23, 34, 56}))); const std::byte* textureBufferDataMip0 = this->m_scene.impl().getIScene().getTextureBuffer(textureBufferHandle).mipMaps[0].data.data(); EXPECT_EQ(12u, UnsafeTestMemoryHelpers::GetTypedValueFromMemoryBlob(textureBufferDataMip0, 0)); @@ -97,7 +97,7 @@ namespace ramses::internal EXPECT_EQ(56u, UnsafeTestMemoryHelpers::GetTypedValueFromMemoryBlob(textureBufferDataMip0, 3 * 1 + 1)); // update mipLevel = 1 - EXPECT_TRUE(textureBuffer.updateData(1, 0, 0, 1, 1, std::array{ {78} }.data())); + EXPECT_TRUE(textureBuffer.updateData(1, 0, 0, 1, 1, UnsafeTestMemoryHelpers::ConvertToBytes({78}))); const std::byte* textureBufferDataMip1 = this->m_scene.impl().getIScene().getTextureBuffer(textureBufferHandle).mipMaps[1].data.data(); EXPECT_EQ(78u, UnsafeTestMemoryHelpers::GetTypedValueFromMemoryBlob(textureBufferDataMip1, 0)); } @@ -107,7 +107,7 @@ namespace ramses::internal Texture2DBuffer& textureBuffer = *m_scene.createTexture2DBuffer(ETextureFormat::RGBA8, 3, 4, 2); // update mipLevel = 0 - EXPECT_TRUE(textureBuffer.updateData(0, 0, 0, 2, 2, std::array{ {12, 23, 34, 56} }.data())); + EXPECT_TRUE(textureBuffer.updateData(0, 0, 0, 2, 2, UnsafeTestMemoryHelpers::ConvertToBytes({12, 23, 34, 56}))); std::array mipLevel0RetrievedData{}; textureBuffer.getMipLevelData(0u, mipLevel0RetrievedData.data(), textureBuffer.getMipLevelDataSizeInBytes(0u)); @@ -118,7 +118,7 @@ namespace ramses::internal EXPECT_EQ(56u, mipLevel0RetrievedData[3 * 1 + 1]); // update mipLevel = 1 - EXPECT_TRUE(textureBuffer.updateData(1, 0, 0, 1, 1, std::array{ {78} }.data())); + EXPECT_TRUE(textureBuffer.updateData(1, 0, 0, 1, 1, UnsafeTestMemoryHelpers::ConvertToBytes({78}))); std::array mipLevel1RetrievedData{}; textureBuffer.getMipLevelData(1u, mipLevel1RetrievedData.data(), textureBuffer.getMipLevelDataSizeInBytes(1u)); @@ -130,13 +130,13 @@ namespace ramses::internal { Texture2DBuffer& textureBuffer = *m_scene.createTexture2DBuffer(ETextureFormat::RGBA8, 3, 4, 2); - EXPECT_TRUE(textureBuffer.updateData(0, 0, 0, 2, 2, std::array{ {12, 23, 34, 56} }.data())); + EXPECT_TRUE(textureBuffer.updateData(0, 0, 0, 2, 2, UnsafeTestMemoryHelpers::ConvertToBytes({12, 23, 34, 56}))); std::array mipLevel0RetrievedData{}; textureBuffer.getMipLevelData(0u, &mipLevel0RetrievedData, sizeof(uint32_t) * 2u); EXPECT_EQ(12u, mipLevel0RetrievedData[0]); EXPECT_EQ(23u, mipLevel0RetrievedData[1]); - EXPECT_TRUE(textureBuffer.updateData(1, 0, 0, 1, 2, std::array{ {78, 87} }.data())); + EXPECT_TRUE(textureBuffer.updateData(1, 0, 0, 1, 2, UnsafeTestMemoryHelpers::ConvertToBytes({78, 87}))); uint32_t mipLevel1RetrievedData{}; textureBuffer.getMipLevelData(1u, &mipLevel1RetrievedData, sizeof(uint32_t)); EXPECT_EQ(78u, mipLevel1RetrievedData); @@ -146,10 +146,10 @@ namespace ramses::internal { Texture2DBuffer& textureBuffer = *m_scene.createTexture2DBuffer(ETextureFormat::RGBA8, 3, 4, 2); - EXPECT_FALSE(textureBuffer.updateData(0, 0, 0, 0, 0, std::array().data())); - EXPECT_FALSE(textureBuffer.updateData(0, 2, 2, 0, 0, std::array().data())); - EXPECT_FALSE(textureBuffer.updateData(1, 0, 0, 0, 0, std::array().data())); - EXPECT_FALSE(textureBuffer.updateData(1, 1, 1, 0, 0, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(0, 0, 0, 0, 0, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(0, 2, 2, 0, 0, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(1, 0, 0, 0, 0, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(1, 1, 1, 0, 0, std::array().data())); } TEST_F(ATexture2DBuffer, CanNotBeUpdatedWithDataSizeBiggerThanMaximumSize) @@ -157,26 +157,26 @@ namespace ramses::internal Texture2DBuffer& textureBuffer = *m_scene.createTexture2DBuffer(ETextureFormat::RGBA8, 3, 4, 2); // offset exceeds total size - EXPECT_FALSE(textureBuffer.updateData(0, 3, 0, 1, 1, std::array().data())); - EXPECT_FALSE(textureBuffer.updateData(0, 0, 4, 1, 1, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(0, 3, 0, 1, 1, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(0, 0, 4, 1, 1, std::array().data())); // width/height exceed total size - EXPECT_FALSE(textureBuffer.updateData(0, 0, 0, 3+1, 1, std::array().data())); - EXPECT_FALSE(textureBuffer.updateData(0, 0, 0, 1, 4 + 1, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(0, 0, 0, 3+1, 1, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(0, 0, 0, 1, 4 + 1, std::array().data())); // offset + width/height exceed total size - EXPECT_FALSE(textureBuffer.updateData(0, 1, 0, 3, 1, std::array().data())); - EXPECT_FALSE(textureBuffer.updateData(0, 0, 1, 1, 4, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(0, 1, 0, 3, 1, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(0, 0, 1, 1, 4, std::array().data())); // second mipmap - EXPECT_FALSE(textureBuffer.updateData(0, 1, 0, 3, 1, std::array().data())); - EXPECT_FALSE(textureBuffer.updateData(0, 0, 1, 1, 4, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(0, 1, 0, 3, 1, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(0, 0, 1, 1, 4, std::array().data())); } TEST_F(ATexture2DBuffer, CanNotBeUpdatedForUnexistingMipMapLevel) { Texture2DBuffer& textureBuffer = *m_scene.createTexture2DBuffer(ETextureFormat::RGBA8, 3, 4, 2); - EXPECT_FALSE(textureBuffer.updateData(3, 0, 0, 1, 1, std::array().data())); + EXPECT_FALSE(textureBuffer.updateData(3, 0, 0, 1, 1, std::array().data())); } TEST_F(ATexture2DBuffer, RetrievesMipMapCount) @@ -216,7 +216,7 @@ namespace ramses::internal TEST_F(ATexture2DBuffer, CanBeValidated) { Texture2DBuffer& textureBuffer = *m_scene.createTexture2DBuffer(ETextureFormat::RGBA8, 4, 4, 1); - EXPECT_TRUE(textureBuffer.updateData(0, 0, 0, 2, 2, std::array{ {12, 23, 34, 56} }.data())); + EXPECT_TRUE(textureBuffer.updateData(0, 0, 0, 2, 2, UnsafeTestMemoryHelpers::ConvertToBytes({12, 23, 34, 56}))); m_scene.createTextureSampler(ETextureAddressMode::Clamp, ETextureAddressMode::Clamp, ETextureSamplingMethod::Linear, ETextureSamplingMethod::Linear, textureBuffer); ValidationReport report; textureBuffer.validate(report); @@ -226,7 +226,7 @@ namespace ramses::internal TEST_F(ATexture2DBuffer, ReportsWarningIfNotUsedInSampler) { Texture2DBuffer& textureBuffer = *m_scene.createTexture2DBuffer(ETextureFormat::RGBA8, 4, 4, 1); - EXPECT_TRUE(textureBuffer.updateData(0, 0, 0, 2, 2, std::array{ {12, 23, 34, 56} }.data())); + EXPECT_TRUE(textureBuffer.updateData(0, 0, 0, 2, 2, UnsafeTestMemoryHelpers::ConvertToBytes({12, 23, 34, 56}))); ValidationReport report; textureBuffer.validate(report); EXPECT_TRUE(report.hasIssue()); diff --git a/tests/unittests/client/logic/api/AnchorPointTest.cpp b/tests/unittests/client/logic/api/AnchorPointTest.cpp index 71312719f..1b48a22b8 100644 --- a/tests/unittests/client/logic/api/AnchorPointTest.cpp +++ b/tests/unittests/client/logic/api/AnchorPointTest.cpp @@ -38,13 +38,6 @@ namespace ramses::internal CameraBinding& m_cameraBinding{ *m_logicEngine->createCameraBinding(*m_camera) }; }; - TEST_F(AnAnchorPoint, HasANameAndIdAfterCreation) - { - const auto& anchorPoint = *m_logicEngine->createAnchorPoint(m_nodeBinding, m_cameraBinding, "anchor"); - EXPECT_EQ("anchor", anchorPoint.getName()); - EXPECT_EQ(11u, anchorPoint.getSceneObjectId().getValue()); - } - TEST_F(AnAnchorPoint, ReferencesBindings) { auto& anchorPoint = *m_logicEngine->createAnchorPoint(m_nodeBinding, m_cameraBinding, "anchor"); diff --git a/tests/unittests/client/logic/api/AnimationNodeTest.cpp b/tests/unittests/client/logic/api/AnimationNodeTest.cpp index 8c52de7b8..0684223c9 100644 --- a/tests/unittests/client/logic/api/AnimationNodeTest.cpp +++ b/tests/unittests/client/logic/api/AnimationNodeTest.cpp @@ -38,8 +38,6 @@ namespace ramses::internal // Quaternions which are not normalized (ie. not of unit length). Used for tests to check they are normalized correctly m_dataVec4 = m_logicEngine->createDataArray(std::vector{ { 2.f, 0.f, 0.f, 0.f }, { 0.f, 2.f, 0.f, 0.f } , { 0.f, 0.f, 2.f, 0.f } }); m_dataVecVec = m_logicEngine->createDataArray(std::vector>{ { 1.f, 2.f, 3.f, 4.f, 5.f }, { 3.f, 4.f, 5.f, 6.f, 7.f }, { 5.f, 6.f, 7.f, 8.f, 9.f } }); - - m_saveFileConfigNoValidation.setValidationEnabled(false); } protected: @@ -155,7 +153,7 @@ namespace ramses::internal auto& otherEngine = *m_scene->createLogicEngine(); EXPECT_FALSE(otherEngine.destroy(*animNode)); - EXPECT_EQ("Failed to destroy object 'animNode [LogicObject ScnObjId=13]', cannot find it in this LogicEngine instance.", getLastErrorMessage()); + EXPECT_EQ("Failed to destroy object 'animNode [LogicObject ScnObjId=14]', cannot find it in this LogicEngine instance.", getLastErrorMessage()); } TEST_P(AnAnimationNode, ChangesName) @@ -326,7 +324,7 @@ namespace ramses::internal otherEngine.createAnimationNode(config1, "animNode1"); otherEngine.createAnimationNode(config2, "animNode2"); - ASSERT_TRUE(saveToFileWithoutValidation("logic_animNodes.bin")); + ASSERT_TRUE(saveToFile("logic_animNodes.bin")); } ASSERT_TRUE(recreateFromFile("logic_animNodes.bin")); @@ -436,7 +434,7 @@ namespace ramses::internal EXPECT_TRUE(otherEngine.update()); EXPECT_EQ(15, *animNode->getOutputs()->getChild("channel")->get()); - ASSERT_TRUE(saveToFileWithoutValidation("logic_animNodes.bin")); + ASSERT_TRUE(saveToFile("logic_animNodes.bin")); } ASSERT_TRUE(recreateFromFile("logic_animNodes.bin")); diff --git a/tests/unittests/client/logic/api/AnimationNodeWithDataPropertiesTest.cpp b/tests/unittests/client/logic/api/AnimationNodeWithDataPropertiesTest.cpp index 44ea2c6da..963e0f93a 100644 --- a/tests/unittests/client/logic/api/AnimationNodeWithDataPropertiesTest.cpp +++ b/tests/unittests/client/logic/api/AnimationNodeWithDataPropertiesTest.cpp @@ -248,7 +248,7 @@ namespace ramses::internal ASSERT_TRUE(config.addChannel(channel2)); ASSERT_TRUE(otherEngine.createAnimationNode(config, "animNode")); - ASSERT_TRUE(saveToFileWithoutValidation("logic_animNodes.bin")); + ASSERT_TRUE(saveToFile("logic_animNodes.bin")); } ASSERT_TRUE(recreateFromFile("logic_animNodes.bin")); @@ -301,7 +301,7 @@ namespace ramses::internal animNode->getInputs()->getChild("channelsData")->getChild("channel")->getChild("keyframes")->getChild(2u)->set(1000.f); EXPECT_TRUE(otherEngine.update()); - ASSERT_TRUE(saveToFileWithoutValidation("logic_animNodes.bin")); + ASSERT_TRUE(saveToFile("logic_animNodes.bin")); } ASSERT_TRUE(recreateFromFile("logic_animNodes.bin")); diff --git a/tests/unittests/client/logic/api/AppearanceBindingTest.cpp b/tests/unittests/client/logic/api/AppearanceBindingTest.cpp index 8bd6078c7..152e822cc 100644 --- a/tests/unittests/client/logic/api/AppearanceBindingTest.cpp +++ b/tests/unittests/client/logic/api/AppearanceBindingTest.cpp @@ -737,7 +737,7 @@ namespace ramses::internal { { m_logicEngine->createAppearanceBinding(*m_appearance, "AppearanceBinding"); - ASSERT_TRUE(saveToFileWithoutValidation("appearancebinding.bin")); + ASSERT_TRUE(saveToFile("appearancebinding.bin")); } { @@ -783,7 +783,7 @@ namespace ramses::internal inputs->getChild("vec2Array")->getChild(0)->set({ .11f, .12f }); inputs->getChild("vec2Array")->getChild(1)->set({ .13f, .14f }); m_logicEngine->update(); - ASSERT_TRUE(saveToFileWithoutValidation("logic.bin")); + ASSERT_TRUE(saveToFile("logic.bin")); } { @@ -853,7 +853,7 @@ namespace ramses::internal auto& rAppearanceBinding = *m_logicEngine->createAppearanceBinding(*m_appearance, "AppearanceBinding"); rAppearanceBinding.getInputs()->getChild("floatUniform")->set(42.42f); m_logicEngine->update(); - ASSERT_TRUE(saveToFileWithoutValidation("logic.bin")); + ASSERT_TRUE(saveToFile("logic.bin")); } { @@ -882,7 +882,7 @@ namespace ramses::internal // Set uniform to a different value than the one set on the ramses binding SetUniformValueFloat(appearance, "floatUniform", 100.0f); - ASSERT_TRUE(saveToFileWithoutValidation("SomeValuesSet.bin")); + ASSERT_TRUE(saveToFile("SomeValuesSet.bin")); } { @@ -935,7 +935,7 @@ namespace ramses::internal // or any set() calls to the corresponding AppearanceBinding input SetUniformValueFloat(appearance, "floatUniform2", 200.0f); - ASSERT_TRUE(saveToFileWithoutValidation("SomeValuesLinked.bin")); + ASSERT_TRUE(saveToFile("SomeValuesLinked.bin")); } { diff --git a/tests/unittests/client/logic/api/CameraBindingTest.cpp b/tests/unittests/client/logic/api/CameraBindingTest.cpp index f69f63125..8da63a57f 100644 --- a/tests/unittests/client/logic/api/CameraBindingTest.cpp +++ b/tests/unittests/client/logic/api/CameraBindingTest.cpp @@ -60,13 +60,6 @@ namespace ramses::internal m_withTempDirectory = std::make_unique(); } - bool saveToFileWithoutValidation(std::string_view filename) - { - SaveFileConfig configNoValidation; - configNoValidation.setValidationEnabled(false); - return m_testScene->saveToFile(filename, configNoValidation); - } - bool recreateFromFile(std::string_view filename) { const auto orthoId = m_orthoCam->getSceneObjectId(); @@ -1180,7 +1173,7 @@ namespace ramses::internal frustum->getChild("nearPlane")->set(newNearPlane); frustum->getChild("farPlane")->set(newFarPlane); m_logicEngine->update(); - EXPECT_TRUE(saveToFileWithoutValidation("camerabinding.bin")); + EXPECT_TRUE(m_testScene->saveToFile("camerabinding.bin")); } { EXPECT_TRUE(recreateFromFile("camerabinding.bin")); @@ -1233,7 +1226,7 @@ namespace ramses::internal { { m_logicEngine->createCameraBinding(*m_orthoCam, "CameraBinding"); - ASSERT_TRUE(saveToFileWithoutValidation("camerabinding.bin")); + ASSERT_TRUE(m_testScene->saveToFile("camerabinding.bin")); } { @@ -1250,7 +1243,7 @@ namespace ramses::internal { { m_logicEngine->createCameraBinding(*m_perspectiveCam, "CameraBinding"); - EXPECT_TRUE(saveToFileWithoutValidation("camerabinding.bin")); + EXPECT_TRUE(m_testScene->saveToFile("camerabinding.bin")); } { EXPECT_TRUE(recreateFromFile("camerabinding.bin")); @@ -1263,7 +1256,7 @@ namespace ramses::internal { { m_logicEngine->createCameraBinding(*m_perspectiveCam, "CameraBinding"); - EXPECT_TRUE(saveToFileWithoutValidation("camerabinding.bin")); + EXPECT_TRUE(m_testScene->saveToFile("camerabinding.bin")); } { EXPECT_TRUE(recreateFromFile("camerabinding.bin")); @@ -1288,7 +1281,7 @@ namespace ramses::internal m_logicEngine->update(); m_perspectiveCam->setViewport(11, 12, 13u, 14u); - EXPECT_TRUE(saveToFileWithoutValidation("camerabinding.bin")); + EXPECT_TRUE(m_testScene->saveToFile("camerabinding.bin")); } { @@ -1359,7 +1352,7 @@ namespace ramses::internal ASSERT_TRUE(m_logicEngine->link(*script->getOutputs()->getChild("frustProps")->getChild("fP"), *cameraBinding.getInputs()->getChild("frustum")->getChild("farPlane"))); m_logicEngine->update(); - EXPECT_TRUE(saveToFileWithoutValidation("camerabinding.bin")); + EXPECT_TRUE(m_testScene->saveToFile("camerabinding.bin")); } // Modify 'linked' properties before loading to check if logic will overwrite them after load + update diff --git a/tests/unittests/client/logic/api/DataArrayTest.cpp b/tests/unittests/client/logic/api/DataArrayTest.cpp index 4bcd91faf..e409bd6c1 100644 --- a/tests/unittests/client/logic/api/DataArrayTest.cpp +++ b/tests/unittests/client/logic/api/DataArrayTest.cpp @@ -76,7 +76,7 @@ namespace ramses::internal auto dataArray = otherEngine.createDataArray(SomeDataVector(), "dataarray"); EXPECT_FALSE(this->m_logicEngine->destroy(*dataArray)); - EXPECT_EQ("Failed to destroy object 'dataarray [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance.", this->getLastErrorMessage()); + EXPECT_EQ(fmt::format("Failed to destroy object 'dataarray [LogicObject ScnObjId={}]', cannot find it in this LogicEngine instance.", dataArray->getSceneObjectId()), this->getLastErrorMessage()); } TYPED_TEST(ADataArray, ChangesName) @@ -118,7 +118,7 @@ namespace ramses::internal otherEngine.createDataArray(data4, "dataarray4"); otherEngine.createDataArray(data5, "dataarray5"); - ASSERT_TRUE(this->saveToFileWithoutValidation("LogicEngine.bin")); + ASSERT_TRUE(this->saveToFile("LogicEngine.bin")); } ASSERT_TRUE(this->recreateFromFile("LogicEngine.bin")); diff --git a/tests/unittests/client/logic/api/LogicEngineTest_Compatibility.cpp b/tests/unittests/client/logic/api/LogicEngineTest_Compatibility.cpp index 176407830..7bad2486c 100644 --- a/tests/unittests/client/logic/api/LogicEngineTest_Compatibility.cpp +++ b/tests/unittests/client/logic/api/LogicEngineTest_Compatibility.cpp @@ -13,6 +13,7 @@ #include "PropertyLinkTestUtils.h" #include "ramses/client/logic/Property.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/EffectDescription.h" #include "ramses/client/Effect.h" @@ -167,6 +168,9 @@ namespace ramses::internal const std::vector> expectedData{ { 1.f, 2.f, 3.f, 4.f, 5.f }, { 6.f, 7.f, 8.f, 9.f, 10.f } }; EXPECT_EQ(expectedData, *data); EXPECT_TRUE(logicEngine.findObject("meshnodebinding")); + auto rbBinding = logicEngine.findObject("renderBufferBinding"); + ASSERT_TRUE(rbBinding); + EXPECT_EQ(ramsesScene.findObject("renderBuffer"), &rbBinding->getRenderBuffer()); } static void expectFeatureLevel02Content(const LogicEngine& /*logicEngine*/, ramses::Scene& /*ramsesScene*/) @@ -211,9 +215,7 @@ namespace ramses::internal { WithTempDirectory tempDir; - ramses::SaveFileConfig noValidationConfig; - noValidationConfig.setValidationEnabled(false); - EXPECT_TRUE(scene.saveToFile("temp.ramses", noValidationConfig)); + EXPECT_TRUE(scene.saveToFile("temp.ramses", {})); auto& client = scene.getRamsesClient(); client.destroy(scene); diff --git a/tests/unittests/client/logic/api/LogicEngineTest_Factory.cpp b/tests/unittests/client/logic/api/LogicEngineTest_Factory.cpp index 87f6cce93..42348d2f9 100644 --- a/tests/unittests/client/logic/api/LogicEngineTest_Factory.cpp +++ b/tests/unittests/client/logic/api/LogicEngineTest_Factory.cpp @@ -14,6 +14,7 @@ #include "ramses/client/logic/RenderPassBinding.h" #include "ramses/client/logic/LuaModule.h" #include "ramses/client/logic/AnimationNodeConfig.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/DataObject.h" @@ -68,7 +69,7 @@ namespace ramses::internal auto script = otherLogicEngine.createLuaScript(m_valid_empty_script); ASSERT_TRUE(script); ASSERT_FALSE(m_logicEngine->destroy(*script)); - EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object ' [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object ' [LogicObject ScnObjId=11]', cannot find it in this LogicEngine instance."); } TEST_P(ALogicEngine_Factory, CreatesLuaModule) @@ -123,7 +124,7 @@ namespace ramses::internal ASSERT_NE(nullptr, module); EXPECT_FALSE(m_logicEngine->destroy(*module)); - EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object ' [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object ' [LogicObject ScnObjId=11]', cannot find it in this LogicEngine instance."); } TEST_P(ALogicEngine_Factory, FailsToDestroyLuaModuleIfUsedInLuaScript) @@ -259,7 +260,7 @@ namespace ramses::internal auto nodeBinding = otherLogicEngine.createNodeBinding(*m_node, ramses::ERotationType::Euler_XYZ, "NodeBinding"); ASSERT_TRUE(nodeBinding); ASSERT_FALSE(m_logicEngine->destroy(*nodeBinding)); - EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object 'NodeBinding [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object 'NodeBinding [LogicObject ScnObjId=11]', cannot find it in this LogicEngine instance."); } TEST_P(ALogicEngine_Factory, ProducesErrorsWhenDestroyingAppearanceBindingFromAnotherEngineInstance) @@ -268,7 +269,7 @@ namespace ramses::internal auto binding = otherLogicEngine.createAppearanceBinding(*m_appearance, "AppearanceBinding"); ASSERT_TRUE(binding); ASSERT_FALSE(m_logicEngine->destroy(*binding)); - EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object 'AppearanceBinding [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object 'AppearanceBinding [LogicObject ScnObjId=11]', cannot find it in this LogicEngine instance."); } TEST_P(ALogicEngine_Factory, DestroysCameraBindingWithoutErrors) @@ -284,7 +285,7 @@ namespace ramses::internal auto binding = otherLogicEngine.createCameraBinding(*m_camera, "CameraBinding"); ASSERT_TRUE(binding); ASSERT_FALSE(m_logicEngine->destroy(*binding)); - EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object 'CameraBinding [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object 'CameraBinding [LogicObject ScnObjId=11]', cannot find it in this LogicEngine instance."); } TEST_P(ALogicEngine_Factory, DestroysRenderPassBindingWithoutErrors) @@ -300,7 +301,7 @@ namespace ramses::internal auto binding = otherLogicEngine.createRenderPassBinding(*m_renderPass, "rp"); ASSERT_TRUE(binding); ASSERT_FALSE(m_logicEngine->destroy(*binding)); - EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object 'rp [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object 'rp [LogicObject ScnObjId=11]', cannot find it in this LogicEngine instance."); } TEST_P(ALogicEngine_Factory, DestroysRenderGroupBindingWithoutErrors) @@ -317,7 +318,7 @@ namespace ramses::internal auto& otherLogicEngine = *m_scene->createLogicEngine(); ASSERT_FALSE(otherLogicEngine.destroy(*binding)); - EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object 'renderGroupBinding [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object 'renderGroupBinding [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); } TEST_P(ALogicEngine_Factory, DestroysMeshNodeBindingWithoutErrors) @@ -334,7 +335,7 @@ namespace ramses::internal auto& otherLogicEngine = *m_scene->createLogicEngine(); ASSERT_FALSE(otherLogicEngine.destroy(*binding)); - EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object ' [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(getLastErrorMessage(), "Failed to destroy object ' [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); } TEST_P(ALogicEngine_Factory, ProducesErrorWhenCreatingAnchorPointAndNodeOrCameraFromAnotherInstance) @@ -522,6 +523,7 @@ namespace ramses::internal LogicObject* renderGroupBinding = createRenderGroupBinding(); LogicObject* skin = createSkinBinding(*m_logicEngine); LogicObject* meshBinding = m_logicEngine->createMeshNodeBinding(*m_meshNode); + LogicObject* rbBinding = m_logicEngine->createRenderBufferBinding(*m_renderBuffer); EXPECT_TRUE(luaModule->as()); EXPECT_TRUE(luaScript->as()); @@ -534,6 +536,7 @@ namespace ramses::internal EXPECT_TRUE(renderGroupBinding->as()); EXPECT_TRUE(skin->as()); EXPECT_TRUE(meshBinding->as()); + EXPECT_TRUE(rbBinding->as()); EXPECT_FALSE(luaModule->as()); EXPECT_FALSE(luaScript->as()); @@ -546,6 +549,7 @@ namespace ramses::internal EXPECT_FALSE(renderGroupBinding->as()); EXPECT_FALSE(skin->as()); EXPECT_FALSE(meshBinding->as()); + EXPECT_FALSE(rbBinding->as()); //cast obj -> node -> binding -> appearanceBinding auto* nodeCastFromObject = appearanceBinding->as(); @@ -586,6 +590,7 @@ namespace ramses::internal createRenderGroupBinding(); createSkinBinding(*m_logicEngine); m_logicEngine->createMeshNodeBinding(*m_meshNode, "meshBinding"); + m_logicEngine->createRenderBufferBinding(*m_renderBuffer, "rbBinding"); const auto* immutableLogicEngine = m_logicEngine; const auto* luaModuleConst = immutableLogicEngine->findObject("luaModule"); @@ -599,6 +604,7 @@ namespace ramses::internal const auto* renderGroupBindingConst = immutableLogicEngine->findObject("renderGroupBinding"); const auto* skinConst = immutableLogicEngine->findObject("skin"); const auto* meshBindingConst = immutableLogicEngine->findObject("meshBinding"); + const auto* rbBindingConst = immutableLogicEngine->findObject("rbBinding"); EXPECT_TRUE(luaModuleConst->as()); EXPECT_TRUE(luaScriptConst->as()); @@ -611,6 +617,7 @@ namespace ramses::internal EXPECT_TRUE(renderGroupBindingConst->as()); EXPECT_TRUE(skinConst->as()); EXPECT_TRUE(meshBindingConst->as()); + EXPECT_TRUE(rbBindingConst->as()); EXPECT_FALSE(luaModuleConst->as()); EXPECT_FALSE(luaScriptConst->as()); @@ -623,6 +630,7 @@ namespace ramses::internal EXPECT_FALSE(renderGroupBindingConst->as()); EXPECT_FALSE(skinConst->as()); EXPECT_FALSE(meshBindingConst->as()); + EXPECT_FALSE(rbBindingConst->as()); // cast obj -> node -> binding -> appearanceBinding const auto* nodeCastFromObject = appearanceBindingConst->as(); diff --git a/tests/unittests/client/logic/api/LogicEngineTest_Linking.cpp b/tests/unittests/client/logic/api/LogicEngineTest_Linking.cpp index 5811d3b9e..b97730e04 100644 --- a/tests/unittests/client/logic/api/LogicEngineTest_Linking.cpp +++ b/tests/unittests/client/logic/api/LogicEngineTest_Linking.cpp @@ -28,12 +28,14 @@ #include "ramses/client/logic/NodeBinding.h" #include "ramses/client/logic/CameraBinding.h" #include "ramses/client/logic/RenderPassBinding.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "impl/logic/LogicEngineImpl.h" #include "impl/logic/LogicNodeImpl.h" #include "impl/logic/LuaScriptImpl.h" #include "impl/logic/PropertyImpl.h" #include "impl/logic/NodeBindingImpl.h" +#include "impl/RenderBufferImpl.h" #include "internal/logic/ApiObjects.h" #include "fmt/format.h" @@ -274,8 +276,9 @@ namespace ramses::internal EXPECT_EQ("Failed to sort logic nodes based on links between their properties. Create a loop-free link graph before calling update()!", getLastErrorMessage()); // Also refuse to save to file - EXPECT_FALSE(saveToFileWithoutValidation("will_not_write")); - EXPECT_EQ("Failed to sort logic nodes based on links between their properties. Create a loop-free link graph before calling saveToFile()!", getLastErrorMessage()); + EXPECT_FALSE(saveToFile("will_not_write")); + EXPECT_EQ("Scene::saveToFile failed due to failed logic engine update: Failed to sort logic nodes based on links between their properties." + " Create a loop-free link graph before calling update()!", getLastErrorMessage()); } TEST_F(ALogicEngine_Linking, PropagatesValuesAcrossMultipleLinksInAChain) @@ -1470,7 +1473,7 @@ namespace ramses::internal ASSERT_EQ(std::string("A: forward 'From A' & B: forward forward 'From A'"), *scriptC_concatenate_AB->get()); - ASSERT_TRUE(saveToFileWithoutValidation("links.bin")); + ASSERT_TRUE(saveToFile("links.bin")); } { @@ -1579,7 +1582,7 @@ namespace ramses::internal auto scriptB_concatenated = scriptB->getOutputs()->getChild("concat_all"); ASSERT_EQ(std::string("str1 {foo, str2}"), *scriptB_concatenated->get()); - ASSERT_TRUE(saveToFileWithoutValidation("nested_links.bin")); + ASSERT_TRUE(saveToFile("nested_links.bin")); } { @@ -1669,11 +1672,10 @@ namespace ramses::internal script2Input2->set(std::string("B")); script3Input2->set(std::string("C")); - tmpLogicEngine.update(); - // during 1st update the weak link has no value yet so there is no concatenation from previous update - EXPECT_STREQ("ABC", script3Output->get()->c_str()); + ASSERT_TRUE(saveToFile("weaklinks.bin")); - ASSERT_TRUE(saveToFileWithoutValidation("weaklinks.bin")); + // during 1st update which was executed during saving the weak link has no value yet so there is no concatenation from previous update + EXPECT_STREQ("ABC", script3Output->get()->c_str()); } ASSERT_TRUE(recreateFromFile("weaklinks.bin")); @@ -1812,7 +1814,7 @@ namespace ramses::internal ExpectValues(*ramsesNode2, ENodePropertyStaticIndex::Translation, { 11.1f, 11.2f, 11.3f }); EXPECT_EQ(ramsesNode2->getVisibility(), ramses::EVisibilityMode::Visible); - ASSERT_TRUE(saveToFileWithoutValidation("binding_links.bin")); + ASSERT_TRUE(saveToFile("binding_links.bin")); } { @@ -1911,7 +1913,7 @@ namespace ramses::internal ExpectVec3f(appearance2, "uniform1", { 100.0f, 200.0f, 300.0f }); ExpectVec3f(appearance2, "uniform2", { 100.0f, 200.0f, 300.0f }); - ASSERT_TRUE(saveToFileWithoutValidation("binding_links.bin")); + ASSERT_TRUE(saveToFile("binding_links.bin")); } { @@ -2001,7 +2003,7 @@ namespace ramses::internal EXPECT_EQ(camera2->getViewportX(), 19); EXPECT_EQ(camera2->getFarPlane(), 7.8f); - ASSERT_TRUE(saveToFileWithoutValidation("binding_links.bin")); + ASSERT_TRUE(saveToFile("binding_links.bin")); } { ASSERT_TRUE(recreateFromFile("binding_links.bin")); @@ -2088,7 +2090,7 @@ namespace ramses::internal EXPECT_FALSE(rp2->isEnabled()); EXPECT_EQ(rp2->getRenderOrder(), 33); - ASSERT_TRUE(saveToFileWithoutValidation("binding_links.bin")); + ASSERT_TRUE(saveToFile("binding_links.bin")); } { ASSERT_TRUE(recreateFromFile("binding_links.bin")); @@ -2160,7 +2162,7 @@ namespace ramses::internal EXPECT_EQ(33, renderOrder); // script has no inputs linked, validatation would fail - ASSERT_TRUE(saveToFileWithoutValidation("binding_links.bin")); + ASSERT_TRUE(saveToFile("binding_links.bin")); } { @@ -2177,9 +2179,10 @@ namespace ramses::internal EXPECT_EQ(100, renderOrder); auto binding = m_logicEngine->findObject("binding"); + ASSERT_TRUE(binding); // This value should be overwritten by the link - set it to a different value to make sure that happens - binding->getInputs()->getChild("renderOrders")->getChild("meshNode")->set(222); + EXPECT_TRUE(m_renderGroup->addMeshNode(*m_meshNode, 222)); EXPECT_TRUE(m_logicEngine->update()); m_renderGroup->getMeshNodeOrder(*m_meshNode, renderOrder); @@ -2187,6 +2190,44 @@ namespace ramses::internal } } + TEST_F(ALogicEngine_Linking_WithBindings, PreservesLinksToRenderBufferBindingAfterSavingAndLoadingFromFile) + { + { + LogicEngine& tmpLogicEngine = *m_logicEngine; + const std::string_view scriptSrc = R"( + function interface(IN,OUT) + OUT.width = Type:Int32() + end + function run(IN,OUT) + OUT.width = 33 + end + )"; + + auto script = tmpLogicEngine.createLuaScript(scriptSrc); + auto binding = tmpLogicEngine.createRenderBufferBinding(*m_renderBuffer, "binding"); + ASSERT_TRUE(tmpLogicEngine.link(*script->getOutputs()->getChild("width"), *binding->getInputs()->getChild("width"))); + + ASSERT_TRUE(tmpLogicEngine.update()); + EXPECT_EQ(33u, m_renderBuffer->getWidth()); + ASSERT_TRUE(saveToFile("binding_links.bin")); + } + + { + ASSERT_TRUE(recreateFromFile("binding_links.bin")); + ASSERT_TRUE(m_renderBuffer != nullptr); + + EXPECT_EQ(33u, m_renderBuffer->getWidth()); + auto binding = m_logicEngine->findObject("binding"); + ASSERT_TRUE(binding); + + // This value should be overwritten by the link - set it to a different value to make sure that happens + EXPECT_TRUE(m_renderBuffer->impl().setProperties(222u, 2u, 3u)); + EXPECT_TRUE(m_logicEngine->update()); + + EXPECT_EQ(33u, m_renderBuffer->getWidth()); + } + } + TEST_F(ALogicEngine_Linking, ReportsNodeAsLinked_IFF_ItHasIncomingOrOutgoingLinks) { auto scriptSource = R"( diff --git a/tests/unittests/client/logic/api/LogicEngineTest_Serialization.cpp b/tests/unittests/client/logic/api/LogicEngineTest_Serialization.cpp index 07add8440..944bf2de8 100644 --- a/tests/unittests/client/logic/api/LogicEngineTest_Serialization.cpp +++ b/tests/unittests/client/logic/api/LogicEngineTest_Serialization.cpp @@ -22,6 +22,7 @@ #include "ramses/client/logic/AnimationNode.h" #include "ramses/client/logic/AnimationNodeConfig.h" #include "ramses/client/logic/LuaInterface.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/EffectDescription.h" #include "ramses/client/Effect.h" @@ -42,6 +43,7 @@ #include "impl/logic/NodeBindingImpl.h" #include "impl/logic/RenderGroupBindingImpl.h" #include "impl/logic/RenderPassBindingImpl.h" +#include "impl/logic/RenderBufferBindingImpl.h" #include "internal/logic/ApiObjects.h" #include "internal/logic/FileUtils.h" #include "LogTestUtils.h" @@ -56,8 +58,6 @@ namespace ramses::internal { - const size_t SCENE_ISSUES = 6u; - class ALogicEngine_Serialization : public ALogicEngineBase, public ::testing::TestWithParam { public: @@ -127,15 +127,16 @@ namespace ramses::internal createRenderGroupBinding(logicEngine); createSkinBinding(*nodeBinding, *appearanceBinding, logicEngine); logicEngine.createMeshNodeBinding(*m_meshNode, "mb"); + logicEngine.createRenderBufferBinding(*m_renderBuffer, "rb"); EXPECT_TRUE(logicEngine.update()); - EXPECT_TRUE(saveToFileWithoutValidation("LogicEngine.bin")); + EXPECT_TRUE(saveToFile("LogicEngine.bin")); EXPECT_TRUE(recreateFromFile("LogicEngine.bin")); expectNoError(); const std::vector names{ "module", "script", "nodeBinding", "appearanceBinding", "cameraBinding", "dataArray", "animNode", - "timerNode", "intf", "rpBinding", "anchor", "renderGroupBinding", "skin", "mb" }; + "timerNode", "intf", "rpBinding", "anchor", "renderGroupBinding", "skin", "mb", "rb" }; std::vector objects; for (const auto& name : names) @@ -157,7 +158,7 @@ namespace ramses::internal TEST_P(ALogicEngine_Serialization, ProducesErrorWhenProvidingAFolderAsTargetForSaving) { fs::create_directories("folder"); - EXPECT_FALSE(saveToFileWithoutValidation("folder")); + EXPECT_FALSE(saveToFile("folder")); EXPECT_EQ("Scene::saveToFile failed, could not open file for writing: 'folder'", getLastErrorMessage()); } @@ -209,14 +210,14 @@ namespace ramses::internal #ifndef _WIN32 TEST_P(ALogicEngine_Serialization, CanBeDeserializedFromHardLink) { - ASSERT_TRUE(saveToFileWithoutValidation("testfile.bin")); + ASSERT_TRUE(saveToFile("testfile.bin")); fs::create_hard_link("testfile.bin", "hardlink"); EXPECT_TRUE(recreateFromFile("hardlink")); } TEST_P(ALogicEngine_Serialization, CanBeDeserializedFromSymLink) { - ASSERT_TRUE(saveToFileWithoutValidation("testfile.bin")); + ASSERT_TRUE(saveToFile("testfile.bin")); fs::create_symlink("testfile.bin", "symlink"); EXPECT_TRUE(recreateFromFile("symlink")); } @@ -225,7 +226,7 @@ namespace ramses::internal TEST_P(ALogicEngine_Serialization, ProducesNoErrorIfDeserializedWithNoScriptsAndNoNodeBindings) { { - ASSERT_TRUE(saveToFileWithoutValidation("LogicEngine.bin")); + ASSERT_TRUE(saveToFile("LogicEngine.bin")); } { EXPECT_TRUE(recreateFromFile("LogicEngine.bin")); @@ -239,7 +240,7 @@ namespace ramses::internal LogicEngine& logicEngine = *m_logicEngine; logicEngine.createNodeBinding(*m_node, ramses::ERotationType::Euler_XYZ, "binding"); - ASSERT_TRUE(saveToFileWithoutValidation("LogicEngine.bin")); + ASSERT_TRUE(saveToFile("LogicEngine.bin")); } { EXPECT_TRUE(recreateFromFile("LogicEngine.bin")); @@ -264,7 +265,7 @@ namespace ramses::internal end )", {}, "luascript"); - ASSERT_TRUE(saveToFileWithoutValidation("LogicEngine.bin")); + ASSERT_TRUE(saveToFile("LogicEngine.bin")); } { EXPECT_TRUE(recreateFromFile("LogicEngine.bin")); @@ -280,32 +281,6 @@ namespace ramses::internal } } - TEST_P(ALogicEngine_Serialization, ProducesErrorIfSavedWithValidationError) - { - // Put logic engine to a dirty state (create new object and don't call update) - NodeBinding* nodeBinding = m_logicEngine->createNodeBinding(*m_node, ramses::ERotationType::Euler_XYZ, "binding"); - - std::vector messages; - std::vector messageTypes; - ScopedLogContextLevel scopedLogs(CONTEXT_CLIENT, ELogLevel::Warn, [&](ELogLevel msgType, std::string_view message) { - messages.emplace_back(message); - messageTypes.emplace_back(msgType); - }); - - // Set a value and save -> causes warning - nodeBinding->getInputs()->getChild("visibility")->set(false); - ASSERT_TRUE(nodeBinding->impl().isDirty()); - ASSERT_FALSE(saveToFile("LogicEngine.bin")); - - ASSERT_EQ(SCENE_ISSUES + 3u, messages.size()); - EXPECT_EQ("Saving logic engine content with manually updated binding values without calling update() will result in those values being lost!", messages[0]); - EXPECT_EQ("[binding [LogicObject ScnObjId=9]] Node [binding] has no ingoing links! Node should be deleted or properly linked!", messages[1]); - EXPECT_EQ("Failed to saveToFile() because validation errors were encountered! Refer to the documentation of saveToFile() for details how to address these gracefully.", messages.back()); - EXPECT_EQ(ELogLevel::Warn, messageTypes[0]); - EXPECT_EQ(ELogLevel::Warn, messageTypes[1]); - EXPECT_EQ(ELogLevel::Error, messageTypes.back()); - } - TEST_P(ALogicEngine_Serialization, ProducesNoErrorIfDeserilizedSuccessfully) { saveAndLoadAllTypesOfObjects(); @@ -315,13 +290,13 @@ namespace ramses::internal { auto moduleByName = m_logicEngine->findObject("module"); - auto moduleById = m_logicEngine->findObject(sceneObjectId_t{ 9u }); + auto moduleById = m_logicEngine->findObject(sceneObjectId_t{ 10u }); ASSERT_NE(nullptr, moduleByName); ASSERT_EQ(moduleById, moduleByName); } { auto scriptByName = m_logicEngine->findObject("script"); - auto scriptById = m_logicEngine->findObject(sceneObjectId_t{ 10u }); + auto scriptById = m_logicEngine->findObject(sceneObjectId_t{ 11u }); ASSERT_NE(nullptr, scriptByName); ASSERT_EQ(scriptById, scriptByName); const auto inputs = scriptByName->getInputs(); @@ -331,7 +306,7 @@ namespace ramses::internal } { auto rNodeBindingByName = m_logicEngine->findObject("nodeBinding"); - auto rNodeBindingById = m_logicEngine->findObject(sceneObjectId_t{ 11u }); + auto rNodeBindingById = m_logicEngine->findObject(sceneObjectId_t{ 12u }); ASSERT_NE(nullptr, rNodeBindingByName); ASSERT_EQ(rNodeBindingById, rNodeBindingByName); const auto inputs = rNodeBindingByName->getInputs(); @@ -341,7 +316,7 @@ namespace ramses::internal } { auto rCameraBindingByName = m_logicEngine->findObject("cameraBinding"); - auto rCameraBindingById = m_logicEngine->findObject(sceneObjectId_t{ 13u }); + auto rCameraBindingById = m_logicEngine->findObject(sceneObjectId_t{ 14u }); ASSERT_NE(nullptr, rCameraBindingByName); ASSERT_EQ(rCameraBindingById, rCameraBindingByName); const auto inputs = rCameraBindingByName->getInputs(); @@ -351,7 +326,7 @@ namespace ramses::internal } { auto rAppearanceBindingByName = m_logicEngine->findObject("appearanceBinding"); - auto rAppearanceBindingById = m_logicEngine->findObject(sceneObjectId_t{ 12u }); + auto rAppearanceBindingById = m_logicEngine->findObject(sceneObjectId_t{ 13u }); ASSERT_NE(nullptr, rAppearanceBindingByName); ASSERT_EQ(rAppearanceBindingById, rAppearanceBindingByName); const auto inputs = rAppearanceBindingByName->getInputs(); @@ -366,7 +341,7 @@ namespace ramses::internal } { const auto dataArrayByName = m_logicEngine->findObject("dataArray"); - const auto dataArrayById = m_logicEngine->findObject(sceneObjectId_t{ 14u }); + const auto dataArrayById = m_logicEngine->findObject(sceneObjectId_t{ 15u }); ASSERT_NE(nullptr, dataArrayByName); ASSERT_EQ(dataArrayById, dataArrayByName); EXPECT_EQ(EPropertyType::Float, dataArrayByName->getDataType()); @@ -375,7 +350,7 @@ namespace ramses::internal EXPECT_EQ(expectedData, *m_logicEngine->findObject("dataArray")->getData()); const auto animNodeByName = m_logicEngine->findObject("animNode"); - const auto animNodeById = m_logicEngine->findObject(sceneObjectId_t{ 15u }); + const auto animNodeById = m_logicEngine->findObject(sceneObjectId_t{ 16u }); ASSERT_NE(nullptr, animNodeByName); ASSERT_EQ(animNodeById, animNodeByName); ASSERT_EQ(1u, animNodeByName->getChannels().size()); @@ -384,7 +359,7 @@ namespace ramses::internal } { auto rpBindingByName = m_logicEngine->findObject("rpBinding"); - auto rpBindingById = m_logicEngine->findObject(sceneObjectId_t{ 18u }); + auto rpBindingById = m_logicEngine->findObject(sceneObjectId_t{ 19u }); ASSERT_NE(nullptr, rpBindingByName); ASSERT_EQ(rpBindingById, rpBindingByName); const auto inputs = rpBindingByName->getInputs(); @@ -393,7 +368,7 @@ namespace ramses::internal EXPECT_FALSE(rpBindingByName->impl().isDirty()); auto anchorByName = m_logicEngine->findObject("anchor"); - auto anchorById = m_logicEngine->findObject(sceneObjectId_t{ 19u }); + auto anchorById = m_logicEngine->findObject(sceneObjectId_t{ 20u }); ASSERT_NE(nullptr, anchorByName); ASSERT_EQ(anchorById, anchorByName); const auto outputs = anchorByName->getOutputs(); @@ -402,7 +377,7 @@ namespace ramses::internal } { auto rgBindingByName = m_logicEngine->findObject("renderGroupBinding"); - auto rgBindingById = m_logicEngine->findObject(sceneObjectId_t{ 20u }); + auto rgBindingById = m_logicEngine->findObject(sceneObjectId_t{ 21u }); ASSERT_NE(nullptr, rgBindingByName); ASSERT_EQ(rgBindingById, rgBindingByName); const auto inputs = rgBindingByName->getInputs(); @@ -413,13 +388,13 @@ namespace ramses::internal } { auto skinByName = m_logicEngine->findObject("skin"); - auto skinById = m_logicEngine->findObject(sceneObjectId_t{ 21u }); + auto skinById = m_logicEngine->findObject(sceneObjectId_t{ 22u }); ASSERT_NE(nullptr, skinByName); ASSERT_EQ(skinById, skinByName); } { auto meshBindingByName = m_logicEngine->findObject("mb"); - auto meshBindingById = m_logicEngine->findObject(sceneObjectId_t{ 22u }); + auto meshBindingById = m_logicEngine->findObject(sceneObjectId_t{ 23u }); ASSERT_NE(nullptr, meshBindingByName); ASSERT_EQ(meshBindingById, meshBindingByName); const auto inputs = meshBindingByName->getInputs(); @@ -427,6 +402,16 @@ namespace ramses::internal EXPECT_EQ(4u, inputs->getChildCount()); EXPECT_FALSE(meshBindingByName->impl().isDirty()); } + { + auto rbBindingByName = m_logicEngine->findObject("rb"); + auto rbBindingById = m_logicEngine->findObject(sceneObjectId_t{ 24u }); + ASSERT_NE(nullptr, rbBindingByName); + ASSERT_EQ(rbBindingById, rbBindingByName); + const auto inputs = rbBindingByName->getInputs(); + ASSERT_NE(nullptr, inputs); + EXPECT_EQ(3u, inputs->getChildCount()); + EXPECT_FALSE(rbBindingByName->impl().isDirty()); + } } } @@ -443,7 +428,7 @@ namespace ramses::internal )", {}, "luascript"); logicEngine.createNodeBinding(*m_node, ramses::ERotationType::Euler_XYZ, "binding"); - ASSERT_TRUE(saveToFileWithoutValidation("LogicEngine.bin")); + ASSERT_TRUE(saveToFile("LogicEngine.bin")); } { m_logicEngine->createLuaScript(R"( @@ -498,7 +483,7 @@ namespace ramses::internal EXPECT_TRUE(logicEngine.link(*srcOutput1, *tgtInput1)); EXPECT_TRUE(logicEngine.linkWeak(*srcOutput2, *tgtInput2)); - ASSERT_TRUE(saveToFileWithoutValidation("LogicEngine.bin")); + ASSERT_TRUE(saveToFile("LogicEngine.bin")); } { EXPECT_TRUE(recreateFromFile("LogicEngine.bin")); @@ -561,7 +546,7 @@ namespace ramses::internal auto targetScript = m_logicEngine->createLuaScript(scriptSource, {}, "TargetScript"); // Save logic engine state without links to file - ASSERT_TRUE(saveToFileWithoutValidation("LogicEngine.bin")); + ASSERT_TRUE(saveToFile("LogicEngine.bin")); // Create link (should be wiped after loading from file) auto output = sourceScript->getOutputs()->getChild("output"); @@ -615,7 +600,7 @@ namespace ramses::internal config.addDependency("mymath", *mymath); logicEngineForSaving.createLuaScript(script, config, "script"); - ASSERT_TRUE(saveToFileWithoutValidation("LogicEngine.bin")); + ASSERT_TRUE(saveToFile("LogicEngine.bin")); } // Create a module with name colliding with the one from file - it should be deleted @@ -655,7 +640,7 @@ namespace ramses::internal )", {}, "luascript"); serializedId = script->getSceneObjectId(); - ASSERT_TRUE(saveToFileWithoutValidation("LogicEngine.bin")); + ASSERT_TRUE(saveToFile("LogicEngine.bin")); } EXPECT_TRUE(recreateFromFile("LogicEngine.bin")); @@ -713,7 +698,7 @@ namespace ramses::internal EXPECT_TRUE(skin->setUserId(25u, 26u)); EXPECT_TRUE(meshBinding->setUserId(27u, 28u)); - ASSERT_TRUE(saveToFileWithoutValidation("LogicEngine.bin")); + ASSERT_TRUE(saveToFile("LogicEngine.bin")); } EXPECT_TRUE(recreateFromFile("LogicEngine.bin")); @@ -827,7 +812,7 @@ namespace ramses::internal } // just check that the iterating over all props works - EXPECT_EQ(50, propsCount); + EXPECT_EQ(54, propsCount); } TEST_P(ALogicEngine_Serialization, persistsPropertyImplToHLObjectMapping) @@ -858,6 +843,6 @@ namespace ramses::internal } // just check that the iterating over all props works - EXPECT_EQ(50, propsCount); + EXPECT_EQ(54, propsCount); } } diff --git a/tests/unittests/client/logic/api/LogicEngineTest_SerializedSize.cpp b/tests/unittests/client/logic/api/LogicEngineTest_SerializedSize.cpp index 9a6535ed2..07c4b49fa 100644 --- a/tests/unittests/client/logic/api/LogicEngineTest_SerializedSize.cpp +++ b/tests/unittests/client/logic/api/LogicEngineTest_SerializedSize.cpp @@ -25,6 +25,7 @@ #include "ramses/client/logic/TimerNode.h" #include "ramses/client/logic/AnchorPoint.h" #include "ramses/client/logic/SkinBinding.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/PerspectiveCamera.h" #include "ramses/client/Appearance.h" #include "ramses/client/RenderPass.h" @@ -99,7 +100,7 @@ namespace ramses::internal } }; - static constexpr size_t EmptySerializedSizeTotal{ 164u }; + static constexpr size_t EmptySerializedSizeTotal{ 172u }; INSTANTIATE_TEST_SUITE_P( ALogicEngine_SerializedSizeTests, @@ -124,6 +125,7 @@ namespace ramses::internal EXPECT_EQ(this->m_logicEngine->getSerializedSize(), 0u); EXPECT_EQ(this->m_logicEngine->getSerializedSize(), 0u); EXPECT_EQ(this->m_logicEngine->getSerializedSize(), 0u); + EXPECT_EQ(this->m_logicEngine->getSerializedSize(), 0u); } TEST_P(ALogicEngine_SerializedSize, ChecksSerializedSizeWithInterface) @@ -367,4 +369,11 @@ namespace ramses::internal EXPECT_EQ(this->m_logicEngine->getSerializedSize(), 184u); EXPECT_GT(this->m_logicEngine->getTotalSerializedSize(), EmptySerializedSizeTotal); } + + TEST_P(ALogicEngine_SerializedSize, ChecksSerializedSizeWithRenderBufferBinding) + { + this->m_logicEngine->createRenderBufferBinding(*m_renderBuffer, "rb"); + EXPECT_EQ(this->m_logicEngine->getSerializedSize(), 312u); + EXPECT_GT(this->m_logicEngine->getTotalSerializedSize(), EmptySerializedSizeTotal); + } } diff --git a/tests/unittests/client/logic/api/LogicEngineTest_Validation.cpp b/tests/unittests/client/logic/api/LogicEngineTest_Validation.cpp index 2aa2b3b18..5d56d1ca3 100644 --- a/tests/unittests/client/logic/api/LogicEngineTest_Validation.cpp +++ b/tests/unittests/client/logic/api/LogicEngineTest_Validation.cpp @@ -21,7 +21,7 @@ namespace ramses::internal { - const size_t SCENE_ISSUES = 6u; + const size_t SCENE_ISSUES = 9u; class ALogicEngine_Validation : public ALogicEngine { @@ -33,14 +33,10 @@ namespace ramses::internal { int warningCount = 0; - ScopedLogContextLevel logCollector{ CONTEXT_CLIENT, ELogLevel::Trace, [&](ELogLevel type, std::string_view /*message*/) - { - if (type == ELogLevel::Warn) - { - ++warningCount; - } - } - }; + ScopedLogContextLevel logCollector{ CONTEXT_CLIENT, ELogLevel::Trace, [&](ELogLevel type, std::string_view /*message*/) { + if (type == ELogLevel::Warn) + ++warningCount; + }}; m_logicEngine->validate(report); EXPECT_FALSE(report.hasIssue()); @@ -51,73 +47,6 @@ namespace ramses::internal EXPECT_LE(warningCount, SCENE_ISSUES); // logic is valid, but ramses scene is not } - TEST_F(ALogicEngine_Validation, LogsWarningsWhenSavingFile_WhenContentHasValidationIssues) - { - std::vector warnings; - ScopedLogContextLevel logCollector{ CONTEXT_CLIENT, ELogLevel::Trace, [&](ELogLevel type, std::string_view message) - { - if (type == ELogLevel::Warn) - { - warnings.emplace_back(message); - } - } - }; - - WithTempDirectory tmpDir; - // Cause some validation issues on purpose - NodeBinding& nodeBinding = *m_logicEngine->createNodeBinding(*m_node, ramses::ERotationType::Euler_XYZ, "NodeBinding"); - nodeBinding.getInputs()->getChild("scaling")->set({1.5f, 1.f, 1.f}); - - saveToFile("noWarnings.ramses"); - - ASSERT_EQ(warnings.size(), SCENE_ISSUES + 2u); - EXPECT_EQ(warnings[0], "Saving logic engine content with manually updated binding values without calling update() will result in those values being lost!"); - EXPECT_EQ(warnings[1], "[NodeBinding [LogicObject ScnObjId=9]] Node [NodeBinding] has no ingoing links! Node should be deleted or properly linked!"); - - // Fixing the problems -> removes the warning - warnings.clear(); - auto* intf = m_logicEngine->createLuaInterface(m_interfaceSourceCode, "intf"); - m_logicEngine->link(*intf->getOutputs()->getChild("param_vec3f"), *nodeBinding.getInputs()->getChild("scaling")); - m_logicEngine->update(); - - saveToFile("noWarnings.ramses"); - - ASSERT_EQ(warnings.size(), SCENE_ISSUES); - } - - TEST_F(ALogicEngine_Validation, LogsNoContentWarningsWhenSavingFile_WhenContentHasValidationIssues_ButValidationIsDisabled) - { - std::vector infoLogs; - ScopedLogContextLevel logCollector{ CONTEXT_CLIENT, ELogLevel::Trace, [&](ELogLevel type, std::string_view message) - { - if (type == ELogLevel::Info) - { - infoLogs.emplace_back(message); - } - else - { - FAIL() << "Unexpected log!"; - } - } - }; - - WithTempDirectory tmpDir; - // Cause some validation issues on purpose - NodeBinding& nodeBinding = *m_logicEngine->createNodeBinding(*m_node, ramses::ERotationType::Euler_XYZ, "NodeBinding"); - nodeBinding.getInputs()->getChild("scaling")->set({ 1.5f, 1.f, 1.f }); - - SaveFileConfig conf; - conf.setValidationEnabled(false); - - // Disabling the validation causes a warning - ASSERT_EQ(infoLogs.size(), 1u); - EXPECT_EQ(infoLogs[0], "Validation before saving was disabled during save*() calls! Possible content issues will not yield further warnings."); - infoLogs.clear(); - - // Content warning doesn't show up because disabled - saveToFile("noWarnings.ramses", conf); - } - TEST_F(ALogicEngine_Validation, ProducesWarningIfBindingValuesHaveDirtyValue) { // Create a binding in a "dirty" state - has a non-default value, but update() wasn't called and didn't pass the value to ramses @@ -223,11 +152,11 @@ namespace ramses::internal const auto& warnings = report.getIssues(); ASSERT_EQ(2u, warnings.size()); EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [scr] has no outgoing links! Node should be deleted or properly linked!")), - ::testing::Field(&Issue::message, ::testing::StrEq("Node [scr] has no ingoing links! Node should be deleted or properly linked!")))); + ::testing::Field(&Issue::message, ::testing::StrEq("Node [scr] has no incoming links! Node should be deleted or properly linked!")))); EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } - TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfScriptHasNoIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfScriptHasNoIncomingLinks) { auto* script = m_logicEngine->createLuaScript(m_scriptSrc, {}, "scr"); ASSERT_NE(nullptr, script); @@ -237,7 +166,7 @@ namespace ramses::internal m_logicEngine->validate(report); const auto& warnings = report.getIssues(); ASSERT_EQ(1u, warnings.size()); - EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [scr] has no ingoing links! Node should be deleted or properly linked!")))); + EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [scr] has no incoming links! Node should be deleted or properly linked!")))); EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } @@ -255,7 +184,7 @@ namespace ramses::internal EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } - TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfScriptHasIngoingAndOutgoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfScriptHasIncomingAndOutgoingLinks) { auto* script = m_logicEngine->createLuaScript(m_scriptSrc, {}, "scr"); ASSERT_NE(nullptr, script); @@ -269,7 +198,7 @@ namespace ramses::internal // -- interfaces -- // - TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfInterfaceHasNoIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfInterfaceHasNoIncomingLinks) { LuaInterface* intf = m_logicEngine->createLuaInterface(R"( function interface(INOUT) @@ -286,7 +215,7 @@ namespace ramses::internal // -- node bindings -- // - TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfNodeBindingHasNoIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfNodeBindingHasNoIncomingLinks) { auto* nodeBind = m_logicEngine->createNodeBinding(*m_node, ramses::ERotationType::Euler_XYZ, "binding"); ASSERT_NE(nullptr, nodeBind); @@ -294,11 +223,11 @@ namespace ramses::internal m_logicEngine->validate(report); const auto& warnings = report.getIssues(); ASSERT_EQ(1u, warnings.size()); - EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no ingoing links! Node should be deleted or properly linked!")))); + EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no incoming links! Node should be deleted or properly linked!")))); EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } - TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfNodeBindingHasIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfNodeBindingHasIncomingLinks) { auto* nodeBind = m_logicEngine->createNodeBinding(*m_node, ramses::ERotationType::Euler_XYZ, "binding"); ASSERT_NE(nullptr, nodeBind); @@ -312,7 +241,7 @@ namespace ramses::internal // -- appearance bindings -- // - TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfAppearanceBindingHasNoIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfAppearanceBindingHasNoIncomingLinks) { auto* appearanceBind = m_logicEngine->createAppearanceBinding(*m_appearance, "binding"); ASSERT_NE(nullptr, appearanceBind); @@ -320,11 +249,11 @@ namespace ramses::internal m_logicEngine->validate(report); const auto& warnings = report.getIssues(); ASSERT_EQ(1u, warnings.size()); - EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no ingoing links! Node should be deleted or properly linked!")))); + EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no incoming links! Node should be deleted or properly linked!")))); EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } - TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfAppearanceBindingHasIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfAppearanceBindingHasIncomingLinks) { auto* appearanceBind = m_logicEngine->createAppearanceBinding(*m_appearance, "binding"); ASSERT_NE(nullptr, appearanceBind); @@ -338,7 +267,7 @@ namespace ramses::internal // -- camera bindings -- // - TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfCameraBindingHasNoIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfCameraBindingHasNoIncomingLinks) { auto* cameraBind = m_logicEngine->createCameraBinding(*m_camera, "binding"); ASSERT_NE(nullptr, cameraBind); @@ -346,11 +275,11 @@ namespace ramses::internal m_logicEngine->validate(report); const auto& warnings = report.getIssues(); ASSERT_EQ(1u, warnings.size()); - EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no ingoing links! Node should be deleted or properly linked!")))); + EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no incoming links! Node should be deleted or properly linked!")))); EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } - TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfCameraBindingHasIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfCameraBindingHasIncomingLinks) { auto* cameraBind = m_logicEngine->createCameraBinding(*m_camera, "binding"); ASSERT_NE(nullptr, cameraBind); @@ -364,7 +293,7 @@ namespace ramses::internal // -- render pass bindings -- // - TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfRenderPassBindingHasNoIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfRenderPassBindingHasNoIncomingLinks) { auto* passBind = m_logicEngine->createRenderPassBinding(*m_renderPass, "binding"); ASSERT_NE(nullptr, passBind); @@ -372,11 +301,11 @@ namespace ramses::internal m_logicEngine->validate(report); const auto& warnings = report.getIssues(); ASSERT_EQ(1u, warnings.size()); - EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no ingoing links! Node should be deleted or properly linked!")))); + EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no incoming links! Node should be deleted or properly linked!")))); EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } - TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfRenderPassBindingHasIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfRenderPassBindingHasIncomingLinks) { auto* passBind = m_logicEngine->createRenderPassBinding(*m_renderPass, "binding"); ASSERT_NE(nullptr, passBind); @@ -390,7 +319,7 @@ namespace ramses::internal // -- render group bindings -- // - TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfRenderGroupBindingHasNoIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfRenderGroupBindingHasNoIncomingLinks) { RenderGroupBindingElements elements; elements.addElement(*m_meshNode, "mesh"); @@ -400,11 +329,11 @@ namespace ramses::internal m_logicEngine->validate(report); const auto& warnings = report.getIssues(); ASSERT_EQ(1u, warnings.size()); - EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no ingoing links! Node should be deleted or properly linked!")))); + EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no incoming links! Node should be deleted or properly linked!")))); EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } - TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfRenderGroupBindingHasIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfRenderGroupBindingHasIncomingLinks) { RenderGroupBindingElements elements; elements.addElement(*m_meshNode, "mesh"); @@ -420,18 +349,18 @@ namespace ramses::internal // -- mesh node bindings -- // - TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfMeshNodeBindingHasNoIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfMeshNodeBindingHasNoIncomingLinks) { m_logicEngine->createMeshNodeBinding(*m_meshNode, "binding"); m_logicEngine->validate(report); const auto& warnings = report.getIssues(); ASSERT_EQ(1u, warnings.size()); - EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no ingoing links! Node should be deleted or properly linked!")))); + EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [binding] has no incoming links! Node should be deleted or properly linked!")))); EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } - TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfMeshNodeBindingHasIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfMeshNodeBindingHasIncomingLinks) { const auto binding = m_logicEngine->createMeshNodeBinding(*m_meshNode, "binding"); ASSERT_NE(nullptr, binding); @@ -459,7 +388,7 @@ namespace ramses::internal const auto& warnings = report.getIssues(); ASSERT_EQ(2u, warnings.size()); EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [anim] has no outgoing links! Node should be deleted or properly linked!")), - ::testing::Field(&Issue::message, ::testing::StrEq("Node [anim] has no ingoing links! Node should be deleted or properly linked!")))); + ::testing::Field(&Issue::message, ::testing::StrEq("Node [anim] has no incoming links! Node should be deleted or properly linked!")))); EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } @@ -482,7 +411,7 @@ namespace ramses::internal EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } - TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfAnimationHasNoIngoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, ProducesWarningIfAnimationHasNoIncomingLinks) { const auto* m_dataFloat = m_logicEngine->createDataArray(std::vector{ 1.f, 2.f, 3.f }); const auto* m_dataVec2 = m_logicEngine->createDataArray(std::vector{ { 1.f, 2.f }, { 3.f, 4.f }, { 5.f, 6.f } }); @@ -497,11 +426,11 @@ namespace ramses::internal m_logicEngine->validate(report); const auto& warnings = report.getIssues(); ASSERT_EQ(1u, warnings.size()); - EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [anim] has no ingoing links! Node should be deleted or properly linked!")))); + EXPECT_THAT(warnings, ::testing::ElementsAre(::testing::Field(&Issue::message, ::testing::StrEq("Node [anim] has no incoming links! Node should be deleted or properly linked!")))); EXPECT_THAT(warnings, ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } - TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfAnimationHasIngoingAndOutgoingLinks) + TEST_F(ALogicEngine_ValidatingDanglingNodes, DoesNotProduceWarningIfAnimationHasIncomingAndOutgoingLinks) { const auto* m_dataFloat = m_logicEngine->createDataArray(std::vector{ 1.f, 2.f, 3.f }); const auto* m_dataVec2 = m_logicEngine->createDataArray(std::vector{ { 1.f, 2.f }, { 3.f, 4.f }, { 5.f, 6.f } }); diff --git a/tests/unittests/client/logic/api/LogicObjectTest.cpp b/tests/unittests/client/logic/api/LogicObjectTest.cpp index aaed486f3..5bf482975 100644 --- a/tests/unittests/client/logic/api/LogicObjectTest.cpp +++ b/tests/unittests/client/logic/api/LogicObjectTest.cpp @@ -24,6 +24,7 @@ #include "ramses/client/logic/AnimationNodeConfig.h" #include "ramses/client/logic/TimerNode.h" #include "ramses/client/logic/AnchorPoint.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/PerspectiveCamera.h" #include "ramses/client/RenderGroup.h" #include "ramses/client/RenderPass.h" @@ -44,6 +45,7 @@ #include "impl/logic/AnimationNodeImpl.h" #include "impl/logic/TimerNodeImpl.h" #include "impl/logic/AnchorPointImpl.h" +#include "impl/logic/RenderBufferBindingImpl.h" #include "impl/RamsesObjectTypeTraits.h" #include "impl/RamsesObjectTypeUtils.h" @@ -246,6 +248,7 @@ namespace ramses::internal this->template createObjectOfType("objectName"); this->template createObjectOfType("objectName"); this->template createObjectOfType("objectName"); + this->template createObjectOfType("objectName"); auto* obj = this->template createObjectOfType("objectName"); ASSERT_TRUE(obj); @@ -255,7 +258,7 @@ namespace ramses::internal EXPECT_TRUE(obj->setName("newName")); EXPECT_TRUE(obj->setUserId(1u, 2u)); - ASSERT_TRUE(this->saveToFileWithoutValidation("file.tmp")); + ASSERT_TRUE(this->saveToFile("file.tmp")); ASSERT_TRUE(this->recreateFromFile("file.tmp")); } diff --git a/tests/unittests/client/logic/api/LuaConfigTest.cpp b/tests/unittests/client/logic/api/LuaConfigTest.cpp index a9bfabef0..2ea03ad8b 100644 --- a/tests/unittests/client/logic/api/LuaConfigTest.cpp +++ b/tests/unittests/client/logic/api/LuaConfigTest.cpp @@ -120,7 +120,7 @@ namespace ramses::internal { EXPECT_FALSE(config.addDependency(invalidLabel, *m_module)); - EXPECT_EQ(fmt::format("Failed to add dependency '{}'! The alias name should be a valid Lua label.", invalidLabel), m_errorMessage); + EXPECT_EQ(fmt::format("R.main: Failed to add dependency '{}'! The alias name should be a valid Lua label.", invalidLabel), m_errorMessage); } } @@ -131,7 +131,7 @@ namespace ramses::internal ASSERT_TRUE(config.addDependency("module", *m_module)); EXPECT_FALSE(config.addDependency("module", *m_module)); - EXPECT_EQ("Module dependencies must be uniquely aliased! Alias 'module' is already used!", m_errorMessage); + EXPECT_EQ("R.main: Module dependencies must be uniquely aliased! Alias 'module' is already used!", m_errorMessage); } TEST_F(ALuaConfig, ProducesErrorWhenUsingStandardModuleAsAliasName) @@ -139,13 +139,13 @@ namespace ramses::internal LuaConfig config; EXPECT_FALSE(config.addDependency("math", *m_module)); - EXPECT_EQ("Failed to add dependency 'math'! The alias collides with a standard library name!", m_errorMessage); + EXPECT_EQ("R.main: Failed to add dependency 'math'! The alias collides with a standard library name!", m_errorMessage); EXPECT_FALSE(config.addDependency("string", *m_module)); - EXPECT_EQ("Failed to add dependency 'string'! The alias collides with a standard library name!", m_errorMessage); + EXPECT_EQ("R.main: Failed to add dependency 'string'! The alias collides with a standard library name!", m_errorMessage); EXPECT_FALSE(config.addDependency("debug", *m_module)); - EXPECT_EQ("Failed to add dependency 'debug'! The alias collides with a standard library name!", m_errorMessage); + EXPECT_EQ("R.main: Failed to add dependency 'debug'! The alias collides with a standard library name!", m_errorMessage); EXPECT_FALSE(config.addDependency("table", *m_module)); - EXPECT_EQ("Failed to add dependency 'table'! The alias collides with a standard library name!", m_errorMessage); + EXPECT_EQ("R.main: Failed to add dependency 'table'! The alias collides with a standard library name!", m_errorMessage); } TEST_F(ALuaConfig, CanEnableDebugLogFunctions) diff --git a/tests/unittests/client/logic/api/LuaInterfaceTest.cpp b/tests/unittests/client/logic/api/LuaInterfaceTest.cpp index 1e559bec7..f30144d3c 100644 --- a/tests/unittests/client/logic/api/LuaInterfaceTest.cpp +++ b/tests/unittests/client/logic/api/LuaInterfaceTest.cpp @@ -951,7 +951,7 @@ namespace ramses::internal end )", "intf", config); - EXPECT_TRUE(saveToFileWithoutValidation("temp.ramses")); + EXPECT_TRUE(saveToFile("temp.ramses")); } ASSERT_TRUE(recreateFromFile("temp.ramses")); @@ -1050,7 +1050,7 @@ namespace ramses::internal otherEngine.link(*intf->getOutputs()->getChild("param2")->getChild("y")->getChild(0u), *inputsScript->getInputs()->getChild("param2")->getChild("y")->getChild(0u)); otherEngine.link(*intf->getOutputs()->getChild("param2")->getChild("y")->getChild(1u), *inputsScript->getInputs()->getChild("param2")->getChild("y")->getChild(1u)); - ASSERT_TRUE(saveToFileWithoutValidation("interface.ramses")); + ASSERT_TRUE(saveToFile("interface.ramses")); } ASSERT_TRUE(recreateFromFile("interface.ramses")); @@ -1058,7 +1058,7 @@ namespace ramses::internal const auto loadedIntf = m_logicEngine->findObject("intf"); ASSERT_NE(nullptr, loadedIntf); - EXPECT_EQ(10u, loadedIntf->getSceneObjectId().getValue()); + EXPECT_EQ(11u, loadedIntf->getSceneObjectId().getValue()); EXPECT_EQ(loadedIntf->getInputs(), loadedIntf->getOutputs()); ASSERT_EQ(2u, loadedIntf->getInputs()->getChildCount()); const auto param1 = loadedIntf->getInputs()->getChild("param1"); @@ -1082,12 +1082,6 @@ namespace ramses::internal EXPECT_EQ(EPropertyType::String, param2y->getChild(1u)->getType()); } - TEST_F(ALuaInterface_Serialization, FailsToSaveToFileIfInterfaceOutputsNotLinked) - { - createTestInterface(m_minimalInterface, "intf name"); - EXPECT_FALSE(saveToFile("interface.ramses")); - } - TEST_F(ALuaInterface_Serialization, CanSerializeWithNoIssue) { EXPECT_TRUE(deserializeSerializedDataWithIssue(ALuaInterface_Serialization::ESerializationIssue::AllValid)); diff --git a/tests/unittests/client/logic/api/LuaModuleTest.cpp b/tests/unittests/client/logic/api/LuaModuleTest.cpp index 78a210694..a5a2d3bc9 100644 --- a/tests/unittests/client/logic/api/LuaModuleTest.cpp +++ b/tests/unittests/client/logic/api/LuaModuleTest.cpp @@ -55,7 +55,7 @@ namespace ramses::internal const auto module = m_logicEngine->createLuaModule(m_moduleSourceCode, {}, "mymodule"); ASSERT_NE(nullptr, module); EXPECT_EQ("mymodule", module->getName()); - EXPECT_EQ(module->getSceneObjectId().getValue(), 9u); + EXPECT_EQ(module->getSceneObjectId().getValue(), 10u); } TEST_F(ALuaModule, ChangesName) @@ -129,14 +129,14 @@ namespace ramses::internal { LogicEngine& logic = *m_logicEngine; logic.createLuaModule(m_moduleSourceCode, {}, "mymodule"); - EXPECT_TRUE(saveToFileWithoutValidation("module.tmp")); + EXPECT_TRUE(saveToFile("module.tmp")); } ASSERT_TRUE(recreateFromFile("module.tmp")); const auto module = m_logicEngine->findObject("mymodule"); ASSERT_NE(nullptr, module); EXPECT_EQ("mymodule", module->getName()); - EXPECT_EQ(module->getSceneObjectId().getValue(), 9u); + EXPECT_EQ(module->getSceneObjectId().getValue(), 10u); } TEST_F(ALuaModule_SerializationLifecycle, StoresDuplicateByteCodeOnce) @@ -438,7 +438,7 @@ namespace ramses::internal { LogicEngine& logic = *m_logicEngine; logic.createLuaModule(m_moduleSourceCode, {}, "mymodule"); - EXPECT_TRUE(saveToFileWithoutValidation("module.tmp")); + EXPECT_TRUE(saveToFile("module.tmp")); } ASSERT_TRUE(recreateFromFile("module.tmp")); @@ -473,7 +473,7 @@ namespace ramses::internal const auto quadsMod = m_logicEngine->createLuaModule(m_quadsSrc, createDeps({{"mymath", m_mathSrc}}), "quadsMod"); ASSERT_NE(nullptr, quadsMod); EXPECT_EQ("quadsMod", quadsMod->getName()); - EXPECT_EQ(quadsMod->getSceneObjectId().getValue(), 10u); // module dependency has id 8u + EXPECT_EQ(quadsMod->getSceneObjectId().getValue(), 11u); } TEST_F(ALuaModuleWithDependency, HasTwoDependencies) @@ -599,7 +599,7 @@ namespace ramses::internal LuaConfig config; config.addDependency("mymath", *logic.createLuaModule(m_mathSrc, {}, "mathMod")); logic.createLuaModule(m_quadsSrc, config, "quadsMod"); - EXPECT_TRUE(saveToFileWithoutValidation("dep_modules.tmp")); + EXPECT_TRUE(saveToFile("dep_modules.tmp")); } ASSERT_TRUE(recreateFromFile("dep_modules.tmp")); @@ -608,8 +608,8 @@ namespace ramses::internal auto quadsMod = m_logicEngine->findObject("quadsMod"); ASSERT_NE(mathMod, nullptr); ASSERT_NE(quadsMod, nullptr); - EXPECT_EQ(mathMod->getSceneObjectId().getValue(), 9u); - EXPECT_EQ(quadsMod->getSceneObjectId().getValue(), 10u); + EXPECT_EQ(mathMod->getSceneObjectId().getValue(), 10u); + EXPECT_EQ(quadsMod->getSceneObjectId().getValue(), 11u); EXPECT_THAT(quadsMod->impl().getDependencies(), ::testing::ElementsAre(std::pair({"mymath", mathMod}))); } diff --git a/tests/unittests/client/logic/api/LuaScriptTest_Debug.cpp b/tests/unittests/client/logic/api/LuaScriptTest_Debug.cpp index bd9566c9a..3322ddc0e 100644 --- a/tests/unittests/client/logic/api/LuaScriptTest_Debug.cpp +++ b/tests/unittests/client/logic/api/LuaScriptTest_Debug.cpp @@ -201,12 +201,12 @@ namespace ramses::internal ASSERT_NE(nullptr, script); EXPECT_TRUE(script->impl().hasDebugLogFunctions()); - EXPECT_FALSE(saveToFileWithoutValidation("willNotSave.tmp")); - expectError("Cannot save to file, Lua script 'script [LogicObject ScnObjId=9]' has enabled debug log functions, remove this script before saving.", script); + EXPECT_FALSE(saveToFile("willNotSave.tmp")); + expectError("Cannot save to file, Lua script 'script [LogicObject ScnObjId=10]' has enabled debug log functions, remove this script before saving.", script); // can save after removal EXPECT_TRUE(m_logicEngine->destroy(*script)); - EXPECT_TRUE(saveToFileWithoutValidation("willSave.tmp")); + EXPECT_TRUE(saveToFile("willSave.tmp")); } TEST_F(ALuaScript_Debug, FailsToSaveToFileIfModuleHasDebugLogFunctions) @@ -227,11 +227,11 @@ namespace ramses::internal ASSERT_NE(nullptr, mod); EXPECT_TRUE(mod->impl().hasDebugLogFunctions()); - EXPECT_FALSE(saveToFileWithoutValidation("willNotSave.tmp")); - expectError("Cannot save to file, Lua module 'mod [LogicObject ScnObjId=9]' has enabled debug log functions, remove this module before saving.", mod); + EXPECT_FALSE(saveToFile("willNotSave.tmp")); + expectError("Cannot save to file, Lua module 'mod [LogicObject ScnObjId=10]' has enabled debug log functions, remove this module before saving.", mod); // can save after removal EXPECT_TRUE(m_logicEngine->destroy(*mod)); - EXPECT_TRUE(saveToFileWithoutValidation("willSave.tmp")); + EXPECT_TRUE(saveToFile("willSave.tmp")); } } diff --git a/tests/unittests/client/logic/api/LuaScriptTest_Init.cpp b/tests/unittests/client/logic/api/LuaScriptTest_Init.cpp index 7dbca6fc3..78b91e4b0 100644 --- a/tests/unittests/client/logic/api/LuaScriptTest_Init.cpp +++ b/tests/unittests/client/logic/api/LuaScriptTest_Init.cpp @@ -218,7 +218,7 @@ namespace ramses::internal ASSERT_TRUE(tmpLogicEngine.update()); ASSERT_EQ(5, *script->getOutputs()->getChild("globalValueBefore")->get()); ASSERT_EQ(42, *script->getOutputs()->getChild("globalValueAfter")->get()); - ASSERT_TRUE(saveToFileWithoutValidation("withGlobals.bin")); + ASSERT_TRUE(saveToFile("withGlobals.bin")); } ASSERT_TRUE(recreateFromFile("withGlobals.bin")); @@ -423,7 +423,7 @@ namespace ramses::internal end)", {}, "script"); ASSERT_NE(nullptr, script); EXPECT_TRUE(otherLogic.update()); - EXPECT_TRUE(saveToFileWithoutValidation("intfInGlobal.bin")); + EXPECT_TRUE(saveToFile("intfInGlobal.bin")); } ASSERT_TRUE(recreateFromFile("intfInGlobal.bin")); diff --git a/tests/unittests/client/logic/api/LuaScriptTest_Lifecycle.cpp b/tests/unittests/client/logic/api/LuaScriptTest_Lifecycle.cpp index dc2dfc8cb..b6650c037 100644 --- a/tests/unittests/client/logic/api/LuaScriptTest_Lifecycle.cpp +++ b/tests/unittests/client/logic/api/LuaScriptTest_Lifecycle.cpp @@ -79,7 +79,7 @@ namespace ramses::internal )"); ASSERT_NE(nullptr, script); - EXPECT_TRUE(saveToFileWithoutValidation("script.bin")); + EXPECT_TRUE(saveToFile("script.bin")); } { EXPECT_TRUE(recreateFromFile("script.bin")); @@ -121,7 +121,7 @@ namespace ramses::internal script->getInputs()->getChild("array")->getChild(0)->set(0.1f); script->getInputs()->getChild("array")->getChild(1)->set(0.2f); - EXPECT_TRUE(saveToFileWithoutValidation("script.bin")); + EXPECT_TRUE(saveToFile("script.bin")); } { recreateFromFile("script.bin"); @@ -165,7 +165,7 @@ namespace ramses::internal )", {}, "MyScript"); script->getInputs()->getChild("nested")->getChild("array")->getChild(0)->set({1.1f, 1.2f, 1.3f}); - EXPECT_TRUE(saveToFileWithoutValidation("arrays.bin")); + EXPECT_TRUE(saveToFile("arrays.bin")); } { recreateFromFile("arrays.bin"); @@ -213,7 +213,7 @@ namespace ramses::internal )"); ASSERT_NE(nullptr, script); - EXPECT_TRUE(saveToFileWithoutValidation("nested_array.bin")); + EXPECT_TRUE(saveToFile("nested_array.bin")); } { EXPECT_TRUE(recreateFromFile("nested_array.bin")); @@ -284,7 +284,7 @@ namespace ramses::internal ASSERT_NE(nullptr, script); script->getInputs()->getChild("arrayOfStructs")->getChild(1)->getChild("nested_struct")->getChild("nested_array")->getChild(0)->set(42.f); - EXPECT_TRUE(saveToFileWithoutValidation("array_of_structs.bin")); + EXPECT_TRUE(saveToFile("array_of_structs.bin")); } { EXPECT_TRUE(recreateFromFile("array_of_structs.bin")); @@ -351,7 +351,7 @@ namespace ramses::internal auto script = tempLogicEngine.createLuaScript(scriptSrc, {}, "MyScript"); ASSERT_NE(nullptr, script); - EXPECT_TRUE(saveToFileWithoutValidation("arrays.bin")); + EXPECT_TRUE(saveToFile("arrays.bin")); } { EXPECT_TRUE(recreateFromFile("arrays.bin")); @@ -410,7 +410,7 @@ namespace ramses::internal ASSERT_NE(nullptr, script); script->getInputs()->getChild("data")->set(42); - EXPECT_TRUE(saveToFileWithoutValidation("script.bin")); + EXPECT_TRUE(saveToFile("script.bin")); } EXPECT_TRUE(recreateFromFile("script.bin")); diff --git a/tests/unittests/client/logic/api/LuaScriptTest_Modules.cpp b/tests/unittests/client/logic/api/LuaScriptTest_Modules.cpp index bb1c80a0f..99257104d 100644 --- a/tests/unittests/client/logic/api/LuaScriptTest_Modules.cpp +++ b/tests/unittests/client/logic/api/LuaScriptTest_Modules.cpp @@ -671,9 +671,7 @@ namespace ramses::internal end )", config2, "script2"); - SaveFileConfig configNoValidation; - configNoValidation.setValidationEnabled(false); - EXPECT_TRUE(saveToFileWithoutValidation("scriptmodules.tmp")); + EXPECT_TRUE(saveToFile("scriptmodules.tmp")); } ASSERT_TRUE(recreateFromFile("scriptmodules.tmp")); @@ -850,9 +848,7 @@ namespace ramses::internal EXPECT_TRUE(otherLogicEngine.update()); - SaveFileConfig configNoValidation; - configNoValidation.setValidationEnabled(false); - ASSERT_TRUE(saveToFileWithoutValidation("moduleWithInterface.bin")); + ASSERT_TRUE(saveToFile("moduleWithInterface.bin")); } ASSERT_TRUE(recreateFromFile("moduleWithInterface.bin")); diff --git a/tests/unittests/client/logic/api/MeshNodeBindingTest.cpp b/tests/unittests/client/logic/api/MeshNodeBindingTest.cpp index 689b16a01..0c9f04be2 100644 --- a/tests/unittests/client/logic/api/MeshNodeBindingTest.cpp +++ b/tests/unittests/client/logic/api/MeshNodeBindingTest.cpp @@ -308,7 +308,7 @@ namespace ramses::internal EXPECT_TRUE(m_meshBinding->getInputs()->getChild(size_t(MeshNodeBindingImpl::EInputProperty::IndexOffset))->set(41)); EXPECT_TRUE(m_meshBinding->getInputs()->getChild(size_t(MeshNodeBindingImpl::EInputProperty::InstanceCount))->set(42)); EXPECT_TRUE(m_logicEngine->update()); - ASSERT_TRUE(saveToFileWithoutValidation("binding.bin")); + ASSERT_TRUE(saveToFile("binding.bin")); } { @@ -343,7 +343,7 @@ namespace ramses::internal { { EXPECT_TRUE(m_logicEngine->update()); - ASSERT_TRUE(saveToFileWithoutValidation("binding.bin")); + ASSERT_TRUE(saveToFile("binding.bin")); } { @@ -405,7 +405,7 @@ namespace ramses::internal EXPECT_TRUE(m_logicEngine->update()); EXPECT_EQ(3u, meshNode->getIndexCount()); - ASSERT_TRUE(saveToFileWithoutValidation("binding.bin")); + ASSERT_TRUE(saveToFile("binding.bin")); } ASSERT_TRUE(recreateFromFile("binding.bin")); diff --git a/tests/unittests/client/logic/api/NodeBindingTest.cpp b/tests/unittests/client/logic/api/NodeBindingTest.cpp index c5765216a..7df99b036 100644 --- a/tests/unittests/client/logic/api/NodeBindingTest.cpp +++ b/tests/unittests/client/logic/api/NodeBindingTest.cpp @@ -103,7 +103,7 @@ namespace ramses::internal TEST_F(ANodeBinding, KeepsIdProvidedDuringConstruction) { NodeBinding& nodeBinding = *m_logicEngine->createNodeBinding(*m_node, ERotationType::Euler_XYZ, "NodeBinding"); - EXPECT_EQ(nodeBinding.getSceneObjectId().getValue(), 9u); + EXPECT_EQ(nodeBinding.getSceneObjectId().getValue(), 10u); } TEST_F(ANodeBinding, ReturnsNullptrForOutputs) @@ -529,7 +529,7 @@ namespace ramses::internal EXPECT_EQ(messageType, ELogLevel::Warn); EXPECT_EQ(warningMessage, - fmt::format("Initial rotation values for NodeBinding '{}' will not be imported from bound Ramses node due to mismatching rotation type.", + fmt::format("R.main: Initial rotation values for NodeBinding '{}' will not be imported from bound Ramses node due to mismatching rotation type.", binding->impl().getIdentificationString())); EXPECT_EQ(*binding->getInputs()->getChild("rotation")->get(), vec3f(0.f, 0.f, 0.f)); @@ -558,7 +558,7 @@ namespace ramses::internal EXPECT_EQ( warningMessage, fmt::format( - "Initial rotation values for NodeBinding '{}' will not be imported from bound Ramses node due to mismatching rotation type. Expected Quaternion, got Euler.", + "R.main: Initial rotation values for NodeBinding '{}' will not be imported from bound Ramses node due to mismatching rotation type. Expected Quaternion, got Euler.", binding->impl().getIdentificationString())); EXPECT_EQ(*binding->getInputs()->getChild("rotation")->get(), vec4f(0.f, 0.f, 0.f, 1.f)); @@ -1026,14 +1026,14 @@ namespace ramses::internal nodeBinding.getInputs()->getChild("visibility")->set(true); nodeBinding.getInputs()->getChild("enabled")->set(true); tempEngineForSaving.update(); - EXPECT_TRUE(saveToFileWithoutValidation("OneBinding.bin")); + EXPECT_TRUE(saveToFile("OneBinding.bin")); } { ASSERT_TRUE(recreateFromFile("OneBinding.bin")); ASSERT_TRUE(m_logicEngine != nullptr); const auto& nodeBinding = *m_logicEngine->findObject("NodeBinding"); EXPECT_EQ("NodeBinding", nodeBinding.getName()); - EXPECT_EQ(nodeBinding.getSceneObjectId().getValue(), 9u); + EXPECT_EQ(nodeBinding.getSceneObjectId().getValue(), 10u); const auto& inputs = nodeBinding.getInputs(); ASSERT_EQ(inputs->getChildCount(), 5u); @@ -1084,7 +1084,7 @@ namespace ramses::internal { LogicEngine& tempEngineForSaving = *m_logicEngine; tempEngineForSaving.createNodeBinding(*m_node, ERotationType::Euler_XYZ, "NodeBinding"); - EXPECT_TRUE(saveToFileWithoutValidation("OneBinding.bin")); + EXPECT_TRUE(saveToFile("OneBinding.bin")); } { ASSERT_TRUE(recreateFromFile("OneBinding.bin")); @@ -1099,7 +1099,7 @@ namespace ramses::internal { LogicEngine& tempEngineForSaving = *m_logicEngine; tempEngineForSaving.createNodeBinding(*m_node, ERotationType::Euler_XYZ, "NodeBinding"); - EXPECT_TRUE(saveToFileWithoutValidation("NoValuesSet.bin")); + EXPECT_TRUE(saveToFile("NoValuesSet.bin")); } { ASSERT_TRUE(recreateFromFile("NoValuesSet.bin")); @@ -1131,7 +1131,7 @@ namespace ramses::internal m_node->setScaling({100.f, 100.f, 100.f}); m_node->setVisibility(EVisibilityMode::Invisible); - EXPECT_TRUE(saveToFileWithoutValidation("AllValuesSet.bin")); + EXPECT_TRUE(saveToFile("AllValuesSet.bin")); } { @@ -1190,7 +1190,7 @@ namespace ramses::internal ASSERT_TRUE(tempEngineForSaving.link(*script->getOutputs()->getChild("visibility"), *nodeBinding.getInputs()->getChild("visibility"))); tempEngineForSaving.update(); - EXPECT_TRUE(saveToFileWithoutValidation("SomeInputsLinked.bin")); + EXPECT_TRUE(saveToFile("SomeInputsLinked.bin")); } // Modify 'linked' properties before loading to check if logic will overwrite them after load + update @@ -1246,9 +1246,7 @@ namespace ramses::internal EXPECT_EQ(*prop_enabled->get(), enabled); EXPECT_EQ(*prop_visibility->get(), visibility); - SaveFileConfig saveConfig; - saveConfig.setValidationEnabled(false); - EXPECT_TRUE(scene->saveToFile("visibility.ramses", saveConfig)); + EXPECT_TRUE(scene->saveToFile("visibility.ramses", {})); m_ramses.destroyScene(*scene); } diff --git a/tests/unittests/client/logic/api/PropertyTest.cpp b/tests/unittests/client/logic/api/PropertyTest.cpp index b93cc83a3..c488a25d2 100644 --- a/tests/unittests/client/logic/api/PropertyTest.cpp +++ b/tests/unittests/client/logic/api/PropertyTest.cpp @@ -1150,25 +1150,25 @@ namespace ramses::internal EXPECT_FALSE(int64Property->set(std::numeric_limits::max())); EXPECT_EQ(logType, ELogLevel::Error); - EXPECT_EQ(logMessage, fmt::format("Invalid value when setting property 'int64input', Lua cannot handle full range of 64-bit integer, trying to set '{}' which is out of this range!", + EXPECT_EQ(logMessage, fmt::format("R.main: Invalid value when setting property 'int64input', Lua cannot handle full range of 64-bit integer, trying to set '{}' which is out of this range!", std::numeric_limits::max()).c_str()); EXPECT_FALSE(int64Property->set(std::numeric_limits::min())); EXPECT_EQ(logType, ELogLevel::Error); - EXPECT_EQ(logMessage, fmt::format("Invalid value when setting property 'int64input', Lua cannot handle full range of 64-bit integer, trying to set '{}' which is out of this range!", + EXPECT_EQ(logMessage, fmt::format("R.main: Invalid value when setting property 'int64input', Lua cannot handle full range of 64-bit integer, trying to set '{}' which is out of this range!", std::numeric_limits::min()).c_str()); static constexpr auto maxIntegerAsDouble = static_cast(1LLU << 53u); EXPECT_TRUE(int64Property->set(maxIntegerAsDouble)); EXPECT_FALSE(int64Property->set(maxIntegerAsDouble + 1)); EXPECT_EQ(logType, ELogLevel::Error); - EXPECT_EQ(logMessage, fmt::format("Invalid value when setting property 'int64input', Lua cannot handle full range of 64-bit integer, trying to set '{}' which is out of this range!", + EXPECT_EQ(logMessage, fmt::format("R.main: Invalid value when setting property 'int64input', Lua cannot handle full range of 64-bit integer, trying to set '{}' which is out of this range!", maxIntegerAsDouble + 1).c_str()); EXPECT_TRUE(int64Property->set(-maxIntegerAsDouble)); EXPECT_FALSE(int64Property->set(-maxIntegerAsDouble - 1)); EXPECT_EQ(logType, ELogLevel::Error); - EXPECT_EQ(logMessage, fmt::format("Invalid value when setting property 'int64input', Lua cannot handle full range of 64-bit integer, trying to set '{}' which is out of this range!", + EXPECT_EQ(logMessage, fmt::format("R.main: Invalid value when setting property 'int64input', Lua cannot handle full range of 64-bit integer, trying to set '{}' which is out of this range!", -maxIntegerAsDouble - 1).c_str()); } } diff --git a/tests/unittests/client/logic/api/RenderBufferBindingTest.cpp b/tests/unittests/client/logic/api/RenderBufferBindingTest.cpp new file mode 100644 index 000000000..a9583623e --- /dev/null +++ b/tests/unittests/client/logic/api/RenderBufferBindingTest.cpp @@ -0,0 +1,290 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#include "LogicEngineTest_Base.h" +#include "RamsesTestUtils.h" +#include "SerializationTestUtils.h" +#include "RamsesObjectResolverMock.h" + +#include "ramses/client/logic/RenderBufferBinding.h" +#include "ramses/client/logic/Property.h" +#include "impl/logic/RenderBufferBindingImpl.h" +#include "impl/logic/NodeBindingImpl.h" +#include "impl/logic/PropertyImpl.h" +#include "impl/ErrorReporting.h" +#include "internal/logic/TypeData.h" + +#include "internal/logic/flatbuffers/generated/RenderBufferBindingGen.h" + +namespace ramses::internal +{ + class ARenderBufferBinding : public ALogicEngine + { + protected: + RenderBufferBinding* m_rbBinding{ m_logicEngine->createRenderBufferBinding(*m_renderBuffer, "binding") }; + + static constexpr auto PropCount = static_cast(RenderBufferBindingImpl::EInputProperty::COUNT); + static constexpr auto PropIdxWidth = static_cast(RenderBufferBindingImpl::EInputProperty::Width); + static constexpr auto PropIdxHeight = static_cast(RenderBufferBindingImpl::EInputProperty::Height); + static constexpr auto PropIdxSampleCount = static_cast(RenderBufferBindingImpl::EInputProperty::SampleCount); + }; + + TEST_F(ARenderBufferBinding, RefersToGivenRamsesObject) + { + EXPECT_EQ(m_renderBuffer, &m_rbBinding->getRenderBuffer()); + const auto& rbConst = *m_rbBinding; + EXPECT_EQ(m_renderBuffer, &rbConst.getRenderBuffer()); + const auto& rbImplConst = m_rbBinding->impl(); + EXPECT_EQ(m_renderBuffer, &rbImplConst.getRenderBuffer()); + } + + TEST_F(ARenderBufferBinding, HasInputPropertiesAndNoOutputs) + { + ASSERT_NE(nullptr, m_rbBinding->getInputs()); + ASSERT_EQ(PropCount, m_rbBinding->getInputs()->getChildCount()); + EXPECT_EQ(m_rbBinding->getInputs()->getChild(PropIdxWidth), m_rbBinding->getInputs()->getChild("width")); + EXPECT_EQ(m_rbBinding->getInputs()->getChild(PropIdxHeight), m_rbBinding->getInputs()->getChild("height")); + EXPECT_EQ(m_rbBinding->getInputs()->getChild(PropIdxSampleCount), m_rbBinding->getInputs()->getChild("sampleCount")); + EXPECT_EQ(nullptr, m_rbBinding->getOutputs()); + } + + TEST_F(ARenderBufferBinding, InputPropertiesAreInitializedFromBoundRenderBuffer) + { + EXPECT_EQ(1, *m_rbBinding->getInputs()->getChild(PropIdxWidth)->get()); + EXPECT_EQ(2, *m_rbBinding->getInputs()->getChild(PropIdxHeight)->get()); + EXPECT_EQ(3, *m_rbBinding->getInputs()->getChild(PropIdxSampleCount)->get()); + } + + TEST_F(ARenderBufferBinding, SetsModifiedBoundValuesOnUpdate) + { + // initial values + EXPECT_TRUE(m_logicEngine->update()); + EXPECT_EQ(1u, m_renderBuffer->getWidth()); + EXPECT_EQ(2u, m_renderBuffer->getHeight()); + EXPECT_EQ(3u, m_renderBuffer->getSampleCount()); + + EXPECT_TRUE(m_rbBinding->getInputs()->getChild(PropIdxWidth)->set(42)); + EXPECT_TRUE(m_logicEngine->update()); + EXPECT_EQ(42u, m_renderBuffer->getWidth()); + EXPECT_EQ(2u, m_renderBuffer->getHeight()); + EXPECT_EQ(3u, m_renderBuffer->getSampleCount()); + + EXPECT_TRUE(m_rbBinding->getInputs()->getChild(PropIdxHeight)->set(43)); + EXPECT_TRUE(m_rbBinding->getInputs()->getChild(PropIdxSampleCount)->set(44)); + EXPECT_TRUE(m_logicEngine->update()); + EXPECT_EQ(42u, m_renderBuffer->getWidth()); + EXPECT_EQ(43u, m_renderBuffer->getHeight()); + EXPECT_EQ(44u, m_renderBuffer->getSampleCount()); + } + + TEST_F(ARenderBufferBinding, FailsUpdateIfTryingToSetInvalidValue_Width) + { + EXPECT_TRUE(m_rbBinding->getInputs()->getChild(PropIdxWidth)->set(-1)); + EXPECT_FALSE(m_logicEngine->update()); + expectError("RenderBufferBinding input cannot be negative", m_rbBinding); + } + + TEST_F(ARenderBufferBinding, FailsUpdateIfTryingToSetInvalidValue_Height) + { + EXPECT_TRUE(m_rbBinding->getInputs()->getChild(PropIdxHeight)->set(-1)); + EXPECT_FALSE(m_logicEngine->update()); + expectError("RenderBufferBinding input cannot be negative", m_rbBinding); + } + + TEST_F(ARenderBufferBinding, FailsUpdateIfTryingToSetInvalidValue_SampleCount) + { + EXPECT_TRUE(m_rbBinding->getInputs()->getChild(PropIdxSampleCount)->set(-1)); + EXPECT_FALSE(m_logicEngine->update()); + expectError("RenderBufferBinding input cannot be negative", m_rbBinding); + } + + TEST_F(ARenderBufferBinding, FailsUpdateIfReferencedRenderBufferSetFails) + { + // binding only checks for negative values, render buffer setter for other criteria, e.g. width/height cant be zero + EXPECT_TRUE(m_rbBinding->getInputs()->getChild(PropIdxHeight)->set(0)); + EXPECT_FALSE(m_logicEngine->update()); + expectError("RenderBuffer::setProperties: width and height cannot be zero", m_rbBinding); + } + + class ARenderBufferBinding_SerializationLifecycle : public ARenderBufferBinding + { + protected: + enum class ESerializationIssue + { + AllValid, + MissingBase, + MissingName, + MissingRoot, + CorruptedInputProperties, + MissingBoundObject, + UnresolvedRenderBuffer, + InvalidBoundObjectType + }; + + std::unique_ptr deserializeSerializedDataWithIssue(ESerializationIssue issue) + { + { + auto inputsType = MakeStruct("", { + TypeData{"width", EPropertyType::Int32}, + TypeData{"height", EPropertyType::Int32}, + (issue == ESerializationIssue::CorruptedInputProperties ? TypeData{"wrong", EPropertyType::Int32} : TypeData{"sampleCount", EPropertyType::Int32}) + }); + auto inputs = std::make_unique(std::move(inputsType), EPropertySemantics::BindingInput); + + SerializationMap serializationMap; + const auto logicObject = rlogic_serialization::CreateLogicObject(m_flatBufferBuilder, + (issue == ESerializationIssue::MissingName ? 0 : m_flatBufferBuilder.CreateString("name")), 1u); + auto fbRamsesBinding = rlogic_serialization::CreateRamsesBinding(m_flatBufferBuilder, + logicObject, + (issue == ESerializationIssue::MissingBoundObject ? 0 : rlogic_serialization::CreateRamsesReference(m_flatBufferBuilder, + 1u, (issue == ESerializationIssue::InvalidBoundObjectType ? 0 : static_cast(ramses::ERamsesObjectType::RenderBuffer)))), + (issue == ESerializationIssue::MissingRoot ? 0 : PropertyImpl::Serialize(*inputs, m_flatBufferBuilder, serializationMap))); + + auto fbRenderBufferBinding = rlogic_serialization::CreateRenderBufferBinding(m_flatBufferBuilder, (issue == ESerializationIssue::MissingBase ? 0 : fbRamsesBinding)); + m_flatBufferBuilder.Finish(fbRenderBufferBinding); + } + + switch (issue) + { + case ESerializationIssue::AllValid: + case ESerializationIssue::InvalidBoundObjectType: + EXPECT_CALL(m_resolverMock, findRamsesSceneObjectInScene(::testing::Eq("name"), ramses::sceneObjectId_t{ 1u })).WillOnce(::testing::Return(m_renderBuffer)); + break; + case ESerializationIssue::UnresolvedRenderBuffer: + EXPECT_CALL(m_resolverMock, findRamsesSceneObjectInScene(::testing::Eq("name"), ramses::sceneObjectId_t{ 1u })).WillOnce(::testing::Return(nullptr)); + break; + default: + break; + } + + DeserializationMap deserializationMap{ m_scene->impl() }; + const auto& serialized = *flatbuffers::GetRoot(m_flatBufferBuilder.GetBufferPointer()); + return RenderBufferBindingImpl::Deserialize(serialized, m_resolverMock, m_errorReporting, deserializationMap); + } + + flatbuffers::FlatBufferBuilder m_flatBufferBuilder; + ::testing::StrictMock m_resolverMock; + ErrorReporting m_errorReporting; + }; + + TEST_F(ARenderBufferBinding_SerializationLifecycle, CanSerializeWithNoIssue) + { + EXPECT_TRUE(deserializeSerializedDataWithIssue(ARenderBufferBinding_SerializationLifecycle::ESerializationIssue::AllValid)); + EXPECT_FALSE(m_errorReporting.getError().has_value()); + } + + TEST_F(ARenderBufferBinding_SerializationLifecycle, ReportsSerializationError_MissingBase) + { + EXPECT_FALSE(deserializeSerializedDataWithIssue(ARenderBufferBinding_SerializationLifecycle::ESerializationIssue::MissingBase)); + ASSERT_TRUE(m_errorReporting.getError().has_value()); + EXPECT_EQ(m_errorReporting.getError()->message, "Fatal error during loading of RenderBufferBinding from serialized data: missing base class info!"); + } + + TEST_F(ARenderBufferBinding_SerializationLifecycle, ReportsSerializationError_MissingName) + { + EXPECT_FALSE(deserializeSerializedDataWithIssue(ARenderBufferBinding_SerializationLifecycle::ESerializationIssue::MissingName)); + ASSERT_TRUE(m_errorReporting.getError().has_value()); + EXPECT_EQ(m_errorReporting.getError()->message, "Fatal error during loading of RenderBufferBinding from serialized data: missing name and/or ID!"); + } + + TEST_F(ARenderBufferBinding_SerializationLifecycle, ReportsSerializationError_MissingRoot) + { + EXPECT_FALSE(deserializeSerializedDataWithIssue(ARenderBufferBinding_SerializationLifecycle::ESerializationIssue::MissingRoot)); + ASSERT_TRUE(m_errorReporting.getError().has_value()); + EXPECT_EQ(m_errorReporting.getError()->message, "Fatal error during loading of RenderBufferBinding from serialized data: missing root input!"); + } + + TEST_F(ARenderBufferBinding_SerializationLifecycle, ReportsSerializationError_CorruptedInputProperties) + { + EXPECT_FALSE(deserializeSerializedDataWithIssue(ARenderBufferBinding_SerializationLifecycle::ESerializationIssue::CorruptedInputProperties)); + ASSERT_TRUE(m_errorReporting.getError().has_value()); + EXPECT_EQ(m_errorReporting.getError()->message, "Fatal error during loading of RenderBufferBinding from serialized data: corrupted root input!"); + } + + TEST_F(ARenderBufferBinding_SerializationLifecycle, ReportsSerializationError_MissingBoundObject) + { + EXPECT_FALSE(deserializeSerializedDataWithIssue(ARenderBufferBinding_SerializationLifecycle::ESerializationIssue::MissingBoundObject)); + ASSERT_TRUE(m_errorReporting.getError().has_value()); + EXPECT_EQ(m_errorReporting.getError()->message, "Fatal error during loading of RenderBufferBinding from serialized data: missing ramses object reference!"); + } + + TEST_F(ARenderBufferBinding_SerializationLifecycle, ReportsSerializationError_UnresolvedRenderBuffer) + { + EXPECT_FALSE(deserializeSerializedDataWithIssue(ARenderBufferBinding_SerializationLifecycle::ESerializationIssue::UnresolvedRenderBuffer)); + // error message is generated in resolver which is mocked here + } + + TEST_F(ARenderBufferBinding_SerializationLifecycle, ReportsSerializationError_InvalidBoundObjectType) + { + EXPECT_FALSE(deserializeSerializedDataWithIssue(ARenderBufferBinding_SerializationLifecycle::ESerializationIssue::InvalidBoundObjectType)); + ASSERT_TRUE(m_errorReporting.getError().has_value()); + EXPECT_EQ(m_errorReporting.getError()->message, "Fatal error during loading of RenderBufferBinding from serialized data: loaded object type does not match referenced object type!"); + } + + TEST_F(ARenderBufferBinding_SerializationLifecycle, KeepsItsPropertiesAfterDeserialization) + { + { + EXPECT_TRUE(m_rbBinding->getInputs()->getChild(PropIdxHeight)->set(41)); + EXPECT_TRUE(m_rbBinding->getInputs()->getChild(PropIdxSampleCount)->set(42)); + EXPECT_TRUE(m_logicEngine->update()); + ASSERT_TRUE(saveToFile("binding.bin")); + } + + { + ASSERT_TRUE(recreateFromFile("binding.bin")); + const auto loadedBinding = m_logicEngine->findObject("binding"); + ASSERT_TRUE(loadedBinding); + EXPECT_EQ(m_renderBuffer, &loadedBinding->getRenderBuffer()); + + ASSERT_NE(nullptr, loadedBinding->getInputs()); + ASSERT_EQ(PropCount, loadedBinding->getInputs()->getChildCount()); + EXPECT_EQ(loadedBinding->getInputs()->getChild(PropIdxWidth), loadedBinding->getInputs()->getChild("width")); + EXPECT_EQ(loadedBinding->getInputs()->getChild(PropIdxHeight), loadedBinding->getInputs()->getChild("height")); + EXPECT_EQ(loadedBinding->getInputs()->getChild(PropIdxSampleCount), loadedBinding->getInputs()->getChild("sampleCount")); + EXPECT_EQ(nullptr, loadedBinding->getOutputs()); + + EXPECT_EQ(41, *loadedBinding->getInputs()->getChild(PropIdxHeight)->get()); + EXPECT_EQ(42, *loadedBinding->getInputs()->getChild(PropIdxSampleCount)->get()); + + // confidence test - can set new values + EXPECT_TRUE(loadedBinding->getInputs()->getChild(PropIdxHeight)->set(43)); + EXPECT_TRUE(loadedBinding->getInputs()->getChild(PropIdxSampleCount)->set(44)); + EXPECT_TRUE(m_logicEngine->update()); + EXPECT_EQ(1u, m_renderBuffer->getWidth()); // did not change + EXPECT_EQ(43u, m_renderBuffer->getHeight()); // changed before saving and again after loading + EXPECT_EQ(44u, m_renderBuffer->getSampleCount()); // changed after loading + } + } + + TEST_F(ARenderBufferBinding_SerializationLifecycle, DoesNotModifyAnyValueIfNotSetDuringSerializationAndDeserialization) + { + { + EXPECT_TRUE(m_logicEngine->update()); + ASSERT_TRUE(saveToFile("binding.bin")); + } + + { + ASSERT_TRUE(recreateFromFile("binding.bin")); + const auto loadedBinding = m_logicEngine->findObject("binding"); + ASSERT_TRUE(loadedBinding); + EXPECT_EQ(m_renderBuffer, &loadedBinding->getRenderBuffer()); + + ASSERT_NE(nullptr, loadedBinding->getInputs()); + ASSERT_EQ(PropCount, loadedBinding->getInputs()->getChildCount()); + EXPECT_EQ(loadedBinding->getInputs()->getChild(PropIdxWidth), loadedBinding->getInputs()->getChild("width")); + EXPECT_EQ(loadedBinding->getInputs()->getChild(PropIdxHeight), loadedBinding->getInputs()->getChild("height")); + EXPECT_EQ(loadedBinding->getInputs()->getChild(PropIdxSampleCount), loadedBinding->getInputs()->getChild("sampleCount")); + EXPECT_EQ(nullptr, loadedBinding->getOutputs()); + + EXPECT_TRUE(m_logicEngine->update()); + EXPECT_EQ(1u, m_renderBuffer->getWidth()); + EXPECT_EQ(2u, m_renderBuffer->getHeight()); + EXPECT_EQ(3u, m_renderBuffer->getSampleCount()); + } + } +} diff --git a/tests/unittests/client/logic/api/RenderGroupBindingTest.cpp b/tests/unittests/client/logic/api/RenderGroupBindingTest.cpp index f092bce26..63a777ac3 100644 --- a/tests/unittests/client/logic/api/RenderGroupBindingTest.cpp +++ b/tests/unittests/client/logic/api/RenderGroupBindingTest.cpp @@ -445,7 +445,7 @@ namespace ramses::internal EXPECT_TRUE(m_logicEngine->update()); // binding has no inputs linked, validatation would fail - ASSERT_TRUE(saveToFileWithoutValidation("binding.bin")); + ASSERT_TRUE(saveToFile("binding.bin")); } { diff --git a/tests/unittests/client/logic/api/RenderPassBindingTest.cpp b/tests/unittests/client/logic/api/RenderPassBindingTest.cpp index 1b580af99..0eed7bcbc 100644 --- a/tests/unittests/client/logic/api/RenderPassBindingTest.cpp +++ b/tests/unittests/client/logic/api/RenderPassBindingTest.cpp @@ -475,7 +475,7 @@ namespace ramses::internal { { m_logicEngine->createRenderPassBinding(*m_renderPass, "renderPass"); - ASSERT_TRUE(saveToFileWithoutValidation("binding.bin")); + ASSERT_TRUE(saveToFile("binding.bin")); } { @@ -506,7 +506,7 @@ namespace ramses::internal binding.getInputs()->getChild("renderOrder")->set(42); m_logicEngine->update(); EXPECT_EQ(42, m_renderPass->getRenderOrder()); - ASSERT_TRUE(saveToFileWithoutValidation("logic.bin")); + ASSERT_TRUE(saveToFile("logic.bin")); } { @@ -552,7 +552,7 @@ namespace ramses::internal // or any set() calls to the corresponding RenderPassBinding input m_renderPass->setRenderOnce(true); - ASSERT_TRUE(saveToFileWithoutValidation("SomeValuesLinked.bin")); + ASSERT_TRUE(saveToFile("SomeValuesLinked.bin")); } { diff --git a/tests/unittests/client/logic/api/SaveFileConfigTest.cpp b/tests/unittests/client/logic/api/SaveFileConfigTest.cpp index f8952322d..eb77eaddf 100644 --- a/tests/unittests/client/logic/api/SaveFileConfigTest.cpp +++ b/tests/unittests/client/logic/api/SaveFileConfigTest.cpp @@ -23,7 +23,6 @@ namespace ramses::internal { config.setMetadataString("metadata"); config.setExporterVersion(1u, 2u, 3u, 4u); - config.setValidationEnabled(false); config.setCompressionEnabled(true); config.setLuaSavingMode(ELuaSavingMode::SourceAndByteCode); } @@ -35,9 +34,8 @@ namespace ramses::internal EXPECT_EQ(2u, config.impl().getExporterVersion().minor); EXPECT_EQ(3u, config.impl().getExporterVersion().patch); EXPECT_EQ(4u, config.impl().getExporterVersion().fileFormat); - EXPECT_FALSE(config.impl().getValidationEnabled()); EXPECT_EQ(ELuaSavingMode::SourceAndByteCode, config.impl().getLuaSavingMode()); - EXPECT_EQ("'metadata' exporter:1.2.3.4 validate:false compress:true lua:2", fmt::to_string(config.impl())); + EXPECT_EQ("'metadata' exporter:1.2.3.4 compress:true lua:2", fmt::to_string(config.impl())); } }; @@ -49,9 +47,8 @@ namespace ramses::internal EXPECT_EQ(0u, config.impl().getExporterVersion().minor); EXPECT_EQ(0u, config.impl().getExporterVersion().patch); EXPECT_EQ(0u, config.impl().getExporterVersion().fileFormat); - EXPECT_TRUE(config.impl().getValidationEnabled()); EXPECT_EQ(ELuaSavingMode::SourceAndByteCode, config.impl().getLuaSavingMode()); - EXPECT_EQ("'' exporter:0.0.0.0 validate:true compress:false lua:2", fmt::to_string(config.impl())); + EXPECT_EQ("'' exporter:0.0.0.0 compress:false lua:2", fmt::to_string(config.impl())); } TEST_F(ASaveFileConfig, IsCopied) diff --git a/tests/unittests/client/logic/api/TimerNodeTest.cpp b/tests/unittests/client/logic/api/TimerNodeTest.cpp index 4a3a47499..d8a873110 100644 --- a/tests/unittests/client/logic/api/TimerNodeTest.cpp +++ b/tests/unittests/client/logic/api/TimerNodeTest.cpp @@ -56,7 +56,7 @@ namespace ramses::internal auto& otherEngine = *m_scene->createLogicEngine(); EXPECT_FALSE(otherEngine.destroy(*timerNode)); - EXPECT_EQ("Failed to destroy object 'timerNode [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance.", getLastErrorMessage()); + EXPECT_EQ("Failed to destroy object 'timerNode [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance.", getLastErrorMessage()); } TEST_F(ATimerNode, ChangesName) @@ -186,7 +186,7 @@ namespace ramses::internal { auto& otherEngine = *m_logicEngine; otherEngine.createTimerNode("timerNode"); - ASSERT_TRUE(saveToFileWithoutValidation("logic_timerNode.bin")); + ASSERT_TRUE(saveToFile("logic_timerNode.bin")); } ASSERT_TRUE(recreateFromFile("logic_timerNode.bin")); diff --git a/tests/unittests/client/logic/internal/ApiObjectsTest.cpp b/tests/unittests/client/logic/internal/ApiObjectsTest.cpp index a7786ad12..8269e5234 100644 --- a/tests/unittests/client/logic/internal/ApiObjectsTest.cpp +++ b/tests/unittests/client/logic/internal/ApiObjectsTest.cpp @@ -30,6 +30,7 @@ #include "impl/logic/AnimationNodeImpl.h" #include "impl/logic/SkinBindingImpl.h" #include "impl/logic/TimerNodeImpl.h" +#include "impl/logic/RenderBufferBindingImpl.h" #include "ramses/client/logic/LogicEngine.h" #include "ramses/client/logic/LuaScript.h" @@ -48,10 +49,12 @@ #include "ramses/client/logic/TimerNode.h" #include "ramses/client/logic/AnchorPoint.h" #include "ramses/client/logic/SkinBinding.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/Scene.h" #include "ramses/client/PerspectiveCamera.h" #include "ramses/client/Appearance.h" #include "ramses/client/RenderPass.h" +#include "ramses/client/RenderBuffer.h" #include "RamsesTestUtils.h" #include "LogTestUtils.h" #include "SerializationTestUtils.h" @@ -83,6 +86,7 @@ namespace ramses::internal ramses::RenderPass* m_renderPass = { m_scene->createRenderPass() }; ramses::RenderGroup* m_renderGroup = { m_scene->createRenderGroup() }; ramses::MeshNode* m_meshNode = { m_scene->createMeshNode("meshNode") }; + ramses::RenderBuffer* m_renderBuffer = { m_scene->createRenderBuffer(1u, 2u, ERenderBufferFormat::R16F, ERenderBufferAccessMode::ReadWrite, 3u, "renderBuffer") }; const std::string_view m_moduleSrc = R"( local mymath = {} @@ -205,7 +209,7 @@ namespace ramses::internal EXPECT_EQ(script, otherInstance.getApiObjectContainer().back()); ASSERT_FALSE(m_apiObjects.destroy(*script, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'script [LogicObject ScnObjId=8]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'script [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, script); // Did not affect existence in otherInstance! @@ -237,7 +241,7 @@ namespace ramses::internal EXPECT_EQ(intf, otherInstance.getApiObjectContainer().back()); ASSERT_FALSE(m_apiObjects.destroy(*intf, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'intf [LogicObject ScnObjId=8]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'intf [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, intf); // Did not affect existence in otherInstance! @@ -287,7 +291,7 @@ namespace ramses::internal EXPECT_EQ(nodeBinding, otherInstance.getApiObjectContainer().back()); ASSERT_FALSE(m_apiObjects.destroy(*nodeBinding, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'NodeBinding [LogicObject ScnObjId=8]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'NodeBinding [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, nodeBinding); // Did not affect existence in otherInstance! @@ -323,7 +327,7 @@ namespace ramses::internal EXPECT_EQ(cameraBinding, otherInstance.getApiObjectContainer().back()); ASSERT_FALSE(m_apiObjects.destroy(*cameraBinding, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'CameraBinding [LogicObject ScnObjId=8]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'CameraBinding [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, cameraBinding); // Did not affect existence in otherInstance! @@ -359,7 +363,7 @@ namespace ramses::internal EXPECT_EQ(binding, otherInstance.getApiObjectContainer().back()); ASSERT_FALSE(m_apiObjects.destroy(*binding, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'RenderPassBinding [LogicObject ScnObjId=8]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'RenderPassBinding [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, binding); // Did not affect existence in otherInstance! @@ -397,7 +401,7 @@ namespace ramses::internal EXPECT_EQ(binding, otherInstance.getApiObjectContainer().back()); ASSERT_FALSE(m_apiObjects.destroy(*binding, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'RenderGroupBinding [LogicObject ScnObjId=8]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'RenderGroupBinding [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, binding); // Did not affect existence in otherInstance! @@ -433,7 +437,7 @@ namespace ramses::internal EXPECT_EQ(binding, otherInstance.getApiObjectContainer().back()); EXPECT_FALSE(m_apiObjects.destroy(*binding, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'mb [LogicObject ScnObjId=8]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'mb [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, binding); // Did not affect existence in otherInstance! @@ -468,7 +472,7 @@ namespace ramses::internal EXPECT_EQ(binding, otherInstance.getApiObjectContainer().back()); ASSERT_FALSE(m_apiObjects.destroy(*binding, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'AppearanceBinding [LogicObject ScnObjId=8]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'AppearanceBinding [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, binding); // Did not affect existence in otherInstance! @@ -555,7 +559,7 @@ namespace ramses::internal EXPECT_EQ(dataArray, otherInstance.getApiObjectContainer().back()); EXPECT_FALSE(m_apiObjects.destroy(*dataArray, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'data [LogicObject ScnObjId=8]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'data [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, dataArray); // Did not affect existence in otherInstance! @@ -608,7 +612,7 @@ namespace ramses::internal EXPECT_EQ(animNode, otherInstance.getApiObjectContainer().back()); EXPECT_FALSE(m_apiObjects.destroy(*animNode, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'animNode [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'animNode [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, animNode); // Did not affect existence in otherInstance! @@ -643,7 +647,7 @@ namespace ramses::internal auto timerNode = otherInstance.createTimerNode("timerNode"); EXPECT_FALSE(m_apiObjects.destroy(*timerNode, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'timerNode [LogicObject ScnObjId=8]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'timerNode [LogicObject ScnObjId=9]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, timerNode); // Did not affect existence in otherInstance! @@ -685,7 +689,7 @@ namespace ramses::internal EXPECT_EQ(anchor, otherInstance.getApiObjectContainer().back()); ASSERT_FALSE(m_apiObjects.destroy(*anchor, m_errorReporting)); ASSERT_TRUE(m_errorReporting.getError().has_value()); - EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'anchor [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(m_errorReporting.getError()->message, "Failed to destroy object 'anchor [LogicObject ScnObjId=11]', cannot find it in this LogicEngine instance."); EXPECT_EQ(m_errorReporting.getError()->object, anchor); // Did not affect existence in otherInstance! @@ -750,7 +754,7 @@ namespace ramses::internal ErrorReporting errorReporting; EXPECT_FALSE(otherInstance.destroy(*skin, errorReporting)); ASSERT_TRUE(errorReporting.getError().has_value()); - EXPECT_EQ(errorReporting.getError()->message, "Failed to destroy object 'skin [LogicObject ScnObjId=10]', cannot find it in this LogicEngine instance."); + EXPECT_EQ(errorReporting.getError()->message, "Failed to destroy object 'skin [LogicObject ScnObjId=11]', cannot find it in this LogicEngine instance."); EXPECT_EQ(errorReporting.getError()->object, skin); } @@ -803,6 +807,7 @@ namespace ramses::internal EXPECT_TRUE(m_apiObjects.getApiObjectContainer().empty()); EXPECT_TRUE(m_apiObjects.getApiObjectContainer().empty()); EXPECT_TRUE(m_apiObjects.getApiObjectContainer().empty()); + EXPECT_TRUE(m_apiObjects.getApiObjectContainer().empty()); EXPECT_TRUE(m_apiObjects.getApiObjectContainer().empty()); EXPECT_TRUE(m_apiObjects.getApiObjectOwningContainer().empty()); @@ -819,6 +824,7 @@ namespace ramses::internal EXPECT_TRUE(apiObjectsConst.getApiObjectContainer().empty()); EXPECT_TRUE(apiObjectsConst.getApiObjectContainer().empty()); EXPECT_TRUE(apiObjectsConst.getApiObjectContainer().empty()); + EXPECT_TRUE(apiObjectsConst.getApiObjectContainer().empty()); EXPECT_TRUE(apiObjectsConst.getApiObjectContainer().empty()); EXPECT_TRUE(apiObjectsConst.getApiObjectOwningContainer().empty()); } @@ -880,6 +886,13 @@ namespace ramses::internal EXPECT_THAT(renderGroups, ::testing::ElementsAre(binding)); } + TEST_P(AnApiObjects, ProvidesNonEmptyRenderBufferBindingsCollection_WhenRenderBufferBindingsWereCreated) + { + const auto* binding = m_apiObjects.createRenderBufferBinding(*m_renderBuffer, "rb"); + ApiObjectContainer& bindings = m_apiObjects.getApiObjectContainer(); + EXPECT_THAT(bindings, ::testing::ElementsAre(binding)); + } + TEST_P(AnApiObjects, ProvidesNonEmptyAnchorPointsCollection_WhenAnchorPointsWereCreated) { AnchorPoint* anchor = createAnchorPoint(); @@ -986,40 +999,43 @@ namespace ramses::internal const RenderGroupBinding* renderGroupBinding = createRenderGroupBinding(); const SkinBinding* skinBinding = createSkinBinding(m_apiObjects); const MeshNodeBinding* meshBinding = m_apiObjects.createMeshNodeBinding(*m_meshNode, "mb"); - - EXPECT_EQ(getApiObjectById(8u), luaModule); - EXPECT_EQ(getApiObjectById(9u), luaScript); - EXPECT_EQ(getApiObjectById(10u), nodeBinding); - EXPECT_EQ(getApiObjectById(11u), appearanceBinding); - EXPECT_EQ(getApiObjectById(12u), cameraBinding); - EXPECT_EQ(getApiObjectById(13u), dataArray); - EXPECT_EQ(getApiObjectById(14u), animationNode); - EXPECT_EQ(getApiObjectById(15u), timerNode); - EXPECT_EQ(getApiObjectById(16u), luaInterface); - EXPECT_EQ(getApiObjectById(17u), renderPassBinding); - EXPECT_EQ(getApiObjectById(20u), anchor); - EXPECT_EQ(getApiObjectById(21u), renderGroupBinding); - EXPECT_EQ(getApiObjectById(24u), skinBinding); - EXPECT_EQ(getApiObjectById(25u), meshBinding); + const auto* rbBinding = m_apiObjects.createRenderBufferBinding(*m_renderBuffer, "rb"); + + EXPECT_EQ(getApiObjectById(9u), luaModule); + EXPECT_EQ(getApiObjectById(10u), luaScript); + EXPECT_EQ(getApiObjectById(11u), nodeBinding); + EXPECT_EQ(getApiObjectById(12u), appearanceBinding); + EXPECT_EQ(getApiObjectById(13u), cameraBinding); + EXPECT_EQ(getApiObjectById(14u), dataArray); + EXPECT_EQ(getApiObjectById(15u), animationNode); + EXPECT_EQ(getApiObjectById(16u), timerNode); + EXPECT_EQ(getApiObjectById(17u), luaInterface); + EXPECT_EQ(getApiObjectById(18u), renderPassBinding); + EXPECT_EQ(getApiObjectById(21u), anchor); + EXPECT_EQ(getApiObjectById(22u), renderGroupBinding); + EXPECT_EQ(getApiObjectById(25u), skinBinding); + EXPECT_EQ(getApiObjectById(26u), meshBinding); + EXPECT_EQ(getApiObjectById(27u), rbBinding); EXPECT_TRUE(m_apiObjects.destroy(*luaScript, m_errorReporting)); EXPECT_TRUE(m_apiObjects.destroy(*appearanceBinding, m_errorReporting)); EXPECT_TRUE(m_apiObjects.destroy(*animationNode, m_errorReporting)); - EXPECT_EQ(getApiObjectById(8u), luaModule); - EXPECT_EQ(getApiObjectById(9u), nullptr); - EXPECT_EQ(getApiObjectById(10u), nodeBinding); - EXPECT_EQ(getApiObjectById(11u), nullptr); - EXPECT_EQ(getApiObjectById(12u), cameraBinding); - EXPECT_EQ(getApiObjectById(13u), dataArray); - EXPECT_EQ(getApiObjectById(14u), nullptr); - EXPECT_EQ(getApiObjectById(15u), timerNode); - EXPECT_EQ(getApiObjectById(16u), luaInterface); - EXPECT_EQ(getApiObjectById(17u), renderPassBinding); - EXPECT_EQ(getApiObjectById(20u), anchor); - EXPECT_EQ(getApiObjectById(21u), renderGroupBinding); - EXPECT_EQ(getApiObjectById(24u), skinBinding); - EXPECT_EQ(getApiObjectById(25u), meshBinding); + EXPECT_EQ(getApiObjectById(9u), luaModule); + EXPECT_EQ(getApiObjectById(10u), nullptr); + EXPECT_EQ(getApiObjectById(11u), nodeBinding); + EXPECT_EQ(getApiObjectById(12u), nullptr); + EXPECT_EQ(getApiObjectById(13u), cameraBinding); + EXPECT_EQ(getApiObjectById(14u), dataArray); + EXPECT_EQ(getApiObjectById(15u), nullptr); + EXPECT_EQ(getApiObjectById(16u), timerNode); + EXPECT_EQ(getApiObjectById(17u), luaInterface); + EXPECT_EQ(getApiObjectById(18u), renderPassBinding); + EXPECT_EQ(getApiObjectById(21u), anchor); + EXPECT_EQ(getApiObjectById(22u), renderGroupBinding); + EXPECT_EQ(getApiObjectById(25u), skinBinding); + EXPECT_EQ(getApiObjectById(26u), meshBinding); + EXPECT_EQ(getApiObjectById(27u), rbBinding); } TEST_P(AnApiObjects, logicObjectsGenerateIdentificationStringWithUserId) @@ -1040,6 +1056,7 @@ namespace ramses::internal RenderGroupBinding* renderGroupBinding = createRenderGroupBinding(); SkinBinding* skin = createSkinBinding(m_apiObjects); MeshNodeBinding* meshBinding = m_apiObjects.createMeshNodeBinding(*m_meshNode, "mb"); + auto* rbBinding = m_apiObjects.createRenderBufferBinding(*m_renderBuffer, "rb"); EXPECT_TRUE(luaModule->setUserId(1u, 2u)); EXPECT_TRUE(luaScript->setUserId(3u, 4u)); @@ -1055,21 +1072,23 @@ namespace ramses::internal EXPECT_TRUE(renderGroupBinding->setUserId(23u, 24u)); EXPECT_TRUE(skin->setUserId(25u, 26u)); EXPECT_TRUE(meshBinding->setUserId(27u, 28u)); - - EXPECT_EQ(luaModule->impl().getIdentificationString(), "module [LogicObject UserId=00000000000000010000000000000002 ScnObjId=8]"); - EXPECT_EQ(luaScript->impl().getIdentificationString(), "script [LogicObject UserId=00000000000000030000000000000004 ScnObjId=9]"); - EXPECT_EQ(nodeBinding->impl().getIdentificationString(), "nodeBinding [LogicObject UserId=00000000000000050000000000000006 ScnObjId=10]"); - EXPECT_EQ(appearanceBinding->impl().getIdentificationString(), "appearanceBinding [LogicObject UserId=00000000000000070000000000000008 ScnObjId=11]"); - EXPECT_EQ(cameraBinding->impl().getIdentificationString(), "cameraBinding [LogicObject UserId=0000000000000009000000000000000A ScnObjId=12]"); - EXPECT_EQ(renderPassBinding->impl().getIdentificationString(), "renderPassBinding [LogicObject UserId=000000000000000B000000000000000C ScnObjId=13]"); - EXPECT_EQ(dataArray->impl().getIdentificationString(), "dataArray [LogicObject UserId=000000000000000D000000000000000E ScnObjId=14]"); - EXPECT_EQ(animationNode->impl().getIdentificationString(), "animNode [LogicObject UserId=000000000000000F0000000000000010 ScnObjId=15]"); - EXPECT_EQ(timerNode->impl().getIdentificationString(), "timerNode [LogicObject UserId=00000000000000110000000000000012 ScnObjId=16]"); - EXPECT_EQ(luaInterface->impl().getIdentificationString(), "intf [LogicObject UserId=00000000000000130000000000000014 ScnObjId=17]"); - EXPECT_EQ(anchor->impl().getIdentificationString(), "anchor [LogicObject UserId=00000000000000150000000000000016 ScnObjId=20]"); - EXPECT_EQ(renderGroupBinding->impl().getIdentificationString(), "renderGroupBinding [LogicObject UserId=00000000000000170000000000000018 ScnObjId=21]"); - EXPECT_EQ(skin->impl().getIdentificationString(), "skin [LogicObject UserId=0000000000000019000000000000001A ScnObjId=24]"); - EXPECT_EQ(meshBinding->impl().getIdentificationString(), "mb [LogicObject UserId=000000000000001B000000000000001C ScnObjId=25]"); + EXPECT_TRUE(rbBinding->setUserId(29u, 30u)); + + EXPECT_EQ(luaModule->impl().getIdentificationString(), "module [LogicObject UserId=00000000000000010000000000000002 ScnObjId=9]"); + EXPECT_EQ(luaScript->impl().getIdentificationString(), "script [LogicObject UserId=00000000000000030000000000000004 ScnObjId=10]"); + EXPECT_EQ(nodeBinding->impl().getIdentificationString(), "nodeBinding [LogicObject UserId=00000000000000050000000000000006 ScnObjId=11]"); + EXPECT_EQ(appearanceBinding->impl().getIdentificationString(), "appearanceBinding [LogicObject UserId=00000000000000070000000000000008 ScnObjId=12]"); + EXPECT_EQ(cameraBinding->impl().getIdentificationString(), "cameraBinding [LogicObject UserId=0000000000000009000000000000000A ScnObjId=13]"); + EXPECT_EQ(renderPassBinding->impl().getIdentificationString(), "renderPassBinding [LogicObject UserId=000000000000000B000000000000000C ScnObjId=14]"); + EXPECT_EQ(dataArray->impl().getIdentificationString(), "dataArray [LogicObject UserId=000000000000000D000000000000000E ScnObjId=15]"); + EXPECT_EQ(animationNode->impl().getIdentificationString(), "animNode [LogicObject UserId=000000000000000F0000000000000010 ScnObjId=16]"); + EXPECT_EQ(timerNode->impl().getIdentificationString(), "timerNode [LogicObject UserId=00000000000000110000000000000012 ScnObjId=17]"); + EXPECT_EQ(luaInterface->impl().getIdentificationString(), "intf [LogicObject UserId=00000000000000130000000000000014 ScnObjId=18]"); + EXPECT_EQ(anchor->impl().getIdentificationString(), "anchor [LogicObject UserId=00000000000000150000000000000016 ScnObjId=21]"); + EXPECT_EQ(renderGroupBinding->impl().getIdentificationString(), "renderGroupBinding [LogicObject UserId=00000000000000170000000000000018 ScnObjId=22]"); + EXPECT_EQ(skin->impl().getIdentificationString(), "skin [LogicObject UserId=0000000000000019000000000000001A ScnObjId=25]"); + EXPECT_EQ(meshBinding->impl().getIdentificationString(), "mb [LogicObject UserId=000000000000001B000000000000001C ScnObjId=26]"); + EXPECT_EQ(rbBinding->impl().getIdentificationString(), "rb [LogicObject UserId=000000000000001D000000000000001E ScnObjId=27]"); } TEST_P(AnApiObjects, ValidatesThatAllLuaInterfaceOutputsAreLinked_GeneratesWarningsIfOutputsNotLinked) @@ -1171,7 +1190,7 @@ namespace ramses::internal } } - TEST_P(AnApiObjects, ValidatesDanglingNodes_ProducesWarningIfNodeHasNoIngoingOrOutgoingLinks) + TEST_P(AnApiObjects, ValidatesDanglingNodes_ProducesWarningIfNodeHasNoIncomingOrOutgoingLinks) { auto* script = m_apiObjects.createLuaScript(R"( function interface(IN, OUT) @@ -1187,7 +1206,7 @@ namespace ramses::internal m_apiObjects.validateDanglingNodes(validationResults); EXPECT_EQ(2u, validationResults.getIssues().size()); EXPECT_THAT(validationResults.getIssues()[0].message, ::testing::HasSubstr("Node [script name] has no outgoing links")); - EXPECT_THAT(validationResults.getIssues()[1].message, ::testing::HasSubstr("Node [script name] has no ingoing links")); + EXPECT_THAT(validationResults.getIssues()[1].message, ::testing::HasSubstr("Node [script name] has no incoming links")); EXPECT_THAT(validationResults.getIssues(), ::testing::Each(::testing::Field(&Issue::type, ::testing::Eq(EIssueType::Warning)))); } @@ -1308,7 +1327,7 @@ namespace ramses::internal ASSERT_EQ(1u, serialized.luaScripts()->size()); const rlogic_serialization::LuaScript& serializedScript = *serialized.luaScripts()->Get(0); EXPECT_EQ("script", serializedScript.base()->name()->str()); - EXPECT_EQ(8u, serializedScript.base()->id()); + EXPECT_EQ(9u, serializedScript.base()->id()); EXPECT_EQ(m_valid_empty_script, serializedScript.luaSourceCode()->str()); EXPECT_TRUE(serializedScript.luaByteCode()->size() > 0); @@ -1332,7 +1351,7 @@ namespace ramses::internal ASSERT_EQ(1u, serialized.luaInterfaces()->size()); const rlogic_serialization::LuaInterface& serializedInterface = *serialized.luaInterfaces()->Get(0); EXPECT_EQ("intf", serializedInterface.base()->name()->str()); - EXPECT_EQ(8u, serializedInterface.base()->id()); + EXPECT_EQ(9u, serializedInterface.base()->id()); std::unique_ptr deserialized = ApiObjects::Deserialize(m_scene->impl(), serialized, m_resolverMock, "test", m_errorReporting, GetParam()); EXPECT_TRUE(deserialized); @@ -1357,25 +1376,25 @@ namespace ramses::internal ASSERT_EQ(1u, serialized.nodeBindings()->size()); const rlogic_serialization::NodeBinding& serializedNodeBinding = *serialized.nodeBindings()->Get(0); EXPECT_EQ("node", serializedNodeBinding.base()->base()->name()->str()); - EXPECT_EQ(8u, serializedNodeBinding.base()->base()->id()); + EXPECT_EQ(9u, serializedNodeBinding.base()->base()->id()); ASSERT_NE(nullptr, serialized.appearanceBindings()); ASSERT_EQ(1u, serialized.appearanceBindings()->size()); const rlogic_serialization::AppearanceBinding& serializedAppBinding = *serialized.appearanceBindings()->Get(0); EXPECT_EQ("appearance", serializedAppBinding.base()->base()->name()->str()); - EXPECT_EQ(9u, serializedAppBinding.base()->base()->id()); + EXPECT_EQ(10u, serializedAppBinding.base()->base()->id()); ASSERT_NE(nullptr, serialized.cameraBindings()); ASSERT_EQ(1u, serialized.cameraBindings()->size()); const rlogic_serialization::CameraBinding& serializedCameraBinding = *serialized.cameraBindings()->Get(0); EXPECT_EQ("camera", serializedCameraBinding.base()->base()->name()->str()); - EXPECT_EQ(10u, serializedCameraBinding.base()->base()->id()); + EXPECT_EQ(11u, serializedCameraBinding.base()->base()->id()); ASSERT_NE(nullptr, serialized.renderPassBindings()); ASSERT_EQ(1u, serialized.renderPassBindings()->size()); const rlogic_serialization::RenderPassBinding& serializedRenderPassBinding = *serialized.renderPassBindings()->Get(0); EXPECT_EQ("rp", serializedRenderPassBinding.base()->base()->name()->str()); - EXPECT_EQ(11u, serializedRenderPassBinding.base()->base()->id()); + EXPECT_EQ(12u, serializedRenderPassBinding.base()->base()->id()); } TEST_P(AnApiObjects_Serialization, CreatesFlatbufferContainers_ForLinks) @@ -1439,6 +1458,7 @@ namespace ramses::internal toSerialize.createRenderGroupBinding(*m_renderGroup, elements, "rg"); createSkinBinding(*nodeBinding, *appearanceBinding, toSerialize); toSerialize.createMeshNodeBinding(*m_meshNode, "mb"); + toSerialize.createRenderBufferBinding(*m_renderBuffer, "rb"); ApiObjects::Serialize(toSerialize, builder, ELuaSavingMode::ByteCodeOnly); } @@ -1452,13 +1472,14 @@ namespace ramses::internal EXPECT_CALL(m_resolverMock, findRamsesRenderGroupInScene(::testing::Eq("rg"), m_renderGroup->getSceneObjectId())).WillOnce(::testing::Return(m_renderGroup)); EXPECT_CALL(m_resolverMock, findRamsesSceneObjectInScene(::testing::Eq("rg"), m_meshNode->getSceneObjectId())).WillOnce(::testing::Return(m_meshNode)); EXPECT_CALL(m_resolverMock, findRamsesSceneObjectInScene(::testing::Eq("mb"), m_meshNode->getSceneObjectId())).WillOnce(::testing::Return(m_meshNode)); + EXPECT_CALL(m_resolverMock, findRamsesSceneObjectInScene(::testing::Eq("rb"), m_renderBuffer->getSceneObjectId())).WillOnce(::testing::Return(m_renderBuffer)); std::unique_ptr apiObjectsOptional = ApiObjects::Deserialize(m_scene->impl(), serialized, m_resolverMock, "", m_errorReporting, GetParam()); ASSERT_TRUE(apiObjectsOptional); ApiObjects& apiObjects = *apiObjectsOptional; - ASSERT_EQ(9u, apiObjects.getApiObjectOwningContainer().size()); + ASSERT_EQ(10u, apiObjects.getApiObjectOwningContainer().size()); LuaScript* script = apiObjects.getApiObjectContainer()[0]; EXPECT_EQ(script->getName(), "script"); @@ -1495,6 +1516,10 @@ namespace ramses::internal const auto* meshBinding = apiObjects.getApiObjectContainer()[0]; EXPECT_EQ(meshBinding->getName(), "mb"); EXPECT_EQ(meshBinding, &meshBinding->impl().getLogicObject()); + + const auto* rbBinding = apiObjects.getApiObjectContainer()[0]; + EXPECT_EQ(rbBinding->getName(), "rb"); + EXPECT_EQ(rbBinding, &rbBinding->impl().getLogicObject()); } TEST_P(AnApiObjects_Serialization, ObjectsCreatedAfterLoadingReceiveUniqueId) @@ -1598,8 +1623,9 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) - ); + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) + ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1630,7 +1656,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1662,7 +1689,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1694,7 +1722,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1726,7 +1755,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1758,7 +1788,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1790,7 +1821,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1822,7 +1854,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1854,7 +1887,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1886,7 +1920,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1918,7 +1953,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -1950,7 +1986,8 @@ namespace ramses::internal 0u, // no anchor points container m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -2014,7 +2051,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), 0u, // no skin bindings container - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -2046,7 +2084,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - 0u // no mesh node bindings container + 0u, // no mesh node bindings container + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -2059,6 +2098,39 @@ namespace ramses::internal EXPECT_EQ(m_errorReporting.getError()->message, "Fatal error during loading from serialized data: missing meshnode bindings container!"); } + TEST_P(AnApiObjects_Serialization, ErrorWhenRenderBufferBindingContainerMissing) + { + { + auto apiObjects = rlogic_serialization::CreateApiObjects( + m_flatBufferBuilder, + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}), + 0u // no render buffer bindings container + ); + m_flatBufferBuilder.Finish(apiObjects); + } + + const auto& serialized = *flatbuffers::GetRoot(m_flatBufferBuilder.GetBufferPointer()); + std::unique_ptr deserialized = ApiObjects::Deserialize(m_scene->impl(), serialized, m_resolverMock, "unit test", m_errorReporting, GetParam()); + + EXPECT_FALSE(deserialized); + ASSERT_TRUE(m_errorReporting.getError().has_value()); + EXPECT_EQ(m_errorReporting.getError()->message, "Fatal error during loading from serialized data: missing render buffer bindings container!"); + } + TEST_P(AnApiObjects_Serialization, ReportsErrorWhenScriptCouldNotBeDeserialized) { { @@ -2078,7 +2150,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -2110,7 +2183,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -2142,7 +2216,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -2174,7 +2249,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -2206,7 +2282,8 @@ namespace ramses::internal m_flatBufferBuilder.CreateVector(std::vector>{}), m_flatBufferBuilder.CreateVector(std::vector>{ m_testUtils.serializeTestRenderGroupBindingWithError() }), m_flatBufferBuilder.CreateVector(std::vector>{}), - m_flatBufferBuilder.CreateVector(std::vector>{}) + m_flatBufferBuilder.CreateVector(std::vector>{}), + m_flatBufferBuilder.CreateVector(std::vector>{}) ); m_flatBufferBuilder.Finish(apiObjects); } @@ -2243,6 +2320,7 @@ namespace ramses::internal toSerialize.createRenderGroupBinding(*m_renderGroup, elements, "rg"); createSkinBinding(*node, *appearance, toSerialize); toSerialize.createMeshNodeBinding(*m_meshNode, "mb"); + toSerialize.createRenderBufferBinding(*m_renderBuffer, "rb"); ApiObjects::Serialize(toSerialize, builder, ELuaSavingMode::ByteCodeOnly); } @@ -2256,6 +2334,7 @@ namespace ramses::internal EXPECT_CALL(m_resolverMock, findRamsesRenderGroupInScene(::testing::Eq("rg"), m_renderGroup->getSceneObjectId())).WillOnce(::testing::Return(m_renderGroup)); EXPECT_CALL(m_resolverMock, findRamsesSceneObjectInScene(::testing::Eq("rg"), m_meshNode->getSceneObjectId())).WillOnce(::testing::Return(m_meshNode)); EXPECT_CALL(m_resolverMock, findRamsesSceneObjectInScene(::testing::Eq("mb"), m_meshNode->getSceneObjectId())).WillOnce(::testing::Return(m_meshNode)); + EXPECT_CALL(m_resolverMock, findRamsesSceneObjectInScene(::testing::Eq("rb"), m_renderBuffer->getSceneObjectId())).WillOnce(::testing::Return(m_renderBuffer)); std::unique_ptr deserialized = ApiObjects::Deserialize(m_scene->impl(), serialized, m_resolverMock, "", m_errorReporting, GetParam()); ASSERT_TRUE(deserialized); @@ -2280,7 +2359,8 @@ namespace ramses::internal apiObjects.getApiObjectContainer()[0], apiObjects.getApiObjectContainer()[0], apiObjects.getApiObjectContainer()[0], - apiObjects.getApiObjectContainer()[0] + apiObjects.getApiObjectContainer()[0], + apiObjects.getApiObjectContainer()[0] }; ASSERT_EQ(expected.size(), logicObjects.size()); diff --git a/tests/unittests/client/logic/shared/LogicEngineTestWithCreationHelper.h b/tests/unittests/client/logic/shared/LogicEngineTestWithCreationHelper.h index 1c154b35e..dbf432d6d 100644 --- a/tests/unittests/client/logic/shared/LogicEngineTestWithCreationHelper.h +++ b/tests/unittests/client/logic/shared/LogicEngineTestWithCreationHelper.h @@ -26,6 +26,7 @@ #include "ramses/client/logic/AnimationNodeConfig.h" #include "ramses/client/logic/TimerNode.h" #include "ramses/client/logic/AnchorPoint.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/PerspectiveCamera.h" #include "ramses/client/RenderGroup.h" #include "ramses/client/RenderPass.h" @@ -52,7 +53,8 @@ namespace ramses::internal DataArray, AnimationNode, TimerNode, - AnchorPoint + AnchorPoint, + RenderBufferBinding >; class ALogicEngineBaseWithCreationHelper : public ALogicEngineBase @@ -132,4 +134,8 @@ namespace ramses::internal const auto camBinding = this->m_logicEngine->createCameraBinding(*this->m_camera, "camForAnchor"); return this->m_logicEngine->createAnchorPoint(*nodeBinding, *camBinding, name); } + template <> inline RenderBufferBinding* ALogicEngineBaseWithCreationHelper::createObjectOfType(std::string_view name) + { + return this->m_logicEngine->createRenderBufferBinding(*m_renderBuffer, name); + } } diff --git a/tests/unittests/client/logic/shared/LogicEngineTest_Base.h b/tests/unittests/client/logic/shared/LogicEngineTest_Base.h index 66366e64b..9460d037a 100644 --- a/tests/unittests/client/logic/shared/LogicEngineTest_Base.h +++ b/tests/unittests/client/logic/shared/LogicEngineTest_Base.h @@ -33,6 +33,7 @@ #include "ramses/client/OrthographicCamera.h" #include "ramses/client/Appearance.h" #include "ramses/client/UniformInput.h" +#include "ramses/client/RenderBuffer.h" #include "ramses/client/ramses-utils.h" namespace ramses::internal @@ -46,7 +47,6 @@ namespace ramses::internal // make ramses camera valid, needed for anchor points m_camera->setFrustum(-1.f, 1.f, -1.f, 1.f, 0.1f, 1.f); m_renderGroup->addMeshNode(*m_meshNode); - m_saveFileConfigNoValidation.setValidationEnabled(false); } virtual ~ALogicEngineBase() = default; @@ -82,13 +82,6 @@ namespace ramses::internal return m_scene->saveToFile(filename, config); } - bool saveToFileWithoutValidation(std::string_view filename) - { - SaveFileConfig configNoValidation; - configNoValidation.setValidationEnabled(false); - return m_scene->saveToFile(filename, configNoValidation); - } - virtual bool recreateFromFile(std::string_view filename) { const auto nodeId = m_node->getSceneObjectId(); @@ -97,19 +90,21 @@ namespace ramses::internal const auto renderPassId = m_renderPass->getSceneObjectId(); const auto renderGroupId = m_renderGroup->getSceneObjectId(); const auto meshNodeId = m_meshNode->getSceneObjectId(); + const auto renderBufferId = m_renderBuffer->getSceneObjectId(); const auto logicEngineId = m_logicEngine->getSceneObjectId(); m_ramses.destroyScene(*m_scene); m_scene = m_ramses.getClient().loadSceneFromFile(filename); if (!m_scene) throw std::runtime_error("scene not loaded"); - m_node = m_scene->findObject(nodeId); - m_camera = m_scene->findObject(cameraId); - m_appearance = m_scene->findObject(appearanceId); + m_node = m_scene->findObject(nodeId); + m_camera = m_scene->findObject(cameraId); + m_appearance = m_scene->findObject(appearanceId); m_renderPass = m_scene->findObject(renderPassId); m_renderGroup = m_scene->findObject(renderGroupId); - m_meshNode = m_scene->findObject(meshNodeId); - m_logicEngine = m_scene->findObject(logicEngineId); + m_meshNode = m_scene->findObject(meshNodeId); + m_renderBuffer = m_scene->findObject(renderBufferId); + m_logicEngine = m_scene->findObject(logicEngineId); return m_logicEngine != nullptr; } @@ -154,6 +149,7 @@ namespace ramses::internal ramses::RenderPass* m_renderPass { m_scene->createRenderPass() }; ramses::RenderGroup* m_renderGroup { m_scene->createRenderGroup() }; ramses::MeshNode* m_meshNode { m_scene->createMeshNode("meshNode") }; + ramses::RenderBuffer* m_renderBuffer{ m_scene->createRenderBuffer(1u, 2u, ERenderBufferFormat::R8, ERenderBufferAccessMode::ReadWrite, 3u) }; LogicEngine* m_logicEngine{ m_scene->createLogicEngine("testLogic") }; @@ -193,6 +189,7 @@ namespace ramses::internal m_renderPass = m_scene->createRenderPass(); m_renderGroup = m_scene->createRenderGroup(); m_meshNode = m_scene->createMeshNode(); + m_renderBuffer = m_scene->createRenderBuffer(1u, 2u, ERenderBufferFormat::R8, ERenderBufferAccessMode::ReadWrite, 3u); return m_scene->createLogicEngine(); } diff --git a/tests/unittests/client/logic/shared/RamsesTestUtils.h b/tests/unittests/client/logic/shared/RamsesTestUtils.h index a008a5656..a9d52343c 100644 --- a/tests/unittests/client/logic/shared/RamsesTestUtils.h +++ b/tests/unittests/client/logic/shared/RamsesTestUtils.h @@ -25,6 +25,7 @@ #include "ramses/client/Geometry.h" #include "ramses/client/Effect.h" #include "ramses/client/MeshNode.h" +#include "ramses/client/RenderBuffer.h" #include "ramses/framework/RamsesFramework.h" #include "ramses/framework/DataTypes.h" @@ -88,6 +89,8 @@ namespace ramses::internal renderGroup->addMeshNode(*meshNode); + renderBuffer = scene->createRenderBuffer(1u, 2u, ramses::ERenderBufferFormat::R16F, ramses::ERenderBufferAccessMode::ReadWrite, 3u, "renderBuffer"); + scene->flush(); scene->publish(); } @@ -98,6 +101,7 @@ namespace ramses::internal ramses::RenderGroup* renderGroup; ramses::Appearance* appearance; ramses::MeshNode* meshNode; + ramses::RenderBuffer* renderBuffer; }; diff --git a/tests/unittests/client/res/testScene_01.ramses b/tests/unittests/client/res/testScene_01.ramses index 6f120426240b158445a0091e7990fea3f79fcc60..427038dd378d38a4369401ec8f06a1142755f4aa 100644 GIT binary patch delta 2140 zcmYk7du-EH6vyxF*7i3jtb4Y5^|#Hk!q~Z?O9*3liqJ@i5Pl-6ad zp5CmKy5}6~t>MbJ_R_0%qr`?vE@>&KbfF!z({DzR71uwcp=oV_mJpM>anq!x3A-70 z_^H}aOs$TpJjX)~l^O|hE+-v#m^y>5I~Loy(^Q(}H0dd)pL(6eb^|q;^r3SO{pzew z##24*9EL;Slj2;P1h_Kg$dgFKK=SSef}@kTHc@fPu)6aRVf zw+VNFoTp!SK=_Vu6y)(@ABi{%^2{%Ye+^8|RQ$VOa-z7c$%zVmU_Sa)h~EP8z^%ft zaI^3wko)(i7*m4~JaAkBqaY7_O8hGz5Bv?d5d2wqN9b@WwHWpJ;8L(0YyfMdevxp6 z#9P5-h=;+IY75R5VmT@zU=!F6t^fx?zWH&GI~)O5g2N!Ue-GsLpMZ~opM%`*OOX40 z3qB4`fFbZlC-v!Eyg)lI*F_7bEes4i@&D^n%ApK=C9p143#)>0@v9~}GR=$yp_IzS zQ{YE>8@LI(3Offo2|ETm1Vd64gw2P|gyq7#Fx<7|`#ypGoaQ#32lFUyJ=2XdX8wyQ zFoV-mm#rO6GXpPcC<31% za2j{-73h7?QRo5awa`nT4?|ytHlRnKt8hIIV*)3k4@1{NpW*fJoo3d*> zv@|D+Zq0L*a8EWa1{B{W&V+TUENbw2%xVsy@D1G773u8S*0{5~8^4<(otq*(v_Er} zE~W9zHtnO~Jdduh=D1^8&$Py}CbgbH2Xh)SuoKB*()FBi{fKoiH=uQuHJ&$Y)3dE- zy>Dt=Ns|Rz^(b4%=23NEVB|F3+ejo2829SJz5uAvFd*u7;&VI|gW z*R(Zckl*g6!Sz4UxsZ!?hnC_0p+OfzwK|Xf4vpyoI=*2y{+E}9i^_Og_=58D;DdO0 qL*Ob!uWj(?YFZi&*qhpL{#0W3P+!=v?P;UIaJg+=hjl7^Dg8gK`&sq? delta 2011 zcmZ9MeN5G56vv-)xi3Fn^j_f#2*|A~bdh(9K;lI(1U9dW(j_QdOwqEjVWTyh=B2V> z&Mj`IRcX)7m?EAENf zO`G>BrL3``L%BLw=_+JrjDwqKNtFcy_dGH8cyO%$57?psvx>;dE{f%9TQMimGJe74 zwnv7!*XCJ}r)<6jd2um%(^j+)b=uPxq|fe2iYADSDsHe>ERA{u70*qrZhq4qO?b-g zN0o~_MMNt?X9*jv!APJJ0ez$=z!l&p!cT?c!f!x5?*~v{hCAY0&<^bQh@Q{ua;$ zf4BHAf;!L9poq7HAIO9uP~VO*@vn$~L;PtW;e_=@iNZ`_uCNr;1+5ou26dqw;s^Ib z=t^Igz(=62^qlx#39o_4h~F09<%lG{Usxb47j6J`;>U$ML7li;{9X`wgX&!goCS5_ zaj+cxUihop6YhWFC9IRJ-%`oo0<}hxH=4=AzFR2f1K?Rthn&On&hqh|%#vY^iHmuMcIOrZ6)<3A+ zz<--wI*}Tg7fwgIw1_r5N*!Do`OnB$qttXZ<{^fxY8EZ5LAxeum1>@wo4ZtqF5;$k z%*_Soa*%i$8}7rv{vw>wa%==$2b}|b1lk2X<5ub|=ws05q5GkyaM*qna2ncQsnjpn zbX3pJRO*W?81w{+>V%$vu7u9V|LG)jGxTh70T#iTT&2`!c$*pMFgEQ&5(BNY;#W8I z1U8(mR{WE5HF?%@mV2H#0q8;hOipG+=tkC4~=+3h3B zGo8sNEtG4XN$n+C&1Gp_l*0pQ?eu`@NFO0y>NU&@8KV|jWd=QOSm-{}>Ah~DO!K#_ zpoP-7%U4Fp=77&he@QM&nE!C!XDFt3zMWU;@^ z;DMGwKG|ZJTeo!+pAQ&(b^9Nb$l+E$CGqmMGIH~#wlkE<|F#|A$F>>V6L3==e;x2y Y&Ib6;fY&k;;IwwH<;xvrb^EyWKW>vjP5=M^ diff --git a/tests/unittests/framework-test-utils/include/UnsafeTestMemoryHelpers.h b/tests/unittests/framework-test-utils/include/UnsafeTestMemoryHelpers.h index 12050cb65..0187e58c0 100644 --- a/tests/unittests/framework-test-utils/include/UnsafeTestMemoryHelpers.h +++ b/tests/unittests/framework-test-utils/include/UnsafeTestMemoryHelpers.h @@ -52,5 +52,10 @@ namespace ramses::internal // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast) safe to get std::byte* return absl::MakeSpan(reinterpret_cast(dataBlob), blobSize) == theSpan; } + + inline const std::byte* ConvertToBytes(std::initializer_list values) + { + return reinterpret_cast(std::data(values)); + } } } diff --git a/tests/unittests/framework/Core/Utils/test/BinaryFileInputStreamTest.cpp b/tests/unittests/framework/Core/Utils/BinaryFileInputStreamTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/BinaryFileInputStreamTest.cpp rename to tests/unittests/framework/Core/Utils/BinaryFileInputStreamTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/BinaryFileOutputStreamTest.cpp b/tests/unittests/framework/Core/Utils/BinaryFileOutputStreamTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/BinaryFileOutputStreamTest.cpp rename to tests/unittests/framework/Core/Utils/BinaryFileOutputStreamTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/BinaryInputStreamTest.cpp b/tests/unittests/framework/Core/Utils/BinaryInputStreamTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/BinaryInputStreamTest.cpp rename to tests/unittests/framework/Core/Utils/BinaryInputStreamTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/BinaryOffsetFileInputStreamTest.cpp b/tests/unittests/framework/Core/Utils/BinaryOffsetFileInputStreamTest.cpp similarity index 98% rename from tests/unittests/framework/Core/Utils/test/BinaryOffsetFileInputStreamTest.cpp rename to tests/unittests/framework/Core/Utils/BinaryOffsetFileInputStreamTest.cpp index a2a3f395b..b9880cc0b 100644 --- a/tests/unittests/framework/Core/Utils/test/BinaryOffsetFileInputStreamTest.cpp +++ b/tests/unittests/framework/Core/Utils/BinaryOffsetFileInputStreamTest.cpp @@ -41,7 +41,7 @@ namespace ramses::internal ASSERT_NE(-1, fd); } - std::vector readData(BinaryOffsetFileInputStream& is, size_t size) + static std::vector readData(BinaryOffsetFileInputStream& is, size_t size) { std::vector data(size); is.read(data.data(), size); diff --git a/tests/unittests/framework/Core/Utils/test/BinaryOutputStreamTest.cpp b/tests/unittests/framework/Core/Utils/BinaryOutputStreamTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/BinaryOutputStreamTest.cpp rename to tests/unittests/framework/Core/Utils/BinaryOutputStreamTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/EnumTraitsTest.cpp b/tests/unittests/framework/Core/Utils/EnumTraitsTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/EnumTraitsTest.cpp rename to tests/unittests/framework/Core/Utils/EnumTraitsTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/FileTest.cpp b/tests/unittests/framework/Core/Utils/FileTest.cpp similarity index 99% rename from tests/unittests/framework/Core/Utils/test/FileTest.cpp rename to tests/unittests/framework/Core/Utils/FileTest.cpp index 9a80eba8e..bb751d468 100644 --- a/tests/unittests/framework/Core/Utils/test/FileTest.cpp +++ b/tests/unittests/framework/Core/Utils/FileTest.cpp @@ -14,7 +14,7 @@ namespace ramses::internal class AFile : public ::testing::Test { public: - bool touchFile(const char* name) + static bool touchFile(const char* name) { File f(name); if (f.exists()) diff --git a/tests/unittests/framework/Core/Utils/test/ImageTest.cpp b/tests/unittests/framework/Core/Utils/ImageTest.cpp similarity index 99% rename from tests/unittests/framework/Core/Utils/test/ImageTest.cpp rename to tests/unittests/framework/Core/Utils/ImageTest.cpp index 71b4494a8..620c42763 100644 --- a/tests/unittests/framework/Core/Utils/test/ImageTest.cpp +++ b/tests/unittests/framework/Core/Utils/ImageTest.cpp @@ -122,8 +122,8 @@ namespace ramses::internal for (uint8_t i = 0; i < Width * Height; ++i) { // create mosaic difference - const uint8_t value1 = (i % 2) ? 1 : 3; - const uint8_t value2 = (i % 2) ? 3 : 1; + const uint8_t value1 = (i % 2) != 0 ? 1 : 3; + const uint8_t value2 = (i % 2) != 0 ? 3 : 1; data1[4 * i + 0] = value1; data1[4 * i + 1] = value1; diff --git a/tests/unittests/framework/Core/Utils/test/InplaceStringTokenizerTest.cpp b/tests/unittests/framework/Core/Utils/InplaceStringTokenizerTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/InplaceStringTokenizerTest.cpp rename to tests/unittests/framework/Core/Utils/InplaceStringTokenizerTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/LogHelperTest.cpp b/tests/unittests/framework/Core/Utils/LogHelperTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/LogHelperTest.cpp rename to tests/unittests/framework/Core/Utils/LogHelperTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/LogMacrosTest.cpp b/tests/unittests/framework/Core/Utils/LogMacrosTest.cpp similarity index 78% rename from tests/unittests/framework/Core/Utils/test/LogMacrosTest.cpp rename to tests/unittests/framework/Core/Utils/LogMacrosTest.cpp index 7d38403b2..f6018e0e6 100644 --- a/tests/unittests/framework/Core/Utils/test/LogMacrosTest.cpp +++ b/tests/unittests/framework/Core/Utils/LogMacrosTest.cpp @@ -11,11 +11,6 @@ namespace ramses::internal { - TEST(ALogMacro, canUseStringOutputStreamLog) - { - LOG_INFO(CONTEXT_FRAMEWORK, "Foo " << 123 << 456); - } - TEST(ALogMacro, canUseStringOutputStreamLambdaLog) { LOG_INFO_F(CONTEXT_FRAMEWORK, ([&](StringOutputStream& sos) { @@ -30,15 +25,15 @@ namespace ramses::internal TEST(ALogMacro, canUseFmtlibLog) { - LOG_INFO_P(CONTEXT_FRAMEWORK, "Foo {} {}", 123, 456.f); + LOG_INFO(CONTEXT_FRAMEWORK, "Foo {} {}", 123, 456.f); } TEST(ALogMacro, canUseFmtlibLambdaLog) { LOG_INFO_PF(CONTEXT_FRAMEWORK, ([&](fmt::memory_buffer& out) { - fmt::format_to(out, "Foo {} {}", 123, 456.f); + fmt::format_to(std::back_inserter(out), "Foo {} {}", 123, 456.f); })); - LOG_INFO_PF(CONTEXT_FRAMEWORK, ([&](auto& out) { fmt::format_to(out, "Foo {} {}", 123, 456.f); })); + LOG_INFO_PF(CONTEXT_FRAMEWORK, ([&](auto& out) { fmt::format_to(std::back_inserter(out), "Foo {} {}", 123, 456.f); })); } } @@ -46,6 +41,6 @@ namespace ramses { TEST(ALogMacro, canUseContextFromRamsesNamespace) { - LOG_INFO(CONTEXT_FRAMEWORK, "Foo " << 123 << 456); + LOG_INFO(CONTEXT_FRAMEWORK, "Foo {} {}", 123, 456); } } diff --git a/tests/unittests/framework/Core/Utils/test/LoggingUtilsTest.cpp b/tests/unittests/framework/Core/Utils/LoggingUtilsTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/LoggingUtilsTest.cpp rename to tests/unittests/framework/Core/Utils/LoggingUtilsTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/MemoryPoolExplicitTest.cpp b/tests/unittests/framework/Core/Utils/MemoryPoolExplicitTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/MemoryPoolExplicitTest.cpp rename to tests/unittests/framework/Core/Utils/MemoryPoolExplicitTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/MemoryPoolIteratorTest.cpp b/tests/unittests/framework/Core/Utils/MemoryPoolIteratorTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/MemoryPoolIteratorTest.cpp rename to tests/unittests/framework/Core/Utils/MemoryPoolIteratorTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/MemoryPoolTest.cpp b/tests/unittests/framework/Core/Utils/MemoryPoolTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/MemoryPoolTest.cpp rename to tests/unittests/framework/Core/Utils/MemoryPoolTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/PeriodicLoggerHelperTest.cpp b/tests/unittests/framework/Core/Utils/PeriodicLoggerHelperTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/PeriodicLoggerHelperTest.cpp rename to tests/unittests/framework/Core/Utils/PeriodicLoggerHelperTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/RawBinaryOutputStreamTest.cpp b/tests/unittests/framework/Core/Utils/RawBinaryOutputStreamTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/RawBinaryOutputStreamTest.cpp rename to tests/unittests/framework/Core/Utils/RawBinaryOutputStreamTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/StatisticCollectionTest.cpp b/tests/unittests/framework/Core/Utils/StatisticCollectionTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/StatisticCollectionTest.cpp rename to tests/unittests/framework/Core/Utils/StatisticCollectionTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/StringUtilsTest.cpp b/tests/unittests/framework/Core/Utils/StringUtilsTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/StringUtilsTest.cpp rename to tests/unittests/framework/Core/Utils/StringUtilsTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/TextureMathUtilsTest.cpp b/tests/unittests/framework/Core/Utils/TextureMathUtilsTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/TextureMathUtilsTest.cpp rename to tests/unittests/framework/Core/Utils/TextureMathUtilsTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/ThreadBarrierTest.cpp b/tests/unittests/framework/Core/Utils/ThreadBarrierTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/ThreadBarrierTest.cpp rename to tests/unittests/framework/Core/Utils/ThreadBarrierTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/VectorBinaryOutputStreamTest.cpp b/tests/unittests/framework/Core/Utils/VectorBinaryOutputStreamTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/VectorBinaryOutputStreamTest.cpp rename to tests/unittests/framework/Core/Utils/VectorBinaryOutputStreamTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/VoidOutputStreamTest.cpp b/tests/unittests/framework/Core/Utils/VoidOutputStreamTest.cpp similarity index 100% rename from tests/unittests/framework/Core/Utils/test/VoidOutputStreamTest.cpp rename to tests/unittests/framework/Core/Utils/VoidOutputStreamTest.cpp diff --git a/tests/unittests/framework/Core/Utils/test/MessagePoolTest.cpp b/tests/unittests/framework/Core/Utils/test/MessagePoolTest.cpp deleted file mode 100644 index ab8b750db..000000000 --- a/tests/unittests/framework/Core/Utils/test/MessagePoolTest.cpp +++ /dev/null @@ -1,94 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2015 BMW Car IT GmbH -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "gtest/gtest.h" -#include "internal/Core/Utils/MessagePool.h" - -using namespace testing; - -namespace ramses::internal -{ - class MessagePoolTest : public testing::Test - { - protected: - MessagePool<32u, 0u> m_messagePool; - }; - - TEST_F(MessagePoolTest, getSuccessMsg) - { - EXPECT_STREQ(m_messagePool.getSuccessText(), m_messagePool.getMessage(m_messagePool.SuccessMessageID)); - } - - TEST_F(MessagePoolTest, getInvalidMsg) - { - EXPECT_STREQ(m_messagePool.getUnknownText(), m_messagePool.getMessage(m_messagePool.SuccessMessageID + 1u)); - } - - TEST_F(MessagePoolTest, addMessage) - { - const uint32_t id = m_messagePool.addMessage("msg 1"); - EXPECT_STREQ("msg 1", m_messagePool.getMessage(id)); - } - - TEST_F(MessagePoolTest, fillCache) - { - const std::string msgBase("msg "); - for (uint32_t i = 0u; i < m_messagePool.MaxMessageEntries; ++i) - { - std::string msg = msgBase; - msg += ('0' + static_cast(i)); - m_messagePool.addMessage(msg.c_str()); - } - - EXPECT_STREQ(m_messagePool.getSuccessText(), m_messagePool.getMessage(m_messagePool.SuccessMessageID)); - - for (uint32_t i = 0u; i < m_messagePool.MaxMessageEntries; ++i) - { - std::string msg = msgBase; - msg += ('0' + static_cast(i)); - EXPECT_STREQ(msg.c_str(), m_messagePool.getMessage(m_messagePool.SuccessMessageID + 1u + i)); - } - } - - TEST_F(MessagePoolTest, floodCache) - { - const uint32_t maxMessages = m_messagePool.MaxMessageEntries; - for (uint32_t i = 0u; i < maxMessages * 10; ++i) - { - m_messagePool.addMessage("message"); - } - - EXPECT_STREQ(m_messagePool.getSuccessText(), m_messagePool.getMessage(m_messagePool.SuccessMessageID)); - - const uint32_t id = m_messagePool.addMessage("msg X"); - EXPECT_STREQ("msg X", m_messagePool.getMessage(id)); - } - - TEST_F(MessagePoolTest, tooOldEntryGivesUnknownMessage) - { - const uint32_t maxMessages = m_messagePool.MaxMessageEntries; - for (uint32_t i = 0u; i < maxMessages * 3; ++i) - { - m_messagePool.addMessage("message"); - } - - EXPECT_STREQ(m_messagePool.getSuccessText(), m_messagePool.getMessage(m_messagePool.SuccessMessageID)); - EXPECT_STREQ(m_messagePool.getUnknownText(), m_messagePool.getMessage(maxMessages)); - } - - TEST_F(MessagePoolTest, willNotReturnSuccessMessageIdIfFilled) - { - const std::string msg("msg"); - for (uint32_t i = 0u; i < 2 * m_messagePool.MaxMessageEntries; ++i) - { - const auto id = m_messagePool.addMessage(msg.c_str()); - EXPECT_NE(uint32_t(m_messagePool.SuccessMessageID), id); - EXPECT_STREQ(msg.c_str(), m_messagePool.getMessage(id)); - } - } -} diff --git a/tests/unittests/framework/Core/Utils/test/ThreadLocalLogTest.cpp b/tests/unittests/framework/Core/Utils/test/ThreadLocalLogTest.cpp deleted file mode 100644 index 0f2e3af8b..000000000 --- a/tests/unittests/framework/Core/Utils/test/ThreadLocalLogTest.cpp +++ /dev/null @@ -1,72 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2020 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "internal/Core/Utils/ThreadLocalLog.h" -#include "gtest/gtest.h" - -namespace ramses::internal -{ - class AThreadLocalLog : public ::testing::Test - { - public: - AThreadLocalLog() - { - ThreadLocalLog::SetPrefix(123); - } - }; - - TEST_F(AThreadLocalLog, canGetPrefix) - { - EXPECT_EQ(123, ThreadLocalLog::GetPrefix()); - } - - TEST_F(AThreadLocalLog, canChangePrefix) - { - ThreadLocalLog::SetPrefix(456); - EXPECT_EQ(456, ThreadLocalLog::GetPrefix()); - } - - TEST_F(AThreadLocalLog, canUseStringOutputStreamLog) - { - LOG_INFO_R(CONTEXT_FRAMEWORK, "Foo " << 123 << 456); - } - - TEST_F(AThreadLocalLog, canUseStringOutputStreamLambdaLog) - { - LOG_INFO_RF(CONTEXT_FRAMEWORK, ([&](ramses::internal::StringOutputStream& sos) { - sos << "foo"; - sos << 123 << 456; - })); - LOG_INFO_RF(CONTEXT_FRAMEWORK, ([&](auto& sos) { - sos << "foo"; - sos << 123 << 456; - })); - } - - TEST_F(AThreadLocalLog, canUseFmtlibLog) - { - LOG_INFO_RP(CONTEXT_FRAMEWORK, "Foo {} {}", 123, 456.f); - } - - TEST_F(AThreadLocalLog, canUseFmtlibLambdaLog) - { - LOG_INFO_RPF(CONTEXT_FRAMEWORK, ([&](fmt::memory_buffer& out) { - fmt::format_to(out, "Foo {} {}", 123, 456.f); - })); - LOG_INFO_RPF(CONTEXT_FRAMEWORK, ([&](auto& out) { fmt::format_to(out, "Foo {} {}", 123, 456.f); })); - } -} - -namespace ramses -{ - TEST(AThreadLocalLogRamses, canUseContextFromRamsesNamespace) - { - ramses::internal::ThreadLocalLog::SetPrefix(123); - LOG_INFO_R(CONTEXT_FRAMEWORK, "Foo " << 123 << 456); - } -} diff --git a/tests/unittests/framework/DltLogAppender/DltAdapterTest.cpp b/tests/unittests/framework/DltLogAppender/DltAdapterTest.cpp index 94d5bdd10..ad8ebec67 100644 --- a/tests/unittests/framework/DltLogAppender/DltAdapterTest.cpp +++ b/tests/unittests/framework/DltLogAppender/DltAdapterTest.cpp @@ -85,23 +85,23 @@ namespace ramses::internal TEST_F(ADltAdapter, canLogOnContext) { EXPECT_TRUE(adapter->initialize("TEST", "Test application", true, logLevelChangeCallback, {context.get()}, true)); - StringOutputStream sos(std::string("foo")); - LogMessage msg(*context, ELogLevel::Info, sos); + std::string s("foo"); + LogMessage msg{ *context, ELogLevel::Info, s }; EXPECT_TRUE(adapter->logMessage(msg)); } TEST_F(ADltAdapter, logFailsWithoutInit) { - StringOutputStream sos(std::string("foo")); - LogMessage msg(*context, ELogLevel::Info, sos); + std::string s("foo"); + LogMessage msg{ *context, ELogLevel::Info, s }; EXPECT_FALSE(adapter->logMessage(msg)); } TEST_F(ADltAdapter, canLogWithLogLevelOff) { EXPECT_TRUE(adapter->initialize("TEST", "Test application", true, logLevelChangeCallback, {context.get()}, true)); - StringOutputStream sos(std::string("foo")); - LogMessage msg(*context, ELogLevel::Off, sos); + std::string s("foo"); + LogMessage msg{ *context, ELogLevel::Off, s }; EXPECT_TRUE(adapter->logMessage(msg)); } @@ -110,8 +110,8 @@ namespace ramses::internal EXPECT_TRUE(adapter->initialize("TEST", "Test application", true, logLevelChangeCallback, {context.get()}, true)); std::unique_ptr otherContext(new LogContext("RYYY", "Other test context")); - StringOutputStream sos(std::string("foo")); - LogMessage msg(*otherContext, ELogLevel::Info, sos); + std::string s("foo"); + LogMessage msg{ *otherContext, ELogLevel::Info, s }; EXPECT_FALSE(adapter->logMessage(msg)); } diff --git a/tests/unittests/framework/PlatformAbstraction/PlatformThreadTest.cpp b/tests/unittests/framework/PlatformAbstraction/PlatformThreadTest.cpp index abca5d17a..59ca3cd79 100644 --- a/tests/unittests/framework/PlatformAbstraction/PlatformThreadTest.cpp +++ b/tests/unittests/framework/PlatformAbstraction/PlatformThreadTest.cpp @@ -7,6 +7,7 @@ // ------------------------------------------------------------------------- #include "internal/PlatformAbstraction/PlatformThread.h" +#include "internal/Core/Utils/LogMacros.h" #include "gtest/gtest.h" namespace ramses::internal @@ -44,6 +45,15 @@ namespace ramses::internal } } }; + + class LoggingRunnable : public Runnable + { + public: + void run() override + { + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + } + }; } class APlatformThread : public testing::Test @@ -173,4 +183,34 @@ namespace ramses::internal EXPECT_FALSE(thread.joinable()); EXPECT_FALSE(thread.isRunning()); } + + TEST_F(APlatformThread, setsNameToLogger) + { + std::string logMsg; + GetRamsesLogger().setLogHandler([&logMsg](auto /*unused*/, auto /*unused*/, auto message) { + logMsg = message; + }); + + // logging prefix name tests work with static thread_local variables, each test case needs to run in own thread to not affect other test cases + std::thread t([&] { + + RamsesLogger::SetPrefixes("instName", ""); + + LoggingRunnable runnable; + + PlatformThread thread{ "thrdName" }; + thread.start(runnable); + thread.join(); + EXPECT_EQ("instName.thrdName: test", logMsg); + + PlatformThread thread2{ "thrdName2" }; + thread2.start(runnable); + thread2.join(); + EXPECT_EQ("instName.thrdName2: test", logMsg); + + }); + t.join(); + + GetRamsesLogger().setLogHandler(nullptr); + } } diff --git a/tests/unittests/framework/Ramsh/RamshTest.cpp b/tests/unittests/framework/Ramsh/RamshTest.cpp index a9213f69d..2ad065607 100644 --- a/tests/unittests/framework/Ramsh/RamshTest.cpp +++ b/tests/unittests/framework/Ramsh/RamshTest.cpp @@ -468,10 +468,8 @@ namespace ramses::internal protected: static void LogSomeMessage() { - StringOutputStream stream; - stream << "This is some very interesting log message used for testing purpose"; - LogMessage message(CONTEXT_RAMSH, ELogLevel::Info, stream); - GetRamsesLogger().log(message); + std::string s = "This is some very interesting log message used for testing purpose"; + GetRamsesLogger().log(LogMessage{ CONTEXT_RAMSH, ELogLevel::Info, std::move(s) }); } }; diff --git a/tests/unittests/framework/SceneGraph/Resource/ResourceTest.cpp b/tests/unittests/framework/SceneGraph/Resource/ResourceTest.cpp index 891b1dbf5..20f9bdb0f 100644 --- a/tests/unittests/framework/SceneGraph/Resource/ResourceTest.cpp +++ b/tests/unittests/framework/SceneGraph/Resource/ResourceTest.cpp @@ -365,7 +365,7 @@ namespace ramses::internal res->compress(IResource::CompressionLevel::Realtime); value += std::to_integer(res->getCompressedResourceData().data()[0]); } - LOG_DEBUG(CONTEXT_FRAMEWORK, "Test result " << value); + LOG_DEBUG(CONTEXT_FRAMEWORK, "Test result {}", value); }); } run(); @@ -384,7 +384,7 @@ namespace ramses::internal value += std::to_integer(res->getResourceData().data()[0]); value += res->getDecompressedDataSize(); } - LOG_DEBUG(CONTEXT_FRAMEWORK, "Test result " << value); + LOG_DEBUG(CONTEXT_FRAMEWORK, "Test result {}", value); }); } run(); @@ -409,7 +409,7 @@ namespace ramses::internal res->compress(IResource::CompressionLevel::Realtime); } } - LOG_DEBUG(CONTEXT_FRAMEWORK, "Test result " << value); + LOG_DEBUG(CONTEXT_FRAMEWORK, "Test result {}", value); }); } run(); @@ -430,7 +430,7 @@ namespace ramses::internal value += std::to_integer(res->getResourceData().data()[0]); value += res->getDecompressedDataSize(); } - LOG_DEBUG(CONTEXT_FRAMEWORK, "Test result " << value); + LOG_DEBUG(CONTEXT_FRAMEWORK, "Test result {}", value); }); run(); } diff --git a/tests/unittests/framework/SceneGraph/Scene/ActionTestScene.cpp b/tests/unittests/framework/SceneGraph/Scene/ActionTestScene.cpp index 9bdcc0f8e..895d1f283 100644 --- a/tests/unittests/framework/SceneGraph/Scene/ActionTestScene.cpp +++ b/tests/unittests/framework/SceneGraph/Scene/ActionTestScene.cpp @@ -849,6 +849,12 @@ namespace ramses::internal flushPendingSceneActions(); } + void ActionTestScene::setRenderBufferProperties(RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount) + { + m_actionCollector.setRenderBufferProperties(handle, width, height, sampleCount); + flushPendingSceneActions(); + } + bool ActionTestScene::isRenderBufferAllocated(RenderBufferHandle handle) const { return m_scene.isRenderBufferAllocated(handle); diff --git a/tests/unittests/framework/SceneGraph/Scene/ActionTestScene.h b/tests/unittests/framework/SceneGraph/Scene/ActionTestScene.h index 0015122ab..2293cf4ab 100644 --- a/tests/unittests/framework/SceneGraph/Scene/ActionTestScene.h +++ b/tests/unittests/framework/SceneGraph/Scene/ActionTestScene.h @@ -236,6 +236,7 @@ namespace ramses::internal // Render buffers RenderBufferHandle allocateRenderBuffer (const RenderBuffer& renderBuffer, RenderBufferHandle handle) override; void releaseRenderBuffer (RenderBufferHandle handle) override; + void setRenderBufferProperties (RenderBufferHandle handle, uint32_t width, uint32_t height, uint32_t sampleCount) override; [[nodiscard]] bool isRenderBufferAllocated (RenderBufferHandle handle) const override; [[nodiscard]] uint32_t getRenderBufferCount () const override; [[nodiscard]] const RenderBuffer& getRenderBuffer (RenderBufferHandle handle) const override; diff --git a/tests/unittests/framework/SceneGraph/Scene/ResourceChangeCollectingSceneTest.cpp b/tests/unittests/framework/SceneGraph/Scene/ResourceChangeCollectingSceneTest.cpp index 86c5b1c89..c0d04d626 100644 --- a/tests/unittests/framework/SceneGraph/Scene/ResourceChangeCollectingSceneTest.cpp +++ b/tests/unittests/framework/SceneGraph/Scene/ResourceChangeCollectingSceneTest.cpp @@ -135,6 +135,21 @@ namespace ramses::internal EXPECT_EQ(0u, sceneResourceActions.size()); } + TEST_F(AResourceChangeCollectingScene, setRenderBufferPropertiesIsTracked) + { + const RenderBufferHandle bufferHandle = scene.allocateRenderBuffer({ 1u, 1u, EPixelStorageFormat::R8, ERenderBufferAccessMode::ReadWrite, 0u }, {}); + scene.resetResourceChanges(); + + scene.setRenderBufferProperties(bufferHandle, 1u, 2u, 3u); + ASSERT_EQ(1u, sceneResourceActions.size()); + EXPECT_EQ(bufferHandle, sceneResourceActions[0].handle); + EXPECT_EQ(ESceneResourceAction_UpdateRenderBufferProperties, sceneResourceActions[0].action); + EXPECT_TRUE(scene.haveResourcesChanged()); + + scene.resetResourceChanges(); + EXPECT_EQ(0u, sceneResourceActions.size()); + } + TEST_F(AResourceChangeCollectingScene, createdBlitPassIsTracked) { const BlitPassHandle handle = scene.allocateBlitPass(RenderBufferHandle(0u), RenderBufferHandle(1u), {}); diff --git a/tests/unittests/framework/SceneGraph/Scene/SceneTest_RenderBuffer.cpp b/tests/unittests/framework/SceneGraph/Scene/SceneTest_RenderBuffer.cpp index c0a73812b..8e133c73d 100644 --- a/tests/unittests/framework/SceneGraph/Scene/SceneTest_RenderBuffer.cpp +++ b/tests/unittests/framework/SceneGraph/Scene/SceneTest_RenderBuffer.cpp @@ -51,6 +51,21 @@ namespace ramses::internal EXPECT_FALSE(this->m_scene.isRenderBufferAllocated(buffer)); } + TYPED_TEST(AScene, canSetRenderBufferProperties) + { + const RenderBufferHandle buffer(13u); + EXPECT_EQ(buffer, this->m_scene.allocateRenderBuffer({ 1u, 2u, EPixelStorageFormat::Depth16, ERenderBufferAccessMode::ReadWrite, 0u }, buffer)); + + this->m_scene.setRenderBufferProperties(buffer, 3u, 4u, 8u); + + const RenderBuffer& renderBuffer = this->m_scene.getRenderBuffer(buffer); + EXPECT_EQ(3u, renderBuffer.width); + EXPECT_EQ(4u, renderBuffer.height); + EXPECT_EQ(EPixelStorageFormat::Depth16, renderBuffer.format); + EXPECT_EQ(ERenderBufferAccessMode::ReadWrite, renderBuffer.accessMode); + EXPECT_EQ(8u, renderBuffer.sampleCount); + } + TYPED_TEST(AScene, canCreateMultipleRenderBuffers) { const RenderBufferHandle buffer1(13u); diff --git a/tests/unittests/framework/SceneGraph/Scene/TestingScene.h b/tests/unittests/framework/SceneGraph/Scene/TestingScene.h index 1236fa02b..2247a5342 100644 --- a/tests/unittests/framework/SceneGraph/Scene/TestingScene.h +++ b/tests/unittests/framework/SceneGraph/Scene/TestingScene.h @@ -138,7 +138,8 @@ namespace ramses::internal scene.allocateCamera(ECameraProjectionType::Orthographic, cameraNode, cameraDataInstance, orthographicCamera); scene.allocateRenderTarget(renderTarget); - scene.allocateRenderBuffer({ 23u, 42u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 3u }, renderBuffer); + scene.allocateRenderBuffer({ 1u, 2u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u }, renderBuffer); + scene.setRenderBufferProperties(renderBuffer, 23u, 42u, 3u); scene.addRenderTargetRenderBuffer(renderTarget, renderBuffer); scene.allocateRenderGroup(0u, 0u, renderGroup); diff --git a/tests/unittests/framework/ramses-framework/APILoggingHelperTest.cpp b/tests/unittests/framework/ramses-framework/APILoggingHelperTest.cpp deleted file mode 100644 index c00e28e62..000000000 --- a/tests/unittests/framework/ramses-framework/APILoggingHelperTest.cpp +++ /dev/null @@ -1,34 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2017 BMW Car IT GmbH -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "gtest/gtest.h" -#include "impl/APILoggingHelper.h" - -namespace ramses::internal -{ - TEST(APILoggingHelperTest, emptyArgumentsTest) - { - int32_t argc = 0; - const char* argv[1] = {}; - EXPECT_EQ(APILoggingHelper::MakeLoggingString(argc, argv), "0 arguments: [ ]"); - } - - TEST(APILoggingHelperTest, singleArgumentTest) - { - int32_t argc = 1; - const char* argv[1] = {"foo"}; - EXPECT_EQ(APILoggingHelper::MakeLoggingString(argc, argv), "1 arguments: [ foo ]"); - } - - TEST(APILoggingHelperTest, multiArgumentsTest) - { - int32_t argc = 3; - const char* argv[3] = {"foo", "bar", "huh"}; - EXPECT_EQ(APILoggingHelper::MakeLoggingString(argc, argv), "3 arguments: [ foo ; bar ; huh ]"); - } -} diff --git a/tests/unittests/framework/ramses-framework/ErrorReportingTest.cpp b/tests/unittests/framework/ramses-framework/ErrorReportingTest.cpp index d08074056..8d813298c 100644 --- a/tests/unittests/framework/ramses-framework/ErrorReportingTest.cpp +++ b/tests/unittests/framework/ramses-framework/ErrorReportingTest.cpp @@ -98,8 +98,8 @@ namespace ramses::internal m_errorReporting.set("error 2", &object2); ASSERT_EQ(m_loggedErrors.size(), 2u); - EXPECT_EQ(m_loggedErrors[0], "[obj1] error 1"); - EXPECT_EQ(m_loggedErrors[1], "[obj2] error 2"); + EXPECT_EQ(m_loggedErrors[0], "R.main: [obj1] error 1"); + EXPECT_EQ(m_loggedErrors[1], "R.main: [obj2] error 2"); } TEST_F(AErrorReporting, ClearsError) diff --git a/tests/unittests/framework/ramses-framework/RamsesFrameworkTest.cpp b/tests/unittests/framework/ramses-framework/RamsesFrameworkTest.cpp index 0eb8500af..169d91b8b 100644 --- a/tests/unittests/framework/ramses-framework/RamsesFrameworkTest.cpp +++ b/tests/unittests/framework/ramses-framework/RamsesFrameworkTest.cpp @@ -16,6 +16,7 @@ #include "internal/Core/Utils/LogMacros.h" #include "internal/Core/Utils/ThreadBarrier.h" #include "ApiRamshCommandMock.h" +#include using namespace testing; @@ -133,7 +134,7 @@ TEST(ARamsesFramework, SetLogHandler) RamsesFramework::SetLogHandler([&loggerCalled](auto level, auto context, auto message) { - if (level == ELogLevel::Warn && context == "RFRA" && message == "SetLogHandlerTest") + if (level == ELogLevel::Warn && context == "RFRA" && message == "R.main: SetLogHandlerTest") { loggerCalled = true; } @@ -185,4 +186,120 @@ TEST(ARamsesFramework, multipleInstancesCanBeCreatedInParallel) for (auto& t : threads) t.join(); } + +class ARamsesFrameworkLogging : public ::testing::Test +{ +protected: + void SetUp() override + { + RamsesFramework::SetLogHandler([this](auto /*unused*/, auto /*unused*/, auto message) { + m_logMessage = message; + }); + } + + void TearDown() override + { + RamsesFramework::SetLogHandler(nullptr); + } + + std::string m_logMessage; +}; + +TEST_F(ARamsesFrameworkLogging, SetLoggingInstanceName) +{ + // logging prefix name tests work with static thread_local variables, each test case needs to run in own thread to not affect other test cases + std::thread t([&] { + + // initial default + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("R.main: test", m_logMessage); + + RamsesFrameworkConfig cfg{ EFeatureLevel_Latest }; + cfg.setLoggingInstanceName("instName"); + RamsesFramework fw{ cfg }; + + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("instName.main: test", m_logMessage); + LOG_WARN(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("instName.main: test", m_logMessage); + LOG_ERROR(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("instName.main: test", m_logMessage); + + }); + t.join(); +} + +TEST_F(ARamsesFrameworkLogging, SetLoggingPrefix) +{ + // logging prefix name tests work with static thread_local variables, each test case needs to run in own thread to not affect other test cases + std::thread t([&] { + + // init default + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("R.main: test", m_logMessage); + LOG_WARN(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("R.main: test", m_logMessage); + LOG_ERROR(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("R.main: test", m_logMessage); + + RamsesLogger::SetPrefixes("I", "T", "A"); + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("I.T.A: test", m_logMessage); + LOG_WARN(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("I.T.A: test", m_logMessage); + LOG_ERROR(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("I.T.A: test", m_logMessage); + + }); + t.join(); +} + +TEST_F(ARamsesFrameworkLogging, SetLoggingPrefixPerThread) +{ + // logging prefix name tests work with static thread_local variables, each test case needs to run in own thread to not affect other test cases + std::thread t([&] { + + RamsesFrameworkConfig cfg{ EFeatureLevel_Latest }; + cfg.setLoggingInstanceName("instName1"); + RamsesFramework fw1{ cfg }; + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("instName1.main: test", m_logMessage); + + std::thread t0([&] { + cfg.setLoggingInstanceName("instName2"); + RamsesFramework fw2{ cfg }; + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("instName2.main: test", m_logMessage); + + std::thread t1([&] { + cfg.setLoggingInstanceName("instName3"); + RamsesFramework fw3{ cfg }; + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("instName3.main: test", m_logMessage); + + std::thread t2([&] { + cfg.setLoggingInstanceName("instName4"); + RamsesFramework fw4{ cfg }; + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("instName4.main: test", m_logMessage); + }); + t2.join(); + + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("instName3.main: test", m_logMessage); + }); + t1.join(); + + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("instName2.main: test", m_logMessage); + }); + t0.join(); + + // main thread not affected + LOG_INFO(CONTEXT_FRAMEWORK, "test"); + EXPECT_EQ("instName1.main: test", m_logMessage); + + }); + t.join(); +} } diff --git a/tests/unittests/renderer/embedded-compositor-wayland/EmbeddedCompositor_Wayland_Test.cpp b/tests/unittests/renderer/embedded-compositor-wayland/EmbeddedCompositor_Wayland_Test.cpp index 0fddb429f..c9779fa4b 100644 --- a/tests/unittests/renderer/embedded-compositor-wayland/EmbeddedCompositor_Wayland_Test.cpp +++ b/tests/unittests/renderer/embedded-compositor-wayland/EmbeddedCompositor_Wayland_Test.cpp @@ -25,7 +25,6 @@ #include "WaylandBufferResourceMock.h" #include "internal/Platform/Wayland/EmbeddedCompositor/WaylandBuffer.h" #include "wayland-client.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include "internal/Platform/EGL/Context_EGL.h" #include #include @@ -158,9 +157,6 @@ namespace ramses::internal public: bool init(const std::string& ecSocketName, const std::string& ecSocketGroup = "", int ecSocketFD = -1, bool xdgRuntimeDirSet = true, uint32_t ecSocketPermissions = 0) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - if (xdgRuntimeDirSet) { WaylandEnvironmentUtils::SetVariable(WaylandEnvironmentVariable::XDGRuntimeDir, m_initialValueOfXdgRuntimeDir); diff --git a/tests/unittests/renderer/embedded-compositor-wayland/main.cpp b/tests/unittests/renderer/embedded-compositor-wayland/main.cpp index a4eb0fbd0..8f62799b4 100644 --- a/tests/unittests/renderer/embedded-compositor-wayland/main.cpp +++ b/tests/unittests/renderer/embedded-compositor-wayland/main.cpp @@ -10,14 +10,10 @@ #include "gtest/gtest.h" #include "internal/PlatformAbstraction/PlatformConsole.h" -#include "internal/Core/Utils/ThreadLocalLog.h" int main(int argc, char* argv[]) { testing::InitGoogleMock(&argc, argv); - // set log prefix for all tests - ramses::internal::ThreadLocalLog::SetPrefix(1); - return RUN_ALL_TESTS(); } diff --git a/tests/unittests/renderer/ramses-renderer/RendererSceneControlTest.cpp b/tests/unittests/renderer/ramses-renderer/RendererSceneControlTest.cpp index 6f94b3daa..c33903e98 100644 --- a/tests/unittests/renderer/ramses-renderer/RendererSceneControlTest.cpp +++ b/tests/unittests/renderer/ramses-renderer/RendererSceneControlTest.cpp @@ -23,7 +23,6 @@ #include "internal/RendererLib/RendererCommands.h" #include "RendererSceneControlEventHandlerMock.h" #include "RendererCommandVisitorMock.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include "PlatformFactoryMock.h" #include @@ -42,8 +41,6 @@ namespace ramses::internal m_renderer.impl().getDisplayDispatcher().injectPlatformFactory(std::make_unique()); m_displayId = m_renderer.createDisplay(ramses::DisplayConfig{}); - ThreadLocalLog::SetPrefix(2); - m_renderer.setLoopMode(ELoopMode::UpdateOnly); } diff --git a/tests/unittests/renderer/ramses-renderer/RendererSceneControlWithRendererTest.cpp b/tests/unittests/renderer/ramses-renderer/RendererSceneControlWithRendererTest.cpp index d4997ad0b..0fa16000c 100644 --- a/tests/unittests/renderer/ramses-renderer/RendererSceneControlWithRendererTest.cpp +++ b/tests/unittests/renderer/ramses-renderer/RendererSceneControlWithRendererTest.cpp @@ -195,7 +195,7 @@ namespace ramses::internal TEST_P(ARendererSceneControlWithRenderer_TargetToTarget, switchFromTargetStateToTargetStateAtEveryStep) { - LOG_INFO(CONTEXT_RENDERER, "Testing switch from target state " << EnumToString(GetTargetState1()) << " to target state " << EnumToString(GetTargetState2()) << " at step " << GetStepToSwitchState()); + LOG_INFO(CONTEXT_RENDERER, "Testing switch from target state {} to target state {} at step {}", EnumToString(GetTargetState1()), EnumToString(GetTargetState2()), GetStepToSwitchState()); ramsesClientRenderer->m_sceneControl.setSceneState(ramsesClientRenderer->m_sceneId, GetTargetState1()); ramsesClientRenderer->m_sceneControl.flush(); @@ -203,7 +203,7 @@ namespace ramses::internal int step = 0; for (int i = 0; i < NumLoopsToReachTargetState; ++i) { - LOG_INFO(CONTEXT_RENDERER, "LOOP: " << i << " STEP: " << step); + LOG_INFO(CONTEXT_RENDERER, "LOOP: {} STEP: {}", i, step); if (step == GetStepToSwitchState()) { ramsesClientRenderer->m_sceneControl.setSceneState(ramsesClientRenderer->m_sceneId, GetTargetState2()); @@ -212,7 +212,7 @@ namespace ramses::internal ramsesClientRenderer->m_renderer.doOneLoop(); ++step; - LOG_INFO(CONTEXT_RENDERER, "LOOP: " << i << " STEP: " << step); + LOG_INFO(CONTEXT_RENDERER, "LOOP: {} STEP: {}", i, step); if (step == GetStepToSwitchState()) { ramsesClientRenderer->m_sceneControl.setSceneState(ramsesClientRenderer->m_sceneId, GetTargetState2()); @@ -265,7 +265,7 @@ namespace ramses::internal TEST_P(ARendererSceneControlWithRenderer_ReachTargetStateWithUnpublish, unpublishAtEveryStepWhileReachingEveryState) { - LOG_INFO(CONTEXT_RENDERER, "Testing unpublish from target state " << EnumToString(GetTargetState()) << " at step " << GetStepToUnpublish() << " and re-publish at step " << GetStepToRepublish()); + LOG_INFO(CONTEXT_RENDERER, "Testing unpublish from target state {} at step {} and re-publish at step {}", EnumToString(GetTargetState()), GetStepToUnpublish(), GetStepToRepublish()); ramsesClientRenderer->m_sceneControl.setSceneState(ramsesClientRenderer->m_sceneId, GetTargetState()); ramsesClientRenderer->m_sceneControl.flush(); @@ -273,7 +273,7 @@ namespace ramses::internal int step = 0; for (int i = 0; i < NumLoopsToReachTargetState; ++i) { - LOG_INFO(CONTEXT_RENDERER, "LOOP: " << i << " STEP: " << step); + LOG_INFO(CONTEXT_RENDERER, "LOOP: {} STEP: {}", i, step); if (step == GetStepToUnpublish()) ramsesClientRenderer->m_scene.unpublish(); if (step == GetStepToRepublish()) @@ -281,7 +281,7 @@ namespace ramses::internal ramsesClientRenderer->m_renderer.doOneLoop(); ++step; - LOG_INFO(CONTEXT_RENDERER, "LOOP: " << i << " STEP: " << step); + LOG_INFO(CONTEXT_RENDERER, "LOOP: {} STEP: {}", i, step); if (step == GetStepToUnpublish()) ramsesClientRenderer->m_scene.unpublish(); if (step == GetStepToRepublish()) diff --git a/tests/unittests/renderer/renderer-lib/CMakeLists.txt b/tests/unittests/renderer/renderer-lib/CMakeLists.txt index 327060cf1..be5aa9d25 100644 --- a/tests/unittests/renderer/renderer-lib/CMakeLists.txt +++ b/tests/unittests/renderer/renderer-lib/CMakeLists.txt @@ -7,7 +7,7 @@ # ------------------------------------------------------------------------- createModule( - NAME ramses-renderer-lib-test + NAME ramses-renderer-internal-test TYPE BINARY SRC_FILES RendererFramework/*.cpp RendererFramework/*.h @@ -20,5 +20,5 @@ createModule( ) makeTestFromTarget( - TARGET ramses-renderer-lib-test + TARGET ramses-renderer-internal-test SUFFIX UNITTEST) diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/AsyncEffectUploaderTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/AsyncEffectUploaderTest.cpp index a4e372a8f..f3d8ff14d 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/AsyncEffectUploaderTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/AsyncEffectUploaderTest.cpp @@ -10,7 +10,6 @@ #include "internal/RendererLib/AsyncEffectUploader.h" #include "internal/SceneGraph/Resource/EffectResource.h" #include "PlatformMock.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include "internal/Watchdog/ThreadAliveNotifierMock.h" using namespace testing; @@ -21,10 +20,8 @@ namespace ramses::internal { protected: AnAsyncEffectUploader() - : asyncEffectUploader(platformMock, platformMock.renderBackendMock, (EXPECT_CALL(notifier, registerThread()).WillOnce(Return(ThreadAliveNotifierMock::dummyThreadId)), notifier), 1) + : asyncEffectUploader(platformMock, platformMock.renderBackendMock, (EXPECT_CALL(notifier, registerThread()).WillOnce(Return(ThreadAliveNotifierMock::dummyThreadId)), notifier), DisplayHandle{ 1 }) { - // caller of async shader uploader is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(0); } void TearDown() override diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/DataReferenceLinkCachedSceneTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/DataReferenceLinkCachedSceneTest.cpp index 590f84677..221f405e3 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/DataReferenceLinkCachedSceneTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/DataReferenceLinkCachedSceneTest.cpp @@ -10,7 +10,6 @@ #include "internal/RendererLib/RendererScenes.h" #include "internal/RendererLib/RendererEventCollector.h" #include "SceneAllocateHelper.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include "gtest/gtest.h" namespace ramses::internal @@ -25,9 +24,6 @@ namespace ramses::internal , scene(rendererScenes.createScene(SceneInfo(SceneId(3u)))) , sceneAllocator(scene) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - const DataLayoutHandle layout = sceneAllocator.allocateDataLayout({ DataFieldInfo(EDataType::Int32) }, ResourceContentHash::Invalid()); dataRef = sceneAllocator.allocateDataInstance(layout); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/DataReferenceLinkManagerTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/DataReferenceLinkManagerTest.cpp index 285fef4d2..2f8252c43 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/DataReferenceLinkManagerTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/DataReferenceLinkManagerTest.cpp @@ -11,7 +11,6 @@ #include "internal/RendererLib/RendererEventCollector.h" #include "SceneAllocateHelper.h" #include "internal/SceneGraph/SceneUtils/ISceneDataArrayAccessor.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include "gtest/gtest.h" namespace ramses::internal @@ -36,9 +35,6 @@ namespace ramses::internal , providerId(33u) , consumerId(44u) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - if (createSlots) { const DataLayoutHandle providerLayout = providerSceneAllocator.allocateDataLayout({ DataFieldInfo(EDataType::Float) }, ResourceContentHash::Invalid()); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/DisplayEventHandlerTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/DisplayEventHandlerTest.cpp index 171e25dc2..23fcfbccc 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/DisplayEventHandlerTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/DisplayEventHandlerTest.cpp @@ -12,7 +12,6 @@ #include "internal/RendererLib/RendererEventCollector.h" #include "internal/RendererLib/Enums/EKeyEvent.h" #include "internal/RendererLib/Enums/EKeyModifier.h" -#include "internal/Core/Utils/ThreadLocalLog.h" namespace ramses::internal { @@ -25,8 +24,6 @@ namespace ramses::internal : m_displayHandle(5110u) , m_displayEventHandler(m_displayHandle, m_eventCollector) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); } [[nodiscard]] RendererEvent getRendererEvent(uint32_t index) const diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/EmbeddedCompositingManagerTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/EmbeddedCompositingManagerTest.cpp index 80ccbc3a1..9b1f4646c 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/EmbeddedCompositingManagerTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/EmbeddedCompositingManagerTest.cpp @@ -10,7 +10,6 @@ #include "DeviceMock.h" #include "EmbeddedCompositorMock.h" #include "internal/RendererLib/PlatformBase/TextureUploadingAdapter_Base.h" -#include "internal/Core/Utils/ThreadLocalLog.h" namespace ramses::internal { @@ -19,12 +18,6 @@ namespace ramses::internal class AnEmbeddedCompositingManager : public ::testing::Test { public: - AnEmbeddedCompositingManager() - { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - } - void expectStreamTexUpload(WaylandIviSurfaceId iviSurface, DeviceResourceHandle textureDeviceHandle = compositedTextureDeviceHandle) { EXPECT_CALL(deviceMock, uploadStreamTexture2D(_, _, _, _, _, _)).WillOnce(Return(textureDeviceHandle)); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/LinkManagerBaseTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/LinkManagerBaseTest.cpp index 118c4c880..861d9f062 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/LinkManagerBaseTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/LinkManagerBaseTest.cpp @@ -14,7 +14,6 @@ #include "internal/RendererLib/RendererScenes.h" #include "internal/RendererLib/RendererEventCollector.h" #include "SceneLinksTestUtils.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -36,9 +35,6 @@ namespace ramses::internal , providerSlotHandle(55u) , consumerSlotHandle(66u) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - createDataSlot(providerSceneAllocator, providerSlotHandle, DataSlotId(33u), true); createDataSlot(consumerSceneAllocator, consumerSlotHandle, DataSlotId(44u), false); } diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/PendingSceneResourcesUtilsTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/PendingSceneResourcesUtilsTest.cpp index 55740f013..506a2f525 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/PendingSceneResourcesUtilsTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/PendingSceneResourcesUtilsTest.cpp @@ -24,9 +24,9 @@ namespace ramses::internal { { public: APendingSceneResourcesUtils() - : rendererScenes(rendererEventCollector) - , sceneLinksManager(rendererScenes, rendererEventCollector) - , scene(sceneLinksManager, SceneInfo(sceneID)) + : rendererScenes(rendererEventCollector) + , sceneLinksManager(rendererScenes, rendererEventCollector) + , scene(sceneLinksManager, SceneInfo(sceneID)) , allocateHelper(scene) { allocateHelper.allocateRenderTarget(renderTargetHandle); @@ -71,7 +71,7 @@ namespace ramses::internal { }; static const BasicActionSet ActionSet_RenderTarget{ ESceneResourceAction_CreateRenderTarget, ESceneResourceAction_DestroyRenderTarget }; - static const BasicActionSet ActionSet_RenderBuffer{ ESceneResourceAction_CreateRenderBuffer, ESceneResourceAction_DestroyRenderBuffer }; + static const BasicActionSet ActionSet_RenderBuffer{ ESceneResourceAction_CreateRenderBuffer, ESceneResourceAction_DestroyRenderBuffer, ESceneResourceAction_UpdateRenderBufferProperties }; static const BasicActionSet ActionSet_BlitPass{ ESceneResourceAction_CreateBlitPass, ESceneResourceAction_DestroyBlitPass }; static const BasicActionSet ActionSet_DataBuffer{ ESceneResourceAction_CreateDataBuffer, ESceneResourceAction_DestroyDataBuffer, ESceneResourceAction_UpdateDataBuffer }; static const BasicActionSet ActionSet_TextureBuffer{ ESceneResourceAction_CreateTextureBuffer, ESceneResourceAction_DestroyTextureBuffer, ESceneResourceAction_UpdateTextureBuffer }; @@ -88,13 +88,15 @@ namespace ramses::internal { static const BasicActionSet TestSceneResourceActions_Buffers[] = { ActionSet_DataBuffer, - ActionSet_TextureBuffer + ActionSet_TextureBuffer, + ActionSet_RenderBuffer }; TEST_F(APendingSceneResourcesUtils, appliesSceneResourceActions) { SceneResourceActionVector actions; actions.push_back(SceneResourceAction(renderBufferHandle.asMemoryHandle(), ESceneResourceAction_CreateRenderBuffer)); + actions.push_back(SceneResourceAction(renderBufferHandle.asMemoryHandle(), ESceneResourceAction_UpdateRenderBufferProperties)); actions.push_back(SceneResourceAction(renderTargetHandle.asMemoryHandle(), ESceneResourceAction_CreateRenderTarget)); actions.push_back(SceneResourceAction(blitPassHandle.asMemoryHandle(), ESceneResourceAction_CreateBlitPass)); actions.push_back(SceneResourceAction(dataBufferHandle.asMemoryHandle(), ESceneResourceAction_CreateDataBuffer)); @@ -108,6 +110,7 @@ namespace ramses::internal { InSequence seq; EXPECT_CALL(resourceManager, uploadRenderTargetBuffer(renderBufferHandle, sceneID, _)); + EXPECT_CALL(resourceManager, updateRenderTargetBufferProperties(renderBufferHandle, sceneID, _)); EXPECT_CALL(resourceManager, uploadRenderTarget(renderTargetHandle, _, sceneID)); EXPECT_CALL(resourceManager, uploadBlitPassRenderTargets(blitPassHandle, _, _, sceneID)); EXPECT_CALL(resourceManager, uploadDataBuffer(dataBufferHandle, _, _, _, sceneID)); @@ -277,7 +280,7 @@ namespace ramses::internal { } } - TEST_F(APendingSceneResourcesUtils, removesAnyDataBufferUpdateActionsBeforeDestroyDuringConsolidation) + TEST_F(APendingSceneResourcesUtils, removesAnyBufferUpdateActionsBeforeDestroyDuringConsolidation) { for (const auto& bufferAction : TestSceneResourceActions_Buffers) { @@ -298,7 +301,7 @@ namespace ramses::internal { } } - TEST_F(APendingSceneResourcesUtils, keepsDataBufferUpdateActionForNewlyCreatedAfterRemovedPreviousUpdatesDueToDestroy) + TEST_F(APendingSceneResourcesUtils, consolidatesSequenceOfCreateUpdateDestroyActions) { for (const auto& bufferAction : TestSceneResourceActions_Buffers) { @@ -362,4 +365,21 @@ namespace ramses::internal { EXPECT_EQ(actions.size(), 1u); PendingSceneResourcesUtils::ApplySceneResourceActions(actions, scene, resourceManager); } + + TEST_F(APendingSceneResourcesUtils, consolidatesAndAppliesRenderBufferPropertiesUpdate) + { + SceneResourceActionVector actions; + SceneResourceActionVector actionsNew; + actionsNew.push_back(SceneResourceAction(renderBufferHandle.asMemoryHandle(), ESceneResourceAction_UpdateRenderBufferProperties)); + actionsNew.push_back(SceneResourceAction(renderBufferHandle.asMemoryHandle(), ESceneResourceAction_UpdateRenderBufferProperties)); + actionsNew.push_back(SceneResourceAction(renderBufferHandle.asMemoryHandle(), ESceneResourceAction_UpdateRenderBufferProperties)); + actionsNew.push_back(SceneResourceAction(renderBufferHandle.asMemoryHandle(), ESceneResourceAction_UpdateRenderBufferProperties)); + actionsNew.push_back(SceneResourceAction(renderBufferHandle.asMemoryHandle(), ESceneResourceAction_UpdateRenderBufferProperties)); + PendingSceneResourcesUtils::ConsolidateSceneResourceActions(actionsNew, actions); + EXPECT_EQ(actions.size(), 1u); + + const auto& rb = scene.getRenderBuffer(renderBufferHandle); + EXPECT_CALL(resourceManager, updateRenderTargetBufferProperties(renderBufferHandle, sceneID, Ref(rb))); + PendingSceneResourcesUtils::ApplySceneResourceActions(actions, scene, resourceManager); + } } diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/PlatformTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/PlatformTest.cpp index 02b2e2b99..a49bca62b 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/PlatformTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/PlatformTest.cpp @@ -11,7 +11,6 @@ #include "internal/RendererLib/PlatformInterface/IRenderBackend.h" #include "WindowEventHandlerMock.h" #include "RenderBackendMock.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -19,13 +18,6 @@ namespace ramses::internal { class APlatformTest : public Test { - public: - static void SetUpTestSuite() - { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - } - protected: IRenderBackend* createRenderBackend(Platform_BaseMock& platform) { diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererCommandExecutorTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/RendererCommandExecutorTest.cpp index b6b30d30f..2d420c36f 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererCommandExecutorTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererCommandExecutorTest.cpp @@ -29,7 +29,6 @@ #include "EmbeddedCompositingManagerMock.h" #include "RendererSceneEventSenderMock.h" #include "RendererSceneUpdaterMock.h" -#include "internal/Core/Utils/ThreadLocalLog.h" namespace ramses::internal { @@ -43,9 +42,6 @@ namespace ramses::internal { , m_sceneStateExecutor(m_renderer, m_sceneEventSender, m_rendererEventCollector) , m_commandExecutor(m_renderer, m_commandBuffer, m_sceneUpdater, m_sceneControlLogic, m_rendererEventCollector, m_frameTimer) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - // enable SC ON_CALL(m_renderer.m_platform, getSystemCompositorController()).WillByDefault(Return(&m_renderer.m_platform.systemCompositorControllerMock)); } @@ -490,8 +486,18 @@ namespace ramses::internal { TEST_F(ARendererCommandExecutor, triggersLogRinfo) { - m_commandBuffer.enqueueCommand(RendererCommand::LogInfo{ ERendererLogTopic::Displays, true, NodeHandle{ 6u } }); - EXPECT_CALL(m_sceneUpdater, logRendererInfo(ERendererLogTopic::Displays, true, NodeHandle{ 6u })); + const RendererCommand::LogInfo cmd{ ERendererLogTopic::Displays, true, NodeHandle{ 6u }, true, false, ELoopMode::UpdateOnly, std::chrono::microseconds{ 13 } }; + m_commandBuffer.enqueueCommand(cmd); + EXPECT_CALL(m_sceneUpdater, logRendererInfo(_)).WillOnce([&cmd](const RendererCommand::LogInfo& c) { + EXPECT_EQ(cmd.topic, c.topic); + EXPECT_EQ(cmd.verbose, c.verbose); + EXPECT_EQ(cmd.nodeFilter, c.nodeFilter); + EXPECT_EQ(cmd.displaysThreaded, c.displaysThreaded); + EXPECT_EQ(cmd.displaysThreadsRunning, c.displaysThreadsRunning); + EXPECT_EQ(cmd.rendererLoopMode, c.rendererLoopMode); + EXPECT_EQ(cmd.minFrameTime, c.minFrameTime); + }); + doCommandExecutorLoop(); } } diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererEventCollectorTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/RendererEventCollectorTest.cpp index 68af761af..d089a34f5 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererEventCollectorTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererEventCollectorTest.cpp @@ -9,7 +9,6 @@ #include "gtest/gtest.h" #include "internal/RendererLib/RendererEventCollector.h" #include "internal/RendererLib/Enums/EKeyModifier.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -18,12 +17,6 @@ namespace ramses::internal class ARendererEventCollector : public testing::Test { protected: - ARendererEventCollector() - { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - } - void TearDown() override { // make sure all test cases dispatch all collected events diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceManagerMock.h b/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceManagerMock.h index 78c487efd..ae564b805 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceManagerMock.h +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceManagerMock.h @@ -47,6 +47,7 @@ namespace ramses::internal{ MOCK_METHOD(void, uploadAndUnloadPendingResources, (), (override)); MOCK_METHOD(void, uploadRenderTargetBuffer, (RenderBufferHandle renderBufferHandle, SceneId sceneId, const RenderBuffer& renderBuffer), (override)); MOCK_METHOD(void, unloadRenderTargetBuffer, (RenderBufferHandle renderBufferHandle, SceneId sceneId), (override)); + MOCK_METHOD(void, updateRenderTargetBufferProperties, (RenderBufferHandle renderBufferHandle, SceneId sceneId, const RenderBuffer& renderBuffer), (override)); MOCK_METHOD(void, uploadRenderTarget, (RenderTargetHandle renderTarget, const RenderBufferHandleVector& rtBufferHandles, SceneId sceneId), (override)); MOCK_METHOD(void, unloadRenderTarget, (RenderTargetHandle renderTarget, SceneId sceneId), (override)); MOCK_METHOD(void, uploadOffscreenBuffer, (OffscreenBufferHandle bufferHandle, uint32_t width, uint32_t height, uint32_t sampleCount, bool isDoubleBuffered, EDepthBufferType depthStencilBufferType), (override)); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceManagerTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceManagerTest.cpp index cc0222583..f9125111b 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceManagerTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceManagerTest.cpp @@ -19,7 +19,6 @@ #include "ResourceUploaderMock.h" #include "internal/Watchdog/ThreadAliveNotifierMock.h" #include "internal/RendererLib/DisplayConfig.h" -#include "internal/Core/Utils/ThreadLocalLog.h" namespace ramses::internal { using namespace testing; @@ -29,12 +28,9 @@ namespace ramses::internal { public: explicit ARendererResourceManager() : fakeSceneId(66u) - , asyncEffectUploader(platform, platform.renderBackendMock, notifier, 1) + , asyncEffectUploader(platform, platform.renderBackendMock, notifier, DisplayHandle{ 1 }) , resourceManager(platform.renderBackendMock, std::unique_ptr{ resUploader }, asyncEffectUploader, embeddedCompositingManager, {}, frameTimer, stats) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - InSequence s; EXPECT_CALL(platform.renderBackendMock.contextMock, disable()).WillOnce(Return(true)); EXPECT_CALL(platform, createResourceUploadRenderBackend()); @@ -449,7 +445,7 @@ namespace ramses::internal { TEST_F(ARendererResourceManager, canUploadAndUnloadRenderTargetBuffer) { RenderBufferHandle bufferHandle(1u); - const RenderBuffer colorBuffer(800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u); + const RenderBuffer colorBuffer{ 800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u }; EXPECT_CALL(platform.renderBackendMock.deviceMock, uploadRenderBuffer(800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u)); resourceManager.uploadRenderTargetBuffer(bufferHandle, fakeSceneId, colorBuffer); @@ -460,13 +456,32 @@ namespace ramses::internal { resourceManager.unloadRenderTargetBuffer(bufferHandle, fakeSceneId); } + TEST_F(ARendererResourceManager, gracefullyFailsSettingRenderBufferIfParamsDifferent) + { + RenderBufferHandle bufferHandle(1u); + const RenderBuffer colorBuffer{ 800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u }; + + EXPECT_CALL(platform.renderBackendMock.deviceMock, uploadRenderBuffer(800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u)); + resourceManager.uploadRenderTargetBuffer(bufferHandle, fakeSceneId, colorBuffer); + + // set same params - noop + resourceManager.updateRenderTargetBufferProperties(bufferHandle, fakeSceneId, colorBuffer); + + // set different params - will produce error + const RenderBuffer differentBuffer{ 1u, 2u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 1u }; + resourceManager.updateRenderTargetBufferProperties(bufferHandle, fakeSceneId, differentBuffer); + + EXPECT_CALL(platform.renderBackendMock.deviceMock, deleteRenderBuffer(_)); + resourceManager.unloadRenderTargetBuffer(bufferHandle, fakeSceneId); + } + TEST_F(ARendererResourceManager, canUploadAndUnloadBlitPassRenderTargets) { const BlitPassHandle blitPassHandle(100u); const RenderBufferHandle sourceRenderBufferHandle(101u); const RenderBufferHandle destinationRenderBufferHandle(102u); - const RenderBuffer renderBuffer(800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u); + const RenderBuffer renderBuffer{ 800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u }; const DeviceResourceHandle sourceRenderBufferDeviceHandle(201u); EXPECT_CALL(platform.renderBackendMock.deviceMock, @@ -513,8 +528,8 @@ namespace ramses::internal { bufferHandles.push_back(RenderBufferHandle(1u)); bufferHandles.push_back(RenderBufferHandle(5u)); - const RenderBuffer colorBuffer(800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u); - const RenderBuffer depthBuffer(800u, 600u, EPixelStorageFormat::Depth24, ERenderBufferAccessMode::ReadWrite, 0u); + const RenderBuffer colorBuffer{ 800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u }; + const RenderBuffer depthBuffer{ 800u, 600u, EPixelStorageFormat::Depth24, ERenderBufferAccessMode::ReadWrite, 0u }; { InSequence seq; @@ -1182,8 +1197,8 @@ namespace ramses::internal { bufferHandles.push_back(RenderBufferHandle(5u)); EXPECT_CALL(platform.renderBackendMock.deviceMock, uploadRenderBuffer(800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u)); EXPECT_CALL(platform.renderBackendMock.deviceMock, uploadRenderBuffer(800u, 600u, EPixelStorageFormat::Depth16, ERenderBufferAccessMode::ReadWrite, 0u)); - const RenderBuffer colorBuffer(800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u); - const RenderBuffer depthBuffer(800u, 600u, EPixelStorageFormat::Depth16, ERenderBufferAccessMode::ReadWrite, 0u); + const RenderBuffer colorBuffer{ 800u, 600u, EPixelStorageFormat::RGBA8, ERenderBufferAccessMode::ReadWrite, 0u }; + const RenderBuffer depthBuffer{ 800u, 600u, EPixelStorageFormat::Depth16, ERenderBufferAccessMode::ReadWrite, 0u }; resourceManager.uploadRenderTargetBuffer(bufferHandles[0], fakeSceneId, colorBuffer); resourceManager.uploadRenderTargetBuffer(bufferHandles[1], fakeSceneId, depthBuffer); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceRegistryTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceRegistryTest.cpp index 1284e08c0..c2ca35228 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceRegistryTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererResourceRegistryTest.cpp @@ -12,7 +12,6 @@ #include "internal/SceneGraph/Resource/ArrayResource.h" #include "ResourceMock.h" #include "MockResourceHash.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -20,14 +19,7 @@ namespace ramses::internal { class ARendererResourceRegistry : public ::testing::Test { - public: protected: - ARendererResourceRegistry() - { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - } - void expectResourcesUsedByScene(SceneId sceneId, const ResourceContentHashVector& res) { if (res.empty()) diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneControlLogicTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneControlLogicTest.cpp index b4fd49cd8..87a0b90d7 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneControlLogicTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneControlLogicTest.cpp @@ -9,7 +9,6 @@ #include "gmock/gmock.h" #include "RendererSceneStateControlMock.h" #include "internal/RendererLib/RendererSceneControlLogic.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -21,8 +20,6 @@ namespace ramses::internal ARendererSceneControlLogic() : m_logic(m_logicOutput) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); } void SetUp() override diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneResourceRegistryTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneResourceRegistryTest.cpp index a5e67d785..149e4af61 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneResourceRegistryTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneResourceRegistryTest.cpp @@ -47,10 +47,18 @@ namespace ramses::internal { const RenderBufferHandle rb(13u); const DeviceResourceHandle deviceHandle(123u); - registry.addRenderBuffer(rb, deviceHandle, 0u, false); + const RenderBuffer props{ 16u, 8u, EPixelStorageFormat::R16F, ERenderBufferAccessMode::ReadWrite, 2u }; + registry.addRenderBuffer(rb, deviceHandle, 10u, props); EXPECT_EQ(deviceHandle, registry.getRenderBufferDeviceHandle(rb)); + EXPECT_EQ(10u, registry.getRenderBufferByteSize(rb)); + EXPECT_EQ(props.width, registry.getRenderBufferProperties(rb).width); + EXPECT_EQ(props.height, registry.getRenderBufferProperties(rb).height); + EXPECT_EQ(props.format, registry.getRenderBufferProperties(rb).format); + EXPECT_EQ(props.accessMode, registry.getRenderBufferProperties(rb).accessMode); + EXPECT_EQ(props.sampleCount, registry.getRenderBufferProperties(rb).sampleCount); + RenderBufferHandleVector rbs; registry.getAllRenderBuffers(rbs); ASSERT_EQ(1u, rbs.size()); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneUpdaterMock.h b/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneUpdaterMock.h index 685140191..733d0c0d4 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneUpdaterMock.h +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneUpdaterMock.h @@ -48,6 +48,6 @@ namespace ramses::internal MOCK_METHOD(void, setLimitFlushesForceApply, (size_t limitForPendingFlushesForceApply), (override)); MOCK_METHOD(void, setLimitFlushesForceUnsubscribe, (size_t limitForPendingFlushesForceUnsubscribe), (override)); MOCK_METHOD(void, setSkippingOfUnmodifiedScenes, (bool enable), (override)); - MOCK_METHOD(void, logRendererInfo, (ERendererLogTopic topic, bool verbose, NodeHandle nodeFilter), (const, override)); + MOCK_METHOD(void, logRendererInfo, (const RendererCommand::LogInfo& cmd), (const, override)); }; } diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneUpdaterTest.h b/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneUpdaterTest.h index 5018a6605..6beab9810 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneUpdaterTest.h +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererSceneUpdaterTest.h @@ -32,7 +32,6 @@ #include "RendererSceneUpdaterFacade.h" #include "internal/Components/SceneUpdate.h" #include "internal/Watchdog/ThreadAliveNotifierMock.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include #include @@ -51,9 +50,6 @@ namespace ramses::internal { , sceneStateExecutor(renderer, sceneEventSender, rendererEventCollector) , rendererSceneUpdater(new RendererSceneUpdaterFacade(Display, renderer.m_platform, renderer, rendererScenes, sceneStateExecutor, rendererEventCollector, frameTimer, expirationMonitor, notifier)) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - rendererSceneUpdater->setSceneReferenceLogicHandler(sceneReferenceLogic); frameTimer.startFrame(); rendererSceneUpdater->setLimitFlushesForceApply(ForceApplyFlushesLimit); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererStatisticsTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/RendererStatisticsTest.cpp index 4099d271f..ab1cdbbf1 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererStatisticsTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererStatisticsTest.cpp @@ -39,7 +39,7 @@ namespace ramses::internal stats.frameFinished(2u); stats.frameFinished(3u); stats.frameFinished(4u); - EXPECT_EQ(2u, stats.getDrawCallsPerFrame()); + EXPECT_EQ(3u, stats.getDrawCallsPerFrame()); stats.reset(); EXPECT_EQ(0u, stats.getDrawCallsPerFrame()); @@ -409,7 +409,7 @@ namespace ramses::internal EXPECT_THAT(logOutput(), HasSubstr("Avg framerate: ")); EXPECT_THAT(logOutput(), HasSubstr("FPS [minFrameTime ")); EXPECT_THAT(logOutput(), HasSubstr("us, maxFrameTime ")); - EXPECT_THAT(logOutput(), HasSubstr("], drawcallsPerFrame 25, numFrames 4")); + EXPECT_THAT(logOutput(), HasSubstr("], drawCalls (0/100/25), numFrames 4")); EXPECT_THAT(logOutput(), HasSubstr("resUploaded 2 (79 B)")); EXPECT_THAT(logOutput(), HasSubstr("shadersCompiled 2")); EXPECT_THAT(logOutput(), HasSubstr("for total ms:1")); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/RendererTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/RendererTest.cpp index db356526f..771a38d99 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/RendererTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/RendererTest.cpp @@ -23,7 +23,6 @@ #include "ComponentMocks.h" #include "TestSceneHelper.h" #include -#include "internal/Core/Utils/ThreadLocalLog.h" namespace ramses::internal { @@ -35,9 +34,6 @@ namespace ramses::internal , expirationMonitor(rendererScenes, rendererEventCollector, rendererStatistics) , renderer(DisplayHandle{ 1u }, rendererScenes, rendererEventCollector, expirationMonitor, rendererStatistics) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - sceneRenderInterrupted.incrementRenderableIdx(); sceneRenderInterrupted2.incrementRenderableIdx(); sceneRenderInterrupted2.incrementRenderableIdx(); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/ResourceCachedSceneTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/ResourceCachedSceneTest.cpp index 45a510541..390dd61a2 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/ResourceCachedSceneTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/ResourceCachedSceneTest.cpp @@ -12,7 +12,6 @@ #include "internal/RendererLib/RendererScenes.h" #include "internal/RendererLib/RendererEventCollector.h" #include "SceneAllocateHelper.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include namespace ramses::internal @@ -26,9 +25,6 @@ namespace ramses::internal , sceneAllocator(scene) , sceneHelper(scene, indexArrayAvailable) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - sceneAllocator.allocateDataBuffer(EDataBufferType::VertexBuffer, EDataType::Vector3Buffer, sizeof(float) * 3, verticesDataBuffer); sceneAllocator.allocateTextureBuffer(EPixelStorageFormat::R8, { { 1u, 1u } }, textureBuffer); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/ResourceUploaderTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/ResourceUploaderTest.cpp index 989931ba8..c69f00e4e 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/ResourceUploaderTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/ResourceUploaderTest.cpp @@ -17,7 +17,6 @@ #include "internal/RendererLib/ResourceDescriptor.h" #include "internal/Components/ResourceDeleterCallingCallback.h" #include "internal/Core/Utils/ThreadBarrier.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include namespace ramses::internal @@ -87,8 +86,6 @@ namespace ramses::internal : uploader(true) , dummyManagedResourceCallback(managedResourceDeleter) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); } StrictMock renderer; @@ -493,19 +490,16 @@ namespace ramses::internal ThreadBarrier startBarrier(3); std::thread t1([&]() { - ThreadLocalLog::SetPrefix(2); startBarrier.wait(); uint32_t ramSize = 0; EXPECT_FALSE(uploaderWithBinaryProvider1.uploadResource(renderer, resourceObject1, ramSize).has_value()); }); std::thread t2([&]() { - ThreadLocalLog::SetPrefix(3); startBarrier.wait(); uint32_t ramSize = 0; EXPECT_FALSE(uploaderWithBinaryProvider2.uploadResource(renderer, resourceObject2, ramSize).has_value()); }); std::thread t3([&]() { - ThreadLocalLog::SetPrefix(4); startBarrier.wait(); uint32_t ramSize = 0; EXPECT_FALSE(uploaderWithBinaryProvider3.uploadResource(renderer, resourceObject3, ramSize).has_value()); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/ResourceUploadingManagerTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/ResourceUploadingManagerTest.cpp index 694a9a6d8..b3bd76286 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/ResourceUploadingManagerTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/ResourceUploadingManagerTest.cpp @@ -20,8 +20,6 @@ #include "internal/Components/ResourceDeleterCallingCallback.h" #include "internal/PlatformAbstraction/PlatformThread.h" #include "internal/Watchdog/ThreadAliveNotifierMock.h" -#include "internal/Core/Utils/ThreadLocalLog.h" - namespace ramses::internal { @@ -53,12 +51,9 @@ namespace ramses::internal , dummyManagedResourceCallback(managedResourceDeleter) , sceneId(66u) , uploader(new StrictMock) - , asyncEffectUploader(platformMock, platformMock.renderBackendMock, notifier, 1) + , asyncEffectUploader(platformMock, platformMock.renderBackendMock, notifier, DisplayHandle{ 1 }) , rendererResourceUploader(resourceRegistry, std::unique_ptr{ uploader }, platformMock.renderBackendMock, asyncEffectUploader, cfg, frameTimer, stats) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - InSequence s; EXPECT_CALL(platformMock.renderBackendMock.contextMock, disable()).WillOnce(Return(true)); EXPECT_CALL(platformMock, createResourceUploadRenderBackend()); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/SceneExpirationMonitorTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/SceneExpirationMonitorTest.cpp index 150306201..73680c5fc 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/SceneExpirationMonitorTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/SceneExpirationMonitorTest.cpp @@ -12,7 +12,6 @@ #include "internal/RendererLib/RendererStatistics.h" #include "internal/RendererLib/RendererEventCollector.h" #include "internal/PlatformAbstraction/PlatformThread.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -25,9 +24,6 @@ namespace ramses::internal : rendererScenes(eventCollector) , expirationMonitor(rendererScenes, eventCollector, statistics) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - rendererScenes.createScene(SceneInfo{ scene1 }); rendererScenes.createScene(SceneInfo{ scene2 }); rendererScenes.createScene(SceneInfo{ scene3 }); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/SceneLinksManagerTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/SceneLinksManagerTest.cpp index 1f2f063f6..47ee1af08 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/SceneLinksManagerTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/SceneLinksManagerTest.cpp @@ -11,7 +11,6 @@ #include "internal/RendererLib/RendererScenes.h" #include "internal/RendererLib/RendererEventCollector.h" #include "SceneLinksTestUtils.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -36,9 +35,6 @@ namespace ramses::internal , providerSlotHandle(5u) , consumerSlotHandle(6u) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - createDataSlot(providerSceneAllocator, providerSlotHandle, providerId, true); expectRendererEvent(ERendererEventType::SceneDataSlotProviderCreated, providerSceneId, providerId, SceneId(0u), DataSlotId(0u)); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/SceneLinksTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/SceneLinksTest.cpp index c8c9e6b18..e1b00fb11 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/SceneLinksTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/SceneLinksTest.cpp @@ -8,7 +8,6 @@ #include "gtest/gtest.h" #include "internal/RendererLib/SceneLinks.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -27,8 +26,6 @@ class ASceneLinks : public ::testing::Test , consumerSlot1(3u) , consumerSlot2(4u) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); } protected: diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/SceneReferenceLogicTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/SceneReferenceLogicTest.cpp index bfc5c1ff9..20eb47624 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/SceneReferenceLogicTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/SceneReferenceLogicTest.cpp @@ -16,7 +16,6 @@ #include "RendererSceneEventSenderMock.h" #include "internal/RendererLib/RendererEventCollector.h" #include "SceneAllocateHelper.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -29,8 +28,6 @@ namespace ramses::internal : m_scenes(m_eventCollector) , m_logic(m_scenes, m_sceneLogic, m_sceneUpdater, m_eventSender, m_ownership) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); } void SetUp() override diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/SceneReferenceLogicWithSceneUpdaterTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/SceneReferenceLogicWithSceneUpdaterTest.cpp index 65a173bcf..8fd79a5bf 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/SceneReferenceLogicWithSceneUpdaterTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/SceneReferenceLogicWithSceneUpdaterTest.cpp @@ -25,7 +25,6 @@ #include "ResourceDeviceHandleAccessorMock.h" #include "internal/Components/SceneUpdate.h" #include "internal/Watchdog/ThreadAliveNotifierMock.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -46,8 +45,6 @@ namespace ramses::internal , m_sceneLogic(m_sceneUpdater) , m_sceneRefLogic(m_scenes, m_sceneLogic, m_sceneUpdater, m_sceneEventSenderFromSceneRefLogic, m_sceneRefOwnership) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); m_sceneUpdater.setSceneReferenceLogicHandler(m_sceneRefLogic); } diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/SceneStateExecutorTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/SceneStateExecutorTest.cpp index 22663cf10..d869f71cb 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/SceneStateExecutorTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/SceneStateExecutorTest.cpp @@ -14,7 +14,6 @@ #include "ComponentMocks.h" #include "RendererMock.h" #include "RendererSceneEventSenderMock.h" -#include "internal/Core/Utils/ThreadLocalLog.h" namespace ramses::internal { @@ -30,8 +29,6 @@ namespace ramses::internal , renderer(displayHandle, rendererScenes, rendererEventCollector, expirationMonitor, rendererStatistics) , sceneStateExecutor(renderer, rendererSceneSender, rendererEventCollector) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); } void TearDown() override diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/TextureLinkManagerTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/TextureLinkManagerTest.cpp index 04021fa21..c445d4def 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/TextureLinkManagerTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/TextureLinkManagerTest.cpp @@ -15,7 +15,6 @@ #include "TestSceneHelper.h" #include "SceneAllocateHelper.h" #include "MockResourceHash.h" -#include "internal/Core/Utils/ThreadLocalLog.h" namespace ramses::internal { using namespace testing; @@ -35,9 +34,6 @@ namespace ramses::internal { , consumerSceneAllocator(consumerScene) , sceneHelper(consumerScene) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - consumerSceneAllocator.allocateTextureSampler({ {}, consumerTextureHash }, sampler); consumerSceneAllocator.allocateTextureSampler({ {}, consumerTextureHash }, sampler2); consumerSceneAllocator.allocateTextureSampler({ {}, consumerTextureHash }, sampler3); diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/TransformationLinkCachedSceneTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/TransformationLinkCachedSceneTest.cpp index 0317b660a..e00aaa663 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/TransformationLinkCachedSceneTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/TransformationLinkCachedSceneTest.cpp @@ -12,7 +12,6 @@ #include "internal/RendererLib/RendererEventCollector.h" #include "TestEqualHelper.h" #include "SceneAllocateHelper.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include "internal/Core/Math3d/Rotation.h" #include "glm/gtx/transform.hpp" @@ -76,8 +75,6 @@ namespace ramses::internal , consumer2ndLevelSceneConsumerId(5u) , consumerWithoutTransformsSceneConsumerId(6u) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); setupNodesAndDataSlots(); } diff --git a/tests/unittests/renderer/renderer-lib/RendererLib/TransformationLinkManagerTest.cpp b/tests/unittests/renderer/renderer-lib/RendererLib/TransformationLinkManagerTest.cpp index 1275b4c31..2c240864e 100644 --- a/tests/unittests/renderer/renderer-lib/RendererLib/TransformationLinkManagerTest.cpp +++ b/tests/unittests/renderer/renderer-lib/RendererLib/TransformationLinkManagerTest.cpp @@ -12,7 +12,6 @@ #include "internal/RendererLib/RendererScenes.h" #include "internal/RendererLib/RendererEventCollector.h" #include "SceneAllocateHelper.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include "TestEqualHelper.h" #include "glm/gtx/transform.hpp" @@ -41,9 +40,6 @@ namespace ramses::internal , providerId(33u) , consumerId(44u) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - providerSceneAllocator.allocateNode(0u, providerNode); consumerSceneAllocator.allocateNode(0u, consumerNode); diff --git a/tests/unittests/renderer/renderer-test-common/CMakeLists.txt b/tests/unittests/renderer/renderer-test-common/CMakeLists.txt index b4b346a24..d2e44d52d 100644 --- a/tests/unittests/renderer/renderer-test-common/CMakeLists.txt +++ b/tests/unittests/renderer/renderer-test-common/CMakeLists.txt @@ -13,6 +13,6 @@ createModule( INCLUDE_PATHS . SRC_FILES *.h *.cpp - DEPENDENCIES ramses-renderer-lib + DEPENDENCIES ramses-renderer-internal framework-test-utils ) diff --git a/tests/unittests/renderer/window-wayland-common/AWindowWayland.h b/tests/unittests/renderer/window-wayland-common/AWindowWayland.h index 8ec53b392..8aa6335a8 100644 --- a/tests/unittests/renderer/window-wayland-common/AWindowWayland.h +++ b/tests/unittests/renderer/window-wayland-common/AWindowWayland.h @@ -12,7 +12,6 @@ #include "TestWithWaylandEnvironment.h" #include "internal/RendererLib/DisplayConfig.h" #include "internal/Platform/Wayland/UnixDomainSocket.h" -#include "internal/Core/Utils/ThreadLocalLog.h" #include namespace ramses::internal @@ -23,7 +22,6 @@ namespace ramses::internal public: void SetUp() override { - ThreadLocalLog::SetPrefix(1); createWaylandWindow(); } diff --git a/tests/unittests/renderer/window-windows/Window_Window_Test.cpp b/tests/unittests/renderer/window-windows/Window_Window_Test.cpp index 99e0843a9..f7893fe25 100644 --- a/tests/unittests/renderer/window-windows/Window_Window_Test.cpp +++ b/tests/unittests/renderer/window-windows/Window_Window_Test.cpp @@ -11,7 +11,6 @@ #include "WindowEventHandlerMock.h" #include "internal/RendererLib/DisplayConfig.h" #include "internal/RendererLib/Enums/EKeyModifier.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -25,12 +24,6 @@ namespace ramses::internal { } - static void SetUpTestSuite() - { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - } - virtual void SetUp() { ASSERT_TRUE(window.init()); @@ -86,9 +79,6 @@ namespace ramses::internal TEST(Window_Windows, propagatesResizeEvents) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(0); - DisplayConfig config; config.setResizable(true); NiceMock eventHandlerMock; @@ -109,9 +99,6 @@ namespace ramses::internal TEST(Window_Windows, propagatesWindowMoveEvents) { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - DisplayConfig config; config.setResizable(true); NiceMock eventHandlerMock; diff --git a/tests/unittests/renderer/window-x11/Window_X11_Test.cpp b/tests/unittests/renderer/window-x11/Window_X11_Test.cpp index f631096db..15f884557 100644 --- a/tests/unittests/renderer/window-x11/Window_X11_Test.cpp +++ b/tests/unittests/renderer/window-x11/Window_X11_Test.cpp @@ -11,7 +11,6 @@ #include "WindowEventHandlerMock.h" #include "internal/RendererLib/DisplayConfig.h" #include "internal/RendererLib/Enums/EKeyModifier.h" -#include "internal/Core/Utils/ThreadLocalLog.h" using namespace testing; @@ -25,12 +24,6 @@ namespace ramses::internal { } - static void SetUpTestSuite() - { - // caller is expected to have a display prefix for logs - ThreadLocalLog::SetPrefix(1); - } - void SetUp() override { ASSERT_TRUE(window.init()); diff --git a/tests/unittests/tools/CMakeLists.txt b/tests/unittests/tools/CMakeLists.txt index 3297f7200..7ec1dae0d 100644 --- a/tests/unittests/tools/CMakeLists.txt +++ b/tests/unittests/tools/CMakeLists.txt @@ -7,5 +7,5 @@ # ------------------------------------------------------------------------- if(ramses-sdk_ENABLE_LOGIC) - add_subdirectory(ramses-logic-viewer) + add_subdirectory(ramses-viewer) endif() diff --git a/tests/unittests/tools/ramses-logic-viewer/CMakeLists.txt b/tests/unittests/tools/ramses-viewer/CMakeLists.txt similarity index 80% rename from tests/unittests/tools/ramses-logic-viewer/CMakeLists.txt rename to tests/unittests/tools/ramses-viewer/CMakeLists.txt index d2e113875..d9222a042 100644 --- a/tests/unittests/tools/ramses-logic-viewer/CMakeLists.txt +++ b/tests/unittests/tools/ramses-viewer/CMakeLists.txt @@ -7,21 +7,22 @@ # ------------------------------------------------------------------------- createModule( - NAME ramses-logic-viewer-test + NAME ramses-viewer-test TYPE BINARY ENABLE_INSTALL ON - INCLUDE_PATHS ${PROJECT_SOURCE_DIR}/tools/ramses-logic-viewer + INCLUDE_PATHS ${PROJECT_SOURCE_DIR}/tools/ramses-viewer ${PROJECT_SOURCE_DIR}/tests/unittests/client/logic/shared SRC_FILES LogicViewerTestBase.h LogicViewerTestBase.cpp LogicViewerTest.cpp LogicViewerLuaTest.cpp - DEPENDENCIES ramses-logic-viewer-lib + ValidationCacheTest.cpp + DEPENDENCIES ramses-viewer-lib ramses-client ramses-gmock ramses-gmock-main ) MakeTestFromTarget( - TARGET ramses-logic-viewer-test + TARGET ramses-viewer-test SUFFIX UNITTEST) diff --git a/tests/unittests/tools/ramses-logic-viewer/LogicViewerLuaTest.cpp b/tests/unittests/tools/ramses-viewer/LogicViewerLuaTest.cpp similarity index 92% rename from tests/unittests/tools/ramses-logic-viewer/LogicViewerLuaTest.cpp rename to tests/unittests/tools/ramses-viewer/LogicViewerLuaTest.cpp index 41be4ccab..0b5c14fbb 100644 --- a/tests/unittests/tools/ramses-logic-viewer/LogicViewerLuaTest.cpp +++ b/tests/unittests/tools/ramses-viewer/LogicViewerLuaTest.cpp @@ -60,6 +60,7 @@ namespace ramses::internal OUT.paramBool = Type:Bool() OUT.paramInt32 = Type:Int32() + OUT.paramInt32_2 = Type:Int32() OUT.paramInt64 = Type:Int64() OUT.paramFloat = Type:Float() OUT.paramString = Type:String() @@ -82,6 +83,7 @@ namespace ramses::internal function run(IN,OUT) OUT.paramBool = not IN.paramBool OUT.paramInt32 = 2 * IN.paramInt32 + OUT.paramInt32_2 = IN.paramInt32 + 1 OUT.paramInt64 = 1 + IN.paramInt64 OUT.paramFloat = 3 * IN.paramFloat OUT.paramString = IN.paramString.."foo" @@ -116,6 +118,7 @@ namespace ramses::internal elements.addElement(*m_nestedRenderGroup, "nestedRG"); auto rgBinding = engine.createRenderGroupBinding(*m_renderGroup, elements, "rg"); auto meshBinding = engine.createMeshNodeBinding(*m_meshNode, "mn"); + auto renderBufferBinding = engine.createRenderBufferBinding(*m_renderBuffer, "rb"); ramses::DataArray* animTimestamps = engine.createDataArray(std::vector{ 0.f, 0.5f, 1.f, 1.5f }); // will be interpreted as seconds ramses::DataArray* animKeyframes = engine.createDataArray(std::vector{ {0.f, 0.f, 0.f}, {0.f, 0.f, 180.f}, {0.f, 0.f, 100.f}, {0.f, 0.f, 360.f} }); @@ -156,6 +159,10 @@ namespace ramses::internal *script->getOutputs()->getChild("paramInt32"), *meshBinding->getInputs()->getChild("vertexOffset")); + engine.link( + *script->getOutputs()->getChild("paramInt32_2"), + *renderBufferBinding->getInputs()->getChild("width")); + engine.link( *timer->getOutputs()->getChild("ticker_us"), *script->getInputs()->getChild("paramInt64_2")); @@ -825,6 +832,24 @@ namespace ramses::internal EXPECT_EQ(45, instanceCount->get().value()); } + TEST_F(ALogicViewerLua, renderBufferBindingByName) + { + auto* width = getInput("rb", "width"); + auto* height = getInput("rb", "height"); + auto* sampleCount = getInput("rb", "sampleCount"); + //unlink input to avoid generating error for setting value for a linked input + unlinkInput(*width); + + EXPECT_EQ(Result(), loadLua(R"( + rlogic.renderBufferBindings.rb.IN.width.value = 42 + rlogic.renderBufferBindings.rb.IN.height.value = 43 + rlogic.renderBufferBindings.rb.IN.sampleCount.value = 44 + )")); + EXPECT_EQ(42, width->get().value()); + EXPECT_EQ(43, height->get().value()); + EXPECT_EQ(44, sampleCount->get().value()); + } + TEST_F(ALogicViewerLua, timerNodeByName) { auto* ticker = getInput("foo", "ticker_us"); @@ -876,26 +901,26 @@ namespace ramses::internal TEST_F(ALogicViewerLua, interfaceById) { auto* node = getNode("foo"); - ASSERT_EQ(10u, node->getSceneObjectId().getValue()); - EXPECT_EQ(Result(), loadLua(R"(rlogic.interfaces[10].IN.paramInt32.value = 42)")); + ASSERT_EQ(11u, node->getSceneObjectId().getValue()); + EXPECT_EQ(Result(), loadLua(R"(rlogic.interfaces[11].IN.paramInt32.value = 42)")); EXPECT_EQ(42, GetInput(node, "paramInt32")->get().value()); } TEST_F(ALogicViewerLua, scriptById) { auto* node = getNode("foo"); - ASSERT_EQ(11u, node->getSceneObjectId().getValue()); - EXPECT_EQ(Result(), loadLua(R"(rlogic.scripts[11].IN.paramInt64.value = 99)")); + ASSERT_EQ(12u, node->getSceneObjectId().getValue()); + EXPECT_EQ(Result(), loadLua(R"(rlogic.scripts[12].IN.paramInt64.value = 99)")); EXPECT_EQ(99, GetInput(node, "paramInt64")->get().value()); } TEST_F(ALogicViewerLua, nodeBindingById) { auto* node = getNode("foo"); - ASSERT_EQ(12u, node->getSceneObjectId().getValue()); + ASSERT_EQ(13u, node->getSceneObjectId().getValue()); auto* translation = GetInput(node, "translation"); EXPECT_EQ(Result(), loadLua(R"( - rlogic.nodeBindings[12].IN.translation.value = {1,2,3} + rlogic.nodeBindings[13].IN.translation.value = {1,2,3} )")); EXPECT_FLOAT_EQ(1.f, translation->get().value()[0]); EXPECT_FLOAT_EQ(2.f, translation->get().value()[1]); @@ -905,13 +930,13 @@ namespace ramses::internal TEST_F(ALogicViewerLua, appearanceBindingById) { auto* node = getNode("foo"); - ASSERT_EQ(13u, node->getSceneObjectId().getValue()); + ASSERT_EQ(14u, node->getSceneObjectId().getValue()); auto* floatUniform = GetInput(node, "floatUniform"); //unlink input to avoid generating error for setting value for a linked input unlinkInput(*floatUniform); EXPECT_EQ(Result(), loadLua(R"( - rlogic.appearanceBindings[13].IN.floatUniform.value = 9.1 + rlogic.appearanceBindings[14].IN.floatUniform.value = 9.1 )")); EXPECT_FLOAT_EQ(9.1f, floatUniform->get().value()); } @@ -919,10 +944,10 @@ namespace ramses::internal TEST_F(ALogicViewerLua, cameraBindingById) { auto* node = getNode("foo"); - ASSERT_EQ(14u, node->getSceneObjectId().getValue()); + ASSERT_EQ(15u, node->getSceneObjectId().getValue()); auto* frustum = GetInput(node, "frustum"); EXPECT_EQ(Result(), loadLua(R"( - rlogic.cameraBindings[14].IN.frustum.nearPlane.value = 0.93 + rlogic.cameraBindings[15].IN.frustum.nearPlane.value = 0.93 )")); EXPECT_FLOAT_EQ(0.93f, frustum->getChild("nearPlane")->get().value()); } @@ -930,10 +955,10 @@ namespace ramses::internal TEST_F(ALogicViewerLua, renderPassBindingById) { auto* rp = getNode("foo"); - ASSERT_EQ(15u, rp->getSceneObjectId().getValue()); + ASSERT_EQ(16u, rp->getSceneObjectId().getValue()); auto* renderOrder = GetInput(rp, "renderOrder"); EXPECT_EQ(Result(), loadLua(R"( - rlogic.renderPassBindings[15].IN.renderOrder.value = 42 + rlogic.renderPassBindings[16].IN.renderOrder.value = 42 )")); EXPECT_EQ(42, renderOrder->get().value()); } @@ -941,13 +966,13 @@ namespace ramses::internal TEST_F(ALogicViewerLua, renderGroupBindingById) { auto* rg = getNode("rg"); - ASSERT_EQ(18u, rg->getSceneObjectId().getValue()); + ASSERT_EQ(19u, rg->getSceneObjectId().getValue()); auto* renderOrder = GetInput(rg, "renderOrders")->getChild("nestedRG"); //unlink input to avoid generating error for setting value for a linked input unlinkInput(*renderOrder); EXPECT_EQ(Result(), loadLua(R"( - rlogic.renderGroupBindings[18].IN.renderOrders.nestedRG.value = 42 + rlogic.renderGroupBindings[19].IN.renderOrders.nestedRG.value = 42 )")); EXPECT_EQ(42, renderOrder->get().value()); } @@ -955,7 +980,7 @@ namespace ramses::internal TEST_F(ALogicViewerLua, meshNodeBindingById) { auto* mn = getNode("mn"); - ASSERT_EQ(19u, mn->getSceneObjectId().getValue()); + ASSERT_EQ(20u, mn->getSceneObjectId().getValue()); auto* vertexOffset = GetInput(mn, "vertexOffset"); auto* indexOffset = GetInput(mn, "indexOffset"); auto* indexCount = GetInput(mn, "indexCount"); @@ -965,10 +990,10 @@ namespace ramses::internal unlinkInput(*vertexOffset); EXPECT_EQ(Result(), loadLua(R"( - rlogic.meshNodeBindings[19].IN.vertexOffset.value = 42 - rlogic.meshNodeBindings[19].IN.indexOffset.value = 43 - rlogic.meshNodeBindings[19].IN.indexCount.value = 44 - rlogic.meshNodeBindings[19].IN.instanceCount.value = 45 + rlogic.meshNodeBindings[20].IN.vertexOffset.value = 42 + rlogic.meshNodeBindings[20].IN.indexOffset.value = 43 + rlogic.meshNodeBindings[20].IN.indexCount.value = 44 + rlogic.meshNodeBindings[20].IN.instanceCount.value = 45 )")); EXPECT_EQ(42, vertexOffset->get().value()); EXPECT_EQ(43, indexOffset->get().value()); @@ -976,13 +1001,34 @@ namespace ramses::internal EXPECT_EQ(45, instanceCount->get().value()); } + TEST_F(ALogicViewerLua, renderBufferBindingById) + { + auto* rb = getNode("rb"); + ASSERT_EQ(21u, rb->getSceneObjectId().getValue()); + auto* width = GetInput(rb, "width"); + auto* height = GetInput(rb, "height"); + auto* sampleCount = GetInput(rb, "sampleCount"); + + //unlink input to avoid generating error for setting value for a linked input + unlinkInput(*width); + + EXPECT_EQ(Result(), loadLua(R"( + rlogic.renderBufferBindings[21].IN.width.value = 42 + rlogic.renderBufferBindings[21].IN.height.value = 43 + rlogic.renderBufferBindings[21].IN.sampleCount.value = 44 + )")); + EXPECT_EQ(42, width->get().value()); + EXPECT_EQ(43, height->get().value()); + EXPECT_EQ(44, sampleCount->get().value()); + } + TEST_F(ALogicViewerLua, timerNodeById) { auto* node = getNode("foo"); - ASSERT_EQ(16u, node->getSceneObjectId().getValue()); + ASSERT_EQ(17u, node->getSceneObjectId().getValue()); auto* ticker = GetInput(node, "ticker_us"); EXPECT_EQ(Result(), loadLua(R"( - rlogic.timerNodes[16].IN.ticker_us.value = 19083 + rlogic.timerNodes[17].IN.ticker_us.value = 19083 )")); EXPECT_EQ(19083, ticker->get().value()); } @@ -994,8 +1040,8 @@ namespace ramses::internal unlinkInput(*getInput("foo", "anchorData2")); EXPECT_EQ(Result(), loadLua(R"( - rlogic.scripts.foo.IN.anchorData1.value = { rlogic.anchorPoints[17].OUT.viewportCoords.value[1], rlogic.anchorPoints[17].OUT.viewportCoords.value[2] } - rlogic.scripts.foo.IN.anchorData2.value = rlogic.anchorPoints[17].OUT.depth.value + rlogic.scripts.foo.IN.anchorData1.value = { rlogic.anchorPoints[18].OUT.viewportCoords.value[1], rlogic.anchorPoints[18].OUT.viewportCoords.value[2] } + rlogic.scripts.foo.IN.anchorData2.value = rlogic.anchorPoints[18].OUT.depth.value )")); auto* outScript = getNode("foo"); @@ -1007,13 +1053,13 @@ namespace ramses::internal TEST_F(ALogicViewerLua, animationNodeById) { auto* node = getNode("foo"); - ASSERT_EQ(22u, node->getSceneObjectId().getValue()); + ASSERT_EQ(24u, node->getSceneObjectId().getValue()); auto* progress = GetInput(node, "progress"); //unlink input to avoid generating error for setting value for a linked input unlinkInput(*progress); EXPECT_EQ(Result(), loadLua(R"( - rlogic.animationNodes[22].IN.progress.value = 198 + rlogic.animationNodes[24].IN.progress.value = 198 )")); EXPECT_FLOAT_EQ(198.f, progress->get().value()); } @@ -1021,7 +1067,7 @@ namespace ramses::internal TEST_F(ALogicViewerLua, animationNodeWrongId) { auto* node = getNode("foo"); - ASSERT_EQ(22u, node->getSceneObjectId().getValue()); + ASSERT_EQ(24u, node->getSceneObjectId().getValue()); const auto result = loadLua(R"(rlogic.animationNodes[89032].IN.progress.value = 198)"); EXPECT_THAT(result.getMessage(), testing::HasSubstr("attempt to index")); EXPECT_THAT(result.getMessage(), testing::HasSubstr("a nil value")); @@ -1075,6 +1121,6 @@ namespace ramses::internal EXPECT_EQ(2u, summary.getLinkActivations().maxValue); EXPECT_EQ(4u, summary.getNodesExecuted().size()); - EXPECT_EQ(7u, summary.getNodesSkippedExecution().size()); + EXPECT_EQ(8u, summary.getNodesSkippedExecution().size()); } } diff --git a/tests/unittests/tools/ramses-logic-viewer/LogicViewerTest.cpp b/tests/unittests/tools/ramses-viewer/LogicViewerTest.cpp similarity index 100% rename from tests/unittests/tools/ramses-logic-viewer/LogicViewerTest.cpp rename to tests/unittests/tools/ramses-viewer/LogicViewerTest.cpp diff --git a/tests/unittests/tools/ramses-logic-viewer/LogicViewerTestBase.cpp b/tests/unittests/tools/ramses-viewer/LogicViewerTestBase.cpp similarity index 100% rename from tests/unittests/tools/ramses-logic-viewer/LogicViewerTestBase.cpp rename to tests/unittests/tools/ramses-viewer/LogicViewerTestBase.cpp diff --git a/tests/unittests/tools/ramses-logic-viewer/LogicViewerTestBase.h b/tests/unittests/tools/ramses-viewer/LogicViewerTestBase.h similarity index 96% rename from tests/unittests/tools/ramses-logic-viewer/LogicViewerTestBase.h rename to tests/unittests/tools/ramses-viewer/LogicViewerTestBase.h index b2afa9066..967fa4fd3 100644 --- a/tests/unittests/tools/ramses-logic-viewer/LogicViewerTestBase.h +++ b/tests/unittests/tools/ramses-viewer/LogicViewerTestBase.h @@ -25,6 +25,7 @@ #include "ramses/client/logic/AnimationNode.h" #include "ramses/client/logic/AnchorPoint.h" #include "ramses/client/logic/SkinBinding.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/ramses-client.h" #include @@ -143,6 +144,7 @@ namespace ramses::internal ramses::RenderGroup* m_renderGroup = { m_scene->createRenderGroup() }; ramses::RenderGroup* m_nestedRenderGroup = { m_scene->createRenderGroup() }; ramses::MeshNode* m_meshNode = { m_scene->createMeshNode() }; + ramses::RenderBuffer* m_renderBuffer = { m_scene->createRenderBuffer(1u, 2u, ramses::ERenderBufferFormat::R16F, ramses::ERenderBufferAccessMode::ReadWrite, 3u) }; ramses::LogicEngine* m_logic = { m_scene->createLogicEngine() }; LogicViewer viewer{ *m_logic, doScreenshot }; diff --git a/tests/unittests/tools/ramses-viewer/ValidationCacheTest.cpp b/tests/unittests/tools/ramses-viewer/ValidationCacheTest.cpp new file mode 100644 index 000000000..639a3ff14 --- /dev/null +++ b/tests/unittests/tools/ramses-viewer/ValidationCacheTest.cpp @@ -0,0 +1,134 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#include "ValidationCache.h" +#include "gtest/gtest.h" +#include "gmock/gmock.h" +#include "ramses/client/Scene.h" +#include "impl/ValidationReportImpl.h" + +namespace ramses::internal +{ + class DummyObjectImpl : public SceneObjectImpl + { + public: + explicit DummyObjectImpl(SceneImpl& scene, std::string_view name) + : SceneObjectImpl(scene, ERamsesObjectType::MeshNode, name) + { + } + + void deinitializeFrameworkData() override {} + + void onValidate(ValidationReportImpl& report) const override + { + for (auto& issue : issuesToReport) + report.add(issue.type, issue.message, issue.object); + } + + std::vector issuesToReport; + }; + + class DummyObject : public SceneObject + { + public: + explicit DummyObject(SceneImpl& scene, std::string_view name = {}) + : SceneObject(std::make_unique(scene, name)) + , impl(static_cast(SceneObject::impl())) + { + } + DummyObjectImpl& impl; + }; + + + class AValidationCache : public testing::Test + { + protected: + RamsesFrameworkConfig frameworkConfig{EFeatureLevel_Latest}; + SceneConfig sceneConfig{sceneId_t(1234)}; + RamsesFramework framework{frameworkConfig}; + RamsesClient* client = framework.createClient("client"); + Scene* scene = client->createScene(sceneConfig); + DummyObject objA{scene->impl(), "A"}; + DummyObject objB{scene->impl(), "B"}; + DummyObject objC{scene->impl(), "C"}; + ValidationReport report; + }; + + TEST_F(AValidationCache, empty) + { + ValidationCache cache(report); + EXPECT_EQ(0u, cache.getAllIssues().size()); + auto rangeA = cache.getIssues(objA.impl); + EXPECT_EQ(0, rangeA.second - rangeA.first); + EXPECT_FALSE(cache.getIssueType(objA.impl).has_value()); + auto rangeB = cache.getIssues(objB.impl); + EXPECT_EQ(0, rangeB.second - rangeB.first); + EXPECT_FALSE(cache.getIssueType(objB.impl).has_value()); + } + + TEST_F(AValidationCache, singleWarning) + { + report.impl().add(EIssueType::Warning, "msg1", &objA); + ValidationCache cache(report); + EXPECT_EQ(1u, cache.getAllIssues().size()); + auto rangeA = cache.getIssues(objA.impl); + EXPECT_EQ(1, rangeA.second - rangeA.first); + EXPECT_EQ(EIssueType::Warning, *cache.getIssueType(objA.impl)); + auto rangeB = cache.getIssues(objB.impl); + EXPECT_EQ(0, rangeB.second - rangeB.first); + EXPECT_FALSE(cache.getIssueType(objB.impl).has_value()); + } + + TEST_F(AValidationCache, reordersUnsortedReport) + { + report.impl().add(EIssueType::Warning, "msgC1", &objC); + report.impl().add(EIssueType::Warning, "msgA1", &objA); + report.impl().add(EIssueType::Warning, "msgB1", &objB); + report.impl().add(EIssueType::Error, "msgA2", &objA); + report.impl().add(EIssueType::Warning, "msgA3", &objA); + report.impl().add(EIssueType::Warning, "msgB2", &objB); + + ValidationCache cache(report); + EXPECT_EQ(6u, cache.getAllIssues().size()); + auto rangeA = cache.getIssues(objA.impl); + EXPECT_EQ(3, rangeA.second - rangeA.first); + EXPECT_EQ("msgA1", rangeA.first->message); + EXPECT_EQ("msgA2", (++rangeA.first)->message); + EXPECT_EQ("msgA3", (++rangeA.first)->message); + EXPECT_EQ(EIssueType::Error, *cache.getIssueType(objA.impl)); + + auto rangeB = cache.getIssues(objB.impl); + EXPECT_EQ(2, rangeB.second - rangeB.first); + EXPECT_EQ("msgB1", rangeB.first->message); + EXPECT_EQ("msgB2", (++rangeB.first)->message); + EXPECT_EQ(EIssueType::Warning, *cache.getIssueType(objB.impl)); + + auto rangeC = cache.getIssues(objC.impl); + EXPECT_EQ(1, rangeC.second - rangeC.first); + EXPECT_EQ("msgC1", rangeC.first->message); + EXPECT_EQ(EIssueType::Warning, *cache.getIssueType(objC.impl)); + } + + TEST_F(AValidationCache, usesValidationToFindDependentIssues) + { + // objA depends on objC + report.impl().add(EIssueType::Warning, "msgC1", &objC); + objA.impl.issuesToReport = report.impl().getIssues(); + + ValidationCache cache(report); + EXPECT_EQ(EIssueType::Warning, *cache.getIssueType(objA.impl)); + EXPECT_EQ(EIssueType::Warning, *cache.getIssueType(objA.impl)); // from cache + auto rangeA = cache.getIssues(objA.impl); + EXPECT_EQ(0, rangeA.second - rangeA.first); // only dependent issues + + EXPECT_EQ(EIssueType::Warning, *cache.getIssueType(objC.impl)); + EXPECT_EQ(EIssueType::Warning, *cache.getIssueType(objC.impl)); // from cache + auto rangeC = cache.getIssues(objC.impl); + EXPECT_EQ(1, rangeC.second - rangeC.first); + } +} diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 3df1b4ba6..ac31731cb 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -9,15 +9,12 @@ add_subdirectory(ramses-daemon) if(ramses-sdk_ENABLE_LOGIC) - add_subdirectory(ramses-logic-viewer) - if(ramses-sdk_BUILD_FULL_SHARED_LIB) - add_subdirectory(test-asset-producer) - endif() + add_subdirectory(test-asset-producer) + add_subdirectory(ramses-viewer) endif() if(TARGET ramses-renderer) add_subdirectory(ramses-renderer-standalone) add_subdirectory(ramses-imgui) - add_subdirectory(ramses-scene-viewer) add_subdirectory(ramses-stream-viewer) endif() diff --git a/tools/ramses-daemon/main.cpp b/tools/ramses-daemon/main.cpp index abc129d68..d7bc1a920 100644 --- a/tools/ramses-daemon/main.cpp +++ b/tools/ramses-daemon/main.cpp @@ -48,8 +48,8 @@ int main(int argc, const char* argv[]) ramsh.start(); LOG_INFO(CONTEXT_CLIENT, "Daemon::main Starting Ramses Daemon"); - LOG_INFO(CONTEXT_CLIENT, "Daemon::main Version: " << ::ramses_sdk::RAMSES_SDK_RAMSES_VERSION << - " Hash:" << ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_HASH << " Commit:" << ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_COUNT); + LOG_INFO(CONTEXT_CLIENT, "Daemon::main Version: {} Hash:{} Commit:{}", + ::ramses_sdk::RAMSES_SDK_RAMSES_VERSION, ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_HASH, ::ramses_sdk::RAMSES_SDK_GIT_COMMIT_COUNT); PlatformLock frameworkLock; StatisticCollectionFramework statisticCollection; diff --git a/tools/ramses-imgui/include/ImguiClientHelper.h b/tools/ramses-imgui/include/ImguiClientHelper.h index 594a82d36..f4a43956a 100644 --- a/tools/ramses-imgui/include/ImguiClientHelper.h +++ b/tools/ramses-imgui/include/ImguiClientHelper.h @@ -127,6 +127,7 @@ namespace ramses::internal uint32_t m_screenshotHeight = 0U; bool m_screenshotSaved = false; bool m_isRunning = true; + ImGuiContext* m_context = nullptr; }; inline ramses::Scene* ImguiClientHelper::getScene() diff --git a/tools/ramses-imgui/src/ImguiClientHelper.cpp b/tools/ramses-imgui/src/ImguiClientHelper.cpp index b98378ffc..f26df70ec 100644 --- a/tools/ramses-imgui/src/ImguiClientHelper.cpp +++ b/tools/ramses-imgui/src/ImguiClientHelper.cpp @@ -135,7 +135,10 @@ namespace ramses::internal inputUV = effect->findAttributeInput("a_texcoord"); inputColor = effect->findAttributeInput("Color"); - ImGui::CreateContext(); + if (!ImGui::GetCurrentContext()) + { + m_context = ImGui::CreateContext(); + } ImGuiIO& io = ImGui::GetIO(); io.DisplaySize.x = static_cast(width); io.DisplaySize.y = static_cast(height); @@ -172,7 +175,8 @@ namespace ramses::internal int textureheight = 0; unsigned char* pixels = nullptr; io.Fonts->GetTexDataAsRGBA32(&pixels, &texturewidth, &textureheight); - const std::vector mipLevelData{ MipLevelData(static_cast(texturewidth * textureheight * 4), pixels) }; + auto pixelBytes = reinterpret_cast(pixels); + const std::vector mipLevelData{ MipLevelData(pixelBytes, pixelBytes + texturewidth * textureheight * 4) }; auto texture = m_imguiscene->createTexture2D(ramses::ETextureFormat::RGBA8, texturewidth, textureheight, mipLevelData); sampler = m_imguiscene->createTextureSampler( ramses::ETextureAddressMode::Repeat, @@ -191,7 +195,8 @@ namespace ramses::internal ImguiClientHelper::~ImguiClientHelper() { - ImGui::DestroyContext(); + if (m_context) + ImGui::DestroyContext(m_context); } void ImguiClientHelper::setDisplayId(ramses::displayId_t displayId) diff --git a/tools/ramses-imgui/src/ImguiImageCache.cpp b/tools/ramses-imgui/src/ImguiImageCache.cpp index d77fdf583..37e484a83 100644 --- a/tools/ramses-imgui/src/ImguiImageCache.cpp +++ b/tools/ramses-imgui/src/ImguiImageCache.cpp @@ -26,7 +26,7 @@ namespace ramses::internal if (it == m_imageBuffers.end()) { const ramses::TextureSwizzle textureSwizzle; - std::vector mipLevelData{ramses::MipLevelData(static_cast(mm.data.size()), mm.data.data())}; + std::vector mipLevelData{ mm.data }; auto* texture = m_scene->createTexture2D(TextureUtils::GetTextureFormatFromInternal(format), mm.width, mm.height, @@ -75,7 +75,7 @@ namespace ramses::internal for (const auto& mipSize : res->getMipDataSizes()) { assert(data + mipSize <= blob.data() + blob.size()); - mipLevelData.emplace_back(mipSize, reinterpret_cast(data)); + mipLevelData.emplace_back(data, data + mipSize); data += mipSize; } diff --git a/tools/ramses-logic-viewer/Arguments.h b/tools/ramses-logic-viewer/Arguments.h deleted file mode 100644 index dafdcf636..000000000 --- a/tools/ramses-logic-viewer/Arguments.h +++ /dev/null @@ -1,109 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2021 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -#include "internal/logic/StdFilesystemWrapper.h" -#include -#include -#include -#include -#include "ramses/framework/RamsesFrameworkTypes.h" -#include "ramses/framework/RamsesFrameworkTypes.h" -#include "ramses-sdk-build-config.h" - -class Arguments -{ -public: - void registerOptions(CLI::App& cli) - { - cli.description(R"( -Loads and shows a ramses scene from the . - is auto-resolved if matching file with *.lua extension is found in the same path as . (Explicit argument overrides autodetection.) -)"); - cli.add_option("ramsesfile", m_sceneFile, "Ramses scene file")->required()->check(CLI::ExistingFile); - cli.add_option("luafile,--lua", m_luaFile, "Lua configuration file")->check(CLI::ExistingFile); - auto exec = cli.add_option("--exec", m_luaFunction, "Calls the given lua function and exits."); - cli.add_option("--exec-lua", m_exec, "Calls the given lua code and exits.")->excludes(exec); - auto setWriteConfig = [&](const std::string& filename) { - m_luaFile = filename; - m_writeConfig = true; - }; - cli.add_option_function("--write-config", setWriteConfig, "Writes the default lua configuration file and exits") - ->expected(0, 1) - ->type_name("[FILE]") - ->excludes(exec); - cli.add_flag("--offscreen", m_offscreen, "Renders the scene to an offscreen buffer. Screenshot apply to the offscreen buffer."); - cli.set_version_flag("--version", ramses_sdk::RAMSES_SDK_RAMSES_VERSION); - - std::vector> loglevelMap{{"off", ramses::ELogLevel::Off}, - {"fatal", ramses::ELogLevel::Fatal}, - {"error", ramses::ELogLevel::Error}, - {"warn", ramses::ELogLevel::Warn}, - {"info", ramses::ELogLevel::Info}, - {"debug", ramses::ELogLevel::Debug}, - {"trace", ramses::ELogLevel::Trace}}; - cli.add_option("--log-level-console", m_ramsesLogLevel, "Sets log level for console messages.")->transform(CLI::CheckedTransformer(loglevelMap))->default_val(m_ramsesLogLevel); - } - - const std::string& sceneFile() const - { - return m_sceneFile; - } - - const std::string& luaFile() const - { - if (m_luaFile.empty()) - { - m_luaFile = ReplaceExtension(m_sceneFile, "lua"); - } - return m_luaFile; - } - - const std::string& luaFunction() const - { - return m_luaFunction; - } - - const std::string& exec() const - { - return m_exec; - } - - bool offscreen() const - { - return m_offscreen; - } - - bool writeConfig() const - { - return m_writeConfig; - } - - ramses::ELogLevel ramsesLogLevel() const - { - return m_ramsesLogLevel; - } - -private: - [[nodiscard]] static std::string ReplaceExtension(fs::path filename, const std::string& extension) - { - std::string retval; - filename.replace_extension(extension); - return filename.string(); - } - - std::string m_sceneFile; - mutable std::string m_luaFile; - std::string m_luaFunction; - std::string m_exec; - bool m_offscreen = false; - bool m_writeConfig = false; - ramses::ELogLevel m_ramsesLogLevel = ramses::ELogLevel::Error; -}; - diff --git a/tools/ramses-logic-viewer/CMakeLists.txt b/tools/ramses-logic-viewer/CMakeLists.txt deleted file mode 100644 index 9cf2eeec7..000000000 --- a/tools/ramses-logic-viewer/CMakeLists.txt +++ /dev/null @@ -1,69 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (C) 2021 BMW AG -# ------------------------------------------------------------------------- -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at https://mozilla.org/MPL/2.0/. -# ------------------------------------------------------------------------- - -set(logic_viewer_header - LogicViewerHeadlessApp.h - LogicViewerApp.h - LogicViewer.h - LogicViewerLog.h - LogicViewerSettings.h - LogicViewerLuaTypes.h - UpdateReportSummary.h - Arguments.h - SceneSetup.h) - -set(logic_viewer_src - LogicViewerHeadlessApp.cpp - LogicViewerApp.cpp - LogicViewer.cpp - LogicViewerLog.cpp - LogicViewerSettings.cpp - LogicViewerLuaTypes.cpp) - -add_library(ramses-logic-viewer-lib INTERFACE) -target_sources(ramses-logic-viewer-lib INTERFACE ${logic_viewer_header}) -target_sources(ramses-logic-viewer-lib INTERFACE ${logic_viewer_src}) -target_link_libraries(ramses-logic-viewer-lib INTERFACE imgui fmt::fmt sol2::sol2 lua::lua ramses-framework-cli ramses-client) - -add_library(ramses-logic-viewer-gui-lib INTERFACE) -target_sources(ramses-logic-viewer-gui-lib INTERFACE - LogicViewerGuiApp.h - LogicViewerGui.h - LogicViewerGuiApp.cpp - LogicViewerGui.cpp - ImguiClientHelper.h - ImguiClientHelper.cpp) -target_link_libraries(ramses-logic-viewer-gui-lib INTERFACE ramses-logic-viewer-lib) - - -if(ramses-sdk_BUILD_FULL_SHARED_LIB) - createModule( - NAME ramses-logic-viewer - TYPE BINARY - ENABLE_INSTALL ${ramses-sdk_ENABLE_INSTALL} - SRC_FILES main.cpp - DEPENDENCIES ramses-logic-viewer-gui-lib - ramses-shared-lib - ) -endif() - -if(ramses-sdk_BUILD_HEADLESS_SHARED_LIB) - createModule( - NAME ramses-logic-viewer-headless - TYPE BINARY - ENABLE_INSTALL ON - SRC_FILES main_headless.cpp - DEPENDENCIES ramses-logic-viewer-lib ramses-shared-lib-headless - ) - - if (ramses-sdk_ENABLE_INSTALL) - install( - TARGETS ramses-logic-viewer-headless - DESTINATION ${RAMSES_INSTALL_RUNTIME_PATH}) - endif() -endif() diff --git a/tools/ramses-logic-viewer/ImguiClientHelper.cpp b/tools/ramses-logic-viewer/ImguiClientHelper.cpp deleted file mode 100644 index fe59a1a0c..000000000 --- a/tools/ramses-logic-viewer/ImguiClientHelper.cpp +++ /dev/null @@ -1,542 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2020 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "ImguiClientHelper.h" - -namespace ramses -{ - namespace - { - const char* const ImguiFragShader = R"GLSL( - #version 100 - uniform sampler2D textureSampler; - - varying lowp vec2 v_texcoord; - varying lowp vec4 Frag_Color; - void main(void) - { - gl_FragColor = texture2D(textureSampler, v_texcoord.st)*Frag_Color; - })GLSL"; - - const char* const ImguiVertShader = R"GLSL( - #version 100 - uniform highp mat4 mvpMatrix; - attribute vec2 a_position; - attribute vec2 a_texcoord; - attribute vec4 Color; - varying vec2 v_texcoord; - varying vec4 Frag_Color; - void main(void) - { - gl_Position = mvpMatrix*vec4(a_position.xy, 0.0, 1.0); - v_texcoord = a_texcoord; - Frag_Color = Color; - })GLSL"; - - uint32_t GetSpecialChar(ramses::EKeyCode keyCode, const bool isShift) - { - switch (keyCode) - { - case ramses::EKeyCode_Space: - return ' '; - case ramses::EKeyCode_Numpad_Subtract: - case ramses::EKeyCode_Minus: - return isShift ? '_' : '-'; - case ramses::EKeyCode_Slash: - return isShift ? '?' : '/'; - case ramses::EKeyCode_Numpad_Decimal: - return '.'; - case ramses::EKeyCode_Period: - return isShift ? '>' : '.'; - case ramses::EKeyCode_Comma: - return isShift ? '<' : ','; - case ramses::EKeyCode_Backslash: - return isShift ? '|' : '\\'; - case ramses::EKeyCode_LeftBracket: - return isShift ? '{' : '['; - case ramses::EKeyCode_RightBracket: - return isShift ? '}' : ']'; - case ramses::EKeyCode_Equals: - return isShift ? '+' : '='; - case ramses::EKeyCode_Semicolon: - return isShift ? ':' : ';'; - case ramses::EKeyCode_Apostrophe: - return isShift ? '@' : '\''; - case ramses::EKeyCode_Grave: - return '`'; - case ramses::EKeyCode_NumberSign: - return isShift ? '~' : '#'; - default: - break; - } - - return 0U; - } - - // emulates an English keyboard for the available ramses key events - // (ramses (on Windows) does not consider keymaps, but sends virtual key events - uint32_t GetCharCode(KeyModifiers keyModifiers, ramses::EKeyCode keyCode) - { - const bool isShift = keyModifiers.isSet(ramses::EKeyModifier::Shift); - uint32_t retval = 0U; - if (ramses::EKeyCode_0 <= keyCode && keyCode <= ramses::EKeyCode_9) - { - const char* shift = ")!\"$$%^&*("; - // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - retval = (isShift) ? shift[keyCode - ramses::EKeyCode_0] : ('0' + keyCode - ramses::EKeyCode_0); - } - else if (ramses::EKeyCode_A <= keyCode && keyCode <= ramses::EKeyCode_Z) - { - retval = (isShift) ? ('A' + keyCode - ramses::EKeyCode_A) : ('a' + keyCode - ramses::EKeyCode_A); - } - else if (ramses::EKeyCode_Numpad_0 <= keyCode && keyCode <= ramses::EKeyCode_Numpad_9) - { - retval = ('0' + keyCode - ramses::EKeyCode_Numpad_0); - } - else - { - retval = GetSpecialChar(keyCode, isShift); - } - return retval; - } - } // namespace - - ImguiClientHelper::ImguiClientHelper(ramses::RamsesClient& client, uint32_t width, uint32_t height, ramses::sceneId_t sceneid) - { - assert(ImGui::GetCurrentContext() != nullptr); // context should be already created - ramses::SceneConfig local(sceneid); - m_imguiscene = client.createScene(local, "imgui scene"); - - imguicamera = m_imguiscene->createOrthographicCamera("imgui camera"); - - imguicamera->setFrustum(0.0f, float(width), -float(height), 0.0f, 0.1f, 1.0f); - imguicamera->setViewport(0, 0, width, height); - imguicamera->translate({0.0f, 0.0f, 0.5f}); - imguicamera->scale({1.0, -1.0f, 1.0f}); - - ramses::RenderPass* renderPass = m_imguiscene->createRenderPass("imgui render pass"); - renderPass->setClearFlags(ramses::EClearFlag::None); - renderPass->setCamera(*imguicamera); - renderGroup = m_imguiscene->createRenderGroup(); - renderPass->addRenderGroup(*renderGroup); - ramses::EffectDescription effectDescImgui; - effectDescImgui.setFragmentShader(ImguiFragShader); - effectDescImgui.setVertexShader(ImguiVertShader); - effectDescImgui.setUniformSemantic("mvpMatrix", ramses::EEffectUniformSemantic::ModelViewProjectionMatrix); - - effect = m_imguiscene->createEffect(effectDescImgui); - - textureInput = effect->findUniformInput("textureSampler"); - inputPosition = effect->findAttributeInput("a_position"); - inputUV = effect->findAttributeInput("a_texcoord"); - inputColor = effect->findAttributeInput("Color"); - - ImGuiIO& io = ImGui::GetIO(); - io.DisplaySize.x = static_cast(width); - io.DisplaySize.y = static_cast(height); - io.MousePos = ImVec2(-FLT_MAX, -FLT_MAX); - io.MouseDown[0] = false; - io.MouseDown[1] = false; - io.MouseDown[2] = false; - io.MouseDown[3] = false; - io.MouseDown[4] = false; - io.KeyMap[ImGuiKey_Tab] = ramses::EKeyCode_Tab; - io.KeyMap[ImGuiKey_LeftArrow] = ramses::EKeyCode_Left; - io.KeyMap[ImGuiKey_RightArrow] = ramses::EKeyCode_Right; - io.KeyMap[ImGuiKey_UpArrow] = ramses::EKeyCode_Up; - io.KeyMap[ImGuiKey_DownArrow] = ramses::EKeyCode_Down; - io.KeyMap[ImGuiKey_PageUp] = ramses::EKeyCode_PageUp; - io.KeyMap[ImGuiKey_PageDown] = ramses::EKeyCode_PageDown; - io.KeyMap[ImGuiKey_Home] = ramses::EKeyCode_Home; - io.KeyMap[ImGuiKey_End] = ramses::EKeyCode_End; - io.KeyMap[ImGuiKey_Insert] = ramses::EKeyCode_Insert; - io.KeyMap[ImGuiKey_Delete] = ramses::EKeyCode_Delete; - io.KeyMap[ImGuiKey_Backspace] = ramses::EKeyCode_Backspace; - io.KeyMap[ImGuiKey_Space] = ramses::EKeyCode_Space; - io.KeyMap[ImGuiKey_Enter] = ramses::EKeyCode_Return; - io.KeyMap[ImGuiKey_Escape] = ramses::EKeyCode_Escape; - io.KeyMap[ImGuiKey_KeyPadEnter] = ramses::EKeyCode_Numpad_Enter; - io.KeyMap[ImGuiKey_A] = ramses::EKeyCode_A; - io.KeyMap[ImGuiKey_C] = ramses::EKeyCode_C; - io.KeyMap[ImGuiKey_V] = ramses::EKeyCode_V; - io.KeyMap[ImGuiKey_X] = ramses::EKeyCode_X; - io.KeyMap[ImGuiKey_Y] = ramses::EKeyCode_Y; - io.KeyMap[ImGuiKey_Z] = ramses::EKeyCode_Z; - - int texturewidth = 0; - int textureheight = 0; - unsigned char* pixels = nullptr; - io.Fonts->GetTexDataAsRGBA32(&pixels, &texturewidth, &textureheight); - const std::vector mipLevelData{ MipLevelData(static_cast(texturewidth * textureheight * 4), pixels) }; - auto texture = m_imguiscene->createTexture2D(ramses::ETextureFormat::RGBA8, texturewidth, textureheight, mipLevelData); - sampler = m_imguiscene->createTextureSampler( - ramses::ETextureAddressMode::Repeat, - ramses::ETextureAddressMode::Repeat, - ramses::ETextureSamplingMethod::Linear, - ramses::ETextureSamplingMethod::Linear, - *texture); - - // At this point you've got the texture data and you need to upload that your your graphic system: - // After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'. - // This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID. - io.Fonts->TexID = sampler; - m_imguiscene->publish(ramses::EScenePublicationMode::LocalOnly); - m_imguiscene->flush(); - } - - ImguiClientHelper::~ImguiClientHelper() = default; - - void ImguiClientHelper::setDisplayId(ramses::displayId_t displayId) - { - m_displayId = displayId; - } - - void ImguiClientHelper::draw() - { - // cleanup previous frame/objects - for (auto m : todeleteMeshes) - { - m_imguiscene->destroy(*m); - } - todeleteMeshes.clear(); - for (auto m : todeleteRes) - { - m_imguiscene->destroy(*m); - } - todeleteRes.clear(); - renderGroup->removeAllRenderables(); - - // let imgui update itself - ImGui::Render(); - - // convert all imgui data to ramses objects - int meshnr = 1; - ImDrawData* draw_data = ImGui::GetDrawData(); - for (int n = 0; n < draw_data->CmdListsCount; n++) - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) C-style array in 3rd party code. Bounds are checked by loop condition - const ImDrawList* cmd_list = draw_data->CmdLists[n]; - const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; - auto ramsesind = m_imguiscene->createArrayResource(cmd_list->IdxBuffer.Size, idx_buffer); - todeleteRes.push_back(ramsesind); - unsigned int idx = 0U; - std::vector positions; - std::vector uv; - std::vector color; - for (auto& v : cmd_list->VtxBuffer) - { - positions.emplace_back(v.pos.x, v.pos.y); - uv.emplace_back(v.uv.x, v.uv.y); - - const auto alpha = (v.col >> 24U) & 0xFFU; - const auto blue = (v.col >> 16U) & 0xFFU; - const auto green = (v.col >> 8U) & 0xFFU; - const auto red = v.col & 0xFFU; - color.emplace_back( - static_cast(red) / 255.0f, - static_cast(green) / 255.0f, - static_cast(blue) / 255.0f, - static_cast(alpha) / 255.0f); - } - auto ramsespositions = m_imguiscene->createArrayResource(cmd_list->VtxBuffer.Size, positions.data()); - auto ramsesuv = m_imguiscene->createArrayResource(cmd_list->VtxBuffer.Size, uv.data()); - auto ramsescolor = m_imguiscene->createArrayResource(cmd_list->VtxBuffer.Size, color.data()); - todeleteRes.push_back(ramsespositions); - todeleteRes.push_back(ramsesuv); - todeleteRes.push_back(ramsescolor); - auto geobinding = m_imguiscene->createGeometry(*effect); - todeleteMeshes.push_back(geobinding); - - geobinding->setInputBuffer(*inputPosition, *ramsespositions); - geobinding->setInputBuffer(*inputUV, *ramsesuv); - geobinding->setInputBuffer(*inputColor, *ramsescolor); - geobinding->setIndices(*ramsesind); - for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++) - { - const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i]; - ramses::Appearance* appearance = m_imguiscene->createAppearance(*effect, "triangle appearance"); - todeleteMeshes.push_back(appearance); - appearance->setBlendingFactors(ramses::EBlendFactor::SrcAlpha, ramses::EBlendFactor::OneMinusSrcAlpha, ramses::EBlendFactor::One, ramses::EBlendFactor::One); - appearance->setBlendingOperations(ramses::EBlendOperation::Add, ramses::EBlendOperation::Add); - appearance->setDepthFunction(ramses::EDepthFunc::Disabled); - appearance->setDepthWrite(ramses::EDepthWrite::Disabled); - appearance->setCullingMode(ramses::ECullMode::Disabled); - appearance->setInputTexture(*textureInput, *static_cast(pcmd->TextureId)); - auto mesh = m_imguiscene->createMeshNode(); - todeleteMeshes.push_back(mesh); - mesh->setGeometry(*geobinding); - mesh->setAppearance(*appearance); - const ImVec2 pos = draw_data->DisplayPos; - const ImVec2 displaysize = draw_data->DisplaySize; - appearance->setScissorTest(ramses::EScissorTest::Enabled, - static_cast(pcmd->ClipRect.x - pos.x), - static_cast(displaysize.y - pcmd->ClipRect.w - pos.y), - static_cast(pcmd->ClipRect.z - pos.x - pcmd->ClipRect.x - pos.x), - static_cast(pcmd->ClipRect.w - pos.y - pcmd->ClipRect.y - pos.y)); - mesh->setStartIndex(idx); - mesh->setIndexCount(pcmd->ElemCount); - renderGroup->addMeshNode(*mesh, meshnr++); - // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) C-style array in 3rd party code. - idx_buffer += pcmd->ElemCount; - idx += pcmd->ElemCount; - } - } - - // apply new version of imgui scene - m_imguiscene->flush(); - } - - void ImguiClientHelper::sceneStateChanged(ramses::sceneId_t sceneId, ramses::RendererSceneState state) - { - m_scenes[sceneId].state = state; - } - - void ImguiClientHelper::sceneFlushed(ramses::sceneId_t sceneId, ramses::sceneVersionTag_t sceneVersion) - { - m_scenes[sceneId].version = sceneVersion; - } - - void ImguiClientHelper::offscreenBufferCreated(ramses::displayId_t /*displayId_t*/, ramses::displayBufferId_t offscreenBufferId, ramses::ERendererEventResult result) - { - if (ramses::ERendererEventResult::Failed != result) - { - m_offscreenBuffers.insert(offscreenBufferId); - } - } - - void ImguiClientHelper::offscreenBufferLinked(ramses::displayBufferId_t /*offscreenBufferId*/, ramses::sceneId_t consumerScene, ramses::dataConsumerId_t /*consumerId*/, bool success) - { - if (success) - { - m_scenesConsumingOffscreenBuffer[consumerScene].state = ramses::RendererSceneState::Unavailable; - } - } - - void ImguiClientHelper::displayCreated(ramses::displayId_t displayId, ramses::ERendererEventResult result) - { - if (ramses::ERendererEventResult::Failed != result) - { - m_displays.insert(displayId); - } - else - { - m_isRunning = false; - } - } - - void ImguiClientHelper::displayDestroyed(ramses::displayId_t displayId, ramses::ERendererEventResult result) - { - if (ramses::ERendererEventResult::Failed != result) - { - m_displays.erase(displayId); - } - else - { - m_isRunning = false; - } - } - - void ImguiClientHelper::mouseEvent(ramses::displayId_t displayId, ramses::EMouseEvent eventType, int32_t mousePosX, int32_t mousePosY) - { - if (!m_displayId.isValid() || displayId == m_displayId) - { - ImGuiIO& io = ImGui::GetIO(); - io.MousePos = {static_cast(mousePosX), static_cast(mousePosY)}; - switch (eventType) - { - case ramses::EMouseEvent::LeftButtonUp: - io.MouseDown[0] = false; - m_clickEvent = {mousePosX, mousePosY}; - break; - case ramses::EMouseEvent::LeftButtonDown: - io.MouseDown[0] = true; - break; - case ramses::EMouseEvent::WheelUp: - io.MouseWheel = 1; - break; - case ramses::EMouseEvent::WheelDown: - io.MouseWheel = -1; - break; - case ramses::EMouseEvent::RightButtonDown: - io.MouseDown[1] = true; - break; - case ramses::EMouseEvent::RightButtonUp: - io.MouseDown[1] = false; - break; - - default: - break; - } - } - } - - void ImguiClientHelper::keyEvent(ramses::displayId_t displayId, ramses::EKeyEvent eventType, ramses::KeyModifiers keyModifiers, ramses::EKeyCode keyCode) - { - if (!m_displayId.isValid() || displayId == m_displayId) - { - ImGuiIO& io = ImGui::GetIO(); - const bool pressed = (eventType == ramses::EKeyEvent::Pressed); - io.KeysDown[keyCode] = pressed; - - switch (keyCode) - { - case ramses::EKeyCode_ControlLeft: - case ramses::EKeyCode_ControlRight: - io.KeyCtrl = pressed; - return; - case ramses::EKeyCode_ShiftLeft: - case ramses::EKeyCode_ShiftRight: - io.KeyShift = pressed; - return; - case ramses::EKeyCode_AltLeft: - case ramses::EKeyCode_AltRight: - io.KeyAlt = pressed; - return; - case ramses::EKeyCode_WindowsLeft: - case ramses::EKeyCode_WindowsRight: - io.KeySuper = pressed; - return; - default: - break; - } - - if (pressed) - { - const uint32_t charCode = GetCharCode(keyModifiers, keyCode); - if (charCode != 0U) - io.AddInputCharacter(charCode); - } - } - } - - void ImguiClientHelper::windowResized(ramses::displayId_t displayId, uint32_t width, uint32_t height) - { - if (!m_displayId.isValid() || displayId == m_displayId) - { - imguicamera->setFrustum(0.0f, float(width), -float(height), 0.0f, 0.1f, 1.0f); - imguicamera->setViewport(0, 0, width, height); - ImGuiIO& io = ImGui::GetIO(); - io.DisplaySize.x = static_cast(width); - io.DisplaySize.y = static_cast(height); - } - } - - void ImguiClientHelper::windowClosed(ramses::displayId_t /*displayId*/) - { - m_isRunning = false; - } - - void ImguiClientHelper::framebufferPixelsRead(const uint8_t* pixelData, - const uint32_t pixelDataSize, - ramses::displayId_t displayId, - ramses::displayBufferId_t displayBuffer, - ramses::ERendererEventResult result) - { - static_cast(displayId); - static_cast(displayBuffer); - if (!m_screenshot.empty()) - { - m_screenshotSaved = false; - if (result == ramses::ERendererEventResult::Ok) - { - std::vector buffer; - // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-pointer-arithmetic) - buffer.insert(buffer.end(), &pixelData[0], &pixelData[pixelDataSize]); - m_screenshotSaved = ramses::RamsesUtils::SaveImageBufferToPng(m_screenshot, buffer, m_screenshotWidth, m_screenshotHeight, true); - } - m_screenshot.clear(); - } - } - - void ImguiClientHelper::dispatchClickEvent(std::pair& clickEventOut) - { - clickEventOut = m_clickEvent; - m_clickEvent = {std::numeric_limits::max(), std::numeric_limits::max()}; - } - - void ImguiClientHelper::dispatchEvents() - { - if (m_renderer) - { - m_renderer->dispatchEvents(*this); - m_renderer->getSceneControlAPI()->dispatchEvents(*this); - } - } - - bool ImguiClientHelper::saveScreenshot(const std::string& filename) - { - return saveScreenshot(filename, ramses::displayBufferId_t(), 0, 0, imguicamera->getViewportWidth(), imguicamera->getViewportHeight()); - } - - bool ImguiClientHelper::saveScreenshot(const std::string& filename, ramses::displayBufferId_t screenshotBuf, uint32_t x, uint32_t y, uint32_t width, uint32_t height) - { - if (m_renderer && m_screenshot.empty() && !filename.empty()) - { - m_screenshotSaved = false; - m_screenshot = filename; - m_screenshotWidth = width - x; - m_screenshotHeight = height - x; - m_renderer->readPixels(m_displayId, screenshotBuf, x, y, width, height); - m_renderer->flush(); - return true; - } - return false; - } - - bool ImguiClientHelper::waitForDisplay(ramses::displayId_t displayId) - { - return waitUntil([&] { return m_displays.find(displayId) != m_displays.end(); }); - } - - bool ImguiClientHelper::waitForSceneState(ramses::Scene& scene, ramses::RendererSceneState state) - { - return waitUntil([&] { return m_scenes[scene.getSceneId()].state == state; }, &scene); - } - - bool ImguiClientHelper::waitForSceneVersion(ramses::sceneId_t sceneId, ramses::sceneVersionTag_t version) - { - return waitUntil([&] { return m_scenes[sceneId].version == version; }); - } - - bool ImguiClientHelper::waitForOffscreenBufferCreated(const ramses::displayBufferId_t offscreenBufferId) - { - return waitUntil([&] { return m_offscreenBuffers.find(offscreenBufferId) != m_offscreenBuffers.end(); }); - } - - bool ImguiClientHelper::waitForOffscreenBufferLinked(const ramses::sceneId_t sceneId) - { - return waitUntil([&] { return m_scenesConsumingOffscreenBuffer.count(sceneId) > 0; }); - } - - bool ImguiClientHelper::waitForScreenshot() - { - waitUntil([&] { return m_screenshot.empty(); }); - return m_screenshotSaved; - } - - bool ImguiClientHelper::waitUntil(const std::function& conditionFunction, ramses::Scene* scene) - { - if (m_renderer) - { - const std::chrono::steady_clock::time_point timeoutTS = std::chrono::steady_clock::now() + std::chrono::seconds{5}; - while (m_isRunning && !conditionFunction() && std::chrono::steady_clock::now() < timeoutTS) - { - if (scene) - scene->flush(); // make sure scene gets flushed if subscribing - std::this_thread::sleep_for(std::chrono::milliseconds{5}); // will give the renderer time to process changes - m_renderer->dispatchEvents(*this); - auto* sceneControl = m_renderer->getSceneControlAPI(); - sceneControl->dispatchEvents(*this); - } - } - - return conditionFunction(); - } - -} - diff --git a/tools/ramses-logic-viewer/ImguiClientHelper.h b/tools/ramses-logic-viewer/ImguiClientHelper.h deleted file mode 100644 index a9c7a4423..000000000 --- a/tools/ramses-logic-viewer/ImguiClientHelper.h +++ /dev/null @@ -1,145 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2020 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -#include "ImguiWrapper.h" -#include "ramses/client/ramses-client.h" -#include "ramses/client/ramses-utils.h" -#include "ramses/renderer/RamsesRenderer.h" -#include "ramses/renderer/RendererSceneControl.h" -#include "ramses/renderer/IRendererEventHandler.h" -#include "ramses/renderer/IRendererSceneControlEventHandler.h" - -#include -#include -#include -#include - -namespace ramses -{ - class ImguiClientHelper : public ramses::RendererEventHandlerEmpty, public ramses::RendererSceneControlEventHandlerEmpty - { - public: - ImguiClientHelper(ramses::RamsesClient& client, uint32_t width, uint32_t height, ramses::sceneId_t sceneid); - ImguiClientHelper(const ImguiClientHelper&) = delete; - ImguiClientHelper& operator=(const ImguiClientHelper&) = delete; - ~ImguiClientHelper() override; - - /** - * @brief Used to filter input events for a certain display only - * @param[in] displayId The display to receive events for - invalid displayId handles all events - */ - void setDisplayId(ramses::displayId_t displayId); - - void setRenderer(ramses::RamsesRenderer* renderer); - - void dispatchEvents(); - - void dispatchClickEvent(std::pair& clickEventOut); - - void draw(); - - bool isRunning() const; - ramses::Scene* getScene(); - uint32_t getViewportWidth() const; - uint32_t getViewportHeight() const; - - bool saveScreenshot(const std::string& filename); - bool saveScreenshot(const std::string& filename, ramses::displayBufferId_t screenshotBuf, uint32_t x, uint32_t y, uint32_t width, uint32_t height); - - bool waitForDisplay(ramses::displayId_t displayId); - bool waitForSceneState(ramses::Scene& scene, ramses::RendererSceneState state); - bool waitForSceneVersion(ramses::sceneId_t sceneId, ramses::sceneVersionTag_t version); - bool waitForOffscreenBufferCreated(const ramses::displayBufferId_t offscreenBufferId); - bool waitForOffscreenBufferLinked(const ramses::sceneId_t sceneId); - bool waitForScreenshot(); - - // SceneControlEvents - void sceneStateChanged(ramses::sceneId_t sceneId, ramses::RendererSceneState state) override; - void sceneFlushed(ramses::sceneId_t sceneId, ramses::sceneVersionTag_t sceneVersion) override; - void offscreenBufferCreated(ramses::displayId_t displayId_t, ramses::displayBufferId_t offscreenBufferId, ramses::ERendererEventResult result) override; - void offscreenBufferLinked(ramses::displayBufferId_t offscreenBufferId, ramses::sceneId_t consumerScene, ramses::dataConsumerId_t consumerId, bool success) override; - - // Renderer events - void displayCreated(ramses::displayId_t displayId, ramses::ERendererEventResult result) override; - void displayDestroyed(ramses::displayId_t displayId, ramses::ERendererEventResult result) override; - void mouseEvent(ramses::displayId_t displayId, ramses::EMouseEvent eventType, int32_t mousePosX, int32_t mousePosY) override; - void keyEvent(ramses::displayId_t displayId, ramses::EKeyEvent eventType, ramses::KeyModifiers keyModifiers, ramses::EKeyCode keyCode) override; - void windowResized(ramses::displayId_t displayId, uint32_t width, uint32_t height) override; - void windowClosed(ramses::displayId_t displayId) override; - void framebufferPixelsRead(const uint8_t* pixelData, - const uint32_t pixelDataSize, - ramses::displayId_t displayId, - ramses::displayBufferId_t displayBuffer, - ramses::ERendererEventResult result) override; - - private: - bool waitUntil(const std::function& conditionFunction, ramses::Scene* scene = nullptr); - - struct SceneInfo - { - ramses::RendererSceneState state = ramses::RendererSceneState::Unavailable; - ramses::sceneVersionTag_t version = ramses::InvalidSceneVersionTag; - }; - - using SceneSet = std::unordered_map; - using OffscreenBufferSet = std::unordered_set; - using DisplaySet = std::unordered_set; - - SceneSet m_scenes; - SceneSet m_scenesAssignedToOffscreenBuffer; - SceneSet m_scenesConsumingOffscreenBuffer; - DisplaySet m_displays; - OffscreenBufferSet m_offscreenBuffers; - ramses::RamsesRenderer* m_renderer = nullptr; - ramses::displayId_t m_displayId; - ramses::Scene* m_imguiscene = nullptr; - ramses::OrthographicCamera* imguicamera = nullptr; - ramses::TextureSampler* sampler = nullptr; - ramses::Effect* effect = nullptr; - ramses::RenderGroup* renderGroup = nullptr; - std::optional textureInput{std::nullopt}; - std::optional inputPosition{std::nullopt}; - std::optional inputUV{std::nullopt}; - std::optional inputColor{std::nullopt}; - std::vector todeleteMeshes; - std::vector todeleteRes; - std::pair m_clickEvent; - std::string m_screenshot; - uint32_t m_screenshotWidth = 0U; - uint32_t m_screenshotHeight = 0U; - bool m_screenshotSaved = false; - bool m_isRunning = true; - }; - - inline ramses::Scene* ImguiClientHelper::getScene() - { - return m_imguiscene; - } - - inline bool ImguiClientHelper::isRunning() const - { - return m_isRunning; - } - - inline void ImguiClientHelper::setRenderer(ramses::RamsesRenderer* renderer) - { - m_renderer = renderer; - } - - inline uint32_t ImguiClientHelper::getViewportWidth() const - { - return imguicamera->getViewportWidth(); - } - - inline uint32_t ImguiClientHelper::getViewportHeight() const - { - return imguicamera->getViewportHeight(); - } -} diff --git a/tools/ramses-logic-viewer/LogicViewerApp.cpp b/tools/ramses-logic-viewer/LogicViewerApp.cpp deleted file mode 100644 index 124f23987..000000000 --- a/tools/ramses-logic-viewer/LogicViewerApp.cpp +++ /dev/null @@ -1,132 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2022 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "LogicViewerApp.h" - -#include "Arguments.h" -#include "LogicViewer.h" -#include "LogicViewerSettings.h" -#include "ImguiWrapper.h" - -namespace ramses -{ - LogicViewerApp::LogicViewerApp() - { - m_imguiContext = ImGui::CreateContext(); - } - - LogicViewerApp::~LogicViewerApp() - { - ImGui::DestroyContext(m_imguiContext); - } - - int LogicViewerApp::GetFeatureLevelFromFile(const std::string& sceneFilename, EFeatureLevel& featureLevel) - { - if (!RamsesClient::GetFeatureLevelFromFile(sceneFilename, featureLevel)) - { - std::cerr << "Could not parse feature level from scene file " << sceneFilename << std::endl; - return static_cast(ExitCode::ErrorLoadScene); - } - return 0; - } - - int LogicViewerApp::loadScene(const Arguments& args, EFeatureLevel featureLevel) - { - ramses::RamsesFrameworkConfig frameworkConfig{featureLevel}; - frameworkConfig.setPeriodicLogInterval(std::chrono::seconds(0)); - frameworkConfig.setLogLevelConsole(args.ramsesLogLevel()); - m_framework = std::make_unique(frameworkConfig); - m_client = m_framework->createClient("ramses-logic-viewer"); - if (!m_client) - { - std::cerr << "Could not create ramses client" << std::endl; - return static_cast(ExitCode::ErrorRamsesClient); - } - - m_scene = m_client->loadSceneFromFile(args.sceneFile()); - if (!m_scene) - { - std::cerr << "Failed to load scene: " << args.sceneFile() << std::endl; - return static_cast(ExitCode::ErrorLoadScene); - } - m_scene->publish(); - m_scene->flush(); - - m_settings = std::make_unique(); - return 0; - } - - int LogicViewerApp::createViewer(const Arguments& args, LogicViewer::ScreenshotFunc&& fScreenshot) - { - assert(m_scene); - - // find logic engine - SceneObjectIterator iter{*m_scene, ERamsesObjectType::LogicEngine}; - - m_logic = object_cast(iter.getNext()); - if (!m_logic) - { - std::cerr << "Failed to find logic" << std::endl; - return static_cast(ExitCode::ErrorLoadLogic); - } - - m_viewer = std::make_unique(*m_logic, fScreenshot); - - if (args.writeConfig()) - { - ImGui::NewFrame(); - const auto status = m_viewer->saveDefaultLuaFile(args.luaFile(), *m_settings); - ImGui::EndFrame(); - if (!status.ok()) - { - std::cerr << status.getMessage() << std::endl; - return static_cast(ExitCode::ErrorUnknown); - } - } - else if (!args.luaFunction().empty()) - { - m_loadLuaStatus = m_viewer->loadLuaFile(args.luaFile()); - - if (m_loadLuaStatus.ok()) - { - m_loadLuaStatus = m_viewer->call(args.luaFunction()); - } - if (!m_loadLuaStatus.ok()) - { - std::cerr << m_loadLuaStatus.getMessage() << std::endl; - return static_cast(ExitCode::ErrorLoadLua); - } - } - else if (!args.exec().empty()) - { - // default lua file may be missing (explicit lua file is checked by CLI11 before) - m_loadLuaStatus = m_viewer->loadLuaFile(fs::exists(args.luaFile()) ? args.luaFile() : ""); - if (m_loadLuaStatus.ok()) - { - m_loadLuaStatus = m_viewer->exec(args.exec()); - } - if (!m_loadLuaStatus.ok()) - { - std::cerr << m_loadLuaStatus.getMessage() << std::endl; - return static_cast(ExitCode::ErrorLoadLua); - } - } - else - { - // interactive mode - m_interactive = true; - // default lua file may be missing (explicit lua file is checked by CLI11 before) - if (fs::exists(args.luaFile())) - { - m_loadLuaStatus = m_viewer->loadLuaFile(args.luaFile()); - } - } - return 0; - } -} - diff --git a/tools/ramses-logic-viewer/LogicViewerApp.h b/tools/ramses-logic-viewer/LogicViewerApp.h deleted file mode 100644 index cbb5ec908..000000000 --- a/tools/ramses-logic-viewer/LogicViewerApp.h +++ /dev/null @@ -1,99 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2022 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -#include "ramses/client/ramses-client.h" -#include "ramses/framework/RamsesFrameworkTypes.h" -#include "Result.h" -#include "LogicViewer.h" -#include - -class Arguments; -struct ImGuiContext; - -namespace ramses -{ - struct LogicViewerSettings; - - class LogicViewerApp - { - public: - enum class ExitCode - { - Ok = 0, - ErrorRamsesClient = 1, - ErrorRamsesRenderer = 2, - ErrorSceneControl = 3, - ErrorLoadScene = 4, - ErrorLoadLogic = 5, - ErrorLoadLua = 6, - ErrorNoDisplay = 7, - ErrorUnknown = -1, - }; - - LogicViewerApp(); - - virtual ~LogicViewerApp(); - - LogicViewerApp(const LogicViewerApp&) = delete; - - LogicViewerApp& operator=(const LogicViewerApp&) = delete; - - [[nodiscard]] virtual bool doOneLoop() = 0; - - [[nodiscard]] int exitCode() const; - - [[nodiscard]] int run(); - - [[nodiscard]] ramses::LogicViewer* getViewer(); - - [[nodiscard]] const ramses::LogicViewerSettings* getSettings() const; - - protected: - [[nodiscard]] static int GetFeatureLevelFromFile(const std::string& sceneFilename, EFeatureLevel& featureLevel); - [[nodiscard]] int loadScene(const Arguments& args, EFeatureLevel featureLevel); - [[nodiscard]] int createViewer(const Arguments& args, LogicViewer::ScreenshotFunc&& fScreenshot); - - ImGuiContext* m_imguiContext = nullptr; - std::unique_ptr m_framework; - std::unique_ptr m_settings; - std::unique_ptr m_viewer; - - ramses::RamsesClient* m_client = nullptr; - ramses::Scene* m_scene = nullptr; - ramses::LogicEngine* m_logic = nullptr; - ramses::Result m_loadLuaStatus; - - int m_exitCode = -1; - bool m_interactive = false; - }; - - inline int LogicViewerApp::exitCode() const - { - return m_exitCode; - } - - inline int LogicViewerApp::run() - { - while (doOneLoop()) - ; - return m_exitCode; - } - - inline ramses::LogicViewer* LogicViewerApp::getViewer() - { - return m_viewer.get(); - } - - inline const ramses::LogicViewerSettings* LogicViewerApp::getSettings() const - { - return m_settings.get(); - } -} - diff --git a/tools/ramses-logic-viewer/LogicViewerGui.cpp b/tools/ramses-logic-viewer/LogicViewerGui.cpp deleted file mode 100644 index 02c75ae71..000000000 --- a/tools/ramses-logic-viewer/LogicViewerGui.cpp +++ /dev/null @@ -1,1364 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2021 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "LogicViewerGui.h" -#include "LogicViewer.h" -#include "LogicViewerLog.h" -#include "LogicViewerSettings.h" -#include "ramses/client/Scene.h" -#include "ramses/client/logic/LogicEngine.h" -#include "ramses/client/logic/LuaScript.h" -#include "ramses/client/logic/LuaInterface.h" -#include "ramses/client/logic/AnimationNode.h" -#include "ramses/client/logic/TimerNode.h" -#include "ramses/client/logic/AppearanceBinding.h" -#include "ramses/client/logic/CameraBinding.h" -#include "ramses/client/logic/NodeBinding.h" -#include "ramses/client/logic/RenderPassBinding.h" -#include "ramses/client/logic/RenderGroupBinding.h" -#include "ramses/client/logic/MeshNodeBinding.h" -#include "ramses/client/logic/DataArray.h" -#include "ramses/client/logic/Property.h" -#include "ramses/client/logic/AnchorPoint.h" -#include "ramses/client/logic/SkinBinding.h" -#include "internal/logic/StdFilesystemWrapper.h" -#include "internal/PlatformAbstraction/FmtBase.h" -#include "glm/gtc/type_ptr.hpp" - -#ifndef _MSC_VER -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wold-style-cast" -#endif -#include "imgui_internal.h" // for ImGuiSettingsHandler -#ifndef _MSC_VER -#pragma GCC diagnostic pop -#endif - -template <> struct fmt::formatter -{ - template constexpr auto parse(ParseContext& ctx) - { - return ctx.begin(); - } - - template constexpr auto format(const std::chrono::microseconds value, FormatContext& ctx) - { - const auto c = value.count(); - if (c == 0) - return fmt::format_to(ctx.out(), "0"); - return fmt::format_to(ctx.out(), "{}.{:03}", c / 1000, c % 1000); - } -}; - - -namespace ramses -{ - namespace - { - const char* EnumToString(ramses::ERotationType t) - { - switch (t) - { - case ramses::ERotationType::Euler_XYZ: - return "Euler_XYZ"; - case ramses::ERotationType::Euler_XZY: - return "Euler_XZY"; - case ramses::ERotationType::Euler_YXZ: - return "Euler_YXZ"; - case ramses::ERotationType::Euler_YZX: - return "Euler_YZX"; - case ramses::ERotationType::Euler_ZXY: - return "Euler_ZXY"; - case ramses::ERotationType::Euler_ZYX: - return "Euler_ZYX"; - case ramses::ERotationType::Euler_XYX: - return "Euler_XYX"; - case ramses::ERotationType::Euler_XZX: - return "Euler_XZX"; - case ramses::ERotationType::Euler_YXY: - return "Euler_YXY"; - case ramses::ERotationType::Euler_YZY: - return "Euler_YZY"; - case ramses::ERotationType::Euler_ZXZ: - return "Euler_ZXZ"; - case ramses::ERotationType::Euler_ZYZ: - return "Euler_ZYZ"; - case ramses::ERotationType::Quaternion: - return "Quaternion"; - } - return ""; - } - - const char* EnumToString(EInterpolationType t) - { - switch (t) - { - case EInterpolationType::Step: - return "Step"; - case EInterpolationType::Linear: - return "Linear"; - case EInterpolationType::Cubic: - return "Cubic"; - case EInterpolationType::Linear_Quaternions: - return "Linear_Quaternions"; - case EInterpolationType::Cubic_Quaternions: - return "Cubic_Quaternions"; - } - return ""; - } - - bool TreeNode(const void* ptr_id, const std::string_view& text) - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - return ImGui::TreeNode(ptr_id, "%s", text.data()); - } - - bool TreeNode(const void* ptr_id, const std::string& text) - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - return ImGui::TreeNode(ptr_id, "%s", text.c_str()); - } - - const char* TypeName(const LogicNode* node) - { - const char* name = "Unknown"; - if (node->as() != nullptr) - { - name = "LuaInterface"; - } - else if (node->as() != nullptr) - { - name = "LuaScript"; - } - else if (node->as() != nullptr) - { - name = "Animation"; - } - else if (node->as() != nullptr) - { - name = "NodeBinding"; - } - else if (node->as() != nullptr) - { - name = "AppearanceBinding"; - } - else if (node->as() != nullptr) - { - name = "CameraBinding"; - } - else if (node->as() != nullptr) - { - name = "RenderPassBinding"; - } - else if (node->as() != nullptr) - { - name = "RenderGroupBinding"; - } - else if (node->as() != nullptr) - { - name = "MeshNodeBinding"; - } - else if (node->as() != nullptr) - { - name = "Timer"; - } - else if (node->as() != nullptr) - { - name = "AnchorPoint"; - } - else if (node->as() != nullptr) - { - name = "SkinBinding"; - } - return name; - } - - template - void HelpMarker(const char* desc, Args&& ... args) - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - ImGui::TextDisabled("(?)"); - if (ImGui::IsItemHovered()) - { - ImGui::BeginTooltip(); - ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); - ImGui::TextUnformatted(fmt::format(desc, args...).c_str()); - ImGui::PopTextWrapPos(); - ImGui::EndTooltip(); - } - } - } - - LogicViewerGui::LogicViewerGui(ramses::LogicViewer& viewer, LogicViewerSettings& settings, std::string luafile) - : m_settings(settings) - , m_viewer(viewer) - , m_logicEngine(viewer.getLogic()) - , m_filename(std::move(luafile)) - { - m_viewer.enableUpdateReport(m_settings.showUpdateReport, m_updateReportInterval); - } - - void LogicViewerGui::draw() - { - if (ImGui::IsKeyPressed(ramses::EKeyCode_Left)) - { - m_viewer.setCurrentView(m_viewer.getCurrentView() - 1); - } - else if (ImGui::IsKeyPressed(ramses::EKeyCode_Right)) - { - m_viewer.setCurrentView(m_viewer.getCurrentView() + 1); - } - else if (ImGui::IsKeyPressed(ramses::EKeyCode_F11)) - { - m_settings.showWindow = !m_settings.showWindow; - ImGui::MarkIniSettingsDirty(); - } - else if (ImGui::IsKeyPressed(ramses::EKeyCode_F5)) - { - reloadConfiguration(); - } - else if (ImGui::IsKeyPressed(ramses::EKeyCode_C) && ImGui::GetIO().KeyCtrl) - { - copyScriptInputs(); - } - else - { - } - - drawGlobalContextMenu(); - drawSceneTexture(); - drawErrorPopup(); - - if (m_settings.showWindow) - { - // ImGui::ShowDemoWindow(); - drawWindow(); - } - } - - void LogicViewerGui::openErrorPopup(const std::string& message) - { - // ImGui::OpenPopup("Error") does not work in all cases (The calculated ID seems to be context related) - // The popup will be opened in LogicViewerGui::draw() instead - m_lastErrorMessage = message; - } - - void LogicViewerGui::setSceneTexture(ramses::TextureSampler* sampler, uint32_t width, uint32_t height) - { - m_sampler = sampler; - m_samplerSize.x = static_cast(width); - m_samplerSize.y = static_cast(height); - } - - void LogicViewerGui::setRendererInfo(ramses::RamsesRenderer& renderer, ramses::displayId_t displayId, ramses::displayBufferId_t displayBufferId, const std::array& initialClearColor) - { - m_renderer = &renderer; - m_displayId = displayId; - m_displayBufferId = displayBufferId; - m_clearColor = initialClearColor; - } - - void LogicViewerGui::drawMenuItemShowWindow() - { - if (ImGui::MenuItem("Show Logic Viewer Window", "F11", &m_settings.showWindow)) - { - ImGui::MarkIniSettingsDirty(); - } - } - - void LogicViewerGui::drawMenuItemReload() - { - if (ImGui::MenuItem("Reload configuration", "F5")) - { - reloadConfiguration(); - } - } - - void LogicViewerGui::drawMenuItemCopy() - { - if (ImGui::MenuItem("Copy script inputs", "Ctrl+C")) - { - copyScriptInputs(); - } - } - - void LogicViewerGui::reloadConfiguration() - { - if (fs::exists(m_filename)) - { - loadLuaFile(m_filename); - } - } - - void LogicViewerGui::loadLuaFile(const std::string& filename) - { - auto result = m_viewer.loadLuaFile(filename); - if (!result.ok()) - { - openErrorPopup(result.getMessage()); - } - } - - template - void LogicViewerGui::copyInputs(const std::string_view& ns, Collection collection) - { - LogicViewerLog::PathVector path; - path.push_back(LogicViewer::ltnModule); - path.push_back(ns); - LogicViewerLog log(m_logicEngine, m_settings); - for (auto* node : collection) - { - log.logInputs(node, path); - } - ImGui::SetClipboardText(log.getText().c_str()); - } - - void LogicViewerGui::copyScriptInputs() - { - copyInputs(LogicViewer::ltnScript, m_logicEngine.getCollection()); - } - - void LogicViewerGui::drawGlobalContextMenu() - { - if (ImGui::BeginPopupContextVoid("GlobalContextMenu")) - { - drawMenuItemShowWindow(); - drawMenuItemReload(); - drawMenuItemCopy(); - if (ImGui::MenuItem("Next view", "Arrow Right", nullptr, (m_viewer.getCurrentView() < m_viewer.getViewCount()))) - m_viewer.setCurrentView(m_viewer.getCurrentView() + 1); - if (ImGui::MenuItem("Previous view", "Arrow Left", nullptr, m_viewer.getCurrentView() > 1)) - m_viewer.setCurrentView(m_viewer.getCurrentView() - 1); - ImGui::EndPopup(); - } - } - - void LogicViewerGui::drawSceneTexture() - { - if (m_sampler) - { - ImGui::GetBackgroundDrawList()->AddImage(m_sampler, ImVec2(0, 0), m_samplerSize, ImVec2(0, 1), ImVec2(1, 0)); - } - } - - void LogicViewerGui::drawErrorPopup() - { - if (!m_lastErrorMessage.empty()) - ImGui::OpenPopup("Error"); - - if (ImGui::BeginPopupModal("Error", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) - { - ImGui::TextUnformatted(m_lastErrorMessage.c_str()); - ImGui::Separator(); - - if (ImGui::Button("OK", ImVec2(120, 0))) - { - m_lastErrorMessage.clear(); - ImGui::CloseCurrentPopup(); - } - ImGui::SameLine(); - if (ImGui::Button("Copy Message", ImVec2(120, 0))) - { - ImGui::SetClipboardText(m_lastErrorMessage.c_str()); - } - ImGui::EndPopup(); - } - } - - void LogicViewerGui::drawWindow() - { - if (!ImGui::Begin(fmt::format("Logic Viewer (FeatureLevel 0{})", m_logicEngine.getScene().getRamsesClient().getRamsesFramework().getFeatureLevel()).c_str(), &m_settings.showWindow, ImGuiWindowFlags_MenuBar)) - { - ImGui::End(); - return; - } - - drawMenuBar(); - drawCurrentView(); - - if (m_settings.showInterfaces) - { - drawInterfaces(); - } - - if (m_settings.showScripts) - { - drawScripts(); - } - - if (m_settings.showAnimationNodes) - { - drawAnimationNodes(); - } - - if (m_settings.showTimerNodes) - { - drawTimerNodes(); - } - - if (m_settings.showDataArrays && ImGui::CollapsingHeader("Data Arrays")) - { - for (auto* obj : m_logicEngine.getCollection()) - { - DrawDataArray(obj); - } - } - - if (m_settings.showRamsesBindings) - { - drawAppearanceBindings(); - drawNodeBindings(); - drawCameraBindings(); - drawRenderPassBindings(); - drawRenderGroupBindings(); - drawMeshNodeBindings(); - drawAnchorPoints(); - drawSkinBindings(); - } - - if (m_settings.showUpdateReport) - { - drawUpdateReport(); - } - - if (m_settings.showDisplaySettings && m_renderer) - { - drawDisplaySettings(); - } - - ImGui::End(); - } - - void LogicViewerGui::drawMenuBar() - { - if (ImGui::BeginMenuBar()) - { - if (ImGui::BeginMenu("File")) - { - drawMenuItemReload(); - drawMenuItemCopy(); - ImGui::EndMenu(); - } - - if (ImGui::BeginMenu("Settings")) - { - drawMenuItemShowWindow(); - ImGui::Separator(); - bool changed = ImGui::MenuItem("Show Interfaces", nullptr, &m_settings.showInterfaces); - changed = ImGui::MenuItem("Show Scripts", nullptr, &m_settings.showScripts) || changed; - changed = ImGui::MenuItem("Show Animation Nodes", nullptr, &m_settings.showAnimationNodes) || changed; - changed = ImGui::MenuItem("Show Timer Nodes", nullptr, &m_settings.showTimerNodes) || changed; - changed = ImGui::MenuItem("Show Data Arrays", nullptr, &m_settings.showDataArrays) || changed; - changed = ImGui::MenuItem("Show Ramses Bindings", nullptr, &m_settings.showRamsesBindings) || changed; - if (ImGui::MenuItem("Show Update Report", nullptr, &m_settings.showUpdateReport)) - { - m_viewer.enableUpdateReport(m_settings.showUpdateReport, m_updateReportInterval); - ImGui::MarkIniSettingsDirty(); - } - ImGui::Separator(); - changed = ImGui::MenuItem("Show Linked Inputs", nullptr, &m_settings.showLinkedInputs) || changed; - changed = ImGui::MenuItem("Show Outputs", nullptr, &m_settings.showOutputs) || changed; - ImGui::Separator(); - changed = ImGui::MenuItem("Lua: prefer identifiers (scripts.foo)", nullptr, &m_settings.luaPreferIdentifiers) || changed; - changed = ImGui::MenuItem("Lua: prefer object ids (scripts[1])", nullptr, &m_settings.luaPreferObjectIds) || changed; - ImGui::Separator(); - changed = ImGui::MenuItem("Show Display Settings", nullptr, &m_settings.showDisplaySettings) || changed; - ImGui::EndMenu(); - - if (changed) - { - ImGui::MarkIniSettingsDirty(); - } - } - ImGui::EndMenuBar(); - } - } - - void LogicViewerGui::drawCurrentView() - { - const auto viewCount = static_cast(m_viewer.getViewCount()); - const auto& status = m_viewer.getLastResult(); - if (!status.ok()) - { - ImGui::TextUnformatted(fmt::format("Error occurred in {}", m_viewer.getLuaFilename()).c_str()); - ImGui::TextUnformatted(status.getMessage().c_str()); - } - else if (m_viewer.getLuaFilename().empty()) - { - drawSaveDefaultLuaFile(); - } - else if (viewCount > 0) - { - auto viewId = static_cast(m_viewer.getCurrentView()); - const auto view = m_viewer.getView(viewId); - ImGui::TextUnformatted(!view.name().empty() ? view.name().c_str() : ""); - ImGui::SetNextItemWidth(100); - if (ImGui::InputInt("##View", &viewId)) - m_viewer.setCurrentView(viewId); - ImGui::SameLine(); - ImGui::TextUnformatted(fmt::format("of {}", viewCount).c_str()); - - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - ImGui::TextWrapped("%s", view.description().c_str()); - - for (size_t i = 0U; i < view.getInputCount(); ++i) - { - auto* prop = view.getInput(i); - if (prop) - drawProperty(view.getInput(i), i); - } - } - else - { - ImGui::TextUnformatted("no views defined in configuration file"); - } - - if (m_settings.showUpdateReport) - { - ImGui::Separator(); - ImGui::TextUnformatted(fmt::format("Average Update Time: {} ms", m_viewer.getUpdateReport().getTotalTime().average).c_str()); - ImGui::SameLine(); - HelpMarker("Time it took to update the whole logic nodes network (LogicEngine::update())."); - } - } - - bool LogicViewerGui::DrawTreeNode(ramses::LogicObject* obj) - { - return TreeNode(obj, fmt::format("[{}]: {}", obj->getSceneObjectId().getValue(), obj->getName())); - } - - void LogicViewerGui::drawScripts() - { - const bool openScripts = ImGui::CollapsingHeader("Scripts"); - if (ImGui::BeginPopupContextItem("ScriptsContextMenu")) - { - if (ImGui::MenuItem("Copy all Script inputs")) - { - copyScriptInputs(); - } - ImGui::EndPopup(); - } - if (openScripts) - { - for (auto* script : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(script); - drawNodeContextMenu(script, LogicViewer::ltnScript); - if (open) - { - drawNode(script); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawInterfaces() - { - const bool openInterfaces = ImGui::CollapsingHeader("Interfaces"); - if (ImGui::BeginPopupContextItem("InterfacesContextMenu")) - { - if (ImGui::MenuItem("Copy all Interface inputs")) - { - copyInputs(LogicViewer::ltnInterface, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openInterfaces) - { - for (auto* script : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(script); - drawNodeContextMenu(script, LogicViewer::ltnInterface); - if (open) - { - drawNode(script); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawAnimationNodes() - { - const bool openAnimationNodes = ImGui::CollapsingHeader("Animation Nodes"); - if (ImGui::BeginPopupContextItem("AnimationNodesContextMenu")) - { - if (ImGui::MenuItem("Copy all Animation Node inputs")) - { - copyInputs(LogicViewer::ltnAnimation, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openAnimationNodes) - { - for (auto* obj : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(obj); - drawNodeContextMenu(obj, LogicViewer::ltnAnimation); - if (open) - { - ImGui::TextUnformatted(fmt::format("Duration: {}", *obj->getOutputs()->getChild("duration")->get()).c_str()); - if (ImGui::TreeNode("Channels")) - { - for (auto& ch : obj->getChannels()) - { - if (TreeNode(&ch, ch.name)) - { - ImGui::TextUnformatted(fmt::format("InterpolationType: {}", EnumToString(ch.interpolationType)).c_str()); - DrawDataArray(ch.keyframes, "Keyframes"); - DrawDataArray(ch.tangentsIn, "TangentsIn"); - DrawDataArray(ch.tangentsOut, "TangentsOut"); - DrawDataArray(ch.timeStamps, "TimeStamps"); - ImGui::TreePop(); - } - } - ImGui::TreePop(); - } - drawNode(obj); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawTimerNodes() - { - const bool openTimerNodes = ImGui::CollapsingHeader("Timer Nodes"); - if (ImGui::BeginPopupContextItem("TimerNodesContextMenu")) - { - if (ImGui::MenuItem("Copy all Timer Node inputs")) - { - copyInputs(LogicViewer::ltnTimer, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openTimerNodes) - { - for (auto* obj : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(obj); - drawNodeContextMenu(obj, LogicViewer::ltnTimer); - if (open) - { - drawNode(obj); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawNodeBindings() - { - const bool openBindings = ImGui::CollapsingHeader("Node Bindings"); - if (ImGui::BeginPopupContextItem("NodeBindingsContextMenu")) - { - if (ImGui::MenuItem("Copy all Node Binding inputs")) - { - copyInputs(LogicViewer::ltnNode, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openBindings) - { - for (auto* obj : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(obj); - drawNodeContextMenu(obj, LogicViewer::ltnNode); - if (open) - { - ImGui::TextUnformatted(fmt::format("Ramses Node: {}", obj->getRamsesNode().getName()).c_str()); - ImGui::TextUnformatted(fmt::format("Rotation Mode: {}", EnumToString(obj->getRotationType())).c_str()); - drawNode(obj); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawCameraBindings() - { - const bool openBindings = ImGui::CollapsingHeader("Camera Bindings"); - if (ImGui::BeginPopupContextItem("CameraBindingsContextMenu")) - { - if (ImGui::MenuItem("Copy all Camera Binding inputs")) - { - copyInputs(LogicViewer::ltnCamera, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openBindings) - { - for (auto* obj : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(obj); - drawNodeContextMenu(obj, LogicViewer::ltnCamera); - if (open) - { - ImGui::TextUnformatted(fmt::format("Ramses Camera: {}", obj->getRamsesCamera().getName()).c_str()); - drawNode(obj); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawRenderPassBindings() - { - const bool openBindings = ImGui::CollapsingHeader("RenderPass Bindings"); - if (ImGui::BeginPopupContextItem("RenderPassBindingsContextMenu")) - { - if (ImGui::MenuItem("Copy all RenderPass Binding inputs")) - { - copyInputs(LogicViewer::ltnRenderPass, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openBindings) - { - for (auto* obj : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(obj); - drawNodeContextMenu(obj, LogicViewer::ltnRenderPass); - if (open) - { - ImGui::TextUnformatted(fmt::format("Ramses RenderPass: {}", obj->getRamsesRenderPass().getName()).c_str()); - drawNode(obj); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawRenderGroupBindings() - { - const bool openBindings = ImGui::CollapsingHeader("RenderGroup Bindings"); - if (ImGui::BeginPopupContextItem("RenderGroupBindingsContextMenu")) - { - if (ImGui::MenuItem("Copy all RenderGroup Binding inputs")) - { - copyInputs(LogicViewer::ltnRenderGroup, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openBindings) - { - for (auto* obj : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(obj); - drawNodeContextMenu(obj, LogicViewer::ltnRenderGroup); - if (open) - { - ImGui::TextUnformatted(fmt::format("Ramses RenderGroup: {}", obj->getRamsesRenderGroup().getName()).c_str()); - drawNode(obj); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawMeshNodeBindings() - { - const bool openBindings = ImGui::CollapsingHeader("MeshNode Bindings"); - if (ImGui::BeginPopupContextItem("MeshNodeBindingsContextMenu")) - { - if (ImGui::MenuItem("Copy all MeshNode Binding inputs")) - { - copyInputs(LogicViewer::ltnMeshNode, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openBindings) - { - for (auto* obj : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(obj); - drawNodeContextMenu(obj, LogicViewer::ltnMeshNode); - if (open) - { - ImGui::TextUnformatted(fmt::format("Ramses MeshNode: {}", obj->getRamsesMeshNode().getName()).c_str()); - drawNode(obj); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawAnchorPoints() - { - const bool openAnchors = ImGui::CollapsingHeader("Anchor Points"); - if (ImGui::BeginPopupContextItem("AnchorPointsContextMenu")) - { - if (ImGui::MenuItem("Copy all Anchor Point inputs")) - { - copyInputs(LogicViewer::ltnAnchorPoint, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openAnchors) - { - for (auto* obj : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(obj); - drawNodeContextMenu(obj, LogicViewer::ltnAnchorPoint); - if (open) - { - ImGui::TextUnformatted(fmt::format("Ramses Node: {}", obj->getRamsesNode().getName()).c_str()); - ImGui::TextUnformatted(fmt::format("Ramses Camera: {}", obj->getRamsesCamera().getName()).c_str()); - drawNode(obj); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawSkinBindings() - { - const bool openSkinBindings = ImGui::CollapsingHeader("Skin Bindings"); - if (ImGui::BeginPopupContextItem("SkinBindingsContextMenu")) - { - if (ImGui::MenuItem("Copy all Skin Binding inputs")) - { - copyInputs(LogicViewer::ltnSkinBinding, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openSkinBindings) - { - for (auto* obj : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(obj); - drawNodeContextMenu(obj, LogicViewer::ltnSkinBinding); - if (open) - { - ImGui::TextUnformatted(fmt::format("Ramses Appearance: {}", obj->getAppearanceBinding().getRamsesAppearance().getName()).c_str()); - ImGui::TextUnformatted(fmt::format("Ramses Uniform input: {}", obj->getAppearanceUniformInput().getName()).c_str()); - drawNode(obj); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawUpdateReport() - { - const bool open = ImGui::CollapsingHeader("Update Report"); - if (open) - { - auto interval = static_cast(m_updateReportInterval); - bool refresh = m_viewer.isUpdateReportEnabled(); - if (ImGui::Checkbox("Auto Refresh", &refresh)) - { - m_viewer.enableUpdateReport(refresh, m_updateReportInterval); - } - ImGui::SetNextItemWidth(100); - if (ImGui::DragInt("Refresh Interval", &interval, 0.5f, 1, 1000, "%d Frames")) - { - m_updateReportInterval = static_cast(interval); - m_viewer.enableUpdateReport(refresh, m_updateReportInterval); - } - const auto& report = m_viewer.getUpdateReport(); - const auto& executed = report.getNodesExecuted(); - const auto& skipped = report.getNodesSkippedExecution(); - const auto longest = report.getTotalTime().maxValue; - - ImGui::Separator(); - ImGui::TextUnformatted("Summary:"); - ImGui::SameLine(); - HelpMarker("Timing data is collected and summarized for {} frames.\n'min', 'max', 'avg' show the minimum, maximum, and average value for the measured interval.", m_updateReportInterval); - ImGui::Indent(); - - const auto& updateTime = report.getTotalTime(); - ImGui::TextUnformatted(fmt::format("Total Update Time (ms): max:{} min:{} avg:{}", updateTime.maxValue, updateTime.minValue, updateTime.average).c_str()); - ImGui::SameLine(); - HelpMarker("Time it took to update the whole logic nodes network (LogicEngine::update())."); - - const auto& sortTime = report.getSortTime(); - ImGui::TextUnformatted(fmt::format("Topology Sort Time (ms): max:{} min:{} avg:{}", sortTime.maxValue, sortTime.minValue, sortTime.average).c_str()); - ImGui::SameLine(); - HelpMarker("Time it took to sort logic nodes by their topology during update (see ramses::LogicEngineReport::getTopologySortExecutionTime()"); - - const auto& links = report.getLinkActivations(); - ImGui::TextUnformatted(fmt::format("Activated Links: max:{} min:{} avg:{}", links.maxValue, links.minValue, links.average).c_str()); - ImGui::SameLine(); - HelpMarker("Number of input properties that had been updated by an output property (see ramses::LogicEngineReport::getTotalLinkActivations())."); - ImGui::Unindent(); - - ImGui::TextUnformatted(fmt::format("Details for the longest update ({} ms):", longest).c_str()); - if (TreeNode("Executed", fmt::format("Executed Nodes ({}):", executed.size()))) - { - for (auto& timedNode : executed) - { - auto* node = timedNode.first; - const auto percentage = (longest.count() > 0u) ? (100u * timedNode.second / longest) : 0u; - if (TreeNode(node, fmt::format("{}[{}]: {} [time:{} ms, {}%]", TypeName(node), node->getSceneObjectId().getValue(), node->getName(), timedNode.second, percentage))) - { - drawNode(node); - ImGui::TreePop(); - } - } - ImGui::TreePop(); - } - - if (TreeNode("Skipped", fmt::format("Skipped Nodes ({}):", skipped.size()))) - { - for (auto& node : skipped) - { - if (TreeNode(node, fmt::format("{}[{}]: {}", TypeName(node), node->getSceneObjectId().getValue(), node->getName()))) - { - drawNode(node); - ImGui::TreePop(); - } - } - ImGui::TreePop(); - } - } - } - - void LogicViewerGui::drawAppearanceBindings() - { - const bool openBindings = ImGui::CollapsingHeader("Appearance Bindings"); - if (ImGui::BeginPopupContextItem("AppearanceBindingsContextMenu")) - { - if (ImGui::MenuItem("Copy all Appearance Binding inputs")) - { - copyInputs(LogicViewer::ltnAppearance, m_logicEngine.getCollection()); - } - ImGui::EndPopup(); - } - if (openBindings) - { - for (auto* obj : m_logicEngine.getCollection()) - { - const bool open = DrawTreeNode(obj); - drawNodeContextMenu(obj, LogicViewer::ltnAppearance); - if (open) - { - ImGui::TextUnformatted(fmt::format("Ramses Appearance: {}", obj->getRamsesAppearance().getName()).c_str()); - drawNode(obj); - ImGui::TreePop(); - } - } - } - } - - void LogicViewerGui::drawDisplaySettings() - { - assert(m_renderer); - const bool openDisplaySettings = ImGui::CollapsingHeader("Display Settings"); - if (openDisplaySettings) - { - if (ImGui::DragFloat4("Clear color", m_clearColor.data(), 0.1f, 0.f, 1.f)) - { - m_renderer->setDisplayBufferClearColor(m_displayId, m_displayBufferId, {m_clearColor[0], m_clearColor[1], m_clearColor[2], m_clearColor[3]}); - m_renderer->flush(); - } - - float fps = m_renderer->getFramerateLimit(m_displayId); - if (ImGui::DragFloat("Maximum FPS", &fps, 1.f, 1.f, 1000.f)) - { - m_renderer->setFramerateLimit(m_displayId, fps); - m_renderer->flush(); - } - - if (ImGui::Checkbox("Skip rendering of unmodified buffers", &m_skipUnmodifiedBuffers)) - { - m_renderer->setSkippingOfUnmodifiedBuffers(m_skipUnmodifiedBuffers); - m_renderer->flush(); - } - } - } - - void LogicViewerGui::drawSaveDefaultLuaFile() - { - ImGui::TextUnformatted("No lua configuration file found."); - ImGui::InputText("##filename", &m_filename); - ImGui::SameLine(); - if (ImGui::Button("Save default")) - { - fs::path luafile(m_filename); - if (fs::exists(luafile)) - { - ImGui::OpenPopup("Overwrite?"); - } - else if (!luafile.empty()) - { - saveDefaultLuaFile(); - } - } - ImGui::SameLine(); - if (ImGui::Button("Open")) - { - fs::path luafile(m_filename); - if (fs::exists(luafile)) - { - loadLuaFile(m_filename); - } - else if (!luafile.empty()) - { - m_lastErrorMessage = "File does not exist: " + m_filename; - } - } - - if (ImGui::BeginPopupModal("Overwrite?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) - { - ImGui::TextUnformatted(fmt::format("File exists:\n{}\nOverwrite default lua configuration?", m_filename).c_str()); - ImGui::Separator(); - - if (ImGui::Button("OK", ImVec2(120, 0))) - { - saveDefaultLuaFile(); - ImGui::CloseCurrentPopup(); - } - ImGui::SetItemDefaultFocus(); - ImGui::SameLine(); - if (ImGui::Button("Cancel", ImVec2(120, 0))) - { - ImGui::CloseCurrentPopup(); - } - ImGui::EndPopup(); - } - } - - - void LogicViewerGui::drawNodeContextMenu(ramses::LogicNode* obj, const std::string_view& ns) - { - if (ImGui::BeginPopupContextItem(obj->getName().data())) - { - if (ImGui::MenuItem(fmt::format("Copy {} inputs", obj->getName()).c_str())) - { - LogicViewerLog::PathVector path; - path.push_back(LogicViewer::ltnModule); - path.push_back(ns); - LogicViewerLog log(m_logicEngine, m_settings); - log.logInputs(obj, path); - ImGui::SetClipboardText(log.getText().c_str()); - } - ImGui::EndPopup(); - } - } - - void LogicViewerGui::drawNode(ramses::LogicNode* obj) - { - auto* in = obj->getInputs(); - const auto* out = obj->getOutputs(); - ImGui::SetNextItemOpen(true, ImGuiCond_Always); - if (in != nullptr) - { - if (TreeNode(in, std::string_view("Inputs"))) - { - for (size_t i = 0; i < in->getChildCount(); ++i) - { - drawProperty(in->getChild(i), i); - } - ImGui::TreePop(); - } - } - if (out != nullptr && m_settings.showOutputs) - { - ImGui::SetNextItemOpen(true, ImGuiCond_Always); - if (TreeNode(out, std::string_view("Outputs"))) - { - for (size_t i = 0; i < out->getChildCount(); ++i) - { - drawOutProperty(out->getChild(i), i); - } - ImGui::TreePop(); - } - } - } - - void LogicViewerGui::drawProperty(ramses::Property* prop, size_t index) - { - const bool isLinked = prop->hasIncomingLink(); - if (isLinked && !m_settings.showLinkedInputs) - return; - - std::string strName = prop->getName().data(); - if (prop->getName().empty()) - strName = fmt::format("[{}]", index); - const char* name = strName.c_str(); - - switch (prop->getType()) - { - case ramses::EPropertyType::Int32: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); - } - else if (ImGui::DragInt(name, &value, 0.1f)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::Int64: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); - } - else if (ImGui::DragScalar(name, ImGuiDataType_S64, &value, 0.1f, nullptr, nullptr)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::Float: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); - } - else if (ImGui::DragFloat(name, &value, 0.1f)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::Vec2f: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: ({}, {})", name, value[0], value[1]).c_str()); - } - else if (ImGui::DragFloat2(name, glm::value_ptr(value), 0.1f)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::Vec3f: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {})", name, value[0], value[1], value[2]).c_str()); - } - else if (ImGui::DragFloat3(name, glm::value_ptr(value), 0.1f)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::Vec4f: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {}, {})", name, value[0], value[1], value[2], value[3]).c_str()); - } - else if (ImGui::DragFloat4(name, glm::value_ptr(value), 0.1f)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::Vec2i: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: ({}, {})", name, value[0], value[1]).c_str()); - } - else if (ImGui::DragInt2(name, glm::value_ptr(value), 0.1f)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::Vec3i: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {})", name, value[0], value[1], value[2]).c_str()); - } - else if (ImGui::DragInt3(name, glm::value_ptr(value), 0.1f)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::Vec4i: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {}, {})", name, value[0], value[1], value[2], value[3]).c_str()); - } - else if (ImGui::DragInt4(name, glm::value_ptr(value), 0.1f)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::Struct: - if (TreeNode(prop, fmt::format("Struct {}", name))) - { - for (size_t i = 0U; i < prop->getChildCount(); ++i) - { - auto* child = prop->getChild(i); - drawProperty(child, i); - } - ImGui::TreePop(); - } - break; - case ramses::EPropertyType::Bool: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: {}", name, value ? "true" : "false").c_str()); - } - else if (ImGui::Checkbox(name, &value)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::String: { - auto value = prop->get().value(); - if (isLinked) - { - ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); - } - else if (ImGui::InputText(name, &value)) - { - prop->set(value); - } - break; - } - case ramses::EPropertyType::Array: - if (TreeNode(prop, fmt::format("Array {}", name))) - { - for (size_t i = 0U; i < prop->getChildCount(); ++i) - { - auto* child = prop->getChild(i); - drawProperty(child, i); - } - ImGui::TreePop(); - } - break; - } - } - - void LogicViewerGui::drawOutProperty(const ramses::Property* prop, size_t index) - { - std::string strName = prop->getName().data(); - if (prop->getName().empty()) - strName = fmt::format("[{}]", index); - const char* name = strName.c_str(); - - switch (prop->getType()) - { - case ramses::EPropertyType::Int32: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); - break; - } - case ramses::EPropertyType::Int64: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); - break; - } - case ramses::EPropertyType::Float: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); - break; - } - case ramses::EPropertyType::Vec2f: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: ({}, {})", name, value[0], value[1]).c_str()); - break; - } - case ramses::EPropertyType::Vec3f: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {})", name, value[0], value[1], value[2]).c_str()); - break; - } - case ramses::EPropertyType::Vec4f: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {}, {})", name, value[0], value[1], value[2], value[3]).c_str()); - break; - } - case ramses::EPropertyType::Vec2i: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: ({}, {})", name, value[0], value[1]).c_str()); - break; - } - case ramses::EPropertyType::Vec3i: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {})", name, value[0], value[1], value[2]).c_str()); - break; - } - case ramses::EPropertyType::Vec4i: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {}, {})", name, value[0], value[1], value[2], value[3]).c_str()); - break; - } - case ramses::EPropertyType::Struct: - if (TreeNode(prop, fmt::format("Struct {}", name))) - { - for (size_t i = 0U; i < prop->getChildCount(); ++i) - { - const auto* child = prop->getChild(i); - drawOutProperty(child, i); - } - ImGui::TreePop(); - } - break; - case ramses::EPropertyType::String: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); - break; - } - case ramses::EPropertyType::Bool: { - auto value = prop->get().value(); - ImGui::TextUnformatted(fmt::format("{}: {}", name, value ? "true" : "false").c_str()); - break; - } - case ramses::EPropertyType::Array: - if (TreeNode(prop, fmt::format("Array {}", name))) - { - for (size_t i = 0U; i < prop->getChildCount(); ++i) - { - const auto* child = prop->getChild(i); - drawOutProperty(child, i); - } - ImGui::TreePop(); - } - break; - } - } - - void LogicViewerGui::DrawDataArray(const ramses::DataArray* obj, std::string_view context) - { - if (obj != nullptr) - { - if (!context.empty()) - { - ImGui::TextUnformatted( - fmt::format("{}: [{}]: {} Type:{}[{}]", context.data(), obj->getSceneObjectId().getValue(), obj->getName(), GetLuaPrimitiveTypeName(obj->getDataType()), obj->getNumElements()).c_str()); - } - else - { - ImGui::TextUnformatted(fmt::format("[{}]: {} Type:{}[{}]", obj->getSceneObjectId().getValue(), obj->getName(), GetLuaPrimitiveTypeName(obj->getDataType()), obj->getNumElements()).c_str()); - } - } - } - - void LogicViewerGui::saveDefaultLuaFile() - { - const auto result = m_viewer.saveDefaultLuaFile(m_filename, m_settings); - if (result.ok()) - { - loadLuaFile(m_filename); - } - else - { - m_lastErrorMessage = result.getMessage(); - } - } -} - diff --git a/tools/ramses-logic-viewer/LogicViewerGui.h b/tools/ramses-logic-viewer/LogicViewerGui.h deleted file mode 100644 index 26857b59e..000000000 --- a/tools/ramses-logic-viewer/LogicViewerGui.h +++ /dev/null @@ -1,110 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2021 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -#include "ImguiClientHelper.h" -#include "ramses/client/logic/Collection.h" -#include - -struct ImGuiSettingsHandler; - -namespace ramses -{ - class Scene; - class RamsesRenderer; -} - -namespace ramses -{ - class LogicEngine; - class Property; - class LogicObject; - class LogicNode; - class LogicViewer; - class DataArray; - struct LogicViewerSettings; - - class LogicViewerGui - { - public: - /** - * @param luafile the luafile argument provided by command line - * If it does not exist the LogicViewerGui will provide a UI to save the default settings - */ - explicit LogicViewerGui(ramses::LogicViewer& viewer, LogicViewerSettings& settings, std::string luafile); - void draw(); - void openErrorPopup(const std::string& message); - void setSceneTexture(ramses::TextureSampler* sampler, uint32_t width, uint32_t height); - void setRendererInfo(ramses::RamsesRenderer& renderer, ramses::displayId_t displayId, ramses::displayBufferId_t displayBufferId, const std::array& initialClearColor); - - private: - void drawMenuItemShowWindow(); - void drawMenuItemReload(); - void drawMenuItemCopy(); - - void drawGlobalContextMenu(); - void drawSceneTexture(); - void drawErrorPopup(); - void drawWindow(); - void drawMenuBar(); - void drawCurrentView(); - void drawInterfaces(); - void drawScripts(); - void drawAnimationNodes(); - void drawTimerNodes(); - void drawNodeBindings(); - void drawCameraBindings(); - void drawRenderPassBindings(); - void drawRenderGroupBindings(); - void drawMeshNodeBindings(); - void drawAnchorPoints(); - void drawSkinBindings(); - void drawUpdateReport(); - void drawAppearanceBindings(); - void drawDisplaySettings(); - void drawSaveDefaultLuaFile(); - - static bool DrawTreeNode(ramses::LogicObject* obj); - - void drawNodeContextMenu(ramses::LogicNode* obj, const std::string_view& ns); - void drawNode(ramses::LogicNode* obj); - void drawProperty(ramses::Property* prop, size_t index); - void drawOutProperty(const ramses::Property* prop, size_t index); - static void DrawDataArray(const ramses::DataArray* obj, std::string_view context = std::string_view()); - - void reloadConfiguration(); - void loadLuaFile(const std::string& filename); - void saveDefaultLuaFile(); - - /** - * copies all node inputs to clipboard (lua syntax) - */ - template - void copyInputs(const std::string_view& ns, Collection collection); - void copyScriptInputs(); - - LogicViewerSettings& m_settings; - ramses::LogicViewer& m_viewer; - ramses::LogicEngine& m_logicEngine; - - std::string m_lastErrorMessage; - std::string m_filename; - size_t m_updateReportInterval = 60u; - - ramses::TextureSampler* m_sampler = nullptr; - ImVec2 m_samplerSize; - - ramses::RamsesRenderer* m_renderer = nullptr; - ramses::displayId_t m_displayId; - ramses::displayBufferId_t m_displayBufferId; - std::array m_clearColor{ 0, 0, 0, 1 }; - bool m_skipUnmodifiedBuffers = true; - }; -} - diff --git a/tools/ramses-logic-viewer/LogicViewerGuiApp.cpp b/tools/ramses-logic-viewer/LogicViewerGuiApp.cpp deleted file mode 100644 index f27b61d7b..000000000 --- a/tools/ramses-logic-viewer/LogicViewerGuiApp.cpp +++ /dev/null @@ -1,225 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2022 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "LogicViewerGuiApp.h" - -#include "Arguments.h" -#include "SceneSetup.h" -#include "ImguiClientHelper.h" -#include "LogicViewerGui.h" -#include "LogicViewer.h" -#include "LogicViewerSettings.h" -#include "ramses-cli.h" - -namespace ramses -{ - namespace - { - bool getPreferredSize(const ramses::Scene& scene, uint32_t& width, uint32_t& height) - { - ramses::SceneObjectIterator it(scene, ramses::ERamsesObjectType::RenderPass); - ramses::RamsesObject* obj = nullptr; - while (nullptr != (obj = it.getNext())) - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-static-cast-downcast) - auto* rp = static_cast(obj); - if (!rp->getRenderTarget()) - { - auto* camera = rp->getCamera(); - if (camera) - { - width = camera->getViewportWidth(); - height = camera->getViewportHeight(); - return true; - } - } - } - return false; - } - } // namespace - - LogicViewerGuiApp::LogicViewerGuiApp(int argc, const char * const * argv) - { - m_exitCode = init(argc, argv); - } - - LogicViewerGuiApp::~LogicViewerGuiApp() = default; - - int LogicViewerGuiApp::init(int argc, char const* const* argv) - { - if (argc == 0 || argv == nullptr) - { - return static_cast(ExitCode::ErrorUnknown); - } - - CLI::App cli; - Arguments args; - ramses::DisplayConfig displayConfig; - displayConfig.setResizable(true); - - try - { - args.registerOptions(cli); - cli.add_flag("--headless", m_headless, "Runs without user interface and renderer. Disables screenshots."); - auto setClearColor = [&](const auto& clearColor) { m_defaultClearColor = clearColor; }; - cli.add_option_function>("--clear-color", setClearColor, "Background clear color as RGBA (ex. --clearColor 0 0.5 0.8 1"); - ramses::registerOptions(cli, displayConfig); - } - catch (const CLI::Error& err) - { - // catch configuration errors - std::cerr << err.what() << std::endl; - return -1; - } - - CLI11_PARSE(cli, argc, argv); - - const bool customWidth = cli.get_option("--width")->count() > 0; - const bool customHeight = cli.get_option("--width")->count() > 0; - const bool autoDetectViewportSize = !customHeight && !customWidth; - - ramses::EFeatureLevel featureLevel = ramses::EFeatureLevel_01; - auto exitCode = GetFeatureLevelFromFile(args.sceneFile(), featureLevel); - if (exitCode != 0) - { - return exitCode; - } - - exitCode = LogicViewerApp::loadScene(args, featureLevel); - if (exitCode != 0) - { - return exitCode; - } - - const auto guiSceneId = ramses::sceneId_t(m_scene->getSceneId().getValue() + 1); - - if (autoDetectViewportSize && getPreferredSize(*m_scene, m_width, m_height)) - { - displayConfig.setWindowRectangle(0, 0, m_width, m_height); - } - - int32_t winX = 0; - int32_t winY = 0; - displayConfig.getWindowRectangle(winX, winY, m_width, m_height); - m_imguiHelper = std::make_unique(*m_client, m_width, m_height, guiSceneId); - - ramses::RamsesRenderer* renderer = nullptr; - ramses::displayId_t displayId; - if (!m_headless) - { - renderer = m_framework->createRenderer({}); - if (!renderer) - { - std::cerr << "Could not create ramses renderer" << std::endl; - return static_cast(ExitCode::ErrorRamsesRenderer); - } - - displayId = initDisplay(args, *renderer, displayConfig); - if (!displayId.isValid()) - { - std::cerr << "Could not create ramses display" << std::endl; - return static_cast(ExitCode::ErrorNoDisplay); - } - } - - auto takeScreenshot = [&](const std::string& filename) { - static ramses::sceneVersionTag_t ver = 42; - ++ver; - m_scene->flush(ver); - if (m_imguiHelper->waitForSceneVersion(m_scene->getSceneId(), ver)) - { - if (m_imguiHelper->saveScreenshot(filename, m_sceneSetup->getOffscreenBuffer(), 0, 0, m_sceneSetup->getWidth(), m_sceneSetup->getHeight())) - { - if (m_imguiHelper->waitForScreenshot()) - { - return true; - } - } - } - return false; - }; - - if (m_headless) - { - exitCode = LogicViewerApp::createViewer(args, LogicViewer::ScreenshotFunc()); - } - else - { - m_sceneSetup->apply(); - exitCode = LogicViewerApp::createViewer(args, takeScreenshot); - } - - if (exitCode != 0) - { - return exitCode; - } - - m_gui = std::make_unique(*m_viewer, *m_settings, args.luaFile()); - if (!m_headless) - { - m_gui->setSceneTexture(m_sceneSetup->getTextureSampler(), m_width, m_height); - m_gui->setRendererInfo(*renderer, displayId, m_sceneSetup->getOffscreenBuffer(), m_defaultClearColor); - } - - return 0; - } - - ramses::displayId_t LogicViewerGuiApp::initDisplay(const Arguments& args, ramses::RamsesRenderer& renderer, const ramses::DisplayConfig& displayConfig) - { - renderer.startThread(); - m_imguiHelper->setRenderer(&renderer); - - const auto display = renderer.createDisplay(displayConfig); - m_imguiHelper->setDisplayId(display); - renderer.flush(); - - if (!m_imguiHelper->waitForDisplay(display)) - { - return {}; - } - - if (args.offscreen()) - { - m_sceneSetup = std::make_unique(*m_imguiHelper, renderer, m_scene, display, m_width, m_height); - } - else - { - m_sceneSetup = std::make_unique(*m_imguiHelper, renderer, m_scene, display); - } - - renderer.setDisplayBufferClearColor(display, m_sceneSetup->getOffscreenBuffer(), {m_defaultClearColor[0], m_defaultClearColor[1], m_defaultClearColor[2], m_defaultClearColor[3]}); - renderer.flush(); - - return display; - } - - bool LogicViewerGuiApp::doOneLoop() - { - const auto isRunning = m_interactive && (m_exitCode == 0) && m_imguiHelper && m_imguiHelper->isRunning(); - if (isRunning) - { - const auto updateStatus = m_viewer->update(); - m_scene->flush(); - m_imguiHelper->dispatchEvents(); - ImGui::NewFrame(); - m_gui->draw(); - if (!m_loadLuaStatus.ok()) - { - m_gui->openErrorPopup(m_loadLuaStatus.getMessage()); - m_loadLuaStatus = ramses::Result(); - } - if (!updateStatus.ok()) - m_gui->openErrorPopup(updateStatus.getMessage()); - ImGui::EndFrame(); - m_imguiHelper->draw(); - std::this_thread::sleep_for(std::chrono::milliseconds(16)); - } - return isRunning; - } -} - diff --git a/tools/ramses-logic-viewer/LogicViewerGuiApp.h b/tools/ramses-logic-viewer/LogicViewerGuiApp.h deleted file mode 100644 index 6d3ef0f6a..000000000 --- a/tools/ramses-logic-viewer/LogicViewerGuiApp.h +++ /dev/null @@ -1,74 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2022 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -#include "LogicViewerApp.h" - -class ISceneSetup; - -namespace ramses -{ - class DisplayConfig; - class RendererConfig; -} - -namespace ramses -{ - class ImguiClientHelper; - class LogicViewerGui; - - class LogicViewerGuiApp : public LogicViewerApp - { - public: - enum class ExitCode - { - Ok = 0, - ErrorRamsesClient = 1, - ErrorRamsesRenderer = 2, - ErrorSceneControl = 3, - ErrorLoadScene = 4, - ErrorLoadLogic = 5, - ErrorLoadLua = 6, - ErrorNoDisplay = 7, - ErrorUnknown = -1, - }; - - LogicViewerGuiApp(int argc, char const* const* argv); - - ~LogicViewerGuiApp() override; - - LogicViewerGuiApp(const LogicViewerGuiApp&) = delete; - - LogicViewerGuiApp& operator=(const LogicViewerGuiApp&) = delete; - - [[nodiscard]] bool doOneLoop() override; - - [[nodiscard]] ramses::ImguiClientHelper* getImguiClientHelper(); - - private: - [[nodiscard]] int init(int argc, char const* const* argv); - [[nodiscard]] ramses::displayId_t initDisplay(const Arguments& args, ramses::RamsesRenderer& renderer, const ramses::DisplayConfig& displayConfig); - - - std::unique_ptr m_imguiHelper; - std::unique_ptr m_gui; - std::unique_ptr m_sceneSetup; - - uint32_t m_width = 0u; - uint32_t m_height = 0u; - std::array m_defaultClearColor{ 0, 0, 0, 1 }; - bool m_headless = false; - }; - - inline ramses::ImguiClientHelper* LogicViewerGuiApp::getImguiClientHelper() - { - return m_imguiHelper.get(); - } -} - diff --git a/tools/ramses-logic-viewer/LogicViewerHeadlessApp.cpp b/tools/ramses-logic-viewer/LogicViewerHeadlessApp.cpp deleted file mode 100644 index 708e228b7..000000000 --- a/tools/ramses-logic-viewer/LogicViewerHeadlessApp.cpp +++ /dev/null @@ -1,87 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2022 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "LogicViewerHeadlessApp.h" -#include "ImguiWrapper.h" -#include "Arguments.h" -#include "LogicViewer.h" -#include "LogicViewerSettings.h" - -namespace ramses -{ - LogicViewerHeadlessApp::LogicViewerHeadlessApp(int argc, const char * const * argv) - { - ImGuiIO& io = ImGui::GetIO(); - io.DisplaySize.x = 400.f; - io.DisplaySize.y = 320.f; - int texturewidth = 0; - int textureheight = 0; - unsigned char* pixels = nullptr; - io.Fonts->GetTexDataAsRGBA32(&pixels, &texturewidth, &textureheight); - m_exitCode = init(argc, argv); - } - - LogicViewerHeadlessApp::~LogicViewerHeadlessApp() = default; - - int LogicViewerHeadlessApp::init(int argc, char const* const* argv) - { - if (argc == 0 || argv == nullptr) - { - return static_cast(ExitCode::ErrorUnknown); - } - - CLI::App cli; - Arguments args; - - try - { - CLI::deprecate_option(cli.add_flag("--headless", "headless by default - flag will be ignored"), ""); - args.registerOptions(cli); - } - catch (const CLI::Error& err) - { - // catch configuration errors - std::cerr << err.what() << std::endl; - return -1; - } - - CLI11_PARSE(cli, argc, argv); - - EFeatureLevel featureLevel{EFeatureLevel_01}; - auto exitCode = GetFeatureLevelFromFile(args.sceneFile(), featureLevel); - if (exitCode != 0) - { - return exitCode; - } - - exitCode = LogicViewerApp::loadScene(args, featureLevel); - if (exitCode != 0) - { - return exitCode; - } - - exitCode = LogicViewerApp::createViewer(args, LogicViewer::ScreenshotFunc()); - if (exitCode != 0) - { - return exitCode; - } - - if (m_interactive) - { - std::cerr << "no interactive mode in headless viewer" << std::endl; - return static_cast(ExitCode::ErrorUnknown); - } - return 0; - } - - bool LogicViewerHeadlessApp::doOneLoop() - { - return false; // never interactive - } -} - diff --git a/tools/ramses-logic-viewer/LogicViewerSettings.cpp b/tools/ramses-logic-viewer/LogicViewerSettings.cpp deleted file mode 100644 index 5efbbfd92..000000000 --- a/tools/ramses-logic-viewer/LogicViewerSettings.cpp +++ /dev/null @@ -1,144 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2022 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "LogicViewerSettings.h" -#include "ImguiWrapper.h" - -#ifndef _MSC_VER -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wold-style-cast" -#endif -#include "imgui_internal.h" // for ImGuiSettingsHandler -#ifndef _MSC_VER -#pragma GCC diagnostic pop -#endif - -namespace ramses -{ - namespace - { - bool IniReadFlag(const char* line, const char* fmt, int* flag) - { - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg, cert-err34-c) no suitable replacement - return (sscanf(line, fmt, flag) == 1); - } - } - - LogicViewerSettings::LogicViewerSettings() - { - auto* ctx = ImGui::GetCurrentContext(); - assert(ctx != nullptr); - ImGuiSettingsHandler ini_handler; - ini_handler.TypeName = "LogicViewerGui"; - ini_handler.TypeHash = ImHashStr("LogicViewerGui"); - ini_handler.ReadOpenFn = IniReadOpen; - ini_handler.ReadLineFn = IniReadLine; - ini_handler.WriteAllFn = IniWriteAll; - ini_handler.UserData = this; - ctx->SettingsHandlers.push_back(ini_handler); - ImGui::LoadIniSettingsFromDisk(ImGui::GetIO().IniFilename); - } - - void* LogicViewerSettings::IniReadOpen(ImGuiContext* /*context*/, ImGuiSettingsHandler* handler, const char* /*name*/) - { - return handler->UserData; - } - - void LogicViewerSettings::IniReadLine(ImGuiContext* /*context*/, ImGuiSettingsHandler* handler, void* /*entry*/, const char* line) - { - auto* gui = static_cast(handler->UserData); - int flag = 0; - if (IniReadFlag(line, "ShowWindow=%d", &flag)) - { - gui->showWindow = (flag != 0); - } - else if (IniReadFlag(line, "ShowInterfaces=%d", &flag)) - { - gui->showInterfaces = (flag != 0); - } - else if (IniReadFlag(line, "ShowScripts=%d", &flag)) - { - gui->showScripts = (flag != 0); - } - else if (IniReadFlag(line, "ShowAnimationNodes=%d", &flag)) - { - gui->showAnimationNodes = (flag != 0); - } - else if (IniReadFlag(line, "ShowTimerNodes=%d", &flag)) - { - gui->showTimerNodes = (flag != 0); - } - else if (IniReadFlag(line, "ShowDataArrays=%d", &flag)) - { - gui->showDataArrays = (flag != 0); - } - else if (IniReadFlag(line, "ShowRamsesBindings=%d", &flag)) - { - gui->showRamsesBindings = (flag != 0); - } - else if (IniReadFlag(line, "ShowUpdateReport=%d", &flag)) - { - gui->showUpdateReport = (flag != 0); - } - else if (IniReadFlag(line, "ShowLinkedInputs=%d", &flag)) - { - gui->showLinkedInputs = (flag != 0); - } - else if (IniReadFlag(line, "ShowOutputs=%d", &flag)) - { - gui->showOutputs = (flag != 0); - } - else if (IniReadFlag(line, "LuaPreferObjectIds=%d", &flag)) - { - gui->luaPreferObjectIds = (flag != 0); - } - else if (IniReadFlag(line, "LuaPreferIdentifiers=%d", &flag)) - { - gui->luaPreferIdentifiers = (flag != 0); - } - else if (IniReadFlag(line, "ShowDisplaySettings=%d", &flag)) - { - gui->showDisplaySettings = (flag != 0); - } - } - - void LogicViewerSettings::IniWriteAll(ImGuiContext* /*context*/, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) - { - auto* gui = static_cast(handler->UserData); - buf->reserve(buf->size() + 400); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("[%s][Settings]\n", handler->TypeName); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowWindow=%d\n", gui->showWindow ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowInterfaces=%d\n", gui->showInterfaces ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowScripts=%d\n", gui->showScripts ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowAnimationNodes=%d\n", gui->showAnimationNodes ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowTimerNodes=%d\n", gui->showTimerNodes ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowDataArrays=%d\n", gui->showDataArrays ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowRamsesBindings=%d\n", gui->showRamsesBindings ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowUpdateReport=%d\n", gui->showUpdateReport ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowLinkedInputs=%d\n", gui->showLinkedInputs ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowOutputs=%d\n", gui->showOutputs ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("LuaPreferObjectIds=%d\n", gui->luaPreferObjectIds ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("LuaPreferIdentifiers=%d\n", gui->luaPreferIdentifiers ? 1 : 0); - // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface - buf->appendf("ShowDisplaySettings=%d\n", gui->showDisplaySettings ? 1 : 0); - buf->append("\n"); - } -} diff --git a/tools/ramses-logic-viewer/LogicViewerSettings.h b/tools/ramses-logic-viewer/LogicViewerSettings.h deleted file mode 100644 index 510c013fb..000000000 --- a/tools/ramses-logic-viewer/LogicViewerSettings.h +++ /dev/null @@ -1,41 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2022 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -struct ImGuiSettingsHandler; -struct ImGuiContext; -struct ImGuiTextBuffer; - -namespace ramses -{ - struct LogicViewerSettings - { - bool showWindow = true; - bool showOutputs = true; - bool showLinkedInputs = true; - bool showInterfaces = true; - bool showScripts = false; - bool showAnimationNodes = false; - bool showTimerNodes = false; - bool showDataArrays = false; - bool showRamsesBindings = false; - bool showUpdateReport = true; - - bool luaPreferObjectIds = false; - bool luaPreferIdentifiers = false; - - bool showDisplaySettings = false; - - LogicViewerSettings(); - - static void* IniReadOpen(ImGuiContext* context, ImGuiSettingsHandler* handler, const char* name); - static void IniReadLine(ImGuiContext* context, ImGuiSettingsHandler* handler, void* entry, const char* line); - static void IniWriteAll(ImGuiContext* context, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf); - }; -} diff --git a/tools/ramses-logic-viewer/SceneSetup.h b/tools/ramses-logic-viewer/SceneSetup.h deleted file mode 100644 index 0e9d59231..000000000 --- a/tools/ramses-logic-viewer/SceneSetup.h +++ /dev/null @@ -1,169 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2021 BMW AG -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -#include "ImguiClientHelper.h" - -#include "ramses/client/ramses-client.h" - -#include "ramses/renderer/RamsesRenderer.h" -#include "ramses/renderer/DisplayConfig.h" -#include "ramses/renderer/RendererSceneControl.h" - -#include - -class ISceneSetup -{ -public: - virtual ~ISceneSetup() = default; - - virtual void apply() = 0; - - [[nodiscard]] virtual uint32_t getWidth() const = 0; - - [[nodiscard]] virtual uint32_t getHeight() const = 0; - - [[nodiscard]] virtual ramses::displayBufferId_t getOffscreenBuffer() const = 0; - - [[nodiscard]] virtual ramses::TextureSampler* getTextureSampler() = 0; -}; - -class OffscreenSetup : public ISceneSetup -{ -public: - OffscreenSetup(ramses::ImguiClientHelper& imguiHelper, ramses::RamsesRenderer& renderer, ramses::Scene* scene, ramses::displayId_t display, uint32_t width, uint32_t height) - : m_imguiHelper(imguiHelper) - , m_sceneControl(renderer.getSceneControlAPI()) - , m_scene(scene) - , m_width(width) - , m_height(height) - { - m_ob = renderer.createOffscreenBuffer(display, width, height); - renderer.flush(); - - static const std::array imgbuf = {255, 255, 255, 255}; - const std::vector mipLevelData{ ramses::MipLevelData(4, imgbuf.data()) }; - auto* texture = imguiHelper.getScene()->createTexture2D(ramses::ETextureFormat::RGBA8, 1, 1, mipLevelData); - m_sampler = imguiHelper.getScene()->createTextureSampler( - ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Linear, ramses::ETextureSamplingMethod::Linear, *texture); - - const auto guiSceneId = imguiHelper.getScene()->getSceneId(); - m_sceneControl->setSceneMapping(scene->getSceneId(), display); - m_sceneControl->setSceneMapping(guiSceneId, display); - m_sceneControl->setSceneState(scene->getSceneId(), ramses::RendererSceneState::Ready); - m_sceneControl->setSceneState(guiSceneId, ramses::RendererSceneState::Ready); - m_sceneControl->flush(); - } - - void apply() override - { - const auto guiSceneId = m_imguiHelper.getScene()->getSceneId(); - const ramses::dataConsumerId_t consumerId(519); - - m_imguiHelper.waitForSceneState(*m_imguiHelper.getScene(), ramses::RendererSceneState::Ready); - m_imguiHelper.waitForSceneState(*m_scene, ramses::RendererSceneState::Ready); - - m_imguiHelper.getScene()->createTextureConsumer(*m_sampler, consumerId); - m_imguiHelper.getScene()->flush(42); - m_imguiHelper.waitForSceneVersion(guiSceneId, 42); - m_imguiHelper.waitForOffscreenBufferCreated(m_ob); - - m_sceneControl->setSceneDisplayBufferAssignment(m_scene->getSceneId(), m_ob); - m_sceneControl->linkOffscreenBuffer(m_ob, guiSceneId, consumerId); - m_sceneControl->flush(); - m_imguiHelper.waitForOffscreenBufferLinked(guiSceneId); - m_sceneControl->setSceneState(guiSceneId, ramses::RendererSceneState::Rendered); - m_sceneControl->setSceneState(m_scene->getSceneId(), ramses::RendererSceneState::Rendered); - m_sceneControl->flush(); - - m_imguiHelper.waitForSceneState(*m_scene, ramses::RendererSceneState::Rendered); - m_imguiHelper.waitForSceneState(*m_imguiHelper.getScene(), ramses::RendererSceneState::Rendered); - } - - [[nodiscard]] uint32_t getWidth() const override - { - return m_width; - } - - [[nodiscard]] uint32_t getHeight() const override - { - return m_height; - } - - [[nodiscard]] ramses::displayBufferId_t getOffscreenBuffer() const override - { - return m_ob; - } - - [[nodiscard]] ramses::TextureSampler* getTextureSampler() override - { - return m_sampler; - } - -private: - ramses::ImguiClientHelper& m_imguiHelper; - ramses::RendererSceneControl* m_sceneControl; - ramses::Scene* m_scene; - uint32_t m_width; - uint32_t m_height; - ramses::displayBufferId_t m_ob; - ramses::TextureSampler* m_sampler = nullptr; -}; - -class FramebufferSetup : public ISceneSetup -{ -public: - FramebufferSetup(ramses::ImguiClientHelper& imguiHelper, ramses::RamsesRenderer& renderer, ramses::Scene* scene, ramses::displayId_t display) - : m_imguiHelper(imguiHelper) - , m_sceneControl(renderer.getSceneControlAPI()) - , m_scene(scene) - { - const auto guiSceneId = imguiHelper.getScene()->getSceneId(); - m_sceneControl->setSceneMapping(scene->getSceneId(), display); - m_sceneControl->setSceneMapping(guiSceneId, display); - // inspection gui must be drawn on top - m_sceneControl->setSceneDisplayBufferAssignment(guiSceneId, ramses::displayBufferId_t(), 255); - m_sceneControl->setSceneState(scene->getSceneId(), ramses::RendererSceneState::Rendered); - m_sceneControl->flush(); - } - - void apply() override - { - m_imguiHelper.waitForSceneState(*m_scene, ramses::RendererSceneState::Rendered); - const auto guiSceneId = m_imguiHelper.getScene()->getSceneId(); - m_sceneControl->setSceneState(guiSceneId, ramses::RendererSceneState::Rendered); - m_sceneControl->flush(); - } - - [[nodiscard]] uint32_t getWidth() const override - { - return m_imguiHelper.getViewportWidth(); - } - - [[nodiscard]] uint32_t getHeight() const override - { - return m_imguiHelper.getViewportHeight(); - } - - [[nodiscard]] ramses::displayBufferId_t getOffscreenBuffer() const override - { - return ramses::displayBufferId_t(); - } - - [[nodiscard]] ramses::TextureSampler* getTextureSampler() override - { - return nullptr; - } - -private: - ramses::ImguiClientHelper& m_imguiHelper; - ramses::RendererSceneControl* m_sceneControl; - ramses::Scene* m_scene; -}; - diff --git a/tools/ramses-scene-viewer/CMakeLists.txt b/tools/ramses-scene-viewer/CMakeLists.txt deleted file mode 100644 index 36987d44b..000000000 --- a/tools/ramses-scene-viewer/CMakeLists.txt +++ /dev/null @@ -1,17 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (C) 2018 BMW Car IT GmbH -# ------------------------------------------------------------------------- -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at https://mozilla.org/MPL/2.0/. -# ------------------------------------------------------------------------- - -createModuleWithRenderer( - NAME ramses-scene-viewer - TYPE BINARY - ENABLE_INSTALL ON - SRC_FILES src/*.cpp - DEPENDENCIES ramses-client - ramses-imgui - ramses-cli -) diff --git a/tools/ramses-scene-viewer/src/SceneViewer.cpp b/tools/ramses-scene-viewer/src/SceneViewer.cpp deleted file mode 100644 index a585ca1dd..000000000 --- a/tools/ramses-scene-viewer/src/SceneViewer.cpp +++ /dev/null @@ -1,250 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2017 BMW Car IT GmbH -// Copyright (C) 2019 Daniel Werner Lima Souza de Almeida (dwlsalmeida@gmail.com) -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#include "SceneViewer.h" -#include "SceneViewerGui.h" - -#include "ramses/client/ramses-client.h" -#include "ramses/client/ramses-utils.h" - -#include "internal/Core/Utils/LogMacros.h" -#include "internal/Core/Utils/RamsesLogger.h" -#include "ImguiClientHelper.h" - -#include "ramses/renderer/RamsesRenderer.h" -#include "ramses/renderer/IRendererSceneControlEventHandler.h" -#include "ramses/framework/RamsesFramework.h" -#include "impl/RamsesFrameworkConfigImpl.h" - -#include "internal/PlatformAbstraction/PlatformThread.h" -#include -#include "internal/Core/Utils/Image.h" -#include "internal/Core/Utils/File.h" -#include "SceneSetup.h" -#include "ramses-cli.h" - - -namespace ramses::internal -{ - namespace - { - const int ErrorUsage = 1; - const int ErrorClient = 2; - const int ErrorRenderer = 3; - const int ErrorScene = 4; - const int ErrorScreenshot = 5; - const int ErrorDisplay = 6; - - void setPreferredSize(ramses::DisplayConfig& cfg, const ramses::Scene& scene) - { - ramses::SceneObjectIterator it(scene, ramses::ERamsesObjectType::RenderPass); - ramses::RamsesObject* obj = nullptr; - while (nullptr != (obj = it.getNext())) - { - auto* rp = static_cast(obj); - if (!rp->getRenderTarget()) - { - auto* camera = rp->getCamera(); - if (camera) - { - const auto width = camera->getViewportWidth(); - const auto height = camera->getViewportHeight(); - cfg.setWindowRectangle(0, 0, width, height); - } - } - } - } - } - - SceneViewer::SceneViewer() - { - // set default configuration - m_frameworkConfig.setPeriodicLogInterval(std::chrono::seconds(0)); - m_frameworkConfig.setRequestedRamsesShellType(ramses::ERamsesShellType::Console); - m_displayConfig.setResizable(true); - } - - void SceneViewer::registerOptions(CLI::App& cli) - { - cli.description("Loads and views a RAMSES scene from file"); - const std::map modes{{"on", GuiMode::On}, {"overlay", GuiMode::Overlay}, {"off", GuiMode::Off}, {"only", GuiMode::Only}}; - cli.add_option("-s,--scene,scene", m_sceneName, "Scene file to load")->check(CLI::ExistingFile)->required(); - auto gui = cli.add_option("--gui", m_guiMode, "Inspection Gui display mode")->transform(CLI::CheckedTransformer(modes)); - cli.add_flag("--no-validation", m_noValidation, "Disable scene validation (faster startup for complex scenes)"); - cli.add_option("--output", m_validationOutput, "Directory Path were validation output should be saved"); - auto screenshot = cli.add_option("-x,--screenshot", m_screenshotFile, "Stores a screenshot of the scene to the given filename and exits"); - cli.add_flag("--no-skub", m_noSkub, "Disable skub (skip unmodified buffers). Render unchanged frames."); - - ramses::registerOptions(cli, m_frameworkConfig); - ramses::registerOptions(cli, m_rendererConfig); - ramses::registerOptions(cli, m_displayConfig); - m_width = cli.get_option("--width"); - m_height = cli.get_option("--height"); - screenshot->excludes("--fullscreen")->excludes(gui); - } - - int SceneViewer::run() - { - GetRamsesLogger().initialize(m_frameworkConfig.impl().loggerConfig, false, true); - const auto scenePathAndFile = m_sceneName; - const File sceneFile(scenePathAndFile); - m_sceneName = sceneFile.getFileName(); - return loadAndRenderScene(scenePathAndFile); - } - - int SceneViewer::loadAndRenderScene(const std::string& sceneFile) - { - ramses::EFeatureLevel featureLevel = ramses::EFeatureLevel_01; - if (!ramses::RamsesClient::GetFeatureLevelFromFile(sceneFile, featureLevel)) - return ErrorUsage; - - m_frameworkConfig.setFeatureLevel(featureLevel); - ramses::RamsesFramework framework(m_frameworkConfig); - - auto client = framework.createClient("ramses-scene-viewer"); - if (!client) - { - LOG_ERROR(CONTEXT_CLIENT, "Creation of client failed"); - return ErrorClient; - } - - auto renderer = framework.createRenderer(m_rendererConfig); - if (!renderer) - { - LOG_ERROR(CONTEXT_CLIENT, "Creation of renderer failed"); - return ErrorRenderer; - } - renderer->setSkippingOfUnmodifiedBuffers(!m_noSkub); - renderer->startThread(); - framework.connect(); - - LOG_INFO(CONTEXT_CLIENT, "Load scene:" << sceneFile); - // scene viewer relies on resources being kept in memory (e.g. to query size), - // load scene as 'remote' which uses a shadowcopy scene and guarantees to keep resources in memory - auto loadedScene = client->loadSceneFromFile(sceneFile, SceneConfig({}, EScenePublicationMode::LocalAndRemote)); - if (loadedScene == nullptr) - { - LOG_ERROR(CONTEXT_CLIENT, "Loading scene failed!"); - framework.disconnect(); - return ErrorScene; - } - loadedScene->publish(); - loadedScene->flush(); - ramses::ValidationReport validationReport; - if (!m_noValidation) - { - validateContent(validationReport, *loadedScene); - } - - const bool customWidth = m_width ? (m_width->count() > 0) : false; - const bool customHeight = m_height ? (m_height->count() > 0) : false; - if (!customHeight && !customWidth) - { - setPreferredSize(m_displayConfig, *loadedScene); - } - int32_t winX = 0; - int32_t winY = 0; - uint32_t winWidth = 0u; - uint32_t winHeight = 0u; - m_displayConfig.getWindowRectangle(winX, winY, winWidth, winHeight); - const ramses::displayId_t displayId = renderer->createDisplay(m_displayConfig); - renderer->flush(); - - // avoid sceneId collision - const auto imguiSceneId = ramses::sceneId_t(loadedScene->getSceneId().getValue() + 1); - ImguiClientHelper imguiHelper(*client, winWidth, winHeight, imguiSceneId); - imguiHelper.setDisplayId(displayId); - imguiHelper.setRenderer(renderer); - - if (!imguiHelper.waitForDisplay(displayId)) - { - return ErrorDisplay; - } - - std::unique_ptr sceneSetup; - switch (m_guiMode) - { - case GuiMode::On: - sceneSetup = std::make_unique(imguiHelper, renderer, loadedScene, displayId, winWidth, winHeight); - break; - case GuiMode::Only: - sceneSetup = std::make_unique(imguiHelper, renderer, nullptr, displayId); - break; - case GuiMode::Overlay: - case GuiMode::Off: - sceneSetup = std::make_unique(imguiHelper, renderer, loadedScene, displayId); - break; - } - loadedScene->flush(); - sceneSetup->apply(); - - SceneViewerGui gui(*loadedScene, sceneFile, imguiHelper, validationReport); - gui.setSceneTexture(sceneSetup->getTextureSampler(), winWidth, winHeight); - - if (!m_screenshotFile.empty()) - { - if (!imguiHelper.saveScreenshot(m_screenshotFile, sceneSetup->getOffscreenBuffer(), 0, 0, winWidth, winHeight)) - { - LOG_ERROR(CONTEXT_CLIENT, "Failure when saving screenshot"); - return ErrorScreenshot; - } - if (!imguiHelper.waitForScreenshot()) - { - LOG_ERROR(CONTEXT_CLIENT, "Screenshot not saved"); - return ErrorScreenshot; - } - } - else - { - // interactive mode - while (imguiHelper.isRunning()) - { - loadedScene->flush(); - imguiHelper.dispatchEvents(); - if (m_guiMode != GuiMode::Off) - { - ImGui::NewFrame(); - gui.draw(); - // ImGui::ShowDemoWindow(); - ImGui::EndFrame(); - imguiHelper.draw(); - } - ramses::internal::PlatformThread::Sleep(20u); - } - } - return 0; - } - - void SceneViewer::validateContent(ramses::ValidationReport& report, const ramses::Scene& scene) const - { - scene.validate(report); - - if (m_guiMode == GuiMode::Off) - { - LOG_INFO(CONTEXT_CLIENT, "Scene validation report: " << report.impl().toString()); - } - - if (!m_validationOutput.empty()) - { - // dump scene verification - const std::string validationFilePath = m_validationOutput + m_sceneName + "_validationReport.txt"; - std::ofstream validationFile(validationFilePath); - validationFile << report.impl().toString() << std::endl; - // dump unused objects - const std::string unrequiredObjectsReportFilePath = m_validationOutput + m_sceneName + "_unrequObjsReport.txt"; - std::ofstream unrequObjsOfstream(unrequiredObjectsReportFilePath); - ramses::RamsesUtils::DumpUnrequiredSceneObjectsToFile(scene, unrequObjsOfstream); - } - - if (m_guiMode == GuiMode::Off) - { - ramses::RamsesUtils::DumpUnrequiredSceneObjects(scene); - } - } -} diff --git a/tools/ramses-scene-viewer/src/SceneViewer.h b/tools/ramses-scene-viewer/src/SceneViewer.h deleted file mode 100644 index 7f32e2ed8..000000000 --- a/tools/ramses-scene-viewer/src/SceneViewer.h +++ /dev/null @@ -1,70 +0,0 @@ -// ------------------------------------------------------------------------- -// Copyright (C) 2017 BMW Car IT GmbH -// ------------------------------------------------------------------------- -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. -// ------------------------------------------------------------------------- - -#pragma once - -#include "ramses/framework/RamsesFrameworkConfig.h" -#include "ramses/renderer/RendererConfig.h" -#include "ramses/renderer/DisplayConfig.h" - -#include -#include -#include - -namespace ramses -{ - class RamsesClient; - class Scene; - class RamsesRenderer; - class ValidationReport; -} - -namespace CLI -{ - class App; - class Option; -} - -namespace ramses::internal -{ - class SceneViewer - { - public: - SceneViewer(); - - void registerOptions(CLI::App& cli); - - int run(); - - private: - enum class GuiMode - { - Off, - On, ///< Loaded scene rendered to offscreen buffer (configurable size and position) - Overlay, ///< Debugging gui overlaps the rendered scene (no offscreen buffer) - Only, ///< Only shows the gui, not the scene itself - }; - - int loadAndRenderScene(const std::string& sceneFile); - void validateContent(ramses::ValidationReport& report, const ramses::Scene& scene) const; - - std::string m_sceneName; - GuiMode m_guiMode = GuiMode::Overlay; - bool m_noValidation = false; - bool m_noSkub = false; - std::string m_validationOutput; - std::string m_screenshotFile; - - ramses::RamsesFrameworkConfig m_frameworkConfig{ramses::EFeatureLevel_Latest}; - ramses::RendererConfig m_rendererConfig; - ramses::DisplayConfig m_displayConfig; - - CLI::Option* m_width = nullptr; - CLI::Option* m_height = nullptr; - }; -} diff --git a/tools/ramses-stream-viewer/src/main.cpp b/tools/ramses-stream-viewer/src/main.cpp index a1930fca2..32e2f0ea5 100644 --- a/tools/ramses-stream-viewer/src/main.cpp +++ b/tools/ramses-stream-viewer/src/main.cpp @@ -87,8 +87,8 @@ class StreamSourceViewer std::array indicesArray = {0, 1, 2, 2, 1, 3}; m_indices = m_scene->createArrayResource(6u, indicesArray.data()); - const std::array textureData = {1u, 1u, 1u, 1u}; - const std::vector mipLevelData{ ramses::MipLevelData(4, textureData.data()) }; + const std::vector textureData(4, std::byte{ 1u }); + const std::vector mipLevelData{ textureData }; m_texture = m_scene->createTexture2D(ramses::ETextureFormat::RGBA8, 1u, 1u, mipLevelData, false, {}, ""); ramses::EffectDescription effectDesc; diff --git a/tools/ramses-viewer/CMakeLists.txt b/tools/ramses-viewer/CMakeLists.txt new file mode 100644 index 000000000..ac168e037 --- /dev/null +++ b/tools/ramses-viewer/CMakeLists.txt @@ -0,0 +1,64 @@ +# ------------------------------------------------------------------------- +# Copyright (C) 2018 BMW Car IT GmbH +# ------------------------------------------------------------------------- +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +# ------------------------------------------------------------------------- + +add_library(ramses-viewer-lib INTERFACE) +target_sources(ramses-viewer-lib INTERFACE + LogicViewer.h + LogicViewer.cpp + LogicViewerLog.h + LogicViewerLog.cpp + LogicViewerLuaTypes.h + LogicViewerLuaTypes.cpp + ProgressMonitor.h + ResourceList.h + Result.h + SceneSetup.h + UpdateReportSummary.h + ValidationCache.h + ViewerApp.h + ViewerApp.cpp + ViewerHeadlessApp.h + ViewerHeadlessApp.cpp + ViewerSettings.h + ViewerSettings.cpp +) +target_link_libraries(ramses-viewer-lib INTERFACE imgui fmt::fmt ramses-framework-cli ramses-client) + +add_library(ramses-viewer-gui-lib INTERFACE) +target_sources(ramses-viewer-gui-lib INTERFACE + LogicEngineGui.h + LogicEngineGui.cpp + LogicViewerGui.h + LogicViewerGui.cpp + SceneViewerGui.h + SceneViewerGui.cpp + ViewerGui.h + ViewerGui.cpp + ViewerGuiApp.h + ViewerGuiApp.cpp +) +target_link_libraries(ramses-viewer-gui-lib INTERFACE ramses-viewer-lib ramses-imgui) + +if(TARGET ramses-renderer) + createModule( + NAME ramses-viewer + TYPE BINARY + ENABLE_INSTALL ON + SRC_FILES main.cpp + DEPENDENCIES ramses-viewer-gui-lib + ramses-renderer + ) +endif() + +createModule( + NAME ramses-viewer-headless + TYPE BINARY + ENABLE_INSTALL ON + SRC_FILES main_headless.cpp + DEPENDENCIES ramses-viewer-lib +) diff --git a/tools/ramses-logic-viewer/ImguiWrapper.h b/tools/ramses-viewer/ImguiWrapper.h similarity index 100% rename from tools/ramses-logic-viewer/ImguiWrapper.h rename to tools/ramses-viewer/ImguiWrapper.h diff --git a/tools/ramses-viewer/LogicEngineGui.cpp b/tools/ramses-viewer/LogicEngineGui.cpp new file mode 100644 index 000000000..25b635568 --- /dev/null +++ b/tools/ramses-viewer/LogicEngineGui.cpp @@ -0,0 +1,522 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2021 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#include "LogicEngineGui.h" +#include "LogicViewer.h" +#include "ViewerGuiApp.h" +#include "ViewerSettings.h" +#include "ramses/client/Scene.h" +#include "ramses/client/logic/LogicEngine.h" +#include "internal/logic/StdFilesystemWrapper.h" +#include "internal/PlatformAbstraction/FmtBase.h" +#include "glm/gtc/type_ptr.hpp" + +namespace ramses::internal +{ + namespace + { + const char* EnumToString(ramses::ERotationType t) + { + switch (t) + { + case ramses::ERotationType::Euler_XYZ: + return "Euler_XYZ"; + case ramses::ERotationType::Euler_XZY: + return "Euler_XZY"; + case ramses::ERotationType::Euler_YXZ: + return "Euler_YXZ"; + case ramses::ERotationType::Euler_YZX: + return "Euler_YZX"; + case ramses::ERotationType::Euler_ZXY: + return "Euler_ZXY"; + case ramses::ERotationType::Euler_ZYX: + return "Euler_ZYX"; + case ramses::ERotationType::Euler_XYX: + return "Euler_XYX"; + case ramses::ERotationType::Euler_XZX: + return "Euler_XZX"; + case ramses::ERotationType::Euler_YXY: + return "Euler_YXY"; + case ramses::ERotationType::Euler_YZY: + return "Euler_YZY"; + case ramses::ERotationType::Euler_ZXZ: + return "Euler_ZXZ"; + case ramses::ERotationType::Euler_ZYZ: + return "Euler_ZYZ"; + case ramses::ERotationType::Quaternion: + return "Quaternion"; + } + return ""; + } + + const char* EnumToString(EInterpolationType t) + { + switch (t) + { + case EInterpolationType::Step: + return "Step"; + case EInterpolationType::Linear: + return "Linear"; + case EInterpolationType::Cubic: + return "Cubic"; + case EInterpolationType::Linear_Quaternions: + return "Linear_Quaternions"; + case EInterpolationType::Cubic_Quaternions: + return "Cubic_Quaternions"; + } + return ""; + } + + bool TreeNode(const void* ptr_id, const std::string_view& text) + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + return ImGui::TreeNode(ptr_id, "%s", text.data()); + } + + bool TreeNode(const void* ptr_id, const std::string& text) + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + return ImGui::TreeNode(ptr_id, "%s", text.c_str()); + } + } + + LogicEngineGui::LogicEngineGui(const ViewerSettings& settings) + : m_settings(settings) + { + } + + bool LogicEngineGui::DrawTreeNode(ramses::LogicObject* obj) + { + return TreeNode(obj, fmt::format("[{}]: {}", obj->getSceneObjectId().getValue(), obj->getName())); + } + + void LogicEngineGui::draw(ramses::LuaScript* obj) + { + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::LuaInterface* obj) + { + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::AnimationNode* obj) + { + ImGui::TextUnformatted(fmt::format("Duration: {}", *obj->getOutputs()->getChild("duration")->get()).c_str()); + if (ImGui::TreeNode("Channels")) + { + for (auto& ch : obj->getChannels()) + { + if (TreeNode(&ch, ch.name)) + { + ImGui::TextUnformatted(fmt::format("InterpolationType: {}", EnumToString(ch.interpolationType)).c_str()); + DrawDataArray(ch.keyframes, "Keyframes"); + DrawDataArray(ch.tangentsIn, "TangentsIn"); + DrawDataArray(ch.tangentsOut, "TangentsOut"); + DrawDataArray(ch.timeStamps, "TimeStamps"); + ImGui::TreePop(); + } + } + ImGui::TreePop(); + } + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::TimerNode* obj) + { + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::NodeBinding* obj) + { + ImGui::TextUnformatted(fmt::format("Ramses Node: {}", obj->getRamsesNode().getName()).c_str()); + ImGui::TextUnformatted(fmt::format("Rotation Mode: {}", EnumToString(obj->getRotationType())).c_str()); + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::CameraBinding* obj) + { + ImGui::TextUnformatted(fmt::format("Ramses Camera: {}", obj->getRamsesCamera().getName()).c_str()); + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::RenderPassBinding* obj) + { + ImGui::TextUnformatted(fmt::format("Ramses RenderPass: {}", obj->getRamsesRenderPass().getName()).c_str()); + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::RenderGroupBinding* obj) + { + ImGui::TextUnformatted(fmt::format("Ramses RenderGroup: {}", obj->getRamsesRenderGroup().getName()).c_str()); + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::MeshNodeBinding* obj) + { + ImGui::TextUnformatted(fmt::format("Ramses MeshNode: {}", obj->getRamsesMeshNode().getName()).c_str()); + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::AnchorPoint* obj) + { + ImGui::TextUnformatted(fmt::format("Ramses Node: {}", obj->getRamsesNode().getName()).c_str()); + ImGui::TextUnformatted(fmt::format("Ramses Camera: {}", obj->getRamsesCamera().getName()).c_str()); + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::SkinBinding* obj) + { + ImGui::TextUnformatted(fmt::format("Ramses Appearance: {}", obj->getAppearanceBinding().getRamsesAppearance().getName()).c_str()); + ImGui::TextUnformatted(fmt::format("Ramses Uniform input: {}", obj->getAppearanceUniformInput().getName()).c_str()); + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::AppearanceBinding* obj) + { + ImGui::TextUnformatted(fmt::format("Ramses Appearance: {}", obj->getRamsesAppearance().getName()).c_str()); + drawNode(obj); + } + + void LogicEngineGui::draw(ramses::RenderBufferBinding* obj) + { + ImGui::TextUnformatted(fmt::format("Ramses RenderBuffer: {}", obj->getRenderBuffer().getName()).c_str()); + drawNode(obj); + } + + void LogicEngineGui::drawNodeContextMenu(ramses::LogicNode* obj, const std::string_view& ns) + { + if (ImGui::BeginPopupContextItem(obj->getName().data())) + { + if (ImGui::MenuItem(fmt::format("Copy {} inputs", obj->getName()).c_str())) + { + LogicViewerLog::PathVector path; + path.push_back(LogicViewer::ltnModule); + path.push_back(ns); + LogicViewerLog log(m_settings); + log.logInputs(obj, path); + ImGui::SetClipboardText(log.getText().c_str()); + } + ImGui::EndPopup(); + } + } + + void LogicEngineGui::drawNode(ramses::LogicNode* obj) + { + auto* in = obj->getInputs(); + const auto* out = obj->getOutputs(); + if (in == out) + { + // Interfaces have combined in/out parameters + for (size_t i = 0; i < in->getChildCount(); ++i) + { + drawProperty(in->getChild(i), i); + } + } + else + { + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (in != nullptr) + { + if (TreeNode(in, std::string_view("Inputs"))) + { + for (size_t i = 0; i < in->getChildCount(); ++i) + { + drawProperty(in->getChild(i), i); + } + ImGui::TreePop(); + } + } + if (out != nullptr) + { + ImGui::SetNextItemOpen(true, ImGuiCond_Once); + if (TreeNode(out, std::string_view("Outputs"))) + { + for (size_t i = 0; i < out->getChildCount(); ++i) + { + drawOutProperty(out->getChild(i), i); + } + ImGui::TreePop(); + } + } + } + } + + void LogicEngineGui::drawProperty(ramses::Property* prop, size_t index) + { + const bool isLinked = prop->hasIncomingLink(); + std::string strName = prop->getName().data(); + if (prop->getName().empty()) + strName = fmt::format("[{}]", index); + const char* name = strName.c_str(); + + switch (prop->getType()) + { + case ramses::EPropertyType::Int32: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); + } + else if (ImGui::DragInt(name, &value, 0.1f)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::Int64: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); + } + else if (ImGui::DragScalar(name, ImGuiDataType_S64, &value, 0.1f, nullptr, nullptr)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::Float: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); + } + else if (ImGui::DragFloat(name, &value, 0.1f)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::Vec2f: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: ({}, {})", name, value[0], value[1]).c_str()); + } + else if (ImGui::DragFloat2(name, glm::value_ptr(value), 0.1f)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::Vec3f: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {})", name, value[0], value[1], value[2]).c_str()); + } + else if (ImGui::DragFloat3(name, glm::value_ptr(value), 0.1f)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::Vec4f: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {}, {})", name, value[0], value[1], value[2], value[3]).c_str()); + } + else if (ImGui::DragFloat4(name, glm::value_ptr(value), 0.1f)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::Vec2i: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: ({}, {})", name, value[0], value[1]).c_str()); + } + else if (ImGui::DragInt2(name, glm::value_ptr(value), 0.1f)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::Vec3i: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {})", name, value[0], value[1], value[2]).c_str()); + } + else if (ImGui::DragInt3(name, glm::value_ptr(value), 0.1f)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::Vec4i: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {}, {})", name, value[0], value[1], value[2], value[3]).c_str()); + } + else if (ImGui::DragInt4(name, glm::value_ptr(value), 0.1f)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::Struct: + if (TreeNode(prop, fmt::format("Struct {}", name))) + { + for (size_t i = 0U; i < prop->getChildCount(); ++i) + { + auto* child = prop->getChild(i); + drawProperty(child, i); + } + ImGui::TreePop(); + } + break; + case ramses::EPropertyType::Bool: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: {}", name, value ? "true" : "false").c_str()); + } + else if (ImGui::Checkbox(name, &value)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::String: { + auto value = prop->get().value(); + if (isLinked) + { + ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); + } + else if (ImGui::InputText(name, &value)) + { + prop->set(value); + } + break; + } + case ramses::EPropertyType::Array: + if (TreeNode(prop, fmt::format("Array {}", name))) + { + for (size_t i = 0U; i < prop->getChildCount(); ++i) + { + auto* child = prop->getChild(i); + drawProperty(child, i); + } + ImGui::TreePop(); + } + break; + } + } + + void LogicEngineGui::drawOutProperty(const ramses::Property* prop, size_t index) + { + std::string strName = prop->getName().data(); + if (prop->getName().empty()) + strName = fmt::format("[{}]", index); + const char* name = strName.c_str(); + + switch (prop->getType()) + { + case ramses::EPropertyType::Int32: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); + break; + } + case ramses::EPropertyType::Int64: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); + break; + } + case ramses::EPropertyType::Float: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); + break; + } + case ramses::EPropertyType::Vec2f: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: ({}, {})", name, value[0], value[1]).c_str()); + break; + } + case ramses::EPropertyType::Vec3f: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {})", name, value[0], value[1], value[2]).c_str()); + break; + } + case ramses::EPropertyType::Vec4f: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {}, {})", name, value[0], value[1], value[2], value[3]).c_str()); + break; + } + case ramses::EPropertyType::Vec2i: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: ({}, {})", name, value[0], value[1]).c_str()); + break; + } + case ramses::EPropertyType::Vec3i: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {})", name, value[0], value[1], value[2]).c_str()); + break; + } + case ramses::EPropertyType::Vec4i: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: ({}, {}, {}, {})", name, value[0], value[1], value[2], value[3]).c_str()); + break; + } + case ramses::EPropertyType::Struct: + if (TreeNode(prop, fmt::format("Struct {}", name))) + { + for (size_t i = 0U; i < prop->getChildCount(); ++i) + { + const auto* child = prop->getChild(i); + drawOutProperty(child, i); + } + ImGui::TreePop(); + } + break; + case ramses::EPropertyType::String: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: {}", name, value).c_str()); + break; + } + case ramses::EPropertyType::Bool: { + auto value = prop->get().value(); + ImGui::TextUnformatted(fmt::format("{}: {}", name, value ? "true" : "false").c_str()); + break; + } + case ramses::EPropertyType::Array: + if (TreeNode(prop, fmt::format("Array {}", name))) + { + for (size_t i = 0U; i < prop->getChildCount(); ++i) + { + const auto* child = prop->getChild(i); + drawOutProperty(child, i); + } + ImGui::TreePop(); + } + break; + } + } + + void LogicEngineGui::DrawDataArray(const ramses::DataArray* obj, std::string_view context) + { + if (obj != nullptr) + { + if (!context.empty()) + { + ImGui::TextUnformatted( + fmt::format("{}: [{}]: {} Type:{}[{}]", context.data(), obj->getSceneObjectId().getValue(), obj->getName(), GetLuaPrimitiveTypeName(obj->getDataType()), obj->getNumElements()).c_str()); + } + else + { + ImGui::TextUnformatted(fmt::format("[{}]: {} Type:{}[{}]", obj->getSceneObjectId().getValue(), obj->getName(), GetLuaPrimitiveTypeName(obj->getDataType()), obj->getNumElements()).c_str()); + } + } + } +} + diff --git a/tools/ramses-viewer/LogicEngineGui.h b/tools/ramses-viewer/LogicEngineGui.h new file mode 100644 index 000000000..c820bff27 --- /dev/null +++ b/tools/ramses-viewer/LogicEngineGui.h @@ -0,0 +1,144 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2021 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#pragma once + +#include "ImguiClientHelper.h" +#include "LogicViewerLog.h" +#include "ramses/client/logic/Collection.h" +#include "ramses/client/logic/LogicEngine.h" +#include "ramses/client/logic/LuaScript.h" +#include "ramses/client/logic/LuaInterface.h" +#include "ramses/client/logic/AnimationNode.h" +#include "ramses/client/logic/TimerNode.h" +#include "ramses/client/logic/AppearanceBinding.h" +#include "ramses/client/logic/CameraBinding.h" +#include "ramses/client/logic/NodeBinding.h" +#include "ramses/client/logic/RenderPassBinding.h" +#include "ramses/client/logic/RenderGroupBinding.h" +#include "ramses/client/logic/MeshNodeBinding.h" +#include "ramses/client/logic/RenderBufferBinding.h" +#include "ramses/client/logic/DataArray.h" +#include "ramses/client/logic/Property.h" +#include "ramses/client/logic/AnchorPoint.h" +#include "ramses/client/logic/SkinBinding.h" +#include "fmt/format.h" +#include + +namespace ramses::internal +{ + struct ViewerSettings; + + class LogicEngineGui + { + public: + explicit LogicEngineGui(const ViewerSettings& settings); + + template + void drawCollection(ramses::LogicEngine& logicEngine, std::string_view ns, const char* headline); + + template + void drawCollection(ramses::Collection collection, std::string_view ns, const char* headline, const C& cb); + + void draw(ramses::LuaInterface* obj); + void draw(ramses::LuaScript* obj); + void draw(ramses::AnimationNode* obj); + void draw(ramses::TimerNode* obj); + void draw(ramses::NodeBinding* obj); + void draw(ramses::CameraBinding* obj); + void draw(ramses::RenderPassBinding* obj); + void draw(ramses::RenderGroupBinding* obj); + void draw(ramses::MeshNodeBinding* obj); + void draw(ramses::AnchorPoint* obj); + void draw(ramses::SkinBinding* obj); + void draw(ramses::AppearanceBinding* obj); + void draw(ramses::RenderBufferBinding* obj); + + void drawNode(ramses::LogicNode* obj); + void drawProperty(ramses::Property* prop, size_t index); + + /** + * copies all node inputs to clipboard (lua syntax) + */ + template + void copyInputs(const std::string_view& ns, Collection collection); + + private: + static bool DrawTreeNode(ramses::LogicObject* obj); + + void drawNodeContextMenu(ramses::LogicNode* obj, const std::string_view& ns); + void drawOutProperty(const ramses::Property* prop, size_t index); + static void DrawDataArray(const ramses::DataArray* obj, std::string_view context = std::string_view()); + + const ViewerSettings& m_settings; + }; + + template + inline void LogicEngineGui::drawCollection(ramses::LogicEngine& logicEngine, std::string_view ns, const char* headline) + { + const bool openCollection = ImGui::CollapsingHeader(headline); + if (ImGui::BeginPopupContextItem(fmt::format("{}ContextMenu", ns).c_str())) + { + if (ImGui::MenuItem(fmt::format("{}: Copy all inputs", headline).c_str())) + { + copyInputs(ns, logicEngine.getCollection()); + } + ImGui::EndPopup(); + } + if (openCollection) + { + for (auto* obj : logicEngine.getCollection()) + { + const bool open = DrawTreeNode(obj); + drawNodeContextMenu(obj, ns); + if (open) + { + draw(obj); + ImGui::TreePop(); + } + } + } + } + + template + void LogicEngineGui::drawCollection(ramses::Collection collection, std::string_view ns, const char* headline, const C& cbDrawItem) + { + const bool openCollection = ImGui::TreeNode(headline); + if (ImGui::BeginPopupContextItem(fmt::format("{}ContextMenu", ns).c_str())) + { + if (ImGui::MenuItem(fmt::format("{}: Copy all inputs", headline).c_str())) + { + copyInputs(ns, collection); + } + ImGui::EndPopup(); + } + if (openCollection) + { + for (auto* obj : collection) + { + cbDrawItem(obj); + } + ImGui::TreePop(); + } + } + + template + inline void LogicEngineGui::copyInputs(const std::string_view& ns, Collection collection) + { + LogicViewerLog::PathVector path; + path.push_back(LogicViewer::ltnModule); + path.push_back(ns); + LogicViewerLog log(m_settings); + for (auto* node : collection) + { + log.logInputs(node, path); + } + ImGui::SetClipboardText(log.getText().c_str()); + } +} + diff --git a/tools/ramses-logic-viewer/LogicViewer.cpp b/tools/ramses-viewer/LogicViewer.cpp similarity index 89% rename from tools/ramses-logic-viewer/LogicViewer.cpp rename to tools/ramses-viewer/LogicViewer.cpp index de7a5085a..debc63f4e 100644 --- a/tools/ramses-logic-viewer/LogicViewer.cpp +++ b/tools/ramses-viewer/LogicViewer.cpp @@ -23,12 +23,13 @@ #include "ramses/client/logic/Property.h" #include "ramses/client/logic/AnchorPoint.h" #include "ramses/client/logic/SkinBinding.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "fmt/format.h" #include "internal/logic/SolHelper.h" #include #include -namespace ramses +namespace ramses::internal { namespace { @@ -74,6 +75,7 @@ namespace ramses , meshNodeBindings(logicEngine) , anchorPoints(logicEngine) , skinBindings(logicEngine) + , renderBufferBindings(logicEngine) { } @@ -91,6 +93,7 @@ namespace ramses NodeListWrapper meshNodeBindings; NodeListWrapper anchorPoints; NodeListWrapper skinBindings; + NodeListWrapper renderBufferBindings; }; const char* const LogicViewer::ltnModule = "rlogic"; @@ -106,6 +109,7 @@ namespace ramses const char* const LogicViewer::ltnMeshNode = "meshNodeBindings"; const char* const LogicViewer::ltnAnchorPoint = "anchorPoints"; const char* const LogicViewer::ltnSkinBinding = "skinBindings"; + const char* const LogicViewer::ltnRenderBuffer = "renderBufferBindings"; const char* const LogicViewer::ltnScreenshot = "screenshot"; const char* const LogicViewer::ltnViews = "views"; const char* const LogicViewer::ltnLink = "link"; @@ -145,6 +149,7 @@ namespace ramses registerNodeListType(m_sol, "MeshNodeBindings"); registerNodeListType(m_sol, "AnchorPoints"); registerNodeListType(m_sol, "SkinBindings"); + registerNodeListType(m_sol, "RenderBufferBindings"); m_sol.new_usertype("LogicNode", sol::meta_function::index, &LogicNodeWrapper::get, sol::meta_function::to_string, &LogicNodeWrapper::toString); m_sol.new_usertype("LogicProperty", ltnPropertyValue, @@ -180,6 +185,8 @@ namespace ramses sol::readonly(&LogicWrapper::anchorPoints), ltnSkinBinding, sol::readonly(&LogicWrapper::skinBindings), + ltnRenderBuffer, + sol::readonly(&LogicWrapper::renderBufferBindings), ltnViews, &LogicWrapper::views, ltnScreenshot, @@ -305,7 +312,7 @@ namespace ramses } } - Result LogicViewer::saveDefaultLuaFile(const std::string& filename, const LogicViewerSettings& settings) + Result LogicViewer::saveDefaultLuaFile(const std::string& filename, const ViewerSettings& settings) { std::ofstream outfile; outfile.open(filename, std::ios::out | std::ios::binary); @@ -313,19 +320,20 @@ namespace ramses { return Result(fmt::format("Could not open file: {}", filename)); } - LogicViewerLog log(m_logicEngine, settings); + LogicViewerLog log(settings); log.logText("function default()\n"); - log.logAllInputs("--Interfaces\n", LogicViewer::ltnInterface); - log.logAllInputs("--Scripts\n", LogicViewer::ltnScript); - log.logAllInputs("--Node bindings\n", LogicViewer::ltnNode); - log.logAllInputs("--Appearance bindings\n", LogicViewer::ltnAppearance); - log.logAllInputs("--Camera bindings\n", LogicViewer::ltnCamera); - log.logAllInputs("--RenderPass bindings\n", LogicViewer::ltnRenderPass); - log.logAllInputs("--RenderGroup bindings\n", LogicViewer::ltnRenderGroup); - log.logAllInputs("--MeshNode bindings\n", LogicViewer::ltnMeshNode); - log.logAllInputs("--Anchor points\n", LogicViewer::ltnAnchorPoint); - log.logAllInputs("--Skin bindings\n", LogicViewer::ltnSkinBinding); + log.logAllInputs(m_logicEngine, "--Interfaces\n", LogicViewer::ltnInterface); + log.logAllInputs(m_logicEngine, "--Scripts\n", LogicViewer::ltnScript); + log.logAllInputs(m_logicEngine, "--Node bindings\n", LogicViewer::ltnNode); + log.logAllInputs(m_logicEngine, "--Appearance bindings\n", LogicViewer::ltnAppearance); + log.logAllInputs(m_logicEngine, "--Camera bindings\n", LogicViewer::ltnCamera); + log.logAllInputs(m_logicEngine, "--RenderPass bindings\n", LogicViewer::ltnRenderPass); + log.logAllInputs(m_logicEngine, "--RenderGroup bindings\n", LogicViewer::ltnRenderGroup); + log.logAllInputs(m_logicEngine, "--MeshNode bindings\n", LogicViewer::ltnMeshNode); + log.logAllInputs(m_logicEngine, "--Anchor points\n", LogicViewer::ltnAnchorPoint); + log.logAllInputs(m_logicEngine, "--Skin bindings\n", LogicViewer::ltnSkinBinding); + log.logAllInputs(m_logicEngine, "--RenderBuffer bindings\n", LogicViewer::ltnRenderBuffer); log.logText("end\n\n"); const char* code = R"( diff --git a/tools/ramses-logic-viewer/LogicViewer.h b/tools/ramses-viewer/LogicViewer.h similarity index 97% rename from tools/ramses-logic-viewer/LogicViewer.h rename to tools/ramses-viewer/LogicViewer.h index 1b754040c..98dbed5b4 100644 --- a/tools/ramses-logic-viewer/LogicViewer.h +++ b/tools/ramses-viewer/LogicViewer.h @@ -16,11 +16,9 @@ #include #include -namespace ramses +namespace ramses::internal { - class LogicEngine; - struct LogicViewerSettings; - class Property; + struct ViewerSettings; class LogicViewer { @@ -41,6 +39,7 @@ namespace ramses static const char* const ltnMeshNode; static const char* const ltnAnchorPoint; static const char* const ltnSkinBinding; + static const char* const ltnRenderBuffer; static const char* const ltnScreenshot; static const char* const ltnViews; static const char* const ltnLink; @@ -146,7 +145,7 @@ namespace ramses /** * saves a simple default lua configuration that can be used as a starting point */ - [[nodiscard]] Result saveDefaultLuaFile(const std::string& filename, const LogicViewerSettings& settings); + [[nodiscard]] Result saveDefaultLuaFile(const std::string& filename, const ViewerSettings& settings); private: void updateEngine(); diff --git a/tools/ramses-viewer/LogicViewerGui.cpp b/tools/ramses-viewer/LogicViewerGui.cpp new file mode 100644 index 000000000..0162a9227 --- /dev/null +++ b/tools/ramses-viewer/LogicViewerGui.cpp @@ -0,0 +1,475 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2021 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#include "LogicViewerGui.h" +#include "LogicEngineGui.h" +#include "LogicViewer.h" +#include "LogicViewerLog.h" +#include "ViewerGuiApp.h" +#include "ViewerSettings.h" +#include "ramses/client/Scene.h" +#include "ramses/client/logic/LogicEngine.h" +#include "ramses/client/logic/LuaScript.h" +#include "ramses/client/logic/LuaInterface.h" +#include "ramses/client/logic/AnimationNode.h" +#include "ramses/client/logic/TimerNode.h" +#include "ramses/client/logic/AppearanceBinding.h" +#include "ramses/client/logic/CameraBinding.h" +#include "ramses/client/logic/NodeBinding.h" +#include "ramses/client/logic/RenderPassBinding.h" +#include "ramses/client/logic/RenderGroupBinding.h" +#include "ramses/client/logic/MeshNodeBinding.h" +#include "ramses/client/logic/DataArray.h" +#include "ramses/client/logic/Property.h" +#include "ramses/client/logic/AnchorPoint.h" +#include "ramses/client/logic/SkinBinding.h" +#include "ramses/client/logic/RenderBufferBinding.h" +#include "internal/logic/StdFilesystemWrapper.h" +#include "internal/PlatformAbstraction/FmtBase.h" +#include "glm/gtc/type_ptr.hpp" + +#ifndef _MSC_VER +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#endif +#include "imgui_internal.h" // for ImGuiSettingsHandler +#ifndef _MSC_VER +#pragma GCC diagnostic pop +#endif + +template <> struct fmt::formatter +{ + template constexpr auto parse(ParseContext& ctx) + { + return ctx.begin(); + } + + template constexpr auto format(const std::chrono::microseconds value, FormatContext& ctx) + { + const auto c = value.count(); + if (c == 0) + return fmt::format_to(ctx.out(), "0"); + return fmt::format_to(ctx.out(), "{}.{:03}", c / 1000, c % 1000); + } +}; + + +namespace ramses::internal +{ + namespace + { + bool TreeNode(const void* ptr_id, const std::string& text) + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + return ImGui::TreeNode(ptr_id, "%s", text.c_str()); + } + + const char* NodeTypeName(const LogicNode* node) + { + const char* name = "Unknown"; + if (node->as() != nullptr) + { + name = "LuaInterface"; + } + else if (node->as() != nullptr) + { + name = "LuaScript"; + } + else if (node->as() != nullptr) + { + name = "Animation"; + } + else if (node->as() != nullptr) + { + name = "NodeBinding"; + } + else if (node->as() != nullptr) + { + name = "AppearanceBinding"; + } + else if (node->as() != nullptr) + { + name = "CameraBinding"; + } + else if (node->as() != nullptr) + { + name = "RenderPassBinding"; + } + else if (node->as() != nullptr) + { + name = "RenderGroupBinding"; + } + else if (node->as() != nullptr) + { + name = "MeshNodeBinding"; + } + else if (node->as() != nullptr) + { + name = "Timer"; + } + else if (node->as() != nullptr) + { + name = "AnchorPoint"; + } + else if (node->as() != nullptr) + { + name = "SkinBinding"; + } + else if (node->as() != nullptr) + { + name = "RenderBufferBinding"; + } + return name; + } + + template + void HelpMarker(const char* desc, Args&& ... args) + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + ImGui::TextDisabled("(?)"); + if (ImGui::IsItemHovered()) + { + ImGui::BeginTooltip(); + ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); + ImGui::TextUnformatted(fmt::format(desc, args...).c_str()); + ImGui::PopTextWrapPos(); + ImGui::EndTooltip(); + } + } + } + + LogicViewerGui::LogicViewerGui(ViewerGuiApp& app, std::string& errorMessage) + : m_settings(*app.getSettings()) + , m_viewer(*app.getLogicViewer()) + , m_logicEngine(m_viewer.getLogic()) + , m_lastErrorMessage(errorMessage) + , m_filename(app.getLuaFile()) + { + m_viewer.enableUpdateReport(m_settings.showUpdateReport, m_updateReportInterval); + } + + void LogicViewerGui::handleShortcuts() + { + if (ImGui::IsKeyPressed(ramses::EKeyCode_Left)) + { + m_viewer.setCurrentView(m_viewer.getCurrentView() - 1); + } + else if (ImGui::IsKeyPressed(ramses::EKeyCode_Right)) + { + m_viewer.setCurrentView(m_viewer.getCurrentView() + 1); + } + else if (ImGui::IsKeyPressed(ramses::EKeyCode_F5)) + { + reloadConfiguration(); + } + else + { + } + } + + void LogicViewerGui::draw() + { + if (m_settings.showLogicWindow) + { + drawWindow(); + } + } + + void LogicViewerGui::drawMenuItemReload() + { + if (ImGui::MenuItem("Reload configuration", "F5")) + { + reloadConfiguration(); + } + } + + void LogicViewerGui::reloadConfiguration() + { + if (fs::exists(m_filename)) + { + loadLuaFile(m_filename); + } + } + + void LogicViewerGui::loadLuaFile(const std::string& filename) + { + auto result = m_viewer.loadLuaFile(filename); + if (!result.ok()) + { + m_lastErrorMessage = result.getMessage(); + } + } + + void LogicViewerGui::drawGlobalContextMenuItems() + { + drawMenuItemReload(); + if (ImGui::MenuItem("Next view", "Arrow Right", nullptr, (m_viewer.getCurrentView() < m_viewer.getViewCount()))) + m_viewer.setCurrentView(m_viewer.getCurrentView() + 1); + if (ImGui::MenuItem("Previous view", "Arrow Left", nullptr, m_viewer.getCurrentView() > 1)) + m_viewer.setCurrentView(m_viewer.getCurrentView() - 1); + } + + void LogicViewerGui::drawWindow() + { + const auto windowTitle = m_logicEngine.getName().empty() + ? fmt::format("LogicEngine[{}]", m_logicEngine.getSceneObjectId().getValue()) + : fmt::format("LogicEngine[{}]: {}", m_logicEngine.getSceneObjectId().getValue(), m_logicEngine.getName()); + if (!ImGui::Begin(windowTitle.c_str(), &m_settings.showLogicWindow, ImGuiWindowFlags_MenuBar)) + { + ImGui::End(); + return; + } + + drawMenuBar(); + drawCurrentView(); + + if (m_settings.showUpdateReport) + { + drawUpdateReport(); + } + + ImGui::End(); + } + + void LogicViewerGui::drawMenuBar() + { + if (ImGui::BeginMenuBar()) + { + if (ImGui::BeginMenu("File")) + { + drawMenuItemReload(); + ImGui::EndMenu(); + } + + if (ImGui::BeginMenu("Settings")) + { + if (ImGui::MenuItem("Show Update Report", nullptr, &m_settings.showUpdateReport)) + { + m_viewer.enableUpdateReport(m_settings.showUpdateReport, m_updateReportInterval); + ImGui::MarkIniSettingsDirty(); + } + ImGui::Separator(); + auto changed = ImGui::MenuItem("Lua: prefer identifiers (scripts.foo)", nullptr, &m_settings.luaPreferIdentifiers); + changed = ImGui::MenuItem("Lua: prefer object ids (scripts[1])", nullptr, &m_settings.luaPreferObjectIds) || changed; + ImGui::EndMenu(); + + if (changed) + { + ImGui::MarkIniSettingsDirty(); + } + } + ImGui::EndMenuBar(); + } + } + + void LogicViewerGui::drawCurrentView() + { + const auto viewCount = static_cast(m_viewer.getViewCount()); + const auto& status = m_viewer.getLastResult(); + if (!status.ok()) + { + ImGui::TextUnformatted(fmt::format("Error occurred in {}", m_viewer.getLuaFilename()).c_str()); + ImGui::TextUnformatted(status.getMessage().c_str()); + } + else if (m_viewer.getLuaFilename().empty()) + { + drawSaveDefaultLuaFile(); + } + else if (viewCount > 0) + { + auto viewId = static_cast(m_viewer.getCurrentView()); + const auto view = m_viewer.getView(viewId); + ImGui::TextUnformatted(!view.name().empty() ? view.name().c_str() : ""); + ImGui::SetNextItemWidth(100); + if (ImGui::InputInt("##View", &viewId)) + m_viewer.setCurrentView(viewId); + ImGui::SameLine(); + ImGui::TextUnformatted(fmt::format("of {}", viewCount).c_str()); + + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + ImGui::TextWrapped("%s", view.description().c_str()); + + LogicEngineGui engineGui(m_settings); + for (size_t i = 0U; i < view.getInputCount(); ++i) + { + auto* prop = view.getInput(i); + if (prop) + engineGui.drawProperty(view.getInput(i), i); + } + } + else + { + ImGui::TextUnformatted("no views defined in configuration file"); + } + + if (m_settings.showUpdateReport) + { + ImGui::Separator(); + ImGui::TextUnformatted(fmt::format("Average Update Time: {} ms", m_viewer.getUpdateReport().getTotalTime().average).c_str()); + ImGui::SameLine(); + HelpMarker("Time it took to update the whole logic nodes network (LogicEngine::update())."); + } + } + + void LogicViewerGui::drawUpdateReport() + { + const bool open = ImGui::CollapsingHeader("Update Report"); + if (open) + { + auto interval = static_cast(m_updateReportInterval); + bool refresh = m_viewer.isUpdateReportEnabled(); + if (ImGui::Checkbox("Auto Refresh", &refresh)) + { + m_viewer.enableUpdateReport(refresh, m_updateReportInterval); + } + ImGui::SetNextItemWidth(100); + if (ImGui::DragInt("Refresh Interval", &interval, 0.5f, 1, 1000, "%d Frames")) + { + m_updateReportInterval = static_cast(interval); + m_viewer.enableUpdateReport(refresh, m_updateReportInterval); + } + const auto& report = m_viewer.getUpdateReport(); + const auto& executed = report.getNodesExecuted(); + const auto& skipped = report.getNodesSkippedExecution(); + const auto longest = report.getTotalTime().maxValue; + + ImGui::Separator(); + ImGui::TextUnformatted("Summary:"); + ImGui::SameLine(); + HelpMarker("Timing data is collected and summarized for {} frames.\n'min', 'max', 'avg' show the minimum, maximum, and average value for the measured interval.", m_updateReportInterval); + ImGui::Indent(); + + const auto& updateTime = report.getTotalTime(); + ImGui::TextUnformatted(fmt::format("Total Update Time (ms): max:{} min:{} avg:{}", updateTime.maxValue, updateTime.minValue, updateTime.average).c_str()); + ImGui::SameLine(); + HelpMarker("Time it took to update the whole logic nodes network (LogicEngine::update())."); + + const auto& sortTime = report.getSortTime(); + ImGui::TextUnformatted(fmt::format("Topology Sort Time (ms): max:{} min:{} avg:{}", sortTime.maxValue, sortTime.minValue, sortTime.average).c_str()); + ImGui::SameLine(); + HelpMarker("Time it took to sort logic nodes by their topology during update (see ramses::LogicEngineReport::getTopologySortExecutionTime()"); + + const auto& links = report.getLinkActivations(); + ImGui::TextUnformatted(fmt::format("Activated Links: max:{} min:{} avg:{}", links.maxValue, links.minValue, links.average).c_str()); + ImGui::SameLine(); + HelpMarker("Number of input properties that had been updated by an output property (see ramses::LogicEngineReport::getTotalLinkActivations())."); + ImGui::Unindent(); + + ImGui::TextUnformatted(fmt::format("Details for the longest update ({} ms):", longest).c_str()); + LogicEngineGui engineGui(m_settings); + if (TreeNode("Executed", fmt::format("Executed Nodes ({}):", executed.size()))) + { + for (auto& timedNode : executed) + { + auto* node = timedNode.first; + const auto percentage = (longest.count() > 0u) ? (100u * timedNode.second / longest) : 0u; + if (TreeNode(node, fmt::format("{}[{}]: {} [time:{} ms, {}%]", NodeTypeName(node), node->getSceneObjectId().getValue(), node->getName(), timedNode.second, percentage))) + { + engineGui.drawNode(node); + ImGui::TreePop(); + } + } + ImGui::TreePop(); + } + + if (TreeNode("Skipped", fmt::format("Skipped Nodes ({}):", skipped.size()))) + { + for (auto& node : skipped) + { + if (TreeNode(node, fmt::format("{}[{}]: {}", NodeTypeName(node), node->getSceneObjectId().getValue(), node->getName()))) + { + engineGui.drawNode(node); + ImGui::TreePop(); + } + } + ImGui::TreePop(); + } + } + } + + void LogicViewerGui::drawSaveDefaultLuaFile() + { + ImGui::TextUnformatted("No lua configuration file found."); + ImGui::InputText("##filename", &m_filename); + ImGui::SameLine(); + if (ImGui::Button("Save default")) + { + fs::path luafile(m_filename); + if (fs::exists(luafile)) + { + ImGui::OpenPopup("Overwrite?"); + } + else if (!luafile.empty()) + { + saveDefaultLuaFile(); + } + } + ImGui::SameLine(); + if (ImGui::Button("Open")) + { + fs::path luafile(m_filename); + if (fs::exists(luafile)) + { + loadLuaFile(m_filename); + } + else if (!luafile.empty()) + { + m_lastErrorMessage = "File does not exist: " + m_filename; + } + } + + if (ImGui::BeginPopupModal("Overwrite?", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::TextUnformatted(fmt::format("File exists:\n{}\nOverwrite default lua configuration?", m_filename).c_str()); + ImGui::Separator(); + + if (ImGui::Button("OK", ImVec2(120, 0))) + { + saveDefaultLuaFile(); + ImGui::CloseCurrentPopup(); + } + ImGui::SetItemDefaultFocus(); + ImGui::SameLine(); + if (ImGui::Button("Cancel", ImVec2(120, 0))) + { + ImGui::CloseCurrentPopup(); + } + ImGui::EndPopup(); + } + } + + void LogicViewerGui::DrawDataArray(const ramses::DataArray* obj, std::string_view context) + { + if (obj != nullptr) + { + if (!context.empty()) + { + ImGui::TextUnformatted( + fmt::format("{}: [{}]: {} Type:{}[{}]", context.data(), obj->getSceneObjectId().getValue(), obj->getName(), GetLuaPrimitiveTypeName(obj->getDataType()), obj->getNumElements()).c_str()); + } + else + { + ImGui::TextUnformatted(fmt::format("[{}]: {} Type:{}[{}]", obj->getSceneObjectId().getValue(), obj->getName(), GetLuaPrimitiveTypeName(obj->getDataType()), obj->getNumElements()).c_str()); + } + } + } + + void LogicViewerGui::saveDefaultLuaFile() + { + const auto result = m_viewer.saveDefaultLuaFile(m_filename, m_settings); + if (result.ok()) + { + loadLuaFile(m_filename); + } + else + { + m_lastErrorMessage = result.getMessage(); + } + } +} + diff --git a/tools/ramses-viewer/LogicViewerGui.h b/tools/ramses-viewer/LogicViewerGui.h new file mode 100644 index 000000000..ef45c8bff --- /dev/null +++ b/tools/ramses-viewer/LogicViewerGui.h @@ -0,0 +1,65 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2021 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#pragma once + +#include "ImguiClientHelper.h" +#include "ramses/client/logic/Collection.h" +#include + +namespace ramses +{ + class LogicEngine; + class DataArray; +} + +namespace ramses::internal +{ + class ViewerGuiApp; + class LogicViewer; + struct ViewerSettings; + + class LogicViewerGui + { + public: + /** + * @param luafile the luafile argument provided by command line + * If it does not exist the LogicViewerGui will provide a UI to save the default settings + */ + explicit LogicViewerGui(ViewerGuiApp& app, std::string& errorMessage); + void draw(); + + void drawGlobalContextMenuItems(); + + void handleShortcuts(); + + private: + void drawMenuItemReload(); + + void drawWindow(); + void drawMenuBar(); + void drawCurrentView(); + void drawUpdateReport(); + void drawSaveDefaultLuaFile(); + + static void DrawDataArray(const ramses::DataArray* obj, std::string_view context = std::string_view()); + + void reloadConfiguration(); + void loadLuaFile(const std::string& filename); + void saveDefaultLuaFile(); + + ViewerSettings& m_settings; + LogicViewer& m_viewer; + ramses::LogicEngine& m_logicEngine; + + std::string& m_lastErrorMessage; + std::string m_filename; + size_t m_updateReportInterval = 60u; + }; +} + diff --git a/tools/ramses-logic-viewer/LogicViewerLog.cpp b/tools/ramses-viewer/LogicViewerLog.cpp similarity index 96% rename from tools/ramses-logic-viewer/LogicViewerLog.cpp rename to tools/ramses-viewer/LogicViewerLog.cpp index 6792ba961..4357d0394 100644 --- a/tools/ramses-logic-viewer/LogicViewerLog.cpp +++ b/tools/ramses-viewer/LogicViewerLog.cpp @@ -8,18 +8,17 @@ #include "LogicViewerLog.h" #include "LogicViewer.h" -#include "LogicViewerSettings.h" +#include "ViewerSettings.h" #include "ramses/client/Scene.h" #include "ramses/client/logic/LogicEngine.h" #include "ramses/client/logic/LogicNode.h" #include "ramses/client/logic/Property.h" #include "fmt/format.h" -namespace ramses +namespace ramses::internal { - LogicViewerLog::LogicViewerLog(ramses::LogicEngine& engine, const LogicViewerSettings& settings) + LogicViewerLog::LogicViewerLog(const ViewerSettings& settings) : m_settings(settings) - , m_logicEngine(engine) { } diff --git a/tools/ramses-logic-viewer/LogicViewerLog.h b/tools/ramses-viewer/LogicViewerLog.h similarity index 71% rename from tools/ramses-logic-viewer/LogicViewerLog.h rename to tools/ramses-viewer/LogicViewerLog.h index 6a30bcab5..2a445c02c 100644 --- a/tools/ramses-logic-viewer/LogicViewerLog.h +++ b/tools/ramses-viewer/LogicViewerLog.h @@ -13,21 +13,18 @@ #include "LogicViewer.h" #include -namespace ramses +namespace ramses::internal { - class LogicEngine; - class Property; - class LogicNode; - struct LogicViewerSettings; + struct ViewerSettings; class LogicViewerLog { public: - explicit LogicViewerLog(ramses::LogicEngine& engine, const LogicViewerSettings& settings); + explicit LogicViewerLog(const ViewerSettings& settings); void logText(const std::string& text); - template void logAllInputs(std::string_view headline, std::string_view ltn); + template void logAllInputs(ramses::LogicEngine& logicEngine, std::string_view headline, std::string_view ltn); using PathVector = std::vector; void logInputs(ramses::LogicNode* obj, const PathVector& path); @@ -39,20 +36,19 @@ namespace ramses } private: - const LogicViewerSettings& m_settings; - ramses::LogicEngine& m_logicEngine; + const ViewerSettings& m_settings; std::string m_text; }; template - inline void LogicViewerLog::logAllInputs(std::string_view headline, std::string_view ltn) + inline void LogicViewerLog::logAllInputs(ramses::LogicEngine& logicEngine, std::string_view headline, std::string_view ltn) { PathVector path; const std::string indent = " "; std::string name = indent + LogicViewer::ltnModule + "." + ltn.data(); path.push_back(name); logText(indent + headline.data()); - for (auto* node : m_logicEngine.getCollection()) + for (auto* node : logicEngine.getCollection()) { logInputs(node, path); } diff --git a/tools/ramses-logic-viewer/LogicViewerLuaTypes.cpp b/tools/ramses-viewer/LogicViewerLuaTypes.cpp similarity index 98% rename from tools/ramses-logic-viewer/LogicViewerLuaTypes.cpp rename to tools/ramses-viewer/LogicViewerLuaTypes.cpp index a6e7ecba3..461f1e7a7 100644 --- a/tools/ramses-logic-viewer/LogicViewerLuaTypes.cpp +++ b/tools/ramses-viewer/LogicViewerLuaTypes.cpp @@ -22,6 +22,7 @@ #include "ramses/client/logic/MeshNodeBinding.h" #include "ramses/client/logic/AnchorPoint.h" #include "ramses/client/logic/SkinBinding.h" +#include "ramses/client/logic/RenderBufferBinding.h" #include "ramses/client/logic/Property.h" #include "internal/logic/SolHelper.h" #include "fmt/format.h" @@ -54,7 +55,7 @@ namespace glm } } -namespace ramses +namespace ramses::internal { namespace { @@ -318,5 +319,6 @@ namespace ramses template struct NodeListWrapper; template struct NodeListWrapper; template struct NodeListWrapper; + template struct NodeListWrapper; } // namespace ramses diff --git a/tools/ramses-logic-viewer/LogicViewerLuaTypes.h b/tools/ramses-viewer/LogicViewerLuaTypes.h similarity index 98% rename from tools/ramses-logic-viewer/LogicViewerLuaTypes.h rename to tools/ramses-viewer/LogicViewerLuaTypes.h index 132cf8697..ce76b4686 100644 --- a/tools/ramses-logic-viewer/LogicViewerLuaTypes.h +++ b/tools/ramses-viewer/LogicViewerLuaTypes.h @@ -16,7 +16,10 @@ namespace ramses class Property; class LogicNode; class LogicEngine; +} +namespace ramses::internal +{ struct PropertyWrapper { explicit PropertyWrapper(ramses::Property& property); diff --git a/tools/ramses-scene-viewer/src/ProgressMonitor.h b/tools/ramses-viewer/ProgressMonitor.h similarity index 100% rename from tools/ramses-scene-viewer/src/ProgressMonitor.h rename to tools/ramses-viewer/ProgressMonitor.h diff --git a/tools/ramses-scene-viewer/src/ResourceList.h b/tools/ramses-viewer/ResourceList.h similarity index 100% rename from tools/ramses-scene-viewer/src/ResourceList.h rename to tools/ramses-viewer/ResourceList.h diff --git a/tools/ramses-logic-viewer/Result.h b/tools/ramses-viewer/Result.h similarity index 98% rename from tools/ramses-logic-viewer/Result.h rename to tools/ramses-viewer/Result.h index 67606f604..ccaddf0f1 100644 --- a/tools/ramses-logic-viewer/Result.h +++ b/tools/ramses-viewer/Result.h @@ -10,7 +10,7 @@ #include #include -namespace ramses +namespace ramses::internal { /** * @brief Result class as a return object for functions diff --git a/tools/ramses-scene-viewer/src/SceneSetup.h b/tools/ramses-viewer/SceneSetup.h similarity index 97% rename from tools/ramses-scene-viewer/src/SceneSetup.h rename to tools/ramses-viewer/SceneSetup.h index 920383927..dc2499154 100644 --- a/tools/ramses-scene-viewer/src/SceneSetup.h +++ b/tools/ramses-viewer/SceneSetup.h @@ -47,8 +47,8 @@ class OffscreenSetup : public ISceneSetup m_ob = renderer->createOffscreenBuffer(display, width, height); renderer->flush(); - static const std::array imgbuf = { 255, 255, 255, 255 }; - const std::vector mipLevelData{ ramses::MipLevelData(4, imgbuf.data()) }; + static const std::vector imgbuf(4, std::byte{ 255 }); + const std::vector mipLevelData = { imgbuf }; auto* texture = imguiHelper.getScene()->createTexture2D(ramses::ETextureFormat::RGBA8, 1, 1, mipLevelData); m_sampler = imguiHelper.getScene()->createTextureSampler( ramses::ETextureAddressMode::Clamp, ramses::ETextureAddressMode::Clamp, ramses::ETextureSamplingMethod::Linear, ramses::ETextureSamplingMethod::Linear, *texture); diff --git a/tools/ramses-scene-viewer/src/SceneViewerGui.cpp b/tools/ramses-viewer/SceneViewerGui.cpp similarity index 91% rename from tools/ramses-scene-viewer/src/SceneViewerGui.cpp rename to tools/ramses-viewer/SceneViewerGui.cpp index aab19d392..486889138 100644 --- a/tools/ramses-scene-viewer/src/SceneViewerGui.cpp +++ b/tools/ramses-viewer/SceneViewerGui.cpp @@ -8,12 +8,30 @@ // ------------------------------------------------------------------------- #include "SceneViewerGui.h" +#include "ViewerGuiApp.h" +#include "LogicEngineGui.h" #include "impl/SceneDumper.h" #include "ramses/renderer/DisplayConfig.h" #include "ramses/client/Scene.h" #include "ramses/client/ramses-utils.h" +#include "ramses/client/logic/LuaInterface.h" #include "impl/SceneImpl.h" +#include "impl/logic/LogicEngineImpl.h" +#include "impl/logic/LogicObjectImpl.h" +#include "impl/logic/LuaInterfaceImpl.h" +#include "impl/logic/LuaScriptImpl.h" +#include "impl/logic/AnchorPointImpl.h" +#include "impl/logic/AnimationNodeImpl.h" +#include "impl/logic/TimerNodeImpl.h" +#include "impl/logic/NodeBindingImpl.h" +#include "impl/logic/AppearanceBindingImpl.h" +#include "impl/logic/CameraBindingImpl.h" +#include "impl/logic/MeshNodeBindingImpl.h" +#include "impl/logic/RenderGroupBindingImpl.h" +#include "impl/logic/RenderPassBindingImpl.h" +#include "impl/logic/SkinBindingImpl.h" +#include "impl/logic/RenderBufferBindingImpl.h" #include "impl/NodeImpl.h" #include "impl/PickableObjectImpl.h" #include "impl/MeshNodeImpl.h" @@ -186,15 +204,13 @@ namespace ramses::internal template bool SceneViewerGui::drawRamsesObject(SceneObjectImpl& obj, const C& drawTreeNode) { - ramses::ValidationReport report; - obj.getRamsesObject().validate(report); - const bool hasIssues = report.hasIssue(); - const bool isUnused = !m_usedObjects.contains(&obj); - if (report.hasError()) + const auto issueType = m_validationCache.getIssueType(obj); + const bool isUnused = (obj.getType() != ERamsesObjectType::LogicObject) && !m_usedObjects.contains(&obj); + if (issueType.has_value() && *issueType == EIssueType::Error) { ImGui::PushStyleColor(ImGuiCol_Text, ImColor(255, 0, 0).Value); } - else if (hasIssues) + else if (issueType.has_value()) { ImGui::PushStyleColor(ImGuiCol_Text, ImColor(255, 255, 0).Value); } @@ -215,10 +231,10 @@ namespace ramses::internal ImGui::EndPopup(); } - if (hasIssues) + if (issueType.has_value()) { if (isOpen) - DrawIssues(obj, report); + DrawIssues(obj, m_validationCache); ImGui::PopStyleColor(); } else if (isUnused) @@ -239,11 +255,15 @@ namespace ramses::internal }); } - void SceneViewerGui::DrawIssues(const SceneObjectImpl& obj, const ramses::ValidationReport& report) + void SceneViewerGui::DrawIssues(const SceneObjectImpl& obj, const ValidationCache& report) { - for (auto& m : report.getIssues()) + const auto range = report.getIssues(obj); + for (auto it = range.first; it != range.second; ++it) { - if (m.object == &obj.getRamsesObject() && m.type <= ramses::EIssueType::Warning) + auto m = *it; + // hide child issues unless it's a logic object + bool showObj = m.object->isOfType(ERamsesObjectType::LogicObject) || (m.object == &obj.getRamsesObject()); + if (showObj && m.type <= ramses::EIssueType::Warning) { switch (m.type) { @@ -291,12 +311,15 @@ namespace ramses::internal } } - SceneViewerGui::SceneViewerGui(ramses::Scene& scene, const std::string& filename, ImguiClientHelper& imguiHelper, const ramses::ValidationReport& report) + SceneViewerGui::SceneViewerGui(ViewerGuiApp& app, ramses::Scene& scene, std::string& errorMessage, ProgressMonitor& progressMonitor) : m_scene(scene) - , m_validationReport(report) - , m_loadedSceneFile(filename) - , m_filename(filename) - , m_imageCache(imguiHelper.getScene()) + , m_validationCache(app.getValidationReport()) + , m_loadedSceneFile(app.getSceneFile()) + , m_filename(app.getSceneFile()) + , m_lastErrorMessage(errorMessage) + , m_imageCache(app.getImguiClientHelper()->getScene()) + , m_settings(*app.getSettings()) + , m_progressMonitor(progressMonitor) { ramses::internal::StringOutputStream dummyStream; SceneDumper sceneDumper(scene.impl()); @@ -600,6 +623,12 @@ namespace ramses::internal case ramses::ERamsesObjectType::BlitPass: drawBlitPass(static_cast(obj)); break; + case ramses::ERamsesObjectType::LogicEngine: + drawLogicEngine(static_cast(obj)); + break; + case ramses::ERamsesObjectType::LogicObject: + drawLogicObject(static_cast(obj)); + break; case ramses::ERamsesObjectType::Invalid: case ramses::ERamsesObjectType::ClientObject: case ramses::ERamsesObjectType::RamsesObject: @@ -608,14 +637,104 @@ namespace ramses::internal case ramses::ERamsesObjectType::Scene: case ramses::ERamsesObjectType::Camera: case ramses::ERamsesObjectType::Resource: - case ramses::ERamsesObjectType::LogicEngine: - case ramses::ERamsesObjectType::LogicObject: ImGui::Text("tbd."); } ImGui::TreePop(); } } + void SceneViewerGui::drawLogicEngine(LogicEngineImpl& obj) + { + auto& engine = static_cast(obj.getRamsesObject()); + LogicEngineGui logicGui(m_settings); + + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnInterface, "Interfaces", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnScript, "Scripts", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnAnimation, "AnimationNodes", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnTimer, "Timer Nodes", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnAppearance, "Appearance Bindings", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnNode, "Node Bindings", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnCamera, "Camera Bindings", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnRenderPass, "RenderPass Bindings", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnRenderGroup, "RenderGroup Bindings", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnMeshNode, "MeshNode Bindings", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnAnchorPoint, "Anchor Bindings", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnSkinBinding, "Skin Bindings", [&](auto* o) { draw(o->impl()); }); + logicGui.drawCollection(engine.getCollection(), LogicViewer::ltnRenderBuffer, "RenderBuffer Bindings", [&](auto* o) { draw(o->impl()); }); + } + + void SceneViewerGui::drawLogicObject(LogicObjectImpl& obj) + { + LogicEngineGui engineGui(m_settings); + auto* logicNode = obj.getLogicObject().as(); + assert(logicNode); + auto* appearanceBinding = logicNode->as(); + auto* cameraBinding = logicNode->as(); + auto* nodeBinding = logicNode->as(); + auto* renderGroupBinding = logicNode->as(); + auto* renderPassBinding = logicNode->as(); + auto* meshNodeBinding = logicNode->as(); + auto* skinBinding = logicNode->as(); + auto* anchorPoint = logicNode->as(); + auto* animationNode = logicNode->as(); + auto* renderBufferBinding = logicNode->as(); + if (appearanceBinding) + { + engineGui.drawNode(appearanceBinding); + draw(appearanceBinding->getRamsesAppearance().impl()); + } + else if (animationNode) + { + engineGui.draw(animationNode); + } + else if (cameraBinding) + { + engineGui.drawNode(cameraBinding); + draw(cameraBinding->getRamsesCamera().impl()); + } + else if (nodeBinding) + { + engineGui.drawNode(nodeBinding); + draw(nodeBinding->getRamsesNode().impl()); + } + else if (meshNodeBinding) + { + engineGui.drawNode(meshNodeBinding); + draw(meshNodeBinding->getRamsesMeshNode().impl()); + } + else if (renderGroupBinding) + { + engineGui.drawNode(renderGroupBinding); + draw(renderGroupBinding->getRamsesRenderGroup().impl()); + } + else if (renderPassBinding) + { + engineGui.drawNode(renderPassBinding); + draw(renderPassBinding->getRamsesRenderPass().impl()); + } + else if (skinBinding) + { + engineGui.drawNode(skinBinding); + ImGui::TextUnformatted(fmt::format("Ramses Uniform input: {}", skinBinding->getAppearanceUniformInput().getName()).c_str()); + draw(skinBinding->getAppearanceBinding().getRamsesAppearance().impl()); + } + else if (renderBufferBinding) + { + engineGui.drawNode(renderBufferBinding); + draw(renderBufferBinding->getRenderBuffer().impl()); + } + else if (anchorPoint) + { + engineGui.drawNode(anchorPoint); + draw(anchorPoint->impl().getNodeBinding().getRamsesNode().impl()); + draw(anchorPoint->impl().getCameraBinding().getRamsesCamera().impl()); + } + else + { + engineGui.drawNode(logicNode); + } + } + void SceneViewerGui::drawNode(NodeImpl& obj) { int vis = static_cast(obj.getVisibility()); @@ -750,7 +869,7 @@ namespace ramses::internal if (obj.isFrustumPlanesBound()) { ImGui::Text("Frustum (l,r,b,t):"); - auto frustum = const_cast(findDataObject(obj.getFrustrumPlanesHandle())); + auto frustum = const_cast(findDataObject(obj.getFrustumPlanesHandle())); if (frustum != nullptr) { ImGui::SameLine(); @@ -758,7 +877,7 @@ namespace ramses::internal } ImGui::Text("Frustum (n,f):"); - auto nearFar = const_cast(findDataObject(obj.getFrustrumNearFarPlanesHandle())); + auto nearFar = const_cast(findDataObject(obj.getFrustumNearFarPlanesHandle())); if (nearFar != nullptr) { ImGui::SameLine(); @@ -1448,7 +1567,7 @@ namespace ramses::internal ImGui::BulletText("size (kB): %" PRIu32, static_cast(it->data.size() / 1024)); if (ImGui::Button("Save png")) { - const auto filename = fmt::format("{:04}_Texture2DBuffer.png", obj.getObjectRegistryHandle().asMemoryHandle()); + const auto filename = fmt::format("{:04}_Texture2DBuffer.png", obj.getSceneObjectId()); m_lastErrorMessage = imgui::SaveToPng(reinterpret_cast(it->data.data()), it->data.size(), tb.textureFormat, it->width, it->height, filename); } imgui::PreviewImage(m_imageCache.get(*it, tb.textureFormat), ImVec2(128, 128)); @@ -1691,8 +1810,8 @@ namespace ramses::internal }); drawRefs("Used by Camera", obj.impl(), [&](const ramses::Camera* ref) { - auto fp = findDataObject(ref->impl().getFrustrumPlanesHandle()); - auto nf = findDataObject(ref->impl().getFrustrumNearFarPlanesHandle()); + auto fp = findDataObject(ref->impl().getFrustumPlanesHandle()); + auto nf = findDataObject(ref->impl().getFrustumNearFarPlanesHandle()); auto pos = findDataObject(ref->impl().getViewportOffsetHandle()); auto size = findDataObject(ref->impl().getViewportSizeHandle()); const auto objPtr = &obj; @@ -1921,7 +2040,7 @@ namespace ramses::internal { m_resourceInfo->setDisplayLimit(displayLimit); } - ImGui::TextUnformatted(fmt::format("Resources sorted by {} (descending):", m_resourceInfo->orderCriteriaItems[m_resourceInfo->getOrderCriteriaIndex()]).c_str()); + ImGui::TextUnformatted(fmt::format("Resources sorted by {} (decending):", m_resourceInfo->orderCriteriaItems[m_resourceInfo->getOrderCriteriaIndex()]).c_str()); for (auto it : *m_resourceInfo) { draw(it->impl()); @@ -1954,11 +2073,11 @@ namespace ramses::internal { auto& renderPass = static_cast(pObj->impl()); const ramses::RenderTarget* rt = renderPass.getRenderTarget(); - const auto handle = renderPass.getObjectRegistryHandle().asMemoryHandle(); + const auto handle = renderPass.getSceneObjectId().getValue(); const char* name = renderPass.getName().c_str(); - auto treeNode = [&]() { return ImGui::TreeNode(&renderPass, "RenderPass[%u]: %s", handle, name); }; - auto treeNodeRT = [&]() { return ImGui::TreeNode(&renderPass, "RenderPass[%u]: %s ", handle, name, rt->getWidth(), rt->getHeight()); }; + auto treeNode = [&]() { return ImGui::TreeNode(&renderPass, "RenderPass[%lu]: %s", handle, name); }; + auto treeNodeRT = [&]() { return ImGui::TreeNode(&renderPass, "RenderPass[%lu]: %s ", handle, name, rt->getWidth(), rt->getHeight()); }; const bool isOpen = (rt == nullptr) ? drawRamsesObject(renderPass, treeNode) : drawRamsesObject(renderPass, treeNodeRT); if (isOpen) { @@ -1971,7 +2090,7 @@ namespace ramses::internal void SceneViewerGui::drawErrors() { - if (m_validationReport.hasIssue()) + if (!m_validationCache.getAllIssues().empty()) { if (ImGui::CollapsingHeader("Objects with warnings/errors")) { @@ -1979,7 +2098,7 @@ namespace ramses::internal { ImGui::LogToClipboard(); ImGui::LogText("IssueType, Message, ObjectType, Name, Id\n"); - for (auto& issue : m_validationReport.getIssues()) + for (auto& issue : m_validationCache.getAllIssues()) { if (issue.object) { @@ -1999,7 +2118,7 @@ namespace ramses::internal } ImGui::Separator(); const ramses::RamsesObject* lastVisited = nullptr; - for (auto& msg : m_validationReport.getIssues()) + for (auto& msg : m_validationCache.getAllIssues()) { if (msg.type <= ramses::EIssueType::Warning) { @@ -2064,163 +2183,34 @@ namespace ramses::internal void SceneViewerGui::draw() { - if (ImGui::IsKeyPressed(ramses::EKeyCode_F11)) - { - m_settings.showWindow = !m_settings.showWindow; - } - - if (ImGui::IsKeyPressed(ramses::EKeyCode_F10)) - { - m_settings.showPreview = !m_settings.showPreview; - } - - if (ImGui::BeginPopupContextVoid("GlobalContextMenu")) - { - drawMenuItemShowWindow(); - drawMenuItemShowPreview(); - ImGui::Separator(); - drawMenuItemCopyTexture2D(); - drawMenuItemStorePng(); - drawMenuItemExportShaderSources(); - ImGui::EndPopup(); - } - - if (m_progress.isRunning() && !m_progress.canceled) - { - ImGui::OpenPopup("Progress"); - } - - if (ImGui::BeginPopupModal("Progress", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) - { - const uint32_t current = m_progress.current; - ImGui::TextUnformatted(m_progress.getDescription().c_str()); - ImGui::TextUnformatted(fmt::format("{} of {}", current, m_progress.getTotal()).c_str()); - ImGui::Separator(); - if (ImGui::Button("Cancel", ImVec2(120,0))) - { - m_progress.canceled = true; - ImGui::CloseCurrentPopup(); - } - if (!m_progress.isRunning()) - { - ImGui::CloseCurrentPopup(); - auto result = m_progress.getResult(); - if (!result.empty()) - { - m_lastErrorMessage = fmt::format("{}", fmt::join(result, "\n")); - } - } - ImGui::EndPopup(); - } - - if (!m_lastErrorMessage.empty()) - { - ImGui::OpenPopup("Error"); - } - - if (ImGui::BeginPopupModal("Error", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) - { - ImGui::TextUnformatted(m_lastErrorMessage.c_str()); - ImGui::Separator(); - - if (ImGui::Button("OK", ImVec2(120, 0))) - { - m_lastErrorMessage.clear(); - ImGui::CloseCurrentPopup(); - } - ImGui::SameLine(); - if (ImGui::Button("Copy Message", ImVec2(120, 0))) - { - ImGui::LogToClipboard(); - ImGui::LogText("%s", m_lastErrorMessage.c_str()); - ImGui::LogFinish(); - } - ImGui::EndPopup(); - } - - drawSceneTexture(); drawInspectionWindow(); if (m_nodeVisibilityChanged) { - // refresh resource information in next iteration - m_nodeVisibilityChanged = false; + // refresh resource information in next interation + m_nodeVisibilityChanged = false; // TODO: won't work if node visibility changed by logic gui m_resourceInfo->clear(); } } - void SceneViewerGui::setSceneTexture(ramses::TextureSampler* sampler, uint32_t width, uint32_t height) - { - m_sceneTexture = sampler; - m_sceneTextureSize.x = static_cast(width); - m_sceneTextureSize.y = static_cast(height); - } - - void SceneViewerGui::zoomIn() - { - if (m_settings.zoomIx < (static_cast(m_settings.zoomLevels.size()) - 1)) - { - ++m_settings.zoomIx; - } - } - - void SceneViewerGui::zoomOut() - { - if (m_settings.zoomIx > 0) - { - --m_settings.zoomIx; - } - } - - void SceneViewerGui::drawSceneTexture() + void SceneViewerGui::drawGlobalContextMenuItems() { - if (m_sceneTexture) - { - if (m_settings.showPreview) - { - if (ImGui::Begin("Preview", &m_settings.showPreview, ImGuiWindowFlags_AlwaysAutoResize)) - { - if (ImGui::GetIO().KeyCtrl) - { - if (ImGui::GetIO().MouseWheel >= 1.f) - { - zoomIn(); - } - if (ImGui::GetIO().MouseWheel <= -1.f) - { - zoomOut(); - } - } - const auto f = m_settings.zoomLevels[m_settings.zoomIx]; - if (ImGui::SmallButton("-")) - zoomOut(); - ImGui::SameLine(); - if (ImGui::SmallButton("+")) - zoomIn(); - ImGui::SameLine(); - ImGui::Text("Zoom %d%%", static_cast(f * 100)); - ImVec2 size(m_sceneTextureSize.x * f, m_sceneTextureSize.y * f); - ImGui::Image(m_sceneTexture, size, ImVec2(0, 1), ImVec2(1, 0)); - ImGui::End(); - } - else - { - ImGui::End(); - } - } - else - { - ImGui::GetBackgroundDrawList()->AddImage(m_sceneTexture, ImVec2(0, 0), m_sceneTextureSize, ImVec2(0, 1), ImVec2(1, 0)); - } - } + drawMenuItemCopyTexture2D(); + drawMenuItemStorePng(); + drawMenuItemExportShaderSources(); } void SceneViewerGui::drawInspectionWindow() { - if (m_settings.showWindow) + if (m_settings.showSceneViewerWindow) { - const std::string windowTitle = fmt::format("[Scene] id:{} name:{}", m_scene.getSceneId().getValue(), m_scene.getName()); - if (!ImGui::Begin(windowTitle.c_str(), &m_settings.showWindow, ImGuiWindowFlags_MenuBar)) + const auto featureLevel = m_scene.getRamsesClient().getRamsesFramework().getFeatureLevel(); + const std::string windowTitle = + m_scene.getName().empty() + ? fmt::format("Scene[{}] (FeatureLevel 0{})", m_scene.getSceneId().getValue(), featureLevel) + : fmt::format("Scene[{}]: {} (FeatureLevel 0{})", m_scene.getSceneId().getValue(), m_scene.getName(), featureLevel); + + if (!ImGui::Begin(windowTitle.c_str(), &m_settings.showSceneViewerWindow, ImGuiWindowFlags_MenuBar)) { ImGui::End(); return; @@ -2247,30 +2237,10 @@ namespace ramses::internal drawMenuItemExportShaderSources(); ImGui::EndMenu(); } - - if (ImGui::BeginMenu("Settings")) - { - drawMenuItemShowWindow(); - drawMenuItemShowPreview(); - ImGui::EndMenu(); - } ImGui::EndMenuBar(); } } - void SceneViewerGui::drawMenuItemShowWindow() - { - ImGui::MenuItem("Show Inspection Window", "F11", &m_settings.showWindow); - } - - void SceneViewerGui::drawMenuItemShowPreview() - { - if (m_sceneTexture) - { - ImGui::MenuItem("Show Preview Window", "F10", &m_settings.showPreview); - } - } - void SceneViewerGui::drawMenuItemCopyTexture2D() { if (ImGui::MenuItem("Copy Texture2D list (CSV)")) @@ -2291,7 +2261,7 @@ namespace ramses::internal { SceneObjectVector objects; m_scene.impl().getObjectRegistry().getObjectsOfType(objects, objType); - m_progress.stop(); + m_progressMonitor.stop(); ProgressMonitor::FutureList futures; const size_t tasks = objects.size() > 16u ? 4u : 1u; const auto chunkSize = static_cast(objects.size() / tasks); @@ -2300,26 +2270,26 @@ namespace ramses::internal const auto begin = objects.begin() + static_cast(i) * chunkSize; if (i + 1 == tasks) { - futures.push_back(std::async(std::launch::async, func, SceneObjectVector(begin, objects.end()))); + futures.push_back(std::async(std::launch::async, func, std::ref(m_progressMonitor), SceneObjectVector(begin, objects.end()))); } else { - futures.push_back(std::async(std::launch::async, func, SceneObjectVector(begin, begin + chunkSize))); + futures.push_back(std::async(std::launch::async, func, std::ref(m_progressMonitor), SceneObjectVector(begin, begin + chunkSize))); } } - m_progress.start(std::move(futures), static_cast(objects.size()), message); + m_progressMonitor.start(std::move(futures), static_cast(objects.size()), message); } void SceneViewerGui::drawMenuItemStorePng() { if (ImGui::MenuItem("Export all 2D textures to png")) { - auto storeAllTextures = [&](SceneObjectVector objects) { + auto storeAllTextures = [&](ProgressMonitor& progress, SceneObjectVector objects) { std::vector errorList; - for (auto it = objects.begin(); it != objects.end() && !m_progress.canceled; ++it) + for (auto it = objects.begin(); it != objects.end() && !progress.canceled; ++it) { const ramses::Texture2D* obj = static_cast(*it); - ++m_progress.current; + ++progress.current; const auto error = saveTexture2D(obj->impl()); if (!error.empty()) { @@ -2337,12 +2307,12 @@ namespace ramses::internal { if (ImGui::MenuItem("Export all shader sources")) { - auto exportShaders = [&](SceneObjectVector objects) { + auto exportShaders = [&](ProgressMonitor& progress, SceneObjectVector objects) { std::vector errorList; - for (auto it = objects.begin(); it != objects.end() && !m_progress.canceled; ++it) + for (auto it = objects.begin(); it != objects.end() && !progress.canceled; ++it) { const ramses::Effect* obj = static_cast(*it); - ++m_progress.current; + ++progress.current; const auto error = saveShaderSources(obj->impl()); if (!error.empty()) { @@ -2360,7 +2330,6 @@ namespace ramses::internal { SaveFileConfig config; config.setCompressionEnabled(m_compressFile); - config.setValidationEnabled(false); if (!m_scene.saveToFile(m_filename.c_str(), config)) { m_lastErrorMessage = m_scene.getRamsesClient().getRamsesFramework().getLastError().value_or(Issue{}).message; @@ -2374,7 +2343,7 @@ namespace ramses::internal if (resource) { const auto* textureResource = resource->convertTo(); - const auto filename = fmt::format("{:04}_{}.png", obj.getObjectRegistryHandle().asMemoryHandle(), obj.getName()); + const auto filename = fmt::format("{:04}_{}.png", obj.getSceneObjectId(), obj.getName()); errorMsg = imgui::SaveTextureToPng(textureResource, filename); } return errorMsg; diff --git a/tools/ramses-scene-viewer/src/SceneViewerGui.h b/tools/ramses-viewer/SceneViewerGui.h similarity index 88% rename from tools/ramses-scene-viewer/src/SceneViewerGui.h rename to tools/ramses-viewer/SceneViewerGui.h index e7e180392..76cc65b93 100644 --- a/tools/ramses-scene-viewer/src/SceneViewerGui.h +++ b/tools/ramses-viewer/SceneViewerGui.h @@ -8,6 +8,7 @@ #pragma once +#include "ValidationCache.h" #include "ImguiClientHelper.h" #include "ImguiImageCache.h" #include "internal/SceneGraph/SceneAPI/Handles.h" @@ -18,7 +19,6 @@ #include "ResourceList.h" #include #include -#include namespace ramses { @@ -40,17 +40,23 @@ namespace ramses::internal class SceneReferenceImpl; class AnimationSystemImpl; class BlitPassImpl; + class LogicEngineImpl; + class LogicObjectImpl; class TextureResource; struct DataSlot; struct MipMap; + class ViewerGuiApp; + struct ViewerSettings; + class SceneViewerGui { public: - SceneViewerGui(ramses::Scene& scene, const std::string& filename, ImguiClientHelper& imguiHelper, const ramses::ValidationReport& report); + SceneViewerGui(ViewerGuiApp& app, ramses::Scene& scene, std::string& errorMessage, ProgressMonitor& progressMonitor); void draw(); - void setSceneTexture(ramses::TextureSampler* sampler, uint32_t width, uint32_t height); + + void drawGlobalContextMenuItems(); private: [[nodiscard]] const ramses::RenderBuffer* findRenderBuffer(ramses::internal::RenderBufferHandle handle) const; @@ -65,14 +71,8 @@ namespace ramses::internal [[nodiscard]] const ramses::internal::DataSlot* findDataSlot(ramses::internal::TextureSamplerHandle handle) const; [[nodiscard]] const ramses::internal::DataSlot* findDataSlot(ramses::internal::ResourceContentHash hash) const; - void zoomIn(); - void zoomOut(); - void drawInspectionWindow(); - void drawSceneTexture(); void drawMenuBar(); - void drawMenuItemShowWindow(); - void drawMenuItemShowPreview(); void drawMenuItemCopyTexture2D(); void drawMenuItemStorePng(); void drawMenuItemExportShaderSources(); @@ -87,6 +87,8 @@ namespace ramses::internal void drawRefs(const char* headline, const SceneObjectImpl& target, Filter f); void draw(SceneObjectImpl& obj); + void drawLogicEngine(LogicEngineImpl& obj); + void drawLogicObject(LogicObjectImpl& obj); void drawNode(NodeImpl& obj); void drawPickableObject(PickableObjectImpl& obj); void drawNodeChildrenParent(NodeImpl& obj); @@ -124,7 +126,7 @@ namespace ramses::internal [[nodiscard]] bool passFilter(const SceneObjectImpl& obj) const; bool drawRamsesObject(SceneObjectImpl& obj); - static void DrawIssues(const SceneObjectImpl& obj, const ramses::ValidationReport& report); + static void DrawIssues(const SceneObjectImpl& obj, const ValidationCache& report); template bool drawRamsesObject(SceneObjectImpl& obj, const C& drawTreeNode); @@ -161,11 +163,11 @@ namespace ramses::internal ImGuiTextFilter m_filter; NodeFilter m_nodeFilter; ramses::Scene& m_scene; - const ramses::ValidationReport& m_validationReport; + ValidationCache m_validationCache; SceneDumper::RamsesObjectImplSet m_usedObjects; const std::string m_loadedSceneFile; std::string m_filename; - std::string m_lastErrorMessage; + std::string& m_lastErrorMessage; SceneObjects m_sceneObjects; std::unique_ptr m_resourceInfo; RenderInfo m_renderInfo; @@ -198,18 +200,7 @@ namespace ramses::internal std::unordered_map m_refs; - struct Settings - { - bool showWindow = true; - bool showPreview = false; - const std::array zoomLevels = {(1.f / 4.f), (1.f / 3.f), (1.f / 2.f), (2.f / 3.f), (3.f / 4.f), 1.f}; - int zoomIx = 4; - }; - Settings m_settings; - - ProgressMonitor m_progress; - - ramses::TextureSampler* m_sceneTexture = nullptr; - ImVec2 m_sceneTextureSize; + ViewerSettings& m_settings; + ProgressMonitor& m_progressMonitor; }; } diff --git a/tools/ramses-logic-viewer/UpdateReportSummary.h b/tools/ramses-viewer/UpdateReportSummary.h similarity index 99% rename from tools/ramses-logic-viewer/UpdateReportSummary.h rename to tools/ramses-viewer/UpdateReportSummary.h index 550ac9a4a..e8db53f1f 100644 --- a/tools/ramses-logic-viewer/UpdateReportSummary.h +++ b/tools/ramses-viewer/UpdateReportSummary.h @@ -13,7 +13,7 @@ #include #include -namespace ramses +namespace ramses::internal { class UpdateReportSummary { diff --git a/tools/ramses-viewer/ValidationCache.h b/tools/ramses-viewer/ValidationCache.h new file mode 100644 index 000000000..7332f5811 --- /dev/null +++ b/tools/ramses-viewer/ValidationCache.h @@ -0,0 +1,95 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#pragma once + +#include +#include "ramses/framework/ValidationReport.h" +#include "ramses/client/SceneObject.h" +#include "impl/SceneObjectImpl.h" +#include + +namespace ramses::internal +{ + class ValidationCache + { + public: + explicit ValidationCache(const ramses::ValidationReport& sceneReport) + : m_allIssues(sceneReport.getIssues()) + { + // Sort the issues by owning object (required for getIssues()) + // (ramses-logic validation does not guarantee sorting) + std::sort(m_allIssues.begin(), m_allIssues.end(), [](const Issue& a, const Issue& b) { + const auto* objA = object_cast(a.object); + const auto* objB = object_cast(b.object); + const auto idA = objA ? objA->getSceneObjectId().getValue() : 0; + const auto idB = objB ? objB->getSceneObjectId().getValue() : 0; + return idA < idB; + }); + } + + using iterator = std::vector::const_iterator; + + /** + * Gets the most severe issue type for this object or dependent objects + */ + std::optional getIssueType(const SceneObjectImpl& obj) + { + const auto found = m_cache.find(obj.getSceneObjectId()); + if (found != m_cache.end()) + return found->second; + auto insert = m_cache.insert(found, {obj.getSceneObjectId(), calculateIssueType(obj)}); + assert(insert != m_cache.end()); + return insert->second; + } + + /** + * Gets all issues that are directly related to the given object + */ + std::pair getIssues(const SceneObjectImpl& obj) const + { + const auto& issues = m_allIssues; + auto begin = std::find_if(issues.begin(), issues.end(), [&](const Issue& issue) { return issue.object == &obj.getRamsesObject(); }); + auto it = begin; + for (; it != issues.end(); ++it) + { + if (it->object != &obj.getRamsesObject()) + break; + } + return {begin, it}; + } + + const std::vector& getAllIssues() const + { + return m_allIssues; + } + + private: + std::optional calculateIssueType(const SceneObjectImpl& obj) + { + ramses::ValidationReport report; + obj.validate(report.impl()); + if (report.hasError()) + return EIssueType::Error; + if (report.hasIssue()) + return EIssueType::Warning; + auto range = getIssues(obj); + for (auto it = range.first; it != range.second; ++it) + { + if (it->type == EIssueType::Error) + return EIssueType::Error; + } + if (range.first != range.second) + return EIssueType::Warning; + return std::nullopt; + } + + std::vector m_allIssues; + std::unordered_map> m_cache; + }; +} diff --git a/tools/ramses-viewer/ViewerApp.cpp b/tools/ramses-viewer/ViewerApp.cpp new file mode 100644 index 000000000..46d3c7d04 --- /dev/null +++ b/tools/ramses-viewer/ViewerApp.cpp @@ -0,0 +1,202 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2017 BMW Car IT GmbH +// Copyright (C) 2019 Daniel Werner Lima Souza de Almeida (dwlsalmeida@gmail.com) +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#include "ViewerApp.h" + +#include "ramses-cli.h" +#include "ramses/client/ramses-client.h" +#include "ramses/client/ramses-utils.h" + +#include "impl/ValidationReportImpl.h" + +#include "internal/logic/StdFilesystemWrapper.h" +#include "internal/Core/Utils/File.h" +#include "internal/Core/Utils/LogMacros.h" +#include "ramses-sdk-build-config.h" +#include "ImguiWrapper.h" + +#include + + +namespace ramses::internal +{ + ViewerApp::ViewerApp() + { + m_imguiContext = ImGui::CreateContext(); + m_settings = std::make_unique(); + // set default configuration + m_frameworkConfig.setPeriodicLogInterval(std::chrono::seconds(0)); + m_frameworkConfig.setRequestedRamsesShellType(ramses::ERamsesShellType::Console); + m_frameworkConfig.setLogLevelConsole(ELogLevel::Error); + } + + ViewerApp::~ViewerApp() + { + ImGui::DestroyContext(m_imguiContext); + } + + void ViewerApp::registerOptions(CLI::App& cli) + { + cli.description(R"( +Loads and shows a ramses scene from the . + is auto-resolved if matching file with *.lua extension is found in the same path as . (Explicit argument overrides autodetection.) +)"); + cli.set_version_flag("--version", ramses_sdk::RAMSES_SDK_RAMSES_VERSION); + cli.add_option("-s,--scene,scene", m_sceneFile, "Scene file to load")->check(CLI::ExistingFile)->required(); + cli.add_option("luafile,--lua", m_luaFile, "Lua configuration file")->check(CLI::ExistingFile); + auto exec = cli.add_option("--exec", m_luaFunction, "Calls the given lua function and exits."); + cli.add_option("--exec-lua", m_luaExec, "Calls the given lua code and exits.")->excludes(exec); + auto setWriteConfig = [&](const std::string& filename) { + m_luaFile = filename; + m_writeConfig = true; + }; + cli.add_option_function("--write-config", setWriteConfig, "Writes the default lua configuration file and exits") + ->expected(0, 1) + ->type_name("[FILE]") + ->excludes(exec); + auto nv = cli.add_flag("--no-validation", m_noValidation, "Disable scene validation (faster startup for complex scenes)"); + m_report = cli.add_option("--report", m_validationReportFile, "Prints the validation report to the given file (or stdout if no filename is given)")->expected(0, 1)->excludes(nv); + + ramses::registerOptions(cli, m_frameworkConfig); + } + + ViewerApp::ExitCode ViewerApp::loadScene() + { + ramses::EFeatureLevel featureLevel = ramses::EFeatureLevel_01; + if (!ramses::RamsesClient::GetFeatureLevelFromFile(m_sceneFile, featureLevel)) + return ExitCode::ErrorUsage; + + m_frameworkConfig.setFeatureLevel(featureLevel); + m_framework = std::make_unique(m_frameworkConfig); + + m_client = m_framework->createClient("ramses-viewer"); + if (!m_client) + { + LOG_ERROR(CONTEXT_CLIENT, "Creation of client failed"); + return ExitCode::ErrorClient; + } + + // scene viewer relies on resources being kept in memory (e.g. to query size), + // load scene as 'remote' which uses a shadowcopy scene and guarantees to keep resources in memory + m_scene = m_client->loadSceneFromFile(m_sceneFile, SceneConfig({}, EScenePublicationMode::LocalAndRemote)); + if (!m_scene) + { + LOG_ERROR(CONTEXT_CLIENT, "Loading scene failed! ({})", m_sceneFile); + return ExitCode::ErrorScene; + } + m_scene->publish(); + m_scene->flush(); + + if (!m_noValidation) + { + m_scene->validate(m_validationReport); + if (m_report->count() > 0) + { + printValidationReport(); + } + } + + return ExitCode::Ok; + } + + ViewerApp::ExitCode ViewerApp::createLogicViewer(LogicViewer::ScreenshotFunc&& fScreenshot) + { + // find first logic engine + // TODO: LogicViewer should handle all LogicEngine instances + SceneObjectIterator iter{*m_scene, ERamsesObjectType::LogicEngine}; + auto logic = object_cast(iter.getNext()); + if (logic) + { + m_logicViewer = std::make_unique(*logic, fScreenshot); + return runLogicCliCommands(); + } + + return ExitCode::Ok; + } + + ViewerApp::ExitCode ViewerApp::runLogicCliCommands() + { + m_interactive = false; + assert(m_logicViewer); + if (m_luaFile.empty()) + { + m_luaFile = fs::path(m_sceneFile).replace_extension("lua").string(); + } + + if (m_writeConfig) + { + ImGui::NewFrame(); + const auto status = m_logicViewer->saveDefaultLuaFile(m_luaFile, *m_settings); + ImGui::EndFrame(); + if (!status.ok()) + { + std::cerr << status.getMessage() << std::endl; + return ExitCode::ErrorUnknown; + } + } + else if (!m_luaFunction.empty()) + { + auto loadLuaStatus = m_logicViewer->loadLuaFile(m_luaFile); + + if (loadLuaStatus.ok()) + { + loadLuaStatus = m_logicViewer->call(m_luaFunction); + } + if (!loadLuaStatus.ok()) + { + std::cerr << loadLuaStatus.getMessage() << std::endl; + return ExitCode::ErrorLoadLua; + } + } + else if (!m_luaExec.empty()) + { + // default lua file may be missing (explicit lua file is checked by CLI11 before) + auto loadLuaStatus = m_logicViewer->loadLuaFile(fs::exists(m_luaFile) ? m_luaFile : ""); + if (loadLuaStatus.ok()) + { + loadLuaStatus = m_logicViewer->exec(m_luaExec); + } + if (!loadLuaStatus.ok()) + { + std::cerr << loadLuaStatus.getMessage() << std::endl; + return ExitCode::ErrorLoadLua; + } + } + else + { + // interactive mode + m_interactive = true; + // default lua file may be missing (explicit lua file is checked by CLI11 before) + if (fs::exists(m_luaFile)) + { + m_loadLuaStatus = m_logicViewer->loadLuaFile(m_luaFile); + } + } + return ExitCode::Ok; + } + + void ViewerApp::printValidationReport() const + { + if (m_validationReportFile.empty()) + { + printValidationReport(std::cout); + } + else + { + std::ofstream os(m_validationReportFile); + printValidationReport(os); + } + } + + void ViewerApp::printValidationReport(std::ostream& os) const + { + os << m_validationReport.impl().toString() << std::endl; + ramses::RamsesUtils::DumpUnrequiredSceneObjectsToFile(*m_scene, os); + } +} diff --git a/tools/ramses-viewer/ViewerApp.h b/tools/ramses-viewer/ViewerApp.h new file mode 100644 index 000000000..6fdba0ae9 --- /dev/null +++ b/tools/ramses-viewer/ViewerApp.h @@ -0,0 +1,177 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2017 BMW Car IT GmbH +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#pragma once + +#include "ramses/framework/RamsesFrameworkConfig.h" +#include "ramses/framework/RamsesFramework.h" +#include "ramses/framework/ValidationReport.h" + +#include "LogicViewer.h" +#include "ViewerSettings.h" + +#include +#include +#include + +struct ImGuiContext; + +namespace ramses +{ + class RamsesClient; + class Scene; +} + +namespace CLI +{ + class App; + class Option; +} + +namespace ramses::internal +{ + class ViewerApp + { + public: + enum class ExitCode + { + Ok, + ErrorUsage = 1, + ErrorClient = 2, + ErrorRenderer = 3, + ErrorScene = 4, + ErrorScreenshot = 5, + ErrorDisplay = 6, + ErrorLoadLua = 7, + ErrorUnknown = -1, + }; + + ViewerApp(); + ~ViewerApp(); + + [[nodiscard]] LogicViewer* getLogicViewer(); + + [[nodiscard]] const ViewerSettings* getSettings() const; + + [[nodiscard]] ViewerSettings* getSettings(); + + [[nodiscard]] const ramses::ValidationReport& getValidationReport() const; + + [[nodiscard]] const std::string& getSceneFile() const; + + [[nodiscard]] const std::string& getLuaFile() const; + + [[nodiscard]] ramses::Scene* getScene(); + + protected: + void registerOptions(CLI::App& cli); + + [[nodiscard]] ExitCode loadScene(); + [[nodiscard]] ExitCode createLogicViewer(LogicViewer::ScreenshotFunc&& fScreenshot); + + [[nodiscard]] ramses::RamsesFramework* getFramework(); + [[nodiscard]] ramses::RamsesClient* getClient(); + + void setInteractive(bool interactive); + [[nodiscard]] bool isInteractive() const; + + [[nodiscard]] Result popLoadLuaStatus(); + + private: + [[nodiscard]] ExitCode runLogicCliCommands(); + + void printValidationReport() const; + void printValidationReport(std::ostream& os) const; + + std::string m_sceneFile; + std::string m_validationReportFile; + std::string m_luaFile; + std::string m_luaFunction; + std::string m_luaExec; + bool m_noValidation = false; + bool m_writeConfig = false; + + bool m_interactive = true; + + ImGuiContext* m_imguiContext = nullptr; + + ramses::RamsesFrameworkConfig m_frameworkConfig{ramses::EFeatureLevel_Latest}; + + std::unique_ptr m_framework; + std::unique_ptr m_settings; + std::unique_ptr m_logicViewer; + + ramses::RamsesClient* m_client = nullptr; + ramses::Scene* m_scene = nullptr; + ramses::ValidationReport m_validationReport; + + Result m_loadLuaStatus; + + CLI::Option* m_report = nullptr; + }; + + inline ramses::RamsesFramework* ViewerApp::getFramework() + { + return m_framework.get(); + } + + inline ramses::Scene* ViewerApp::getScene() + { + return m_scene; + } + + inline ramses::RamsesClient* ViewerApp::getClient() + { + return m_client; + } + + inline LogicViewer* ViewerApp::getLogicViewer() + { + return m_logicViewer.get(); + } + + inline const ramses::ValidationReport& ViewerApp::getValidationReport() const + { + return m_validationReport; + } + + inline const std::string& ViewerApp::getSceneFile() const + { + return m_sceneFile; + } + + inline const std::string& ViewerApp::getLuaFile() const + { + return m_luaFile; + } + + inline const ViewerSettings* ViewerApp::getSettings() const + { + return m_settings.get(); + } + + inline ViewerSettings* ViewerApp::getSettings() + { + return m_settings.get(); + } + + inline void ViewerApp::setInteractive(bool interactive) + { + m_interactive = interactive; + } + + inline bool ViewerApp::isInteractive() const + { + return m_interactive; + } + + inline Result ViewerApp::popLoadLuaStatus() + { + return std::move(m_loadLuaStatus); + } +} diff --git a/tools/ramses-viewer/ViewerGui.cpp b/tools/ramses-viewer/ViewerGui.cpp new file mode 100644 index 000000000..cc7dce426 --- /dev/null +++ b/tools/ramses-viewer/ViewerGui.cpp @@ -0,0 +1,273 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2021 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#include "ViewerGui.h" +#include "ViewerSettings.h" +#include "ViewerGuiApp.h" +#include "ImguiWrapper.h" +#include "glm/gtc/type_ptr.hpp" + +namespace ramses::internal +{ + ViewerGui::ViewerGui(ViewerGuiApp& app) + : m_app(app) + , m_settings(*app.getSettings()) + { + auto* scene = app.getScene(); + if (scene) + m_sceneGui = std::make_unique(app, *app.getScene(), m_lastErrorMessage, m_progress); + + if (app.getLogicViewer()) + m_logicGui = std::make_unique(app, m_lastErrorMessage); + } + + void ViewerGui::setRendererInfo(ramses::RamsesRenderer& renderer, ramses::displayId_t displayId, ramses::displayBufferId_t displayBufferId) + { + m_renderer = &renderer; + m_displayId = displayId; + m_displayBufferId = displayBufferId; + } + + void ViewerGui::openErrorPopup(const std::string& message) + { + // ImGui::OpenPopup("Error") does not work in all cases (The calculated ID seems to be context related) + // The popup will be opened in ViewerGui::draw() instead + m_lastErrorMessage = message; + } + + void ViewerGui::draw() + { + if (ImGui::IsKeyPressed(ramses::EKeyCode_F11)) + { + m_settings.showGui = !m_settings.showGui; + } + + if (ImGui::IsKeyPressed(ramses::EKeyCode_F10)) + { + m_settings.showSceneViewerWindow = !m_settings.showSceneViewerWindow; + } + + if (m_logicGui) + m_logicGui->handleShortcuts(); + + if (ImGui::BeginPopupContextVoid("GlobalContextMenu")) + { + drawMenuItemShowWindow(); + if (m_sceneGui) + { + ImGui::Separator(); + m_sceneGui->drawGlobalContextMenuItems(); + } + if (m_logicGui) + { + ImGui::Separator(); + m_logicGui->drawGlobalContextMenuItems(); + } + ImGui::EndPopup(); + } + + drawSceneTexture(); + drawErrorPopup(); + drawProgressPopup(); + + if (m_settings.showGui) + { + drawMenuBar(); + if (m_sceneGui) + m_sceneGui->draw(); + if (m_logicGui) + m_logicGui->draw(); + } + } + + void ViewerGui::setSceneTexture(ramses::TextureSampler* sampler, uint32_t width, uint32_t height) + { + m_sceneTexture = sampler; + m_sceneTextureSize.x = static_cast(width); + m_sceneTextureSize.y = static_cast(height); + } + + void ViewerGui::drawMenuBar() + { + if (ImGui::BeginMainMenuBar()) + { + if (ImGui::BeginMenu("Settings")) + { + drawMenuItemShowWindow(); + drawMenuItemDisplaySettings(); + ImGui::EndMenu(); + } + ImGui::EndMainMenuBar(); + } + } + + void ViewerGui::drawMenuItemShowWindow() + { + ImGui::MenuItem("Show Gui", "F11", &m_settings.showGui); + ImGui::MenuItem("Show Scene Inspection Window", "F10", &m_settings.showSceneViewerWindow, m_settings.showGui); + ImGui::MenuItem("Show Logic Window", nullptr, &m_settings.showLogicWindow, m_settings.showGui); + if (m_app.getGuiMode() == ViewerGuiApp::GuiMode::On) + { + ImGui::MenuItem("Show Scene in Window", nullptr, &m_settings.showSceneInWindow, m_settings.showGui); + } + } + + void ViewerGui::drawMenuItemDisplaySettings() + { + if (m_renderer) + { + ImGui::Separator(); + if (DrawColorSetting("Clear color", m_settings.clearColor)) + { + m_renderer->setDisplayBufferClearColor(m_displayId, m_displayBufferId, m_settings.clearColor); + m_renderer->flush(); + } + + if (ImGui::MenuItem("Skip rendering of unmodified buffers", nullptr, &m_skipUnmodifiedBuffers)) + { + m_renderer->setSkippingOfUnmodifiedBuffers(m_skipUnmodifiedBuffers); + m_renderer->flush(); + } + + float fps = m_renderer->getFramerateLimit(m_displayId); + if (ImGui::DragFloat("Maximum FPS", &fps, 1.f, 1.f, 1000.f)) + { + m_renderer->setFramerateLimit(m_displayId, fps); + m_renderer->flush(); + } + } + } + + bool ViewerGui::DrawColorSetting(const char* name, glm::vec4& color) + { + bool modified = false; + const auto flags = ImGuiColorEditFlags_NoInputs | ImGuiColorEditFlags_NoLabel; + if (ImGui::ColorEdit4(name, glm::value_ptr(color), flags)) + { + modified = true; + } + ImGui::SameLine(); + ImGui::TextUnformatted(name); + return modified; + } + + void ViewerGui::drawErrorPopup() + { + if (!m_lastErrorMessage.empty()) + ImGui::OpenPopup("Error"); + + if (ImGui::BeginPopupModal("Error", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) + { + ImGui::TextUnformatted(m_lastErrorMessage.c_str()); + ImGui::Separator(); + + if (ImGui::Button("OK", ImVec2(120, 0))) + { + m_lastErrorMessage.clear(); + ImGui::CloseCurrentPopup(); + } + ImGui::SameLine(); + if (ImGui::Button("Copy Message", ImVec2(120, 0))) + { + ImGui::SetClipboardText(m_lastErrorMessage.c_str()); + } + ImGui::EndPopup(); + } + } + + void ViewerGui::drawProgressPopup() + { + if (m_progress.isRunning() && !m_progress.canceled) + { + ImGui::OpenPopup("Progress"); + } + + if (ImGui::BeginPopupModal("Progress", nullptr, ImGuiWindowFlags_AlwaysAutoResize)) + { + const uint32_t current = m_progress.current; + ImGui::TextUnformatted(m_progress.getDescription().c_str()); + ImGui::TextUnformatted(fmt::format("{} of {}", current, m_progress.getTotal()).c_str()); + ImGui::Separator(); + if (ImGui::Button("Cancel", ImVec2(120,0))) + { + m_progress.canceled = true; + ImGui::CloseCurrentPopup(); + } + if (!m_progress.isRunning()) + { + ImGui::CloseCurrentPopup(); + auto result = m_progress.getResult(); + if (!result.empty()) + { + m_lastErrorMessage = fmt::format("{}", fmt::join(result, "\n")); + } + } + ImGui::EndPopup(); + } + } + + void ViewerGui::zoomIn() + { + if (m_settings.zoomIx < (static_cast(m_settings.zoomLevels.size()) - 1)) + { + ++m_settings.zoomIx; + } + } + + void ViewerGui::zoomOut() + { + if (m_settings.zoomIx > 0) + { + --m_settings.zoomIx; + } + } + + void ViewerGui::drawSceneTexture() + { + if (m_sceneTexture) + { + if (m_settings.showSceneInWindow) + { + if (ImGui::Begin("Preview", &m_settings.showSceneInWindow, ImGuiWindowFlags_AlwaysAutoResize)) + { + if (ImGui::GetIO().KeyCtrl) + { + if (ImGui::GetIO().MouseWheel >= 1.f) + { + zoomIn(); + } + if (ImGui::GetIO().MouseWheel <= -1.f) + { + zoomOut(); + } + } + const auto f = m_settings.zoomLevels[m_settings.zoomIx]; + if (ImGui::SmallButton("-")) + zoomOut(); + ImGui::SameLine(); + if (ImGui::SmallButton("+")) + zoomIn(); + ImGui::SameLine(); + ImGui::TextUnformatted(fmt::format("Zoom {}%", static_cast(f * 100)).c_str()); + ImVec2 size(m_sceneTextureSize.x * f, m_sceneTextureSize.y * f); + ImGui::Image(m_sceneTexture, size, ImVec2(0, 1), ImVec2(1, 0)); + ImGui::End(); + } + else + { + ImGui::End(); + } + } + else + { + ImGui::GetBackgroundDrawList()->AddImage(m_sceneTexture, ImVec2(0, 0), m_sceneTextureSize, ImVec2(0, 1), ImVec2(1, 0)); + } + } + } + +} diff --git a/tools/ramses-viewer/ViewerGui.h b/tools/ramses-viewer/ViewerGui.h new file mode 100644 index 000000000..eeb4db8c2 --- /dev/null +++ b/tools/ramses-viewer/ViewerGui.h @@ -0,0 +1,71 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#pragma once + +#include "SceneViewerGui.h" +#include "LogicViewerGui.h" +#include + +namespace ramses +{ + class TextureSampler; +} + +namespace ramses::internal +{ + class ViewerGuiApp; + struct ViewerSettings; + + class ViewerGui + { + public: + explicit ViewerGui(ViewerGuiApp& app); + void draw(); + + void setSceneTexture(ramses::TextureSampler* sampler, uint32_t width, uint32_t height); + + void setRendererInfo(ramses::RamsesRenderer& renderer, ramses::displayId_t displayId, ramses::displayBufferId_t displayBufferId); + + void openErrorPopup(const std::string& message); + + private: + void drawMenuBar(); + void drawMenuItemShowWindow(); + void drawMenuItemDisplaySettings(); + + static bool DrawColorSetting(const char* name, glm::vec4& color); + + void drawErrorPopup(); + void drawProgressPopup(); + + void zoomIn(); + void zoomOut(); + + void drawSceneTexture(); + + ViewerGuiApp& m_app; + ViewerSettings& m_settings; + + std::unique_ptr m_sceneGui; + std::unique_ptr m_logicGui; + + ramses::TextureSampler* m_sceneTexture = nullptr; + ImVec2 m_sceneTextureSize; + + std::string m_lastErrorMessage; + + ramses::RamsesRenderer* m_renderer = nullptr; + ramses::displayId_t m_displayId; + ramses::displayBufferId_t m_displayBufferId; + bool m_skipUnmodifiedBuffers = true; + + ProgressMonitor m_progress; + }; +} + diff --git a/tools/ramses-viewer/ViewerGuiApp.cpp b/tools/ramses-viewer/ViewerGuiApp.cpp new file mode 100644 index 000000000..d58f7ce8c --- /dev/null +++ b/tools/ramses-viewer/ViewerGuiApp.cpp @@ -0,0 +1,212 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#include "ViewerGuiApp.h" +#include "ramses-cli.h" +#include "ramses/client/ramses-client.h" +#include "ramses/client/ramses-utils.h" +#include "ramses/renderer/RamsesRenderer.h" +#include "ramses/renderer/IRendererSceneControlEventHandler.h" +#include "impl/DisplayConfigImpl.h" +#include "internal/PlatformAbstraction/PlatformThread.h" +#include "internal/Core/Utils/LogMacros.h" +#include + +namespace ramses::internal +{ + namespace + { + void SetPreferredSize(ramses::DisplayConfig& cfg, const ramses::Scene& scene) + { + ramses::SceneObjectIterator it(scene, ramses::ERamsesObjectType::RenderPass); + ramses::RamsesObject* obj = nullptr; + while (nullptr != (obj = it.getNext())) + { + auto* rp = static_cast(obj); + if (!rp->getRenderTarget()) + { + auto* camera = rp->getCamera(); + if (camera) + { + const auto width = camera->getViewportWidth(); + const auto height = camera->getViewportHeight(); + cfg.setWindowRectangle(0, 0, width, height); + } + } + } + } + } + + ViewerGuiApp::ViewerGuiApp() + { + m_displayConfig.setResizable(true); + } + + void ViewerGuiApp::registerOptions(CLI::App& cli) + { + ViewerApp::registerOptions(cli); + + const std::map modes{{"on", GuiMode::On}, {"overlay", GuiMode::Overlay}, {"off", GuiMode::Off}, {"only", GuiMode::Only}}; + auto gui = cli.add_option("--gui", m_guiMode, "Inspection Gui display mode")->transform(CLI::CheckedTransformer(modes)); + cli.add_flag("--no-skub", m_noSkub, "Disable skub (skip unmodified buffers). Render unchanged frames."); + cli.add_flag("--headless", m_headless, "Runs without user interface and renderer. Disables screenshots."); + auto screenshot = cli.add_option("-x,--screenshot", m_screenshotFile, "Stores a screenshot of the scene to the given filename and exits"); + ramses::registerOptions(cli, m_rendererConfig); + ramses::registerOptions(cli, m_displayConfig); + m_width = cli.get_option("--width"); + m_height = cli.get_option("--height"); + screenshot->excludes(gui); + } + + ViewerGuiApp::ExitCode ViewerGuiApp::setup() + { + if (m_imguiHelper) + return ExitCode::ErrorUsage; // double setup is not allowed + + auto exitCode = ViewerApp::loadScene(); + if (exitCode != ExitCode::Ok) + return exitCode; + + const bool customWidth = m_width ? (m_width->count() > 0) : false; + const bool customHeight = m_height ? (m_height->count() > 0) : false; + if (!customHeight && !customWidth) + SetPreferredSize(m_displayConfig, *getScene()); + int32_t winX = 0; + int32_t winY = 0; + uint32_t winWidth = 0u; + uint32_t winHeight = 0u; + m_displayConfig.getWindowRectangle(winX, winY, winWidth, winHeight); + + // avoid sceneId collision + const auto imguiSceneId = ramses::sceneId_t(getScene()->getSceneId().getValue() + 1); + m_imguiHelper = std::make_unique(*getClient(), winWidth, winHeight, imguiSceneId); + + if (m_headless) + return createLogicViewer(LogicViewer::ScreenshotFunc()); + + auto renderer = getFramework()->createRenderer(m_rendererConfig); + if (!renderer) + { + LOG_ERROR(CONTEXT_CLIENT, "Creation of renderer failed"); + return ExitCode::ErrorRenderer; + } + renderer->setSkippingOfUnmodifiedBuffers(!m_noSkub); + renderer->startThread(); + + getFramework()->connect(); + + const ramses::displayId_t displayId = renderer->createDisplay(m_displayConfig); + renderer->flush(); + + m_imguiHelper->setDisplayId(displayId); + m_imguiHelper->setRenderer(renderer); + + if (!m_imguiHelper->waitForDisplay(displayId)) + { + return ExitCode::ErrorDisplay; + } + + switch (m_guiMode) + { + case GuiMode::On: + m_sceneSetup = std::make_unique(*m_imguiHelper, renderer, getScene(), displayId, winWidth, winHeight); + break; + case GuiMode::Only: + m_sceneSetup = std::make_unique(*m_imguiHelper, renderer, nullptr, displayId); + break; + case GuiMode::Overlay: + case GuiMode::Off: + m_sceneSetup = std::make_unique(*m_imguiHelper, renderer, getScene(), displayId); + break; + } + getScene()->flush(); + getSettings()->clearColor = m_displayConfig.impl().getInternalDisplayConfig().getClearColor(); + renderer->setDisplayBufferClearColor(displayId, m_sceneSetup->getOffscreenBuffer(), getSettings()->clearColor); + m_sceneSetup->apply(); + + auto takeScreenshot = [&](const std::string& filename) { + static ramses::sceneVersionTag_t ver = 42; + ++ver; + getScene()->flush(ver); + if (m_imguiHelper->waitForSceneVersion(getScene()->getSceneId(), ver)) + { + if (m_imguiHelper->saveScreenshot(filename, m_sceneSetup->getOffscreenBuffer(), 0, 0, m_sceneSetup->getWidth(), m_sceneSetup->getHeight())) + { + if (m_imguiHelper->waitForScreenshot()) + { + return true; + } + } + } + return false; + }; + exitCode = createLogicViewer(takeScreenshot); + if (exitCode != ExitCode::Ok) + return exitCode; + + m_gui = std::make_unique(*this); + m_gui->setSceneTexture(m_sceneSetup->getTextureSampler(), winWidth, winHeight); + m_gui->setRendererInfo(*renderer, displayId, m_sceneSetup->getOffscreenBuffer()); + + if (!m_screenshotFile.empty()) + { + if (!m_imguiHelper->saveScreenshot(m_screenshotFile, m_sceneSetup->getOffscreenBuffer(), 0, 0, winWidth, winHeight)) + { + LOG_ERROR(CONTEXT_CLIENT, "Failure when saving screenshot"); + return ExitCode::ErrorScreenshot; + } + if (!m_imguiHelper->waitForScreenshot()) + { + LOG_ERROR(CONTEXT_CLIENT, "Screenshot not saved"); + return ExitCode::ErrorScreenshot; + } + setInteractive(false); + } + + return ExitCode::Ok; + } + + ViewerGuiApp::ExitCode ViewerGuiApp::run() + { + const auto exitCode = setup(); + if (exitCode != ExitCode::Ok) + return exitCode; + + while (doOneLoop()) + { + ramses::internal::PlatformThread::Sleep(40u); + } + return ExitCode::Ok; + } + + bool ViewerGuiApp::doOneLoop() + { + const bool isRunning = isInteractive() && m_imguiHelper->isRunning(); + if (!isRunning) + return false; + + Result updateStatus; + if (getLogicViewer()) + updateStatus = getLogicViewer()->update(); + getScene()->flush(); + m_imguiHelper->dispatchEvents(); + if (m_guiMode != GuiMode::Off) + { + ImGui::NewFrame(); + m_gui->draw(); + auto loadLuaStatus = popLoadLuaStatus(); + if (!loadLuaStatus.ok()) + m_gui->openErrorPopup(loadLuaStatus.getMessage()); + if (!updateStatus.ok()) + m_gui->openErrorPopup(updateStatus.getMessage()); + ImGui::EndFrame(); + m_imguiHelper->draw(); + } + return true; + } +} diff --git a/tools/ramses-viewer/ViewerGuiApp.h b/tools/ramses-viewer/ViewerGuiApp.h new file mode 100644 index 000000000..2b6d5488b --- /dev/null +++ b/tools/ramses-viewer/ViewerGuiApp.h @@ -0,0 +1,73 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#pragma once + +#include "ViewerApp.h" +#include "ramses/renderer/RendererConfig.h" +#include "ramses/renderer/DisplayConfig.h" +#include "ImguiClientHelper.h" +#include "SceneSetup.h" +#include "ViewerGui.h" +#include "SceneViewerGui.h" +#include "LogicViewerGui.h" + +namespace ramses::internal +{ + class ViewerGuiApp final : public ViewerApp + { + public: + ViewerGuiApp(); + + void registerOptions(CLI::App& cli); + + [[nodiscard]] ExitCode run(); + + // for integration tests + [[nodiscard]] ImguiClientHelper* getImguiClientHelper(); + [[nodiscard]] ExitCode setup(); + [[nodiscard]] bool doOneLoop(); + + enum class GuiMode + { + Off, + On, ///< Loaded scene rendered to offscreen buffer (configurable size and position) + Overlay, ///< Debugging gui overlaps the rendered scene (no offscreen buffer) + Only, ///< Only shows the gui, not the scene itself + }; + [[nodiscard]] GuiMode getGuiMode() const; + + private: + GuiMode m_guiMode = GuiMode::Overlay; + + ramses::RendererConfig m_rendererConfig; + ramses::DisplayConfig m_displayConfig; + + std::string m_screenshotFile; + + CLI::Option* m_width = nullptr; + CLI::Option* m_height = nullptr; + + bool m_noSkub = false; + bool m_headless = false; + + std::unique_ptr m_imguiHelper; + std::unique_ptr m_sceneSetup; + std::unique_ptr m_gui; + }; + + inline ImguiClientHelper* ViewerGuiApp::getImguiClientHelper() + { + return m_imguiHelper.get(); + } + + inline ViewerGuiApp::GuiMode ViewerGuiApp::getGuiMode() const + { + return m_guiMode; + } +} diff --git a/tools/ramses-viewer/ViewerHeadlessApp.cpp b/tools/ramses-viewer/ViewerHeadlessApp.cpp new file mode 100644 index 000000000..5162d80dd --- /dev/null +++ b/tools/ramses-viewer/ViewerHeadlessApp.cpp @@ -0,0 +1,42 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- +#include "ViewerHeadlessApp.h" +#include "ImguiWrapper.h" + +namespace ramses::internal +{ + ViewerHeadlessApp::ViewerHeadlessApp() + { + // context needed for saving default lua file (uses imgui logging) + ImGuiIO& io = ImGui::GetIO(); + io.DisplaySize.x = 400.f; + io.DisplaySize.y = 320.f; + int texturewidth = 0; + int textureheight = 0; + unsigned char* pixels = nullptr; + io.Fonts->GetTexDataAsRGBA32(&pixels, &texturewidth, &textureheight); + } + + void ViewerHeadlessApp::registerOptions(CLI::App& cli) + { + ViewerApp::registerOptions(cli); + } + + ViewerHeadlessApp::ExitCode ViewerHeadlessApp::run() + { + auto exitCode = loadScene(); + if (exitCode != ExitCode::Ok) + return exitCode; + + exitCode = createLogicViewer(LogicViewer::ScreenshotFunc()); + if (exitCode != ExitCode::Ok) + return exitCode; + + return ExitCode::Ok; + } +} diff --git a/tools/ramses-logic-viewer/LogicViewerHeadlessApp.h b/tools/ramses-viewer/ViewerHeadlessApp.h similarity index 56% rename from tools/ramses-logic-viewer/LogicViewerHeadlessApp.h rename to tools/ramses-viewer/ViewerHeadlessApp.h index 23cc745df..f6aa935c9 100644 --- a/tools/ramses-logic-viewer/LogicViewerHeadlessApp.h +++ b/tools/ramses-viewer/ViewerHeadlessApp.h @@ -1,5 +1,5 @@ // ------------------------------------------------------------------------- -// Copyright (C) 2022 BMW AG +// Copyright (C) 2023 BMW AG // ------------------------------------------------------------------------- // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this @@ -8,21 +8,18 @@ #pragma once -#include "LogicViewerApp.h" +#include "ViewerApp.h" -namespace ramses +namespace ramses::internal { - class LogicViewerHeadlessApp : public LogicViewerApp + + class ViewerHeadlessApp : public ViewerApp { public: - LogicViewerHeadlessApp(int argc, char const* const* argv); - - ~LogicViewerHeadlessApp() override; + ViewerHeadlessApp(); - [[nodiscard]] bool doOneLoop() override; + void registerOptions(CLI::App& cli); - private: - [[nodiscard]] int init(int argc, char const* const* argv); + [[nodiscard]] ExitCode run(); }; } - diff --git a/tools/ramses-viewer/ViewerSettings.cpp b/tools/ramses-viewer/ViewerSettings.cpp new file mode 100644 index 000000000..3e8f6eba8 --- /dev/null +++ b/tools/ramses-viewer/ViewerSettings.cpp @@ -0,0 +1,97 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2022 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#include "ViewerSettings.h" + +#include"ImguiWrapper.h" + +#ifndef _MSC_VER +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wold-style-cast" +#endif +#include "imgui_internal.h" // for ImGuiSettingsHandler +#ifndef _MSC_VER +#pragma GCC diagnostic pop +#endif + +namespace ramses::internal +{ + namespace + { + bool IniReadFlag(const char* line, const char* fmt, int* flag) + { + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg, cert-err34-c) no suitable replacement + return (sscanf(line, fmt, flag) == 1); + } + } + + ViewerSettings::ViewerSettings() + { + auto* ctx = ImGui::GetCurrentContext(); + assert(ctx != nullptr); + ImGuiSettingsHandler ini_handler; + ini_handler.TypeName = "ramses-viewer"; + ini_handler.TypeHash = ImHashStr("ramses-viewer"); + ini_handler.ReadOpenFn = IniReadOpen; + ini_handler.ReadLineFn = IniReadLine; + ini_handler.WriteAllFn = IniWriteAll; + ini_handler.UserData = this; + ctx->SettingsHandlers.push_back(ini_handler); + ImGui::LoadIniSettingsFromDisk(ImGui::GetIO().IniFilename); + } + + void* ViewerSettings::IniReadOpen(ImGuiContext* /*context*/, ImGuiSettingsHandler* handler, const char* /*name*/) + { + return handler->UserData; + } + + void ViewerSettings::IniReadLine(ImGuiContext* /*context*/, ImGuiSettingsHandler* handler, void* /*entry*/, const char* line) + { + auto* gui = static_cast(handler->UserData); + int flag = 0; + if (IniReadFlag(line, "ShowSceneViewerWindow=%d", &flag)) + { + gui->showSceneViewerWindow = (flag != 0); + } + else if (IniReadFlag(line, "ShowLogicWindow=%d", &flag)) + { + gui->showLogicWindow = (flag != 0); + } + else if (IniReadFlag(line, "ShowUpdateReport=%d", &flag)) + { + gui->showUpdateReport = (flag != 0); + } + else if (IniReadFlag(line, "LuaPreferObjectIds=%d", &flag)) + { + gui->luaPreferObjectIds = (flag != 0); + } + else if (IniReadFlag(line, "LuaPreferIdentifiers=%d", &flag)) + { + gui->luaPreferIdentifiers = (flag != 0); + } + } + + void ViewerSettings::IniWriteAll(ImGuiContext* /*context*/, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) + { + auto* gui = static_cast(handler->UserData); + buf->reserve(buf->size() + 400); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + buf->appendf("[%s][Settings]\n", handler->TypeName); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + buf->appendf("ShowSceneViewerWindow=%d\n", gui->showSceneViewerWindow ? 1 : 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + buf->appendf("ShowLogicWindow=%d\n", gui->showLogicWindow ? 1 : 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + buf->appendf("ShowUpdateReport=%d\n", gui->showUpdateReport ? 1 : 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + buf->appendf("LuaPreferObjectIds=%d\n", gui->luaPreferObjectIds ? 1 : 0); + // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg) 3rd party interface + buf->appendf("LuaPreferIdentifiers=%d\n", gui->luaPreferIdentifiers ? 1 : 0); + buf->append("\n"); + } +} diff --git a/tools/ramses-viewer/ViewerSettings.h b/tools/ramses-viewer/ViewerSettings.h new file mode 100644 index 000000000..f1705018d --- /dev/null +++ b/tools/ramses-viewer/ViewerSettings.h @@ -0,0 +1,46 @@ +// ------------------------------------------------------------------------- +// Copyright (C) 2023 BMW AG +// ------------------------------------------------------------------------- +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. +// ------------------------------------------------------------------------- + +#pragma once + +#include +#include + +struct ImGuiSettingsHandler; +struct ImGuiContext; +struct ImGuiTextBuffer; + +namespace ramses::internal +{ + struct ViewerSettings + { + // scene viewer settings + bool showGui = true; + + bool showSceneViewerWindow = true; + bool showSceneInWindow = false; + + const std::array zoomLevels = {(1.f / 4.f), (1.f / 3.f), (1.f / 2.f), (2.f / 3.f), (3.f / 4.f), 1.f}; + int zoomIx = 4; + + // Logic viewer settings + bool showLogicWindow = true; + bool showUpdateReport = true; + + bool luaPreferObjectIds = false; + bool luaPreferIdentifiers = false; + + glm::vec4 clearColor{ 0, 0, 0, 1 }; + + ViewerSettings(); + + static void* IniReadOpen(ImGuiContext* context, ImGuiSettingsHandler* handler, const char* name); + static void IniReadLine(ImGuiContext* context, ImGuiSettingsHandler* handler, void* entry, const char* line); + static void IniWriteAll(ImGuiContext* context, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf); + }; +} diff --git a/tools/ramses-scene-viewer/src/main.cpp b/tools/ramses-viewer/main.cpp similarity index 83% rename from tools/ramses-scene-viewer/src/main.cpp rename to tools/ramses-viewer/main.cpp index 0346729b7..8289cd5bd 100644 --- a/tools/ramses-scene-viewer/src/main.cpp +++ b/tools/ramses-viewer/main.cpp @@ -6,14 +6,14 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. // ------------------------------------------------------------------------- -#include "SceneViewer.h" +#include "ViewerGuiApp.h" #include "ramses-cli.h" int main(int argc, char* argv[]) { CLI::App cli; - ramses::internal::SceneViewer sceneViewer; + ramses::internal::ViewerGuiApp sceneViewer; sceneViewer.registerOptions(cli); CLI11_PARSE(cli, argc, argv); - return sceneViewer.run(); + return static_cast(sceneViewer.run()); } diff --git a/tools/ramses-logic-viewer/main_headless.cpp b/tools/ramses-viewer/main_headless.cpp similarity index 63% rename from tools/ramses-logic-viewer/main_headless.cpp rename to tools/ramses-viewer/main_headless.cpp index 781164150..8e0cfbb1d 100644 --- a/tools/ramses-logic-viewer/main_headless.cpp +++ b/tools/ramses-viewer/main_headless.cpp @@ -1,15 +1,19 @@ // ------------------------------------------------------------------------- -// Copyright (C) 2022 BMW AG +// Copyright (C) 2023 BMW AG // ------------------------------------------------------------------------- // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // ------------------------------------------------------------------------- -#include "LogicViewerHeadlessApp.h" +#include "ViewerHeadlessApp.h" +#include "ramses-cli.h" int main(int argc, char* argv[]) { - ramses::LogicViewerHeadlessApp app(argc, argv); - return app.run(); + CLI::App cli; + ramses::internal::ViewerHeadlessApp sceneViewer; + sceneViewer.registerOptions(cli); + CLI11_PARSE(cli, argc, argv); + return static_cast(sceneViewer.run()); } diff --git a/tools/test-asset-producer/CMakeLists.txt b/tools/test-asset-producer/CMakeLists.txt index 72a16fc93..a3f4501b6 100644 --- a/tools/test-asset-producer/CMakeLists.txt +++ b/tools/test-asset-producer/CMakeLists.txt @@ -11,7 +11,7 @@ createModule( TYPE BINARY ENABLE_INSTALL OFF SRC_FILES main.cpp - DEPENDENCIES ramses-shared-lib + DEPENDENCIES ramses-shared-lib-headless ) add_custom_target(RL_REGEN_TEST_ASSETS diff --git a/tools/test-asset-producer/main.cpp b/tools/test-asset-producer/main.cpp index 8d884a6cd..ed010e5c2 100644 --- a/tools/test-asset-producer/main.cpp +++ b/tools/test-asset-producer/main.cpp @@ -293,6 +293,7 @@ int main(int argc, char* argv[]) const auto meshNode = scene->createMeshNode(); renderGroup->addMeshNode(*meshNode); renderGroup->addRenderGroup(*nestedRenderGroup); + auto renderBuffer = scene->createRenderBuffer(16u, 16u, ramses::ERenderBufferFormat::RGBA8, ramses::ERenderBufferAccessMode::ReadWrite, 0u, "renderBuffer"); // create triangle that can actually be visible when rendered createTriangle(*scene); @@ -323,6 +324,7 @@ int main(int argc, char* argv[]) animConfig.setExposingOfChannelDataAsProperties(true); logicEngine.createAnimationNode(animConfig, "animNodeWithDataProperties"); logicEngine.createTimerNode("timerNode"); + logicEngine.createRenderBufferBinding(*renderBuffer, "renderBufferBinding"); logicEngine.link(*intf->getOutputs()->getChild("struct")->getChild("floatInput"), *script1->getInputs()->getChild("floatInput")); logicEngine.link(*script1->getOutputs()->getChild("floatOutput"), *script2->getInputs()->getChild("floatInput")); @@ -337,13 +339,21 @@ int main(int argc, char* argv[]) logicEngine.link(*script1->getOutputs()->getChild("boolOutput"), *nodeBinding->getInputs()->getChild("enabled")); if (!logicEngine.update()) - return 1; + return EXIT_FAILURE; - ramses::SaveFileConfig noValidationConfig; - noValidationConfig.setValidationEnabled(false); - noValidationConfig.setMetadataString("test-asset-producer"); + ramses::ValidationReport report; + scene->validate(report); + if (report.hasIssue()) + { + for (const auto& issue : report.getIssues()) + std::cout << (issue.type == ramses::EIssueType::Error ? "ERROR: " : "Warn: ") << issue.message << std::endl; + } - if (!scene->saveToFile(basePath + "/" + ramsesFilename, noValidationConfig)) + ramses::SaveFileConfig saveConfig; + saveConfig.setMetadataString("test-asset-producer"); + const auto filePath = basePath + "/" + ramsesFilename; + std::cout << "Saving to " << filePath << std::endl; + if (!scene->saveToFile(filePath, saveConfig)) return EXIT_FAILURE; return 0; From 8cf2c13f8cf06b21ea5ab614d8ab9c11c288d08d Mon Sep 17 00:00:00 2001 From: Askanaz Torosyan <46795157+nVxx@users.noreply.github.com> Date: Wed, 22 Nov 2023 08:41:37 +0100 Subject: [PATCH 2/5] Disable iOS build job. --- .github/workflows/test.yml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 0d01ee824..ca86eb303 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -26,9 +26,10 @@ jobs: type: [Debug, Release] compiler: [default] include: - - target-platform: iphoneos - os: macos-12 - type: Debug + # temporarily disable iOS build for 28 RC3 release + # - target-platform: iphoneos + # os: macos-12 + # type: Debug - target-platform: iphonesimulator os: macos-12 type: Debug From d1d8f6da91587b20f879df67304dbe3b0349de38 Mon Sep 17 00:00:00 2001 From: Askanaz Torosyan <46795157+nVxx@users.noreply.github.com> Date: Wed, 22 Nov 2023 09:26:11 +0100 Subject: [PATCH 3/5] Disable iphone simulator build. --- .github/workflows/test.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ca86eb303..9ab7afdc1 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -30,9 +30,9 @@ jobs: # - target-platform: iphoneos # os: macos-12 # type: Debug - - target-platform: iphonesimulator - os: macos-12 - type: Debug + # - target-platform: iphonesimulator + # os: macos-12 + # type: Debug # Test with Clang too - os: ubuntu-20.04 type: Debug From 0e281d733623241601b2788270ea1b47eb7d4432 Mon Sep 17 00:00:00 2001 From: Askanaz Torosyan <46795157+nVxx@users.noreply.github.com> Date: Wed, 22 Nov 2023 10:53:50 +0100 Subject: [PATCH 4/5] Disable MacOS builds. --- .github/workflows/test.yml | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 9ab7afdc1..99ff5ad89 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,11 +22,13 @@ jobs: strategy: matrix: target-platform: [host-os] - os: [ubuntu-20.04, ubuntu-22.04, windows-2022, macos-12] + # temporarily disable MacOS builds for 28 RC3 release + # os: [ubuntu-20.04, ubuntu-22.04, windows-2022, macos-12] + os: [ubuntu-20.04, ubuntu-22.04, windows-2022] type: [Debug, Release] compiler: [default] include: - # temporarily disable iOS build for 28 RC3 release + # temporarily disable iOS builds for 28 RC3 release # - target-platform: iphoneos # os: macos-12 # type: Debug From 8d1345db71753bdb0c03aecd953d6cfca9f1e56f Mon Sep 17 00:00:00 2001 From: Askanaz Torosyan <46795157+nVxx@users.noreply.github.com> Date: Wed, 22 Nov 2023 11:25:27 +0100 Subject: [PATCH 5/5] Disable tests for MacOS platform. --- .github/workflows/test.yml | 19 +++++++++---------- 1 file changed, 9 insertions(+), 10 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 99ff5ad89..325241d33 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -22,19 +22,16 @@ jobs: strategy: matrix: target-platform: [host-os] - # temporarily disable MacOS builds for 28 RC3 release - # os: [ubuntu-20.04, ubuntu-22.04, windows-2022, macos-12] - os: [ubuntu-20.04, ubuntu-22.04, windows-2022] + os: [ubuntu-20.04, ubuntu-22.04, windows-2022, macos-12] type: [Debug, Release] compiler: [default] include: - # temporarily disable iOS builds for 28 RC3 release - # - target-platform: iphoneos - # os: macos-12 - # type: Debug - # - target-platform: iphonesimulator - # os: macos-12 - # type: Debug + - target-platform: iphoneos + os: macos-12 + type: Debug + - target-platform: iphonesimulator + os: macos-12 + type: Debug # Test with Clang too - os: ubuntu-20.04 type: Debug @@ -90,6 +87,8 @@ jobs: cmake_args+=" -Dramses-sdk_ENABLE_DEFAULT_WINDOW_TYPE=OFF" cmake_args+=" -Dramses-sdk_BUILD_FULL_SHARED_LIB=OFF" cmake_args+=" -Dramses-sdk_BUILD_HEADLESS_SHARED_LIB=ON" + # temporarily disable building tests for MacOS platform + cmake_args+=" -Dramses-sdk_BUILD_TESTS=OFF" fi if [[ "${{matrix.target-platform}}" == "iphone"* ]]; then