From 3defbce31b42452f8cd598acdce37f95472fb0ed Mon Sep 17 00:00:00 2001 From: bosnichd Date: Tue, 11 May 2021 09:31:02 -0600 Subject: [PATCH] Remove legacy serialization and QPropertyTree (#684) Remove: - CryCommon/CryExtension/* - CryCommon/Serialization/* - Sandbox/Plugins/EditorCommon/QPropertyTree/* - All related CryCommon interfaces - All CrySystem implementations - Various related Editor classes --- Code/CryEngine/CryCommon/AnimTime.h | 173 - Code/CryEngine/CryCommon/Bezier.h | 321 -- .../CryExtension/CryCreateClassInstance.h | 96 - .../CryCommon/CryExtension/CryGUID.h | 123 - .../CryCommon/CryExtension/CryTypeID.h | 29 - .../CryCommon/CryExtension/ICryFactory.h | 41 - .../CryExtension/ICryFactoryRegistry.h | 56 - .../CryCommon/CryExtension/ICryUnknown.h | 224 -- .../CryCommon/CryExtension/Impl/ClassWeaver.h | 461 --- .../CryCommon/CryExtension/Impl/Conversion.h | 109 - .../CryExtension/Impl/CryGUIDHelper.h | 67 - .../Impl/ICryFactoryRegistryImpl.h | 58 - .../CryExtension/Impl/RegFactoryNode.h | 52 - .../CryCommon/CryExtension/Impl/TypeList.h | 236 -- Code/CryEngine/CryCommon/CryPool/Allocator.h | 207 -- Code/CryEngine/CryCommon/CryPool/Container.h | 655 ---- Code/CryEngine/CryCommon/CryPool/Defrag.h | 65 - Code/CryEngine/CryCommon/CryPool/Fallback.h | 81 - Code/CryEngine/CryCommon/CryPool/Inspector.h | 203 -- Code/CryEngine/CryCommon/CryPool/List.h | 366 -- Code/CryEngine/CryCommon/CryPool/Memory.h | 70 - Code/CryEngine/CryCommon/CryPool/PoolAlloc.h | 55 - Code/CryEngine/CryCommon/CryPool/STLWrapper.h | 148 - Code/CryEngine/CryCommon/CryPool/ThreadSafe.h | 58 - Code/CryEngine/CryCommon/CryPool/example.h | 287 -- .../CryEngine/CryCommon/GeomCacheFileFormat.h | 202 -- Code/CryEngine/CryCommon/IEngineModule.h | 53 - Code/CryEngine/CryCommon/IRemoteCommand.h | 763 ---- Code/CryEngine/CryCommon/IServiceNetwork.h | 344 -- Code/CryEngine/CryCommon/ISystem.h | 22 - Code/CryEngine/CryCommon/Mocks/IConsoleMock.h | 1 - Code/CryEngine/CryCommon/Mocks/ISystemMock.h | 8 - .../CryCommon/Serialization/Assert.h | 46 - .../CryCommon/Serialization/BitVector.h | 39 - .../CryCommon/Serialization/BitVectorImpl.h | 88 - .../CryCommon/Serialization/BlackBox.h | 93 - .../CryCommon/Serialization/BoostSharedPtr.h | 102 - .../CryCommon/Serialization/CRCRef.h | 30 - .../CryCommon/Serialization/CRCRefImpl.h | 100 - .../CryCommon/Serialization/Callback.h | 184 - .../CryCommon/Serialization/ClassFactory.h | 376 -- .../Serialization/ClassFactoryImpl.h | 47 - .../CryEngine/CryCommon/Serialization/Color.h | 55 - .../CryCommon/Serialization/ColorImpl.h | 53 - .../CryCommon/Serialization/CryExtension.h | 44 - .../Serialization/CryExtensionImpl.h | 281 -- .../CryCommon/Serialization/CryName.h | 26 - .../CryCommon/Serialization/CryNameImpl.h | 61 - .../CryCommon/Serialization/CryStrings.h | 36 - .../CryCommon/Serialization/CryStringsImpl.h | 74 - .../Serialization/Decorators/ActionButton.h | 89 - .../Serialization/Decorators/BitFlags.h | 64 - .../Serialization/Decorators/BitFlagsImpl.h | 67 - .../Serialization/Decorators/ColorPicker.h | 43 - .../Decorators/ColorPickerImpl.h | 33 - .../Serialization/Decorators/JointName.h | 19 - .../Serialization/Decorators/JointNameImpl.h | 19 - .../Serialization/Decorators/LocalFrame.h | 117 - .../Serialization/Decorators/LocalFrameImpl.h | 89 - .../Serialization/Decorators/OutputFilePath.h | 49 - .../Decorators/OutputFilePathImpl.h | 32 - .../Serialization/Decorators/Range.h | 63 - .../Serialization/Decorators/RangeImpl.h | 50 - .../Decorators/ResourceFilePath.h | 59 - .../Decorators/ResourceFilePathImpl.h | 32 - .../Decorators/ResourceFolderPath.h | 43 - .../Decorators/ResourceFolderPathImpl.h | 34 - .../Decorators/ResourceSelector.h | 100 - .../Serialization/Decorators/Resources.h | 67 - .../Serialization/Decorators/ResourcesAudio.h | 31 - .../Serialization/Decorators/ResourcesImpl.h | 44 - .../Serialization/Decorators/Slider.h | 88 - .../Serialization/Decorators/SliderImpl.h | 47 - .../Serialization/Decorators/Sprite.h | 44 - .../Serialization/Decorators/SpriteImpl.h | 35 - .../Serialization/Decorators/TagList.h | 49 - .../Serialization/Decorators/TagListImpl.h | 40 - .../CryCommon/Serialization/DynArray.h | 27 - .../CryCommon/Serialization/DynArrayImpl.h | 28 - Code/CryEngine/CryCommon/Serialization/Enum.h | 170 - .../CryCommon/Serialization/EnumImpl.h | 248 -- .../CryCommon/Serialization/IArchive.h | 446 --- .../CryCommon/Serialization/IArchiveHost.h | 153 - .../CryCommon/Serialization/IClassFactory.h | 85 - .../Serialization/ITextInputArchive.h | 46 - .../Serialization/ITextOutputArchive.h | 55 - .../CryCommon/Serialization/IXmlArchive.h | 175 - .../Serialization/IntrusiveFactory.h | 99 - .../CryCommon/Serialization/KeyValue.h | 37 - Code/CryEngine/CryCommon/Serialization/Math.h | 166 - .../CryCommon/Serialization/MathImpl.h | 207 -- .../Serialization/NetScriptSerialize.h | 27 - .../CryCommon/Serialization/Object.h | 153 - Code/CryEngine/CryCommon/Serialization/STL.h | 52 - .../CryCommon/Serialization/STLImpl.h | 251 -- .../CryCommon/Serialization/Serializer.h | 268 -- .../CryCommon/Serialization/SerializerImpl.h | 95 - .../CryCommon/Serialization/SmartPtr.h | 31 - .../CryCommon/Serialization/SmartPtrImpl.h | 73 - .../CryCommon/Serialization/StringList.h | 301 -- .../CryCommon/Serialization/StringListImpl.h | 126 - .../CryCommon/Serialization/Strings.h | 32 - .../CryCommon/Serialization/TypeID.h | 290 -- .../CryCommon/Serialization/TypeInfo.h | 46 - .../CryCommon/Serialization/TypeInfoImpl.h | 245 -- .../CryEngine/CryCommon/crycommon_files.cmake | 100 - Code/CryEngine/CryCommon/platform_impl.cpp | 16 +- Code/CryEngine/CrySystem/DllMain.cpp | 9 +- .../CryFactoryRegistryImpl.cpp | 359 -- .../ExtensionSystem/CryFactoryRegistryImpl.h | 128 - .../TestCases/TestExtensions.cpp | 955 ----- .../TestCases/TestExtensions.h | 126 - Code/CryEngine/CrySystem/RemoteCommand.cpp | 191 - Code/CryEngine/CrySystem/RemoteCommand.h | 459 --- .../CrySystem/RemoteCommandClient.cpp | 756 ---- .../CrySystem/RemoteCommandHelpers.cpp | 361 -- .../CrySystem/RemoteCommandHelpers.h | 307 -- .../CrySystem/RemoteCommandServer.cpp | 832 ----- .../CrySystem/Serialization/ArchiveHost.cpp | 239 -- .../CrySystem/Serialization/ArchiveHost.h | 21 - .../CrySystem/Serialization/BinArchive.cpp | 839 ----- .../CrySystem/Serialization/BinArchive.h | 180 - .../CrySystem/Serialization/JSONIArchive.cpp | 1525 -------- .../CrySystem/Serialization/JSONIArchive.h | 95 - .../CrySystem/Serialization/JSONOArchive.cpp | 828 ----- .../CrySystem/Serialization/JSONOArchive.h | 102 - .../CrySystem/Serialization/MemoryReader.cpp | 92 - .../CrySystem/Serialization/MemoryReader.h | 56 - .../CrySystem/Serialization/MemoryWriter.cpp | 236 -- .../CrySystem/Serialization/MemoryWriter.h | 72 - .../Serialization/Test_ArchiveHost.cpp | 492 --- .../CryEngine/CrySystem/Serialization/Token.h | 89 - .../CrySystem/Serialization/XmlIArchive.cpp | 297 -- .../CrySystem/Serialization/XmlIArchive.h | 62 - .../CrySystem/Serialization/XmlOArchive.cpp | 213 -- .../CrySystem/Serialization/XmlOArchive.h | 60 - Code/CryEngine/CrySystem/ServiceNetwork.cpp | 2035 ----------- Code/CryEngine/CrySystem/ServiceNetwork.h | 475 --- Code/CryEngine/CrySystem/System.cpp | 5 - Code/CryEngine/CrySystem/System.h | 9 - Code/CryEngine/CrySystem/SystemInit.cpp | 172 - Code/CryEngine/CrySystem/XConsole.cpp | 1 - .../CryEngine/CrySystem/crysystem_files.cmake | 29 - .../CrySystem/crysystem_test_files.cmake | 1 - .../Editor/Controls/CurveEditorCtrl.cpp | 821 ----- .../Sandbox/Editor/Controls/CurveEditorCtrl.h | 112 - Code/Sandbox/Editor/EditorViewportWidget.cpp | 8 - Code/Sandbox/Editor/IEditorImpl.cpp | 3 - .../Editor/Include/IResourceSelectorHost.h | 26 - Code/Sandbox/Editor/ResourceSelectorHost.cpp | 10 - Code/Sandbox/Editor/Serialization.h | 26 - .../Editor/Serialization/VariableIArchive.cpp | 283 -- .../Editor/Serialization/VariableIArchive.h | 71 - .../Editor/Serialization/VariableOArchive.cpp | 416 --- .../Editor/Serialization/VariableOArchive.h | 83 - Code/Sandbox/Editor/SettingsBlock.cpp | 177 - Code/Sandbox/Editor/SettingsBlock.h | 76 - Code/Sandbox/Editor/editor_lib_files.cmake | 9 - .../ComponentEntityEditorPlugin.cpp | 1 - .../Plugins/EditorCommon/BatchFileDialog.cpp | 357 -- .../Plugins/EditorCommon/BatchFileDialog.h | 77 - .../Plugins/EditorCommon/CMakeLists.txt | 3 - .../Plugins/EditorCommon/CurveEditor.cpp | 2459 ------------- .../Plugins/EditorCommon/CurveEditor.h | 233 -- .../Plugins/EditorCommon/CurveEditorContent.h | 155 - .../EditorCommon/CurveEditorContent_38.h | 84 - .../EditorCommon/CurveEditorContent_impl.h | 20 - .../EditorCommon/CurveEditorControl.cpp | 352 -- .../Plugins/EditorCommon/CurveEditorControl.h | 150 - .../Plugins/EditorCommon/CurveEditor_38.cpp | 1825 ---------- .../Plugins/EditorCommon/CurveEditor_38.h | 154 - .../EditorCommon/DisplayViewportAdapter.cpp | 194 -- .../EditorCommon/DisplayViewportAdapter.h | 64 - .../EditorCommon/DockTitleBarWidget.cpp | 17 +- .../EditorCommon/DrawingPrimitives/Ruler.cpp | 6 +- .../Plugins/EditorCommon/EditorCommon.qrc | 15 - .../EditorCommon/Events/EventManager.cpp | 144 - .../EditorCommon/Events/EventManager.h | 204 -- .../EditorCommon/ListSelectionDialog.cpp | 224 -- .../EditorCommon/ListSelectionDialog.h | 73 - .../QPropertyTree/Unicode_UnixLike.cpp | 29 - .../Platform/Linux/platform_linux_files.cmake | 14 - .../Platform/Mac/platform_mac_files.cmake | 14 - .../Windows/QPropertyTree/Unicode_Windows.cpp | 41 - .../Windows/platform_windows_files.cmake | 14 - .../QAbstractQVariantTreeDataModel.cpp | 75 - .../QAbstractQVariantTreeDataModel.h | 87 - .../Plugins/EditorCommon/QParentWndWidget.cpp | 309 -- .../Plugins/EditorCommon/QParentWndWidget.h | 67 - .../Plugins/EditorCommon/QPropertyCtrl.h | 49 - .../EditorCommon/QPropertyTree/Color.cpp | 123 - .../EditorCommon/QPropertyTree/Color.h | 66 - .../QPropertyTree/ConstStringList.cpp | 58 - .../QPropertyTree/ConstStringList.h | 46 - .../EditorCommon/QPropertyTree/ContextList.h | 76 - .../EditorCommon/QPropertyTree/Factory.h | 156 - .../EditorCommon/QPropertyTree/MathUtils.h | 54 - .../QPropertyTree/PropertyDrawContext.cpp | 466 --- .../QPropertyTree/PropertyDrawContext.h | 98 - .../QPropertyTree/PropertyIArchive.cpp | 377 -- .../QPropertyTree/PropertyIArchive.h | 80 - .../QPropertyTree/PropertyOArchive.cpp | 487 --- .../QPropertyTree/PropertyOArchive.h | 112 - .../QPropertyTree/PropertyRow.cpp | 1906 ---------- .../EditorCommon/QPropertyTree/PropertyRow.h | 575 --- .../QPropertyTree/PropertyRowActionButton.cpp | 168 - .../QPropertyTree/PropertyRowBool.cpp | 116 - .../QPropertyTree/PropertyRowBool.h | 50 - .../QPropertyTree/PropertyRowColor.cpp | 241 -- .../QPropertyTree/PropertyRowColor.h | 75 - .../QPropertyTree/PropertyRowColorPicker.cpp | 158 - .../QPropertyTree/PropertyRowColorPicker.h | 56 - .../QPropertyTree/PropertyRowContainer.cpp | 439 --- .../QPropertyTree/PropertyRowContainer.h | 96 - .../QPropertyTree/PropertyRowField.cpp | 84 - .../QPropertyTree/PropertyRowField.h | 39 - .../QPropertyTree/PropertyRowIconXPM.cpp | 119 - .../QPropertyTree/PropertyRowImpl.h | 48 - .../QPropertyTree/PropertyRowLocalFrame.cpp | 152 - .../QPropertyTree/PropertyRowLocalFrame.h | 70 - .../QPropertyTree/PropertyRowNumber.cpp | 43 - .../QPropertyTree/PropertyRowNumber.h | 237 -- .../QPropertyTree/PropertyRowNumberField.cpp | 287 -- .../QPropertyTree/PropertyRowNumberField.h | 75 - .../QPropertyTree/PropertyRowObject.cpp | 42 - .../QPropertyTree/PropertyRowObject.h | 51 - .../PropertyRowOutputFilePath.cpp | 205 -- .../QPropertyTree/PropertyRowOutputFilePath.h | 74 - .../QPropertyTree/PropertyRowPointer.cpp | 346 -- .../QPropertyTree/PropertyRowPointer.h | 95 - .../PropertyRowResourceFilePath.cpp | 177 - .../PropertyRowResourceFilePath.h | 79 - .../PropertyRowResourceFolderPath.cpp | 159 - .../PropertyRowResourceFolderPath.h | 76 - .../PropertyRowResourceSelector.cpp | 425 --- .../PropertyRowResourceSelector.h | 100 - .../QPropertyTree/PropertyRowSlider.cpp | 521 --- .../QPropertyTree/PropertyRowSprite.cpp | 299 -- .../QPropertyTree/PropertyRowSprite.h | 70 - .../QPropertyTree/PropertyRowString.cpp | 87 - .../QPropertyTree/PropertyRowString.h | 114 - .../PropertyRowStringListValue.cpp | 42 - .../PropertyRowStringListValue.h | 303 -- .../QPropertyTree/PropertyRowTagList.cpp | 132 - .../QPropertyTree/PropertyRowTagList.h | 51 - .../QPropertyTree/PropertyRowToggleButton.cpp | 205 -- .../QPropertyTree/PropertyTreeMenuHandler.h | 45 - .../QPropertyTree/PropertyTreeModel.cpp | 445 --- .../QPropertyTree/PropertyTreeModel.h | 208 -- .../QPropertyTree/PropertyTreeOperator.cpp | 53 - .../QPropertyTree/PropertyTreeOperator.h | 65 - .../QPropertyTree/QPropertyDialog.cpp | 227 -- .../QPropertyTree/QPropertyDialog.h | 76 - .../QPropertyTree/QPropertyTree.cpp | 3083 ----------------- .../QPropertyTree/QPropertyTree.h | 528 --- .../QPropertyTree/QPropertyTreeStyle.h | 90 - .../QPropertyTree/Serialization.h | 29 - .../EditorCommon/QPropertyTree/SlicerEdit.cpp | 56 - .../EditorCommon/QPropertyTree/SlicerEdit.h | 46 - .../QPropertyTree/SlicerManipulator.cpp | 143 - .../QPropertyTree/SlicerManipulator.h | 58 - .../EditorCommon/QPropertyTree/SlicerView.cpp | 25 - .../EditorCommon/QPropertyTree/SlicerView.h | 34 - .../QPropertyTree/SpriteBorderEditor.cpp | 175 - .../QPropertyTree/SpriteBorderEditor.h | 41 - .../SpriteBorderEditorCommon.cpp | 120 - .../QPropertyTree/SpriteBorderEditorCommon.h | 78 - .../EditorCommon/QPropertyTree/Strings.h | 29 - .../EditorCommon/QPropertyTree/Unicode.h | 24 - .../QPropertyTree/ValidatorBlock.h | 172 - .../EditorCommon/QPropertyTree/error.xpm | 126 - .../EditorCommon/QPropertyTree/file_open.xpm | 142 - .../EditorCommon/QPropertyTree/file_save.xpm | 168 - .../EditorCommon/QPropertyTree/gear.xpm | 24 - .../QPropertyTree/wWidgets_NOTICES.txt | 49 - .../EditorCommon/QPropertyTree/warning.xpm | 134 - .../Plugins/EditorCommon/QViewport.cpp | 913 ----- Code/Sandbox/Plugins/EditorCommon/QViewport.h | 193 -- .../Plugins/EditorCommon/QViewportConsumer.h | 37 - .../Plugins/EditorCommon/QViewportEvents.h | 96 - .../Plugins/EditorCommon/QViewportSettings.h | 269 -- .../Plugins/EditorCommon/Serialization.cpp | 15 - .../Plugins/EditorCommon/Serialization.h | 44 - .../EditorCommon/Serialization/BinArchive.cpp | 839 ----- .../EditorCommon/Serialization/BinArchive.h | 183 - .../Decorators/EditorActionButton.h | 76 - .../Serialization/Decorators/IGizmoSink.h | 49 - .../Decorators/INavigationProvider.h | 43 - .../Serialization/Decorators/IconXPM.h | 100 - .../Serialization/Decorators/ToggleButton.h | 50 - .../Decorators/ToggleButtonImpl.h | 44 - .../Serialization/JSONIArchive.cpp | 1522 -------- .../EditorCommon/Serialization/JSONIArchive.h | 103 - .../Serialization/JSONOArchive.cpp | 828 ----- .../EditorCommon/Serialization/JSONOArchive.h | 108 - .../Serialization/MemoryReader.cpp | 92 - .../EditorCommon/Serialization/MemoryReader.h | 62 - .../Serialization/MemoryWriter.cpp | 275 -- .../EditorCommon/Serialization/MemoryWriter.h | 80 - .../EditorCommon/Serialization/Pointers.h | 265 -- .../EditorCommon/Serialization/PointersImpl.h | 140 - .../Plugins/EditorCommon/Serialization/Qt.cpp | 393 --- .../Plugins/EditorCommon/Serialization/Qt.h | 33 - .../EditorCommon/Serialization/QtImpl.h | 24 - .../EditorCommon/Serialization/Token.h | 93 - .../Serialization/yasli_NOTICES.txt | 49 - .../Sandbox/Plugins/EditorCommon/Timeline.cpp | 2728 --------------- Code/Sandbox/Plugins/EditorCommon/Timeline.h | 216 -- .../Plugins/EditorCommon/TimelineContent.cpp | 20 - .../Plugins/EditorCommon/TimelineContent.h | 154 - .../EditorCommon/UnsavedChangesDialog.cpp | 117 - .../EditorCommon/UnsavedChangesDialog.h | 42 - .../EditorCommon/editorcommon_files.cmake | 132 - Code/Sandbox/Plugins/EditorCommon/moc.cpp | 21 - .../Android/AudioEngineWwise_Traits_Android.h | 1 - .../Linux/AudioEngineWwise_Traits_Linux.h | 1 - .../Mac/AudioEngineWwise_Traits_Mac.h | 1 - .../Windows/AudioEngineWwise_Traits_Windows.h | 1 - .../iOS/AudioEngineWwise_Traits_iOS.h | 1 - .../AudioEngineWwiseGemSystemComponent.cpp | 11 - .../Source/Editor/AudioSystemEditor_wwise.h | 11 - .../Source/Engine/AudioSystemImpl_wwise.cpp | 7 - .../Code/Source/Engine/Common_wwise.h | 14 - .../Code/Include/Editor/IAudioConnection.h | 6 - .../Code/Source/Editor/AudioControl.h | 1 + .../Source/Editor/AudioResourceSelectors.cpp | 1 - .../Code/Source/Editor/ConnectionsWidget.ui | 28 - .../Code/Source/Editor/QConnectionsWidget.cpp | 17 - Gems/GameEffectSystem/preview.png | 3 - Gems/LyShine/Code/Editor/ViewportWidget.cpp | 1 - .../Code/Source/Cinematics/CryMovie.cpp | 79 - .../Code/Source/Cinematics/CryMovie.def | 3 - .../Maestro/Code/Source/Cinematics/CryMovie.h | 40 - .../Code/Source/Cinematics/CryMovie.rc | 111 - Gems/SVOGI/preview.png | 3 - .../ConsoleFrontendConfig.in | 1 - .../Windows/package_filelists/atom.json | 1 - .../commit_validation/pal_allowedlist.txt | 1 - 338 files changed, 16 insertions(+), 63358 deletions(-) delete mode 100644 Code/CryEngine/CryCommon/AnimTime.h delete mode 100644 Code/CryEngine/CryCommon/Bezier.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/CryCreateClassInstance.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/CryGUID.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/CryTypeID.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/ICryFactory.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/ICryFactoryRegistry.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/ICryUnknown.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/ClassWeaver.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/Conversion.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/CryGUIDHelper.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/ICryFactoryRegistryImpl.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/RegFactoryNode.h delete mode 100644 Code/CryEngine/CryCommon/CryExtension/Impl/TypeList.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Allocator.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Container.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Defrag.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Fallback.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Inspector.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/List.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/Memory.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/PoolAlloc.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/STLWrapper.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/ThreadSafe.h delete mode 100644 Code/CryEngine/CryCommon/CryPool/example.h delete mode 100644 Code/CryEngine/CryCommon/GeomCacheFileFormat.h delete mode 100644 Code/CryEngine/CryCommon/IEngineModule.h delete mode 100644 Code/CryEngine/CryCommon/IRemoteCommand.h delete mode 100644 Code/CryEngine/CryCommon/IServiceNetwork.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Assert.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/BitVector.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/BitVectorImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/BlackBox.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/BoostSharedPtr.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CRCRef.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CRCRefImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Callback.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/ClassFactory.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/ClassFactoryImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Color.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/ColorImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryExtension.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryExtensionImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryName.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryNameImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryStrings.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/CryStringsImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ActionButton.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/BitFlags.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/BitFlagsImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ColorPicker.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ColorPickerImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/JointName.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/JointNameImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrame.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrameImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/OutputFilePath.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/OutputFilePathImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/Range.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/RangeImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePath.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePathImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPath.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPathImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourceSelector.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/Resources.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesAudio.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/Slider.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/SliderImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/Sprite.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/SpriteImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/TagList.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Decorators/TagListImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/DynArray.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/DynArrayImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Enum.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/EnumImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/IArchive.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/IArchiveHost.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/IClassFactory.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/ITextInputArchive.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/ITextOutputArchive.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/IXmlArchive.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/IntrusiveFactory.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/KeyValue.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Math.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/MathImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/NetScriptSerialize.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Object.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/STL.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/STLImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Serializer.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/SerializerImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/SmartPtr.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/SmartPtrImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/StringList.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/StringListImpl.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/Strings.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/TypeID.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/TypeInfo.h delete mode 100644 Code/CryEngine/CryCommon/Serialization/TypeInfoImpl.h delete mode 100644 Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.cpp delete mode 100644 Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.h delete mode 100644 Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.cpp delete mode 100644 Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.h delete mode 100644 Code/CryEngine/CrySystem/RemoteCommand.cpp delete mode 100644 Code/CryEngine/CrySystem/RemoteCommand.h delete mode 100644 Code/CryEngine/CrySystem/RemoteCommandClient.cpp delete mode 100644 Code/CryEngine/CrySystem/RemoteCommandHelpers.cpp delete mode 100644 Code/CryEngine/CrySystem/RemoteCommandHelpers.h delete mode 100644 Code/CryEngine/CrySystem/RemoteCommandServer.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/ArchiveHost.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/ArchiveHost.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/BinArchive.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/BinArchive.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/JSONIArchive.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/JSONIArchive.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/JSONOArchive.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/JSONOArchive.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/MemoryReader.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/MemoryReader.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/MemoryWriter.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/MemoryWriter.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/Test_ArchiveHost.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/Token.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/XmlIArchive.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/XmlIArchive.h delete mode 100644 Code/CryEngine/CrySystem/Serialization/XmlOArchive.cpp delete mode 100644 Code/CryEngine/CrySystem/Serialization/XmlOArchive.h delete mode 100644 Code/CryEngine/CrySystem/ServiceNetwork.cpp delete mode 100644 Code/CryEngine/CrySystem/ServiceNetwork.h delete mode 100644 Code/Sandbox/Editor/Controls/CurveEditorCtrl.cpp delete mode 100644 Code/Sandbox/Editor/Controls/CurveEditorCtrl.h delete mode 100644 Code/Sandbox/Editor/Serialization.h delete mode 100644 Code/Sandbox/Editor/Serialization/VariableIArchive.cpp delete mode 100644 Code/Sandbox/Editor/Serialization/VariableIArchive.h delete mode 100644 Code/Sandbox/Editor/Serialization/VariableOArchive.cpp delete mode 100644 Code/Sandbox/Editor/Serialization/VariableOArchive.h delete mode 100644 Code/Sandbox/Editor/SettingsBlock.cpp delete mode 100644 Code/Sandbox/Editor/SettingsBlock.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditor.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditor.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditorContent.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_38.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_impl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/EditorCommon.qrc delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Events/EventManager.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Events/EventManager.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Platform/Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Platform/Windows/QPropertyTree/Unicode_Windows.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyCtrl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ContextList.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Factory.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/MathUtils.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowActionButton.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowIconXPM.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowImpl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSlider.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowToggleButton.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeMenuHandler.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTreeStyle.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Serialization.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Strings.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Unicode.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ValidatorBlock.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/error.xpm delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_open.xpm delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_save.xpm delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/gear.xpm delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/wWidgets_NOTICES.txt delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QPropertyTree/warning.xpm delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QViewport.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QViewport.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QViewportConsumer.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QViewportEvents.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/QViewportSettings.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/EditorActionButton.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IGizmoSink.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/INavigationProvider.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IconXPM.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButton.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButtonImpl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Pointers.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/PointersImpl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/QtImpl.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/Token.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Serialization/yasli_NOTICES.txt delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Timeline.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/Timeline.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/TimelineContent.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/TimelineContent.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.cpp delete mode 100644 Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.h delete mode 100644 Code/Sandbox/Plugins/EditorCommon/moc.cpp delete mode 100644 Gems/GameEffectSystem/preview.png delete mode 100644 Gems/Maestro/Code/Source/Cinematics/CryMovie.cpp delete mode 100644 Gems/Maestro/Code/Source/Cinematics/CryMovie.def delete mode 100644 Gems/Maestro/Code/Source/Cinematics/CryMovie.h delete mode 100644 Gems/Maestro/Code/Source/Cinematics/CryMovie.rc delete mode 100644 Gems/SVOGI/preview.png diff --git a/Code/CryEngine/CryCommon/AnimTime.h b/Code/CryEngine/CryCommon/AnimTime.h deleted file mode 100644 index 8bd0b9d442..0000000000 --- a/Code/CryEngine/CryCommon/AnimTime.h +++ /dev/null @@ -1,173 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef __animtime_h__ -#define __animtime_h__ - -#include -#include -#include - -struct SAnimTime -{ - static const uint numTicksPerSecond = 6000; - - // List of possible frame rates (dividers of 6000). Most commonly used ones first. - enum EFrameRate - { - // Common - eFrameRate_30fps, eFrameRate_60fps, eFrameRate_120fps, - - // Possible - eFrameRate_10fps, eFrameRate_12fps, eFrameRate_15fps, eFrameRate_24fps, - eFrameRate_25fps, eFrameRate_40fps, eFrameRate_48fps, eFrameRate_50fps, - eFrameRate_75fps, eFrameRate_80fps, eFrameRate_100fps, eFrameRate_125fps, - eFrameRate_150fps, eFrameRate_200fps, eFrameRate_240fps, eFrameRate_250fps, - eFrameRate_300fps, eFrameRate_375fps, eFrameRate_400fps, eFrameRate_500fps, - eFrameRate_600fps, eFrameRate_750fps, eFrameRate_1000fps, eFrameRate_1200fps, - eFrameRate_1500fps, eFrameRate_2000fps, eFrameRate_3000fps, eFrameRate_6000fps, - - eFrameRate_Num - }; - - SAnimTime() - : m_ticks(0) {} - explicit SAnimTime(int32 ticks) - : m_ticks(ticks) {} - explicit SAnimTime(float time) - : m_ticks(aznumeric_caster(std::lround(static_cast(time) * numTicksPerSecond))) {} - - static uint GetFrameRateValue(EFrameRate frameRate) - { - const uint frameRateValues[eFrameRate_Num] = - { - // Common - 30, 60, 120, - - // Possible - 10, 12, 15, 24, 25, 40, 48, 50, 75, 80, 100, 125, - 150, 200, 240, 250, 300, 375, 400, 500, 600, 750, - 1000, 1200, 1500, 2000, 3000, 6000 - }; - - return frameRateValues[frameRate]; - } - - static const char* GetFrameRateName(EFrameRate frameRate) - { - const char* frameRateNames[eFrameRate_Num] = - { - // Common - "30 fps", "60 fps", "120 fps", - - // Possible - "10 fps", "12 fps", "15 fps", "24 fps", - "25 fps", "40 fps", "48 fps", "50 fps", - "75 fps", "80 fps", "100 fps", "125 fps", - "150 fps", "200 fps", "240 fps", "250 fps", - "300 fps", "375 fps", "400 fps", "500 fps", - "600 fps", "750 fps", "1000 fps", "1200 fps", - "1500 fps", "2000 fps", "3000 fps", "6000 fps" - }; - - return frameRateNames[frameRate]; - } - - float ToFloat() const { return static_cast(m_ticks) / numTicksPerSecond; } - - void Serialize(Serialization::IArchive& ar) - { - ar(m_ticks, "ticks", "Ticks"); - } - - // Helper to serialize from ticks or old float time - void Serialize(XmlNodeRef keyNode, bool bLoading, const char* pName, const char* pLegacyName) - { - if (bLoading) - { - int32 ticks; - if (!keyNode->getAttr(pName, ticks)) - { - // Backwards compatibility - float time = 0.0f; - keyNode->getAttr(pLegacyName, time); - *this = SAnimTime(time); - } - else - { - m_ticks = ticks; - } - } - else if (m_ticks > 0) - { - keyNode->setAttr(pName, m_ticks); - } - } - - int32 GetTicks() const { return m_ticks; } - - static SAnimTime Min() { SAnimTime minTime; minTime.m_ticks = std::numeric_limits::lowest(); return minTime; } - static SAnimTime Max() { SAnimTime maxTime; maxTime.m_ticks = (std::numeric_limits::max)(); return maxTime; } - - SAnimTime operator-() const { return SAnimTime(-m_ticks); } - SAnimTime operator-(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks -= r.m_ticks; return temp; } - SAnimTime operator+(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks += r.m_ticks; return temp; } - SAnimTime operator*(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks *= r.m_ticks; return temp; } - SAnimTime operator/(SAnimTime r) const { SAnimTime temp; temp.m_ticks = static_cast((static_cast(m_ticks) * numTicksPerSecond) / r.m_ticks); return temp; } - SAnimTime operator%(SAnimTime r) const { SAnimTime temp = *this; temp.m_ticks %= r.m_ticks; return temp; } - SAnimTime operator*(float r) const { SAnimTime temp; temp.m_ticks = aznumeric_caster(std::lround(static_cast(m_ticks) * r)); return temp; } - SAnimTime operator/(float r) const { SAnimTime temp; temp.m_ticks = aznumeric_caster(std::lround(static_cast(m_ticks) / r)); return temp; } - SAnimTime& operator+=(SAnimTime r) { *this = *this + r; return *this; } - SAnimTime& operator-=(SAnimTime r) { *this = *this - r; return *this; } - SAnimTime& operator*=(SAnimTime r) { *this = *this * r; return *this; } - SAnimTime& operator/=(SAnimTime r) { *this = *this / r; return *this; } - SAnimTime& operator%=(SAnimTime r) { *this = *this % r; return *this; } - SAnimTime& operator*=(float r) { *this = *this * r; return *this; } - SAnimTime& operator/=(float r) { *this = *this / r; return *this; } - - bool operator<(SAnimTime r) const { return m_ticks < r.m_ticks; } - bool operator<=(SAnimTime r) const { return m_ticks <= r.m_ticks; } - bool operator>(SAnimTime r) const { return m_ticks > r.m_ticks; } - bool operator>=(SAnimTime r) const { return m_ticks >= r.m_ticks; } - bool operator==(SAnimTime r) const { return m_ticks == r.m_ticks; } - bool operator!=(SAnimTime r) const { return m_ticks != r.m_ticks; } - - // Snap to nearest multiple of given frame rate - SAnimTime SnapToNearest(const EFrameRate frameRate) - { - const int sign = sgn(m_ticks); - const int32 absTicks = abs(m_ticks); - - const int framesMod = numTicksPerSecond / GetFrameRateValue(frameRate); - const int32 remainder = absTicks % framesMod; - const bool bNextMultiple = remainder >= (framesMod / 2); - return SAnimTime(sign * ((absTicks - remainder) + (bNextMultiple ? framesMod : 0))); - } - -private: - int32 m_ticks; - - friend bool Serialize(Serialization::IArchive& ar, SAnimTime& animTime, const char* name, const char* label); -}; - -inline bool Serialize(Serialization::IArchive& ar, SAnimTime& animTime, const char* name, const char* label) -{ - return ar(animTime.m_ticks, name, label); -} - -inline SAnimTime abs(SAnimTime time) -{ - return (time >= SAnimTime(0)) ? time : -time; -} - -#endif diff --git a/Code/CryEngine/CryCommon/Bezier.h b/Code/CryEngine/CryCommon/Bezier.h deleted file mode 100644 index fa1cf60d49..0000000000 --- a/Code/CryEngine/CryCommon/Bezier.h +++ /dev/null @@ -1,321 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef __BEZIER_H__ -#define __BEZIER_H__ - -#include -#include -#include - -struct SBezierControlPoint -{ - SBezierControlPoint() - : m_value(0.0f) - , m_inTangent(ZERO) - , m_outTangent(ZERO) - , m_inTangentType(eTangentType_Auto) - , m_outTangentType(eTangentType_Auto) - , m_bBreakTangents(false) - { - } - - enum ETangentType - { - eTangentType_Custom, - eTangentType_Auto, - eTangentType_Zero, - eTangentType_Step, - eTangentType_Linear, - }; - - void Serialize(Serialization::IArchive& ar) - { - ar(m_value, "value", "Value"); - - if (ar.IsOutput()) - { - bool breakTangents = m_bBreakTangents; - ar(breakTangents, "breakTangents", "Break Tangents"); - } - else - { - bool breakTangents = false; - ar(breakTangents, "breakTangents", "Break Tangents"); - m_bBreakTangents = breakTangents; - } - - if (ar.IsOutput()) - { - ETangentType inTangentType = m_inTangentType; - ar(inTangentType, "inTangentType", "Incoming tangent type"); - } - else - { - ETangentType inTangentType = eTangentType_Auto; - ar(inTangentType, "inTangentType", "Incoming tangent type"); - m_inTangentType = inTangentType; - } - - ar(m_inTangent, "inTangent", (m_inTangentType == eTangentType_Custom) ? "Incoming Tangent" : NULL); - - if (ar.IsOutput()) - { - ETangentType outTangentType = m_outTangentType; - ar(outTangentType, "outTangentType", "Outgoing tangent type"); - } - else - { - ETangentType outTangentType = eTangentType_Auto; - ar(outTangentType, "outTangentType", "Outgoing tangent type"); - m_outTangentType = outTangentType; - } - - ar(m_outTangent, "outTangent", (m_outTangentType == eTangentType_Custom) ? "Outgoing Tangent" : NULL); - } - - float m_value; - - // For 1D Bezier only the Y component is used - Vec2 m_inTangent; - Vec2 m_outTangent; - - ETangentType m_inTangentType : 4; - ETangentType m_outTangentType : 4; - bool m_bBreakTangents : 1; -}; - -struct SBezierKey -{ - SBezierKey() - : m_time(0) {} - - void Serialize(Serialization::IArchive& ar) - { - ar(m_time, "time", "Time"); - ar(m_controlPoint, "controlPoint", "Control Point"); - } - - SAnimTime m_time; - SBezierControlPoint m_controlPoint; -}; - -namespace Bezier -{ - inline float Evaluate(float t, float p0, float p1, float p2, float p3) - { - const float a = 1 - t; - const float aSq = a * a; - const float tSq = t * t; - return (aSq * a * p0) + (3.0f * aSq * t * p1) + (3.0f * a * tSq * p2) + (tSq * t * p3); - } - - inline float EvaluateDeriv(float t, float p0, float p1, float p2, float p3) - { - const float a = 1 - t; - const float ta = t * a; - const float aSq = a * a; - const float tSq = t * t; - return 3.0f * ((-p2 * tSq) + (p3 * tSq) - (p0 * aSq) + (p1 * aSq) + 2.0f * ((-p1 * ta) + (p2 * ta))); - } - - inline float EvaluateX(const float t, const float duration, const SBezierControlPoint& start, const SBezierControlPoint& end) - { - const float p0 = 0.0f; - const float p1 = p0 + start.m_outTangent.x; - const float p3 = duration; - const float p2 = p3 + end.m_inTangent.x; - return Evaluate(t, p0, p1, p2, p3); - } - - inline float EvaluateY(const float t, const SBezierControlPoint& start, const SBezierControlPoint& end) - { - const float p0 = start.m_value; - const float p1 = p0 + start.m_outTangent.y; - const float p3 = end.m_value; - const float p2 = p3 + end.m_inTangent.y; - return Evaluate(t, p0, p1, p2, p3); - } - - // Duration = (time at end key) - (time at start key) - inline float EvaluateDerivX(const float t, const float duration, const SBezierControlPoint& start, const SBezierControlPoint& end) - { - const float p0 = 0.0f; - const float p1 = p0 + start.m_outTangent.x; - const float p3 = duration; - const float p2 = p3 + end.m_inTangent.x; - return EvaluateDeriv(t, p0, p1, p2, p3); - } - - inline float EvaluateDerivY(const float t, const SBezierControlPoint& start, const SBezierControlPoint& end) - { - const float p0 = start.m_value; - const float p1 = p0 + start.m_outTangent.y; - const float p3 = end.m_value; - const float p2 = p3 + end.m_inTangent.y; - return EvaluateDeriv(t, p0, p1, p2, p3); - } - - // Find interpolation factor where 2D bezier curve has the given x value. Works only for curves where x is monotonically increasing. - // The passed x must be in range [0, duration]. Uses the Newton-Raphson root finding method. Usually takes 2 or 3 iterations. - // - // Note: This is for "1D" 2D bezier curves as used in TrackView. The curves are restricted by the curve editor to be monotonically increasing. - // - inline float InterpolationFactorFromX(const float x, const float duration, const SBezierControlPoint& start, const SBezierControlPoint& end) - { - float t = (x / duration); - - const float epsilon = 0.00001f; - const uint maxSteps = 10; - - for (uint i = 0; i < maxSteps; ++i) - { - const float currentX = EvaluateX(t, duration, start, end) - x; - if (fabs(currentX) <= epsilon) - { - break; - } - - const float currentXDeriv = EvaluateDerivX(t, duration, start, end); - t -= currentX / currentXDeriv; - } - - return t; - } - - inline SBezierControlPoint CalculateInTangent( - float time, const SBezierControlPoint& point, - float leftTime, const SBezierControlPoint* pLeftPoint, - float rightTime, const SBezierControlPoint* pRightPoint) - { - SBezierControlPoint newPoint = point; - - // In tangent X can never be positive - newPoint.m_inTangent.x = std::min(point.m_inTangent.x, 0.0f); - - if (pLeftPoint) - { - switch (point.m_inTangentType) - { - case SBezierControlPoint::eTangentType_Custom: - { - // Need to clamp tangent if it is reaching over last point - const float deltaTime = time - leftTime; - if (deltaTime < -newPoint.m_inTangent.x) - { - if (newPoint.m_inTangent.x == 0) - { - newPoint.m_inTangent = Vec2(ZERO); - } - else - { - float scaleFactor = deltaTime / -newPoint.m_inTangent.x; - newPoint.m_inTangent.x = -deltaTime; - newPoint.m_inTangent.y *= scaleFactor; - } - } - } - break; - case SBezierControlPoint::eTangentType_Zero: - // Fall through. Zero for y is same as Auto, x is set to 0.0f - case SBezierControlPoint::eTangentType_Auto: - { - const SBezierControlPoint& rightPoint = pRightPoint ? *pRightPoint : point; - const float deltaTime = (pRightPoint ? rightTime : time) - leftTime; - if (deltaTime > 0.0f) - { - const float ratio = (time - leftTime) / deltaTime; - const float deltaValue = rightPoint.m_value - pLeftPoint->m_value; - const bool bIsZeroTangent = (point.m_inTangentType == SBezierControlPoint::eTangentType_Zero); - newPoint.m_inTangent = Vec2(-(deltaTime * ratio) / 3.0f, bIsZeroTangent ? 0.0f : -(deltaValue * ratio) / 3.0f); - } - else - { - newPoint.m_inTangent = Vec2(ZERO); - } - } - break; - case SBezierControlPoint::eTangentType_Linear: - newPoint.m_inTangent = Vec2((leftTime - time) / 3.0f, - (pLeftPoint->m_value - point.m_value) / 3.0f); - break; - } - } - - return newPoint; - } - - inline SBezierControlPoint CalculateOutTangent( - float time, const SBezierControlPoint& point, - float leftTime, const SBezierControlPoint* pLeftPoint, - float rightTime, const SBezierControlPoint* pRightPoint) - { - SBezierControlPoint newPoint = point; - - // Out tangent X can never be negative - newPoint.m_outTangent.x = std::max(point.m_outTangent.x, 0.0f); - - if (pRightPoint) - { - switch (point.m_outTangentType) - { - case SBezierControlPoint::eTangentType_Custom: - { - // Need to clamp tangent if it is reaching over next point - const float deltaTime = rightTime - time; - if (deltaTime < newPoint.m_outTangent.x) - { - if (newPoint.m_outTangent.x == 0) - { - newPoint.m_outTangent = Vec2(ZERO); - } - else - { - float scaleFactor = deltaTime / newPoint.m_outTangent.x; - newPoint.m_outTangent.x = deltaTime; - newPoint.m_outTangent.y *= scaleFactor; - } - } - } - break; - case SBezierControlPoint::eTangentType_Zero: - // Fall through. Zero for y is same as Auto, x is set to 0.0f - case SBezierControlPoint::eTangentType_Auto: - { - const SBezierControlPoint& leftPoint = pLeftPoint ? *pLeftPoint : point; - const float deltaTime = rightTime - (pLeftPoint ? leftTime : time); - if (deltaTime > 0.0f) - { - const float ratio = (rightTime - time) / deltaTime; - const float deltaValue = pRightPoint->m_value - leftPoint.m_value; - const bool bIsZeroTangent = (point.m_outTangentType == SBezierControlPoint::eTangentType_Zero); - newPoint.m_outTangent = Vec2((deltaTime * ratio) / 3.0f, bIsZeroTangent ? 0.0f : (deltaValue * ratio) / 3.0f); - } - else - { - newPoint.m_outTangent = Vec2(ZERO); - } - } - break; - case SBezierControlPoint::eTangentType_Linear: - newPoint.m_outTangent = Vec2((rightTime - time) / 3.0f, - (pRightPoint->m_value - point.m_value) / 3.0f); - break; - } - } - - return newPoint; - } -} - -#endif diff --git a/Code/CryEngine/CryCommon/CryExtension/CryCreateClassInstance.h b/Code/CryEngine/CryCommon/CryExtension/CryCreateClassInstance.h deleted file mode 100644 index 1d1a4805d4..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/CryCreateClassInstance.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_CRYCREATECLASSINSTANCE_H -#define CRYINCLUDE_CRYEXTENSION_CRYCREATECLASSINSTANCE_H -#pragma once - - -#include "ICryUnknown.h" -#include "ICryFactory.h" -#include "ICryFactoryRegistry.h" -#include // <> required for Interfuscator - - -template -bool CryCreateClassInstance(const CryClassID& cid, AZStd::shared_ptr& p) -{ - p = AZStd::shared_ptr(); - ICryFactoryRegistry* pFactoryReg = gEnv->pSystem->GetCryFactoryRegistry(); - if (pFactoryReg) - { - ICryFactory* pFactory = pFactoryReg->GetFactory(cid); - if (pFactory && pFactory->ClassSupports(cryiidof())) - { - ICryUnknownPtr pUnk = pFactory->CreateClassInstance(); - AZStd::shared_ptr pT = cryinterface_cast(pUnk); - if (pT) - { - p = pT; - } - } - } - return p.get() != NULL; -} - - -template -bool CryCreateClassInstance(const char* cname, AZStd::shared_ptr& p) -{ - p = AZStd::shared_ptr(); - ICryFactoryRegistry* pFactoryReg = gEnv->pSystem->GetCryFactoryRegistry(); - if (pFactoryReg) - { - ICryFactory* pFactory = pFactoryReg->GetFactory(cname); - if (pFactory != NULL && pFactory->ClassSupports(cryiidof())) - { - ICryUnknownPtr pUnk = pFactory->CreateClassInstance(); - AZStd::shared_ptr pT = cryinterface_cast(pUnk); - if (pT) - { - p = pT; - } - } - } - return p.get() != NULL; -} - - -template -bool CryCreateClassInstanceForInterface(const CryInterfaceID& iid, AZStd::shared_ptr& p) -{ - p = AZStd::shared_ptr(); - ICryFactoryRegistry* pFactoryReg = gEnv->pSystem->GetCryFactoryRegistry(); - if (pFactoryReg) - { - size_t numFactories = 1; - ICryFactory* pFactory = 0; - pFactoryReg->IterateFactories(iid, &pFactory, numFactories); - if (numFactories == 1 && pFactory) - { - ICryUnknownPtr pUnk = pFactory->CreateClassInstance(); - AZStd::shared_ptr pT = cryinterface_cast(pUnk); - if (pT) - { - p = pT; - } - } - } - return p.get() != NULL; -} - - -#endif // CRYINCLUDE_CRYEXTENSION_CRYCREATECLASSINSTANCE_H diff --git a/Code/CryEngine/CryCommon/CryExtension/CryGUID.h b/Code/CryEngine/CryCommon/CryExtension/CryGUID.h deleted file mode 100644 index a779e91bd2..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/CryGUID.h +++ /dev/null @@ -1,123 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_CRYGUID_H -#define CRYINCLUDE_CRYEXTENSION_CRYGUID_H -#pragma once - -#include "Serialization/IArchive.h" -#include "Random.h" - -#include - -struct CryGUID -{ - uint64 hipart; - uint64 lopart; - - // !!! Do NOT turn CryGUID into a non-aggregate !!! - // It will prevent inlining and type list unrolling opportunities within - // cryinterface_cast() and cryiidof(). As such prevent constructors, - // non-public members, base classes and virtual functions! - - //CryGUID() : hipart(0), lopart(0) {} - //CryGUID(uint64 h, uint64 l) : hipart(h), lopart(l) {} - - static CryGUID Construct(const uint64& hipart, const uint64& lopart) - { - CryGUID guid = {hipart, lopart}; - return guid; - } - - static CryGUID Create() - { - uint64 lopart = 0; - uint64 hipart = 0; - while (lopart == 0 || hipart == 0) - { - const uint32 a = cry_random_uint32(); - const uint32 b = cry_random_uint32(); - const uint32 c = cry_random_uint32(); - const uint32 d = cry_random_uint32(); - lopart = (uint64)a | ((uint64)b << 32); - hipart = (uint64)c | ((uint64)d << 32); - } - - return Construct(lopart, hipart); - } - - static CryGUID Null() - { - return Construct(0, 0); - } - - bool operator ==(const CryGUID& rhs) const {return hipart == rhs.hipart && lopart == rhs.lopart; } - bool operator !=(const CryGUID& rhs) const {return hipart != rhs.hipart || lopart != rhs.lopart; } - bool operator <(const CryGUID& rhs) const {return hipart == rhs.hipart ? lopart < rhs.lopart : hipart < rhs.hipart; } - - void Serialize(Serialization::IArchive& ar) - { - if (ar.IsInput()) - { - uint32 dwords[4]; - ar(dwords, "guid"); - lopart = (((uint64)dwords[1]) << 32) | (uint64)dwords[0]; - hipart = (((uint64)dwords[3]) << 32) | (uint64)dwords[2]; - } - else - { - uint32 guid[4] = { - (uint32)(lopart & 0xFFFFFFFF), (uint32)((lopart >> 32) & 0xFFFFFFFF), - (uint32)(hipart & 0xFFFFFFFF), (uint32)((hipart >> 32) & 0xFFFFFFFF) - }; - ar(guid, "guid"); - } - } -}; - -// This is only used by the editor where we use C++ 11. -namespace std -{ - template<> - struct hash - { - public: - size_t operator()(const CryGUID& guid) const - { - std::hash hasher; - return hasher(guid.lopart) ^ hasher(guid.hipart); - } - }; -} - -namespace AZStd -{ - template<> - struct hash - { - public: - size_t operator()(const CryGUID& guid) const - { - std::hash hasher; - return hasher(guid); - } - }; -} - -#define MAKE_CRYGUID(high, low) CryGUID::Construct((uint64) high##LL, (uint64) low##LL) - - -#endif // CRYINCLUDE_CRYEXTENSION_CRYGUID_H diff --git a/Code/CryEngine/CryCommon/CryExtension/CryTypeID.h b/Code/CryEngine/CryCommon/CryExtension/CryTypeID.h deleted file mode 100644 index 16ae05b448..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/CryTypeID.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_CRYTYPEID_H -#define CRYINCLUDE_CRYEXTENSION_CRYTYPEID_H -#pragma once - - -#include "CryGUID.h" - - -typedef CryGUID CryInterfaceID; -typedef CryGUID CryClassID; - - -#endif // CRYINCLUDE_CRYEXTENSION_CRYTYPEID_H diff --git a/Code/CryEngine/CryCommon/CryExtension/ICryFactory.h b/Code/CryEngine/CryCommon/CryExtension/ICryFactory.h deleted file mode 100644 index a1a7344198..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/ICryFactory.h +++ /dev/null @@ -1,41 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_ICRYFACTORY_H -#define CRYINCLUDE_CRYEXTENSION_ICRYFACTORY_H -#pragma once - - -#include "CryTypeID.h" -#include - -struct ICryUnknown; -DECLARE_SMART_POINTERS(ICryUnknown); - -struct ICryFactory -{ - virtual const char* GetName() const = 0; - virtual const CryClassID& GetClassID() const = 0; - virtual bool ClassSupports(const CryInterfaceID& iid) const = 0; - virtual void ClassSupports(const CryInterfaceID*& pIIDs, size_t& numIIDs) const = 0; - virtual ICryUnknownPtr CreateClassInstance() const = 0; - -protected: - // prevent explicit destruction from client side (delete, shared_ptr, etc) - virtual ~ICryFactory() {} -}; - -#endif // CRYINCLUDE_CRYEXTENSION_ICRYFACTORY_H diff --git a/Code/CryEngine/CryCommon/CryExtension/ICryFactoryRegistry.h b/Code/CryEngine/CryCommon/CryExtension/ICryFactoryRegistry.h deleted file mode 100644 index f97c0780a1..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/ICryFactoryRegistry.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_ICRYFACTORYREGISTRY_H -#define CRYINCLUDE_CRYEXTENSION_ICRYFACTORYREGISTRY_H -#pragma once - - -#include "CryTypeID.h" - - -struct ICryFactory; - - -struct ICryFactoryRegistry -{ - virtual ICryFactory* GetFactory(const char* cname) const = 0; - virtual ICryFactory* GetFactory(const CryClassID& cid) const = 0; - /** - * Iterates all factories implementing the interface specified by \p iid. - * \param[in] iid ID of the interface to iterate. Often procured using cryiidof<...>(). - * \param[out] pFactories A pointer of the array of factories to fill in. May be nullptr (see below). - * \param[in] Size (in elements) of the pFactories array [out] Number of elements actually written to pFactories or, when pFactories is null, the number of elements that would be written if sufficient storage was available. - * - * Example: - * \code{.cpp} - * size_t factoryCount = 0; - * // Assigns the number of found factories to factoryCount - * factoryRegistry->IterateFactories(cryiidof(), 0, factoryCount); - * // Allocate an array of the proper length on the stack - * ICryFactory** factories = static_cast(alloca(sizeof(ICryFactory*) * factoryCount); - * // Fill in factories with factoryCount results. - * factoryRegistry->IterateFactories(cryiidof(), factories, factoryCount); - * \endcode - */ - virtual void IterateFactories(const CryInterfaceID& iid, ICryFactory** pFactories, size_t& numFactories) const = 0; - -protected: - // prevent explicit destruction from client side (delete, shared_ptr, etc) - virtual ~ICryFactoryRegistry() {} -}; - -#endif // CRYINCLUDE_CRYEXTENSION_ICRYFACTORYREGISTRY_H diff --git a/Code/CryEngine/CryCommon/CryExtension/ICryUnknown.h b/Code/CryEngine/CryCommon/CryExtension/ICryUnknown.h deleted file mode 100644 index 0de018305b..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/ICryUnknown.h +++ /dev/null @@ -1,224 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_ICRYUNKNOWN_H -#define CRYINCLUDE_CRYEXTENSION_ICRYUNKNOWN_H -#pragma once - - -#include "CryTypeID.h" -#include - - -struct ICryFactory; -struct ICryUnknown; - -namespace InterfaceCastSemantics -{ - template - const CryInterfaceID& cryiidof() - { - return T::IID(); - } - -#define _BEFRIEND_CRYIIDOF() \ - template \ - friend const CryInterfaceID&InterfaceCastSemantics::cryiidof(); - - - template - Dst* cryinterface_cast(Src* p) - { - return static_cast(p ? p->QueryInterface(cryiidof()) : 0); - } - - template - Dst* cryinterface_cast(const Src* p) - { - return static_cast(p ? p->QueryInterface(cryiidof()) : 0); - } - - namespace Internal - { - template - struct cryinterface_cast_shared_ptr_helper; - - template - struct cryinterface_cast_shared_ptr_helper - { - static AZStd::shared_ptr Op(const AZStd::shared_ptr& p) - { - Dst* dp = cryinterface_cast(p.get()); - return dp ? AZStd::shared_ptr(p, dp) : AZStd::shared_ptr(); - } - }; - - template - struct cryinterface_cast_shared_ptr_helper - { - static AZStd::shared_ptr Op(const AZStd::shared_ptr& p) - { - ICryUnknown* dp = cryinterface_cast(p.get()); - return dp ? AZStd::shared_ptr(*((const AZStd::shared_ptr*) & p), dp) : AZStd::shared_ptr(); - } - }; - - template - struct cryinterface_cast_shared_ptr_helper - { - static AZStd::shared_ptr Op(const AZStd::shared_ptr& p) - { - const ICryUnknown* dp = cryinterface_cast(p.get()); - return dp ? AZStd::shared_ptr(*((const AZStd::shared_ptr*) & p), dp) : AZStd::shared_ptr(); - } - }; - } // namespace Internal - - template - AZStd::shared_ptr cryinterface_cast(const AZStd::shared_ptr& p) - { - return Internal::cryinterface_cast_shared_ptr_helper::Op(p); - } - -#define _BEFRIEND_CRYINTERFACE_CAST() \ - template \ - friend Dst * InterfaceCastSemantics::cryinterface_cast(Src*); \ - template \ - friend Dst * InterfaceCastSemantics::cryinterface_cast(const Src*); \ - template \ - friend AZStd::shared_ptr InterfaceCastSemantics::cryinterface_cast(const AZStd::shared_ptr&); -} // namespace InterfaceCastSemantics - -using InterfaceCastSemantics::cryiidof; -using InterfaceCastSemantics::cryinterface_cast; - - -template -bool CryIsSameClassInstance(S* p0, T* p1) -{ - return static_cast(p0) == static_cast(p1) || cryinterface_cast(p0) == cryinterface_cast(p1); -} - -template -bool CryIsSameClassInstance(const AZStd::shared_ptr& p0, T* p1) -{ - return CryIsSameClassInstance(p0.get(), p1); -} - -template -bool CryIsSameClassInstance(S* p0, const AZStd::shared_ptr& p1) -{ - return CryIsSameClassInstance(p0, p1.get()); -} - -template -bool CryIsSameClassInstance(const AZStd::shared_ptr& p0, const AZStd::shared_ptr& p1) -{ - return CryIsSameClassInstance(p0.get(), p1.get()); -} - - -namespace CompositeQuerySemantics -{ - template - AZStd::shared_ptr crycomposite_query(Src* p, const char* name, bool* pExposed = 0) - { - void* pComposite = p ? p->QueryComposite(name) : 0; - pExposed ? *pExposed = pComposite != 0 : 0; - return pComposite ? *static_cast*>(pComposite) : AZStd::shared_ptr(); - } - - template - AZStd::shared_ptr crycomposite_query(const Src* p, const char* name, bool* pExposed = 0) - { - void* pComposite = p ? p->QueryComposite(name) : 0; - pExposed ? *pExposed = pComposite != 0 : 0; - return pComposite ? *static_cast*>(pComposite) : AZStd::shared_ptr(); - } - - template - AZStd::shared_ptr crycomposite_query(const AZStd::shared_ptr& p, const char* name, bool* pExposed = 0) - { - return crycomposite_query(p.get(), name, pExposed); - } - - template - AZStd::shared_ptr crycomposite_query(const AZStd::shared_ptr& p, const char* name, bool* pExposed = 0) - { - return crycomposite_query(p.get(), name, pExposed); - } - -#define _BEFRIEND_CRYCOMPOSITE_QUERY() \ - template \ - friend AZStd::shared_ptr CompositeQuerySemantics::crycomposite_query(Src*, const char*, bool*); \ - template \ - friend AZStd::shared_ptr CompositeQuerySemantics::crycomposite_query(const Src*, const char*, bool*); \ - template \ - friend AZStd::shared_ptr CompositeQuerySemantics::crycomposite_query(const AZStd::shared_ptr&, const char*, bool*); \ - template \ - friend AZStd::shared_ptr CompositeQuerySemantics::crycomposite_query(const AZStd::shared_ptr&, const char*, bool*); -} // namespace CompositeQuerySemantics - -using CompositeQuerySemantics::crycomposite_query; - - -#define _BEFRIEND_MAKE_SHARED() \ - template \ - friend class AZStd::Internal::sp_ms_deleter; \ - template \ - friend AZStd::shared_ptr AZStd::make_shared(); \ - template \ - friend AZStd::shared_ptr AZStd::allocate_shared(A const& a); - -// prevent explicit destruction from client side -#define _PROTECTED_DTOR(iname) \ -protected: \ - virtual ~iname() {} - - -// Befriending cryinterface_cast() and crycomposite_query() via CRYINTERFACE_DECLARE is actually only needed for ICryUnknown -// since QueryInterface() and QueryComposite() are usually not redeclared in derived interfaces but it doesn't hurt either -#define CRYINTERFACE_DECLARE(iname, iidHigh, iidLow) \ - _BEFRIEND_CRYIIDOF() \ - _BEFRIEND_CRYINTERFACE_CAST() \ - _BEFRIEND_CRYCOMPOSITE_QUERY() \ - _BEFRIEND_MAKE_SHARED() \ - _PROTECTED_DTOR(iname) \ - \ -private: \ - static const CryInterfaceID& IID() \ - { \ - static const CryInterfaceID iid = {(uint64) iidHigh##LL, (uint64) iidLow##LL}; \ - return iid; \ - } \ -public: - - -struct ICryUnknown -{ - CRYINTERFACE_DECLARE(ICryUnknown, 0x1000000010001000, 0x1000100000000000) - - virtual ICryFactory * GetFactory() const = 0; - -protected: - virtual void* QueryInterface(const CryInterfaceID& iid) const = 0; - virtual void* QueryComposite(const char* name) const = 0; -}; - -DECLARE_SMART_POINTERS(ICryUnknown); - - -#endif // CRYINCLUDE_CRYEXTENSION_ICRYUNKNOWN_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/ClassWeaver.h b/Code/CryEngine/CryCommon/CryExtension/Impl/ClassWeaver.h deleted file mode 100644 index c3b5bb340c..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/ClassWeaver.h +++ /dev/null @@ -1,461 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_CLASSWEAVER_H -#define CRYINCLUDE_CRYEXTENSION_IMPL_CLASSWEAVER_H -#pragma once - -#include "TypeList.h" -#include "Conversion.h" -#include "RegFactoryNode.h" -#include "../ICryUnknown.h" -#include "../ICryFactory.h" -#include - -namespace CW -{ - namespace Internal - { - template - struct InterfaceCast; - - template - struct InterfaceCast - { - template - static void* Op(T* p) - { - return (Dst*) p; - } - }; - - template <> - struct InterfaceCast - { - template - static void* Op(T* p) - { - return const_cast(static_cast(static_cast(p))); - } - }; - } - - template - struct InterfaceCast; - - template <> - struct InterfaceCast - { - template - static void* Op(T*, const CryInterfaceID&) - { - return 0; - } - }; - - template - struct InterfaceCast > - { - template - static void* Op(T* p, const CryInterfaceID& iid) - { - if (cryiidof() == iid) - { - return Internal::InterfaceCast::Op(p); - } - return InterfaceCast::Op(p, iid); - } - }; - - template - struct FillIIDs; - - template <> - struct FillIIDs - { - static void Op(CryInterfaceID*) - { - } - }; - - template - struct FillIIDs > - { - static void Op(CryInterfaceID* p) - { - *p++ = cryiidof(); - FillIIDs::Op(p); - } - }; - - namespace Internal - { - template - struct PickList; - - template - struct PickList - { - typedef TL::BuildTypelist<>::Result Result; - }; - - template - struct PickList - { - typedef typename S::FullCompositeList Result; - }; - } - - template - struct ProbeFullCompositeList - { - private: - typedef char y[1]; - typedef char n[2]; - - template - static y& test(typename S::FullCompositeList*); - - template - static n& test(...); - - public: - enum - { - listFound = sizeof(test(0)) == sizeof(y) - }; - - typedef typename Internal::PickList::Result ListType; - }; - - namespace Internal - { - template - struct CompositeQuery; - - template <> - struct CompositeQuery - { - template - static void* Op(const T&, const char*) - { - return 0; - } - }; - - template - struct CompositeQuery > - { - template - static void* Op(const T& ref, const char* name) - { - void* p = ref.Head::CompositeQueryImpl(name); - return p ? p : CompositeQuery::Op(ref, name); - } - }; - } - - struct CompositeQuery - { - template - static void* Op(const T& ref, const char* name) - { - return Internal::CompositeQuery::ListType>::Op(ref, name); - } - }; - - inline bool NameMatch(const char* name, const char* compositeName) - { - if (!name || !compositeName) - { - return false; - } - size_t i = 0; - for (; name[i] && name[i] == compositeName[i]; ++i) - { - } - return name[i] == compositeName[i]; - } - - template - void* CheckCompositeMatch(const char* name, const AZStd::shared_ptr& composite, const char* compositeName) - { - typedef TC::SuperSubClass Rel; - COMPILE_TIME_ASSERT(Rel::exists); - return NameMatch(name, compositeName) ? const_cast(static_cast(&composite)) : 0; - } -} // namespace CW - - -#define CRYINTERFACE_BEGIN() \ -private: \ - typedef TL::BuildTypelist < ICryUnknown - -#define CRYINTERFACE_ADD(iname) , iname - -#define CRYINTERFACE_END() > ::Result _UserDefinedPartialInterfaceList; \ -protected: \ - typedef TL::NoDuplicates<_UserDefinedPartialInterfaceList>::Result FullInterfaceList; - -#define _CRY_TPL_APPEND0(base) TL::Append::Result -#define _CRY_TPL_APPEND(base, intermediate) TL::Append::Result - -#define CRYINTERFACE_ENDWITHBASE(base) > ::Result _UserDefinedPartialInterfaceList; \ -protected: \ - typedef TL::NoDuplicates<_CRY_TPL_APPEND0(base)>::Result FullInterfaceList; - -#define CRYINTERFACE_ENDWITHBASE2(base0, base1) > ::Result _UserDefinedPartialInterfaceList; \ -protected: \ - typedef TL::NoDuplicates<_CRY_TPL_APPEND(base0, _CRY_TPL_APPEND0(base1))>::Result FullInterfaceList; - -#define CRYINTERFACE_ENDWITHBASE3(base0, base1, base2) > ::Result _UserDefinedPartialInterfaceList; \ -protected: \ - typedef TL::NoDuplicates<_CRY_TPL_APPEND(base0, _CRY_TPL_APPEND(base1, _CRY_TPL_APPEND0(base2)))>::Result FullInterfaceList; - -#define CRYINTERFACE_SIMPLE(iname) \ - CRYINTERFACE_BEGIN() \ - CRYINTERFACE_ADD(iname) \ - CRYINTERFACE_END() - -#define CRYCOMPOSITE_BEGIN() \ -private: \ - void* CompositeQueryImpl(const char* name) const \ - { \ - (void)(name); \ - void* res = 0; (void)(res); \ - -#define CRYCOMPOSITE_ADD(member, membername) \ - COMPILE_TIME_ASSERT((sizeof(membername) / sizeof(membername[0])) > 1); \ - if ((res = CW::CheckCompositeMatch(name, member, membername)) != 0) { \ - return res; } - -#define _CRYCOMPOSITE_END(implclassname) \ - return 0; \ - }; \ -protected: \ - typedef TL::BuildTypelist::Result _PartialCompositeList; \ - \ - template \ - friend struct CW::Internal::PickList; - -#define CRYCOMPOSITE_END(implclassname) \ - _CRYCOMPOSITE_END(implclassname) \ -protected: \ - typedef _PartialCompositeList FullCompositeList; - -#define _CRYCOMPOSITE_APPEND0(base) TL::Append<_PartialCompositeList, CW::ProbeFullCompositeList::ListType>::Result -#define _CRYCOMPOSITE_APPEND(base, intermediate) TL::Append::ListType>::Result - -#define CRYCOMPOSITE_ENDWITHBASE(implclassname, base) \ - _CRYCOMPOSITE_END(implclassname) \ -protected: \ - typedef _CRYCOMPOSITE_APPEND0 (base) FullCompositeList; - -#define CRYCOMPOSITE_ENDWITHBASE2(implclassname, base0, base1) \ - _CRYCOMPOSITE_END(implclassname) \ -protected: \ - typedef TL::NoDuplicates<_CRYCOMPOSITE_APPEND(base1, _CRYCOMPOSITE_APPEND0(base0))>::Result FullCompositeList; - -#define CRYCOMPOSITE_ENDWITHBASE3(implclassname, base0, base1, base2) \ - _CRYCOMPOSITE_END(implclassname) \ -protected: \ - typedef TL::NoDuplicates<_CRYCOMPOSITE_APPEND(base2, _CRYCOMPOSITE_APPEND(base1, _CRYCOMPOSITE_APPEND0(base0)))>::Result FullCompositeList; - -template -class CFactory - : public ICryFactory -{ -public: - virtual const char* GetName() const - { - return T::GetCName(); - } - - virtual const CryClassID& GetClassID() const - { - return T::GetCID(); - } - - virtual bool ClassSupports(const CryInterfaceID& iid) const - { - for (size_t i = 0; i < m_numIIDs; ++i) - { - if (iid == m_pIIDs[i]) - { - return true; - } - } - return false; - } - - virtual void ClassSupports(const CryInterfaceID*& pIIDs, size_t& numIIDs) const - { - pIIDs = m_pIIDs; - numIIDs = m_numIIDs; - } -public: - virtual ICryUnknownPtr CreateClassInstance() const - { - AZStd::shared_ptr p = AZStd::make_shared(); - return cryinterface_cast (p); - } - - CFactory() - : m_numIIDs(0) - , m_pIIDs(0) - , m_regFactory() - { - static CryInterfaceID supportedIIDs[TL::Length < typename T::FullInterfaceList > ::value]; - CW::FillIIDs::Op(supportedIIDs); - m_pIIDs = &supportedIIDs[0]; - m_numIIDs = TL::Length::value; - new(&m_regFactory)SRegFactoryNode(this); - } - -protected: - CFactory(const CFactory&); - CFactory& operator =(const CFactory&); - - - size_t m_numIIDs; - CryInterfaceID* m_pIIDs; - SRegFactoryNode m_regFactory; -}; - -template -class CSingletonFactory - : public CFactory -{ -public: - CSingletonFactory() - : CFactory() - , m_csCreateClassInstance() - { - } - - virtual ICryUnknownPtr CreateClassInstance() const - { - CryAutoLock lock(m_csCreateClassInstance); - // override the allocator. These function static instances are being destroyed after the AZ alloctor has been deleted. - // On win, TerminateProcess() prevents these destructors from being called, but that is not the case on OSX. - static typename AZStd::aligned_storage,SingletonAllocator>), AZStd::alignment_of::value>::type m_storage; - static ICryUnknownPtr p = AZStd::allocate_shared(SingletonAllocator(AZStd::addressof(m_storage))); - return p; - } - - mutable CryCriticalSection m_csCreateClassInstance; - - struct SingletonAllocator - { - SingletonAllocator(void* ptr) : - m_data(ptr) - {} - void* allocate(size_t /*byteSize*/, size_t /*alignment*/, int /*flags*/ = 0) - { - return m_data; - } - void deallocate(void* /*ptr*/, size_t /*byteSize*/, size_t /*alignment*/) - { - // nothing to see here - } - void* m_data; - }; -}; - -#define _CRYFACTORY_DECLARE(implclassname) \ -private: \ - friend class CFactory; \ - static CFactory s_factory; - -#define _CRYFACTORY_DECLARE_SINGLETON(implclassname) \ -private: \ - friend class CFactory; \ - friend void* Get##implclassname##Factory(); \ - static CSingletonFactory s_factory; - -#define _IMPLEMENT_ICRYUNKNOWN() \ -public: \ - virtual ICryFactory* GetFactory() const \ - { \ - return &s_factory; \ - } \ - \ -protected: \ - virtual void* QueryInterface(const CryInterfaceID&iid) const \ - { \ - return CW::InterfaceCast::Op(this, iid); \ - } \ - \ - template \ - friend struct CW::Internal::CompositeQuery; \ - \ - virtual void* QueryComposite(const char* name) const \ - { \ - return CW::CompositeQuery::Op(*this, name); \ - } - -#define _ENFORCE_CRYFACTORY_USAGE(implclassname, cname, cidHigh, cidLow) \ -public: \ - static const char* GetCName() \ - { \ - return cname; \ - } \ - static const CryClassID& GetCID() \ - { \ - static const CryClassID cid = {(uint64) cidHigh##LL, (uint64) cidLow##LL}; \ - return cid; \ - } \ - static AZStd::shared_ptr CreateClassInstance() \ - { \ - ICryUnknownPtr p = s_factory.CreateClassInstance(); \ - return AZStd::shared_ptr(*static_cast*>(static_cast(&p))); \ - } \ - \ -protected: \ - implclassname(); \ - virtual ~implclassname(); - -#define _BEFRIEND_OPS() \ - _BEFRIEND_CRYINTERFACE_CAST() \ - _BEFRIEND_CRYCOMPOSITE_QUERY() \ - _BEFRIEND_MAKE_SHARED() - -#define CRYGENERATE_CLASS(implclassname, cname, cidHigh, cidLow) \ - _CRYFACTORY_DECLARE(implclassname) \ - _BEFRIEND_OPS() \ - _IMPLEMENT_ICRYUNKNOWN() \ - _ENFORCE_CRYFACTORY_USAGE(implclassname, cname, cidHigh, cidLow) - -#define CRYGENERATE_SINGLETONCLASS(implclassname, cname, cidHigh, cidLow) \ - _CRYFACTORY_DECLARE_SINGLETON(implclassname) \ - _BEFRIEND_OPS() \ - _IMPLEMENT_ICRYUNKNOWN() \ - _ENFORCE_CRYFACTORY_USAGE(implclassname, cname, cidHigh, cidLow) - - -#define CRYREGISTER_CLASS(implclassname) \ - CFactory implclassname::s_factory; - -#define DECLARE_CRYREGISTER_SINGLETON_CLASS(implclassname) \ - void* Get##implclassname##Factory(); - -#define CRYREGISTER_SINGLETON_CLASS(implclassname) \ - CSingletonFactory implclassname::s_factory; \ - void* Get##implclassname##Factory() { \ - return &implclassname::s_factory; \ - } - -#endif // CRYINCLUDE_CRYEXTENSION_IMPL_CLASSWEAVER_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/Conversion.h b/Code/CryEngine/CryCommon/CryExtension/Impl/Conversion.h deleted file mode 100644 index bd729f259e..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/Conversion.h +++ /dev/null @@ -1,109 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_CONVERSION_H -#define CRYINCLUDE_CRYEXTENSION_IMPL_CONVERSION_H -#pragma once - - -namespace TC -{ - //template - //struct Conversion - //{ - //private: - // typedef char y[1]; - // typedef char n[2]; - // static y& Test(U); - // static n& Test(...); - // static T MakeT(); - - //public: - // enum - // { - // exists = sizeof(Test(MakeT())) == sizeof(y), - // sameType = false - // }; - //}; - - //template - //struct Conversion - //{ - //public: - // enum - // { - // exists = true, - // sameType = true - // }; - //}; - - //template - //struct CheckInheritance - //{ - // enum - // { - // exists = Conversion::exists && !Conversion::sameType - // }; - //}; - - //template - //struct CheckStrictInheritance - //{ - // enum - // { - // exists = CheckInheritance::exists && !Conversion::sameType - // }; - //}; - - - template - struct SuperSubClass - { - private: - typedef char y[1]; - typedef char n[2]; - - template - static y& check(const volatile Derived&, T); - static n& check(const volatile Base&, int); - - struct C - { - operator const volatile Base&() const; - operator const volatile Derived&(); - }; - - static C getC(); - - public: - enum - { - exists = sizeof(check(getC(), 0)) == sizeof(y), - sameType = false - }; - }; - - template - struct SuperSubClass - { - enum - { - exists = true - }; - }; -} // namespace TC - -#endif // CRYINCLUDE_CRYEXTENSION_IMPL_CONVERSION_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/CryGUIDHelper.h b/Code/CryEngine/CryCommon/CryExtension/Impl/CryGUIDHelper.h deleted file mode 100644 index 53ee4352fc..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/CryGUIDHelper.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_CRYGUIDHELPER_H -#define CRYINCLUDE_CRYEXTENSION_IMPL_CRYGUIDHELPER_H -#pragma once - - -#include "../CryGUID.h" -#include "../../CryString.h" - - -namespace CryGUIDHelper -{ - string Print(const CryGUID& val) - { - char buf[39]; // sizeof("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") - - static const char hex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; - char* p = buf; - *p++ = '{'; - for (int i = 15; i >= 8; --i) - { - *p++ = hex[(unsigned char) ((val.hipart >> (i << 2)) & 0xF)]; - } - *p++ = '-'; - for (int i = 7; i >= 4; --i) - { - *p++ = hex[(unsigned char) ((val.hipart >> (i << 2)) & 0xF)]; - } - *p++ = '-'; - for (int i = 3; i >= 0; --i) - { - *p++ = hex[(unsigned char) ((val.hipart >> (i << 2)) & 0xF)]; - } - *p++ = '-'; - for (int i = 15; i >= 12; --i) - { - *p++ = hex[(unsigned char) ((val.lopart >> (i << 2)) & 0xF)]; - } - *p++ = '-'; - for (int i = 11; i >= 0; --i) - { - *p++ = hex[(unsigned char) ((val.lopart >> (i << 2)) & 0xF)]; - } - *p++ = '}'; - *p++ = '\0'; - - return string(buf); - } -} - - -#endif // CRYINCLUDE_CRYEXTENSION_IMPL_CRYGUIDHELPER_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/ICryFactoryRegistryImpl.h b/Code/CryEngine/CryCommon/CryExtension/Impl/ICryFactoryRegistryImpl.h deleted file mode 100644 index 051c33fc33..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/ICryFactoryRegistryImpl.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_ICRYFACTORYREGISTRYIMPL_H -#define CRYINCLUDE_CRYEXTENSION_IMPL_ICRYFACTORYREGISTRYIMPL_H -#pragma once - - -#include "../ICryFactoryRegistry.h" - - -struct SRegFactoryNode; - - -struct ICryFactoryRegistryCallback -{ - virtual void OnNotifyFactoryRegistered(ICryFactory* pFactory) = 0; - virtual void OnNotifyFactoryUnregistered(ICryFactory* pFactory) = 0; - -protected: - virtual ~ICryFactoryRegistryCallback() {} -}; - - -struct ICryFactoryRegistryImpl - : public ICryFactoryRegistry -{ - virtual ICryFactory* GetFactory(const char* cname) const = 0; - virtual ICryFactory* GetFactory(const CryClassID& cid) const = 0; - virtual void IterateFactories(const CryInterfaceID& iid, ICryFactory** pFactories, size_t& numFactories) const = 0; - - virtual void RegisterCallback(ICryFactoryRegistryCallback* pCallback) = 0; - virtual void UnregisterCallback(ICryFactoryRegistryCallback* pCallback) = 0; - - virtual void RegisterFactories(const SRegFactoryNode* pFactories) = 0; - virtual void UnregisterFactories(const SRegFactoryNode* pFactories) = 0; - - virtual void UnregisterFactory(ICryFactory* const pFactory) = 0; - -protected: - // prevent explicit destruction from client side (delete, shared_ptr, etc) - virtual ~ICryFactoryRegistryImpl() {} -}; - -#endif // CRYINCLUDE_CRYEXTENSION_IMPL_ICRYFACTORYREGISTRYIMPL_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/RegFactoryNode.h b/Code/CryEngine/CryCommon/CryExtension/Impl/RegFactoryNode.h deleted file mode 100644 index 8209ae9728..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/RegFactoryNode.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_IMPL_REGFACTORYNODE_H -#define CRYINCLUDE_CRYEXTENSION_IMPL_REGFACTORYNODE_H -#pragma once - -struct ICryFactory; -struct SRegFactoryNode; - -extern SRegFactoryNode* g_pHeadToRegFactories; - -struct SRegFactoryNode -{ - SRegFactoryNode() - { - } - - SRegFactoryNode(ICryFactory* pFactory) - : m_pFactory(pFactory) - , m_pNext(g_pHeadToRegFactories) - { - g_pHeadToRegFactories = this; - } - - static void* operator new(size_t, void* p) - { - return p; - } - - static void operator delete(void*, void*) - { - } - - ICryFactory* m_pFactory; - SRegFactoryNode* m_pNext; -}; - -#endif // CRYINCLUDE_CRYEXTENSION_IMPL_REGFACTORYNODE_H diff --git a/Code/CryEngine/CryCommon/CryExtension/Impl/TypeList.h b/Code/CryEngine/CryCommon/CryExtension/Impl/TypeList.h deleted file mode 100644 index 231283fc19..0000000000 --- a/Code/CryEngine/CryCommon/CryExtension/Impl/TypeList.h +++ /dev/null @@ -1,236 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYEXTENSION_TYPELIST_H -#define CRYINCLUDE_CRYEXTENSION_TYPELIST_H -#pragma once - - -namespace TL -{ - // typelist terminator - class NullType - { - }; - - - // structure for typelist generation - template - struct Typelist - { - typedef T Head; - typedef U Tail; - }; - - - // helper structure to automatically build typelists containing n types - template - < - typename T0 = NullType, typename T1 = NullType, typename T2 = NullType, typename T3 = NullType, typename T4 = NullType, - typename T5 = NullType, typename T6 = NullType, typename T7 = NullType, typename T8 = NullType, typename T9 = NullType, - typename T10 = NullType, typename T11 = NullType, typename T12 = NullType, typename T13 = NullType, typename T14 = NullType, - typename T15 = NullType, typename T16 = NullType, typename T17 = NullType, typename T18 = NullType, typename T19 = NullType - > - struct BuildTypelist - { - private: - typedef typename BuildTypelist::Result TailResult; - - public: - typedef Typelist Result; - }; - - template <> - struct BuildTypelist<> - { - typedef NullType Result; - }; - - // typelist operation : Length - template - struct Length; - - template <> - struct Length - { - enum - { - value = 0 - }; - }; - - template - struct Length > - { - enum - { - value = 1 + Length::value - }; - }; - - - // typelist operation : TypeAt - template - struct TypeAt; - - template - struct TypeAt, 0> - { - typedef Head Result; - }; - - template - struct TypeAt, index> - { - typedef typename TypeAt::Result Result; - }; - - - // typelist operation : IndexOf - template - struct IndexOf; - - template - struct IndexOf - { - enum - { - value = -1 - }; - }; - - template - struct IndexOf, T> - { - enum - { - value = 0 - }; - }; - - template - struct IndexOf, T> - { - private: - enum - { - temp = IndexOf::value - }; - public: - enum - { - value = temp == -1 ? -1 : 1 + temp - }; - }; - - - // typelist operation : Append - template - struct Append; - - template <> - struct Append - { - typedef NullType Result; - }; - - template - struct Append - { - typedef Typelist Result; - }; - - template - struct Append > - { - typedef Typelist Result; - }; - - template - struct Append, T> - { - typedef Typelist::Result> Result; - }; - - - // typelist operation : Erase - template - struct Erase; - - template - struct Erase - { - typedef NullType Result; - }; - - template - struct Erase, T> - { - typedef Tail Result; - }; - - template - struct Erase, T> - { - typedef Typelist::Result> Result; - }; - - - // typelist operation : Erase All - template - struct EraseAll; - - template - struct EraseAll - { - typedef NullType Result; - }; - - template - struct EraseAll, T> - { - typedef typename EraseAll::Result Result; - }; - - template - struct EraseAll, T> - { - typedef Typelist::Result> Result; - }; - - - // typelist operation : NoDuplicates - template - struct NoDuplicates; - - template <> - struct NoDuplicates - { - typedef NullType Result; - }; - - template - struct NoDuplicates > - { - private: - typedef typename NoDuplicates::Result L1; - typedef typename Erase::Result L2; - public: - typedef Typelist Result; - }; -} // namespace TL - -#endif // CRYINCLUDE_CRYEXTENSION_TYPELIST_H diff --git a/Code/CryEngine/CryCommon/CryPool/Allocator.h b/Code/CryEngine/CryCommon/CryPool/Allocator.h deleted file mode 100644 index cc751e68f1..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Allocator.h +++ /dev/null @@ -1,207 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYPOOL_ALLOCATOR_H -#define CRYINCLUDE_CRYPOOL_ALLOCATOR_H -#pragma once - - -namespace NCryPoolAlloc -{ - template - class CFirstFit - : public TPool - { - public: - ILINE CFirstFit() - { - } - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - //fastpath? - if (TPool::m_pEmpty && TPool::m_pEmpty->Available(Size, Align)) - { - TItem* pItem = TPool::Split(TPool::m_pEmpty, Size, Align); - if (!pItem) - { - return 0; - } - pItem->InUse(Align); - TPool::AllocatedMemory(pItem->MemSize()); - - //not fully occupied empty space? - TPool::m_pEmpty = pItem != TPool::m_pEmpty ? TPool::m_pEmpty : 0; - return TPool::Handle(pItem); - } - - TItem* pBestItem; - for (pBestItem = TPool::m_Items.First(); pBestItem; pBestItem = pBestItem->Next()) - { - if (pBestItem->Available(Size, Align)) // && (!pBestItem || pItem->MemSize()MemSize())) - { - break; - } - } - if (!pBestItem) - { - return 0; //out of mem - } - TItem* pItem = TPool::Split(pBestItem, Size, Align); - if (!pItem) //no free node - { - return 0; - } - pItem->InUse(Align); - TPool::AllocatedMemory(pItem->MemSize()); - - //not fully occupied empty space? - TPool::m_pEmpty = pItem != pBestItem ? pBestItem : 0; - return TPool::Handle(pItem); - } - template - ILINE bool Free(T Handle, bool ForceBoundsCheck = false) - { - return Handle ? TPool::Free(Handle, ForceBoundsCheck) : false; - } - }; - - template - class CWorstFit - : public TPool - { - public: - ILINE CWorstFit() - { - } - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - TItem* pBestItem = 0; - for (TItem* pItem = TPool::m_Items.First(); pItem; pItem = pItem->Next()) - { - if (pItem->IsFree() && (!pBestItem || pItem->MemSize() > pBestItem->MemSize())) - { - pBestItem = pItem; - } - } - if (!pBestItem || !pBestItem->Available(Size, Align)) - { - return 0; //out of mem - } - TItem* pItem = Split(pBestItem, Size, Align); - if (!pItem) //no free node - { - return 0; - } - pItem->InUse(Align); - AllocatedMemory(pItem->MemSize()); - return Handle(pItem); - } - }; - - template - class CBestFit - : public TPool - { - public: - ILINE CBestFit() - { - } - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - TItem* pBestItem = 0; - for (TItem* pItem = TPool::m_Items.First(); pItem; pItem = pItem->Next()) - { - if ((!pBestItem || pItem->MemSize() < pBestItem->MemSize()) && pItem->Available(Size, Align)) - { - if (pItem->MemSize() == Size) - { - pItem->InUse(Align); - AllocatedMemory(pItem->MemSize()); - return (T)Handle(pItem); - } - pBestItem = pItem; - } - } - if (!pBestItem) - { - return 0; //out of mem - } - TItem* pItem = Split(pBestItem, Size, Align); - if (!pItem) //no free node - { - return 0; - } - pItem->InUse(Align); - AllocatedMemory(pItem->MemSize()); - return (T)Handle(pItem); - } - }; - - - template - class CReallocator - : public TAllocator - { - public: - - template - ILINE bool Reallocate(T* pData, size_t Size, size_t Alignment) - { - //special cases - if (!Size) //just free? - { - TAllocator::Free(*pData); - *pData = 0; - return true; - } - - if (!*pData) //just alloc? - { - *pData = TAllocator::template Allocate(Size, Alignment); - return *pData != 0; - } - - //same size, nothing to do at all? - if (TAllocator::Item(*pData)->MemSize() == Size) - { - return true; - } - - if (TAllocator::ReSize(pData, Size)) - { - return true; - } - - T pNewData = TAllocator::template Allocate(Size, Alignment); - if (!pNewData) - { - return false; - } - memcpy(TAllocator::template Resolve(pNewData), - TAllocator::template Resolve(*pData), min(TAllocator::Item(*pData)->MemSize(), Size)); - TAllocator::template Free(*pData); - *pData = pNewData; - return true; - } - }; -} - - -#endif // CRYINCLUDE_CRYPOOL_ALLOCATOR_H - diff --git a/Code/CryEngine/CryCommon/CryPool/Container.h b/Code/CryEngine/CryCommon/CryPool/Container.h deleted file mode 100644 index 82ea2735bc..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Container.h +++ /dev/null @@ -1,655 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYPOOL_CONTAINER_H -#define CRYINCLUDE_CRYPOOL_CONTAINER_H -#pragma once - - -namespace NCryPoolAlloc -{ - template - class CPool - : public CMemoryStatic - { - class CPoolNode; - class CPoolNode - : public CListItem - { - }; - CList m_List; - public: - ILINE CPool() - { - CPoolNode* pPrev = 0; - CPoolNode* pNode = 0; - for (size_t a = 1; a < TElementCount; a++) //skip first element as it would be counted as zero ptr - { - uint8* pData = &CMemoryStatic::Data()[a * sizeof(TElement)]; - pNode = reinterpret_cast(pData); - pNode->Prev(pPrev); - if (pPrev) - { - pPrev->Next(pNode); - } - else - { - m_List.First(pNode); - } - pPrev = pNode; - // m_List.AddLast(pNode); - } - if (pPrev) - { - pPrev->Next(0); - m_List.Last(pPrev); - } - } - ILINE uint8* Allocate([[maybe_unused]] size_t Size, [[maybe_unused]] size_t Align = 1) - { - CPoolNode* pNode = m_List.PopFirst(); - return reinterpret_cast(pNode); - } - - template - ILINE void Free(T* pData) - { - if (pData) - { - CPoolNode* pNode = reinterpret_cast(pData); - m_List.AddLast(pNode); - } - } - - ILINE TElement& operator[](uint32 Idx) - { - uint8* pData = &CMemoryStatic::Data()[Idx * sizeof(TElement)]; - return *reinterpret_cast(pData); - } - - ILINE const TElement& operator[](uint32 Idx) const - { - const uint8* pData = &CMemoryStatic::Data()[Idx * sizeof(TElement)]; - return *reinterpret_cast(pData); - } - }; - - template - class CInPlace - : public TMemory - { - protected: - CList m_Items; - size_t m_Allocated; - CListItemInPlace* m_pEmpty; - - - ILINE void AllocatedMemory(size_t S) - { - m_Allocated += S + sizeof(CListItemInPlace); - } - ILINE void FreedMemory(size_t S) - { - m_Allocated -= S + sizeof(CListItemInPlace); - } - ILINE void Stack(CListItemInPlace* pItem) - { - } - public: - ILINE CInPlace() - : m_Allocated(0) - { - } - - ILINE void InitMem(const size_t S = 0, uint8* pData = 0) - { - TMemory::InitMem(S, pData); - if (!TMemory::MemSize()) - { - return; - } - pData = TMemory::Data(); - CListItemInPlace* pFirst = reinterpret_cast(pData); - CListItemInPlace* pFree = pFirst + 1; - CListItemInPlace* pLast = reinterpret_cast(pData + TMemory::MemSize()) - 1; - m_Items.~CList(); - new (&m_Items)CList(); - m_Items.AddLast(pFirst); - m_Items.AddLast(pFree); - m_Items.AddLast(pLast); - - pFirst->InUse(0); //static first item - pFree->Free(); - pLast->InUse(0); //static last item - m_pEmpty = pFree; - m_Allocated = 0; - } - - ILINE size_t FragmentCount() const - { - return m_Items.Count(); - } - - ILINE CListItemInPlace* Split(CListItemInPlace* pItem, size_t Size, size_t Align) - { - size_t Offset = reinterpret_cast(pItem->Data()); - Offset += pItem->MemSize(); //ptr to end - Offset -= Size; //minus size - Size += Offset & (Align - 1); //adjust size to fit required alignment - Offset -= Offset & (Align - 1); - size_t TSize = sizeof(CListItemInPlace); - Offset -= TSize; //header - - if (Offset <= reinterpret_cast(pItem + 1)) //not enough space for splitting? - { - return pItem; - } - - CListItemInPlace* pItemNext = reinterpret_cast(Offset); - - const size_t Offset2 = reinterpret_cast(pItemNext->Data()); - CPA_ASSERT(!(Offset2 & (Align - 1))); - m_Items.AddBehind(pItemNext, pItem); - //pItemNext->Prev(pItem); - //pItemNext->Next(pItem->Next()); - - // if(pItem->Next()) - // pItem->Next()->Prev(pItemNext); - - // pItem->Next(pItemNext); - pItemNext->Free(); - return pItemNext; - } - - ILINE void Merge(CListItemInPlace* pItem) - { - //merge with next if possible - CListItemInPlace* pItemNext = pItem->Next(); - if (pItemNext->IsFree()) - { - if (m_pEmpty == pItemNext) - { - m_pEmpty = pItem; - } - m_Items.Remove(pItemNext); - //pItem->Next(pItemNext->Next()); - //pItem->Next()->Prev(pItem); - } - //merge with prev if possible - CListItemInPlace* pItemPrev = pItem->Prev(); - if (pItemPrev->IsFree()) - { - if (m_pEmpty == pItem) - { - m_pEmpty = pItemPrev; - } - m_Items.Remove(pItem); - //pItemPrev->Next(pItem->Next()); - //pItem->Next()->Prev(pItemPrev); - pItem = pItemPrev; - } - } - template - ILINE T Resolve(void* rItem) const - { - return reinterpret_cast(rItem); - } - - template - ILINE size_t Size(const T* pData) const - { - const CListItemInPlace* pItem = Item(pData); - return pItem->MemSize(); - } - - bool InBounds(const void* pData, const bool Check) const - { - return !Check || ( - reinterpret_cast(pData) >= reinterpret_cast(TMemory::Data()) && - reinterpret_cast(pData) < reinterpret_cast(TMemory::Data()) + TMemory::MemSize()); - } - - template - ILINE bool Free(T* pData, bool ForceBoundsCheck = false) - { - if (pData && InBounds(pData, BoundsCheck | ForceBoundsCheck)) - { - CListItemInPlace* pItem = Item(pData); - FreedMemory(pItem->MemSize()); - pItem->Free(); - Merge(pItem); - return true; - } - return false; - } - - ILINE bool Beat(){return false; }//dummy beat in case no defragmentator is wraping - ILINE size_t MemFree() const{return TMemory::MemSize() - m_Allocated; } - ILINE size_t MemSize() const{return TMemory::MemSize(); } - - ILINE uint8* Handle(CListItemInPlace* pItem) const - { - return pItem->Data(); - } - template - ILINE CListItemInPlace* Item(T* pData) - { - return reinterpret_cast(pData) - 1; - } - template - ILINE const CListItemInPlace* Item(const T* pData) const - { - return reinterpret_cast(pData) - 1; - } - ILINE static bool Defragmentable(){return false; } - - template - ILINE bool ReSize(T* pData, size_t SizeNew) - { - //special cases - CListItemInPlace* pItem = Item(*pData); - const size_t SizeOld = pItem->MemSize(); - - //reduction - if (SizeOld > SizeNew) - { - if (pItem->Next()->IsFree()) - { - CListItemInPlace* pNextNext = pItem->Next()->Next(); - size_t Offset = reinterpret_cast(pItem->Data()); - Offset += SizeNew; //Offset to next - CListItemInPlace* pItemNext = reinterpret_cast(Offset); - pItem->Next(pItemNext); - pNextNext->Prev(pItemNext); - pItemNext->Prev(pItem); - pItemNext->Next(pNextNext); - pItemNext->Free(); - return true; - } - - if (SizeOld - SizeNew <= sizeof(CListItemInPlace)) - { - return true; //header is bigger than the amount of freed memory - } - //split - size_t Offset = reinterpret_cast(pItem->Data()); - Offset += SizeNew; //Offset to next - CListItemInPlace* pItemNext = reinterpret_cast(Offset); - m_Items.AddBehind(pItemNext, pItem); - pItemNext->Free(); - return true; - } - - //SizeOldNext(); - CListItemInPlace* pNextNext = pNext->Next(); - const size_t SizeNext = pNext->IsFree() ? pNext->MemSize() + sizeof(CListItemInPlace) : 0; - if (SizeNew <= SizeNext + SizeOld) - { - if (SizeNew + sizeof(CListItemInPlace) + 1 < SizeNext + SizeOld) - { - size_t Offset = reinterpret_cast(pItem->Data()); - Offset += SizeNew; //Offset to next - CListItemInPlace* pItemNext = reinterpret_cast(Offset); - pItem->Next(pItemNext); - pNextNext->Prev(pItemNext); - pItemNext->Prev(pItem); - pItemNext->Next(pNextNext); - pItemNext->Free(); - } - else - { - pItem->Next(pNextNext); - pNextNext->Prev(pItem); - } - return true; - } - return false; //no further in-place realloc possible - } - }; - - template - class CReferenced - : public TMemory - { - typedef CPool tdNodePool; - - protected: - tdNodePool m_NodePool; - CList m_Items; - size_t m_Allocated; - CListItemReference* m_pEmpty; - - ILINE void AllocatedMemory(size_t S) - { - m_Allocated += S; - } - ILINE void FreedMemory(size_t S) - { - m_Allocated -= S; - } - ILINE void Stack(CListItemReference* pItem) - { - m_Items.Validate(pItem); - CListItemReference* pItem2 = 0; - CListItemReference* pNext = pItem->Next(); - uint8* pData = pItem->Data(pNext->Align()); - if (pData != pItem->Data()) //needs splitting 'cause of alignment? - { - pItem2 = reinterpret_cast(m_NodePool.Allocate(1, 1)); - if (!pItem2) //no free node found for splitting? - { - return; //failed to stack -> return - } - } - - memmove(pData, pNext->Data(), pNext->MemSize()); - - if (pItem2) //was not aligned? - { - //then keep the current ITem - const size_t SizeItem = pItem->MemSize(); - const size_t SizeNext = pNext->MemSize(); - m_Items.AddBehind(pItem2, pNext); - pItem2->Data(pData + SizeNext); - pNext->Data(pData); - pItem2->MemSize(pItem2->Next()->Data() - pItem2->Data()); - pNext->MemSize(SizeNext); - pItem->MemSize(pNext->Data() - pItem->Data()); - m_Items.Validate(pItem); - m_Items.Validate(pItem2); - m_Items.Validate(pNext); - } - else - { - const size_t SizeItem = pItem->MemSize(); - const size_t SizeNext = pNext->MemSize(); - m_Items.Remove(pItem); - m_Items.AddBehind(pItem, pNext); - pItem->Data(pNext->Data()); - pNext->Data(pData); - pNext->MemSize(SizeItem); - pItem->MemSize(SizeNext); - m_Items.Validate(pItem); - m_Items.Validate(pNext); - } - } - public: - ILINE CReferenced() - : m_Allocated(0) - { - } - - ILINE void InitMem(const size_t S = 0, uint8* pData = 0) - { - TMemory::InitMem(S, pData); - if (!TMemory::MemSize()) - { - return; - } - pData = TMemory::Data(); - CListItemReference* pItem = reinterpret_cast(m_NodePool.Allocate(1, 1)); - CListItemReference* pLast = reinterpret_cast(m_NodePool.Allocate(1, 1)); - m_Items.AddFirst(pItem); - m_Items.AddLast(pLast); - pLast->Init(pData + TMemory::MemSize(), 0, pItem, 0); - pLast->InUse(0); - pItem->Init(pData, TMemory::MemSize(), 0, pLast); - pItem->Free(); - m_pEmpty = pItem; - m_Allocated = 0; - } - - ILINE size_t FragmentCount() const - { - return m_Items.Count(); - } - - ILINE CListItemReference* Split(CListItemReference* pItem, size_t Size, size_t Align) - { - size_t Offset = reinterpret_cast(pItem->Data()); - if (!(Offset & (Align - 1))) //perfectly aligned? - { - if (pItem->MemSize() != Size) //not perfectly fitting? - { //then split - CListItemReference* pItemPrev = reinterpret_cast(m_NodePool.Allocate(1, 1)); - if (!pItemPrev) - { - return 0; - } - const size_t OrgSize = pItem->MemSize(); - m_Items.AddBefore(pItemPrev, pItem); - pItemPrev->Data(pItem->Data()); - pItem->Data(pItem->Data() + Size); - pItem->MemSize(OrgSize - Size); - pItemPrev->MemSize(Size); - pItem = pItemPrev; - } - return pItem; - } - - //not aligned to block start - //then lets try to align to block end - Offset += pItem->MemSize(); //ptr to end - Offset -= Size; //minus size - if (!(Offset & (Align - 1))) //perfectly aligned? - { - CListItemReference* pItemPrev = reinterpret_cast(m_NodePool.Allocate(1, 1)); - if (!pItemPrev) - { - return 0; - } - const size_t OrgSize = pItem->MemSize(); - m_Items.AddBefore(pItemPrev, pItem); - pItemPrev->Data(pItem->Data()); - pItem->Data(reinterpret_cast(Offset)); - pItemPrev->MemSize(OrgSize - Size); - pItem->MemSize(Size); - pItemPrev->Free(); - return pItem; - } - //last resort, fragment it into 3 parts - - //Size +=Offset&(Align-1); //adjust size to fit required alignment - Offset -= Offset & (Align - 1); - - CListItemReference* pItemPrev = reinterpret_cast(m_NodePool.Allocate(1, 1)); - CListItemReference* pItemNext = reinterpret_cast(m_NodePool.Allocate(1, 1)); - if (!pItemPrev || !pItemNext) - { - return 0; - } - const size_t OrgSize = pItem->MemSize(); - - m_Items.AddBefore(pItemPrev, pItem); - m_Items.AddBehind(pItemNext, pItem); - - pItemPrev->Data(pItem->Data()); - pItem->Data(reinterpret_cast(Offset)); - pItemNext->Data(pItem->Data() + Size); - pItemPrev->MemSize(pItem->Data() - pItemPrev->Data()); - pItemNext->MemSize(OrgSize - pItemPrev->MemSize() - Size); - pItem->MemSize(Size); - - pItemPrev->Free(); - pItemNext->Free(); - return pItem; - } - - ILINE void Merge(CListItemReference* pItem) - { - m_Items.Validate(pItem); - - //merge with next if possible - CListItemReference* pItemNext = pItem->Next(); - if (pItemNext && pItemNext->IsFree()) - { - if (m_pEmpty == pItemNext) - { - m_pEmpty = pItem; - } - const size_t OrgSize = pItem->MemSize(); - const size_t NextSize = pItemNext->MemSize(); - m_Items.Remove(pItemNext); - pItem->MemSize(OrgSize + NextSize); - m_NodePool.Free(pItemNext); - } - //merge with prev if possible - CListItemReference* pItemPrev = pItem->Prev(); - if (pItemPrev && pItemPrev->IsFree()) - { - if (m_pEmpty == pItem) - { - m_pEmpty = pItemPrev; - } - const size_t OrgSize = pItem->MemSize(); - const size_t PrevSize = pItemPrev->MemSize(); - m_Items.Remove(pItem); - pItemPrev->MemSize(PrevSize + OrgSize); - m_NodePool.Free(pItem); - } - } - - template - ILINE T Resolve(const uint32 ID) - { - CPA_ASSERT(ID); //0 is invalid - return reinterpret_cast(Item(ID)->Data()); - } - - ILINE uint32 AddressToHandle(void* pData) - { - for (CListItemReference* pItem = m_Items.First(); pItem; pItem = pItem->Next()) - { - if (pItem->Data() == pData) - { - return Handle(pItem); - } - } - return 0; - } - - template - ILINE size_t Size(T ID) const - { - CPA_ASSERT(ID); //0 is invalid - return Item(ID)->MemSize(); - } - template - bool InBounds([[maybe_unused]] T ID, [[maybe_unused]] const bool Check) const - { - //boundscheck doesn't work for Referenced containers - return true; - } - - template - ILINE bool Free(T ID, bool ForceBoundsCheck = false) - { - IF (!ID, false) - { - return true; - } - IF (!InBounds(ID, BoundsCheck | ForceBoundsCheck), false) - { - return false; - } - - CListItemReference* pItem = Item(ID); - FreedMemory(pItem->MemSize()); - pItem->Free(); - Merge(pItem); - return true; - } - - ILINE bool Beat(){return false; }//dummy beat in case no defragmentator is wraping - - ILINE size_t MemFree() const{return TMemory::MemSize() - m_Allocated; } - - ILINE size_t MemSize() const{return TMemory::MemSize(); } - - ILINE uint32 Handle(CListItemReference* pItem) const - { - return static_cast(pItem - &m_NodePool[0]); - } - ILINE CListItemReference* Item(uint32 ID) - { - return &m_NodePool[ID]; - } - ILINE const CListItemReference* Item(uint32 ID) const - { - return &m_NodePool[ID]; - } - ILINE static bool Defragmentable(){return true; } - - - - template - ILINE bool ReSize(T* pData, size_t SizeNew) - { - CListItemReference* pItem = Item(*pData); - const size_t SizeOld = pItem->MemSize(); - - //reduction - if (SizeOld > SizeNew) - { - if (pItem->Next()->IsFree()) - { - CListItemReference* pNext = pItem->Next(); - const size_t NextSize = pNext->MemSize(); - pNext->Data(pNext->Data() + SizeNew - SizeOld); - pNext->MemSize(NextSize - SizeNew + SizeOld); - pItem->MemSize(SizeNew); - return true; - } - - //split - CListItemReference* pItemNext = reinterpret_cast(m_NodePool.Allocate(1, 1)); - m_Items.AddBehind(pItemNext, pItem); - pItemNext->Data(pItem->Data() + SizeNew); - pItem->MemSize(SizeNew); - pItemNext->MemSize(SizeOld - SizeNew); - pItemNext->Free(); - return true; - } - - //SizeOldNext(); - const size_t SizeNext = pNext->IsFree() ? pNext->MemSize() : 0; - if (SizeNew <= SizeNext + SizeOld) - { - if (SizeNew == SizeNext + SizeOld) - { - m_Items.Remove(pNext); - m_NodePool.Free(pNext); - } - else - { - pNext->Data(pNext->Data() + SizeNew - SizeOld); - pNext->MemSize(SizeNext - SizeNew + SizeOld); - } - pItem->MemSize(SizeNew); - return true; - } - return false; //no further in-place realloc possible - } - }; -} - - - - - - - -#endif // CRYINCLUDE_CRYPOOL_CONTAINER_H - diff --git a/Code/CryEngine/CryCommon/CryPool/Defrag.h b/Code/CryEngine/CryCommon/CryPool/Defrag.h deleted file mode 100644 index 51fe6fabfb..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Defrag.h +++ /dev/null @@ -1,65 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYPOOL_DEFRAG_H -#define CRYINCLUDE_CRYPOOL_DEFRAG_H -#pragma once - - -namespace NCryPoolAlloc -{ - template - class CDefragStacked - : public T - { - template - ILINE bool DefragElement(TItem* pItem) - { - T::m_Items.Validate(); - if (pItem) - { - for (; pItem->Next(); pItem = pItem->Next()) - { - if (!pItem->IsFree()) - { - continue; - } - if (pItem->Next()->Locked()) - { - continue; - } - if (!pItem->Available(pItem->Next()->Align(), pItem->Next()->Align())) - { - continue; - } - T::m_Items.Validate(pItem); - Stack(pItem); - T::m_Items.Validate(pItem); - Merge(pItem); - T::m_Items.Validate(); - return true; - } - } - return false; - } - public: - ILINE bool Beat() - { - return T::Defragmentable() && DefragElement(T::m_Items.First()); - }; - }; -} - - -#endif // CRYINCLUDE_CRYPOOL_DEFRAG_H - diff --git a/Code/CryEngine/CryCommon/CryPool/Fallback.h b/Code/CryEngine/CryCommon/CryPool/Fallback.h deleted file mode 100644 index 4a2babce1a..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Fallback.h +++ /dev/null @@ -1,81 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYPOOL_FALLBACK_H -#define CRYINCLUDE_CRYPOOL_FALLBACK_H -#pragma once - - -namespace NCryPoolAlloc -{ - enum EFallbackMode - { - EFM_DISABLED, - EFM_ENABLED, - EFM_ALWAYS - }; - template - class CFallback - : public TAllocator - { - EFallbackMode m_Fallback; - public: - ILINE CFallback() - : m_Fallback(EFM_DISABLED) - { - } - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - if (EFM_ALWAYS == m_Fallback) - { - return reinterpret_cast(CPA_ALLOC(Align, Size)); - } - T pRet = TAllocator::template Allocate(Size, Align); - if (!pRet && EFM_ENABLED == m_Fallback) - { - return reinterpret_cast(CPA_ALLOC(Align, Size)); - } - return pRet; - } - - template - ILINE bool Free(T Handle) - { - if (!Handle) - { - return true; - } - if (EFM_ALWAYS == m_Fallback) - { - CPA_FREE(Handle); - return true; - } - - if (EFM_ENABLED == m_Fallback && TAllocator::InBounds(Handle, true)) - { - CPA_FREE(Handle); - return true; - } - return TAllocator::template Free(Handle); - } - - void FallbackMode(EFallbackMode M){m_Fallback = M; } - EFallbackMode FallbaclMode() const{return m_Fallback; } - }; -} - - -#endif // CRYINCLUDE_CRYPOOL_FALLBACK_H - diff --git a/Code/CryEngine/CryCommon/CryPool/Inspector.h b/Code/CryEngine/CryCommon/CryPool/Inspector.h deleted file mode 100644 index 1d16095828..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Inspector.h +++ /dev/null @@ -1,203 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYPOOL_INSPECTOR_H -#define CRYINCLUDE_CRYPOOL_INSPECTOR_H -#pragma once - - -namespace NCryPoolAlloc -{ - template - class CInspector - : public TAllocator - { - enum - { - EITableSize = 30 - }; - size_t m_Allocations[EITableSize]; - size_t m_Alignment[EITableSize]; - char m_LogFileName[1024]; - size_t m_AllocCount; - size_t m_FreeCount; - size_t m_ResizeCount; - size_t m_FailAllocCount; - size_t m_FailFreeCount; - size_t m_FailResizeCount; - - void WriteOut(const char* pFileName, uint32 Stack, const char* pFormat, ...) const - { - /* - if(!pFileName) - { - if(!*m_LogFileName) - return; - pFileName = m_LogFileName; - } - FILE* File = fopen(pFileName,"a"); - if(File) - { - - char Buffer[1024]; - for(uint32 a=0;a>= 1; - while (C) - { - Count++; - C >>= 1; - } - return Count >= EITableSize ? EITableSize - 1 : Count; - } - public: - CInspector() - { - for (size_t a = 0; a < EITableSize; a++) - { - m_Allocations[a] = m_Alignment[a] = 0; - } - - m_LogFileName[0] = 0; - m_AllocCount = 0; - m_FreeCount = 0; - m_ResizeCount = 0; - m_FailAllocCount = 0; - m_FailFreeCount = 0; - m_FailResizeCount = 0; - } - - bool LogFileName(const char* pFileName) - { - const size_t Size = strlen(pFileName) + 1; - if (Size > sizeof(m_LogFileName)) - { - m_LogFileName[0] = 0; - return false; - } - memcpy(m_LogFileName, pFileName, Size); - WriteOut(0, "[log start]\n"); - return true; - } - void SaveStats(const char* pFileName) const - { - WriteOut(pFileName, 0, "stats:\n"); - - WriteOut(pFileName, 1, "Counter calls|fails\n"); - WriteOut(pFileName, 2, "Alloc: %6d|%6d\n", m_AllocCount, m_FailAllocCount); - WriteOut(pFileName, 2, "Free: %6d|%6d\n", m_FreeCount, m_FailFreeCount); - WriteOut(pFileName, 2, "Resize:%6d|%6d\n", m_ResizeCount, m_FailResizeCount); - - WriteOut(pFileName, 1, "Allocations:\n"); - for (size_t a = 0; a < EITableSize; a++) - { - WriteOut(pFileName, 2, "%9dByte: %8d\n", 1 << a, m_Allocations[a]); - } - - WriteOut(pFileName, 1, "Alignment:\n"); - for (size_t a = 0; a < EITableSize; a++) - { - WriteOut(pFileName, 2, "%9dByte: %8d\n", 1 << a, m_Alignment[a]); - } - } - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - m_AllocCount++; - m_Allocations[Bit(Size)]++; - m_Alignment[Bit(Align)]++; - T pData = TAllocator::template Allocate(Size, Align); - WriteOut(0, 0, "[A|%d|%d|%d]", (int)pData, Size, Align); - if (!pData) - { - m_FailAllocCount++; - WriteOut(0, 0, "[failed]", Size, Align); - } - return pData; - } - - - template - ILINE bool Free(T pData, bool ForceBoundsCheck = false) - { - m_FreeCount++; - const bool Ret = TAllocator::Free(pData, ForceBoundsCheck); - WriteOut(0, 0, "[F|%d|%d|%d]", (int)pData, (int)ForceBoundsCheck, (int)Ret); - m_FailFreeCount += !Ret; - return Ret; - } - //template - //ILINE bool Free(T pData) - // { - // m_FreeCount++; - // const bool Ret = TAllocator::Free(pData); - // WriteOut(0,0,"[F|%d|%d|%d]",(int)pData,(int)-1,(int)Ret); - // m_FailFreeCount+=!Ret; - // return Ret; - // } - - template - ILINE bool Resize(T** pData, size_t Size, size_t Alignment) - { - m_ResizeCount++; - const bool Ret = TAllocator::Resize(pData, Size, Alignment); - WriteOut(0, 0, "[R|%d|%d|%d]", (int)*pData, (int)-1, (int)Ret); - m_FailResizeCount += !Ret; - return Ret; - } - - template - ILINE size_t FindBiggest(const T* pItem) - { - size_t Biggest = 0; - while (pItem) - { - if (pItem->IsFree() && pItem->MemSize() > Biggest) - { - Biggest = pItem->MemSize(); - } - pItem = pItem->Next(); - } - return Biggest; - } - - ILINE size_t BiggestFreeBlock() - { - return FindBiggest(TAllocator::m_Items.First()); - } - - ILINE uint8* FirstItem() - { - return TAllocator::m_Items.First()->Data(); - } - }; -} - - - - -#endif // CRYINCLUDE_CRYPOOL_INSPECTOR_H - diff --git a/Code/CryEngine/CryCommon/CryPool/List.h b/Code/CryEngine/CryCommon/CryPool/List.h deleted file mode 100644 index 5c4588d40c..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/List.h +++ /dev/null @@ -1,366 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYPOOL_LIST_H -#define CRYINCLUDE_CRYPOOL_LIST_H -#pragma once - -namespace NCryPoolAlloc -{ - class CListItemInPlace; - class CListItemReference; - - template - class CListItem - { - TItem* m_pPrev; - TItem* m_pNext; - public: - - ILINE TItem* Prev(){return m_pPrev; } - ILINE TItem* Next(){return m_pNext; } - ILINE const TItem* Prev() const{return m_pPrev; } - ILINE const TItem* Next() const{return m_pNext; } - ILINE void Prev(TItem* pPrev){ m_pPrev = pPrev; } - ILINE void Next(TItem* pNext){ m_pNext = pNext; } - - //debugging - void Validate(); - }; - - template - class CListItemFlagged - : public CListItem - { - enum - { - ELIF_INUSE = (1 << 0), - ELIF_LOCKED = (1 << 1), - }; - uint32 m_Flags : 8; - uint32 m_Align : 24; - public: - ILINE CListItemFlagged() - : m_Flags(0) - { - } - ILINE bool IsFree() const{return (m_Flags & ELIF_INUSE) != ELIF_INUSE; } - ILINE void Free(){m_Flags &= ~ELIF_INUSE; } - ILINE void InUse(uint32 A){m_Flags |= ELIF_INUSE; m_Align = A; } - ILINE bool Locked() const{return ELIF_LOCKED == (m_Flags & ELIF_LOCKED); } - ILINE void Lock(){m_Flags |= ELIF_LOCKED; } - ILINE void Unlock(){m_Flags &= ~ELIF_LOCKED; } - ILINE uint32 Align() const{return m_Align; } - }; - - class CListItemInPlace - : public CListItemFlagged - { - public: - ILINE void Init([[maybe_unused]] uint8* pData, [[maybe_unused]] size_t Size, CListItemInPlace* pPrev, CListItemInPlace* pNext) - { - Prev(pPrev); - Next(pNext); - CPA_ASSERT(Size == MemSize()); - } - - ILINE bool Available(size_t Size, size_t Align) const - { - size_t Offset = reinterpret_cast(Data()); - if (Offset & (Align - 1)) //not aligned? - { - Size += sizeof(CListItemInPlace) + Align - 1; //then an intermedian node needs to fit - } - return Size <= MemSize() && IsFree(); - } - ILINE uint8* Data(){return reinterpret_cast(this) + sizeof(CListItemInPlace); } - ILINE const uint8* Data() const{return reinterpret_cast(this) + sizeof(CListItemInPlace); } - ILINE size_t MemSize() const - { - const uint8* pNext = reinterpret_cast(Next()); - const uint8* pThis = reinterpret_cast(this); - const size_t ESize = sizeof(CListItemInPlace); - size_t Delta = pNext - pThis; - Delta -= ESize; - return Delta; - } - }; - - class CListItemReference - : public CListItemFlagged - { - uint8* m_pData; - // size_t m_Size; - public: - ILINE void Init(uint8* pData, size_t Size, CListItemReference* pPrev, CListItemReference* pNext) - { - Data(pData); - Prev(pPrev); - Next(pNext); - MemSize(Size); - } - ILINE bool Available(size_t Size, size_t Align) const - { - size_t Offset = reinterpret_cast(Data()); - if ((Offset & (Align - 1))) - { - Size += Align - (Offset & (Align - 1)); - } - return Size <= MemSize() && IsFree(); - } - ILINE void Data(uint8* pData){m_pData = pData; } - ILINE uint8* Data(size_t Align) - { - Align--; - size_t Offset = reinterpret_cast(m_pData); - Offset = (Offset + Align) & ~Align; - return reinterpret_cast(Offset); - } - ILINE uint8* Data(){return m_pData; } - ILINE const uint8* Data() const{return m_pData; } - ILINE void MemSize([[maybe_unused]] size_t Size) { } - ILINE size_t MemSize() const - { - const size_t T = reinterpret_cast(Data()); - const size_t N = Next() ? reinterpret_cast(Next()->Data()) : T; - return N - T; - } - //ILINE void MemSize(size_t Size){m_Size=Size;} - //ILINE size_t MemSize()const{return m_Size;} - }; - - template - class CList - { - TItem* m_pFirst; - TItem* m_pLast; - size_t m_Count; - public: - ILINE CList() - : m_pFirst(0) - , m_pLast(0) - , m_Count(0) - { - } - - ILINE void First(TItem* pItem){m_pFirst = pItem; } - ILINE TItem* First(){return m_pFirst; } - ILINE void Last(TItem* pItem){m_pLast = pItem; } - ILINE TItem* Last(){return m_pLast; } - ILINE bool Empty() const{return m_pFirst == 0; } - - ILINE TItem* PopFirst() - { - Validate(); - - if (!m_pFirst) - { - return 0; - } - - TItem* pRet = m_pFirst; - - m_pFirst = m_pFirst->Next(); - - if (m_pFirst) //if any element exists - { - m_pFirst->Prev(0); //set prev ptr of this element to 0 - } - else - { - m_pLast = 0; //set ptr to last element to 0 if ptr to first is zero as well - } - Validate(); - m_Count--; - return pRet; - } - - ILINE TItem* PopLast() - { - Validate(); - - if (!m_pLast) - { - return 0; - } - - TItem* pRet = m_pLast; - - m_pLast = m_pLast->Prev(); - - if (m_pLast) //if any element exists - { - m_pLast->Next(0); //set prev ptr of this element to 0 - } - else - { - m_pFirst = 0; //set ptr to last element to 0 if ptr to first is zero as well - } - Validate(); - m_Count--; - return pRet; - } - - ILINE void AddFirst(TItem* pItem) - { - CPA_ASSERT(pItem); //ERROR AddFirst got 0 pointer - - Validate(); - - pItem->Prev(0); - pItem->Next(m_pFirst); - if (!m_pFirst) - { - m_pLast = pItem; - } - else - { - m_pFirst->Prev(pItem); - } - m_pFirst = pItem; - - m_Count++; - Validate(); - } - - ILINE void AddLast(TItem* pItem) - { - CPA_ASSERT(pItem); //ERROR AddLast got 0 pointer - - Validate(); - - pItem->Prev(m_pLast); - pItem->Next(0); - if (!m_pLast) - { - m_pFirst = pItem; - } - else - { - m_pLast->Next(pItem); - } - m_pLast = pItem; - - m_Count++; - Validate(); - } - ILINE void AddBefore(TItem* pItem, TItem* pItemSuccessor) - { - CPA_ASSERT(pItem); - CPA_ASSERT(pItemSuccessor); - - Validate(); - - pItem->Next(pItemSuccessor); - pItem->Prev(pItemSuccessor->Prev()); - pItemSuccessor->Prev(pItem); - - if (pItemSuccessor == m_pFirst) - { - m_pFirst = pItem; - } - else - { - pItem->Prev()->Next(pItem); - } - - m_Count++; - Validate(); - } - ILINE void AddBehind(TItem* pItem, TItem* pItemPredecessor) - { - CPA_ASSERT(pItem); - CPA_ASSERT(pItemPredecessor); - - Validate(); - - pItem->Next(pItemPredecessor->Next()); - pItem->Prev(pItemPredecessor); - pItemPredecessor->Next(pItem); - - if (pItemPredecessor == m_pLast) - { - m_pLast = pItem; - } - else - { - pItem->Next()->Prev(pItem); - } - - m_Count++; - Validate(); - } - - ILINE void Remove(TItem* pItem) - { - CPA_ASSERT(pItem); //ERROR releasing empty item - - if (pItem == m_pFirst) - { - PopFirst(); - return; - } - if (pItem == m_pLast) - { - PopLast(); - return; - } - - Validate(pItem); - - pItem->Prev()->Next(pItem->Next()); - pItem->Next()->Prev(pItem->Prev()); - - m_Count--; - Validate(); - } - - //debug - ILINE void Validate(TItem* pReferenceItem = 0) - { - if (!VALIDATE) - { - return; - } - - //one-sided empty? - CPA_ASSERT((!First() && !Last()) || (First() && Last())); //ERROR validating item-list, just one end is 0 - - // endles linking? - TItem* pPrev = 0; - TItem* pItem = First(); - while (pItem) - { - if (pReferenceItem == pItem) - { - pReferenceItem = 0; - } - CPA_ASSERT(pPrev == pItem->Prev()); //ERROR validating item-list, endless linking NULL - pPrev = pItem; - pItem = pItem->Next(); - } - - CPA_ASSERT(pPrev == Last()); //ERROR validating item-list, broken list, does not end at specified Last item - CPA_ASSERT(!pReferenceItem); //ERROR reference item not found in the item-list - } - ILINE size_t Count() const{return m_Count; } - }; -} - - - - - - -#endif // CRYINCLUDE_CRYPOOL_LIST_H - diff --git a/Code/CryEngine/CryCommon/CryPool/Memory.h b/Code/CryEngine/CryCommon/CryPool/Memory.h deleted file mode 100644 index 43daaaeada..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/Memory.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYPOOL_MEMORY_H -#define CRYINCLUDE_CRYPOOL_MEMORY_H -#pragma once - -namespace NCryPoolAlloc -{ - class CMemoryDynamic - { - size_t m_Size; - uint8* m_pData; - - protected: - ILINE CMemoryDynamic() - : m_Size(0) - , m_pData(0){} - - public: - ILINE void InitMem(const size_t S, uint8* pData) - { - m_Size = S; - m_pData = pData; - CPA_ASSERT(S); - CPA_ASSERT(pData); - } - - ILINE size_t MemSize() const{return m_Size; } - ILINE uint8* Data(){return m_pData; } - ILINE const uint8* Data() const{return m_pData; } - }; - - template - class CMemoryStatic - { - uint8 m_Data[TSize]; - - protected: - ILINE CMemoryStatic() - { - } - public: - ILINE void InitMem(const size_t S, uint8* pData) - { - } - ILINE size_t MemSize() const{return TSize; } - ILINE uint8* Data(){return m_Data; } - ILINE const uint8* Data() const{return m_Data; } - }; -} - - - - - - - -#endif // CRYINCLUDE_CRYPOOL_MEMORY_H - diff --git a/Code/CryEngine/CryCommon/CryPool/PoolAlloc.h b/Code/CryEngine/CryCommon/CryPool/PoolAlloc.h deleted file mode 100644 index 23eda51a2a..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/PoolAlloc.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#if defined(POOLALLOCTESTSUIT) -//cheat just for unit testing on windows -#include "BaseTypes.h" -#define ILINE inline -#endif - -// Traits -#if defined(AZ_RESTRICTED_PLATFORM) - #include AZ_RESTRICTED_FILE(CryPool/PoolAlloc_h) -#elif defined(APPLE) || defined(LINUX) -#define POOLALLOC_H_TRAIT_USE_MEMALIGN 1 -#endif - - -#if POOLALLOC_H_TRAIT_USE_MEMALIGN -#define CPA_ALLOC memalign -#define CPA_FREE free -#else -#define CPA_ALLOC _aligned_malloc -#define CPA_FREE _aligned_free -#endif -#define CPA_ASSERT assert -#define CPA_ASSERT_STATIC(X) {uint8 assertdata[(X) ? 0 : 1]; } -#define CPA_BREAK __debugbreak() - -#include "List.h" -#include "Memory.h" -#include "Container.h" -#include "Allocator.h" -#include "Defrag.h" -#include "STLWrapper.h" -#include "Inspector.h" -#include "Fallback.h" -#if !defined(POOLALLOCTESTSUIT) -#include "ThreadSafe.h" -#endif - -#undef CPA_ASSERT -#undef CPA_ASSERT_STATIC -#undef CPA_BREAK diff --git a/Code/CryEngine/CryCommon/CryPool/STLWrapper.h b/Code/CryEngine/CryCommon/CryPool/STLWrapper.h deleted file mode 100644 index cb06ced1a4..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/STLWrapper.h +++ /dev/null @@ -1,148 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYPOOL_STLWRAPPER_H -#define CRYINCLUDE_CRYPOOL_STLWRAPPER_H -#pragma once - -namespace NCryPoolAlloc -{ - //namespace CSTLPoolAllocWrapperHelper - //{ - // inline void destruct(char *) {} - // inline void destruct(wchar_t*) {} - // template - // inline void destruct(T *t) {t->~T();} - //} - - //template - //struct CSTLPoolAllocWrapperStatic - //{ - // static PoolAllocator * allocator; - //}; - - //template - //struct CSTLPoolAllocWrapperKungFu : public CSTLPoolAllocWrapperStatic - //{ - //}; - - template - class CSTLPoolAllocWrapper - { - private: - static TCont* m_pContainer; - public: - typedef size_t size_type; - typedef ptrdiff_t difference_type; - typedef T* pointer; - typedef const T* const_pointer; - typedef T& reference; - typedef const T& const_reference; - typedef T value_type; - - static TCont* Container(){return m_pContainer; } - static void Container(TCont* pContainer){m_pContainer = pContainer; } - - - template - struct rebind - { - typedef CSTLPoolAllocWrapper other; - }; - - CSTLPoolAllocWrapper() throw() - { - } - - CSTLPoolAllocWrapper(const CSTLPoolAllocWrapper&) throw() - { - } - - template - CSTLPoolAllocWrapper(const CSTLPoolAllocWrapper&) throw() - { - } - - ~CSTLPoolAllocWrapper() throw() - { - } - - pointer address(reference x) const - { - return &x; - } - - const_pointer address(const_reference x) const - { - return &x; - } - - pointer allocate(size_type n = 1, const_pointer hint = 0) - { - TCont* pContainer = Container(); - uint8* pData = pContainer->TCont::template Allocate(n * sizeof(T), sizeof(T)); - return pContainer->TCont::template Resolve(pData); - // return Container()?Container()->Allocate(n*sizeof(T),sizeof(T)):0 - } - - void deallocate(pointer p, size_type n = 1) - { - if (Container()) - { - Container()->Free(p); - } - } - - size_type max_size() const throw() - { - return Container() ? Container()->MemSize() : 0; - } - - void construct(pointer p, const T& val) - { - new(static_cast(p))T(val); - } - - void construct(pointer p) - { - new(static_cast(p))T(); - } - - void destroy(pointer p) - { - p->~T(); - } - - pointer new_pointer() - { - return new(allocate())T(); - } - - pointer new_pointer(const T& val) - { - return new(allocate())T(val); - } - - void delete_pointer(pointer p) - { - p->~T(); - deallocate(p); - } - - bool operator==(const CSTLPoolAllocWrapper&) {return true; } - bool operator!=(const CSTLPoolAllocWrapper&) {return false; } - }; -} - -#endif // CRYINCLUDE_CRYPOOL_STLWRAPPER_H - diff --git a/Code/CryEngine/CryCommon/CryPool/ThreadSafe.h b/Code/CryEngine/CryCommon/CryPool/ThreadSafe.h deleted file mode 100644 index 5ae7dbd4bc..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/ThreadSafe.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYPOOL_THREADSAFE_H -#define CRYINCLUDE_CRYPOOL_THREADSAFE_H -#pragma once - - -#include - -namespace NCryPoolAlloc -{ - template - class CThreadSafe - : public TAllocator - { - CryCriticalSection m_Mutex; - public: - - template - ILINE T Allocate(size_t Size, size_t Align = 1) - { - CryAutoLock lock(m_Mutex); - return TAllocator::template Allocate(Size, Align); - } - - - template - ILINE bool Free(T pData, bool ForceBoundsCheck = false) - { - CryAutoLock lock(m_Mutex); - return TAllocator::Free(pData, ForceBoundsCheck); - } - - template - ILINE bool Resize(T** pData, size_t Size, size_t Alignment) - { - CryAutoLock lock(m_Mutex); - return TAllocator::Resize(pData, Size, Alignment); - } - }; -} - - - - -#endif // CRYINCLUDE_CRYPOOL_THREADSAFE_H - diff --git a/Code/CryEngine/CryCommon/CryPool/example.h b/Code/CryEngine/CryCommon/CryPool/example.h deleted file mode 100644 index e17d5abee2..0000000000 --- a/Code/CryEngine/CryCommon/CryPool/example.h +++ /dev/null @@ -1,287 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYPOOL_EXAMPLE_H -#define CRYINCLUDE_CRYPOOL_EXAMPLE_H -#pragma once - - -//The documentation is split up into 3 main parts, so strg+f for -// -Theory -// -Building blocks -// -Usage -// -FAQ -// -Realloc/Resize - -///////////////////////////////////////////////////////////////////////// -// -Theory -///////////////////////////////////////////////////////////////////////// - - -//this includes the 3 major parts of the allocate suite -//1. the memory location templates -//2. container types -//3. some allocator version -//addtional you get -//4. a simple stack based defragmentation template -//5. helper - -//1. memory location templates -// There are two types of them, static and dynamic -//1.1 CMemoryStatic allows you do define on compile time what size -// it should have, suitable for pool you know that they won't grow or -// shrink -//1.2 CMemoryDynamic, this one has no template parameter, it has just one -// indirection via ptr to the memory location and size, that you will -// set during initialization. - -//2. Container types -// We have also two container types, one so called "In Place" -// and one "Referenced". -//2.1 "In Place" means that a header is placed above every allocation, -// this is the usual way most allocators work. -//2.2 "Referenced", has an extra pool of headers that point to the actual -// memory. This is suitable for -// - external memory locations that are not directly accessable by the -// cpu. E.g. pools on disk, networks, rsx memory.. -// - defragmentation, because you don't save a ptr to the real memory -// location, just a "handle" of the referencing item. -// - big alignments, having 4kb of alignment would waste also -// - 4kb for ever "In Place" header, you might not want that. - -//3. Allocators -// This time we have 3 of them, "BestFit", "WorstFit" and "FirstFit" -//3.1 FirstFit just seeks for any location big enought to fit your -// requested size of memory. Internally it also saves the last used -// free memory area to speed up allocations. -// Use this also if you have just one particular allocation size. -//3.2 WorstFit, although it might sound illogical, WorstFit can reduce -// memory fragmentation in a cases with very random allocation sizes, -// because it gives smaller free blocks the chance to concatenate to -// bigger free blocks again while filling up those previously -// generated big blocks. The bad side is that it takes quite some time -// to find the biggest block as this needs to be done every time you -// allocate, so use this just when having a low amount of allocations -// or you're really desperately looking for mem. -//3.3 BestFit, it's best used if you don't have just one allocation size, -// but still very few varying sizes. Previously released blocks of -// the currently allocating sizes will be seeked and reused, this -// strongly helps to reduce fragmentation. While this might be slow -// in some cases, it can save you from doing any defragmentation. - -//4. Defragmentation -// At the moment just one defragmentation algorithm is implemented: -// "Stack defragmentator" -// If you don't want some block to be moved, "Lock" it using your -// memory handle. -//4.1 Stack based -// To reduce fragmentation, holes are filled up with the next used, -// memory area. This defragmentation sheme is useful when you have -// some long living locations as well as very short living ones. -// At some point all long live memory will end up at the bottom of -// the stack, while leaving empty memory areas at the top for short -// living allocations. - -//5. Helper -// this should be filled up with some handy helper tools for this -// pool suite. -// The first tool is a wrapper for the usage with stl -//5.1 Wrapper for STL -// As you know, you can pass your own allocator as the last -// parameter of stl containers, with this helper you can use a pool -// created with this suite and wrap it for the stl. - - -///////////////////////////////////////////////////////////////////////// -// -Building blocks -///////////////////////////////////////////////////////////////////////// - -//That's the theory, so how does it work? -//It's pretty simple, you compose the pool of your dreams by cascading -//templates. -//Lets start with an exmaple -//Per level you want to allocate a fixed amount of memory for your -//textures. -CMemoryDynamic -//- They are placed in some memory you can access directly with the cpu: -CInPlace -//- and you don't want to defragmentate, so you prefer an allocation -// sheme that reduces fragmentation. - CBestFit -//now you combine them -typedef CBestFit, CListItemInPlace> TMyOwnPool; - -//Yes, it's that simple. -//ok, ok, texture memory is usually nothing you want to access directly -//with your cpu, so let's create a referencing pool. Therefor you need -//to also specify how many nodes that can reference your pool will have. -//We won't have more than 4000 textures, so let's start with -{ - enum TEXTURE_NODE_COUNT = 4096 -}; -//and now our referencing pool -typedef CBestFit < CReferenced TMyOwnPool; - -//But yeah, you're right, texture memory has also a fixed size, lets -//assume it's 128MB. -{ - enum TEXTURE_MEMORY_SIZE = 128 * 1024 * 1024 -}; -//and our fixed sized memory pool -typedef CBestFit < CReferenced, TEXTURE_NODE_COUNT> TMyOwnPool; - -//ok, but you don't trust the best fit allocator in all cases, you prefer -//a fast one and you accept the slow down for defragmentation incase the -//allocation fails. -//So lets created a straight First Fit allocator with defragmentation: -typedef CDefragStacked < CFirstFit, TEXTURE_NODE_COUNT> > TMyOwnPool; - -//here you see how simple you can add defragmentation, but be careful, it -//works of course just on Reference based memory containers, if you have -//Direct pointers to In Place allocation, we cannot shuffle them around. - - -///////////////////////////////////////////////////////////////////////// -// -Usage -///////////////////////////////////////////////////////////////////////// - - -//it all starts by including the meain header -#include "PoolAlloc.h" - -//Define your dream allocator, preferably using a typedef (or macro) -typedef CBestFit, CListItemInPlace> TMyOwnPool; -//also typedef (or macro) your handle -typedef uint8* TMyHandle; //in case of "In Place" allocations -typedef uint32 TMyHandle; //in case of "Referenced" - -//Instantiate it -TMyOwnPool g_MyMemory; - -//now you need to initialize it, -g_MyMemory.InitMem(pMemoryArea, MemorySize); //in case you use "CMemoryDynamic" -g_MyMemory.InitMem(); //in case you use "CmemoryStatic, -//altough you could pass the same -//parameters, they'd be ignored. -//Use this also to flush the pool -//quickly - - -//now allocate -TMyHandle MemID = g_MyMemory.Allocate(Size); -//optionally alignment can be passed as 2nd parameter -TMyHandle MemID = g_MyMemory.Allocate(Size, Align); - -//free it simply by calling -g_Memory.Free(MemID); - -//you might want to call the beat function to defragment the memory -//on regular base -g_Memory.Beat(); -//you might also want to call it just when an allocation failed to -//defragmentate the memory as good as possible -if (!(MemID = g_Memoery.Allocate(Size))) -{ - while (g_Memory.Beat()) - { - ; - } - MemID = g_Memoery.Allocate(Size); -} - -//To acquire the pointer to your data, you need to resolve the handle -MyObject* pObject = g_Memory.Resolve(MemID); - -///////////////////////////////////////////////////////////////////////// -// -Realloc/Resize -///////////////////////////////////////////////////////////////////////// - -// The Containers provide a "resize" function. This one does nothing else -// than the name suggest, it is freeing some memory at the end of your -// allocation or, if free memory is available, allocates some memory to -// the end of your buffer. But it may also fail, if not enough memory -// available to allocate. -// "Realloc" on the other side requires an extra template that you wrap -// around your existing one like: -typedef CReallocator TMyOwnPoolWithReallocation; -// This one will first try to use resize, but in case it fails, it will -// allocate a seperate memory area, copy the data and free the old one. -// -// But this may fail as well, therefor the result is not a pointer to the -// allocation, but true/false. -// There for you need to pass a pointer to your pointer to the memory area -// or handle you deal with. -Handle = rMemory.Allocate(10, 1); -if (!rMemory.Reallocate(&Handles, 11, 1)) -{ - //handle realloc failure -} - - -///////////////////////////////////////////////////////////////////////// -// -FAQ -///////////////////////////////////////////////////////////////////////// - -//"DO I HAVE TO ALWAYS RESOLVE?" -//if you use "In Place" memory, not at all, all resolve does is to -//cast your handle to your object ptr and returns it. -//if you use "Referenced" memory and you don't defragmentate, you -//can do it once and keep the ptr, but you also need to keep the -//handle to free the memory later on. - -//"any reason I should resolve?" -//Yes, first of all, it makes it very easy to switch between various -//pool configuration for testing, you simply change some params of -//your typedef (or macro) and it should work out of the box. -//second, for defragmentation it's the only way to go and for future -//things it might be needed as well - -//"but isn't resolving just overhead?" -//in case of "In Place": no, the resolve function just returns the -//pointer, casting to your wanted type -//in case of "Referenced": it cost you one indirection. - - -//"How do I flush the whole pool without freeing all items?" -g_Memory.InitMem() -//yes, you can call "InitMem" once again, you need to pass the mem -//ptr and size if using CMemoryDynamic e.g. -g_Memory.Init(g_Memory.Size(), g_Memory.Data()); - -//"How do I lock the allocated memory to avoid any reallocation" -g_Memory.Item(ptr)->Lock(); - - -//"How do I get the size of a memory block?" -g_Memory.Item(ptr)->MemSize(); - - - - -//"Is there any example?" -//for a real life example check PAUnitTest.cpp used to validate all -//functions of this pool. - - -//bug reports? questions? support? -//just ask me :) (michael kopietz) - - - - - - - - -#endif // CRYINCLUDE_CRYPOOL_EXAMPLE_H - diff --git a/Code/CryEngine/CryCommon/GeomCacheFileFormat.h b/Code/CryEngine/CryCommon/GeomCacheFileFormat.h deleted file mode 100644 index a8328e8a14..0000000000 --- a/Code/CryEngine/CryCommon/GeomCacheFileFormat.h +++ /dev/null @@ -1,202 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_GEOMCACHEFILEFORMAT_H -#define CRYINCLUDE_CRYCOMMON_GEOMCACHEFILEFORMAT_H -#pragma once - -#include "CryExtension/CryGUID.h" - -#if !defined(LINUX) -#pragma pack(push) -#pragma pack(1) -#define PACK_GCC -#else -#define PACK_GCC __attribute__ ((packed)) -#endif - -namespace GeomCacheFile -{ - // Important: The enums are serialized, don't change the values - // without increasing the file version, conversion code etc! - - typedef Vec3_tpl Position; - typedef Vec2_tpl Texcoords; - typedef Vec4_tpl QTangent; - typedef uint8 Color; - - // ASCII "CAXCACHE" - const uint64 kFileSignature = 0x4548434143584143ull; - - // The smallest 'UVmax' we'll support - this avoids division by zero when encoding/decoding UVs - const float kMinUVrange = .01f; - - // Bit Precision of tangents quaternions - const uint kTangentQuatPrecision = 10; - - // Current file version GUID. Files with other GUIDs will not be loaded by the engine. - const CryGUID kCurrentVersion = MAKE_CRYGUID(0x1641defe440af501, 0x7ec5e9164c8c2d1c); - - // Mesh prediction look back array size - const uint kMeshPredictorLookBackMaxDist = 4096; - - // Number of frames between index frames. Needs to be <= g_kMaxBufferedFrames. - const uint kMaxIFrameDistance = 30; - - enum EFileHeaderFlags - { - eFileHeaderFlags_PlaybackFromMemory = BIT(0), - eFileHeaderFlags_32BitIndices = BIT(1) - }; - - enum EBlockCompressionFormat - { - eBlockCompressionFormat_None = 0, - eBlockCompressionFormat_Deflate = 1, // zlib - eBlockCompressionFormat_LZ4HC = 2, // LZ4 HC - eBlockCompressionFormat_ZSTD = 3, //ZStandard - }; - - enum EStreams - { - eStream_Indices = BIT(0), - eStream_Positions = BIT(1), - eStream_Texcoords = BIT(2), - eStream_QTangents = BIT(3), - eStream_Colors = BIT(4) - }; - - enum ETransformType - { - eTransformType_Constant, - eTransformType_Animated - }; - - enum ENodeType - { - eNodeType_Transform = 0, // Transforms all sub nodes - eNodeType_Mesh = 1, - eNodeType_PhysicsGeometry = 2, - }; - - // Common frame - enum EFrameType - { - eFrameType_IFrame = 0, - eFrameType_BFrame = 1 - }; - - // Common frame flags - enum EFrameFlags - { - eFrameFlags_Hidden = BIT(0) - }; - - // Flags for mesh index frames - enum EMeshIFrameFlags - { - eMeshIFrameFlags_UsePredictor = BIT(1) - }; - - struct SHeader - { - SHeader() - : m_signature(0) - , m_version(kCurrentVersion) - , m_blockCompressionFormat(0) - , m_flags(0) - , m_numFrames(0) {} - - uint64 m_signature; - CryGUID m_version; - uint16 m_blockCompressionFormat; - uint32 m_flags; - uint32 m_numFrames; - uint64 m_totalUncompressedAnimationSize; - float m_aabbMin[3]; - float m_aabbMax[3]; - } PACK_GCC; - - struct SFrameInfo - { - uint32 m_frameType; - uint32 m_frameSize; - uint64 m_frameOffset; - float m_frameTime; - } PACK_GCC; - - struct SCompressedBlockHeader - { - uint32 m_uncompressedSize; - uint32 m_compressedSize; - } PACK_GCC; - - struct SFrameHeader - { - uint32 m_nodeDataOffset; - float m_frameAABBMin[3]; - float m_frameAABBMax[3]; - uint32 m_padding; - } PACK_GCC; - - struct STemporalPredictorControl - { - uint8 m_acceleration; - uint8 m_indexFrameLerpFactor; - uint8 m_combineFactor; - uint8 m_padding; - } PACK_GCC; - - struct SMeshFrameHeader - { - uint32 m_flags; - STemporalPredictorControl m_positionStreamPredictorControl; - STemporalPredictorControl m_texcoordStreamPredictorControl; - STemporalPredictorControl m_qTangentStreamPredictorControl; - STemporalPredictorControl m_colorStreamPredictorControl[4]; - } PACK_GCC; - - struct SMeshInfo - { - uint8 m_constantStreams; - uint8 m_animatedStreams; - uint8 m_positionPrecision[3]; - float m_uvMax; - uint8 m_padding; - uint16 m_numMaterials; - uint32 m_numVertices; - uint32 m_flags; - float m_aabbMin[3]; - float m_aabbMax[3]; - uint32 m_nameLength; - uint64 m_hash; - } PACK_GCC; - - struct SNodeInfo - { - uint8 m_type; - uint8 m_bVisible; - uint16 m_transformType; - uint32 m_meshIndex; - uint32 m_numChildren; - uint32 m_nameLength; - } PACK_GCC; -} - -#undef PACK_GCC - -#if !defined(LINUX) -#pragma pack(pop) -#endif - -#endif // CRYINCLUDE_CRYCOMMON_GEOMCACHEFILEFORMAT_H diff --git a/Code/CryEngine/CryCommon/IEngineModule.h b/Code/CryEngine/CryCommon/IEngineModule.h deleted file mode 100644 index 7835cde26e..0000000000 --- a/Code/CryEngine/CryCommon/IEngineModule.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Defines the extension interface for the CryEngine modules. - - -#ifndef CRYINCLUDE_CRYCOMMON_IENGINEMODULE_H -#define CRYINCLUDE_CRYCOMMON_IENGINEMODULE_H -#pragma once - -#include -#include -#include -#include - -struct SSystemInitParams; - -// Base Interface for all engine module extensions -struct IEngineModule - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IEngineModule, 0xf899cf661df04f61, 0xa341a8a7ffdf9de4); - - // - // Retrieve name of the extension module. - virtual const char* GetName() const = 0; - - // Retrieve category for the extension module (CryEngine for standard modules). - virtual const char* GetCategory() const = 0; - - // This is called to initialize the new module. - virtual bool Initialize(SSystemGlobalEnvironment& env, const SSystemInitParams& initParams) = 0; - // - - // This is called to register any AZ console vars declared within this engine module - virtual void RegisterConsoleVars() - { - AZ::ConsoleFunctorBase*& deferredHead = AZ::ConsoleFunctorBase::GetDeferredHead(); - AZ::Interface::Get()->LinkDeferredFunctors(deferredHead); - } -}; - -#endif // CRYINCLUDE_CRYCOMMON_IENGINEMODULE_H diff --git a/Code/CryEngine/CryCommon/IRemoteCommand.h b/Code/CryEngine/CryCommon/IRemoteCommand.h deleted file mode 100644 index 03adb89b44..0000000000 --- a/Code/CryEngine/CryCommon/IRemoteCommand.h +++ /dev/null @@ -1,763 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Service network interface - - -#ifndef CRYINCLUDE_CRYCOMMON_IREMOTECOMMAND_H -#define CRYINCLUDE_CRYCOMMON_IREMOTECOMMAND_H -#pragma once - -#include -#include - -//----------------------------------------------------------------------------- -// Helpers for writing/reading command data stream from network message packets. -// Those interfaces automatically handle byteswapping for big endian systems. -// The native format for data inside the messages is little endian. -//----------------------------------------------------------------------------- - -/// Write stream interface -struct IDataWriteStream -{ -public: - virtual ~IDataWriteStream() {}; - -public: - // Virtualized write method for general data buffer - virtual void Write(const void* pData, const uint32 size) = 0; - - // Virtualized write method for types with size 8 (support byteswapping, a little bit faster than general case) - virtual void Write8(const void* pData) = 0; - - // Virtualized write method for types with size 4 (support byteswapping, a little bit faster than general case) - virtual void Write4(const void* pData) = 0; - - // Virtualized write method for types with size 2 (support byteswapping, a little bit faster than general case) - virtual void Write2(const void* pData) = 0; - - // Virtualized write method for types with size 1 (a little bit faster than general case) - virtual void Write1(const void* pData) = 0; - - // Get number of bytes written - virtual const uint32 GetSize() const = 0; - - // Convert to service network message - virtual struct IServiceNetworkMessage* BuildMessage() const = 0; - - // Save the data from this writer stream to the provided buffer - virtual void CopyToBuffer(void* pData) const = 0; - - // Destroy object (if dynamically created) - virtual void Delete() = 0; - -public: - IDataWriteStream& operator<<(const uint8& val) - { - Write1(&val); - return *this; - } - - IDataWriteStream& operator<<(const uint16& val) - { - Write2(&val); - return *this; - } - - IDataWriteStream& operator<<(const uint32& val) - { - Write4(&val); - return *this; - } - - IDataWriteStream& operator<<(const uint64& val) - { - Write8(&val); - return *this; - } - - IDataWriteStream& operator<<(const int8& val) - { - Write1(&val); - return *this; - } - - IDataWriteStream& operator<<(const int16& val) - { - Write2(&val); - return *this; - } - - IDataWriteStream& operator<<(const int32& val) - { - Write4(&val); - return *this; - } - - IDataWriteStream& operator<<(const int64& val) - { - Write8(&val); - return *this; - } - - IDataWriteStream& operator<<(const float& val) - { - Write4(&val); - return *this; - } - - // Bool is saved by writing an 8 bit value to make it portable - IDataWriteStream& operator<<(const bool& val) - { - const uint8 uVal = val ? 1 : 0; - Write1(&uVal); - return *this; - } - -public: - // Write C string to stream - void WriteString(const char* str); - - // Write string to stream - void WriteString(const string& str); - - // Write int8 value to stream - void WriteInt8(const int8 val) - { - Write1(&val); - } - - // Write int16 value to stream - void WriteInt16(const int16 val) - { - Write2(&val); - } - - // Write int32 value to stream - void WriteInt32(const int32 val) - { - Write4(&val); - } - - // Write int64 value to stream - void WriteInt64(const int64 val) - { - Write8(&val); - } - - // Write uint8 value to stream - void WriteUint8(const uint8 val) - { - Write1(&val); - } - - // Write uint16 value to stream - void WriteUint16(const uint16 val) - { - Write2(&val); - } - - // Write uint32 value to stream - void WriteUint32(const uint32 val) - { - Write4(&val); - } - - // Write uint64 value to stream - void WriteUint64(const uint64 val) - { - Write8(&val); - } - - // Write float value to stream - void WriteFloat(const float val) - { - Write4(&val); - } -}; - -//----------------------------------------------------------------------------- - -/// Read stream interface -/// This interface should support endianess swapping -struct IDataReadStream -{ -public: - virtual ~IDataReadStream() {}; - -public: - // Destroy object (if dynamically created) - virtual void Delete() = 0; - - // Skip given amount of data without reading it - virtual void Skip(const uint32 size) = 0; - - // Virtualized read method (for general buffers) - virtual void Read(void* pData, const uint32 size) = 0; - - // Virtualized read method for types with size 8 (a little bit faster than general method, supports byte swapping for BE systems) - virtual void Read8(void* pData) = 0; - - // Virtualized read method for types with size 4 (a little bit faster than general method, supports byte swapping for BE systems) - virtual void Read4(void* pData) = 0; - - // Virtualized read method for types with size 2 (a little bit faster than general method, supports byte swapping for BE systems) - virtual void Read2(void* pData) = 0; - - // Virtualized read method for types with size 1 (a little bit faster than general method, supports byte swapping for BE systems) - virtual void Read1(void* pData) = 0; - - // Optimization case - get direct pointer to the underlying buffer - virtual const void* GetPointer() = 0; - -public: - IDataReadStream& operator<<(uint8& val) - { - Read1(&val); - return *this; - } - - IDataReadStream& operator<<(uint16& val) - { - Read2(&val); - return *this; - } - - IDataReadStream& operator<<(uint32& val) - { - Read4(&val); - return *this; - } - - IDataReadStream& operator<<(uint64& val) - { - Read8(&val); - return *this; - } - - IDataReadStream& operator<<(int8& val) - { - Read1(&val); - return *this; - } - - IDataReadStream& operator<<(int16& val) - { - Read2(&val); - return *this; - } - - IDataReadStream& operator<<(int32& val) - { - Read4(&val); - return *this; - } - - IDataReadStream& operator<<(int64& val) - { - Read8(&val); - return *this; - } - - IDataReadStream& operator<<(float& val) - { - Read4(&val); - return *this; - } - - // Bool is saved by writing an 8 bit value to make it portable - IDataReadStream& operator<<(bool& val) - { - uint8 uVal = 0; - Read1(&uVal); - val = (uVal != 0); - return *this; - } - -public: - // Read string from stream - string ReadString(); - - // Skip string data in a stream without loading the data - void SkipString(); - - // Read int8 from stream - int8 ReadInt8() - { - int8 val = 0; - Read1(&val); - return val; - } - - // Read int16 from stream - int16 ReadInt16() - { - int16 val = 0; - Read2(&val); - return val; - } - - // Read int32 from stream - int32 ReadInt32() - { - int32 val = 0; - Read4(&val); - return val; - } - - // Read int64 from stream - int64 ReadInt64() - { - int64 val = 0; - Read8(&val); - return val; - } - - // Read uint8 from stream - uint8 ReadUint8() - { - uint8 val = 0; - Read1(&val); - return val; - } - - // Read uint16 from stream - uint16 ReadUint16() - { - uint16 val = 0; - Read2(&val); - return val; - } - - // Read uint32 from stream - uint32 ReadUint32() - { - uint32 val = 0; - Read4(&val); - return val; - } - - // Read int64 from stream - uint64 ReadUint64() - { - uint64 val = 0; - Read8(&val); - return val; - } - - // Read float from stream - float ReadFloat() - { - float val = 0.0f; - Read4(&val); - return val; - } -}; - -//----------------------------------------------------------------------------- - -/// Remote command class info (simple RTTI) -struct IRemoteCommandClass -{ -public: - virtual ~IRemoteCommandClass() {}; - - // Get class name - virtual const char* GetName() const = 0; - - // Create command instance - virtual struct IRemoteCommand* CreateObject() = 0; -}; - -/// Remote command interface -struct IRemoteCommand -{ -protected: - virtual ~IRemoteCommand() {}; - -public: - // Get command class - virtual IRemoteCommandClass* GetClass() const = 0; - - // Save to data stream - virtual void SaveToStream(struct IDataWriteStream& writeStream) const = 0; - - // Load from data stream - virtual void LoadFromStream(struct IDataReadStream& readStream) = 0; - - // Execute (remote call) = 0; - virtual void Execute() = 0; - - // Delete the command object (can be allocated from different heap) - virtual void Delete() = 0; -}; - -//----------------------------------------------------------------------------- - -// This is a implementation of a synchronous listener (limited to the engine tick rate) -// that processes and responds to the raw messages received from clients. -struct IRemoteCommandListenerSync -{ -public: - virtual ~IRemoteCommandListenerSync() {}; - - // Process a raw message and optionally provide an answer to the request, return true if you have processed the message. - // Messages is accessible via the data reader. Response can be written to a data writer. - virtual bool OnRawMessageSync(const class ServiceNetworkAddress& remoteAddress, struct IDataReadStream& msg, struct IDataWriteStream& response) = 0; -}; - -//----------------------------------------------------------------------------- - -// This is a implementation of a asynchronous listener (called from network thread) -// that processes and responds to the raw messages received from clients. -struct IRemoteCommandListenerAsync -{ -public: - virtual ~IRemoteCommandListenerAsync() {}; - - // Process a raw message and optionally provide an answer to the request, return true if you have processed the message. - // Messages is accessible via the data reader. Response can be written to a data writer. - virtual bool OnRawMessageAsync(const class ServiceNetworkAddress& remoteAddress, struct IDataReadStream& msg, struct IDataWriteStream& response) = 0; -}; - -//----------------------------------------------------------------------------- - -/// Remote command server -struct IRemoteCommandServer -{ -protected: - virtual ~IRemoteCommandServer() {}; - -public: - // Execute all of the received pending commands - // This should be called from a safe place (main thread) - virtual void FlushCommandQueue() = 0; - - // Suppress command execution - virtual void SuppressCommands() = 0; - - // Resume command execution - virtual void ResumeCommands() = 0; - - // Register/Unregister synchronous message listener (limited to tick rate) - virtual void RegisterSyncMessageListener(IRemoteCommandListenerSync* pListener) = 0; - virtual void UnregisterSyncMessageListener(IRemoteCommandListenerSync* pListener) = 0; - - // Register/Unregister asynchronous message listener (called from network thread) - virtual void RegisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener) = 0; - virtual void UnregisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener) = 0; - - // Broadcast a message to all connected clients - virtual void Broadcast(IServiceNetworkMessage* pMessage) = 0; - - // Do we have any clients connected ? - virtual bool HasConnectedClients() const = 0; - - // Delete the client - virtual void Delete() = 0; -}; - -//----------------------------------------------------------------------------- - -/// Connection to remote command server -struct IRemoteCommandConnection -{ -protected: - virtual ~IRemoteCommandConnection() {}; - -public: - // Are we connected ? - // This returns false when the underlying network connection has failed (sockets error). - // Also, this returns false if the remote connection was closed by remote peer. - virtual bool IsAlive() const = 0; - - // Get address of remote command server - // This returns the full address of the endpoint (with valid port) - virtual const ServiceNetworkAddress& GetRemoteAddress() const = 0; - - // Send raw message to the other side of this connection. - // Raw messages are not buffer and are sent right away, - // they also have precedence over internal command traffic. - // The idea is that you need some kind of bidirectional signaling - // channel to extend the rather one-directional nature of commands. - // Returns true if message was added to the send queue. - virtual bool SendRawMessage(IServiceNetworkMessage* pMessage) = 0; - - // See if there's a raw message waiting for us and if it is, get it - // Be aware that messages are reference counted. - virtual IServiceNetworkMessage* ReceiveRawMessage() = 0; - - // Close connection - // - pending commands are not sent - // - pending raw messages are sent or not (depending on the flag) - virtual void Close(bool bFlushQueueBeforeClosing = false) = 0; - - // Add internal reference to object (Refcounting interface) - virtual void AddRef() = 0; - - // Release internal reference to object (Refcounting interface) - virtual void Release() = 0; -}; - -//----------------------------------------------------------------------------- - -/// Remote command client -struct IRemoteCommandClient -{ -protected: - virtual ~IRemoteCommandClient() {}; - -public: - // Connect to remote server, returns true on success, false on failure - virtual IRemoteCommandConnection* ConnectToServer(const class ServiceNetworkAddress& serverAddress) = 0; - - // Schedule command to be executed on the all of the remote servers - virtual bool Schedule(const IRemoteCommand& command) = 0; - - // Delete the client object - virtual void Delete() = 0; -}; - -//----------------------------------------------------------------------------- - -/// Remote command manager -struct IRemoteCommandManager -{ -public: - virtual ~IRemoteCommandManager() {}; - - // Set debug message verbose level - virtual void SetVerbosityLevel(const uint32 level) = 0; - - // Create local server for executing remote commands on given local port - virtual IRemoteCommandServer* CreateServer(uint16 localPort) = 0; - - // Create client interface for executing remote commands on remote servers - virtual IRemoteCommandClient* CreateClient() = 0; - - // Register command class (will be accessible by both clients and server) - virtual void RegisterCommandClass(IRemoteCommandClass& commandClass) = 0; -}; - -//----------------------------------------------------------------------------- - -/// Class RTTI wrapper for remote command classes -template< typename T > -class CRemoteCommandClass - : public IRemoteCommandClass -{ -private: - const char* m_szName; - -public: - CRemoteCommandClass(const char* szName) - : m_szName(szName) - {} - - virtual const char* GetName() const - { - return m_szName; - } - - virtual struct IRemoteCommand* CreateObject() - { - return new T(); - } -}; - -#define DECLARE_REMOTE_COMMAND(x) \ -public: static IRemoteCommandClass& GetStaticClass() { \ - static IRemoteCommandClass* theClass = new CRemoteCommandClass(#x); return *theClass; } \ -public: virtual IRemoteCommandClass* GetClass() const { return &GetStaticClass(); } \ -public: virtual void Delete() { delete this; } \ -public: virtual void SaveToStream(IDataWriteStream & writeStream) const { const_cast(this)->Serialize(writeStream); } \ -public: virtual void LoadFromStream(IDataReadStream & readStream) { Serialize(readStream); } - -//----------------------------------------------------------------------------- - -/// CryString serialization helper (read) -inline IDataReadStream& operator<<(IDataReadStream& stream, string& outString) -{ - const uint32 kMaxTempString = 256; - - // read length - uint32 length = 0; - stream << length; - - // load string - if (length > 0) - { - if (length < kMaxTempString) - { - // load the string into temporary buffer - char temp[kMaxTempString]; - stream.Read(&temp, length); - temp[length] = 0; - - // set the string with new value - outString = temp; - } - else - { - // allocate temporary memory and load the string - std::vector temp; - temp.resize(length + 1, 0); - stream.Read(&temp[0], length); - - // set the string with new value - outString = &temp[0]; - } - } - else - { - // empty string - outString.clear(); - } - - return stream; -} - -/// CryString serialization helper (write) -inline IDataWriteStream& operator<<(IDataWriteStream& stream, const string& str) -{ - // write length - const uint32 length = static_cast(str.length()); - stream << length; - - // write string data - if (length > 0) - { - stream.Write(str.c_str(), length); - } - - return stream; -} - -//------------------------------------------------------------------------ - -/// Vector serialization helper (reading) -template< class T > -IDataReadStream& operator<<(IDataReadStream& ar, std::vector& outVector) -{ - // Load item count - uint32 count = 0; - ar << count; - - // Adapt the vector size (exact fit) - outVector.resize(count); - - // Load items - for (uint32 i = 0; i < count; ++i) - { - ar << outVector[i]; - } - - return ar; -} - -/// Vector serialization helper (writing) -template< class T > -IDataWriteStream& operator<<(IDataWriteStream& ar, const std::vector& vec) -{ - // Save item count - const uint32 count = vec.size(); - ar << count; - - // Save items - for (uint32 i = 0; i < count; ++i) - { - ar << const_cast(vec[i]); - } - - return ar; -} - -//------------------------------------------------------------------------ - -inline void IDataWriteStream::WriteString(const char* str) -{ - string tempString(str); - *this << tempString; -} - -inline void IDataWriteStream::WriteString(const string& str) -{ - *this << str; -} - -inline string IDataReadStream::ReadString() -{ - string ret; - *this << ret; - return ret; -} - -inline void IDataReadStream::SkipString() -{ - // read length - uint32 length = 0; - *this << length; - Skip(length); -} - - -//------------------------------------------------------------------------ - -// Helper class for using the data reader and writer classes -// The only major differce betwen auto_ptr is that we call Delete() instead of operator delete -template -class TAutoDelete -{ -public: - T* m_ptr; - -public: - TAutoDelete(T* ptr) - : m_ptr(ptr) - { - } - - ~TAutoDelete() - { - if (NULL != m_ptr) - { - m_ptr->Delete(); - m_ptr = NULL; - } - } - - operator bool() - { - return (NULL != m_ptr); - } - - operator T& () - { - return *m_ptr; - } - - T* operator->() - { - return m_ptr; - } - -private: - TAutoDelete(const TAutoDelete& other) - : m_ptr(NULL){}; - TAutoDelete& operator=(const TAutoDelete& other) { return *this; } -}; - -//------------------------------------------------------------------------ - - -#endif // CRYINCLUDE_CRYCOMMON_IREMOTECOMMAND_H diff --git a/Code/CryEngine/CryCommon/IServiceNetwork.h b/Code/CryEngine/CryCommon/IServiceNetwork.h deleted file mode 100644 index 3df3f79abd..0000000000 --- a/Code/CryEngine/CryCommon/IServiceNetwork.h +++ /dev/null @@ -1,344 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Service network interface - - -#ifndef CRYINCLUDE_CRYCOMMON_ISERVICENETWORK_H -#define CRYINCLUDE_CRYCOMMON_ISERVICENETWORK_H -#pragma once - - -#include -//----------------------------------------------------------------------------- -// -// Service network is a simple abstract interface for connecting between instances -// of the editor and game running on various platforms. It implements it's own -// small message based communication layer and shall not be used for raw communication -// with anything else. -// -// Features currently implemented by the service network: -// - Completely thread safe (so can be used from within other threads) -// - Completely asynchronous (only one thread) -// - Message based approach (both on the send and receive ends) -// - Automatic and transparent reconnection -// - Debug-friendly (will not time-out easily when one of the endpoints is being debugged) -// - Easy to use -// -// Usage case (server) -// - Create listener (IServiceListener) on some pre-defined port -// - Poll the incoming connections by calling Accept() method -// - Service the traffic by calling connection's ReceiveMessage()/SendMessage() methods -// - Close() and Release() connections -// - Close() and Release() listener -// -// Usage case (client) -// - Connect to a remote listener by calling Connect() method -// - Service the traffic by calling connection's ReceiveMessage()/SendMessage() methods -// - Close() and Release() connection -// -// Both sending and receiving is asynchronous. Calling the SendMessage()/ReceiveMessage() methods -// only pushes/pops the message buffers to/from the queue. -// NOTE: Message buffers are internally reference counted by the network system and they are kept around -// untill they are sent (in case of outgoing traffic) or untill they are polled by ReceiveMessage(). -// Be aware that this can cause memory spikes, especially when incoming traffic is not serviced fast enough. -// There are customizable limits (around 1MB) on the amount of data that can be buffered internally by -// the service network before the new messages are rejected. -// It's up to the higher layer to ensure damage control in such situation. -// -// NOTE: connection is also a reference counted object, make sure to call Close() before calling Release(). -// -//----------------------------------------------------------------------------- - -/// Network address abstraction -class ServiceNetworkAddress -{ -public: - struct StringAddress - { - char m_data[32]; - - ILINE const char* c_str() const - { - return m_data; - } - }; - - struct Address - { - uint8 m_ip0; - uint8 m_ip1; - uint8 m_ip2; - uint8 m_ip3; - uint16 m_port; - - ILINE Address() - : m_ip0(0) - , m_ip1(0) - , m_ip2(0) - , m_ip3(0) - , m_port(0) - {} - }; - -private: - Address m_address; - -public: - // By default creates ("invalid address") - ILINE ServiceNetworkAddress() - { - } - - // Copy (with optional port change) - ILINE ServiceNetworkAddress(const ServiceNetworkAddress& other, uint16 newPort = 0) - : m_address(other.m_address) - { - if (newPort != 0) - { - m_address.m_port = newPort; - } - } - - // Initialize from ip:host pattern (if you want to initialize from host name use the DebugNetwork interface) - ILINE ServiceNetworkAddress(uint8 ip0, uint8 ip1, uint8 ip2, uint8 ip3, uint16 port) - { - m_address.m_ip0 = ip0; - m_address.m_ip1 = ip1; - m_address.m_ip2 = ip2; - m_address.m_ip3 = ip3; - m_address.m_port = port; - } - - // Set new port value - ILINE void SetPort(uint16 port) - { - m_address.m_port = port; - } - - // Is this a valid address - ILINE bool IsValid() const - { - return (m_address.m_ip0 != 0) && - (m_address.m_ip1 != 1) && - (m_address.m_ip2 != 1) && - (m_address.m_ip3 != 1) && - (m_address.m_port != 0); - } - - // Convert to human readable string - ILINE StringAddress ToString() const - { - // format the string buffer - StringAddress ret; - sprintf_s(ret.m_data, sizeof(ret.m_data), - "%d.%d.%d.%d:%d", - m_address.m_ip0, m_address.m_ip1, m_address.m_ip2, m_address.m_ip3, - m_address.m_port); - - // return as managed string - return ret; - } - - // Get the literal data - ILINE const Address& GetAddress() const - { - return m_address; - } - -public: - // Compare base address (IP only) of two connections - static bool CompareBaseAddress(const ServiceNetworkAddress& a, const ServiceNetworkAddress& b) - { - return (a.m_address.m_ip0 == b.m_address.m_ip0) && - (a.m_address.m_ip1 == b.m_address.m_ip1) && - (a.m_address.m_ip2 == b.m_address.m_ip2) && - (a.m_address.m_ip3 == b.m_address.m_ip3); - } - - // Compare full address (IP+port) of two connections - static bool CompareFullAddress(const ServiceNetworkAddress& a, const ServiceNetworkAddress& b) - { - return (a.m_address.m_ip0 == b.m_address.m_ip0) && - (a.m_address.m_ip1 == b.m_address.m_ip1) && - (a.m_address.m_ip2 == b.m_address.m_ip2) && - (a.m_address.m_ip3 == b.m_address.m_ip3) && - (a.m_address.m_port == b.m_address.m_port); - } -}; - -//----------------------------------------------------------------------------- - -/// Message buffer used by the network system -struct IServiceNetworkMessage -{ -protected: - IServiceNetworkMessage() {}; - virtual ~IServiceNetworkMessage() {}; - -public: - // Get unique message ID (message ID is used just once) - virtual uint32 GetId() const = 0; - - // Get the size of message buffer - virtual uint32 GetSize() const = 0; - - // Get pointer to the message data - virtual void* GetPointer() = 0; - - // Get pointer to the message data - virtual const void* GetPointer() const = 0; - - // Create reader interface for reading message data, returned object is not - // reference counted but it will hold a reference to the message. - virtual struct IDataReadStream* CreateReader() const = 0; - - // Add reference (buffer is internally refcounted) - virtual void AddRef() = 0; - - // Release reference - virtual void Release() = 0; -}; - -//----------------------------------------------------------------------------- - -/// General network TCP/IP connection -struct IServiceNetworkConnection -{ -protected: - IServiceNetworkConnection() {}; - virtual ~IServiceNetworkConnection() {}; - -public: - static const uint32 kDefaultFlushTime = 10000; // ms - - // Get the unique connection ID (is shared between host and client) - virtual const CryGUID& GetGUID() const = 0; - - // Get remote endpoint address - virtual const ServiceNetworkAddress& GetRemoteAddress() const = 0; - - // Get local endpoint address - virtual const ServiceNetworkAddress& GetLocalAddress() const = 0; - - // Add a message buffer to the connection send queue. - // Connection can refuse to send the buffer if it's full or invalid. - // If a message is rejected this function returns false. - virtual bool SendMsg(IServiceNetworkMessage* message) = 0; - - // Get a message from connection receive queue. - // If there are no pending messages a NULL is returned. - // Since message is a ref-counted you need to call Release() when you are done with the buffer. - virtual IServiceNetworkMessage* ReceiveMsg() = 0; - - // Checks if connection is still alive. - // Returns false only if connection has been damaged beyond repair. - virtual bool IsAlive() const = 0; - - // Get number of messages sent by this connection so far - virtual uint32 GetMessageSendCount() const = 0; - - // Get number of messages received by this connection so far - virtual uint32 GetMessageReceivedCount() const = 0; - - // Get size of data sent by this connection so far - virtual uint64 GetMessageSendDataSize() const = 0; - - // Get size of data received by this connection so far - virtual uint64 GetMessageReceivedDataSize() const = 0; - - // Request connection to be closed but not before sending out all of the pending messages. Incoming messages are ignored. - // Processing and sending the messages is done on the networking thread so this function will not block. - // As an option, connection can be forcefully closed after given amount of time (in ms). - virtual void FlushAndClose(const uint32 timeoutMs = kDefaultFlushTime) = 0; - - // Synchronous wait for the connection to send all outgoing messages - virtual void FlushAndWait() = 0; - - // Request connection to be closed now. All pending messages are discarded. - virtual void Close() = 0; - - // Add reference (connection is an internally reference counted object) - virtual void AddRef() = 0; - - // Release reference - virtual void Release() = 0; -}; - -//----------------------------------------------------------------------------- - -/// General listening socket (async) -struct IServiceNetworkListener -{ -protected: - IServiceNetworkListener() {}; - virtual ~IServiceNetworkListener() {}; - -public: - // Get the local address - virtual const ServiceNetworkAddress& GetLocalAddress() const = 0; - - // Get number of active connections handled by this listener - virtual uint GetConnectionCount() const = 0; - - // Accept incoming connection (asynchronously) - // Will return NULL if there's nothing to accept - // Will return new IDebugNetworkConnection if something was received - virtual IServiceNetworkConnection* Accept() = 0; - - // Is listener able to accept connections ? - virtual bool IsAlive() const = 0; - - // Request listener to be closed (closes the socket) - virtual void Close() = 0; - - // Add reference (listener is an internally reference counted object) - virtual void AddRef() = 0; - - // Release reference - virtual void Release() = 0; -}; - -//----------------------------------------------------------------------------- - -/// General service (background) network interface -struct IServiceNetwork -{ -public: - virtual ~IServiceNetwork() {}; - - // Set verbosity level of debug messages that got printed to log, levels 0-3 are commonly used - virtual void SetVerbosityLevel(const uint32 level) = 0; - - // Allocate empty message buffer of given size, message buffer is a reference counted object - virtual IServiceNetworkMessage* AllocMessageBuffer(const uint32 size) = 0; - - // Create general message writer stream, object is not reference counted - virtual struct IDataWriteStream* CreateMessageWriter() = 0; - - // Create general message reader stream and initialize it with data - virtual struct IDataReadStream* CreateMessageReader(const void* pData, const uint32 dataSize) = 0; - - // Translate host address (string:port) to network address - virtual ServiceNetworkAddress GetHostAddress(const string& addressString, uint16 optionalPort = 0) const = 0; - - // Create network listener on given local port, listening and accepting connections is done on network thread - virtual IServiceNetworkListener* CreateListener(uint16 localPort) = 0; - - // Connect to remote address (will block until connection is made or refused) - virtual IServiceNetworkConnection* Connect(const ServiceNetworkAddress& remoteAddress) = 0; -}; - -//----------------------------------------------------------------------------- - -#endif // CRYINCLUDE_CRYCOMMON_ISERVICENETWORK_H diff --git a/Code/CryEngine/CryCommon/ISystem.h b/Code/CryEngine/CryCommon/ISystem.h index 93de0008b0..86c2b57464 100644 --- a/Code/CryEngine/CryCommon/ISystem.h +++ b/Code/CryEngine/CryCommon/ISystem.h @@ -91,7 +91,6 @@ struct IAVI_Reader; class CPNoise3; struct IVisualLog; struct ILocalizationManager; -struct ICryFactoryRegistry; struct ISoftCodeMgr; struct IZLibCompressor; struct IZLibDecompressor; @@ -99,8 +98,6 @@ struct ILZ4Decompressor; class IZStdDecompressor; struct IOutputPrintSink; struct IThreadManager; -struct IServiceNetwork; -struct IRemoteCommandManager; struct IWindowMessageHandler; struct IImageHandler; class IResourceCompilerHelper; @@ -798,8 +795,6 @@ struct SSystemGlobalEnvironment IRenderer* pRenderer; IMaterialEffects* pMaterialEffects; ISoftCodeMgr* pSoftCodeMgr; - IServiceNetwork* pServiceNetwork; - IRemoteCommandManager* pRemoteCommandManager; ILyShine* pLyShine; IResourceCompilerHelper* pResourceCompilerHelper; SharedEnvironmentInstance* pSharedEnvironment; @@ -1244,10 +1239,6 @@ struct ISystem // Retrieves access to XML utilities interface. virtual IXmlUtils* GetXmlUtils() = 0; - // Summary: - // Interface to access different implementations of Serialization::IArchive in a centralized way. - virtual Serialization::IArchiveHost* GetArchiveHost() const = 0; - virtual void SetViewCamera(CCamera& Camera) = 0; virtual CCamera& GetViewCamera() = 0; @@ -1368,10 +1359,6 @@ struct ISystem // Retrieves system update counter. virtual uint64 GetUpdateCounter() = 0; - // Summary: - // Gets access to all registered factories. - virtual ICryFactoryRegistry* GetCryFactoryRegistry() const = 0; - ////////////////////////////////////////////////////////////////////////// // Error callback handling @@ -1491,15 +1478,6 @@ struct ISystem virtual const IImageHandler* GetImageHandler() const = 0; - // Summary: - // Loads a dynamic library, creates and initializes an instance of the module class - - virtual bool InitializeEngineModule(const char* dllName, const char* moduleClassName, const SSystemInitParams& initParams) = 0; - - // Summary: - // Unloads a dynamic library as well as the corresponding instance of the module class - virtual bool UnloadEngineModule(const char* dllName, const char* moduleClassName) = 0; - // Summary: // Gets the root window message handler function // The returned pointer is platform-specific: diff --git a/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h b/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h index 31509ca6ba..3d4327116e 100644 --- a/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h +++ b/Code/CryEngine/CryCommon/Mocks/IConsoleMock.h @@ -13,7 +13,6 @@ #define CRYINCLUDE_CRYCOMMON_ICONSOLEMOCK_H #pragma once -#include #include #include diff --git a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h index 9e5182ebcf..1e28937764 100644 --- a/Code/CryEngine/CryCommon/Mocks/ISystemMock.h +++ b/Code/CryEngine/CryCommon/Mocks/ISystemMock.h @@ -164,8 +164,6 @@ public: XmlNodeRef(const char*, bool)); MOCK_METHOD0(GetXmlUtils, IXmlUtils * ()); - MOCK_CONST_METHOD0(GetArchiveHost, - Serialization::IArchiveHost * ()); MOCK_METHOD1(SetViewCamera, void(CCamera & Camera)); MOCK_METHOD0(GetViewCamera, @@ -223,8 +221,6 @@ public: CPNoise3 * ()); MOCK_METHOD0(GetUpdateCounter, uint64()); - MOCK_CONST_METHOD0(GetCryFactoryRegistry, - ICryFactoryRegistry * ()); MOCK_METHOD1(RegisterErrorObserver, bool(IErrorObserver * errorObserver)); MOCK_METHOD1(UnregisterErrorObserver, @@ -287,10 +283,6 @@ public: bool()); MOCK_CONST_METHOD0(GetImageHandler, const IImageHandler * ()); - MOCK_METHOD3(InitializeEngineModule, - bool(const char* dllName, const char* moduleClassName, const SSystemInitParams&initParams)); - MOCK_METHOD2(UnloadEngineModule, - bool(const char* dllName, const char* moduleClassName)); MOCK_METHOD0(GetRootWindowMessageHandler, void*()); MOCK_METHOD1(RegisterWindowMessageHandler, diff --git a/Code/CryEngine/CryCommon/Serialization/Assert.h b/Code/CryEngine/CryCommon/Serialization/Assert.h deleted file mode 100644 index a1ce890dc8..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Assert.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_ASSERT_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ASSERT_H -#pragma once - -#ifdef SERIALIZATION_STANDALONE -#include -#else -#include -#endif - -#ifdef YASLI_ASSERT -# undef YASLI_ASSERT -#endif - -#ifdef YASLI_VERIFY -# undef YASLI_VERIFY -#endif - -#ifdef YASLI_ESCAPE -# undef YASLI_ESCAPE -#endif - -#ifdef SERIALIZATION_STANDALONE -#define YASLI_ASSERT(x) assert(x) -#define YASLI_ASSERT_STR(x, str) assert(x && str) -#define YASLI_ESCAPE(x, action) if (!(x)) { YASLI_ASSERT(0 && #x); action; }; -#else -#define YASLI_ASSERT(x) CRY_ASSERT(x) -#define YASLI_ASSERT_STR(x, str) CRY_ASSERT_MESSAGE(x, str) -#define YASLI_ESCAPE(x, action) if (!(x)) { YASLI_ASSERT(0 && #x); action; }; -#endif // SERIALIZATION_STANDALONE - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ASSERT_H diff --git a/Code/CryEngine/CryCommon/Serialization/BitVector.h b/Code/CryEngine/CryCommon/Serialization/BitVector.h deleted file mode 100644 index 06cb3b956a..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/BitVector.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2012 Crytek GmbH -// Authors: Evgeny Andreeshchev, Alexander Kotliar -// Based on: Yasli - the serialization library. -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTOR_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTOR_H -#pragma once - - -namespace Serialization{ - -class IArchive; -template -class BitVector -{ -public: - BitVector(int value = 0) : value_(value) {} - - operator int&() { return value_; } - operator int() const { return value_; } - - BitVector& operator|= (Enum value) { value_ |= value; return *this; } - BitVector& operator|= (int value) { value_ |= value; return *this; } - BitVector& operator&= (int value) { value_ &= value; return *this; } - - void Serialize(IArchive& ar); -private: - int value_; -}; - -template -bool Serialize(Serialization::IArchive& ar, Serialization::BitVector& value, const char* name, const char* label); - -} - -#include "BitVectorImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTOR_H diff --git a/Code/CryEngine/CryCommon/Serialization/BitVectorImpl.h b/Code/CryEngine/CryCommon/Serialization/BitVectorImpl.h deleted file mode 100644 index 1d5c02342c..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/BitVectorImpl.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTORIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTORIMPL_H -#pragma once - -#include "Serialization/BitVector.h" -#include "Serialization/IArchive.h" -#include "Serialization/Enum.h" - -namespace Serialization { - struct BitVectorWrapper - { - int* valuePointer; - int value; - const CEnumDescription* description; - - explicit BitVectorWrapper(int* _value = 0, const CEnumDescription* _description = 0) - : valuePointer(_value) - , description(_description) - { - if (valuePointer) - { - value = *valuePointer; - } - } - BitVectorWrapper(const BitVectorWrapper& _rhs) - : value(_rhs.value) - , description(0) - , valuePointer(0) - { - } - - ~BitVectorWrapper() - { - if (valuePointer) - { - * valuePointer = value; - } - } - BitVectorWrapper& operator=(const BitVectorWrapper& rhs) - { - value = rhs.value; - return *this; - } - - - void Serialize(IArchive& ar) - { - ar(value, "value", "Value"); - } - }; - - template - void BitVector::Serialize(IArchive& ar) - { - ar(value_, "value", "Value"); - } -} - -template -bool Serialize(Serialization::IArchive& ar, Serialization::BitVector& value, const char* name, const char* label) -{ - using namespace Serialization; - CEnumDescription& desc = getEnumDescription(); - if (ar.IsEdit()) - { - return ar(BitVectorWrapper(&static_cast(value), &desc), name, label); - } - else - { - return desc.serializeBitVector(ar, static_cast(value), name, label); - } -} - - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_BITVECTORIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/BlackBox.h b/Code/CryEngine/CryCommon/Serialization/BlackBox.h deleted file mode 100644 index 7efbbf7ece..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/BlackBox.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_BLACKBOX_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_BLACKBOX_H -#pragma once - -#include // for malloc and free - -namespace Serialization -{ - // Black box is used to store opaque data blobs in a format internal to - // specific Archive. For example it can be used to store sections of the JSON - // or binary archive. - // - // This is useful for the Editor to store portions of files with unfamiliar - // structure. - // - // We store deallocation function here so we can safely pass the blob - // across DLLs with different memory allocators. - struct SBlackBox - { - const char* format; - void* data; - size_t size; - typedef void(* FreeFunction)(void*); - FreeFunction freeFunction; - - SBlackBox() - : format("") - , data(0) - , size(0) - , freeFunction(0) - { - } - - SBlackBox(const SBlackBox& rhs) - : format("") - , data(0) - , size(0) - , freeFunction(0) - { - *this = rhs; - } - - void set(const char* _format, const void* _data, size_t _size) - { - if (_data && freeFunction) - { - freeFunction(this->data); - this->data = 0; - this->size = 0; - freeFunction = 0; - } - this->format = _format; - if (_data && _size) - { - this->data = CryModuleMalloc(_size); - memcpy(this->data, _data, _size); - this->size = _size; - freeFunction = &Free; - } - } - - SBlackBox& operator=(const SBlackBox& rhs) - { - set(rhs.format, rhs.data, rhs.size); - return *this; - } - - ~SBlackBox() - { - set("", 0, 0); - } - - static void Free(void* ptr) - { - CryModuleFree(ptr); - } - }; -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_BLACKBOX_H diff --git a/Code/CryEngine/CryCommon/Serialization/BoostSharedPtr.h b/Code/CryEngine/CryCommon/Serialization/BoostSharedPtr.h deleted file mode 100644 index 7d1d8591d0..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/BoostSharedPtr.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include - -#include "ClassFactory.h" - -template -class BoostSharedPtrSerializer - : public Serialization::IPointer -{ -public: - BoostSharedPtrSerializer(AZStd::shared_ptr& ptr) - : m_ptr(ptr) - { - } - - const char* registeredTypeName() const override - { - if (m_ptr) - { - return factoryOverride().getRegisteredTypeName(m_ptr.get()); - } - else - { - return ""; - } - } - - void create(const char* registeredTypeName) const override - { - CRY_ASSERT(!m_ptr || m_ptr.use_count() == 1); - if (registeredTypeName && registeredTypeName[0] != '\0') - { - m_ptr.reset(factoryOverride().create(registeredTypeName)); - } - else - { - m_ptr.reset(); - } - } - - Serialization::TypeID baseType() const override - { - return Serialization::TypeID::get(); - } - - virtual Serialization::SStruct serializer() const override - { - return Serialization::SStruct(*m_ptr); - } - - void* get() const - { - return reinterpret_cast(m_ptr.get()); - } - - const void* handle() const - { - return &m_ptr; - } - - Serialization::TypeID pointerType() const override - { - return Serialization::TypeID::get >(); - } - - Serialization::ClassFactory* factory() const override - { - return &factoryOverride(); - } - - virtual Serialization::ClassFactory& factoryOverride() const - { - return Serialization::ClassFactory::the(); - } - -protected: - AZStd::shared_ptr& m_ptr; -}; - -namespace AZStd -{ - template - bool Serialize(Serialization::IArchive& ar, AZStd::shared_ptr& ptr, const char* name, const char* label) - { - BoostSharedPtrSerializer serializer(ptr); - return ar(static_cast(serializer), name, label); - } -} diff --git a/Code/CryEngine/CryCommon/Serialization/CRCRef.h b/Code/CryEngine/CryCommon/Serialization/CRCRef.h deleted file mode 100644 index b26195dd99..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CRCRef.h +++ /dev/null @@ -1,30 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREF_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREF_H -#pragma once - -template -struct SCRCRef; - -namespace Serialization -{ - class IArchive; -} - -template -bool Serialize(Serialization::IArchive& ar, SCRCRef& crcRef, const char* name, const char* label); - -#include "CRCRefImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREF_H diff --git a/Code/CryEngine/CryCommon/Serialization/CRCRefImpl.h b/Code/CryEngine/CryCommon/Serialization/CRCRefImpl.h deleted file mode 100644 index 28b0f4305b..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CRCRefImpl.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREFIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREFIMPL_H -#pragma once - -#include "IArchive.h" -#include "Serializer.h" - -template -class CRCRefSerializer - : public Serialization::IString -{ -public: - CRCRefSerializer(TCRCRef& crcRef) - : m_crcRef(crcRef) - { - } - - virtual void set(const char* value) - { - m_crcRef.SetByString(value); - } - - virtual const char* get() const - { - return m_crcRef.c_str(); - } - - const void* handle() const - { - return &m_crcRef; - } - - Serialization::TypeID type() const - { - return Serialization::TypeID::get(); - } - - - TCRCRef& m_crcRef; -}; - - -template -class CCRCRefSerializerNoStrings -{ -public: - CCRCRefSerializerNoStrings(struct SCRCRef& crcRef) - : crc(crcRef.crc) - { - } - - bool Serialize(Serialization::IArchive& ar) - { - return ar(crc, "CRC", "CRC"); - } - - typedef typename THash::TInt TInt; - TInt& crc; -}; - - - -template -bool Serialize(Serialization::IArchive& ar, struct SCRCRef& crcRef, const char* name, const char* label) -{ - if (StoreStrings == 0) - { - if (ar.IsInput()) - { - SCRCRef crcCopy; - ar(CCRCRefSerializerNoStrings(crcCopy), name, label); - if (crcCopy.crc != THash::INVALID) - { - crcRef = crcCopy; - return true; - } - } - else if (ar.IsOutput()) - { - return ar(CCRCRefSerializerNoStrings(crcRef), name, label); - } - } - - CRCRefSerializer > crcRefSerializer(crcRef); - return ar(static_cast(crcRefSerializer), name, label); -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRCREFIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Callback.h b/Code/CryEngine/CryCommon/Serialization/Callback.h deleted file mode 100644 index 0a0ce2b7f8..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Callback.h +++ /dev/null @@ -1,184 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CALLBACK_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CALLBACK_H -#pragma once - -#include - -namespace Serialization -{ - struct ICallback - { - virtual bool SerializeValue(IArchive& ar, const char* name, const char* value) = 0; - virtual ICallback* Clone() = 0; - virtual void Release() = 0; - virtual TypeID Type() const = 0; - - typedef AZStd::function ApplyFunction; - virtual void Call(const ApplyFunction&) = 0; - }; - - template - struct CallbackSimple - : ICallback - { - typedef AZStd::function CallbackFunction; - T* value; - T oldValue; - CallbackFunction callback; - - CallbackSimple(T* value, const T& oldValue, const AZStd::function& callback) - : value(value) - , oldValue(oldValue) - , callback(callback) - { - } - - ICallback* Clone() { return new CallbackSimple(0, oldValue, callback); } - void Release() { delete this; } - bool SerializeValue(IArchive& ar, const char* name, const char* label) { return ar(*value, name, label); } - TypeID Type() const{ return TypeID::get(); } - - void Call(const ApplyFunction& applyFunction) - { - T newValue; - applyFunction((void*)&newValue, TypeID::get()); - if (oldValue != newValue) - { - callback(newValue); - oldValue = newValue; - } - } - }; - - template - struct CallbackWithDecorator - : ICallback - { - typedef AZStd::function CallbackFunction; - typedef AZStd::function DecoratorFunction; - - T oldValue; - T* value; - CallbackFunction callback; - DecoratorFunction decorator; - - CallbackWithDecorator(T* value, - const T& oldValue, - const CallbackFunction& callback, - const DecoratorFunction& decorator) - : value(value) - , oldValue(oldValue) - , callback(callback) - , decorator(decorator) - { - } - - ICallback* Clone() { return new CallbackWithDecorator(0, oldValue, callback, decorator); } - void Release() { delete this; } - bool SerializeValue(IArchive& ar, const char* name, const char* label) { return ar(decorator(*value), name, label); } - TypeID Type() const{ return TypeID::get(); } - - void Call(const ApplyFunction& applyFunction) - { - T newValue; - Decorator dec = decorator(newValue); - applyFunction((void*)&dec, TypeID::get()); - if (oldValue != newValue) - { - callback(newValue); - oldValue = newValue; - } - } - }; - - - - namespace Detail - { - template - struct MethodReturnType - { - typedef void type; - }; - - template - struct MethodReturnType - { - typedef ReturnType type; - }; - - template - struct OperatorBracketsReturnType - { - typedef typename MethodReturnType::type Type; - }; - } - - template - CallbackSimple - Callback(T& value, const CallbackFunc& callback) - { - return CallbackSimple(&value, value, AZStd::function(callback)); - } - - - template - CallbackWithDecorator::Type> - Callback(T& value, const CallbackFunc& callback, const DecoratorFunc& decorator) - { - typedef typename Detail::OperatorBracketsReturnType::Type Decorator; - return CallbackWithDecorator(&value, value, - AZStd::function(callback), - AZStd::function(decorator)); - } - - - template - bool Serialize(IArchive& ar, CallbackSimple& callback, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(static_cast(callback), name, label); - } - else - { - if (!ar(*callback.value, name, label)) - { - return false; - } - return true; - } - } - - template - bool Serialize(IArchive& ar, CallbackWithDecorator& callback, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(static_cast(callback), name, label); - } - else - { - if (!ar(*callback.value, name, label)) - { - return false; - } - return true; - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CALLBACK_H diff --git a/Code/CryEngine/CryCommon/Serialization/ClassFactory.h b/Code/CryEngine/CryCommon/Serialization/ClassFactory.h deleted file mode 100644 index 4734a566eb..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/ClassFactory.h +++ /dev/null @@ -1,376 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORY_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORY_H -#pragma once - -#include -#include - -#include "Serialization/Assert.h" -#include "Serialization/IClassFactory.h" -#include "Serialization/TypeID.h" - -namespace Serialization { - class IArchive; - - class ClassFactoryManager - { - public: - static ClassFactoryManager& the() - { - static ClassFactoryManager factoryManager; - return factoryManager; - } - - const IClassFactory* find(TypeID baseType) const - { - lazyRegisterFactories(); - Factories::const_iterator it = factories_.find(baseType); - if (it == factories_.end()) - { - return 0; - } - else - { - return it->second; - } - } - - void registerFactory([[maybe_unused]] TypeID type, IClassFactory* factory) - { - factory->m_next = m_head; - m_head = factory; - } - protected: - void lazyRegisterFactories() const - { - if (m_head) - { - IClassFactory* factory = m_head; - while (factory) - { - const_cast(this)->factories_[factory->baseType_] = factory; - factory = factory->m_next; - } - const_cast(this)->m_head = nullptr; - } - } - - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> Factories; - Factories factories_; - IClassFactory* m_head = nullptr; - }; - - template - class ClassFactory - : public IClassFactory - { - public: - static ClassFactory& the() - { - static AZStd::aligned_storage_for_t storage; - if (s_instance != (decltype(s_instance))&storage) - { - s_instance = new(&storage) ClassFactory(); - } - return *s_instance; - } - - static void destroy() - { - if (s_instance) - { - s_instance->~ClassFactory(); - s_instance = nullptr; - } - } - - class CreatorBase - { - public: - virtual ~CreatorBase() {} - virtual BaseType* create() const = 0; - virtual const TypeDescription& description() const{ return *description_; } - virtual void* vptr() const { return vptr_; } - virtual TypeID typeID() const = 0; - protected: - const TypeDescription* description_ = nullptr; - void* vptr_ = nullptr; - public: - CreatorBase* next; - }; - - static void* extractVPtr(BaseType* ptr) - { - return *((void**)ptr); - } - - template - struct Annotation - { - Annotation(IClassFactory* factory, const char* name, const char* value) { static_cast*>(factory)->addAnnotation(name, value); } - }; - - template - class Creator - : public CreatorBase - { - public: - Creator(const TypeDescription* description, ClassFactory* factory = nullptr) - { - this->description_ = description; - - if (!factory) - { - factory = &ClassFactory::the(); - } - - factory->registerCreator(this); - } - - void* vptr() const override - { - if (!this->vptr_) - { - Derived vptrProbe; - const_cast(this)->vptr_ = extractVPtr(&vptrProbe); - } - return this->vptr_; - } - - BaseType* create() const override { return new Derived(); } - TypeID typeID() const override { return Serialization::TypeID::get(); } - }; - - ClassFactory() - : IClassFactory(TypeID::get()) - { - ClassFactoryManager::the().registerFactory(baseType_, this); - } - - ~ClassFactory() - { - m_data->~Data(); - m_data = nullptr; - } - - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> TypeToCreatorMap; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> VPtrToCreatorMap; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> RegisteredNameToTypeID; - typedef AZStd::unordered_map >, AZStd::hash, AZStd::equal_to, AZ::StdLegacyAllocator> AnnotationMap; - - virtual BaseType* create(const char* registeredName) const - { - lazyRegisterCreators(); - if (!registeredName) - { - return 0; - } - if (registeredName[0] == '\0') - { - return 0; - } - typename TypeToCreatorMap::const_iterator it = m_data->typeToCreatorMap_.find(registeredName); - if (it != m_data->typeToCreatorMap_.end()) - { - return it->second->create(); - } - else - { - return 0; - } - } - - virtual const char* getRegisteredTypeName(BaseType* ptr) const - { - lazyRegisterCreators(); - if (ptr == 0) - { - return ""; - } - void* vptr = extractVPtr(ptr); - typename VPtrToCreatorMap::const_iterator it = m_data->vptrToCreatorMap_.find(vptr); - if (it == m_data->vptrToCreatorMap_.end()) - { - return ""; - } - return it->second->description().name(); - } - - BaseType* createByIndex(int index) const - { - lazyRegisterCreators(); - YASLI_ASSERT(size_t(index) < m_data->creators_.size()); - return m_data->creators_[index]->create(); - } - - void serializeNewByIndex(IArchive& ar, int index, const char* name, const char* label) - { - lazyRegisterCreators(); - YASLI_ESCAPE(size_t(index) < m_data->creators_.size(), return ); - BaseType* ptr = m_data->creators_[index]->create(); - ar(*ptr, name, label); - delete ptr; - } - // from ClassFactoryInterface: - size_t size() const{ return m_data->creators_.size(); } - const TypeDescription* descriptionByIndex(int index) const override - { - lazyRegisterCreators(); - if (size_t(index) >= int(m_data->creators_.size())) - { - return 0; - } - return &m_data->creators_[index]->description(); - } - - const TypeDescription* descriptionByRegisteredName(const char* name) const override - { - lazyRegisterCreators(); - const size_t numCreators = m_data->creators_.size(); - for (size_t i = 0; i < numCreators; ++i) - { - if (strcmp(m_data->creators_[i]->description().name(), name) == 0) - { - return &m_data->creators_[i]->description(); - } - } - return 0; - } - // ^^^ - - TypeID typeIDByRegisteredName(const char* registeredTypeName) const - { - lazyRegisterCreators(); - RegisteredNameToTypeID::const_iterator it = m_data->registeredNameToTypeID_.find(registeredTypeName); - if (it == m_data->registeredNameToTypeID_.end()) - { - return TypeID(); - } - return it->second; - } - - const char* findAnnotation(const char* registeredTypeName, const char* name) const - { - lazyRegisterCreators(); - TypeID typeID = typeIDByRegisteredName(registeredTypeName); - AnnotationMap::const_iterator it = m_data->annotations_.find(typeID); - if (it == m_data->annotations_.end()) - { - return ""; - } - for (size_t i = 0; i < it->second.size(); ++i) - { - if (strcmp(it->second[i].first, name) == 0) - { - return it->second[i].second; - } - } - return ""; - } - void unregisterCreator(const TypeDescription& typeDescription) - { - auto creator = m_data->typeToCreatorMap_.find(typeDescription.name()); - if (creator != m_data->typeToCreatorMap_.end()) - { - m_data->creators_.erase(std::find(m_data->creators_.begin(), m_data->creators_.end(), m_data->creator->second)); - m_data->vptrToCreatorMap_.erase(m_data->vptrToCreatorMap_.find(creator->second->vptr())); - m_data->typeToCreatorMap_.erase(creator); - } - } - - protected: - virtual void registerCreator(CreatorBase* creator) - { - creator->next = creatorsList; - creatorsList = creator; - } - - void lazyRegisterCreators() const - { - if (!m_data) - { - const_cast(this)->m_data = ::new((void*)&m_dataStorage) Data(); - for (CreatorBase* creator = creatorsList; creator; creator = creator->next) - { - if (!const_cast(this)->m_data->typeToCreatorMap_.insert(AZStd::make_pair(creator->description().name(), creator)).second) - { - YASLI_ASSERT(0 && "Type registered twice in the same factory. Was SERIALIZATION_CLASS_NAME put into header file by mistake?"); - } - const_cast(this)->m_data->creators_.push_back(creator); - const_cast(this)->m_data->registeredNameToTypeID_[creator->description().name()] = creator->typeID(); - const_cast(this)->m_data->vptrToCreatorMap_[creator->vptr()] = creator; - } - } - } - - template - void addAnnotation(const char* name, const char* value) - { - addAnnotation(Serialization::TypeID::get(), name, value); - } - - virtual void addAnnotation(const Serialization::TypeID& id, const char* name, const char* value) - { - lazyRegisterCreators(); - m_data->annotations_[id].push_back(std::make_pair(name, value)); - } - - CreatorBase* creatorsList = nullptr; - static ClassFactory* s_instance; - - struct Data - { - TypeToCreatorMap typeToCreatorMap_; - AZStd::vector creators_; - VPtrToCreatorMap vptrToCreatorMap_; - RegisteredNameToTypeID registeredNameToTypeID_; - AnnotationMap annotations_; - }; - Data* m_data = nullptr; - AZStd::aligned_storage_for_t m_dataStorage; - }; - - template - ClassFactory* ClassFactory::s_instance = nullptr; -} - -#define SERIALIZATION_CLASS_NULL(BaseType, name) \ - namespace { \ - bool BaseType##_NullRegistered = Serialization::ClassFactory::the().setNullLabel(name); \ - } - -#define SERIALIZATION_CLASS_NAME(BaseType, Type, name, label) \ - static const Serialization::TypeDescription Type##BaseType##_DerivedDescription(name, label); \ - static Serialization::ClassFactory::Creator Type##BaseType##_Creator(&Type##BaseType##_DerivedDescription); \ - int dummyForType_##Type##BaseType; - -#define SERIALIZATION_CLASS_NAME_FOR_FACTORY(Factory, BaseType, Type, name, label) \ - static const Serialization::TypeDescription Type##BaseType##_DerivedDescription(name, label); \ - static Serialization::ClassFactory::Creator Type##BaseType##_Creator(&Type##BaseType##_DerivedDescription, &(Factory)); - -#define SERIALIZATION_CLASS_ANNOTATION(BaseType, Type, attributeName, attributeValue) \ - static Serialization::ClassFactory::Annotation Type##BaseType##_Annotation(&Serialization::ClassFactory::the(), attributeName, attributeValue); - -#define SERIALIZATION_CLASS_ANNOTATION_FOR_FACTORY(factory, BaseType, Type, attributeName, attributeValue) \ - static Serialization::ClassFactory::Annotation Type##BaseType##_Annotation(&factory, attributeName, attributeValue); - -#define SERIALIZATION_FORCE_CLASS(BaseType, Type) \ - extern int dummyForType_##Type##BaseType; \ - int* dummyForTypePtr_##Type##BaseType = &dummyForType_##Type##BaseType + 1; - -#include "ClassFactoryImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORY_H diff --git a/Code/CryEngine/CryCommon/Serialization/ClassFactoryImpl.h b/Code/CryEngine/CryCommon/Serialization/ClassFactoryImpl.h deleted file mode 100644 index f3d034fb51..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/ClassFactoryImpl.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORYIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORYIMPL_H -#pragma once - -#include "IArchive.h" -#include "IClassFactory.h" -#include "STL.h" -#include "ClassFactory.h" -#include "Strings.h" - -namespace Serialization { - inline bool Serialize(Serialization::IArchive& ar, Serialization::TypeNameWithFactory& value, const char* name, [[maybe_unused]] const char* label) - { - if (!ar(value.registeredName, name)) - { - return false; - } - - if (ar.IsInput()) - { - const TypeDescription* desc = value.factory->descriptionByRegisteredName(value.registeredName.c_str()); - if (!desc) - { - ar.Error(value, "Unable to read TypeID: unregistered type name: \'%s\'", value.registeredName.c_str()); - value.registeredName.clear(); - return false; - } - } - return true; - } -} - - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CLASSFACTORYIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Color.h b/Code/CryEngine/CryCommon/Serialization/Color.h deleted file mode 100644 index 1b4f612bcd..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Color.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLOR_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLOR_H -#pragma once - -#include -#include - -template -inline bool Serialize(Serialization::IArchive& ar, Color_tpl& c, const char* name, const char* label); - -namespace Serialization -{ - struct Vec3AsColor - { - Vec3& v; - Vec3AsColor(Vec3& v) - : v(v) {} - - void Serialize(Serialization::IArchive& ar) - { - ar(Range(v.x, 0.0f, 1.0f), "r", "^"); - ar(Range(v.y, 0.0f, 1.0f), "g", "^"); - ar(Range(v.z, 0.0f, 1.0f), "b", "^"); - } - }; - - inline bool Serialize(Serialization::IArchive& ar, Vec3AsColor& c, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct(c), name, label); - } - else - { - typedef float (* Array)[3]; - return ar(*((Array) & c.v.x), name, label); - } - } -} - -#include "ColorImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLOR_H diff --git a/Code/CryEngine/CryCommon/Serialization/ColorImpl.h b/Code/CryEngine/CryCommon/Serialization/ColorImpl.h deleted file mode 100644 index cf7f5886d7..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/ColorImpl.h +++ /dev/null @@ -1,53 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLORIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLORIMPL_H -#pragma once - -#include "Color.h" - -////////////////////////////////////////////////////////////////////////// -template -struct SerializableColor_tpl - : Color_tpl -{ - static float ColorRangeMin(float) { return 0.0f; } - static float ColorRangeMax(float) { return 1.0f; } - static unsigned char ColorRangeMin(unsigned char) { return 0; } - static unsigned char ColorRangeMax(unsigned char) { return 255; } - - void Serialize(Serialization::IArchive& ar) - { - ar(Serialization::Range(Color_tpl::r, ColorRangeMin(Color_tpl::r), ColorRangeMax(Color_tpl::r)), "r", "^"); - ar(Serialization::Range(Color_tpl::g, ColorRangeMin(Color_tpl::g), ColorRangeMax(Color_tpl::g)), "g", "^"); - ar(Serialization::Range(Color_tpl::b, ColorRangeMin(Color_tpl::b), ColorRangeMax(Color_tpl::b)), "b", "^"); - ar(Serialization::Range(Color_tpl::a, ColorRangeMin(Color_tpl::a), ColorRangeMax(Color_tpl::a)), "a", "^"); - } -}; - -template -bool Serialize(Serialization::IArchive& ar, Color_tpl& c, const char* name, const char* label) -{ - if (ar.IsEdit()) - { - return Serialize(ar, static_cast&>(c), name, label); - } - else - { - typedef T (& Array)[4]; - return ar((Array)c, name, label); - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_COLORIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/CryExtension.h b/Code/CryEngine/CryCommon/Serialization/CryExtension.h deleted file mode 100644 index ed4e99fba1..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryExtension.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSION_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSION_H -#pragma once - -#ifdef GetClassName -#undef GetClassName -#endif -#include - -namespace Serialization -{ - // Allows to have AZStd::shared_ptr but serialize it by - // interface-casting to TSerializable, i.e. implementing Serialization through - // separate interface. - template - struct CryExtensionPointer - { - AZStd::shared_ptr& ptr; - - CryExtensionPointer(AZStd::shared_ptr& _ptr) - : ptr(_ptr) {} - void Serialize(Serialization::IArchive& ar); - }; -} - -// This function treats T as a type derived from CryUnknown type. -template -bool Serialize(Serialization::IArchive& ar, AZStd::shared_ptr& ptr, const char* name, const char* label); - -#include "CryExtensionImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSION_H diff --git a/Code/CryEngine/CryCommon/Serialization/CryExtensionImpl.h b/Code/CryEngine/CryCommon/Serialization/CryExtensionImpl.h deleted file mode 100644 index e976163d55..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryExtensionImpl.h +++ /dev/null @@ -1,281 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSIONIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSIONIMPL_H -#pragma once - -#include -#include -#include -#include - -namespace Serialization { - // Generate user-friendly class name, e.g. convert - // "AnimationPoseModifier_FootStore" -> "Foot Store" - inline string MakePrettyClassName(const char* className) - { - const char* firstSep = strchr(className, '_'); - if (!firstSep) - { - // name doesn't follow expected convention, return as is - return className; - } - - const char* start = firstSep + 1; - string result; - result.reserve(strlen(start) + 4); - - const char* p = start; - while (*p != '\0') - { - if (*p >= 'A' && *p <= 'Z' && - *(p - 1) >= 'a' && *(p - 1) <= 'z') - { - result += ' '; - } - if (*p == '_') - { - result += ' '; - } - else - { - result += *p; - } - ++p; - } - - return result; - } - - // Provides Serialization::IClassFactory interface for classes - // registered with CryExtension to IArchive. - // - // TSerializable can be used to expose Serialize method through - // a separate interface, rathern than TBase. Safe to missing - // as QueryInterface is used to check its presence. - template - class CryExtensionClassFactory - : public Serialization::IClassFactory - { - public: - size_t size() const override - { - return m_types.size(); - } - - static CryExtensionClassFactory& the() - { - static CryExtensionClassFactory instance; - return instance; - } - - CryExtensionClassFactory() - : IClassFactory(Serialization::TypeID::get()) - { - setNullLabel("[ None ]"); - ICryFactoryRegistry* factoryRegistry = gEnv->pSystem->GetCryFactoryRegistry(); - - size_t factoryCount = 0; - factoryRegistry->IterateFactories(cryiidof(), 0, factoryCount); - - if (factoryCount) - { - string sharedPrefix; - bool hasSharedPrefix = true; - AZStd::unique_ptr factories(new ICryFactory*[factoryCount]); - factoryRegistry->IterateFactories(cryiidof(), factories.get(), factoryCount); - - for (size_t i = 0; i < factoryCount; ++i) - { - ICryFactory* factory = factories[i]; - if (factory->ClassSupports(cryiidof())) - { - m_factories.push_back(factory); - if (hasSharedPrefix) - { - // make sure that shared prefix is the same for all the names - const char* name = factory->GetName(); - const char* lastPrefixCharacter = strchr(name, '_'); - if (lastPrefixCharacter == 0) - { - hasSharedPrefix = false; - } - else - { - if (!sharedPrefix.empty()) - { - if (strncmp(name, sharedPrefix.c_str(), sharedPrefix.size()) != 0) - { - hasSharedPrefix = false; - } - } - else - { - sharedPrefix.assign(name, lastPrefixCharacter + 1); - } - } - } - } - } - - size_t usableFactoriesCount = m_factories.size(); - m_types.reserve(usableFactoriesCount); - m_labels.reserve(usableFactoriesCount); - - for (size_t i = 0; i < usableFactoriesCount; ++i) - { - ICryFactory* factory = m_factories[i]; - m_classIds.push_back(factory->GetClassID()); - const char* name = factory->GetName(); - m_labels.push_back(MakePrettyClassName(name)); - if (hasSharedPrefix) - { - name += sharedPrefix.size(); - } - m_types.push_back(Serialization::TypeDescription(name, m_labels.back().c_str())); - } - } - } - - const Serialization::TypeDescription* descriptionByIndex(int index) const override - { - if (size_t(index) >= m_types.size()) - { - return 0; - } - return &m_types[index]; - } - - const Serialization::TypeDescription* descriptionByRegisteredName(const char* registeredName) const override - { - size_t count = m_types.size(); - for (size_t i = 0; i < m_types.size(); ++i) - { - if (strcmp(m_types[i].name(), registeredName) == 0) - { - return &m_types[i]; - } - } - return 0; - } - - const char* findAnnotation(const char* typeName, const char* name) const override { return ""; } - - void serializeNewByIndex(IArchive& ar, int index, const char* name, const char* label) override - { - if (size_t(index) >= m_types.size()) - { - return; - } - AZStd::shared_ptr ptr(create(m_types[index].name())); - if (TSerializable* ser = cryinterface_cast(ptr.get())) - { - ar(*ser, name, label); - } - } - - AZStd::shared_ptr create(const char* registeredName) - { - size_t count = m_types.size(); - for (size_t i = 0; i < count; ++i) - { - if (strcmp(m_types[i].name(), registeredName) == 0) - { - return AZStd::static_pointer_cast(m_factories[i]->CreateClassInstance()); - } - } - return AZStd::shared_ptr(); - } - - const char* getRegisteredTypeName(const AZStd::shared_ptr& ptr) const - { - if (!ptr.get()) - { - return ""; - } - CryInterfaceID id = AZStd::static_pointer_cast(ptr)->GetFactory()->GetClassID(); - size_t count = m_classIds.size(); - for (size_t i = 0; i < count; ++i) - { - if (m_classIds[i] == id) - { - return m_types[i].name(); - } - } - return ""; - } - - private: - std::vector m_types; - std::vector m_labels; - std::vector m_factories; - std::vector m_classIds; - }; - - // Exposes CryExtension shared_ptr<> as serializeable type for Serialization::IArchive - template - class CryExtensionSharedPtr - : public Serialization::IPointer - { - public: - CryExtensionSharedPtr(AZStd::shared_ptr& ptr) - : m_ptr(ptr) - {} - - const char* registeredTypeName() const override - { - if (m_ptr) - { - return factory()->getRegisteredTypeName(m_ptr); - } - else - { - return ""; - } - } - - void create(const char* registeredTypeName) const override - { - if (registeredTypeName[0] != '\0') - { - m_ptr = factory()->create(registeredTypeName); - } - else - { - m_ptr.reset((T*)0); - } - } - - Serialization::TypeID baseType() const{ return Serialization::TypeID::get(); } - virtual Serialization::SStruct serializer() const override - { - if (TSerializable* ser = cryinterface_cast(m_ptr.get())) - { - return Serialization::SStruct(*ser); - } - else - { - return Serialization::SStruct(); - } - } - void* get() const override { return reinterpret_cast(m_ptr.get()); } - const void* handle() const override { return &m_ptr; } - Serialization::TypeID pointerType() const override { return Serialization::TypeID::get >(); } - CryExtensionClassFactory* factory() const override { return &CryExtensionClassFactory::the(); } - protected: - AZStd::shared_ptr& m_ptr; - }; -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYEXTENSIONIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/CryName.h b/Code/CryEngine/CryCommon/Serialization/CryName.h deleted file mode 100644 index 978af33379..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryName.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAME_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAME_H -#pragma once - -namespace Serialization { - class IArchive; -} - -inline bool Serialize(Serialization::IArchive & ar, class CCryName & cryName, const char* name, const char* label); - -#include "CryNameImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAME_H diff --git a/Code/CryEngine/CryCommon/Serialization/CryNameImpl.h b/Code/CryEngine/CryCommon/Serialization/CryNameImpl.h deleted file mode 100644 index e307892fd3..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryNameImpl.h +++ /dev/null @@ -1,61 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAMEIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAMEIMPL_H -#pragma once - -#include "CryName.h" -#include "IArchive.h" - -class CryNameSerializer - : public Serialization::IString -{ -public: - CryNameSerializer(CCryName& s) - : m_s(s) - { - } - - virtual void set(const char* value) - { - m_s = value; - } - - virtual const char* get() const - { - return m_s.c_str(); - } - - virtual const void* handle() const - { - return &m_s; - } - - virtual Serialization::TypeID type() const - { - return Serialization::TypeID::get(); - } - - CCryName& m_s; -}; - - -inline bool Serialize(Serialization::IArchive& ar, CCryName& cryName, const char* name, const char* label) -{ - CryNameSerializer serializer(cryName); - return ar(static_cast(serializer), name, label); -} - - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_CRYNAMEIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/CryStrings.h b/Code/CryEngine/CryCommon/Serialization/CryStrings.h deleted file mode 100644 index 560f64c045..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryStrings.h +++ /dev/null @@ -1,36 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "CryFixedString.h" - -#include "Serialization/Serializer.h" - -namespace Serialization -{ - class IArchive; -} - -// Note : if you are looking for the CryStringT serialization, it is handled in Serialization/STL.h - -template< size_t N > -bool Serialize(Serialization::IArchive& ar, CryFixedStringT< N >& value, const char* name, const char* label); - -template< size_t N > -bool Serialize(Serialization::IArchive& ar, CryStackStringT< char, N >& value, const char* name, const char* label); - -template< size_t N > -bool Serialize(Serialization::IArchive& ar, CryStackStringT< wchar_t, N >& value, const char* name, const char* label); - -#include "Serialization/CryStringsImpl.h" diff --git a/Code/CryEngine/CryCommon/Serialization/CryStringsImpl.h b/Code/CryEngine/CryCommon/Serialization/CryStringsImpl.h deleted file mode 100644 index 41de581b36..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/CryStringsImpl.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "Serialization/IArchive.h" -#include "Serialization/CryStrings.h" - -namespace Serialization -{ - template< class TFixedStringClass > - class CFixedStringSerializer - : public IString - { - public: - CFixedStringSerializer(TFixedStringClass& str) - : str_(str) { } - - void set(const char* value) { str_ = value; } - const char* get() const { return str_.c_str(); } - const void* handle() const { return &str_; } - TypeID type() const { return TypeID::get(); } - private: - TFixedStringClass& str_; - }; - - template< class TFixedStringClass > - class CFixedWStringSerializer - : public IWString - { - public: - CFixedWStringSerializer(TFixedStringClass& str) - : str_(str) { } - - void set(const wchar_t* value) { str_ = value; } - const wchar_t* get() const { return str_.c_str(); } - const void* handle() const { return &str_; } - TypeID type() const { return TypeID::get(); } - private: - TFixedStringClass& str_; - }; -} - -template< size_t N > -inline bool Serialize(Serialization::IArchive& ar, CryFixedStringT< N >& value, const char* name, const char* label) -{ - Serialization::CFixedStringSerializer< CryFixedStringT< N > > str(value); - return ar(static_cast(str), name, label); -} - -template< size_t N > -inline bool Serialize(Serialization::IArchive& ar, CryStackStringT< char, N >& value, const char* name, const char* label) -{ - Serialization::CFixedStringSerializer< CryStackStringT< char, N > > str(value); - return ar(static_cast(str), name, label); -} - -template< size_t N > -inline bool Serialize(Serialization::IArchive& ar, CryStackStringT< wchar_t, N >& value, const char* name, const char* label) -{ - Serialization::CFixedWStringSerializer< CryStackStringT< wchar_t, N > > str(value); - return ar(static_cast(str), name, label); -} - diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ActionButton.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ActionButton.h deleted file mode 100644 index 2e8e07f597..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ActionButton.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include -#include -#include - -namespace Serialization -{ - struct IActionButton; - - DECLARE_SMART_POINTERS(IActionButton) - - struct IActionButton - { - virtual ~IActionButton() {} - - virtual void Callback() const = 0; - virtual const char* Icon() const = 0; - virtual IActionButtonPtr Clone() const = 0; - }; - - typedef AZStd::function FunctorActionButtonCallback; - - struct FunctorActionButton - : public IActionButton - { - FunctorActionButtonCallback callback; - string icon; - - explicit FunctorActionButton(const FunctorActionButtonCallback& callback, const char* icon = "") - : callback(callback) - , icon(icon) - { - } - - // IActionButton - - virtual void Callback() const override - { - if (callback) - { - callback(); - } - } - - virtual const char* Icon() const override - { - return icon.c_str(); - } - - virtual IActionButtonPtr Clone() const override - { - return IActionButtonPtr(new FunctorActionButton(callback, icon.c_str())); - } - - // ~IActionButton - }; - - inline bool Serialize(Serialization::IArchive& ar, FunctorActionButton& button, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(button)), name, label); - } - else - { - return false; - } - } - - inline FunctorActionButton ActionButton(const FunctorActionButtonCallback& callback, const char* icon = "") - { - return FunctorActionButton(callback, icon); - } -} - diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlags.h b/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlags.h deleted file mode 100644 index 1e23ecee27..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlags.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_BITFLAGS_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_BITFLAGS_H -#pragma once - -#include - -namespace Serialization { - class IArchive; - - struct BitFlagsWrapper - { - int* variable; - unsigned int visibleMask; - const CEnumDescription* description; - - void Serialize(IArchive& ar); - }; - - template - BitFlagsWrapper BitFlags(Enum& value) - { - BitFlagsWrapper wrapper; - wrapper.variable = (int*)&value; - wrapper.visibleMask = ~0U; - wrapper.description = &getEnumDescription(); - return wrapper; - } - - template - BitFlagsWrapper BitFlags(int& value, int visibleMask = ~0) - { - BitFlagsWrapper wrapper; - wrapper.variable = &value; - wrapper.visibleMask = visibleMask; - wrapper.description = &getEnumDescription(); - return wrapper; - } - - template - BitFlagsWrapper BitFlags(unsigned int& value, unsigned int visibleMask = ~0) - { - BitFlagsWrapper wrapper; - wrapper.variable = (int*)&value; - wrapper.visibleMask = visibleMask; - wrapper.description = &getEnumDescription(); - return wrapper; - } -} - -#include "BitFlagsImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_BITFLAGS_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlagsImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlagsImpl.h deleted file mode 100644 index 77b48fd1f0..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/BitFlagsImpl.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_BITFLAGSIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_BITFLAGSIMPL_H -#pragma once - -#include "Serialization/IArchive.h" - -namespace Serialization { - inline void BitFlagsWrapper::Serialize(IArchive& ar) - { - const Serialization::CEnumDescription& desc = *description; - int count = desc.count(); - if (ar.IsInput()) - { - int previousValue = *variable; - for (int i = 0; i < count; ++i) - { - int flagValue = desc.valueByIndex(i); - if (!(flagValue & visibleMask)) - { - continue; - } - bool flag = (previousValue & flagValue) == flagValue; - bool previousFlag = flag; - ar(flag, desc.nameByIndex(i), desc.labelByIndex(i)); - if (flag != previousFlag) - { - if (flag) - { - *variable |= flagValue; - } - else - { - *variable &= ~flagValue; - } - } - } - } - else - { - for (int i = 0; i < count; ++i) - { - int flagValue = desc.valueByIndex(i); - if (!(flagValue & visibleMask)) - { - continue; - } - bool flag = (*variable & flagValue) == flagValue; - ar(flag, desc.nameByIndex(i), desc.labelByIndex(i)); - } - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_BITFLAGSIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPicker.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPicker.h deleted file mode 100644 index 146e7bf42f..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPicker.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKER_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKER_H -#pragma once - -#include -#include - -#include - -namespace Serialization -{ - class IArchive; - - struct ColorPicker - { - ColorF* color; - - explicit ColorPicker(ColorF& color_) - : color(&color_) - { - } - - // the function should stay virtual to ensure cross-dll calls are using right heap - virtual void SetColor(const ColorF* color_){* color = *color_; } - }; - - bool Serialize(Serialization::IArchive& ar, Serialization::ColorPicker& value, const char* name, const char* label); -} // namespace Serialization - -#include "ColorPickerImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKER_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPickerImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPickerImpl.h deleted file mode 100644 index 6585f40a91..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ColorPickerImpl.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKERIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKERIMPL_H -#pragma once - -#include "../Color.h" - -namespace Serialization -{ - inline bool Serialize(Serialization::IArchive& ar, Serialization::ColorPicker& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(value), name, label); - } - else - { - return ar(*value.color, name, label); - } - } -} // namespace Serialization - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_COLORPICKERIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/JointName.h b/Code/CryEngine/CryCommon/Serialization/Decorators/JointName.h deleted file mode 100644 index 69195c20bf..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/JointName.h +++ /dev/null @@ -1,19 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAME_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAME_H -#pragma once - -#include -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAME_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/JointNameImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/JointNameImpl.h deleted file mode 100644 index ad168a92a3..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/JointNameImpl.h +++ /dev/null @@ -1,19 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAMEIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAMEIMPL_H -#pragma once - - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_JOINTNAMEIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrame.h b/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrame.h deleted file mode 100644 index 39841623f9..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrame.h +++ /dev/null @@ -1,117 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_LOCALFRAME_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_LOCALFRAME_H -#pragma once - -#include -#include "Serialization/Math.h" - -namespace Serialization -{ - class IArchive; - - struct LocalPosition - { - Vec3* value; - int space; - const char* parentName; - const void* handle; - - LocalPosition(Vec3& _vec, int _space, const char* _parentName, const void* _handle) - : value(&_vec) - , space(_space) - , parentName(_parentName) - , handle(_handle) - { - } - - void Serialize(IArchive& ar); - }; - - struct LocalOrientation - { - Quat* value; - int space; - const char* parentName; - const void* handle; - - LocalOrientation(Quat& _vec, int _space, const char* _parentName, const void* _handle) - : value(&_vec) - , space(_space) - , parentName(_parentName) - , handle(_handle) - { - } - - void Serialize(IArchive& ar); - }; - - struct LocalFrame - { - Quat* rotation; - Vec3* position; - const char* parentName; - int rotationSpace; - int positionSpace; - const void* handle; - - LocalFrame(Quat* _rotation, int _rotationSpace, Vec3* _position, int _positionSpace, const char* _parentName, const void* _handle) - : rotation(_rotation) - , position(_position) - , parentName(_parentName) - , rotationSpace(_rotationSpace) - , positionSpace(_positionSpace) - , handle(_handle) - { - } - - void Serialize(IArchive& ar); - }; - - enum - { - SPACE_JOINT, - SPACE_ENTITY, - SPACE_JOINT_WITH_PARENT_ROTATION, - SPACE_JOINT_WITH_CHARACTER_ROTATION, - SPACE_SOCKET_RELATIVE_TO_JOINT, - SPACE_SOCKET_RELATIVE_TO_BINDPOSE - }; - - - - //position - inline LocalPosition LocalToEntity(Vec3& position, const void* handle = 0) - { - return LocalPosition(position, SPACE_ENTITY, "", handle ? handle : &position); - } - inline LocalPosition LocalToJoint(Vec3& position, const string& jointName, const void* handle = 0) - { - return LocalPosition(position, SPACE_JOINT, jointName.c_str(), handle ? handle : &position); - } - - inline LocalPosition LocalToJointCharacterRotation(Vec3& position, const string& jointName, const void* handle = 0) - { - return LocalPosition(position, SPACE_JOINT_WITH_CHARACTER_ROTATION, jointName.c_str(), handle ? handle : &position); - } - - bool Serialize(Serialization::IArchive& ar, Serialization::LocalPosition& value, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::LocalOrientation& value, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::LocalFrame& value, const char* name, const char* label); -} - -#include "LocalFrameImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_LOCALFRAME_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrameImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrameImpl.h deleted file mode 100644 index 774cc06852..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/LocalFrameImpl.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_LOCALFRAMEIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_LOCALFRAMEIMPL_H -#pragma once - -#include "LocalFrame.h" -#include "Serialization/IArchive.h" -#include "Serialization/MathImpl.h" - -namespace Serialization -{ - inline void LocalPosition::Serialize(Serialization::IArchive& ar) - { - ar(value->x, "x", "^"); - ar(value->y, "y", "^"); - ar(value->z, "z", "^"); - } - - inline void LocalOrientation::Serialize(Serialization::IArchive& ar) - { - ar(Serialization::AsAng3(*value), "q", "^"); - } - - inline void LocalFrame::Serialize(Serialization::IArchive& ar) - { - ar(*position, "t", "m_path = path; } - }; - - bool Serialize(Serialization::IArchive& ar, Serialization::OutputFilePath& value, const char* name, const char* label); -} - -#include "OutputFilePathImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_OUTPUTFILEPATH_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/OutputFilePathImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/OutputFilePathImpl.h deleted file mode 100644 index 29d64fcff7..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/OutputFilePathImpl.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_OUTPUTFILEPATHIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_OUTPUTFILEPATHIMPL_H -#pragma once - -namespace Serialization -{ - inline bool Serialize(Serialization::IArchive& ar, Serialization::OutputFilePath& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(value), name, label); - } - else - { - return ar(*value.m_path, name, label); - } - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_OUTPUTFILEPATHIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/Range.h b/Code/CryEngine/CryCommon/Serialization/Decorators/Range.h deleted file mode 100644 index 7966c579dd..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/Range.h +++ /dev/null @@ -1,63 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RANGE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RANGE_H -#pragma once - -namespace Serialization -{ - template - struct RangeDecorator - { - T* value; - T softMin; - T softMax; - T hardMin; - T hardMax; - }; - - template - RangeDecorator Range(T& value, T hardMin, T hardMax) - { - RangeDecorator r; - r.value = &value; - r.softMin = hardMin; - r.softMax = hardMax; - r.hardMin = hardMin; - r.hardMax = hardMax; - return r; - } - - template - RangeDecorator Range(T& value, T softMin, T softMax, T hardMin, T hardMax) - { - RangeDecorator r; - r.value = &value; - r.softMin = softMin; - r.softMax = softMax; - r.hardMin = hardMin; - r.hardMax = hardMax; - return r; - } - - namespace Decorators - { - // Obsolete name, will be removed. Please use Serialization::Range instead. - using Serialization::Range; - } -} - -#include "RangeImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RANGE_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/RangeImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/RangeImpl.h deleted file mode 100644 index bc0508f3cb..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/RangeImpl.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RANGEIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RANGEIMPL_H -#pragma once - -namespace Serialization -{ - template - bool Serialize(IArchive& ar, RangeDecorator& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - if (!ar(SStruct::ForEdit(value), name, label)) - { - return false; - } - } - else if (!ar(*value.value, name, label)) - { - return false; - } - - if (ar.IsInput()) - { - if (*value.value < value.hardMin) - { - *value.value = value.hardMin; - } - if (*value.value > value.hardMax) - { - *value.value = value.hardMax; - } - } - return true; - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RANGEIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePath.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePath.h deleted file mode 100644 index 0f0c6dc34e..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePath.h +++ /dev/null @@ -1,59 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFILEPATH_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFILEPATH_H -#pragma once - -#include "Serialization/Strings.h" - -namespace Serialization -{ - class IArchive; - - struct ResourceFilePath - { - enum - { - STRIP_EXTENSION = 1 << 0 - }; - - string* m_path; - string filter; - bool group; - int flags; - - // filters are defined in the following format: - // "All Images (bmp, jpg, tga)|*.bmp;*.jpg;*.tga|Targa (tga)|*.tga" - explicit ResourceFilePath(string& path, const char* filter = "", bool group = false, int flags = 0) - : m_path(&path) - , filter(filter) - , group(group) - , flags(flags) - { - } - - // the function should stay virtual to ensure cross-dll calls are using right heap - virtual void SetPath(const char* path) { *this->m_path = path; } - }; - - inline ResourceFilePath MaterialPath(string& path) - { - return ResourceFilePath(path, "Material", false, ResourceFilePath::STRIP_EXTENSION); - } - - bool Serialize(Serialization::IArchive& ar, Serialization::ResourceFilePath& value, const char* name, const char* label); -} - -#include "ResourceFilePathImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFILEPATH_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePathImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePathImpl.h deleted file mode 100644 index 66c9140236..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFilePathImpl.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFILEPATHIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFILEPATHIMPL_H -#pragma once - -namespace Serialization -{ - inline bool Serialize(Serialization::IArchive& ar, Serialization::ResourceFilePath& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(value), name, label); - } - else - { - return ar(*value.m_path, name, label); - } - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFILEPATHIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPath.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPath.h deleted file mode 100644 index 327f668e43..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPath.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATH_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATH_H -#pragma once - -#include "Serialization/Strings.h" - -namespace Serialization -{ - class IArchive; - - struct ResourceFolderPath - { - string* m_path; - string startFolder; - - explicit ResourceFolderPath(string& path, const char* startFolder = "") - : m_path(&path) - , startFolder(startFolder) - { - } - - // the function should stay virtual to ensure cross-dll calls are using right heap - virtual void SetPath(const char* path) { *this->m_path = path; } - }; - - bool Serialize(Serialization::IArchive& ar, Serialization::ResourceFolderPath& value, const char* name, const char* label); -} - -#include "ResourceFolderPathImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATH_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPathImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPathImpl.h deleted file mode 100644 index 33ceacbe10..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceFolderPathImpl.h +++ /dev/null @@ -1,34 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATHIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATHIMPL_H -#pragma once - -#include "Serialization/IArchive.h" - -namespace Serialization -{ - inline bool Serialize(Serialization::IArchive& ar, Serialization::ResourceFolderPath& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(value), name, label); - } - else - { - return ar(*value.m_path, name, label); - } - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCEFOLDERPATHIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceSelector.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceSelector.h deleted file mode 100644 index 3b9920be6c..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourceSelector.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -namespace Serialization -{ - struct IResourceSelector - { - const char* resourceType; - - virtual ~IResourceSelector() {} - virtual const char* GetValue() const = 0; - virtual void SetValue(const char* s) = 0; - virtual int GetId() const{ return -1; } - virtual const void* GetHandle() const = 0; - virtual Serialization::TypeID GetType() const = 0; - }; - - // Provides a way to annotate resource reference so different UI can be used - // for them. See IResourceSelector.h to see how selectors for specific types - // are registered. - // - // TString could be SCRCRef or CCryName as well. - // - // Do not use this class directly, instead use function that wraps it for - // specific type, see Resources.h for example. - template - struct ResourceSelector - : IResourceSelector - { - TString& value; - - const char* GetValue() const { return value.c_str(); } - void SetValue(const char* s) { value = s; } - const void* GetHandle() const { return &value; } - Serialization::TypeID GetType() const { return Serialization::TypeID::get(); } - - ResourceSelector(TString& _value, const char* _resourceType) - : value(_value) - { - this->resourceType = _resourceType; - } - }; - - struct ResourceSelectorWithId - : IResourceSelector - { - string& value; - int id; - - const char* GetValue() const { return value.c_str(); } - void SetValue(const char* s) { value = s; } - int GetId() const { return id; } - const void* GetHandle() const { return &value; } - Serialization::TypeID GetType() const { return Serialization::TypeID::get(); } - - ResourceSelectorWithId(string& _value, const char* _resourceType, int _id) - : value(_value) - , id(_id) - { - this->resourceType = _resourceType; - } - }; - - template - bool Serialize(IArchive& ar, ResourceSelector& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(value)), name, label); - } - else - { - return ar(value.value, name, label); - } - } - - inline bool Serialize(IArchive& ar, ResourceSelectorWithId& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(value)), name, label); - } - else - { - return ar(value.value, name, label); - } - } -} diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/Resources.h b/Code/CryEngine/CryCommon/Serialization/Decorators/Resources.h deleted file mode 100644 index 637fc937ed..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/Resources.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCES_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCES_H -#pragma once -#include "ResourceSelector.h" - -namespace Serialization -{ - // animation resources - template - ResourceSelector AnimationAlias(T& s) { return ResourceSelector(s, "AnimationAlias"); } // "name" from animation set - template - ResourceSelector AnimationPath(T& s) { return ResourceSelector(s, "Animation"); } - inline ResourceSelectorWithId AnimationPathWithId(string& s, int id) { return ResourceSelectorWithId(s, "Animation", id); } - template - ResourceSelector CharacterPath(T& s) { return ResourceSelector(s, "Character"); } - template - ResourceSelector CharacterPhysicsPath(T& s) { return ResourceSelector(s, "CharacterPhysics"); } - template - ResourceSelector CharacterRigPath(T& s) { return ResourceSelector(s, "CharacterRig"); } - template - ResourceSelector SkeletonPath(T& s) { return ResourceSelector(s, "Skeleton"); } - template - ResourceSelector SkeletonParamsPath(T& s) { return ResourceSelector(s, "SkeletonParams"); } // CHRParams - template - ResourceSelector JointName(T& s) { return ResourceSelector(s, "Joint"); } - template - ResourceSelector AttachmentName(T& s) { return ResourceSelector(s, "Attachment"); } - - // miscelaneous resources - template - ResourceSelector SoundName(T& s) { return ResourceSelector(s, "Sound"); } - template - ResourceSelector DialogName(T& s) { return ResourceSelector(s, "Dialog"); } - template - ResourceSelector ForceFeedbackIdName(T& s) { return ResourceSelector(s, "ForceFeedbackId"); } - template - ResourceSelector ModelFilename(T& s) { return ResourceSelector(s, "Model"); } - template - ResourceSelector ParticleName(T& s) { return ResourceSelector(s, "Particle"); } - - namespace Decorators - { - // Decorators namespace is obsolete now, SHOULD NOT BE USED. - template - ResourceSelector AnimationName(T& s) { return ResourceSelector(s, "Animation"); } - using Serialization::SoundName; - using Serialization::AttachmentName; - template - ResourceSelector ObjectFilename(T& s) { return ResourceSelector(s, "Model"); } - using Serialization::JointName; - using Serialization::ForceFeedbackIdName; - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCES_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesAudio.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesAudio.h deleted file mode 100644 index 9e10be6c3b..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesAudio.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#include "ResourceSelector.h" - -namespace Serialization -{ - template - ResourceSelector AudioTrigger(T& s) { return ResourceSelector(s, "AudioTrigger"); } - template - ResourceSelector AudioSwitch(T& s) { return ResourceSelector(s, "AudioSwitch"); } - template - ResourceSelector AudioSwitchState(T& s) { return ResourceSelector(s, "AudioSwitchState"); } - template - ResourceSelector AudioRTPC(T& s) { return ResourceSelector(s, "AudioRTPC"); } - template - ResourceSelector AudioEnvironment(T& s) { return ResourceSelector(s, "AudioEnvironment"); } - template - ResourceSelector AudioPreloadRequest(T& s) { return ResourceSelector(s, "AudioPreloadRequest"); } -}; diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesImpl.h deleted file mode 100644 index dde4e1ae0c..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/ResourcesImpl.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCESIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCESIMPL_H -#pragma once - -namespace Serialization -{ - template - bool Serialize(IArchive& ar, ResourceSelector& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(value)), name, label); - } - else - { - return ar(value.value, name, label); - } - } - - inline bool Serialize(IArchive& ar, ResourceSelectorWithId& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(value)), name, label); - } - else - { - return ar(value.value, name, label); - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_RESOURCESIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/Slider.h b/Code/CryEngine/CryCommon/Serialization/Decorators/Slider.h deleted file mode 100644 index 8be5086660..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/Slider.h +++ /dev/null @@ -1,88 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SLIDER_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SLIDER_H -#pragma once - -namespace Serialization -{ - class IArchive; - - struct SSliderF - { - SSliderF(float* value, float _minLimit, float _maxLimit) - : valuePointer(value) - , minLimit(_minLimit) - , maxLimit(_maxLimit) - { - } - - SSliderF() - : valuePointer(0) - , minLimit(0.0f) - , maxLimit(1.0f) - { - } - - - float* valuePointer; - float minLimit; - float maxLimit; - }; - - struct SSliderI - { - SSliderI(int* value, int minLimit, int maxLimit) - : valuePointer(value) - , minLimit(minLimit) - , maxLimit(maxLimit) - { - } - - SSliderI() - : valuePointer(0) - , minLimit(0) - , maxLimit(1) - { - } - - int* valuePointer; - int minLimit; - int maxLimit; - }; - - - inline SSliderF Slider(float& value, float minLimit, float maxLimit) - { - return SSliderF(&value, minLimit, maxLimit); - } - - inline SSliderI Slider(int& value, int minLimit, int maxLimit) - { - return SSliderI(&value, minLimit, maxLimit); - } - - bool Serialize(IArchive& ar, SSliderF& slider, const char* name, const char* label); - bool Serialize(IArchive& ar, SSliderI& slider, const char* name, const char* label); - - namespace Decorators - { - // OBSOLETE NAME, please use Serialization::Slider instead (without Decorators namespace) - using Serialization::Slider; - } -} - -#include "SliderImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SLIDER_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/SliderImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/SliderImpl.h deleted file mode 100644 index c9e0dfc891..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/SliderImpl.h +++ /dev/null @@ -1,47 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SLIDERIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SLIDERIMPL_H -#pragma once - -#include "Slider.h" -#include "Serialization/IArchive.h" - -namespace Serialization -{ - inline bool Serialize(IArchive& ar, SSliderF& slider, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(SStruct::ForEdit(slider), name, label); - } - else - { - return ar(*slider.valuePointer, name, label); - } - } - - inline bool Serialize(IArchive& ar, SSliderI& slider, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(SStruct::ForEdit(slider), name, label); - } - else - { - return ar(*slider.valuePointer, name, label); - } - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SLIDERIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/Sprite.h b/Code/CryEngine/CryCommon/Serialization/Decorators/Sprite.h deleted file mode 100644 index 0eeefd7536..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/Sprite.h +++ /dev/null @@ -1,44 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITE_H -#pragma once - -namespace Serialization -{ -class IArchive; - -struct Sprite -{ - string* m_path; - string m_filter; - string m_startFolder; - - // filters are defined in the following format: - // "All Images (bmp, jpg, tga)|*.bmp;*.jpg;*.tga|Targa (tga)|*.tga" - explicit Sprite(string& path, const char* filter = "All files|*.*", const char* startFolder = "") - : m_path(&path) - , m_filter(filter) - , m_startFolder(startFolder) - { - } -}; - -bool Serialize(IArchive& ar, Sprite& value, const char* name, const char* label); - -} // namespace Serialization - -#include "SpriteImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITE_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/SpriteImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/SpriteImpl.h deleted file mode 100644 index 6d0075fafc..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/SpriteImpl.h +++ /dev/null @@ -1,35 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITEIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITEIMPL_H -#pragma once - -namespace Serialization -{ - -inline bool Serialize(IArchive& ar, Sprite& value, const char* name, const char* label) -{ - if (ar.IsEdit()) - { - return ar(SStruct::ForEdit(value), name, label); - } - else - { - return ar(*value.m_path, name, label); - } -} - -} // namespace Serialization - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_SPRITEIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/TagList.h b/Code/CryEngine/CryCommon/Serialization/Decorators/TagList.h deleted file mode 100644 index 4c4ad81ebf..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/TagList.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLIST_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLIST_H -#pragma once - -#include -#include "Serialization/Strings.h" - -namespace Serialization { - class IArchive; -} - -struct ITagSource -{ - virtual void AddRef() = 0; - virtual void Release() = 0; - virtual unsigned int TagCount(unsigned int group) const = 0; - virtual const char* TagValue(unsigned int group, unsigned int index) const = 0; - virtual const char* TagDescription(unsigned int group, unsigned int index) const = 0; - virtual const char* GroupName(unsigned int group) const = 0; - virtual unsigned int GroupCount() const = 0; -}; - -struct TagList -{ - std::vector* tags; - - TagList(std::vector& tags) - : tags(&tags) - { - } -}; - -bool Serialize(Serialization::IArchive& ar, TagList& tagList, const char* name, const char* label); - -#include "TagListImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLIST_H diff --git a/Code/CryEngine/CryCommon/Serialization/Decorators/TagListImpl.h b/Code/CryEngine/CryCommon/Serialization/Decorators/TagListImpl.h deleted file mode 100644 index 2ee6e1769b..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Decorators/TagListImpl.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLISTIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLISTIMPL_H -#pragma once - -#include -#include "Serialization/IArchive.h" -#include "Serialization/Strings.h" -#include "Serialization/STL.h" - -struct TagListContainer - : Serialization::ContainerSTL, Serialization::string> -{ - TagListContainer(TagList& tagList) - : ContainerSTL(tagList.tags) - { - } - - Serialization::TypeID containerType() const override { return Serialization::TypeID::get(); }; -}; - -inline bool Serialize(Serialization::IArchive& ar, TagList& tagList, const char* name, const char* label) -{ - TagListContainer container(tagList); - return ar(static_cast(container), name, label); -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DECORATORS_TAGLISTIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/DynArray.h b/Code/CryEngine/CryCommon/Serialization/DynArray.h deleted file mode 100644 index 1904cf4ac3..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/DynArray.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAY_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAY_H -#pragma once - -namespace Serialization { - class IArchive; -} - -template -bool Serialize(Serialization::IArchive& ar, DynArray& container, const char* name, const char* label); - -#include "DynArrayImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAY_H diff --git a/Code/CryEngine/CryCommon/Serialization/DynArrayImpl.h b/Code/CryEngine/CryCommon/Serialization/DynArrayImpl.h deleted file mode 100644 index c437604f67..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/DynArrayImpl.h +++ /dev/null @@ -1,28 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAYIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAYIMPL_H -#pragma once - -#include "IArchive.h" -#include "STLImpl.h" - -template -bool Serialize(Serialization::IArchive& ar, DynArray& container, const char* name, const char* label) -{ - Serialization::ContainerSTL, T> ser(&container); - return ar(static_cast(ser), name, label); -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_DYNARRAYIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Enum.h b/Code/CryEngine/CryCommon/Serialization/Enum.h deleted file mode 100644 index e377269013..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Enum.h +++ /dev/null @@ -1,170 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_ENUM_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ENUM_H -#pragma once - - -#include -#include - -#include "StringList.h" -#include "Serialization/TypeID.h" - -namespace Serialization { - class IArchive; - - struct LessStrCmp - { - bool operator()(const char* l, const char* r) const - { - return strcmp(l, r) < 0; - } - }; - - class CEnumDescription - { - public: - struct NameValue - { - NameValue* m_next; - const char* m_name; - const int m_value; - const char* m_label; - - NameValue(CEnumDescription& desc, const char* name, int value, const char* label="") - : m_next(desc.m_regListHead) - , m_name(name) - , m_value(value) - , m_label(label) - { - desc.m_regListHead = this; - } - }; - - NameValue* m_regListHead = nullptr; - - CEnumDescription(const Serialization::TypeID& type) - : type_(type) {} - inline int value(const char* name) const; - inline int valueByIndex(int index) const; - inline int valueByLabel(const char* label) const; - inline const char* name(int value) const; - inline const char* nameByIndex(int index) const; - inline const char* labelByIndex(int index) const; - inline const char* label(int value) const; - inline const char* indexByName(const char* name) const; - inline int indexByValue(int value) const; - - inline bool Serialize(IArchive& ar, int& value, const char* name, const char* label) const; - inline bool serializeBitVector(IArchive& ar, int& value, const char* name, const char* label) const; - - void add(int value, const char* name, const char* label = ""); - int count() const{ return int(values_.size()); } - const StringListStatic& names() const{ return names_; } - const StringListStatic& labels() const{ return labels_; } - inline StringListStatic nameCombination(int bitVector) const; - inline StringListStatic labelCombination(int bitVector) const; - bool registered() const { return !names_.empty(); } - TypeID type() const{ return type_; } - private: - void lazyRegister() const; - - StringListStatic names_; - StringListStatic labels_; - - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> NameToValue; - NameToValue nameToValue_; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> LabelToValue; - LabelToValue labelToValue_; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> ValueToIndex; - ValueToIndex valueToIndex_; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> ValueToName; - ValueToName valueToName_; - typedef AZStd::unordered_map, AZStd::equal_to, AZ::StdLegacyAllocator> ValueToLabel; - ValueToName valueToLabel_; - AZStd::vector values_; - TypeID type_; - }; - - template - class EnumDescriptionImpl - : public CEnumDescription - { - EnumDescriptionImpl() - : CEnumDescription(Serialization::TypeID::get()) {} - public: - static CEnumDescription& the() - { - static EnumDescriptionImpl description; - return description; - } - }; - - template - CEnumDescription& getEnumDescription() - { - return EnumDescriptionImpl::the(); - } - - inline bool serializeEnum(const CEnumDescription& desc, IArchive& ar, int& value, const char* name, const char* label) - { - return desc.Serialize(ar, value, name, label); - } -} - -#define SERIALIZATION_ENUM_BEGIN(Type, label) \ - namespace { \ - bool registerEnum_##Type(); \ - bool Type##_enum_registered = registerEnum_##Type(); \ - bool registerEnum_##Type(){ \ - Serialization::CEnumDescription& description = Serialization::EnumDescriptionImpl::the(); - -#define SERIALIZATION_ENUM_BEGIN_NESTED(Class, Enum, label) \ - namespace { \ - bool registerEnum_##Class##_##Enum(); \ - bool Class##_##Enum##_enum_registered = registerEnum_##Class##_##Enum(); \ - bool registerEnum_##Class##_##Enum(){ \ - Serialization::CEnumDescription& description = Serialization::EnumDescriptionImpl::the(); - -#define SERIALIZATION_ENUM_BEGIN_NESTED2(Class, Class1, Enum, label) \ - namespace { \ - bool registerEnum_##Class##Class1##_##Enum(); \ - bool Class##Class1##_##Enum##_enum_registered = registerEnum_##Class##Class1##_##Enum(); \ - bool registerEnum_##Class##Class1##_##Enum(){ \ - Serialization::CEnumDescription& description = Serialization::EnumDescriptionImpl::the(); - - -#define SERIALIZATION_ENUM_VALUE(value, label) \ - static Serialization::CEnumDescription::NameValue AZ_JOIN(enumValue, __LINE__)(description, label, (int)value); - -#define SERIALIZATION_ENUM(value, name, label) \ - static Serialization::CEnumDescription::NameValue AZ_JOIN(enumValue, __LINE__)(description, name, (int)value, label); - -#define SERIALIZATION_ENUM_VALUE_NESTED(Class, value, label) \ - static Serialization::CEnumDescription::NameValue AZ_JOIN(enumValue, __LINE__)(description, #value, (int)Class::value, label); - -#define SERIALIZATION_ENUM_VALUE_NESTED2(Class, Class1, value, label) \ - static Serialization::CEnumDescription::NameValue AZ_JOIN(enumValue, __LINE__)(description, #value, (int)Class::Class1::value, label); - - -#define SERIALIZATION_ENUM_END() \ - return true; \ - }; \ - }; - -#include "EnumImpl.h" -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ENUM_H diff --git a/Code/CryEngine/CryCommon/Serialization/EnumImpl.h b/Code/CryEngine/CryCommon/Serialization/EnumImpl.h deleted file mode 100644 index e5af93e43c..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/EnumImpl.h +++ /dev/null @@ -1,248 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_ENUMIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ENUMIMPL_H -#pragma once - -#pragma once -#include "IArchive.h" -#include "STL.h" -#include "Enum.h" -#include "StringList.h" -#ifndef SERIALIZATION_STANDALONE -#include -#endif - -namespace Serialization { - inline void CEnumDescription::add(int value, const char* name, const char* label) - { - YASLI_ESCAPE(name && label, return ); - // Filter for dupes in case enum description included in a shared header - NameToValue::iterator nameIt = nameToValue_.find(name); - if (nameIt != nameToValue_.end() && nameIt->second == value) - { LabelToValue::iterator labelIt = labelToValue_.find(label); - if (labelIt != labelToValue_.end() && labelIt->second == value) - { - return; - } - } - nameToValue_[name] = value; - labelToValue_[label] = value; - valueToName_[value] = name; - valueToLabel_[value] = label; - valueToIndex_[value] = int(names_.size()); - names_.push_back(name); - labels_.push_back(label); - values_.push_back(value); - } - - inline bool CEnumDescription::Serialize(IArchive& ar, int& value, const char* name, const char* label) const - { - lazyRegister(); - if (!ar.IsInPlace()) - { - if (count() == 0) - { -#ifdef SERIALIZATION_STANDALONE - assert(0 && "Attempt to serialize enum type that is not registered with SERIALIZATION_ENUM macro"); -#else - CryFatalError("Attempt to serialize enum type that is not registered with SERIALIZATION_ENUM macro: %s", type().name()); -#endif - return false; - } - - int index = StringListStatic::npos; - if (ar.IsOutput()) - { - index = indexByValue(value); - } - StringListStaticValue stringListValue(ar.IsEdit() ? labels() : names(), index, &value, type()); - ar(stringListValue, name, label); - if (ar.IsInput()) - { - if (stringListValue.index() == StringListStatic::npos) - { - return false; - } - value = ar.IsEdit() ? valueByLabel(stringListValue.c_str()) : this->value(stringListValue.c_str()); - } - else if (index == StringListStatic::npos) - { - ar.Error(&value, type(), "Unregistered or uninitialized enumeration value."); - } - } - else - { - return ar(value, name, label); - } - return true; - } - - inline bool CEnumDescription::serializeBitVector(IArchive& ar, int& value, const char* name, const char* label) const - { - lazyRegister(); - if (ar.IsOutput()) - { - StringListStatic names = nameCombination(value); - string str; - joinStringList(&str, names, '|'); - return ar(str, name, label); - } - else - { - string str; - if (!ar(str, name, label)) - { - return false; - } - StringList values; - splitStringList(&values, str.c_str(), '|'); - StringList::iterator it; - value = 0; - for (it = values.begin(); it != values.end(); ++it) - { - if (!it->empty()) - { - value |= this->value(it->c_str()); - } - } - return true; - } - } - - - inline const char* CEnumDescription::name(int value) const - { - lazyRegister(); - ValueToName::const_iterator it = valueToName_.find(value); - YASLI_ESCAPE(it != valueToName_.end(), return ""); - return it->second; - } - inline const char* CEnumDescription::label(int value) const - { - lazyRegister(); - ValueToLabel::const_iterator it = valueToLabel_.find(value); - YASLI_ESCAPE(it != valueToLabel_.end(), return ""); - return it->second; - } - - inline StringListStatic CEnumDescription::nameCombination(int bitVector) const - { - lazyRegister(); - StringListStatic strings; - for (ValueToName::const_iterator i = valueToName_.begin(); i != valueToName_.end(); ++i) - { - if ((bitVector & i->first) == i->first) - { - bitVector &= ~i->first; - strings.push_back(i->second); - } - } - YASLI_ASSERT(!bitVector && "Unregistered enum value"); - return strings; - } - - inline StringListStatic CEnumDescription::labelCombination(int bitVector) const - { - lazyRegister(); - StringListStatic strings; - for (ValueToLabel::const_iterator i = valueToLabel_.begin(); i != valueToLabel_.end(); ++i) - { - if (i->second && (bitVector & i->first) == i->first) - { - bitVector &= ~i->first; - strings.push_back(i->second); - } - } - YASLI_ASSERT(!bitVector && "Unregistered enum value"); - return strings; - } - - - inline int CEnumDescription::indexByValue(int value) const - { - lazyRegister(); - ValueToIndex::const_iterator it = valueToIndex_.find(value); - if (it == valueToIndex_.end()) - { - return -1; - } - else - { - return it->second; - } - } - - inline int CEnumDescription::valueByIndex(int index) const - { - lazyRegister(); - if (size_t(index) < values_.size()) - { - return values_[index]; - } - return 0; - } - - inline const char* CEnumDescription::nameByIndex(int index) const - { - lazyRegister(); - if (size_t(index) < size_t(names_.size())) - { - return names_[size_t(index)]; - } - return 0; - } - - inline const char* CEnumDescription::labelByIndex(int index) const - { - lazyRegister(); - if (size_t(index) < size_t(labels_.size())) - { - return labels_[size_t(index)]; - } - return 0; - } - - inline int CEnumDescription::value(const char* name) const - { - lazyRegister(); - NameToValue::const_iterator it = nameToValue_.find(name); - YASLI_ESCAPE(it != nameToValue_.end(), return 0); - return it->second; - } - inline int CEnumDescription::valueByLabel(const char* label) const - { - lazyRegister(); - LabelToValue::const_iterator it = labelToValue_.find(label); - YASLI_ESCAPE(it != labelToValue_.end(), return 0); - return it->second; - } - - inline void CEnumDescription::lazyRegister() const - { - if (m_regListHead) - { - NameValue* val = m_regListHead; - while (val) - { - const_cast(this)->add(val->m_value, val->m_name, val->m_label); - val = val->m_next; - } - const_cast(this)->m_regListHead = nullptr; - } - } -} -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ENUMIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/IArchive.h b/Code/CryEngine/CryCommon/Serialization/IArchive.h deleted file mode 100644 index 30de83ccc1..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/IArchive.h +++ /dev/null @@ -1,446 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_IARCHIVE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_IARCHIVE_H -#pragma once - - -#include -#include - -#include "Serializer.h" -#include "KeyValue.h" -#include "TypeID.h" - -namespace Serialization { - class IArchive; - - template - bool Serialize(Serialization::IArchive& ar, T& object, const char* name, const char* label); - - class CEnumDescription; - template - CEnumDescription& getEnumDescription(); - bool serializeEnum(const CEnumDescription& desc, IArchive& ar, int& value, const char* name, const char* label); - - // SContextLink should not be used directly. See SContext<> below. - struct SContextLink - { - SContextLink* outer; - TypeID type; - void* contextObject; - - SContextLink() - : outer() - , contextObject() - { - } - }; - - struct SBlackBox; - struct ICallback; - - class IArchive - { - public: - enum ArchiveCaps - { - INPUT = 1 << 0, - OUTPUT = 1 << 1, - TEXT = 1 << 2, - BINARY = 1 << 3, - EDIT = 1 << 4, - INPLACE = 1 << 5, - NO_EMPTY_NAMES = 1 << 6, - VALIDATION = 1 << 7, - DOCUMENTATION = 1 << 8 - }; - - IArchive(int caps) - : caps_(caps) - , filter_(0) - , innerContext_(0) - { - } - virtual ~IArchive() {} - - bool IsInput() const{ return caps_ & INPUT ? true : false; } - bool IsOutput() const{ return caps_ & OUTPUT ? true : false; } - bool IsEdit() const - { -#if !defined(CONSOLE) && !defined(RELEASE) - return (caps_ & EDIT) != 0; -#else - return false; -#endif - } - bool IsInPlace() const{ return caps_ & INPLACE ? true : false; } - bool GetCaps(int caps) const { return (caps_ & caps) == caps; } - - void SetFilter(int filter) - { - filter_ = filter; - } - int GetFilter() const{ return filter_; } - bool Filter(int flags) const - { - YASLI_ASSERT(flags != 0 && "flags is supposed to be a bit mask"); - YASLI_ASSERT(filter_ && "Filter is not set!"); - return (filter_ & flags) != 0; - } - - virtual bool operator()([[maybe_unused]] bool& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] char& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] uint8& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] int8& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] int16& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] uint16& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] int32& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] uint32& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] int64& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] uint64& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] float& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] double& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - - virtual bool operator()([[maybe_unused]] IString& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] IWString& value, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] const SStruct& ser, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { notImplemented(); return false; } - virtual bool operator()([[maybe_unused]] IContainer& ser, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { return false; } - virtual bool operator()(IPointer& ptr, const char* name = "", const char* label = 0); - virtual bool operator()(IKeyValue& keyValue, const char* name = "", const char* label = 0) { return operator()(SStruct(keyValue), name, label); } - virtual bool operator()([[maybe_unused]] const SBlackBox& blackBox, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { return false; } - virtual bool operator()([[maybe_unused]] ICallback& callback, [[maybe_unused]] const char* name = "", [[maybe_unused]] const char* label = 0) { return false; } - - template - bool operator()(const T& value, const char* name = "", const char* label = 0); - - // Error and Warning calls are used for diagnostics and validation of the - // values. Output depends on the specific implementation of IArchive, - // for example PropertyTree uses it to show bubbles with errors in UI - // next to the mentioned property. - template - void Error(T& value, const char* format, ...); - template - void Warning(T& value, const char* format, ...); - - void Error(const void* value, const Serialization::TypeID& type, const char* format, ...); - // Used to add tooltips in PropertyTree - void Doc(const char* docString); - - virtual bool OpenBlock([[maybe_unused]] const char* name, [[maybe_unused]] const char* label) { return true; } - virtual void CloseBlock() {} - - // long, unsigned long and long double are intentionally omitted - - template - T* FindContext() const { return (T*)FindContextByType(TypeID::get()); } - - void* FindContextByType(const TypeID& type) const - { - SContextLink* context = innerContext_; - while (context) - { - if (context->type == type) - { - return context->contextObject; - } - context = context->outer; - } - return 0; - } - - SContextLink* SetInnerContext(SContextLink* context) - { - SContextLink* result = innerContext_; - innerContext_ = context; - return result; - } - SContextLink* GetInnerContext() const{ return innerContext_; } - protected: - virtual void ValidatorMessage([[maybe_unused]] bool error, [[maybe_unused]] const void* handle, [[maybe_unused]] const TypeID& type, [[maybe_unused]] const char* message) {} - virtual void DocumentLastField([[maybe_unused]] const char* text) {} - - void notImplemented() { YASLI_ASSERT(0 && "Not implemented!"); } - - int caps_; - int filter_; - - SContextLink* innerContext_; - }; - - - // IArchive::SContext can be used to establish access to outer objects in serialization stack. - // - // Example: - // void Scene::Serialize(...) { - // IArchive::SContext context(ar, this); - // ar(rootNode, ...); - // } - // - // void Node::Serialize(...) { - // Scene* scene = ar.FindContext(); - // } - template - struct SContext - : SContextLink - { - SContext(IArchive& ar, T* context) - : ar_(&ar) - { - outer = ar_->SetInnerContext(this); - type = TypeID::get(); - contextObject = (void*)context; - } - SContext(T* context) - : ar_(0) - { - outer = 0; - type = TypeID::get(); - contextObject = (void*)context; - } - ~SContext() - { - if (ar_) - { - ar_->SetInnerContext(outer); - } - } - private: - IArchive* ar_; - }; - - namespace detail { - template - struct Selector{}; - - template - struct Selector - { - typedef T2 type; - }; - - template - struct Selector - { - typedef T1 type; - }; - - template - struct Select - { - typedef typename Selector::type selected_type; - typedef typename selected_type::type type; - }; - - template - struct Identity - { - typedef T type; - }; - - - template - struct IsArray - { - enum - { - value = false - }; - }; - - template - struct IsArray< T[Size] > - { - enum - { - value = true - }; - }; - - template - struct ArraySize - { - enum - { - value = true - }; - }; - - template - struct SerializeStruct - { - static bool invoke(IArchive& ar, T& value, const char* name, const char* label) - { - SStruct ser(value); - return ar(ser, name, label); - }; - }; - - template - struct SerializeEnum - { - static bool invoke(IArchive& ar, Enum& value, const char* name, const char* label) - { - const CEnumDescription& enumDescription = getEnumDescription(); - return serializeEnum(enumDescription, ar, reinterpret_cast(value), name, label); - }; - }; - - template - struct SerializeArray{}; - - template - struct SerializeArray - { - static bool invoke(IArchive& ar, T value[Size], const char* name, const char* label) - { - ContainerArray ser(value, Size); - return ar(static_cast(ser), name, label); - } - }; - - - template - struct IsClass - { - private: - struct NoType - { - char dummy; - }; - struct YesType - { - char dummy[100]; - }; - - template - static YesType function_helper(void(U::*)(void)); - - template - static NoType function_helper(...); - public: - enum - { - value = (sizeof(function_helper(0)) == sizeof(YesType)) - }; - }; - } - - template - bool IArchive::operator()(const T& value, const char* name, const char* label) - { - return Serialize(*this, const_cast(value), name, label); - } - - inline bool IArchive::operator()(IPointer& ptr, const char* name, const char* label) - { - return (*this)(SStruct(const_cast(ptr)), name, label); - } - - inline void IArchive::Doc([[maybe_unused]] const char* docString) - { -#if !defined(CONSOLE) && !defined(RELEASE) - if (caps_ & DOCUMENTATION) - { - DocumentLastField(docString); - } -#endif - } - - template - void IArchive::Error([[maybe_unused]] T& value, [[maybe_unused]] const char* format, ...) - { -#if !defined(CONSOLE) && !defined(RELEASE) - if ((caps_ & VALIDATION) == 0) - { - return; - } - va_list args; - va_start(args, format); - char buf[1024]; - azvsnprintf(buf, sizeof(buf), format, args); - va_end(args); - ValidatorMessage(true, &value, TypeID::get(), buf); -#endif - } - - inline void IArchive::Error([[maybe_unused]] const void* handle, [[maybe_unused]] const Serialization::TypeID& type, [[maybe_unused]] const char* format, ...) - { -#if !defined(CONSOLE) && !defined(RELEASE) - if ((caps_ & VALIDATION) == 0) - { - return; - } - va_list args; - va_start(args, format); - char buf[1024]; - azvsnprintf(buf, sizeof(buf), format, args); - va_end(args); - ValidatorMessage(true, handle, type, buf); -#endif - } - - template - void IArchive::Warning([[maybe_unused]] T& value, [[maybe_unused]] const char* format, ...) - { -#if !defined(CONSOLE) && !defined(RELEASE) - if ((caps_ & VALIDATION) == 0) - { - return; - } - va_list args; - va_start(args, format); - char buf[1024]; - azvsnprintf(buf, sizeof(buf), format, args); - va_end(args); - ValidatorMessage(false, &value, TypeID::get(), buf); -#endif - } - - template - bool Serialize(Serialization::IArchive& ar, T object[Size], const char* name, const char* label) - { - YASLI_ASSERT(0); - return false; - } - - template - bool Serialize(Serialization::IArchive& ar, const T& object, const char* name, const char* label) - { - T::unable_to_serialize_CONST_object(); - YASLI_ASSERT(0); - return false; - } - - template - bool Serialize(Serialization::IArchive& ar, T& object, const char* name, const char* label) - { - using namespace Serialization::detail; - - return - Select< IsClass, - Identity< SerializeStruct >, - Select< IsArray, - Identity< SerializeArray >, - Identity< SerializeEnum > - > - >::type::invoke(ar, object, name, label); - } -} - -#include "Serialization/SerializerImpl.h" - -// vim: ts=4 sw=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_IARCHIVE_H diff --git a/Code/CryEngine/CryCommon/Serialization/IArchiveHost.h b/Code/CryEngine/CryCommon/Serialization/IArchiveHost.h deleted file mode 100644 index c2afc1778f..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/IArchiveHost.h +++ /dev/null @@ -1,153 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -// IArchiveHost serves a purpose of sharing IArchive implementations among -// diffferent modules. -// -// Example of usage: -// -// struct SType -// { -// void Serialize(Serialization::IArchive& ar); -// }; -// -// SType instanceToSave; -// bool saved = Serialization::SaveJsonFile("Scripts/instance.json", instanceToSave); -// -// SType instanceToLoad; -// bool loaded = Serialization::LoadJsonFile(instanceToLoad, "Scripts/instance.json"); -// -#include -#include - -namespace Serialization -{ - struct IArchiveHost - { - virtual ~IArchiveHost() {} - virtual bool LoadJsonFile(const SStruct& outObj, const char* filename) = 0; - virtual bool SaveJsonFile(const char* filename, const SStruct& obj) = 0; - virtual bool LoadJsonBuffer(const SStruct& outObj, const char* buffer, size_t bufferLength) = 0; - virtual bool SaveJsonBuffer(DynArray& outBuffer, const SStruct& obj) = 0; - - virtual bool LoadBinaryFile(const SStruct& outObj, const char* filename) = 0; - virtual bool SaveBinaryFile(const char* filename, const SStruct& obj) = 0; - virtual bool LoadBinaryBuffer(const SStruct& outObj, const char* buffer, size_t bufferLength) = 0; - virtual bool SaveBinaryBuffer(DynArray& outBuffer, const SStruct& obj) = 0; - virtual bool CloneBinary(const SStruct& dest, const SStruct& source) = 0; - // Compares two instances in serialized form through binary archive - virtual bool CompareBinary(const SStruct& lhs, const SStruct& rhs) = 0; - - virtual bool LoadXmlFile(const SStruct& outObj, const char* filename) = 0; - virtual bool SaveXmlFile(const char* filename, const SStruct& obj, const char* rootNodeName) = 0; - virtual bool LoadXmlNode(const SStruct& outObj, const XmlNodeRef& node) = 0; - virtual XmlNodeRef SaveXmlNode(const SStruct& obj, const char* nodeName) = 0; - virtual bool SaveXmlNode(XmlNodeRef& node, const SStruct& obj) = 0; - }; - - // Syntactic sugar - template - bool LoadJsonFile(T& instance, const char* filename) - { - return gEnv->pSystem->GetArchiveHost()->LoadJsonFile(Serialization::SStruct(instance), filename); - } - - template - bool SaveJsonFile(const char* filename, const T& instance) - { - return gEnv->pSystem->GetArchiveHost()->SaveJsonFile(filename, Serialization::SStruct(instance)); - } - - template - bool LoadJsonBuffer(T& instance, const char* buffer, size_t bufferLength) - { - return gEnv->pSystem->GetArchiveHost()->LoadJsonBuffer(Serialization::SStruct(instance), buffer, bufferLength); - } - - template - bool SaveJsonBuffer(DynArray& outBuffer, const T& instance) - { - return gEnv->pSystem->GetArchiveHost()->SaveJsonBuffer(outBuffer, Serialization::SStruct(instance)); - } - - // --------------------------------------------------------------------------- - - template - bool LoadBinaryFile(T& outInstance, const char* filename) - { - return gEnv->pSystem->GetArchiveHost()->LoadBinaryFile(Serialization::SStruct(outInstance), filename); - } - - template - bool SaveBinaryFile(const char* filename, const T& instance) - { - return gEnv->pSystem->GetArchiveHost()->SaveBinaryFile(filename, Serialization::SStruct(instance)); - } - - template - bool LoadBinaryBuffer(T& outInstance, const char* buffer, size_t bufferLength) - { - return gEnv->pSystem->GetArchiveHost()->LoadBinaryBuffer(Serialization::SStruct(outInstance), buffer, bufferLength); - } - - template - bool SaveBinaryBuffer(DynArray& outBuffer, const T& instance) - { - return gEnv->pSystem->GetArchiveHost()->SaveBinaryBuffer(outBuffer, Serialization::SStruct(instance)); - } - - template - bool CloneBinary(T& outInstance, const T& inInstance) - { - return gEnv->pSystem->GetArchiveHost()->CloneBinary(Serialization::SStruct(outInstance), Serialization::SStruct(inInstance)); - } - - template - bool CompareBinary(const T& lhs, const T& rhs) - { - return gEnv->pSystem->GetArchiveHost()->CompareBinary(Serialization::SStruct(lhs), Serialization::SStruct(rhs)); - } - - // --------------------------------------------------------------------------- - - template - bool LoadXmlFile(T& outInstance, const char* filename) - { - return gEnv->pSystem->GetArchiveHost()->LoadXmlFile(Serialization::SStruct(outInstance), filename); - } - - template - bool SaveXmlFile(const char* filename, const T& instance, const char* rootNodeName) - { - return gEnv->pSystem->GetArchiveHost()->SaveXmlFile(filename, Serialization::SStruct(instance), rootNodeName); - } - - template - bool LoadXmlNode(T& outInstance, const XmlNodeRef& node) - { - return gEnv->pSystem->GetArchiveHost()->LoadXmlNode(Serialization::SStruct(outInstance), node); - } - - template - XmlNodeRef SaveXmlNode(const T& instance, const char* nodeName) - { - return gEnv->pSystem->GetArchiveHost()->SaveXmlNode(Serialization::SStruct(instance), nodeName); - } - - template - bool SaveXmlNode(XmlNodeRef& node, const T& instance) - { - return gEnv->pSystem->GetArchiveHost()->SaveXmlNode(node, Serialization::SStruct(instance)); - } -} diff --git a/Code/CryEngine/CryCommon/Serialization/IClassFactory.h b/Code/CryEngine/CryCommon/Serialization/IClassFactory.h deleted file mode 100644 index bf50b17acd..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/IClassFactory.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_ICLASSFACTORY_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ICLASSFACTORY_H -#pragma once - -#include - -#include "Serialization/Assert.h" -#include "Serialization/TypeID.h" - -namespace Serialization { - class IArchive; - class TypeDescription - { - public: - TypeDescription(const char* name, const char* label) - : name_(name) - , label_(label) - { - } - const char* name() const{ return name_; } - const char* label() const{ return label_; } - - protected: - const char* name_; - const char* label_; - }; - - class IClassFactory - { - friend class ClassFactoryManager; - public: - IClassFactory(TypeID baseType) - : baseType_(baseType) - , nullLabel_(0) - { - } - - virtual ~IClassFactory() { } - - virtual size_t size() const = 0; - virtual const TypeDescription* descriptionByIndex(int index) const = 0; - virtual const TypeDescription* descriptionByRegisteredName(const char* typeName) const = 0; - virtual const char* findAnnotation(const char* registeredTypeName, const char* annotationName) const = 0; - virtual void serializeNewByIndex(IArchive& ar, int index, const char* name, const char* label) = 0; - - bool setNullLabel(const char* label){ nullLabel_ = label ? label : ""; return true; } - const char* nullLabel() const{ return nullLabel_; } - protected: - TypeID baseType_; - const char* nullLabel_; - IClassFactory* m_next = nullptr; - }; - - - struct TypeNameWithFactory - { - string registeredName; - IClassFactory* factory; - - TypeNameWithFactory(const char* _registeredName, IClassFactory* _factory = 0) - : registeredName(_registeredName) - , factory(_factory) - { - } - }; - - bool Serialize(Serialization::IArchive& ar, Serialization::TypeNameWithFactory& value, const char* name, const char* label); -} - -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ICLASSFACTORY_H diff --git a/Code/CryEngine/CryCommon/Serialization/ITextInputArchive.h b/Code/CryEngine/CryCommon/Serialization/ITextInputArchive.h deleted file mode 100644 index c9f268d9a4..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/ITextInputArchive.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_ITEXTINPUTARCHIVE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ITEXTINPUTARCHIVE_H -#pragma once -#include "Serialization/IArchive.h" -#include "CryExtension/ICryUnknown.h" -#include "CryExtension/CryCreateClassInstance.h" - -namespace Serialization { - class ITextInputArchive - : public ICryUnknown - , public IArchive - { - public: - CRYINTERFACE_DECLARE(ITextInputArchive, 0x1845738b1dcc4168, 0xb440dba776b460c9) - - using IArchive::operator(); - - virtual bool LoadFileUsingCRT(const char* filename) = 0; - virtual bool AttachMemory(const char* buffer, size_t size) = 0; - - protected: - ITextInputArchive(int caps) - : IArchive(caps) {} - }; - - inline AZStd::shared_ptr CreateTextInputArchive() - { - AZStd::shared_ptr pArchive; - CryCreateClassInstance(MAKE_CRYGUID(0x7a83a1c890054608, 0x9f8447a4b0ad6c3b), pArchive); - return pArchive; - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ITEXTINPUTARCHIVE_H diff --git a/Code/CryEngine/CryCommon/Serialization/ITextOutputArchive.h b/Code/CryEngine/CryCommon/Serialization/ITextOutputArchive.h deleted file mode 100644 index e87b819404..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/ITextOutputArchive.h +++ /dev/null @@ -1,55 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_ITEXTOUTPUTARCHIVE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_ITEXTOUTPUTARCHIVE_H -#pragma once -#include "Serialization/IArchive.h" -#include "CryExtension/ICryUnknown.h" -#include "CryExtension/CryCreateClassInstance.h" - -namespace Serialization { - class ITextOutputArchive - : public ICryUnknown - , public IArchive - { - CRYINTERFACE_DECLARE(ITextOutputArchive, 0xa273d6157a8b4f0d, 0x80ad6c8031bbfbf3) - public: - virtual bool SaveFileUsingCRT(const char* filename) = 0; - - // use precise but less readable way to write float/double types - virtual void SetExponentFloatRepresentation(bool) = 0; - - // buffer is a null-terminated string - virtual const char* GetBuffer() const = 0; - virtual size_t GetBufferLength() const = 0; - - // by default nested structres are put in one line, unless the line length is - // longer than 'textWidth' - virtual void SetTextWidth(int textWidth) = 0; - - using IArchive::operator(); - protected: - ITextOutputArchive(int caps) - : IArchive(caps) {} - }; - - inline AZStd::shared_ptr CreateTextOutputArchive() - { - AZStd::shared_ptr pArchive; - CryCreateClassInstance(MAKE_CRYGUID(0xd1f14adbc4e74e49, 0x9cea55d80a55cbdb), pArchive); - return pArchive; - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_ITEXTOUTPUTARCHIVE_H diff --git a/Code/CryEngine/CryCommon/Serialization/IXmlArchive.h b/Code/CryEngine/CryCommon/Serialization/IXmlArchive.h deleted file mode 100644 index 07d4438d92..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/IXmlArchive.h +++ /dev/null @@ -1,175 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_IXMLARCHIVE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_IXMLARCHIVE_H -#pragma once - - -#include "Serialization/IArchive.h" -#include "CryExtension/ICryUnknown.h" -#include "CryExtension/CryCreateClassInstance.h" - -namespace Serialization -{ - struct IXmlArchive - : public ICryUnknown - , public IArchive - { - public: - CRYINTERFACE_DECLARE(IXmlArchive, 0x1386c94ded174f96, 0xab14d20e1b616588); - - using IArchive::operator(); - - virtual void SetXmlNode(XmlNodeRef pRootNode) = 0; - virtual XmlNodeRef GetXmlNode() const = 0; - - protected: - IXmlArchive(int caps) - : IArchive(caps | IArchive::NO_EMPTY_NAMES) {} - }; - - - typedef AZStd::shared_ptr< IXmlArchive > IXmlArchivePtr; - - - inline IXmlArchivePtr CreateXmlInputArchive() - { - IXmlArchivePtr pArchive; - CryCreateClassInstance("CXmlIArchive", pArchive); - return pArchive; - } - - - inline IXmlArchivePtr CreateXmlInputArchive(XmlNodeRef pXmlNode) - { - if (pXmlNode) - { - IXmlArchivePtr pArchive = CreateXmlInputArchive(); - if (pArchive) - { - pArchive->SetXmlNode(pXmlNode); - } - return pArchive; - } - return IXmlArchivePtr(); - } - - - inline IXmlArchivePtr CreateXmlInputArchive(const char* const filename) - { - XmlNodeRef pXmlNode = gEnv->pSystem->LoadXmlFromFile(filename); - return CreateXmlInputArchive(pXmlNode); - } - - - inline IXmlArchivePtr CreateXmlOutputArchive() - { - IXmlArchivePtr pArchive; - CryCreateClassInstance("CXmlOArchive", pArchive); - return pArchive; - } - - - inline IXmlArchivePtr CreateXmlOutputArchive(XmlNodeRef pXmlNode) - { - if (pXmlNode) - { - IXmlArchivePtr pArchive = CreateXmlOutputArchive(); - if (pArchive) - { - pArchive->SetXmlNode(pXmlNode); - } - return pArchive; - } - return IXmlArchivePtr(); - } - - - inline IXmlArchivePtr CreateXmlOutputArchive(const char* const xmlRootElementName) - { - XmlNodeRef pXmlNode = gEnv->pSystem->CreateXmlNode(xmlRootElementName); - return CreateXmlOutputArchive(pXmlNode); - } - - - template< typename T > - bool StructFromXml(const char* const filename, T& dataOut) - { - Serialization::IXmlArchivePtr pXmlArchive = Serialization::CreateXmlInputArchive(filename); - if (pXmlArchive) - { - Serialization::SStruct serializer = Serialization::SStruct(dataOut); - const bool success = serializer(*pXmlArchive); - return success; - } - return false; - } - - - template< typename T > - bool StructFromXml(XmlNodeRef pXmlNode, T& dataOut) - { - Serialization::IXmlArchivePtr pXmlArchive = Serialization::CreateXmlInputArchive(pXmlNode); - if (pXmlArchive) - { - Serialization::SStruct serializer = Serialization::SStruct(dataOut); - const bool success = serializer(*pXmlArchive); - return success; - } - return false; - } - - - template< typename T > - XmlNodeRef StructToXml(const char* const xmlRootElementName, const T& dataIn) - { - Serialization::IXmlArchivePtr pXmlArchive = Serialization::CreateXmlOutputArchive(xmlRootElementName); - if (pXmlArchive) - { - Serialization::SStruct serializer = Serialization::SStruct(const_cast< T& >(dataIn)); - const bool success = serializer(*pXmlArchive); - if (success) - { - return pXmlArchive->GetXmlNode(); - } - } - return XmlNodeRef(); - } - - - template< typename T > - bool StructToXml(XmlNodeRef pXmlNode, const T& dataIn) - { - Serialization::IXmlArchivePtr pXmlArchive = Serialization::CreateXmlOutputArchive(pXmlNode); - if (pXmlArchive) - { - Serialization::SStruct serializer = Serialization::SStruct(const_cast< T& >(dataIn)); - const bool success = serializer(*pXmlArchive); - return success; - } - return false; - } - - - template< typename T > - bool StructToXml(const char* const filename, const char* const xmlRootElementName, const T& dataIn) - { - XmlNodeRef pXmlNode = Serialization::StructToXml(xmlRootElementName, dataIn); - if (pXmlNode) - { - return pXmlNode->saveToFile(filename); - } - return false; - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_IXMLARCHIVE_H diff --git a/Code/CryEngine/CryCommon/Serialization/IntrusiveFactory.h b/Code/CryEngine/CryCommon/Serialization/IntrusiveFactory.h deleted file mode 100644 index dcd92d51a9..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/IntrusiveFactory.h +++ /dev/null @@ -1,99 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_INTRUSIVEFACTORY_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_INTRUSIVEFACTORY_H -#pragma once - -#include - -template -class CIntrusiveFactory -{ -private: - struct ICreator - { - virtual TBase* Create() const = 0; - }; - -public: - template - struct SCreator - : ICreator - { - SCreator() { CIntrusiveFactory::Instance().RegisterType(this); } - - TBase* Create() const override { return new TDerived(); } - }; - - static CIntrusiveFactory& Instance() { static CIntrusiveFactory instance; return instance; } - - TBase* Create(const char* keyType) const - { - TCreatorByType::const_iterator it = m_creators.find(keyType); - if (it == m_creators.end() || it->second == 0) - { - return 0; - } - else - { - return it->second->Create(); - } - } - - struct SSerializer - { - _smart_ptr& pointer; - - SSerializer(_smart_ptr& pointer) - : pointer(pointer) {} - - void Serialize(Serialization::IArchive& ar); - }; - -private: - template - void RegisterType(ICreator* creator) - { - const char* type = TDerived::GetType(); - m_creators[type] = creator; - } - - typedef std::map > TCreatorByType; - TCreatorByType m_creators; -}; - -template -void CIntrusiveFactory::SSerializer::Serialize(Serialization::IArchive & ar) -{ - string type = pointer.get() ? pointer->GetInstanceType() : ""; - string oldType = type; - ar(type, "type", "Type"); - if (ar.IsInput()) - { - if (oldType != type) - { - pointer.reset(CIntrusiveFactory::Instance().Create(type.c_str())); - } - } - if (pointer) - { - pointer->Serialize(ar); - } -} - - - -#define REGISTER_IN_INTRUSIVE_FACTORY(BaseType, DerivedType) namespace { CIntrusiveFactory::SCreator baseType##DerivedType##_Creator; } - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_INTRUSIVEFACTORY_H diff --git a/Code/CryEngine/CryCommon/Serialization/KeyValue.h b/Code/CryEngine/CryCommon/Serialization/KeyValue.h deleted file mode 100644 index afe74927df..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/KeyValue.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_KEYVALUE_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_KEYVALUE_H -#pragma once -namespace Serialization { - class IArchive; - - class IKeyValue - : IString - { - public: - virtual const char* get() const = 0; - virtual void set(const char* key) = 0; - virtual bool serializeValue(IArchive& ar, const char* name, const char* label) = 0; - template - void Serialize(TArchive& ar) - { - ar(*(IString*)this, "", "^"); - serializeValue(ar, "", "^"); - } - }; -} - - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_KEYVALUE_H diff --git a/Code/CryEngine/CryCommon/Serialization/Math.h b/Code/CryEngine/CryCommon/Serialization/Math.h deleted file mode 100644 index c7d86935e0..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Math.h +++ /dev/null @@ -1,166 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// This header extends serialization to support common geometrical types. -// It allows serialization of mentioned below types simple passing them to archive. -// For example: -// -// #include -// #include -// -// Serialization::IArchive& ar; -// -// Vec3 v; -// ar(v, "v"); -// -// QuatT q; -// ar(q, "q"); -// - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATH_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATH_H -#pragma once -namespace Serialization { - class IArchive; -} - -template -bool Serialize(Serialization::IArchive& ar, struct Vec2_tpl& v, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct Vec3_tpl& v, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct Vec4_tpl& v, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct Quat_tpl& q, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct QuatT_tpl& qt, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct Ang3_tpl& a, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, struct Matrix34_tpl& value, const char* name, const char* label); - -bool Serialize(Serialization::IArchive& ar, struct AABB& aabb, const char* name, const char* label); - -// --------------------------------------------------------------------------- -// RadiansAsDeg allows to present radian values as degrees to the user in the -// editor. -// -// Example: -// ... -// float radians; -// ar(RadiansAsDeg(radians), "degrees", "Degrees"); -// -// Ang3 euler; -// ar(RadiansAsDeg(euler), "eulerDegrees", "Euler Degrees"); -// -namespace Serialization -{ - template - struct SRadianAng3AsDeg - { - Ang3_tpl* ang3; - SRadianAng3AsDeg(Ang3_tpl* _ang3) - : ang3(_ang3) {} - }; - - template - SRadianAng3AsDeg RadiansAsDeg(Ang3_tpl& radians) - { - return SRadianAng3AsDeg(&radians); - } - - template - struct SRadiansAsDeg - { - T* radians; - SRadiansAsDeg(T* _radians) - : radians(_radians) {} - }; - - template - SRadiansAsDeg RadiansAsDeg(T& radians) - { - return SRadiansAsDeg(&radians); - } - - template - bool Serialize(Serialization::IArchive& ar, Serialization::SRadiansAsDeg& value, const char* name, const char* label); - template - bool Serialize(Serialization::IArchive& ar, Serialization::SRadianAng3AsDeg& value, const char* name, const char* label); - - // --------------------------------------------------------------------------- - // QuatAsAng3 provides a wrapper that allows editing of quaternions as Ang3 (in degrees). - // - // Example: - // ... - // Quat q; - // ar(QuatAsAng3(q), "orientation", "Orientation"); - // - - template - struct QuatAsAng3 - { - Quat_tpl* quat; - QuatAsAng3(Quat_tpl& _quat) - : quat(&_quat) {} - }; - - template - bool Serialize(Serialization::IArchive& ar, Serialization::QuatAsAng3& value, const char* name, const char* label); - - // --------------------------------------------------------------------------- - // QuatTAsVec3Ang3 provides a wrapper that allows editing of transforms as Vec3 and Ang3 (in degrees). - // - // Example: - // ... - // QuatT trans; - // ar(QuatTAsVec3Ang3(trans), "transform", "Transform"); - // - - template - struct QuatTAsVec3Ang3 - { - QuatT_tpl* trans; - QuatTAsVec3Ang3(QuatT_tpl& _trans) - : trans(&_trans) {} - }; - - template - bool Serialize(Serialization::IArchive& ar, Serialization::QuatTAsVec3Ang3& value, const char* name, const char* label); - - // --------------------------------------------------------------------------- - // Helper functions for Ang3 - // - // Example: - // ... - // Quat q; - // QuatT trans; - // ar(AsAng3(q),"orientation","Orientation"); - // ar(AsAnge(trans),"transform", "Transform"); - // - - template - inline QuatAsAng3 AsAng3(Quat_tpl& q){ return QuatAsAng3(q); } - template - inline QuatTAsVec3Ang3 AsAng3(QuatT_tpl& trans){ return QuatTAsVec3Ang3(trans); } -} - -#include "MathImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATH_H diff --git a/Code/CryEngine/CryCommon/Serialization/MathImpl.h b/Code/CryEngine/CryCommon/Serialization/MathImpl.h deleted file mode 100644 index 95ff63e179..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/MathImpl.h +++ /dev/null @@ -1,207 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATHIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATHIMPL_H -#pragma once - -#include "Serialization/IArchive.h" - -#include "Cry_Vector2.h" -#include "Cry_Vector3.h" -#include "Cry_Vector4.h" -#include "Cry_Quat.h" -#include "Cry_Matrix34.h" -#include "Cry_Geo.h" - - -template -bool Serialize(Serialization::IArchive& ar, Vec2_tpl& value, const char* name, const char* label) -{ - typedef T (& Array)[2]; - return ar((Array)value, name, label); -} - -template -bool Serialize(Serialization::IArchive& ar, Vec3_tpl& value, const char* name, const char* label) -{ - typedef T (& Array)[3]; - return ar((Array)value, name, label); -} - -template -inline bool Serialize(Serialization::IArchive& ar, struct Vec4_tpl& v, const char* name, const char* label) -{ - typedef T (& Array)[4]; - return ar((Array)v, name, label); -} - - -template -bool Serialize(Serialization::IArchive& ar, struct Quat_tpl& value, const char* name, const char* label) -{ - typedef T (& Array)[4]; - return ar((Array)value, name, label); -} - -template -struct SerializableQuatT - : QuatT_tpl -{ - void Serialize(Serialization::IArchive& ar) - { - ar(this->q, "q", "Quaternion"); - ar(this->t, "t", "Translation"); - } -}; - -template -bool Serialize(Serialization::IArchive& ar, struct QuatT_tpl& value, const char* name, const char* label) -{ - return Serialize(ar, static_cast&>(value), name, label); -} - -struct SerializableAABB - : AABB -{ - void Serialize(Serialization::IArchive& ar) - { - ar(this->min, "min", "Min"); - ar(this->max, "max", "Max"); - } -}; - -inline bool Serialize(Serialization::IArchive& ar, struct AABB& value, const char* name, const char* label) -{ - return Serialize(ar, static_cast(value), name, label); -} - -template -bool Serialize(Serialization::IArchive& ar, Matrix34_tpl& value, const char* name, const char* label) -{ - typedef T (& Array)[3][4]; - return ar((Array)value, name, label); -} - -////////////////////////////////////////////////////////////////////////// - - -namespace Serialization -{ - template - bool Serialize(Serialization::IArchive& ar, Serialization::SRadiansAsDeg& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - float degrees = RAD2DEG(*value.radians); - float oldDegrees = degrees; - if (!ar(degrees, name, label)) - { - return false; - } - if (oldDegrees != degrees) - { - *value.radians = DEG2RAD(degrees); - } - return true; - } - else - { - return ar(*value.radians, name, label); - } - } - - template - bool Serialize(Serialization::IArchive& ar, Serialization::SRadianAng3AsDeg& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - Ang3 degrees(RAD2DEG(value.ang3->x), RAD2DEG(value.ang3->y), RAD2DEG(value.ang3->z)); - Ang3 oldDegrees = degrees; - if (!ar(degrees, name, label)) - { - return false; - } - if (oldDegrees != degrees) - { - *value.ang3 = Ang3(DEG2RAD(degrees.x), DEG2RAD(degrees.y), DEG2RAD(degrees.z)); - } - return true; - } - else - { - return ar(*value.ang3, name, label); - } - } -} - -////////////////////////////////////////////////////////////////////////// - -template -bool Serialize(Serialization::IArchive& ar, Ang3_tpl& value, const char* name, const char* label) -{ - typedef T (& Array)[3]; - return ar((Array)value, name, label); -} - -////////////////////////////////////////////////////////////////////////// - -namespace Serialization -{ - template - bool Serialize(Serialization::IArchive& ar, Serialization::QuatAsAng3& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - Ang3 ang3(*value.quat); - Ang3 oldAng3 = ang3; - if (!ar(Serialization::RadiansAsDeg(ang3), name, label)) - { - return false; - } - if (ang3 != oldAng3) - { - *value.quat = Quat(ang3); - } - return true; - } - else - { - return ar(*value.quat, name, label); - } - } - - template - bool Serialize(Serialization::IArchive& ar, Serialization::QuatTAsVec3Ang3& value, const char* name, const char* label) - { - if (ar.IsEdit()) - { - if (!ar.OpenBlock(name, label)) - { - return false; - } - - ar(QuatAsAng3((value.trans)->q), "rot", "Rotation"); - ar.Doc("Euler Angles in degrees"); - ar((value.trans)->t, "t", "Translation"); - ar.CloseBlock(); - return true; - } - else - { - return ar(*(value.trans), name, label); - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_MATHIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/NetScriptSerialize.h b/Code/CryEngine/CryCommon/Serialization/NetScriptSerialize.h deleted file mode 100644 index 8c66452419..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/NetScriptSerialize.h +++ /dev/null @@ -1,27 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_CRYCOMMON_CRYSCRIPTSYSTEM_NETSCRIPTSERIALIZE_H -#define CRYINCLUDE_CRYCOMMON_CRYSCRIPTSYSTEM_NETSCRIPTSERIALIZE_H - -namespace Serialization -{ - class INetScriptMarshaler - { - public: - virtual TSerialize FindSerializer(const char* name) = 0; - virtual bool CommitSerializer(const char* name, TSerialize serializer) = 0; - - virtual int GetMaxServerProperties() const = 0; - }; -} - -#endif diff --git a/Code/CryEngine/CryCommon/Serialization/Object.h b/Code/CryEngine/CryCommon/Serialization/Object.h deleted file mode 100644 index d304883452..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Object.h +++ /dev/null @@ -1,153 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_OBJECT_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_OBJECT_H -#pragma once - -#include "Serializer.h" - -// --------------------------------------------------------------------------- - -namespace Serialization { - typedef int(* AddRefFunc)(void*); - typedef int(* DecRefFunc)(void*); - - // represents a reference to the persistent object - class Object - { - public: - Object() - : address_(0) - , addRefFunc_(0) - , decRefFunc_(0) - , serializeFunc_(0) - { - } - - Object(const Object& o) - : address_(o.address_) - , type_(o.type_) - , addRefFunc_(o.addRefFunc_) - , decRefFunc_(o.decRefFunc_) - , serializeFunc_(o.serializeFunc_) - { - addRef(); - } - - Object(const SStruct& ser) - : address_(ser.pointer()) - , type_(ser.type()) - , addRefFunc_(0) - , decRefFunc_(0) - , serializeFunc_(ser.serializeFunc()) - { - } - - Object(void* address, const TypeID& type, AddRefFunc addRefFunc, DecRefFunc decRefFunc, SerializeStructFunc serializeFunc) - : address_(address) - , type_(type) - , addRefFunc_(addRefFunc) - , decRefFunc_(decRefFunc) - , serializeFunc_(serializeFunc) - { - addRef(); - } - - ~Object() - { - if (address_) - { - decRef(); - address_ = 0; - } - } - - void* address() const{ return address_; } - const TypeID& type() const{ return type_; } - bool isSet() { return serializeFunc_ != 0; } - - int addRef() - { - if (!addRefFunc_) - { - return 1; - } - if (!address_) - { - return -1; - } - return addRefFunc_(address_); - } - - int decRef() - { - if (!decRefFunc_) - { - return 1; - } - if (!address_) - { - return -1; - } - return decRefFunc_(address_); - } - - bool operator()(IArchive& ar) const - { - if (!serializeFunc_ || !address_) - { - return false; - } - return serializeFunc_(address_, ar); - } - - SStruct serializer() const - { - return SStruct(type_, address_, 0, serializeFunc_); - } - - Object& operator=(const Object& o) - { - if (this == &o) - { - return *this; - } - - if (address_) - { - decRef(); - } - - address_ = o.address_; - type_ = o.type_; - addRefFunc_ = o.addRefFunc_; - decRefFunc_ = o.decRefFunc_; - serializeFunc_ = o.serializeFunc_; - - addRef(); - return *this; - } - - private: - void* address_; - TypeID type_; - AddRefFunc addRefFunc_; - DecRefFunc decRefFunc_; - SerializeStructFunc serializeFunc_; - }; -} - -// --------------------------------------------------------------------------- - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_OBJECT_H diff --git a/Code/CryEngine/CryCommon/Serialization/STL.h b/Code/CryEngine/CryCommon/Serialization/STL.h deleted file mode 100644 index 357a8937a4..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/STL.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_STL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_STL_H -#pragma once - - -#include -#include -#include - -#include "Serialization/Serializer.h" - -namespace Serialization { - class IArchive; -} - -namespace std -{ - template - bool Serialize(Serialization::IArchive& ar, std::pair& pair, const char* name, const char* label); - - template - bool Serialize(Serialization::IArchive& ar, std::vector& container, const char* name, const char* label); - - template - bool Serialize(Serialization::IArchive& ar, std::list& container, const char* name, const char* label); - - template - bool Serialize(Serialization::IArchive& ar, std::map& container, const char* name, const char* label); -} - -namespace Serialization -{ - bool Serialize(Serialization::IArchive& ar, Serialization::string& value, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::wstring& value, const char* name, const char* label); -} - -#include "STLImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_STL_H diff --git a/Code/CryEngine/CryCommon/Serialization/STLImpl.h b/Code/CryEngine/CryCommon/Serialization/STLImpl.h deleted file mode 100644 index b03d877b55..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/STLImpl.h +++ /dev/null @@ -1,251 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_STLIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_STLIMPL_H -#pragma once - - -#include "Serialization/IArchive.h" -#include "Serialization/Serializer.h" - -namespace Serialization { - template - class ContainerSTL - : public IContainer /*{{{*/ - { - public: - explicit ContainerSTL(Container* container = 0) - : container_(container) - , it_(container->begin()) - , size_(container->size()) - { - YASLI_ASSERT(container_ != 0); - } - - template - void resizeHelper(size_t _size, std::vector* _v) const - { - _v->resize(_size); - } - - void resizeHelper(size_t _size, ...) const - { - while (size_t(container_->size()) > _size) - { - typename Container::iterator it = container_->end(); - --it; - container_->erase(it); - } - while (size_t(container_->size()) < _size) - { - container_->insert(container_->end(), Element()); - } - } - - // from ContainerSerializationInterface - size_t size() const - { - YASLI_ESCAPE(container_ != 0, return 0); - return container_->size(); - } - size_t resize(size_t size) - { - YASLI_ESCAPE(container_ != 0, return 0); - resizeHelper(size, container_); - it_ = container_->begin(); - size_ = size; - return size; - } - - void* pointer() const{ return reinterpret_cast(container_); } - TypeID elementType() const{ return TypeID::get(); } - TypeID containerType() const{ return TypeID::get(); } - - - bool next() - { - YASLI_ESCAPE(container_ && it_ != container_->end(), return false); - ++it_; - return it_ != container_->end(); - } - - void* elementPointer() const { return &*it_; } - size_t elementSize() const { return sizeof(typename Container::value_type); } - - bool operator()(IArchive& ar, const char* name, const char* label) - { - YASLI_ESCAPE(container_, return false); - if (it_ == container_->end()) - { - it_ = container_->insert(container_->end(), Element()); - return ar(*it_, name, label); - } - else - { - return ar(*it_, name, label); - } - } - operator bool() const{ - return container_ != 0; - } - void serializeNewElement(IArchive& ar, const char* name = "", const char* label = 0) const - { - Element element; - ar(element, name, label); - } - // ^^^ - protected: - Container* container_; - typename Container::iterator it_; - size_t size_; - };/*}}}*/ -} - -namespace std -{ - template - bool Serialize(Serialization::IArchive& ar, std::vector& container, const char* name, const char* label) - { - Serialization::ContainerSTL, T> ser(&container); - return ar(static_cast(ser), name, label); - } - - template - bool Serialize(Serialization::IArchive& ar, std::list& container, const char* name, const char* label) - { - Serialization::ContainerSTL, T> ser(&container); - return ar(static_cast(ser), name, label); - } - - template - bool Serialize(Serialization::IArchive& ar, std::map& container, const char* name, const char* label) - { - std::vector > temp; - if (ar.IsOutput()) - { - temp.assign(container.begin(), container.end()); - } - if (!ar(temp, name, label)) - { - return false; - } - if (ar.IsInput()) - { - container.clear(); - container.insert(temp.begin(), temp.end()); - } - return true; - } -} - -// --------------------------------------------------------------------------- -namespace Serialization { - class StringSTL - : public IString - { - public: - StringSTL(string& str) - : str_(str) { } - - void set(const char* value) { str_ = value; } - const char* get() const { return str_.c_str(); } - const void* handle() const { return &str_; } - TypeID type() const { return TypeID::get(); } - private: - string& str_; - }; - - inline bool Serialize(Serialization::IArchive& ar, Serialization::string& value, const char* name, const char* label) - { - Serialization::StringSTL str(value); - return ar(static_cast(str), name, label); - } - - // --------------------------------------------------------------------------- - - class WStringSTL - : public IWString - { - public: - WStringSTL(Serialization::wstring& str) - : str_(str) { } - - void set(const wchar_t* value) { str_ = value; } - const wchar_t* get() const { return str_.c_str(); } - const void* handle() const { return &str_; } - TypeID type() const { return TypeID::get(); } - private: - wstring& str_; - }; - - inline bool Serialize(Serialization::IArchive& ar, Serialization::wstring& value, const char* name, const char* label) - { - Serialization::WStringSTL str(value); - return ar(static_cast(str), name, label); - } - - // --------------------------------------------------------------------------- - - template - struct StdPair - { - StdPair(std::pair& pair) - : pair_(pair) {} - void Serialize(Serialization::IArchive& ar) - { - ar(pair_.first, "key", "Key"); - ar(pair_.second, "value", "Value"); - } - std::pair& pair_; - }; - - template - struct StdStringPair - : Serialization::IKeyValue - { - const char* get() const { return pair_.first.c_str(); } - void set(const char* key) { pair_.first.assign(key); } - const void* handle() const { return &pair_; } - Serialization::TypeID type() const { return Serialization::TypeID::get(); } - bool serializeValue(Serialization::IArchive& ar, const char* name, const char* label) - { - return ar(pair_.second, name, label); - } - - StdStringPair(std::pair& pair) - : pair_(pair) - { - } - - std::pair& pair_; - }; -} - -namespace std -{ - template - bool Serialize(Serialization::IArchive& ar, std::pair& pair, const char* name, const char* label) - { - Serialization::StdPair keyValue(pair); - return ar(keyValue, name, label); - } - - template - bool Serialize(Serialization::IArchive& ar, std::pair& pair, const char* name, const char* label) - { - Serialization::StdStringPair keyValue(pair); - return ar(static_cast(keyValue), name, label); - } -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_STLIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Serializer.h b/Code/CryEngine/CryCommon/Serialization/Serializer.h deleted file mode 100644 index 13acc57cec..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Serializer.h +++ /dev/null @@ -1,268 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_SERIALIZER_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_SERIALIZER_H -#pragma once - - -#include -#include "Assert.h" -#include "TypeID.h" - -namespace Serialization { - class IArchive; - class IClassFactory; - - typedef bool(* SerializeStructFunc)(void*, IArchive&); - - typedef bool(* SerializeContainerFunc)(void*, IArchive&, size_t index); - typedef size_t(* ContainerResizeFunc)(void*, size_t size); - typedef size_t(* ContainerSizeFunc)(void*); - - // Struct serializer. - // - // This type is used to pass needed struct/class type information through abstract interface. - // Most importantly it captures: - // - pointer to object - // - reference to serialize method (indirectly through pointer to static func.) - // - TypeID - struct SStruct/*{{{*/ - { - friend class IArchive; - public: - SStruct() - : object_(0) - , size_(0) - , serializeFunc_(0) - { - } - - SStruct(TypeID type, void* object, size_t size, SerializeStructFunc Serialize) - : type_(type) - , object_(object) - , size_(size) - , serializeFunc_(Serialize) - { - YASLI_ASSERT(object != 0); - } - - SStruct(const SStruct& _original) - : type_(_original.type_) - , object_(_original.object_) - , size_(_original.size_) - , serializeFunc_(_original.serializeFunc_) - { - } - - template - explicit SStruct(const T& object) - { - type_ = TypeID::get(); - object_ = (void*)(&object); - size_ = sizeof(T); - serializeFunc_ = &SStruct::serializeRaw; - } - - template - explicit SStruct(const T& object, TypeID type) - { - type_ = type; - object_ = (void*)(&object); - size_ = sizeof(T); - serializeFunc_ = &SStruct::serializeRaw; - } - - // This constructs SStruct from an object that doesn't have Serialize method. - // Such SStruct can not be serialized but conveys object reference and type - // information that is needed for Property-archives. Used for decorators. - template - static SStruct ForEdit(const T& object) - { - SStruct r; - r.type_ = TypeID::get(); - r.object_ = (void*)&object; - r.size_ = sizeof(T); - r.serializeFunc_ = 0; - return r; - } - - bool operator()(IArchive& ar, const char* name, const char* label) const; - bool operator()(IArchive& ar) const; - operator bool() const{ - return object_ != 0; - } - bool operator==(const SStruct& rhs) const{ return object_ == rhs.object_ && serializeFunc_ == rhs.serializeFunc_; } - bool operator!=(const SStruct& rhs) const{ return !operator==(rhs); } - void* pointer() const{ return object_; } - void setPointer(void* p) { object_ = p; } - TypeID type() const{ return type_; } - void setType(const TypeID& type) { type_ = type; } - size_t size() const{ return size_; } - SerializeStructFunc serializeFunc() const{ return serializeFunc_; } - - template - static bool serializeRaw(void* rawPointer, IArchive& ar) - { - YASLI_ESCAPE(rawPointer, return false); - // If you're getting compile error here, most likely, you have one of the following situations: - // - The type you're trying to serialize doesn't have Serialize _method_ implemented. - // - Type is supposed to be serialized with non-member Serialize function and this function is out of scope. - ((T*)(rawPointer))->Serialize(ar); - return true; - } - - template - T* cast() const - { - if (type_ == Serialization::TypeID::get()) - { - return (T*)object_; - } - else - { - return 0; - } - } - private: - - TypeID type_; - void* object_; - size_t size_; - SerializeStructFunc serializeFunc_; - };/*}}}*/ - typedef std::vector SStructs; - - // --------------------------------------------------------------------------- - - // This type is used to generalize access to specific container types. - // It is used by concrete IArchive implementations. - class IContainer - { - public: - virtual ~IContainer() { } - - virtual size_t size() const = 0; - virtual size_t resize(size_t size) = 0; - virtual bool isFixedSize() const{ return false; } - - virtual void* pointer() const = 0; - virtual bool next() = 0; - virtual TypeID containerType() const = 0; - - virtual TypeID elementType() const = 0; - virtual void* elementPointer() const = 0; - virtual size_t elementSize() const = 0; - - virtual bool operator()(IArchive& ar, const char* name, const char* label) = 0; - virtual operator bool() const = 0; - virtual void serializeNewElement(IArchive& ar, const char* name = "", const char* label = 0) const = 0; - }; - - template - class ContainerArray - : public IContainer /*{{{*/ - { - friend class IArchive; - public: - explicit ContainerArray(T* array = 0, int size = 0) - : array_(array) - , index_(0) - , size_(size) - { - } - - // from ContainerSerializationInterface: - size_t size() const{ return size_; } - size_t resize([[maybe_unused]] size_t size) - { - index_ = 0; - return size_; - } - - void* pointer() const{ return reinterpret_cast(array_); } - TypeID containerType() const{ return TypeID::get(); } - TypeID elementType() const{ return TypeID::get(); } - void* elementPointer() const { return &array_[index_]; } - size_t elementSize() const { return sizeof(T); } - virtual bool isFixedSize() const{ return true; } - - bool operator()(IArchive& ar, const char* name, const char* label) - { - YASLI_ESCAPE(size_t(index_) < size_, return false); - return ar(array_[index_], name, label); - } - operator bool() const{ - return array_ != 0; - } - bool next() - { - ++index_; - return size_t(index_) < size_; - } - void serializeNewElement(IArchive& ar, const char* name, const char* label) const - { - T element; - ar(element, name, label); - } - // ^^^ - - private: - T* array_; - int index_; - size_t size_; - };/*}}}*/ - - // Generialized interface over owning polymorphic pointers. - // Used by concrete IArchive implementations. - class IPointer - { - public: - virtual ~IPointer() { } - - virtual const char* registeredTypeName() const = 0; - virtual void create(const char* registedTypeName) const = 0; - virtual TypeID baseType() const = 0; - virtual SStruct serializer() const = 0; - virtual void* get() const = 0; - virtual const void* handle() const = 0; - virtual TypeID pointerType() const = 0; - virtual IClassFactory* factory() const = 0; - - void Serialize(IArchive& ar) const; - }; - - class IString - { - public: - virtual ~IString() { } - - virtual void set(const char* value) = 0; - virtual const char* get() const = 0; - virtual const void* handle() const = 0; - virtual TypeID type() const = 0; - }; - class IWString - { - public: - virtual ~IWString() { } - - virtual void set(const wchar_t* value) = 0; - virtual const wchar_t* get() const = 0; - virtual const void* handle() const = 0; - virtual TypeID type() const = 0; - }; -} -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_SERIALIZER_H diff --git a/Code/CryEngine/CryCommon/Serialization/SerializerImpl.h b/Code/CryEngine/CryCommon/Serialization/SerializerImpl.h deleted file mode 100644 index f4e89c185d..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/SerializerImpl.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_SERIALIZERIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_SERIALIZERIMPL_H -#pragma once - -#include "Serializer.h" -#include "IClassFactory.h" -#include "ClassFactory.h" - -// IArchive.h is supposed to be pre-included - -namespace Serialization { - inline bool SStruct::operator()(IArchive& ar) const - { - YASLI_ESCAPE(serializeFunc_ && object_, return false); - return serializeFunc_(object_, ar); - } - - inline bool SStruct::operator()(IArchive& ar, const char* name, const char* label) const - { - return ar(*this, name, label); - } - - - inline void IPointer::Serialize(IArchive& ar) const - { - const bool noEmptyNames = ar.GetCaps(IArchive::NO_EMPTY_NAMES); - const char* const typePropertyName = noEmptyNames ? "type" : ""; - const char* const dataPropertyName = noEmptyNames ? "data" : ""; - - TypeID baseTypeID = baseType(); - const char* oldRegisteredName = registeredTypeName(); - if (!oldRegisteredName) - { - oldRegisteredName = ""; - } - IClassFactory* factory = this->factory(); - - if (ar.IsOutput()) - { - if (oldRegisteredName[0] != '\0') - { - TypeNameWithFactory pair(oldRegisteredName, factory); - if (ar(pair, typePropertyName)) - { - ar(serializer(), dataPropertyName); - } - else - { - ar.Warning(pair, "Unable to write typeID!"); - } - } - } - else - { - TypeNameWithFactory pair("", factory); - if (!ar(pair, typePropertyName)) - { - if (oldRegisteredName[0] != '\0') - { - create(""); // 0 - } - return; - } - - if (oldRegisteredName[0] != '\0' && (pair.registeredName.empty() || (pair.registeredName != oldRegisteredName))) - { - create(""); // 0 - } - if (!pair.registeredName.empty()) - { - if (!get()) - { - create(pair.registeredName.c_str()); - } - ar(serializer(), dataPropertyName); - } - } - } -} -// vim:sw=4 ts=4: - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_SERIALIZERIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/SmartPtr.h b/Code/CryEngine/CryCommon/Serialization/SmartPtr.h deleted file mode 100644 index 8c109887b7..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/SmartPtr.h +++ /dev/null @@ -1,31 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_SMARTPTR_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_SMARTPTR_H -#pragma once - -template -class _smart_ptr; - -namespace Serialization -{ - class IArchive; -}; - -template -bool Serialize(Serialization::IArchive& ar, _smart_ptr& ptr, const char* name, const char* label); - -#include "SmartPtrImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_SMARTPTR_H diff --git a/Code/CryEngine/CryCommon/Serialization/SmartPtrImpl.h b/Code/CryEngine/CryCommon/Serialization/SmartPtrImpl.h deleted file mode 100644 index 64cd7f65c1..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/SmartPtrImpl.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_SMARTPTRIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_SMARTPTRIMPL_H -#pragma once - -#include "SmartPtr.h" -#include -#include "ClassFactory.h" - -// Exposes _smart_ptr<> as serializeable type for Serialization::IArchive -template -class SmartPtrSerializer - : public Serialization::IPointer -{ -public: - SmartPtrSerializer(_smart_ptr& ptr) - : m_ptr(ptr) - {} - - const char* registeredTypeName() const override - { - if (m_ptr) - { - return Serialization::ClassFactory::the().getRegisteredTypeName(m_ptr.get()); - } - else - { - return ""; - } - } - - void create(const char* registeredTypeName) const override - { - CRY_ASSERT(!m_ptr || m_ptr->NumRefs() == 1); - if (registeredTypeName && registeredTypeName[0] != '\0') - { - m_ptr.reset(Serialization::ClassFactory::the().create(registeredTypeName)); - } - else - { - m_ptr.reset((T*)0); - } - } - Serialization::TypeID baseType() const{ return Serialization::TypeID::get(); } - virtual Serialization::SStruct serializer() const{ return Serialization::SStruct(*m_ptr); } - void* get() const{ return reinterpret_cast(m_ptr.get()); } - const void* handle() const { return &m_ptr; } - Serialization::TypeID pointerType() const { return Serialization::TypeID::get<_smart_ptr >(); } - Serialization::IClassFactory* factory() const{ return &Serialization::ClassFactory::the(); } -protected: - _smart_ptr& m_ptr; -}; - -template -bool Serialize(Serialization::IArchive& ar, _smart_ptr& ptr, const char* name, const char* label) -{ - SmartPtrSerializer serializer(ptr); - return ar(static_cast(serializer), name, label); -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_SMARTPTRIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/StringList.h b/Code/CryEngine/CryCommon/Serialization/StringList.h deleted file mode 100644 index 4b2ca96278..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/StringList.h +++ /dev/null @@ -1,301 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGLIST_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGLIST_H -#pragma once - - -#include -#include "Serialization/Strings.h" -#include "Serialization/DynArray.h" -#include -#include "Serialization/Assert.h" -#ifndef SERIALIZATION_STANDALONE -#include -#endif - -#include - -namespace Serialization { - class IArchive; - class StringListStatic -#ifdef SERIALIZATION_STANDALONE - : public std::vector - { -#else - : public AZStd::fixed_vector { -#endif - public: - enum - { - npos = -1 - }; - int find(const char* value) const - { - int numItems = int(size()); - for (int i = 0; i < numItems; ++i) - { - if (strcmp((*this)[i], value) == 0) - { - return i; - } - } - return npos; - } - }; - - class StringListStaticValue - { - public: - StringListStaticValue(const StringListStaticValue& original) - : stringList_(original.stringList_) - , index_(original.index_) - { - handle_ = this; - } - StringListStaticValue() - : stringList_(0) - , index_(StringListStatic::npos) - { - handle_ = this; - } - StringListStaticValue(const StringListStatic& stringList, int value) - : stringList_(&stringList) - , index_(value) - { - handle_ = this; - } - StringListStaticValue(const StringListStatic& stringList, int value, const void* handle, const Serialization::TypeID& type) - : stringList_(&stringList) - , index_(value) - , handle_(handle) - , type_(type) - { - } - StringListStaticValue(const StringListStatic& stringList, const char* value, const void* handle, const Serialization::TypeID& type) - : stringList_(&stringList) - , index_(stringList.find(value)) - , handle_(handle) - , type_(type) - { - YASLI_ASSERT(index_ != StringListStatic::npos); - } - StringListStaticValue& operator=(const char* value) - { - index_ = stringList_->find(value); - return *this; - } - StringListStaticValue& operator=(int value) - { - YASLI_ASSERT(value >= 0 && size_t(value) < size_t(stringList_->size())); - YASLI_ASSERT(this != 0); - index_ = value; - return *this; - } - StringListStaticValue& operator=(const StringListStaticValue& rhs) - { - stringList_ = rhs.stringList_; - index_ = rhs.index_; - return *this; - } - const char* c_str() const - { - if (index_ >= 0 && size_t(index_) < size_t(stringList_->size())) - { - return (*stringList_)[index_]; - } - else - { - return ""; - } - } - int index() const{ return index_; } - const void* handle() const{ return handle_; } - Serialization::TypeID type() const { return type_; } - const StringListStatic& stringList() const{ return *stringList_; } - template - void Serialize(IArchive& ar) - { - ar(index_, "index"); - } - protected: - const StringListStatic* stringList_; - int index_; - const void* handle_; - Serialization::TypeID type_; - }; - - class StringList -#ifdef SERIALIZATION_STANDALONE - : public std::vector - { -#else - : public DynArray{ -#endif - public: - StringList() {} - StringList(const StringList& rhs) - { - *this = rhs; - } - StringList& operator=(const StringList& rhs) - { - // As StringList crosses dll boundaries it is important to copy strings - // rather than reference count them to be sure that stored CryString uses - // proper allocator. - resize(rhs.size()); - for (size_t i = 0; i < size_t(size()); ++i) - { - (*this)[i] = rhs[i].c_str(); - } - return *this; - } - StringList(const StringListStatic& rhs) - { - const int size = int(rhs.size()); - resize(size); - for (int i = 0; i < int(size); ++i) - { - (*this)[i] = rhs[i]; - } - } - enum - { - npos = -1 - }; - int find(const char* value) const - { - const int numItems = int(size()); - for (int i = 0; i < numItems; ++i) - { - if ((*this)[i] == value) - { - return i; - } - } - return npos; - } - }; - - class StringListValue - { - public: - explicit StringListValue(const StringListStaticValue& value) - { - stringList_.resize(value.stringList().size()); - for (size_t i = 0; i < size_t(stringList_.size()); ++i) - { - stringList_[i] = value.stringList()[i]; - } - index_ = value.index(); - } - StringListValue(const StringListValue& value) - { - stringList_ = value.stringList_; - index_ = value.index_; - } - StringListValue() - : index_(StringList::npos) - { - handle_ = this; - } - StringListValue(const StringList& stringList, int value) - : stringList_(stringList) - , index_(value) - { - handle_ = this; - } - StringListValue(const StringList& stringList, int value, const void* handle, const Serialization::TypeID& typeId) - : stringList_(stringList) - , index_(value) - , handle_(handle) - , type_(typeId) - { - } - StringListValue(const StringList& stringList, const char* value) - : stringList_(stringList) - , index_(stringList.find(value)) - { - handle_ = this; - YASLI_ASSERT(index_ != StringList::npos); - } - StringListValue(const StringList& stringList, const char* value, const void* handle, const Serialization::TypeID& typeId) - : stringList_(stringList) - , index_(stringList.find(value)) - , handle_(handle) - , type_(typeId) - { - YASLI_ASSERT(index_ != StringList::npos); - } - StringListValue(const StringListStatic& stringList, const char* value) - : stringList_(stringList) - , index_(stringList.find(value)) - { - handle_ = this; - YASLI_ASSERT(index_ != StringList::npos); - } - StringListValue& operator=(const char* value) - { - index_ = stringList_.find(value); - return *this; - } - StringListValue& operator=(int value) - { - YASLI_ASSERT(value >= 0 && size_t(value) < size_t(stringList_.size())); - YASLI_ASSERT(this != 0); - index_ = value; - return *this; - } - const char* c_str() const - { - if (index_ >= 0 && size_t(index_) < size_t(stringList_.size())) - { - return stringList_[index_].c_str(); - } - else - { - return ""; - } - } - int index() const{ return index_; } - const void* handle() const { return handle_; } - Serialization::TypeID type() const { return type_; } - const StringList& stringList() const{ return stringList_; } - template - void Serialize(IArchive& ar) - { - ar(index_, "index"); - ar(stringList_, "stringList"); - } - protected: - StringList stringList_; - int index_; - const void* handle_; - Serialization::TypeID type_; - }; - - class IArchive; - - void splitStringList(StringList* result, const char* str, char sep); - void joinStringList(string* result, const StringList& stringList, char sep); - void joinStringList(string* result, const StringListStatic& stringList, char sep); - - bool Serialize(Serialization::IArchive& ar, Serialization::StringList& value, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::StringListValue& value, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::StringListStaticValue& value, const char* name, const char* label); -} - -#include "StringListImpl.h" - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGLIST_H diff --git a/Code/CryEngine/CryCommon/Serialization/StringListImpl.h b/Code/CryEngine/CryCommon/Serialization/StringListImpl.h deleted file mode 100644 index 4f7b573623..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/StringListImpl.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGLISTIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGLISTIMPL_H -#pragma once - -#include "StringList.h" -#include "IArchive.h" -#include "DynArray.h" -#include "STL.h" - -namespace Serialization { - // --------------------------------------------------------------------------- - inline void splitStringList(StringList* result, const char* str, char delimeter) - { - result->clear(); - - const char* ptr = str; - for (; *ptr; ++ptr) - { - if (*ptr == delimeter) - { - result->push_back(string(str, ptr)); - str = ptr + 1; - } - } - result->push_back(string(str, ptr)); - } - - inline void joinStringList(string* result, const StringList& stringList, char sep) - { - YASLI_ESCAPE(result != 0, return ); - result->clear(); - for (StringList::const_iterator it = stringList.begin(); it != stringList.end(); ++it) - { - if (!result->empty()) - { - result += sep; - } - result->append(*it); - } - } - - inline void joinStringList(string* result, const StringListStatic& stringList, char sep) - { - YASLI_ESCAPE(result != 0, return ); - result->clear(); - for (StringListStatic::const_iterator it = stringList.begin(); it != stringList.end(); ++it) - { - if (!result->empty()) - { - (*result) += sep; - } - YASLI_ESCAPE(*it != 0, continue); - result->append(*it); - } - } - - inline bool Serialize(Serialization::IArchive& ar, Serialization::StringList& value, const char* name, const char* label) - { -#ifdef SERIALIZATION_STANDALONE - return ar(static_cast&>(value), name, label); -#else - return ar(static_cast&>(value), name, label); -#endif - } - - inline bool Serialize(Serialization::IArchive& ar, Serialization::StringListValue& value, const char* name, const char* label) - { - using Serialization::string; - if (ar.IsEdit()) - { - return ar(Serialization::SStruct(value), name, label); - } - else - { - string str; - if (ar.IsOutput()) - { - str = value.c_str(); - } - if (ar(str, name, label) && ar.IsInput()) - { - value = str.c_str(); - return true; - } - return false; - } - } - - inline bool Serialize(Serialization::IArchive& ar, Serialization::StringListStaticValue& value, const char* name, const char* label) - { - using Serialization::string; - if (ar.IsEdit()) - { - return ar(Serialization::SStruct(value), name, label); - } - else - { - string str; - if (ar.IsOutput()) - { - str = value.c_str(); - } - if (ar(str, name, label) && ar.IsInput()) - { - value = str.c_str(); - return true; - } - return true; - } - } -} - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGLISTIMPL_H diff --git a/Code/CryEngine/CryCommon/Serialization/Strings.h b/Code/CryEngine/CryCommon/Serialization/Strings.h deleted file mode 100644 index db8be9c3b8..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/Strings.h +++ /dev/null @@ -1,32 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGS_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGS_H -#pragma once - -#ifdef SERIALIZATION_STANDALONE -#include -namespace Serialization { - using std::string; - using std::wstring; -} -#else -#include - -namespace Serialization { - typedef CryStringT string; - typedef CryStringT wstring; -} -#endif // SERIALIZATION_STANDALONE -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_STRINGS_H diff --git a/Code/CryEngine/CryCommon/Serialization/TypeID.h b/Code/CryEngine/CryCommon/Serialization/TypeID.h deleted file mode 100644 index 067813d9fc..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/TypeID.h +++ /dev/null @@ -1,290 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEID_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEID_H -#pragma once - - -#include "Serialization/Assert.h" -#include "Serialization/Strings.h" -#include - -namespace Serialization { - class IArchive; - struct TypeInfo; - class TypeID - { - public: - TypeID() - : typeInfo_(0) - , module_(0) {} - - TypeID(const TypeID& original) - : typeInfo_(original.typeInfo_) - , module_(original.module_) - { - } - - operator bool() const{ - return *this != TypeID(); - } - - template - static TypeID get(); - std::size_t sizeOf() const; - const char* name() const; - - bool operator==(const TypeID& rhs) const; - bool operator!=(const TypeID& rhs) const; - bool operator<(const TypeID& rhs) const; - private: - TypeInfo* typeInfo_; - void* module_; - friend struct TypeInfo; - friend class TypeDescription; - }; - - struct TypeInfo - { - TypeID id; - size_t size; - char name[128]; - - // We are trying to minimize type names here. Stripping namespaces, - // whitespaces and S/C/E/I prefixes. Why namespaces? Type names are usually - // used in two contexts: for unique name within factory context, where - // collision is unlikely, or for filtering in PropertyTree where concise - // name is much more useful. - static void cleanTypeName(char*& d, const char* dend, const char*& s, const char* send) - { - if (strncmp(s, "class ", 6) == 0) - { - s += 6; - } - else if (strncmp(s, "struct ", 7) == 0) - { - s += 7; - } - - while (*s == ' ' && s != send) - { - ++s; - } - - // strip C/S/I/E prefixes - if ((*s == 'C' || *s == 'S' || *s == 'I' || *s == 'E') && s[1] >= 'A' && s[1] <= 'Z') - { - ++s; - } - - if (s >= send) - { - return; - } - - char* startd = d; - while (d != dend && s != send) - { - while (*s == ' ' && s != send) - { - ++s; - } - if (s == send) - { - break; - } - if (*s == ':' && s[1] == ':') - { - // strip namespaces - s += 2; - d = startd; - - if ((*s == 'C' || *s == 'S' || *s == 'I' || *s == 'E') && s[1] >= 'A' && s[1] <= 'Z') - { - ++s; - } - } - if (s >= send) - { - break; - } - if (*s == '<') - { - * d = '<'; - ++d; - ++s; - cleanTypeName(d, dend, s, send); - } - else if (*s == '>') - { - * d = '\0'; - return; - } - * d = *s; - ++s; - ++d; - } - } - - template - static void extractTypeName(char (&name)[nameLen], const char* funcName) - { -#ifdef __clang__ - // "static yasli::TypeID yasli::TypeID::get() [T = ActualTypeName]" - const char* s = strstr(funcName, "[T = "); - if (s) - { - s += 5; - } - const char* send = strrchr(funcName, ']'); -#elif __GNUC__ >= 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 4) - // "static yasli::TypeID yasli::TypeID::get() [with T = ActualTypeName]" - const char* s = strstr(funcName, "[with T = "); - if (s) - { - s += 9; - } - const char* send = strrchr(funcName, ']'); -#else - // "static yasli::TypeID yasli::TypeID::get()" - const char* s = strchr(funcName, '<'); - const char* send = strrchr(funcName, '>'); - YASLI_ASSERT(s != 0 && send != 0); - if (s != send) - { - ++s; - } -#endif - YASLI_ASSERT(s != 0 && send != 0); - - char* d = name; - const char* dend = name + sizeof(name) - 1; - cleanTypeName(d, dend, s, send); - * d = '\0'; - - // This assertion is not critical, but may result in collision as - // stripped name wil be used, e.g. for lookup in factory. - YASLI_ASSERT(s == send && "Type name does not fit into the buffer"); - } - - TypeInfo(size_t _size, const char* templatedFunctionName) - : size(_size) - { - extractTypeName(name, templatedFunctionName); - id.typeInfo_ = this; - static int moduleSpecificSymbol; - id.module_ = &moduleSpecificSymbol; - } - - bool operator==(const TypeInfo& rhs) const - { - return size == rhs.size && strcmp(name, rhs.name) == 0; - } - - bool operator<(const TypeInfo& rhs) const - { - if (size == rhs.size) - { - return strcmp(name, rhs.name) < 0; - } - else - { - return size < rhs.size; - } - } - }; - - template - TypeID TypeID::get() - { -#ifdef _MSC_VER - static TypeInfo typeInfo(sizeof(T), __FUNCSIG__); -#else - static TypeInfo typeInfo(sizeof(T), __PRETTY_FUNCTION__); -#endif - return typeInfo.id; - } - - inline const char* TypeID::name() const - { - if (typeInfo_) - { - return typeInfo_->name; - } - else - { - return ""; - } - } - - inline size_t TypeID::sizeOf() const - { - if (typeInfo_) - { - return typeInfo_->size; - } - else - { - return 0; - } - } - - inline bool TypeID::operator==(const TypeID& rhs) const - { - if (typeInfo_ == rhs.typeInfo_) - { - return true; - } - else if (!typeInfo_ || !rhs.typeInfo_) - { - return false; - } - else if (module_ == rhs.module_) - { - return false; - } - else - { - return *typeInfo_ == *rhs.typeInfo_; - } - } - - inline bool TypeID::operator!=(const TypeID& rhs) const - { - return !operator==(rhs); - } - - inline bool TypeID::operator<(const TypeID& rhs) const - { - if (!typeInfo_) - { - return rhs.typeInfo_ != 0; - } - else if (!rhs.typeInfo_) - { - return false; - } - else - { - return *typeInfo_ < *rhs.typeInfo_; - } - } - - template - T* createDerivedClass(TypeID typeID); -} - -//bool Serialize(Serialization::IArchive& ar, Serialization::TypeID& typeID, const char* name, const char* label); - -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEID_H diff --git a/Code/CryEngine/CryCommon/Serialization/TypeInfo.h b/Code/CryEngine/CryCommon/Serialization/TypeInfo.h deleted file mode 100644 index eafd959d51..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/TypeInfo.h +++ /dev/null @@ -1,46 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFO_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFO_H -#pragma once - - -namespace Serialization { - class IArchive; -} - -struct STypeInfoInstance -{ - template - STypeInfoInstance(T& obj) - : m_pTypeInfo(&TypeInfo(&obj)) - , m_pObject(&obj) - { - } - - STypeInfoInstance(const CTypeInfo* typeInfo, void* object) - : m_pTypeInfo(typeInfo) - , m_pObject(object) - { - } - - inline void Serialize(Serialization::IArchive& ar); - - const CTypeInfo* m_pTypeInfo; - void* m_pObject; - std::set m_persistentStrings; -}; - -#include "TypeInfoImpl.h" -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFO_H diff --git a/Code/CryEngine/CryCommon/Serialization/TypeInfoImpl.h b/Code/CryEngine/CryCommon/Serialization/TypeInfoImpl.h deleted file mode 100644 index 7f94e8bec7..0000000000 --- a/Code/CryEngine/CryCommon/Serialization/TypeInfoImpl.h +++ /dev/null @@ -1,245 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFOIMPL_H -#define CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFOIMPL_H -#pragma once - - - -#include "CryTypeInfo.h" -#include "Serialization/Decorators/Range.h" -#include "Serialization/Enum.h" -#include "ISplines.h" -#include -#include "Serialization/Color.h" -#include "Cry_Color.h" -#include "Decorators/Resources.h" - -struct SPrivateTypeInfoInstanceLevel -{ - SPrivateTypeInfoInstanceLevel(const CTypeInfo* typeInfo, void* object, STypeInfoInstance* instance) - : m_pTypeInfo(typeInfo) - , m_pObject(object) - , m_instance(instance) - { - } - - void Serialize(Serialization::IArchive& ar) - { - for AllSubVars(pVar, *m_pTypeInfo) - { - string group; - if (pVar->GetAttr("Group", group)) - { - if (!m_sCurrentGroup.empty()) - { - ar.CloseBlock(); - } - const char* name = m_instance->m_persistentStrings.insert(group).first->c_str(); - ar.OpenBlock(name, name); - m_sCurrentGroup = name; - } - else - { - const char* name = pVar->GetName(); - if (!*name) - { - name = pVar->Type.Name; - } - - const char* label = pVar->GetName(); - if (!*label) - { - string n = "^"; - n += pVar->GetName(); - label = m_instance->m_persistentStrings.insert(n).first->c_str(); - } - - SerializeVariable(pVar, m_pObject, ar, name, label); - } - } - - if (!m_sCurrentGroup.empty()) - { - ar.CloseBlock(); - m_sCurrentGroup.clear(); - } - } - - template - void SerializeT(const CTypeInfo::CVarInfo* pVar, void* pParentAddress, Serialization::IArchive& ar, const char* name, const char* label) - { - T value; - const CTypeInfo& type = pVar->Type; - type.ToValue(pVar->GetAddress(pParentAddress), value); - ar(value, name, label); - if (ar.IsInput()) - { - type.FromValue(pVar->GetAddress(pParentAddress), value); - } - } - - template - void SerializeNumericalT(const CTypeInfo::CVarInfo* pVar, void* pParentAddress, Serialization::IArchive& ar, const char* name, const char* label) - { - T value; - const CTypeInfo& type = pVar->Type; - type.ToValue(pVar->GetAddress(pParentAddress), value); - - float limMin, limMax; - if (pVar->GetLimit(eLimit_Min, limMin) && pVar->GetLimit(eLimit_Max, limMax)) - { - ar(Serialization::Range(value, limMin, limMax), name, label); - } - else - { - ar(value, name, label); - } - if (ar.IsInput()) - { - type.FromValue(pVar->GetAddress(pParentAddress), value); - } - } - - void SerializeVariable(const CTypeInfo::CVarInfo* pVar, void* pParentAddress, Serialization::IArchive& ar, const char* name, const char* label) - { - const CTypeInfo& type = pVar->Type; - - if (type.HasSubVars()) - { - if (strcmp(name, "Color") == 0) - { - Color3F value; - const CTypeInfo& type = pVar->Type; - type.ToValue(pVar->GetAddress(pParentAddress), value); - ColorF colour = value; - ar(colour, name, label); - if (ar.IsInput()) - { - value = Color3F(colour.r, colour.g, colour.b); - type.FromValue(pVar->GetAddress(pParentAddress), value); - } - } - else - { - // load params of sub-variables (variable is a struct or vector) - SPrivateTypeInfoInstanceLevel instance(&type, pVar->GetAddress(pParentAddress), m_instance); - ar(instance, name, label); - } - } - else - { - if (type.IsType()) - { - SerializeT(pVar, pParentAddress, ar, name, label); - } - else if (type.IsType()) - { - SerializeNumericalT(pVar, pParentAddress, ar, name, label); - } - else if (type.IsType()) - { - SerializeNumericalT(pVar, pParentAddress, ar, name, label); - } - else if (type.IsType()) - { - SerializeNumericalT(pVar, pParentAddress, ar, name, label); - } - else if (type.IsType()) - { - SerializeNumericalT(pVar, pParentAddress, ar, name, label); - } - else if (type.IsType()) - { - SerializeNumericalT(pVar, pParentAddress, ar, name, label); - } - else if (type.EnumElem(0)) - { - Serialization::StringList stringList; - const char* enumType = type.EnumElem(0); - for (int i = 1; enumType; ++i) - { - stringList.push_back(enumType); - enumType = type.EnumElem(i); - } - - string enumValue = pVar->ToString(pParentAddress); - int index = std::max(stringList.find(enumValue.c_str()), 0); - - Serialization::StringListValue stringListValue(stringList, index); - ar(stringListValue, name, label); - if (ar.IsInput()) - { - pVar->FromString(pParentAddress, stringListValue.c_str()); - } - } - else - { - ISplineInterpolator* pSpline = 0; - if (type.ToValue(pVar->GetAddress(pParentAddress), pSpline)) - { - // TODO: Curve field - } - else - { - string value; - value = pVar->ToString(pParentAddress); - - if (strcmp(name, "Texture") == 0) - { - // TODO: Texture field - } - else if (strcmp(name, "Material") == 0) - { - // TODO: Material field - } - else if (strcmp(name, "Geometry") == 0) - { - ar(Serialization::ModelFilename(value), name, label); - } - else if (strcmp(name, "Sound") == 0) - { - ar(Serialization::SoundName(value), name, label); - } - else if (strcmp(name, "GeomCache") == 0) - { - // TODO: Geom cache field - } - else - { - ar(value, name, label); - } - if (ar.IsInput()) - { - pVar->FromString(pParentAddress, value.c_str()); - } - } - } - } - } - -private: - const CTypeInfo* m_pTypeInfo; - void* m_pObject; - string m_sCurrentGroup; - STypeInfoInstance* m_instance; -}; - -//------------------------------ -inline void STypeInfoInstance::Serialize(Serialization::IArchive& ar) -{ - SPrivateTypeInfoInstanceLevel instance(m_pTypeInfo, m_pObject, this); - instance.Serialize(ar); -} -#endif // CRYINCLUDE_CRYCOMMON_SERIALIZATION_TYPEINFOIMPL_H diff --git a/Code/CryEngine/CryCommon/crycommon_files.cmake b/Code/CryEngine/CryCommon/crycommon_files.cmake index 3b63dab649..ca95802fd9 100644 --- a/Code/CryEngine/CryCommon/crycommon_files.cmake +++ b/Code/CryEngine/CryCommon/crycommon_files.cmake @@ -20,7 +20,6 @@ set(FILES ICmdLine.h IColorGradingController.h IConsole.h - IEngineModule.h IEntityRenderState.h IEntityRenderState_info.cpp IFlares.h @@ -52,7 +51,6 @@ set(FILES IPostEffectGroup.h IProcess.h IReadWriteXMLSink.h - IRemoteCommand.h IRenderAuxGeom.h IRenderer.h IRenderMesh.h @@ -60,7 +58,6 @@ set(FILES IResourceCompilerHelper.h IResourceManager.h ISerialize.h - IServiceNetwork.h IShader.h IShader_info.h ISoftCodeMgr.h @@ -120,7 +117,6 @@ set(FILES MemoryAccess.h Algorithm.h AnimKey.h - AnimTime.h BitFiddling.h CGFContent.h CGFContent_info.cpp @@ -155,7 +151,6 @@ set(FILES CryVersion.h CryZlib.h FrameProfiler.h - GeomCacheFileFormat.h HashGrid.h HeapAllocator.h HeapContainer.h @@ -207,7 +202,6 @@ set(FILES VectorSet.h VertexFormats.h XMLBinaryHeaders.h - Bezier.h RenderBus.h MainThreadRenderRequestBus.h OceanConstants.h @@ -265,101 +259,7 @@ set(FILES platform_impl.cpp Win32specific.h Win64specific.h - CryExtension/CryCreateClassInstance.h - CryExtension/CryGUID.h - CryExtension/CryTypeID.h - CryExtension/ICryFactory.h - CryExtension/ICryFactoryRegistry.h - CryExtension/ICryUnknown.h - CryExtension/Impl/Conversion.h - CryExtension/Impl/ClassWeaver.h - CryExtension/Impl/CryGUIDHelper.h - CryExtension/Impl/ICryFactoryRegistryImpl.h - CryExtension/Impl/RegFactoryNode.h - CryExtension/Impl/TypeList.h - CryPool/Allocator.h - CryPool/Container.h - CryPool/Defrag.h - CryPool/example.h - CryPool/Fallback.h - CryPool/Inspector.h - CryPool/List.h - CryPool/Memory.h - CryPool/PoolAlloc.h - CryPool/STLWrapper.h - CryPool/ThreadSafe.h stl/STLAlignedAlloc.h - Serialization/Assert.h - Serialization/BitVector.h - Serialization/BitVectorImpl.h - Serialization/BlackBox.h - Serialization/BoostSharedPtr.h - Serialization/Callback.h - Serialization/ClassFactory.h - Serialization/ClassFactoryImpl.h - Serialization/Color.h - Serialization/ColorImpl.h - Serialization/CRCRef.h - Serialization/CRCRefImpl.h - Serialization/CryExtension.h - Serialization/CryExtensionImpl.h - Serialization/CryName.h - Serialization/CryNameImpl.h - Serialization/CryStrings.h - Serialization/CryStringsImpl.h - Serialization/DynArray.h - Serialization/DynArrayImpl.h - Serialization/Enum.h - Serialization/EnumImpl.h - Serialization/IArchive.h - Serialization/IArchiveHost.h - Serialization/IClassFactory.h - Serialization/IntrusiveFactory.h - Serialization/ITextInputArchive.h - Serialization/ITextOutputArchive.h - Serialization/KeyValue.h - Serialization/Math.h - Serialization/MathImpl.h - Serialization/NetScriptSerialize.h - Serialization/Object.h - Serialization/Serializer.h - Serialization/SerializerImpl.h - Serialization/SmartPtr.h - Serialization/SmartPtrImpl.h - Serialization/STL.h - Serialization/STLImpl.h - Serialization/StringList.h - Serialization/StringListImpl.h - Serialization/Strings.h - Serialization/TypeID.h - Serialization/TypeInfo.h - Serialization/TypeInfoImpl.h - Serialization/Decorators/ActionButton.h - Serialization/Decorators/BitFlags.h - Serialization/Decorators/BitFlagsImpl.h - Serialization/Decorators/ColorPicker.h - Serialization/Decorators/ColorPickerImpl.h - Serialization/Decorators/JointName.h - Serialization/Decorators/JointNameImpl.h - Serialization/Decorators/LocalFrame.h - Serialization/Decorators/LocalFrameImpl.h - Serialization/Decorators/OutputFilePath.h - Serialization/Decorators/OutputFilePathImpl.h - Serialization/Decorators/Range.h - Serialization/Decorators/RangeImpl.h - Serialization/Decorators/ResourceFilePath.h - Serialization/Decorators/ResourceFilePathImpl.h - Serialization/Decorators/ResourceFolderPath.h - Serialization/Decorators/ResourceFolderPathImpl.h - Serialization/Decorators/Resources.h - Serialization/Decorators/ResourcesAudio.h - Serialization/Decorators/ResourceSelector.h - Serialization/Decorators/Slider.h - Serialization/Decorators/SliderImpl.h - Serialization/Decorators/Sprite.h - Serialization/Decorators/SpriteImpl.h - Serialization/Decorators/TagList.h - Serialization/Decorators/TagListImpl.h LyShine/IDraw2d.h LyShine/ILyShine.h LyShine/ISprite.h diff --git a/Code/CryEngine/CryCommon/platform_impl.cpp b/Code/CryEngine/CryCommon/platform_impl.cpp index 6c261bb1f1..142f07e5e7 100644 --- a/Code/CryEngine/CryCommon/platform_impl.cpp +++ b/Code/CryEngine/CryCommon/platform_impl.cpp @@ -14,8 +14,7 @@ #include #include #include -#include -#include +#include #include #include @@ -42,9 +41,6 @@ SC_API struct SSystemGlobalEnvironment* gEnv = nullptr; #include AZ_RESTRICTED_FILE(platform_impl_h) #endif -//The reg factory is used for registering the different modules along the whole project -struct SRegFactoryNode* g_pHeadToRegFactories = 0; - ////////////////////////////////////////////////////////////////////////// // If not in static library. #include @@ -106,16 +102,6 @@ extern "C" AZ_DLL_EXPORT void ModuleInitISystem(ISystem* pSystem, [[maybe_unused AZ::AllocatorManager::Instance(); // Force the AllocatorManager to instantiate and register any allocators defined in data sections } AZ::Debug::ProfileModuleInit(); - -#if !defined(AZ_MONOLITHIC_BUILD) - ICryFactoryRegistryImpl* pCryFactoryImpl = static_cast(pSystem->GetCryFactoryRegistry()); - if (pCryFactoryImpl) - { - pCryFactoryImpl->RegisterFactories(g_pHeadToRegFactories); - } - - AZ_Error("System", pCryFactoryImpl, "Failed to successfully load factory for %s. You may have a missing or stale DLL that needs to be recompiled.", moduleName); -#endif } // if pSystem } diff --git a/Code/CryEngine/CrySystem/DllMain.cpp b/Code/CryEngine/CrySystem/DllMain.cpp index aba39fb9fb..6173ebc0c6 100644 --- a/Code/CryEngine/CrySystem/DllMain.cpp +++ b/Code/CryEngine/CrySystem/DllMain.cpp @@ -15,10 +15,6 @@ #include "System.h" #include #include "DebugCallStack.h" -#if defined(AZ_MONOLITHIC_BUILD) -#include -#include -#endif #if defined(AZ_RESTRICTED_PLATFORM) #undef AZ_RESTRICTED_SECTION @@ -132,10 +128,7 @@ CRYSYSTEM_API ISystem* CreateSystemInterface(const SSystemInitParams& startupPar #define AZ_RESTRICTED_SECTION DLLMAIN_CPP_SECTION_2 #include AZ_RESTRICTED_FILE(DllMain_cpp) #endif -#if defined(AZ_MONOLITHIC_BUILD) - ICryFactoryRegistryImpl* pCryFactoryImpl = static_cast(pSystem->GetCryFactoryRegistry()); - pCryFactoryImpl->RegisterFactories(g_pHeadToRegFactories); -#endif // AZ_MONOLITHIC_BUILD + // the earliest point the system exists - w2e tell the callback if (startupParams.pUserCallback) { diff --git a/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.cpp b/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.cpp deleted file mode 100644 index 26c13a070d..0000000000 --- a/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.cpp +++ /dev/null @@ -1,359 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#include "CrySystem_precompiled.h" -#include "CryFactoryRegistryImpl.h" -#include "../System.h" - -#include -#include -#include - -#include - - -CCryFactoryRegistryImpl::CCryFactoryRegistryImpl() - : m_guard() - , m_byCName() - , m_byCID() - , m_byIID() - , m_callbacks() -{ -} - - -CCryFactoryRegistryImpl::~CCryFactoryRegistryImpl() -{ -} - - -CCryFactoryRegistryImpl& CCryFactoryRegistryImpl::Access() -{ - static StaticInstance> s_registry; - return s_registry; -} - - -ICryFactory* CCryFactoryRegistryImpl::GetFactory(const char* cname) const -{ - AUTO_READLOCK(m_guard); - - if (!cname) - { - return 0; - } - - const FactoryByCName search(cname); - FactoriesByCNameConstIt it = std::lower_bound(m_byCName.begin(), m_byCName.end(), search); - return it != m_byCName.end() && !(search < *it) ? (*it).m_ptr : 0; -} - - -ICryFactory* CCryFactoryRegistryImpl::GetFactory(const CryClassID& cid) const -{ - AUTO_READLOCK(m_guard); - - const FactoryByCID search(cid); - FactoriesByCIDConstIt it = std::lower_bound(m_byCID.begin(), m_byCID.end(), search); - return it != m_byCID.end() && !(search < *it) ? (*it).m_ptr : 0; -} - - -void CCryFactoryRegistryImpl::IterateFactories(const CryInterfaceID& iid, ICryFactory** pFactories, size_t& numFactories) const -{ - AUTO_READLOCK(m_guard); - - typedef std::pair SearchResult; - SearchResult res = std::equal_range(m_byIID.begin(), m_byIID.end(), FactoryByIID(iid, 0), LessPredFactoryByIIDOnly()); - - const size_t numFactoriesFound = std::distance(res.first, res.second); - if (pFactories) - { - numFactories = min(numFactories, numFactoriesFound); - FactoriesByIIDConstIt it = res.first; - for (size_t i = 0; i < numFactories; ++i, ++it) - { - pFactories[i] = (*it).m_ptr; - } - } - else - { - numFactories = numFactoriesFound; - } -} - - -void CCryFactoryRegistryImpl::RegisterCallback(ICryFactoryRegistryCallback* pCallback) -{ - if (!pCallback) - { - return; - } - - { - AUTO_MODIFYLOCK(m_guard); - - Callbacks::iterator it = std::lower_bound(m_callbacks.begin(), m_callbacks.end(), pCallback); - if (it == m_callbacks.end() || pCallback < *it) - { - m_callbacks.insert(it, pCallback); - } - else - { - assert(0 && "CCryFactoryRegistryImpl::RegisterCallback() -- pCallback already registered!"); - } - } - { - AUTO_READLOCK(m_guard); - - typedef std::pair SearchResult; - SearchResult res = std::equal_range(m_byIID.begin(), m_byIID.end(), FactoryByIID(cryiidof(), 0), LessPredFactoryByIIDOnly()); - - for (; res.first != res.second; ++res.first) - { - pCallback->OnNotifyFactoryRegistered((*res.first).m_ptr); - } - } -} - - -void CCryFactoryRegistryImpl::UnregisterCallback(ICryFactoryRegistryCallback* pCallback) -{ - if (!pCallback) - { - return; - } - - AUTO_MODIFYLOCK(m_guard); - - Callbacks::iterator it = std::lower_bound(m_callbacks.begin(), m_callbacks.end(), pCallback); - if (it != m_callbacks.end() && !(pCallback < *it)) - { - m_callbacks.erase(it); - } -} - - -bool CCryFactoryRegistryImpl::GetInsertionPos(ICryFactory* pFactory, FactoriesByCNameIt& itPosForCName, FactoriesByCIDIt& itPosForCID) -{ - assert(pFactory); - - struct FatalError - { - static void Report(ICryFactory* pKnownFactory, ICryFactory* pNewFactory) - { - char err[1024]; - sprintf_s(err, sizeof(err), "Conflicting factories...\n" - "Factory (0x%p): ClassID = %s, ClassName = \"%s\"\n" - "Factory (0x%p): ClassID = %s, ClassName = \"%s\"", - pKnownFactory, pKnownFactory ? CryGUIDHelper::Print(pKnownFactory->GetClassID()).c_str() : "$unknown$", pKnownFactory ? pKnownFactory->GetName() : "$unknown$", - pNewFactory, pNewFactory ? CryGUIDHelper::Print(pNewFactory->GetClassID()).c_str() : "$unknown$", pNewFactory ? pNewFactory->GetName() : "$unknown$"); - -#if AZ_LEGACY_CRYSYSTEM_TRAIT_FACTORY_REGISTRY_USE_PRINTF_FOR_FATAL - printf("\n!!! Fatal error !!!\n"); - printf(err); - printf("\n"); -#elif defined(WIN32) || defined(WIN64) - OutputDebugStringA("\n!!! Fatal error !!!\n"); - OutputDebugStringA(err); - OutputDebugStringA("\n"); - MessageBoxA(0, err, "!!! Fatal error !!!", MB_OK | MB_ICONERROR); -#endif - - assert(0); - exit(0); - } - }; - - FactoryByCName searchByCName(pFactory); - FactoriesByCNameIt itForCName = std::lower_bound(m_byCName.begin(), m_byCName.end(), searchByCName); - if (itForCName != m_byCName.end()) - { - // If the addresses match, then this factory is already registered. It's not really worth error-ing about, - // as double registration will not cause any harm. - if (itForCName->m_ptr == pFactory) - { - return false; - } - - if (!(searchByCName < *itForCName)) - { - FatalError::Report((*itForCName).m_ptr, pFactory); - } - } - - FactoryByCID searchByCID(pFactory); - FactoriesByCIDIt itForCID = std::lower_bound(m_byCID.begin(), m_byCID.end(), searchByCID); - if (itForCID != m_byCID.end() && !(searchByCID < *itForCID)) - { - FatalError::Report((*itForCID).m_ptr, pFactory); - } - - itPosForCName = itForCName; - itPosForCID = itForCID; - - return true; -} - - -void CCryFactoryRegistryImpl::RegisterFactories(const SRegFactoryNode* pFactories) -{ - size_t numFactoriesToAdd = 0; - size_t numInterfacesSupported = 0; - { - const SRegFactoryNode* p = pFactories; - while (p) - { - ICryFactory* pFactory = p->m_pFactory; - assert(pFactory); - if (pFactory) - { - const CryInterfaceID* pIIDs = 0; - size_t numIIDs = 0; - pFactory->ClassSupports(pIIDs, numIIDs); - - numInterfacesSupported += numIIDs; - ++numFactoriesToAdd; - } - - p = p->m_pNext; - } - } - - { - AUTO_MODIFYLOCK(m_guard); - - m_byCName.reserve(m_byCName.size() + numFactoriesToAdd); - m_byCID.reserve(m_byCID.size() + numFactoriesToAdd); - m_byIID.reserve(m_byIID.size() + numInterfacesSupported); - - size_t numFactoriesAdded = 0; - const SRegFactoryNode* p = pFactories; - while (p) - { - ICryFactory* pFactory = p->m_pFactory; - if (pFactory) - { - FactoriesByCNameIt itPosForCName; - FactoriesByCIDIt itPosForCID; - if (GetInsertionPos(pFactory, itPosForCName, itPosForCID)) - { - m_byCName.insert(itPosForCName, FactoryByCName(pFactory)); - m_byCID.insert(itPosForCID, FactoryByCID(pFactory)); - - const CryInterfaceID* pIIDs = 0; - size_t numIIDs = 0; - pFactory->ClassSupports(pIIDs, numIIDs); - - for (size_t i = 0; i < numIIDs; ++i) - { - const FactoryByIID newFactory(pIIDs[i], pFactory); - m_byIID.push_back(newFactory); - } - - for (size_t i = 0, s = m_callbacks.size(); i < s; ++i) - { - m_callbacks[i]->OnNotifyFactoryRegistered(pFactory); - } - - ++numFactoriesAdded; - } - } - - p = p->m_pNext; - } - - if (numFactoriesAdded) - { - std::sort(m_byIID.begin(), m_byIID.end()); - } - } -} - - -void CCryFactoryRegistryImpl::UnregisterFactories(const SRegFactoryNode* pFactories) -{ - AUTO_MODIFYLOCK(m_guard); - - const SRegFactoryNode* p = pFactories; - while (p) - { - ICryFactory* pFactory = p->m_pFactory; - UnregisterFactoryInternal(pFactory); - p = p->m_pNext; - } -} - - -void CCryFactoryRegistryImpl::UnregisterFactory(ICryFactory* const pFactory) -{ - AUTO_MODIFYLOCK(m_guard); - - UnregisterFactoryInternal(pFactory); -} - - -void CCryFactoryRegistryImpl::UnregisterFactoryInternal(ICryFactory* const pFactory) -{ - if (pFactory) - { - FactoryByCName searchByCName(pFactory); - FactoriesByCNameIt itForCName = std::lower_bound(m_byCName.begin(), m_byCName.end(), searchByCName); - if (itForCName != m_byCName.end() && !(searchByCName < *itForCName)) - { - assert((*itForCName).m_ptr == pFactory); - if ((*itForCName).m_ptr == pFactory) - { - m_byCName.erase(itForCName); - } - } - - FactoryByCID searchByCID(pFactory); - FactoriesByCIDIt itForCID = std::lower_bound(m_byCID.begin(), m_byCID.end(), searchByCID); - if (itForCID != m_byCID.end() && !(searchByCID < *itForCID)) - { - assert((*itForCID).m_ptr == pFactory); - if ((*itForCID).m_ptr == pFactory) - { - m_byCID.erase(itForCID); - } - } - - const CryInterfaceID* pIIDs = 0; - size_t numIIDs = 0; - pFactory->ClassSupports(pIIDs, numIIDs); - - for (size_t i = 0; i < numIIDs; ++i) - { - FactoryByIID searchByIID(pIIDs[i], pFactory); - FactoriesByIIDIt itForIID = std::lower_bound(m_byIID.begin(), m_byIID.end(), searchByIID); - if (itForIID != m_byIID.end() && !(searchByIID < *itForIID)) - { - m_byIID.erase(itForIID); - } - } - - for (size_t i = 0, s = m_callbacks.size(); i < s; ++i) - { - m_callbacks[i]->OnNotifyFactoryUnregistered(pFactory); - } - } -} - -ICryFactoryRegistry* CSystem::GetCryFactoryRegistry() const -{ - return &CCryFactoryRegistryImpl::Access(); -} diff --git a/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.h b/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.h deleted file mode 100644 index a75ddf782f..0000000000 --- a/Code/CryEngine/CrySystem/ExtensionSystem/CryFactoryRegistryImpl.h +++ /dev/null @@ -1,128 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_CRYFACTORYREGISTRYIMPL_H -#define CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_CRYFACTORYREGISTRYIMPL_H -#pragma once - - - -#include -#include - -#include - - -class CCryFactoryRegistryImpl - : public ICryFactoryRegistryImpl -{ -public: - virtual ICryFactory* GetFactory(const char* cname) const; - virtual ICryFactory* GetFactory(const CryClassID& cid) const; - virtual void IterateFactories(const CryInterfaceID& iid, ICryFactory** pFactories, size_t& numFactories) const; - - virtual void RegisterCallback(ICryFactoryRegistryCallback* pCallback); - virtual void UnregisterCallback(ICryFactoryRegistryCallback* pCallback); - - virtual void RegisterFactories(const SRegFactoryNode* pFactories); - virtual void UnregisterFactories(const SRegFactoryNode* pFactories); - - virtual void UnregisterFactory(ICryFactory* const pFactory); - -public: - static CCryFactoryRegistryImpl& Access(); - CCryFactoryRegistryImpl(); - ~CCryFactoryRegistryImpl(); - -private: - struct FactoryByCName - { - const char* m_cname; - ICryFactory* m_ptr; - - FactoryByCName(const char* cname) - : m_cname(cname) - , m_ptr(0) {assert(m_cname); } - FactoryByCName(ICryFactory* ptr) - : m_cname(ptr ? ptr->GetName() : 0) - , m_ptr(ptr) {assert(m_cname && m_ptr); } - bool operator <(const FactoryByCName& rhs) const {return strcmp(m_cname, rhs.m_cname) < 0; } - }; - typedef std::vector FactoriesByCName; - typedef FactoriesByCName::iterator FactoriesByCNameIt; - typedef FactoriesByCName::const_iterator FactoriesByCNameConstIt; - - struct FactoryByCID - { - CryClassID m_cid; - ICryFactory* m_ptr; - - FactoryByCID(const CryClassID& cid) - : m_cid(cid) - , m_ptr(0) {} - FactoryByCID(ICryFactory* ptr) - : m_cid(ptr ? ptr->GetClassID() : MAKE_CRYGUID(0, 0)) - , m_ptr(ptr) {assert(m_ptr); } - bool operator <(const FactoryByCID& rhs) const {return m_cid < rhs.m_cid; } - }; - typedef std::vector FactoriesByCID; - typedef FactoriesByCID::iterator FactoriesByCIDIt; - typedef FactoriesByCID::const_iterator FactoriesByCIDConstIt; - - struct FactoryByIID - { - CryInterfaceID m_iid; - ICryFactory* m_ptr; - - FactoryByIID(CryInterfaceID iid, ICryFactory* pFactory) - : m_iid(iid) - , m_ptr(pFactory) {} - bool operator <(const FactoryByIID& rhs) const - { - if (m_iid != rhs.m_iid) - { - return m_iid < rhs.m_iid; - } - return m_ptr < rhs.m_ptr; - } - }; - typedef std::vector FactoriesByIID; - typedef FactoriesByIID::iterator FactoriesByIIDIt; - typedef FactoriesByIID::const_iterator FactoriesByIIDConstIt; - struct LessPredFactoryByIIDOnly - { - bool operator ()(const FactoryByIID& lhs, const FactoryByIID& rhs) const {return lhs.m_iid < rhs.m_iid; } - }; - - typedef std::vector Callbacks; - typedef Callbacks::iterator CallbacksIt; - typedef Callbacks::const_iterator CallbacksConstIt; - -private: - bool GetInsertionPos(ICryFactory* pFactory, FactoriesByCNameIt& itPosForCName, FactoriesByCIDIt& itPosForCID); - void UnregisterFactoryInternal(ICryFactory* const pFactory); - -private: - mutable CryReadModifyLock m_guard; - - FactoriesByCName m_byCName; - FactoriesByCID m_byCID; - FactoriesByIID m_byIID; - - Callbacks m_callbacks; -}; - -#endif // CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_CRYFACTORYREGISTRYIMPL_H diff --git a/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.cpp b/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.cpp deleted file mode 100644 index f87643d4f0..0000000000 --- a/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.cpp +++ /dev/null @@ -1,955 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#include "CrySystem_precompiled.h" -#include "TestExtensions.h" - -#ifdef EXTENSION_SYSTEM_INCLUDE_TESTCASES - -#include -#include -#include - - -////////////////////////////////////////////////////////////////////////// - - -namespace TestComposition -{ - struct ITestExt1 - : public ICryUnknown - { - CRYINTERFACE_DECLARE(ITestExt1, 0x9d9e0dcfa5764cb0, 0xa73701595f75bd32) - - virtual void Call1() const = 0; - }; - - DECLARE_SMART_POINTERS(ITestExt1); - - - class CTestExt1 - : public ITestExt1 - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(ITestExt1) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CTestExt1, "TestExt1", 0x43b04e7cc1be45ca, 0x9df6ccb1c0dc1ad8) - - public: - virtual void Call1() const; - - private: - int i; - }; - - CRYREGISTER_CLASS(CTestExt1) - - CTestExt1::CTestExt1() - { - i = 1; - } - - CTestExt1::~CTestExt1() - { - printf("Inside CTestExt1 dtor\n"); - } - - void CTestExt1::Call1() const - { - printf("Inside CTestExt1::Call1()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - struct ITestExt2 - : public ICryUnknown - { - CRYINTERFACE_DECLARE(ITestExt2, 0x8eb7a4b399874b9c, 0xb96bd6da7a8c72f9) - - virtual void Call2() = 0; - }; - - DECLARE_SMART_POINTERS(ITestExt2); - - - class CTestExt2 - : public ITestExt2 - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(ITestExt2) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CTestExt2, "TestExt2", 0x25b3ebf8f1754b9a, 0xb5494e3da7cdd80f) - - public: - virtual void Call2(); - - private: - int i; - }; - - CRYREGISTER_CLASS(CTestExt2) - - CTestExt2::CTestExt2() - { - i = 2; - } - - CTestExt2::~CTestExt2() - { - printf("Inside CTestExt2 dtor\n"); - } - - void CTestExt2::Call2() - { - printf("Inside CTestExt2::Call2()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CComposed - : public ICryUnknown - { - CRYGENERATE_CLASS(CComposed, "Composed", 0x0439d74b8dcd4b7f, 0x9287dcdf7e26a3a5) - - CRYCOMPOSITE_BEGIN() - CRYCOMPOSITE_ADD(m_pTestExt1, "Ext1") - CRYCOMPOSITE_ADD(m_pTestExt2, "Ext2") - CRYCOMPOSITE_END(CComposed) - - CRYINTERFACE_BEGIN() - CRYINTERFACE_END() - - private: - ITestExt1Ptr m_pTestExt1; - ITestExt2Ptr m_pTestExt2; - }; - - CRYREGISTER_CLASS(CComposed) - - CComposed::CComposed() - : m_pTestExt1() - , m_pTestExt2() - { - CryCreateClassInstance("TestExt1", m_pTestExt1); - CryCreateClassInstance("TestExt2", m_pTestExt2); - } - - CComposed::~CComposed() - { - } - - ////////////////////////////////////////////////////////////////////////// - - struct ITestExt3 - : public ICryUnknown - { - CRYINTERFACE_DECLARE(ITestExt3, 0xdd017935a2134898, 0xbd2fffa145551876) - - virtual void Call3() = 0; - }; - - DECLARE_SMART_POINTERS(ITestExt3); - - class CTestExt3 - : public ITestExt3 - { - CRYGENERATE_CLASS(CTestExt3, "TestExt3", 0xeceab40bc4bb4988, 0xa9f63c1db85a69b1) - - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(ITestExt3) - CRYINTERFACE_END() - - public: - virtual void Call3(); - - private: - int i; - }; - - CRYREGISTER_CLASS(CTestExt3) - - CTestExt3::CTestExt3() - { - i = 3; - } - - CTestExt3::~CTestExt3() - { - printf("Inside CTestExt3 dtor\n"); - } - - void CTestExt3::Call3() - { - printf("Inside CTestExt3::Call3()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CComposed2 - : public ICryUnknown - { - CRYGENERATE_CLASS(CComposed2, "Composed2", 0x0439d74b8dcd4b7e, 0x9287dcdf7e26a3a6) - - CRYCOMPOSITE_BEGIN() - CRYCOMPOSITE_ADD(m_pTestExt3, "Ext3") - CRYCOMPOSITE_END(CComposed2) - - CRYINTERFACE_BEGIN() - CRYINTERFACE_END() - - private: - ITestExt3Ptr m_pTestExt3; - }; - - CRYREGISTER_CLASS(CComposed2) - - CComposed2::CComposed2() - : m_pTestExt3() - { - CryCreateClassInstance("TestExt3", m_pTestExt3); - } - - CComposed2::~CComposed2() - { - } - - ////////////////////////////////////////////////////////////////////////// - - class CTestExt4 - : public ITestExt1 - , public ITestExt2 - , public ITestExt3 - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(ITestExt1) - CRYINTERFACE_ADD(ITestExt2) - CRYINTERFACE_ADD(ITestExt3) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CTestExt4, "TestExt4", 0x43204e7cc1be45ca, 0x9df4ccb1c0dc1ad8) - - public: - virtual void Call1() const; - virtual void Call2(); - virtual void Call3(); - - private: - int i; - }; - - CRYREGISTER_CLASS(CTestExt4) - - CTestExt4::CTestExt4() - { - i = 4; - } - - CTestExt4::~CTestExt4() - { - printf("Inside CTestExt4 dtor\n"); - } - - void CTestExt4::Call1() const - { - printf("Inside CTestExt4::Call1()\n"); - } - - void CTestExt4::Call2() - { - printf("Inside CTestExt4::Call2()\n"); - } - - void CTestExt4::Call3() - { - printf("Inside CTestExt4::Call3()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CMegaComposed - : public CComposed - , public CComposed2 - { - CRYGENERATE_CLASS(CMegaComposed, "MegaComposed", 0x512787559f84503, 0x421ac1af66f2fb6f) - - CRYCOMPOSITE_BEGIN() - CRYCOMPOSITE_ADD(m_pTestExt4, "Ext4") - CRYCOMPOSITE_ENDWITHBASE2(CMegaComposed, CComposed, CComposed2) - - CRYINTERFACE_BEGIN() - CRYINTERFACE_END() - - private: - AZStd::shared_ptr m_pTestExt4; - }; - - CRYREGISTER_CLASS(CMegaComposed) - - CMegaComposed::CMegaComposed() - : m_pTestExt4() - { - printf("Inside CMegaComposed ctor\n"); - m_pTestExt4 = CTestExt4::CreateClassInstance(); - } - - CMegaComposed::~CMegaComposed() - { - printf("Inside CMegaComposed dtor\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - static void TestComposition() - { - printf("\nTest composition:\n"); - - ICryUnknownPtr p; - if (CryCreateClassInstance("MegaComposed", p)) - { - ITestExt1Ptr p1 = cryinterface_cast(crycomposite_query(p, "Ext1")); - if (p1) - { - p1->Call1(); // calls CTestExt1::Call1() - } - ITestExt2Ptr p2 = cryinterface_cast(crycomposite_query(p, "Ext2")); - if (p2) - { - p2->Call2(); // calls CTestExt2::Call2() - } - ITestExt3Ptr p3 = cryinterface_cast(crycomposite_query(p, "Ext3")); - if (p3) - { - p3->Call3(); // calls CTestExt3::Call3() - } - p3 = cryinterface_cast(crycomposite_query(p, "Ext4")); - if (p3) - { - p3->Call3(); // calls CTestExt4::Call3() - } - p1 = cryinterface_cast(crycomposite_query(p.get(), "Ext4")); - p2 = cryinterface_cast(crycomposite_query(p.get(), "Ext4")); - - bool b = CryIsSameClassInstance(p1, p2); // true - } - - { - ICryUnknownConstPtr pCUnk = p; - ICryUnknownConstPtr pComp1 = crycomposite_query(pCUnk.get(), "Ext1"); - //ICryUnknownPtr pComp1 = crycomposite_query(pCUnk, "Ext1"); // must fail to compile due to const rules - - ITestExt1ConstPtr p1 = cryinterface_cast(pComp1); - if (p1) - { - p1->Call1(); - } - } - } -} // namespace TestComposition - - -////////////////////////////////////////////////////////////////////////// - - -namespace TestExtension -{ - class CFoobar - : public IFoobar - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IFoobar) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CFoobar, "Foobar", 0x76c8dd6d16634531, 0x95d3b1cfabcf7ef4) - - public: - virtual void Foo(); - }; - - CRYREGISTER_CLASS(CFoobar) - - CFoobar::CFoobar() - { - } - - CFoobar::~CFoobar() - { - } - - void CFoobar::Foo() - { - printf("Inside CFoobar::Foo()\n"); - } - - static void TestFoobar() - { - AZStd::shared_ptr p = CFoobar::CreateClassInstance(); - { - CryInterfaceID iid = cryiidof(); - CryClassID clsid = p->GetFactory()->GetClassID(); - int t = 0; - } - - { - IAPtr sp_ = cryinterface_cast(p); // sp_ == NULL - - ICryUnknownPtr sp1 = cryinterface_cast(p); - IFoobarPtr sp = cryinterface_cast(sp1); - sp->Foo(); - } - - { - CFoobar* pF = p.get(); - pF->Foo(); - ICryUnknown* p1 = cryinterface_cast(pF); - } - - IFoobar* pFoo = cryinterface_cast(p.get()); - ICryFactory* pF1 = pFoo->GetFactory(); - pFoo->Foo(); - - int t = 0; - } - - ////////////////////////////////////////////////////////////////////////// - - class CRaboof - : public IRaboof - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IRaboof) - CRYINTERFACE_END() - - CRYGENERATE_SINGLETONCLASS(CRaboof, "Raabof", 0xba482ce12b2e4309, 0x8238ed8b52cb1f1e) - - public: - virtual void Rab(); - }; - - CRYREGISTER_SINGLETON_CLASS(CRaboof) - - CRaboof::CRaboof() - { - } - - CRaboof::~CRaboof() - { - } - - void CRaboof::Rab() - { - printf("Inside CRaboof::Rab()\n"); - } - - static void TestRaboof() - { - AZStd::shared_ptr pFoo0_ = CRaboof::CreateClassInstance(); - IRaboofPtr pFoo0 = cryinterface_cast(pFoo0_); - ICryUnknownPtr p0 = cryinterface_cast(pFoo0); - - CryInterfaceID iid = cryiidof(); - CryClassID clsid = p0->GetFactory()->GetClassID(); - - AZStd::shared_ptr pFoo1 = CRaboof::CreateClassInstance(); - - pFoo0->Rab(); - pFoo1->Rab(); - } - - ////////////////////////////////////////////////////////////////////////// - - class CAB - : public IA - , public IB - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IA) - CRYINTERFACE_ADD(IB) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CAB, "AB", 0xb9e54711a64448c0, 0xa4819b4ed3024d04) - - public: - virtual void A(); - virtual void B(); - - private: - int i; - }; - - CRYREGISTER_CLASS(CAB) - - CAB::CAB() - { - i = 0x12345678; - } - - CAB::~CAB() - { - } - - void CAB::A() - { - printf("Inside CAB::A()\n"); - } - - void CAB::B() - { - printf("Inside CAB::B()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CABC - : public CAB - , public IC - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IC) - CRYINTERFACE_ENDWITHBASE(CAB) - - CRYGENERATE_CLASS(CABC, "ABC", 0x4e61feae11854be7, 0xa16157c5f8baadd9) - - public: - virtual void C(); - - private: - int a; - }; - - CRYREGISTER_CLASS(CABC) - - CABC::CABC() - //: CAB() - { - a = 0x87654321; - } - - CABC::~CABC() - { - } - - void CABC::C() - { - printf("Inside CABC::C()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CCustomC - : public ICustomC - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ADD(IC) - CRYINTERFACE_ADD(ICustomC) - CRYINTERFACE_END() - - CRYGENERATE_CLASS(CCustomC, "CustomC", 0xee61760b98a44b71, 0xa05e7372b44bd0fd) - - public: - virtual void C(); - virtual void C1(); - - private: - int a; - }; - - CRYREGISTER_CLASS(CCustomC) - - CCustomC::CCustomC() - { - a = 0x87654321; - } - - CCustomC::~CCustomC() - { - } - - void CCustomC::C() - { - printf("Inside CCustomC::C()\n"); - } - - void CCustomC::C1() - { - printf("Inside CCustomC::C1()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - class CMultiBase - : public CAB - , public CCustomC - { - CRYINTERFACE_BEGIN() - CRYINTERFACE_ENDWITHBASE2(CAB, CCustomC) - - CRYGENERATE_CLASS(CMultiBase, "MultiBase", 0x75966b8f98644d42, 0x8fbdd489e94cc29e) - - public: - virtual void A(); - virtual void C1(); - - int i; - }; - - CRYREGISTER_CLASS(CMultiBase) - - CMultiBase::CMultiBase() - { - i = 0x87654321; - } - - CMultiBase::~CMultiBase() - { - } - - void CMultiBase::C1() - { - printf("Inside CMultiBase::C1()\n"); - } - - void CMultiBase::A() - { - printf("Inside CMultiBase::A()\n"); - } - - ////////////////////////////////////////////////////////////////////////// - - static void TestComplex() - { - { - ICPtr p; - if (CryCreateClassInstance(MAKE_CRYGUID(0x75966b8f98644d42, 0x8fbdd489e94cc29e), p)) - { - p->C(); - } - } - - { - ICustomCPtr p; - if (CryCreateClassInstance("MultiBase", p)) - { - p->C(); - } - } - - { - IFoobarPtr p; - if (CryCreateClassInstance(MAKE_CRYGUID(0x75966b8f98644d42, 0x8fbdd489e94cc29e), p)) - { - p->Foo(); - } - } - - { - AZStd::shared_ptr p = CMultiBase::CreateClassInstance(); - AZStd::shared_ptr pc = p; - - { - ICryUnknownPtr pUnk = cryinterface_cast(p); - ICryUnknownConstPtr pCUnk0 = cryinterface_cast(p); - ICryUnknownConstPtr pCUnk1 = cryinterface_cast(pc); - //ICryUnknownPtr pUnkF = cryinterface_cast(pc); // must fail to compile due to const rules - - ICryFactory* pF = pUnk->GetFactory(); - - int t = 0; - } - - ICPtr pC = cryinterface_cast(p); - ICustomCPtr pCC = cryinterface_cast(pC); - - p->C(); - p->C1(); - - pC->C(); - pCC->C1(); - - IAPtr pA = cryinterface_cast(p); - pA->A(); - p->A(); - } - - { - AZStd::shared_ptr p = CCustomC::CreateClassInstance(); - - ICPtr pC = cryinterface_cast(p); - ICustomCPtr pCC = cryinterface_cast(pC); - - p->C(); - p->C1(); - - pC->C(); - pCC->C1(); - } - { - CryInterfaceID ia = cryiidof(); - CryInterfaceID ib = cryiidof(); - CryInterfaceID ic = cryiidof(); - CryInterfaceID ico = cryiidof(); - } - - { - AZStd::shared_ptr p = CAB::CreateClassInstance(); - CryClassID clsid = p->GetFactory()->GetClassID(); - - IAPtr pA = cryinterface_cast(p); - IBPtr pB = cryinterface_cast(p); - - IBPtr pB1 = cryinterface_cast(pA); - IAPtr pA1 = cryinterface_cast(pB); - - pA->A(); - pB->B(); - - ICryUnknownPtr p1 = cryinterface_cast(pA); - ICryUnknownPtr p2 = cryinterface_cast(pB); - const ICryUnknown* p3 = cryinterface_cast(pB.get()); - - int t = 0; - } - - { - AZStd::shared_ptr pABC = CABC::CreateClassInstance(); - CryClassID clsid = pABC->GetFactory()->GetClassID(); - - ICryFactory* pFac = pABC->GetFactory(); - pFac->ClassSupports(cryiidof()); - pFac->ClassSupports(cryiidof()); - - IAPtr pABC0 = cryinterface_cast(pABC); - IBPtr pABC1 = cryinterface_cast(pABC0); - ICPtr pABC2 = cryinterface_cast(pABC1); - - pABC2->C(); - pABC1->B(); - - pABC2->GetFactory(); - - const IC* pCconst = pABC2.get(); - const ICryUnknown* pOconst = cryinterface_cast(pCconst); - const IA* pAconst = cryinterface_cast(pOconst); - const IB* pBconst = cryinterface_cast(pAconst); - - //const IA* pA11 = cryinterface_cast(pOconst); - - pCconst = cryinterface_cast(pBconst); - - IC* pC = static_cast(static_cast(pABC1.get())); - pC->C(); // calls IB::B() - - int t = 0; - } - } - - ////////////////////////////////////////////////////////////////////////// - // use of extension system without any of the helper macros/templates - - class CDontLikeMacrosFactory - : public ICryFactory - { - // ICryFactory - public: - virtual const char* GetClassName() const - { - return "DontLikeMacros"; - } - virtual const CryClassID& GetClassID() const - { - static const CryClassID cid = {0x73c3ab0042e6488aull, 0x89ca1a3763365565ull}; - return cid; - } - virtual bool ClassSupports(const CryInterfaceID& iid) const - { - return iid == cryiidof() || iid == cryiidof(); - } - virtual void ClassSupports(const CryInterfaceID*& pIIDs, size_t& numIIDs) const - { - static const CryInterfaceID iids[2] = {cryiidof(), cryiidof()}; - pIIDs = iids; - numIIDs = 2; - } - virtual ICryUnknownPtr CreateClassInstance() const; - - public: - static CDontLikeMacrosFactory& Access() - { - return s_factory; - } - - private: - CDontLikeMacrosFactory() {} - ~CDontLikeMacrosFactory() {} - - private: - static CDontLikeMacrosFactory s_factory; - }; - - CDontLikeMacrosFactory CDontLikeMacrosFactory::s_factory; - - class CDontLikeMacros - : public IDontLikeMacros - { - // ICryUnknown - public: - virtual ICryFactory* GetFactory() const - { - return &CDontLikeMacrosFactory::Access(); - }; - - // only needed to be able to create initial shared_ptr so we don't lose type info for debugging (i.e. inspecting shared_ptr<>) - template - friend void AZStd::Internal::sp_ms_deleter::destroy(); - template - friend AZStd::shared_ptr AZStd::make_shared(); - - protected: - virtual void* QueryInterface(const CryInterfaceID& iid) const - { - if (iid == cryiidof()) - { - return (void*) (ICryUnknown*) this; - } - else if (iid == cryiidof()) - { - return (void*) (IDontLikeMacros*) this; - } - else - { - return 0; - } - } - - virtual void* QueryComposite(const char*) const - { - return 0; - } - - // IDontLikeMacros - public: - virtual void CallMe() - { - printf("Yey, no macros...\n"); - } - - CDontLikeMacros() {} - - protected: - virtual ~CDontLikeMacros() {} - }; - - ICryUnknownPtr CDontLikeMacrosFactory::CreateClassInstance() const - { - AZStd::shared_ptr p = AZStd::make_shared(); - return ICryUnknownPtr(*static_cast*>(static_cast(&p))); - } - - static SRegFactoryNode g_dontLikeMacrosFactory(&CDontLikeMacrosFactory::Access()); - - ////////////////////////////////////////////////////////////////////////// - - static void TestDontLikeMacros() - { - ICryFactory* f = &CDontLikeMacrosFactory::Access(); - - f->ClassSupports(cryiidof()); - f->ClassSupports(cryiidof()); - - const CryInterfaceID* pIIDs = 0; - size_t numIIDs = 0; - f->ClassSupports(pIIDs, numIIDs); - - ICryUnknownPtr p = f->CreateClassInstance(); - IDontLikeMacrosPtr pp = cryinterface_cast(p); - - ICryUnknownPtr pq = crycomposite_query(p, "blah"); - - pp->CallMe(); - } -} // namespace TestExtension - - -////////////////////////////////////////////////////////////////////////// - - -void TestExtensions(ICryFactoryRegistryImpl* pReg) -{ - printf("Test extensions:\n"); - - struct MyCallback - : public ICryFactoryRegistryCallback - { - virtual void OnNotifyFactoryRegistered(ICryFactory* pFactory) - { - int test = 0; - } - virtual void OnNotifyFactoryUnregistered(ICryFactory* pFactory) - { - int test = 0; - } - }; - - //pReg->RegisterCallback((ICryFactoryRegistryCallback*) 0x4); - //pReg->RegisterCallback((ICryFactoryRegistryCallback*) 0x1); - //pReg->RegisterCallback((ICryFactoryRegistryCallback*) 0x3); - //pReg->RegisterCallback((ICryFactoryRegistryCallback*) 0x3); - //pReg->RegisterCallback((ICryFactoryRegistryCallback*) 0x2); - - //pReg->UnregisterCallback((ICryFactoryRegistryCallback*) 0x2); - //pReg->UnregisterCallback((ICryFactoryRegistryCallback*) 0x2); - //pReg->UnregisterCallback((ICryFactoryRegistryCallback*) 0x4); - //pReg->UnregisterCallback((ICryFactoryRegistryCallback*) 0x3); - //pReg->UnregisterCallback((ICryFactoryRegistryCallback*) 0x1); - - //MyCallback callback0; - //pReg->RegisterCallback(&callback0); - //pReg->RegisterFactories(g_pHeadToRegFactories); - - //pReg->RegisterFactories(g_pHeadToRegFactories); - //pReg->UnregisterFactories(g_pHeadToRegFactories); - - ICryFactory* pF[4]; - size_t numFactories = 4; - pReg->IterateFactories(cryiidof(), pF, numFactories); - pReg->IterateFactories(MAKE_CRYGUID(-1, -1), pF, numFactories); - - numFactories = (size_t) -1; - pReg->IterateFactories(cryiidof(), 0, numFactories); - - MyCallback callback1; - pReg->RegisterCallback(&callback1); - pReg->UnregisterCallback(&callback1); - - ICryFactory* p; - p = pReg->GetFactory(MAKE_CRYGUID(0xee61760b98a44b71, 0xa05e7372b44bd0fd)); - p = pReg->GetFactory("CustomC"); - p = pReg->GetFactory("ABC"); - p = pReg->GetFactory((const char*)0); - - p = pReg->GetFactory("DontLikeMacros"); - p = pReg->GetFactory(MAKE_CRYGUID(0x73c3ab0042e6488a, 0x89ca1a3763365565)); - - TestExtension::TestFoobar(); - TestExtension::TestRaboof(); - TestExtension::TestComplex(); - TestExtension::TestDontLikeMacros(); - - TestComposition::TestComposition(); -} - -#endif // #ifdef EXTENSION_SYSTEM_INCLUDE_TESTCASES diff --git a/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.h b/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.h deleted file mode 100644 index ac9ad04dc7..0000000000 --- a/Code/CryEngine/CrySystem/ExtensionSystem/TestCases/TestExtensions.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Part of CryEngine's extension framework. - - -#ifndef CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_TESTCASES_TESTEXTENSIONS_H -#define CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_TESTCASES_TESTEXTENSIONS_H -#pragma once - - -//#define EXTENSION_SYSTEM_INCLUDE_TESTCASES - -#ifdef EXTENSION_SYSTEM_INCLUDE_TESTCASES - -#include - -struct ICryFactoryRegistryImpl; - -void TestExtensions(ICryFactoryRegistryImpl* pReg); - -struct IFoobar - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IFoobar, 0x539e9c672cad4a03, 0x9ecd8069c99a846b) - - virtual void Foo() = 0; -}; - -DECLARE_SMART_POINTERS(IFoobar); - -struct IRaboof - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IRaboof, 0x135ca25e634b4d13, 0x9e4467968a708822) - - virtual void Rab() = 0; -}; - -DECLARE_SMART_POINTERS(IRaboof); - -struct IA - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IA, 0xd93aaceb35ec427e, 0xb64bf8dec4997e67) - - virtual void A() = 0; -}; - -DECLARE_SMART_POINTERS(IA); - -struct IB - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IB, 0xe0d830c826424e11, 0x9eacfa19eaf31ffb) - - virtual void B() = 0; -}; - -DECLARE_SMART_POINTERS(IB); - -struct IC - : public ICryUnknown -{ - CRYINTERFACE_DECLARE(IC, 0x577509a20fc5477c, 0x893757c9ca88b27b) - - virtual void C() = 0; -}; - -DECLARE_SMART_POINTERS(IC); - -struct ICustomC - : public IC -{ - CRYINTERFACE_DECLARE(ICustomC, 0x2ac769da4c7443bf, 0x80911033e21dfbcf) - - virtual void C1() = 0; -}; - -DECLARE_SMART_POINTERS(ICustomC); - -////////////////////////////////////////////////////////////////////////// -// use of extension system without any of the helper macros/templates - -struct IDontLikeMacros - : public ICryUnknown -{ - template - friend const CryInterfaceID& InterfaceCastSemantics::cryiidof(); - template - friend void AZStd::Internal::sp_ms_deleter::destroy(); - template - friend AZStd::shared_ptr AZStd::make_shared(); -protected: - virtual ~IDontLikeMacros() {} - -private: - // It's very important that this static function is implemented for each interface! - // Otherwise the consistency of cryinterface_cast() is compromised because - // cryiidof() = cryiidof>() {baseof = ICryUnknown in most cases} - static const CryInterfaceID& IID() - { - static const CryInterfaceID iid = {0x0f43b7e3f1364af0ull, 0xb4a16a975bea3ec4ull}; - return iid; - } - -public: - virtual void CallMe() = 0; -}; - -DECLARE_SMART_POINTERS(IDontLikeMacros); - - -#endif // #ifdef EXTENSION_SYSTEM_INCLUDE_TESTCASES - -#endif // CRYINCLUDE_CRYSYSTEM_EXTENSIONSYSTEM_TESTCASES_TESTEXTENSIONS_H diff --git a/Code/CryEngine/CrySystem/RemoteCommand.cpp b/Code/CryEngine/CrySystem/RemoteCommand.cpp deleted file mode 100644 index 5f1129be22..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommand.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Remote command system implementation - -#include "CrySystem_precompiled.h" -#include "IServiceNetwork.h" -#include "RemoteCommand.h" -#include "RemoteCommandHelpers.h" - -//----------------------------------------------------------------------------- - -// remote system internal logging -#ifdef RELEASE - #define LOG_VERBOSE(level, txt, ...) -#else - #define LOG_VERBOSE(level, txt, ...) if (GetManager()->CheckVerbose(level)) { GetManager()->Log(txt, __VA_ARGS__); } -#endif - -//----------------------------------------------------------------------------- - -CRemoteCommandManager::CRemoteCommandManager() -{ - // Create the CVAR - m_pVerboseLevel = gEnv->pConsole->RegisterInt("rc_debugVerboseLevel", 0, VF_DEV_ONLY); -} - -CRemoteCommandManager::~CRemoteCommandManager() -{ - // Release the CVar - if (NULL != m_pVerboseLevel) - { - m_pVerboseLevel->Release(); - m_pVerboseLevel = NULL; - } -} - -IRemoteCommandServer* CRemoteCommandManager::CreateServer(uint16 localPort) -{ - // Create the listener - IServiceNetworkListener* listener = gEnv->pServiceNetwork->CreateListener(localPort); - if (NULL == listener) - { - return NULL; - } - - // Create the wrapper - return new CRemoteCommandServer(this, listener); -} - -IRemoteCommandClient* CRemoteCommandManager::CreateClient() -{ - // Create the wrapper - return new CRemoteCommandClient(this); -} - -void CRemoteCommandManager::RegisterCommandClass(IRemoteCommandClass& commandClass) -{ - // Make sure command class is not already registered - const string& className(commandClass.GetName()); - TClassMap::const_iterator it = m_pClasses.find(className); - if (it != m_pClasses.end()) - { - LOG_VERBOSE(1, "Class '%s' is already registered", - className.c_str()); - - return; - } - - const uint32 classID = m_pClassesByID.size(); - m_pClassesByID.push_back(&commandClass); - m_pClassesMap[ className ] = classID; - m_pClasses[ className ] = &commandClass; - - // Verbose - LOG_VERBOSE(1, "Registered command class '%s' with id %d", - className.c_str(), - classID); -} - -#ifndef RELEASE -bool CRemoteCommandManager::CheckVerbose(const uint32 level) const -{ - const int verboseLevel = m_pVerboseLevel->GetIVal(); - return (int)level < verboseLevel; -} - -void CRemoteCommandManager::Log(const char* txt, ...) const -{ - // format the print buffer - char buffer[512]; - va_list ap; - va_start(ap, txt); - vsprintf_s(buffer, sizeof(buffer), txt, ap); - va_end(ap); - - // pass to log - gEnv->pLog->LogAlways(buffer); -} -#endif - -void CRemoteCommandManager::BuildClassMapping(const std::vector& classNames, std::vector< IRemoteCommandClass* >& outClasses) -{ - LOG_VERBOSE(3, "Building class mapping for %d classes", - classNames.size()); - - // Output list size has the same size as class names array - const uint32 numClasses = classNames.size(); - outClasses.resize(numClasses); - - // Match the classes - for (size_t i = 0; i < numClasses; ++i) - { - // Find the matching class - const string& className = classNames[i]; - TClassMap::const_iterator it = m_pClasses.find(className); - if (it != m_pClasses.end()) - { - CRY_ASSERT(className == it->second->GetName()); - CRY_ASSERT(it->second != NULL); - outClasses[i] = it->second; - - // Report class mapping in heavy verbose mode - LOG_VERBOSE(3, "Class[%d] = %s", - i, - className.c_str()); - } - else - { - outClasses[i] = NULL; - - // Class not mapped (this can cause errors) - LOG_VERBOSE(0, "Remote command class '%s' not found on this machine", - className.c_str()); - } - } -} - -void CRemoteCommandManager::SetVerbosityLevel(const uint32 level) -{ - // propagate the value to CVar (so it is consistent across the engine) - if (NULL != m_pVerboseLevel) - { - m_pVerboseLevel->Set((int)level); - } -} - -void CRemoteCommandManager::GetClassList(std::vector& outClassNames) const -{ - const uint32 numClasses = m_pClassesByID.size(); - outClassNames.resize(numClasses); - for (size_t id = 0; id < numClasses; ++id) - { - IRemoteCommandClass* theClass = m_pClassesByID[id]; - if (NULL != theClass) - { - outClassNames[id] = theClass->GetName(); - } - } -} - -bool CRemoteCommandManager::FindClassId(IRemoteCommandClass* commandClass, uint32& outClassId) const -{ - // Local search (linear, slower) - TClassIDMap::const_iterator it = m_pClassesMap.find(commandClass->GetName()); - if (it != m_pClassesMap.end()) - { - outClassId = it->second; - return true; - } - - // Not found - return false; -} - -//----------------------------------------------------------------------------- - -// Do not remove (can mess up the uber file builds) -#undef LOG_VERBOSE - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/RemoteCommand.h b/Code/CryEngine/CrySystem/RemoteCommand.h deleted file mode 100644 index 6ce5e3fd11..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommand.h +++ /dev/null @@ -1,459 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Remote command system implementation - - -#pragma once - - -//----------------------------------------------------------------------------- - -#include "IServiceNetwork.h" -#include "IRemoteCommand.h" -#include "CryThread.h" - -class CRemoteCommandManager; - -// Remote command client implementation -class CRemoteCommandClient - : public IRemoteCommandClient - , public CryRunnable -{ -protected: - //------------------------------------------------------------- - - class Command - { - public: - ILINE IServiceNetworkMessage* GetMessage() const - { - return m_pMessage; - } - - ILINE uint32 GetCommandId() const - { - return m_id; - } - - public: - // Create command data from serializing a remote command object - static Command* Compile(const IRemoteCommand& cmd, const uint32 commandId, const uint32 classId); - - void AddRef(); - void Release(); - - private: - Command(); - ~Command(); - - volatile int m_refCount; - uint32 m_id; - const char* m_szClassName; // debug only - IServiceNetworkMessage* m_pMessage; - }; - - //------------------------------------------------------------- - - // Local connection reference to command - // NOTE: pCommand is reference counted from the calling code - struct CommandRef - { - Command* m_pCommand; - uint64 m_lastSentTime; - - ILINE CommandRef() - : m_pCommand(NULL) - , m_lastSentTime(0) - {} - - ILINE CommandRef(Command* pCommand) - : m_pCommand(pCommand) - , m_lastSentTime(0) - {} - - // Order function for set container (we want to keep the commands sorted by ID) - static ILINE bool CompareCommandRefs(CommandRef* const& a, CommandRef* const& b) - { - return a->m_pCommand->GetCommandId() < b->m_pCommand->GetCommandId(); - } - }; - - //------------------------------------------------------------- - - // Remote server connection wrapper - class Connection - : public IRemoteCommandConnection - { - // How many commands we can send upfront before waiting for an ACK - static const uint32 kCommandSendLead = 50; - - // How much command data can be merged into a single packet (KB) - static const uint32 kCommandMaxMergePacketSize = 1024; - - // Time after which we start resending commands (ms) - static const uint32 kCommandResendTime = 2000; - - protected: - CRemoteCommandManager* m_pManager; - volatile int m_refCount; - - // Connection (from service network layer) - IServiceNetworkConnection* m_pConnection; - - // Cached address of the remote endpoint - ServiceNetworkAddress m_remoteAddress; - - // Pending commands, they are kept ed here until they are ACKed as executed by server - typedef std::vector TCommands; - TCommands m_pCommands; - CryMutex m_commandAccessMutex; - - // A queue of raw messages - typedef CryMT::CLocklessPointerQueue TRawMessageQueue; - TRawMessageQueue m_pRawMessages; - CryMutex m_rawMessagesMutex; - - // Last command that was ACKed as received by server - // This is used to synchronize the both ends of the pipeline - uint32 m_lastReceivedCommand; - - // Last command that was ACKed as executed by server - // This is used to synchronize the both ends of the pipeline - uint32 m_lastExecutedCommand; - - public: - ILINE CRemoteCommandManager* GetManager() const - { - return m_pManager; - } - - public: - Connection(CRemoteCommandManager* pManager, IServiceNetworkConnection* pConnection, uint32 currentCommandId); - - // Add command to sending queue in this connection - void AddToSendQueue(Command* pCommand); - - // Process the communication, returns false if connection should be deleted - bool Update(); - - // Send the "disconnect" message to the remote side therefore gracefully closing the connection. - void SendDisconnectMessage(); - - public: - // IRemoteCommandConnection interface implementation - virtual bool IsAlive() const; - virtual const ServiceNetworkAddress& GetRemoteAddress() const; - virtual bool SendRawMessage(IServiceNetworkMessage* pMessage); - virtual IServiceNetworkMessage* ReceiveRawMessage(); - virtual void Close(bool bFlushQueueBeforeClosing = false); - virtual void AddRef(); - virtual void Release(); - - private: - ~Connection(); - }; - -protected: - CRemoteCommandManager* m_pManager; - - typedef std::vector TConnections; - TConnections m_pConnections; - TConnections m_pConnectionsToDelete; - CryMutex m_accessMutex; - - // Local command ID counter, incremented atomically using CryInterlockedIncrement - volatile uint32 m_commandId; - - typedef CryThread TRemoteClientThread; - TRemoteClientThread* m_pThread; - CryEvent m_threadEvent; - bool m_bCloseThread; - -public: - ILINE CRemoteCommandManager* GetManager() const - { - return m_pManager; - } - -public: - CRemoteCommandClient(CRemoteCommandManager* pManager); - virtual ~CRemoteCommandClient(); - - // IRemoteCommandClient interface - virtual void Delete(); - virtual bool Schedule(const IRemoteCommand& command); - virtual IRemoteCommandConnection* ConnectToServer(const class ServiceNetworkAddress& serverAddress); - - // CryRunnable interface implementation - virtual void Run(); - virtual void Cancel(); -}; - -//----------------------------------------------------------------------------- - -// Remote command server implementation -class CRemoteCommandServer - : public IRemoteCommandServer - , public CryRunnable -{ -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(RemoteCommand_h) -#endif - -protected: - // Wrapped commands - class WrappedCommand - { - private: - IRemoteCommand* m_pCommand; - volatile int m_refCount; - uint32 m_commandID; - - public: - ILINE const uint32 GetId() const - { - return m_commandID; - } - - ILINE IRemoteCommand* GetCommand() const - { - return m_pCommand; - } - - public: - WrappedCommand(IRemoteCommand* pCommand, const uint32 commandId); - void AddRef(); - void Release(); - - private: - ~WrappedCommand(); - }; - - // Local endpoint - class Endpoint - { - private: - IServiceNetworkConnection* m_pConnection; - class CRemoteCommandServer* m_pServer; - CRemoteCommandManager* m_pManager; - - // ACK counters for synchronization - uint32 m_lastReceivedCommand; - uint32 m_lastExecutedCommand; - uint32 m_lastReceivedCommandACKed; - uint32 m_lastExecutedCommandACKed; - CryMutex m_accessLock; - - // We have received class list (it's a valid RC connection) - bool m_bHasReceivedClassList; - - // Locally mapped class id (because IDs on remote side can be different than here) - typedef std::vector< IRemoteCommandClass* > TLocalClassFactoryList; - TLocalClassFactoryList m_pLocalClassFactories; - - // Commands that were received and should be executed - typedef CryMT::CLocklessPointerQueue< WrappedCommand > TCommandQueue; - TCommandQueue m_pCommandsToExecute; - CryMutex m_commandListLock; - - public: - ILINE CRemoteCommandManager* GetManager() const - { - return m_pManager; - } - - // Get the endpoint connection - ILINE IServiceNetworkConnection* GetConnection() const - { - return m_pConnection; - } - - // Have we received a class list from the client - ILINE bool HasReceivedClassList() const - { - return m_bHasReceivedClassList; - } - - public: - Endpoint(CRemoteCommandManager* pManager, class CRemoteCommandServer* pServer, IServiceNetworkConnection* pConnection); - ~Endpoint(); - - // Execute pending commands (called from main thread) - void Execute(); - - // Update (send/receive, etc) Returns false if endpoint died. - bool Update(); - - // Get the class name as translated by this endpoint (by ID) - const char* GetClassName(const uint32 classId) const; - - // Create command object by class ID - IRemoteCommand* CreateObject(const uint32 classId) const; - }; - - // Received raw message - // Beware to use always via pointer to this type since propper reference counting is not implemented for copy and assigment - struct RawMessage - { - // We keep a reference to connection so we know where to send the response - IServiceNetworkConnection* m_pConnection; - IServiceNetworkMessage* m_pMessage; - - ILINE RawMessage(IServiceNetworkConnection* pConnection, IServiceNetworkMessage* pMessage) - : m_pConnection(pConnection) - , m_pMessage(pMessage) - { - m_pMessage->AddRef(); - m_pConnection->AddRef(); - } - - ILINE ~RawMessage() - { - m_pMessage->Release(); - m_pConnection->Release(); - } - - private: - ILINE RawMessage([[maybe_unused]] const RawMessage& other) {}; - ILINE RawMessage& operator==([[maybe_unused]] const RawMessage& other) { return *this; } - }; - -protected: - CRemoteCommandManager* m_pManager; - - // Network listening socket - IServiceNetworkListener* m_pListener; - - // Live endpoints - typedef std::vector TEndpoints; - TEndpoints m_pEndpoints; - TEndpoints m_pUpdateEndpoints; - CryMutex m_accessLock; - - // Endpoints that were discarded and should be deleted - // We can delete endpoints only from the update thread - TEndpoints m_pEndpointToDelete; - - // Received raw messages - typedef CryMT::CLocklessPointerQueue TRawMessagesQueue; - TRawMessagesQueue m_pRawMessages; - CryMutex m_rawMessagesLock; - - // Listeners for raw messages that require synchronous processing - typedef std::vector TRawMessageListenersSync; - TRawMessageListenersSync m_pRawListenersSync; - - // Listeners for raw messages that can be processed asynchronously (faster path) - typedef std::vector TRawMessageListenersAsync; - TRawMessageListenersAsync m_pRawListenersAsync; - - // Command communication and deserialization is done on thread - typedef CryThread TRemoteServerThread; - TRemoteServerThread* m_pThread; - - // Suppression counter (execution of commands is suppressed when>0) - // This is updated using CryInterlocked* functions - volatile int m_suppressionCounter; - bool m_bIsSuppressed; - - // Request to close the network thread - bool m_bCloseThread; - -public: - ILINE CRemoteCommandManager* GetManager() const - { - return m_pManager; - } - -public: - CRemoteCommandServer(CRemoteCommandManager* pManager, IServiceNetworkListener* pListener); - virtual ~CRemoteCommandServer(); - - // IRemoteCommandServer interface implementation - virtual void Delete(); - virtual void FlushCommandQueue(); - virtual void SuppressCommands(); - virtual void ResumeCommands(); - virtual void RegisterSyncMessageListener(IRemoteCommandListenerSync* pListener); - virtual void UnregisterSyncMessageListener(IRemoteCommandListenerSync* pListener); - virtual void RegisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener); - virtual void UnregisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener); - virtual void Broadcast(IServiceNetworkMessage* pMessage); - virtual bool HasConnectedClients() const; - - // CryRunnable - virtual void Run(); - virtual void Cancel(); - -protected: - void ProcessRawMessageAsync(IServiceNetworkMessage* pMessage, IServiceNetworkConnection* pConnection); - void ProcessRawMessagesSync(); -}; - -//----------------------------------------------------------------------------- - -// Remote command manager implementation -class CRemoteCommandManager - : public IRemoteCommandManager -{ -public: - CRemoteCommandManager(); - virtual ~CRemoteCommandManager(); - - // IRemoteCommandManager interface implementation - virtual void SetVerbosityLevel(const uint32 level); - virtual IRemoteCommandServer* CreateServer(uint16 localPort); - virtual IRemoteCommandClient* CreateClient(); - virtual void RegisterCommandClass(IRemoteCommandClass& commandClass); - - // Debug print -#ifdef RELEASE - void Log([[maybe_unused]] const char* txt, ...) const {}; - bool CheckVerbose([[maybe_unused]] const uint32 level) const { return false; } -#else - void Log(const char* txt, ...) const; - bool CheckVerbose(const uint32 level) const; -#endif - - // Build ID->Class Factory mapping given the class name list, will report errors to the log. - void BuildClassMapping(const std::vector& classNames, std::vector< IRemoteCommandClass* >& outClasses); - - // Get list of class names (in order of their IDs) - void GetClassList(std::vector& outClassNames) const; - - // Find class ID for given class, returns false if not found - bool FindClassId(IRemoteCommandClass* commandClass, uint32& outClassId) const; - -public: - ILINE CRemoteCommandManager* GetManager() - { - return this; - } - -private: - // Class name mapping - typedef std::map< string, IRemoteCommandClass* > TClassMap; - TClassMap m_pClasses; - - // Class ID lookup - typedef std::vector< IRemoteCommandClass* > TClassIDList; - TClassIDList m_pClassesByID; - - // Class ID mapping - typedef std::map< string, int > TClassIDMap; - TClassIDMap m_pClassesMap; - - // Verbose level - ICVar* m_pVerboseLevel; -}; diff --git a/Code/CryEngine/CrySystem/RemoteCommandClient.cpp b/Code/CryEngine/CrySystem/RemoteCommandClient.cpp deleted file mode 100644 index 1855aae4a9..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommandClient.cpp +++ /dev/null @@ -1,756 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Remote command system implementation - -#include "CrySystem_precompiled.h" -#include "IServiceNetwork.h" -#include "RemoteCommand.h" -#include "RemoteCommandHelpers.h" - -//----------------------------------------------------------------------------- - -// remote system internal logging -#ifdef RELEASE - #define LOG_VERBOSE(level, txt, ...) -#else - #define LOG_VERBOSE(level, txt, ...) if (GetManager()->CheckVerbose(level)) { GetManager()->Log(txt, __VA_ARGS__); } -#endif - -//----------------------------------------------------------------------------- - -CRemoteCommandClient::Command::Command() - : m_refCount(1) - , m_szClassName(NULL) - , m_id(0) -{ -} - -CRemoteCommandClient::Command::~Command() -{ - // Release message buffer with compiled command data - if (m_pMessage != NULL) - { - m_pMessage->Release(); - m_pMessage = NULL; - } -} - -CRemoteCommandClient::Command* CRemoteCommandClient::Command::Compile(const IRemoteCommand& cmd, const uint32 commandId, const uint32 classId) -{ - // Build command header - CommandHeader header; - header.classId = classId; - header.commandId = commandId; - header.size = 0; // not known yet - - // Output stream builder - CDataWriteStreamBuffer writer; - - // Start the packet with a command header (it will be later overwritten) - writer << header; - - // Serialize command header and data - const uint32 commandDataStart = writer.GetSize(); - cmd.SaveToStream(writer); - const uint32 commandDataEnd = writer.GetSize(); - - // Extract a message from the stream - IServiceNetworkMessage* pMessage = writer.BuildMessage(); - if (NULL == pMessage) - { - // No message was generated (for some reason) - // Do not allow this command to compile - return NULL; - } - - // Rewrite header with the proper command size - // This is a little bit over-the-top because it uses another serializer created - // on top of the message buffer. The advantage is that we have the endianess problem abstracted away. - // TODO: consider writing the size directly - { - // update header with popper data size - const uint32 dataSize = commandDataEnd - commandDataStart; - header.size = dataSize; - - // rewrite the header in existing message - CDataWriteStreamToMessage inPlaceWriter(pMessage); - inPlaceWriter << header; - } - - // Create command wrapper - Command* pCommand = new Command(); - pCommand->m_id = commandId; - pCommand->m_szClassName = cmd.GetClass()->GetName(); - pCommand->m_pMessage = pMessage; - return pCommand; -} - -void CRemoteCommandClient::Command::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CRemoteCommandClient::Command::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -//----------------------------------------------------------------------------- - -CRemoteCommandClient::Connection::Connection(CRemoteCommandManager* pManager, IServiceNetworkConnection* pConnection, uint32 currentCommandId) - : m_pConnection(pConnection) - , m_pManager(pManager) - , m_lastReceivedCommand(currentCommandId) - , m_lastExecutedCommand(currentCommandId) - , m_remoteAddress(pConnection->GetRemoteAddress()) - , m_refCount(1) -{ - // The first thing to do after the connection is initialized is to - // send the message with list of classes supported by this side. - { - // Write the header - PackedHeader header; - header.magic = PackedHeader::kMagic; - header.msgType = PackedHeader::eCommand_ClassList; - header.count = currentCommandId; // send the intial command ID so we can be in sync - - // Get the class list for our local remote command manager - std::vector< string > classList; - GetManager()->GetClassList(classList); - - // Write the message - CDataWriteStreamBuffer writer; - writer << header; - writer << classList; - - // Send the message to the remote side - IServiceNetworkMessage* pMsg = writer.BuildMessage(); - if (NULL != pMsg) - { - LOG_VERBOSE(1, "Sent class list message (%d classes, size=%d) to '%s'", - classList.size(), - pMsg->GetSize(), - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // TODO: well, there is no reason this can fail since the connection is brand new, but... - // We still relay on the service network to deliver this message unharmed. - m_pConnection->SendMsg(pMsg); - - // cleanup - pMsg->Release(); - } - } -} - -CRemoteCommandClient::Connection::~Connection() -{ - // Close the connection - const bool bFlushBeforeClosing = false; - Close(bFlushBeforeClosing); - - // Release any commands left over on the list - for (TCommands::const_iterator it = m_pCommands.begin(); - it != m_pCommands.end(); ++it) - { - (*it)->m_pCommand->Release(); - delete (*it); - } - m_pCommands.clear(); - - // Release all of the raw messages that were not picked up - while (!m_pRawMessages.empty()) - { - IServiceNetworkMessage* pMessage = m_pRawMessages.pop(); - pMessage->Release(); - } - - // Release the connection object - SAFE_RELEASE(m_pConnection); -} - -void CRemoteCommandClient::Connection::SendDisconnectMessage() -{ - if (NULL != m_pConnection && m_pConnection->IsAlive()) - { - IDataWriteStream* pWriter = gEnv->pServiceNetwork->CreateMessageWriter(); - if (NULL != pWriter) - { - // write header to message - PackedHeader header; - header.magic = PackedHeader::kMagic; - header.count = 0; - header.msgType = PackedHeader::eCommand_Disconnect; - *pWriter << header; - - // Send the disconnect signal - IServiceNetworkMessage* pMessage = pWriter->BuildMessage(); - if (NULL != pMessage) - { - m_pConnection->SendMsg(pMessage); - pMessage->Release(); - } - - pWriter->Delete(); - } - } -} - -void CRemoteCommandClient::Connection::AddToSendQueue(Command* pCommand) -{ - // Do not add commands if the connection is closed - if (m_pConnection == NULL) - { - return; - } - - // Add command to local list - // NOTE: this list always needs to be sorted in increasing command ID for various optimization reason. - // This is achieved by resorting after pushing each element. Usually the cost of this is close to nothing - // because incoming commands tend to be added with increasing command IDs. - // The only case when something else can happen is when commands are added from different threads - // and the one that was lower CommandID took longer to serialize and therefore is added later. - // Anyway, this case is handled here. - { - CryAutoLock lock(m_commandAccessMutex); - - // Always add to the end (don't try to guess position) - // TODO: consider binary search - m_pCommands.push_back(new CommandRef(pCommand)); - - // Resort, NODE: This usually does not sort anything because the vector is already sorted - std::sort(m_pCommands.begin(), m_pCommands.end(), CommandRef::CompareCommandRefs); - } - - // Keep local reference to command (since we added it to our array) - pCommand->AddRef(); -} - -bool CRemoteCommandClient::Connection::Update() -{ - // If the network connection got dead we should close this one to - if ((NULL == m_pConnection) || !m_pConnection->IsAlive()) - { - return false; - } - - // Receive ACKs first so we have better view of what to send - uint32 newLastExecutedCommand = m_lastExecutedCommand; - uint32 newLastReceivedCommand = m_lastReceivedCommand; - IServiceNetworkMessage* pMsg = m_pConnection->ReceiveMsg(); - while (pMsg != NULL) - { - // Deserialize the message - { - CDataReadStreamFormMessage reader(pMsg); - ResponseHeader response; - reader << response; - - // is this proper command system message ? - if (response.magic == PackedHeader::kMagic) - { - if (response.msgType == PackedHeader::eCommand_ACK) - { - // Update internal ACK values - // This code supports getting the ACK messages out of order. - newLastExecutedCommand = max(newLastExecutedCommand, response.lastCommandExecuted); - newLastReceivedCommand = max(newLastReceivedCommand, response.lastCommandReceived); - - LOG_VERBOSE(3, "ACK (rcv=%d, exe=%d) received from '%s'", - response.lastCommandReceived, - response.lastCommandExecuted, - m_pConnection->GetRemoteAddress().ToString().c_str()); - } - else if (response.msgType == PackedHeader::eCommand_Disconnect) - { - // Disconnect request was received - LOG_VERBOSE(3, "DISCONNECT (rcv=%d, exe=%d) received from '%s'", - response.lastCommandReceived, - response.lastCommandExecuted, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // Close connection - m_pConnection->Close(); - m_pConnection->Release(); - m_pConnection = NULL; - - // release the message - pMsg->Release(); - - // Signal manager to delete this object - return false; - } - } - else - { - // Keep an extra reference for the message in the raw message list - pMsg->AddRef(); - - // Assume it's a raw message, add it to the raw list - m_pRawMessages.push(pMsg); - } - } - - // Release message data - pMsg->Release(); - - // Get next message from the network - pMsg = m_pConnection->ReceiveMsg(); - } - - // ACK was updated - if ((newLastExecutedCommand != m_lastExecutedCommand) || - (newLastReceivedCommand != m_lastReceivedCommand)) - { - m_lastExecutedCommand = newLastExecutedCommand; - m_lastReceivedCommand = newLastReceivedCommand; - - // Drop commands that were ACKed as received (server has them and they will be executed soon) - { - CryAutoLock lock(m_commandAccessMutex); - - // we use this to count how many elements we need to remove later from the command vector - uint32 numCommandsToDelete = 0; - - for (TCommands::const_iterator it = m_pCommands.begin(); - it != m_pCommands.end(); ++it) - { - CommandRef* cmdRef = *it; - - // Command is still needed because it was not yet received by the remote part - if (cmdRef->m_pCommand->GetCommandId() > newLastReceivedCommand) - { - break; - } - - // Drop the command data - cmdRef->m_pCommand->Release(); - delete cmdRef; - - ++numCommandsToDelete; - } - - // Erase the command slots in the vector (in one batch) - if (numCommandsToDelete > 0) - { - m_pCommands.erase(m_pCommands.begin(), m_pCommands.begin() + numCommandsToDelete); - } - } - } - - // (Re)Send the commands - { - // Calculate the maximum command ID we can send, this depends on - // the last command that was ACKed as executed on the remote side. - // This effectively throttles the communication and prevents the - // situation when remote side is flooded with unprocessed commands. - // NOTE: the time when command is executed is different to the - // time that command is received. Sometimes if the server is suppressed (level loading) - // it can take a long time before commands begin to execute. - const uint32 maxCommandIdToSend = m_lastExecutedCommand + kCommandSendLead; - - // Calculate the cutoff time for sending (all commands that were not send before this time will be sent again) - // This assumes that the last sent time for new commands is 0 (so they will always got sent the first time) - // This situation can only happen due to the network failure since RemoteCommand layer does not require the commands to be resent. - const uint64 currentTime = gEnv->pTimer->GetAsyncTime().GetMilliSecondsAsInt64(); - const uint64 cutoffTime = currentTime - kCommandResendTime; - - std::vector< CommandRef* > commandsInPacket; // temp array - - // Process until we send all that there is to send - for (;; ) - { - // When sending connections try to merge them in larger packets. - // NOTE: this should not impact delivery time since we are not waiting - // for pending commands to accumulate before sending them, it's just an optimization - // to prevent may small messages from being sent. - uint32 packetDataSizeSoFar = 0; - { - CryAutoLock lock(m_commandAccessMutex); - - // fast local clear - // TODO: do we have a good template alternative to temporary array on stack? - packetDataSizeSoFar = 0; - commandsInPacket.resize(0); - - for (TCommands::iterator it = m_pCommands.begin(); - it != m_pCommands.end(); ++it) - { - CommandRef* commandRef = *it; - - // this command is to new, don't send it - if (commandRef->m_pCommand->GetCommandId() >= maxCommandIdToSend) - { - break; - } - - // should we send this command ? - if (commandRef->m_lastSentTime < cutoffTime) - { - // will it fit into current packet ? - const uint32 commandDataSize = commandRef->m_pCommand->GetMessage()->GetSize(); - if (packetDataSizeSoFar == 0 || // always add at least one command to the packet (no splitting) - (packetDataSizeSoFar + commandDataSize < kCommandMaxMergePacketSize)) - { - if (commandRef->m_lastSentTime == 0) - { - LOG_VERBOSE(3, "Command ID=%d is sent FIRST TIME to '%s'", - commandRef->m_pCommand->GetCommandId(), - m_pConnection->GetRemoteAddress().ToString().c_str()); - } - else - { - LOG_VERBOSE(3, "Command ID=%d is resent to '%s'", - commandRef->m_pCommand->GetCommandId(), - m_pConnection->GetRemoteAddress().ToString().c_str()); - } - - // will be sent - commandsInPacket.push_back(commandRef); - packetDataSizeSoFar += commandDataSize; - } - else - { - LOG_VERBOSE(3, "Command ID=%d is to big (%d) to fit packet size limit (%d)", - commandRef->m_pCommand->GetCommandId(), - commandDataSize, - kCommandMaxMergePacketSize); - - // no more commands will fit current packet - break; - } - } - } - } - - // No new commands to be send - if (commandsInPacket.empty()) - { - break; - } - - // Stats - LOG_VERBOSE(3, "Sending %d commands in packet, total size=%d, maxID=%d, dest: %s", - commandsInPacket.size(), - packetDataSizeSoFar, - maxCommandIdToSend, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // Estimate the size of the network packet - const uint32 messageDataSize = packetDataSizeSoFar + PackedHeader::kSerializationSize; - - // Allocate and fill the message buffer - IServiceNetworkMessage* pSendMsg = gEnv->pServiceNetwork->AllocMessageBuffer(messageDataSize); - if (NULL != pSendMsg) - { - CDataWriteStreamToMessage writer(pSendMsg); - - // Packet header - PackedHeader header; - header.magic = PackedHeader::kMagic; - header.msgType = PackedHeader::eCommand_Command; - header.count = commandsInPacket.size(); // number commands to send in this packet - writer << header; - - // Merge data of single commands - for (size_t i = 0; i < commandsInPacket.size(); ++i) - { - const IServiceNetworkMessage* pCommandMsg = commandsInPacket[i]->m_pCommand->GetMessage(); - writer.Write(pCommandMsg->GetPointer(), pCommandMsg->GetSize()); - } - - // Schedule the packet for sending via our network connection - if (m_pConnection->SendMsg(pSendMsg)) - { - // Only after the network layer has accepted our message we can assume that the commands were sent - for (size_t i = 0; i < commandsInPacket.size(); ++i) - { - CommandRef* cmdRef = commandsInPacket[i]; - cmdRef->m_lastSentTime = currentTime; - } - - // Release temporary message memory - pSendMsg->Release(); - } - else - { - // We failed to send the message (possibly the send queue is full) - pSendMsg->Release(); - break; - } - } - else - { - // No message was created, stop sending - break; - } - } - } - - // Keep the connection alive - return true; -} - -bool CRemoteCommandClient::Connection::IsAlive() const -{ - return (NULL != m_pConnection) && (m_pConnection->IsAlive()); -} - -const ServiceNetworkAddress& CRemoteCommandClient::Connection::GetRemoteAddress() const -{ - return m_remoteAddress; -} - -void CRemoteCommandClient::Connection::Close(bool bFlushQueueBeforeClosing /*= false*/) -{ - // Close the connection - if (NULL != m_pConnection) - { - if (m_pConnection->IsAlive() && bFlushQueueBeforeClosing) - { - // We have a chance to send a graceful disconnect message, so send it - SendDisconnectMessage(); - - // Send all the messages from the send queue before closing this connection. - // This does not block current thread. - m_pConnection->FlushAndClose(IServiceNetworkConnection::kDefaultFlushTime); - } - else - { - // Just close the connection (hasher way) - m_pConnection->Close(); - } - } -} - -bool CRemoteCommandClient::Connection::SendRawMessage(IServiceNetworkMessage* pMessage) -{ - // We can send the raw messages right away - if (NULL != m_pConnection && m_pConnection->IsAlive()) - { - return m_pConnection->SendMsg(pMessage); - } - else - { - return false; - } -} - -IServiceNetworkMessage* CRemoteCommandClient::Connection::ReceiveRawMessage() -{ - return m_pRawMessages.pop(); -} - -void CRemoteCommandClient::Connection::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CRemoteCommandClient::Connection::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -//----------------------------------------------------------------------------- - -CRemoteCommandClient::CRemoteCommandClient(CRemoteCommandManager* pManager) - : m_pManager(pManager) - , m_commandId(0) - , m_bCloseThread(false) -{ - // Start processing thread (sending, etc) - m_pThread = new TRemoteClientThread(); - m_pThread->Start(*this); -} - -CRemoteCommandClient::~CRemoteCommandClient() -{ - // Stop the thread - if (NULL != m_pThread) - { - m_pThread->Cancel(); - m_pThread->Stop(); - m_pThread->WaitForThread(); - delete m_pThread; - } - - // Delete connections - for (size_t i = 0; i < m_pConnections.size(); ++i) - { - m_pConnections[i]->Release(); - } - m_pConnections.clear(); -} - -void CRemoteCommandClient::Delete() -{ - delete this; -} - -IRemoteCommandConnection* CRemoteCommandClient::ConnectToServer(const class ServiceNetworkAddress& serverAddress) -{ - CryAutoLock< CryMutex > lock(m_accessMutex); - - // Do not connect twice to the same server - for (TConnections::const_iterator it = m_pConnections.begin(); - it != m_pConnections.end(); ++it) - { - if (ServiceNetworkAddress::CompareBaseAddress((*it)->GetRemoteAddress(), serverAddress)) - { - LOG_VERBOSE(0, "Failed to connect to server '%s': already connected", - serverAddress.ToString().c_str()); - - return NULL; - } - } - - // Open a network connection - IServiceNetworkConnection* pNetConnection = gEnv->pServiceNetwork->Connect(serverAddress); - if (NULL == pNetConnection) - { - LOG_VERBOSE(0, "Failed to connect to server '%s': server is not responding", - serverAddress.ToString().c_str()); - - return NULL; - } - - // Get current command ID (only commands after this one will be sent) - const uint32 firstCommandId = m_commandId; - - // Create a wrapping class and add it to the connection list - Connection* pConnection = new Connection(GetManager(), pNetConnection, firstCommandId); - m_pConnections.push_back(pConnection); - - // Keep internal reference - pConnection->AddRef(); - - LOG_VERBOSE(0, "Connected to remote command server '%s', first command ID=%d", - serverAddress.ToString().c_str(), - firstCommandId); - - return pConnection; -} - -bool CRemoteCommandClient::Schedule(const IRemoteCommand& command) -{ - // No connections - if (m_pConnections.empty()) - { - return false; - } - - // Find ClassID for command - uint32 classId = 0; - if (!GetManager()->FindClassId(command.GetClass(), classId)) - { - LOG_VERBOSE(0, "Class '%s' not recognized. Did you call RegisterClass() ?", - command.GetClass()->GetName()); - - return false; - } - - // Alloc new command ID and compile command data - // TODO: consider moving the compilation to thread (this may be unsafe). - const uint32 commandId = CryInterlockedIncrement((volatile int*) &m_commandId); - Command* pCommand = Command::Compile(command, commandId, classId); - - // Register new command in all of the existing server connections - if (NULL != pCommand) - { - CryAutoLock lock(m_accessMutex); - - for (TConnections::const_iterator it = m_pConnections.begin(); - it != m_pConnections.end(); ++it) - { - (*it)->AddToSendQueue(pCommand); - } - - // We are done with our reference - pCommand->Release(); - } - - // Signal the thread to process data - m_threadEvent.Set(); - return true; -} - -void CRemoteCommandClient::Run() -{ - TConnections pUpdateList; - - CryThreadSetName(-1, "RemoteCommandThread"); - - while (!m_bCloseThread) - { - // copy to local list for updating - { - CryAutoLock lock(m_accessMutex); - pUpdateList = m_pConnections; - } - - // update current connection list - for (TConnections::const_iterator it = pUpdateList.begin(); - it != pUpdateList.end(); ++it) - { - if (!(*it)->Update()) - { - CryAutoLock lock(m_accessMutex); - m_pConnectionsToDelete.push_back(*it); - } - } - - // delete pending connections - { - CryAutoLock lock(m_accessMutex); - for (TConnections::iterator it = m_pConnectionsToDelete.begin(); - it != m_pConnectionsToDelete.end(); ++it) - { - // delete the object - (*it)->Release(); - (*it)->Close(true); - - // remove from connection list - TConnections::iterator jt = std::find(m_pConnections.begin(), m_pConnections.end(), *it); - if (jt != m_pConnections.end()) - { - m_pConnections.erase(jt); - } - } - - // reset the array - m_pConnectionsToDelete.clear(); - } - - // Limit the CPU usage - const uint32 maxWaitTime = 100; - m_threadEvent.Wait(maxWaitTime); - } -} - -void CRemoteCommandClient::Cancel() -{ - m_bCloseThread = true; -} - -//----------------------------------------------------------------------------- - -// Do not remove (can mess up the uber file builds) -#undef LOG_VERBOSE - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/RemoteCommandHelpers.cpp b/Code/CryEngine/CrySystem/RemoteCommandHelpers.cpp deleted file mode 100644 index 6857a9a31c..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommandHelpers.cpp +++ /dev/null @@ -1,361 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Helper classes for remote command system - - -#include "CrySystem_precompiled.h" -#include "IServiceNetwork.h" -#include "RemoteCommandHelpers.h" - -//----------------------------------------------------------------------------- - -CDataReadStreamFormMessage::CDataReadStreamFormMessage(const IServiceNetworkMessage* message) - : m_pMessage(message) - , m_size(message->GetSize()) - , m_pData(static_cast(message->GetPointer())) - , m_offset(0) -{ - // AddRef() is not const unfortunatelly - const_cast(m_pMessage)->AddRef(); -} - -CDataReadStreamFormMessage::~CDataReadStreamFormMessage() -{ - // Release() is not const unfortunatelly - const_cast(m_pMessage)->Release(); -} - -void CDataReadStreamFormMessage::Delete() -{ - delete this; -} - -void CDataReadStreamFormMessage::Skip(const uint32 size) -{ - CRY_ASSERT(m_offset + size < m_size); - m_offset += size; -} - -void CDataReadStreamFormMessage::Read(void* pData, const uint32 size) -{ - CRY_ASSERT(m_offset + size < m_size); - const char* pReadPtr = m_pData + m_offset; - memcpy(pData, pReadPtr, size); - m_offset += size; -} - -void CDataReadStreamFormMessage::Read8(void* pData) -{ - // it does not actually matter if its uint64, int64 or double so use any - ReadType(pData); -} - -void CDataReadStreamFormMessage::Read4(void* pData) -{ - // it does not actually matter if its uint32, int32 or float so use any - ReadType(pData); -} - -void CDataReadStreamFormMessage::Read2(void* pData) -{ - // it does not actually matter if its uint16, int16 so use any - ReadType(pData); -} - -void CDataReadStreamFormMessage::Read1(void* pData) -{ - // it does not actually matter if its uint8, int8 so use any - ReadType(pData); -} - -const void* CDataReadStreamFormMessage::GetPointer() -{ - const char* pReadPtr = m_pData + m_offset; - return pReadPtr; -} - -//----------------------------------------------------------------------------- - -CDataWriteStreamToMessage::CDataWriteStreamToMessage(IServiceNetworkMessage* pMessage) - : m_pMessage(pMessage) - , m_size(pMessage->GetSize()) - , m_pData(static_cast(pMessage->GetPointer())) - , m_offset(0) -{ - m_pMessage->AddRef(); -} - -CDataWriteStreamToMessage::~CDataWriteStreamToMessage() -{ - m_pMessage->Release(); -} - -void CDataWriteStreamToMessage::Delete() -{ - delete this; -} - -const uint32 CDataWriteStreamToMessage::GetSize() const -{ - return m_size; -} - -void CDataWriteStreamToMessage::CopyToBuffer(void* pData) const -{ - memcpy(pData, m_pData, m_size); -} - -IServiceNetworkMessage* CDataWriteStreamToMessage::BuildMessage() const -{ - m_pMessage->AddRef(); - return m_pMessage; -} - -void CDataWriteStreamToMessage::Write(const void* pData, const uint32 size) -{ - CRY_ASSERT(m_offset + size < m_size); - memcpy((char*)m_pData + m_offset, pData, size); - m_offset += size; -} - -void CDataWriteStreamToMessage::Write8(const void* pData) -{ - // it does not actually matter if its uint64, int64 or double so use any - WriteType(pData); -} - -void CDataWriteStreamToMessage::Write4(const void* pData) -{ - // it does not actually matter if its uint32, int32 or float so use any - WriteType(pData); -} - -void CDataWriteStreamToMessage::Write2(const void* pData) -{ - // it does not actually matter if its uint16, int16 so use any - WriteType(pData); -} - -void CDataWriteStreamToMessage::Write1(const void* pData) -{ - // it does not actually matter if its uint8, int8 so use any - WriteType(pData); -} - -//----------------------------------------------------------------------------- - -CDataReadStreamMemoryBuffer::CDataReadStreamMemoryBuffer(const void* pData, const uint32 size) - : m_size(size) - , m_offset(0) -{ - m_pData = new uint8 [size]; - memcpy(m_pData, pData, size); -} - -CDataReadStreamMemoryBuffer::~CDataReadStreamMemoryBuffer() -{ - delete [] m_pData; - m_pData = NULL; -} - -void CDataReadStreamMemoryBuffer::Delete() -{ - delete this; -} - -void CDataReadStreamMemoryBuffer::Skip(const uint32 size) -{ - CRY_ASSERT(m_offset + size <= m_size); - m_offset += size; -} - -void CDataReadStreamMemoryBuffer::Read8(void* pData) -{ - Read(pData, 8); - SwapEndian(*reinterpret_cast(pData)); -} - -void CDataReadStreamMemoryBuffer::Read4(void* pData) -{ - Read(pData, 4); - SwapEndian(*reinterpret_cast(pData)); -} - -void CDataReadStreamMemoryBuffer::Read2(void* pData) -{ - Read(pData, 2); - SwapEndian(*reinterpret_cast(pData)); -} - -void CDataReadStreamMemoryBuffer::Read1(void* pData) -{ - return Read(pData, 1); -} - -const void* CDataReadStreamMemoryBuffer::GetPointer() -{ - return m_pData + m_offset; -}; - -void CDataReadStreamMemoryBuffer::Read(void* pData, const uint32 size) -{ - CRY_ASSERT(m_offset + size <= m_size); - memcpy(pData, m_pData + m_offset, size); - m_offset += size; -} - -//----------------------------------------------------------------------------- - -CDataWriteStreamBuffer::CDataWriteStreamBuffer() - : m_size(0) -{ - // Start with the initial (preallocated) partition - // This optimization assumes that initial size of most of the messages will be small. - // NOTE: default partition is not added to the partition table (that would require push_backs to vector) - char* partitionMemory = &m_defaultPartition[0]; - m_pCurrentPointer = partitionMemory; - m_leftInPartition = sizeof(m_defaultPartition); -} - -CDataWriteStreamBuffer::~CDataWriteStreamBuffer() -{ - // Free all memory partitions that were allocated dynamically - for (size_t i = 0; i < m_pPartitions.size(); ++i) - { - CryModuleFree(m_pPartitions[i]); - } -} - -void CDataWriteStreamBuffer::Delete() -{ - delete this; -} - -const uint32 CDataWriteStreamBuffer::GetSize() const -{ - return m_size; -} - -void CDataWriteStreamBuffer::CopyToBuffer(void* pData) const -{ - uint32 dataLeft = m_size; - char* pWritePtr = (char*)pData; - - // Copy data from default (preallocated) partition - { - const uint32 partitionSize = sizeof(m_defaultPartition); - const uint32 dataToCopy = min(partitionSize, dataLeft); - memcpy(pWritePtr, &m_defaultPartition[0], dataToCopy); - - // advance - pWritePtr += dataToCopy; - dataLeft -= dataToCopy; - } - - // Copy data from dynamic partitions - for (uint32 i = 0; i < m_pPartitions.size(); ++i) - { - // get size of data to copy - const uint32 partitionSize = m_partitionSizes[i]; - const uint32 dataToCopy = min(partitionSize, dataLeft); - memcpy(pWritePtr, m_pPartitions[i], dataToCopy); - - // advance - pWritePtr += dataToCopy; - dataLeft -= dataToCopy; - } - - // Make sure all data was written - CRY_ASSERT(dataLeft == 0); -} - -IServiceNetworkMessage* CDataWriteStreamBuffer::BuildMessage() const -{ - // No data written, no message created - if (0 == m_size) - { - return NULL; - } - - // Create message to hold all the data - IServiceNetworkMessage* pMessage = gEnv->pServiceNetwork->AllocMessageBuffer(m_size); - if (NULL == pMessage) - { - return NULL; - } - - // Copy data to messages - CopyToBuffer(pMessage->GetPointer()); - return pMessage; -} - -void CDataWriteStreamBuffer::Write(const void* pData, const uint32 size) -{ - static const uint32 kAdditionalPartitionSize = 65536; - - uint32 dataLeft = size; - while (dataLeft > 0) - { - // new partition needed - if (m_leftInPartition == 0) - { - // Allocate new partition data - char* partitionMemory = (char*)CryModuleMalloc(kAdditionalPartitionSize); - CRY_ASSERT(partitionMemory != NULL); - - // add new partition to list - m_partitionSizes.push_back(kAdditionalPartitionSize); - m_pPartitions.push_back(partitionMemory); - m_pCurrentPointer = partitionMemory; - m_leftInPartition = kAdditionalPartitionSize; - } - - // how many bytes can we write to current partition ? - const uint32 maxToWrite = min(m_leftInPartition, dataLeft); - memcpy(m_pCurrentPointer, pData, maxToWrite); - - // advance - m_size += maxToWrite; - dataLeft -= maxToWrite; - pData = (const char*)pData + maxToWrite; - m_pCurrentPointer += maxToWrite; - m_leftInPartition -= maxToWrite; - } -} - -void CDataWriteStreamBuffer::Write8(const void* pData) -{ - // it does not actually matter if its uint64, int64 or double so use any - WriteType(pData); -} - -void CDataWriteStreamBuffer::Write4(const void* pData) -{ - // it does not actually matter if its uint32, int32 or float so use any - WriteType(pData); -} - -void CDataWriteStreamBuffer::Write2(const void* pData) -{ - // it does not actually matter if its uint16, int16 so use any - WriteType(pData); -} - -void CDataWriteStreamBuffer::Write1(const void* pData) -{ - // it does not actually matter if its uint8, int8 so use any - WriteType(pData); -} - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/RemoteCommandHelpers.h b/Code/CryEngine/CrySystem/RemoteCommandHelpers.h deleted file mode 100644 index 948097db22..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommandHelpers.h +++ /dev/null @@ -1,307 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Remote command system helper classes - - -#ifndef CRYINCLUDE_CRYSYSTEM_REMOTECOMMANDHELPERS_H -#define CRYINCLUDE_CRYSYSTEM_REMOTECOMMANDHELPERS_H -#pragma once - - -//------------------------------------------------------------------------ - -#include "IRemoteCommand.h" - -struct IServiceNetworkMessage; - -//------------------------------------------------------------------------ - -// Stream reader for service network message -// Implements automatic byte swapping -class CDataReadStreamFormMessage - : public IDataReadStream -{ -private: - const IServiceNetworkMessage* m_pMessage; - const char* m_pData; - uint32 m_offset; - uint32 m_size; - -private: - template - ILINE void ReadType(void* pData) - { - CRY_ASSERT(m_offset + sizeof(T) < m_size); - const T& readPos = *reinterpret_cast(m_pData + m_offset); - *reinterpret_cast(pData) = readPos; - SwapEndian(*reinterpret_cast(pData)); - m_offset += sizeof(T); - } - -public: - CDataReadStreamFormMessage(const IServiceNetworkMessage* message); - virtual ~CDataReadStreamFormMessage(); - - const uint32 GetOffset() const - { - return m_offset; - } - - void SetPosition(uint32 offset) - { - m_offset = offset; - } - -public: - // IDataReadStream interface - virtual void Delete(); - virtual void Skip(const uint32 size); - virtual void Read(void* pData, const uint32 size); - virtual void Read8(void* pData); - virtual void Read4(void* pData); - virtual void Read2(void* pData); - virtual void Read1(void* pData); - virtual const void* GetPointer(); -}; - -//------------------------------------------------------------------------ - -// Stream writer that writes into the service network message -class CDataWriteStreamToMessage - : public IDataWriteStream -{ -private: - IServiceNetworkMessage* m_pMessage; - char* m_pData; - uint32 m_offset; - uint32 m_size; - -private: - template - ILINE void WriteType(const void* pData) - { - CRY_ASSERT(m_offset + sizeof(T) < m_size); - T& writePos = *reinterpret_cast(m_pData + m_offset); - writePos = *reinterpret_cast(pData); - SwapEndian(writePos); - m_offset += sizeof(T); - } - -public: - CDataWriteStreamToMessage(IServiceNetworkMessage* pMessage); - virtual ~CDataWriteStreamToMessage(); - - // IDataWriteStream interface implementation - virtual void Delete(); - virtual const uint32 GetSize() const; - virtual struct IServiceNetworkMessage* BuildMessage() const; - virtual void CopyToBuffer(void* pData) const; - virtual void Write(const void* pData, const uint32 size); - virtual void Write8(const void* pData); - virtual void Write4(const void* pData); - virtual void Write2(const void* pData); - virtual void Write1(const void* pData); -}; - -//------------------------------------------------------------------------ - -/// Stream reader reading from owner memory buffer -class CDataReadStreamMemoryBuffer - : public IDataReadStream -{ -private: - const uint32 m_size; - uint8* m_pData; - uint32 m_offset; - -public: - // memory is copied! - CDataReadStreamMemoryBuffer(const void* pData, const uint32 size); - virtual ~CDataReadStreamMemoryBuffer(); - - virtual void Delete(); - virtual void Skip(const uint32 size); - virtual void Read8(void* pData); - virtual void Read4(void* pData); - virtual void Read2(void* pData); - virtual void Read1(void* pData); - virtual const void* GetPointer(); - virtual void Read(void* pData, const uint32 size); -}; - -//------------------------------------------------------------------------ - -// Stream writer that writes into the internal memory buffer -class CDataWriteStreamBuffer - : public IDataWriteStream -{ - static const uint32 kStaticPartitionSize = 4096; - -private: - // Default (preallocated) partition - char m_defaultPartition[ kStaticPartitionSize ]; - - // Allocated dynamic partitions - std::vector m_pPartitions; - - // Size of the dynamic message partitions - std::vector m_partitionSizes; - - // Pointer to current writing position in the current partition - char* m_pCurrentPointer; - - // Space left in current partition - uint32 m_leftInPartition; - - // Total message size so far - uint32 m_size; - -private: - // Directly write typed data into the stream - template - ILINE void WriteType(const void* pData) - { - // try to use the faster path if we are not crossing the partition boundary - if (m_leftInPartition >= sizeof(T)) - { - // faster case - T& writePos = *reinterpret_cast(m_pCurrentPointer); - writePos = *reinterpret_cast(pData); - SwapEndian(writePos); - m_pCurrentPointer += sizeof(T); - m_leftInPartition -= sizeof(T); - m_size += sizeof(T); - } - else - { - // slower case (more generic) - T tempVal(*reinterpret_cast(pData)); - SwapEndian(tempVal); - Write(&tempVal, sizeof(tempVal)); - } - } - -public: - CDataWriteStreamBuffer(); - virtual ~CDataWriteStreamBuffer(); - - // IDataWriteStream interface implementation - virtual void Delete(); - virtual const uint32 GetSize() const; - virtual IServiceNetworkMessage* BuildMessage() const; - virtual void CopyToBuffer(void* pData) const; - virtual void Write(const void* pData, const uint32 size); - virtual void Write8(const void* pData); - virtual void Write4(const void* pData); - virtual void Write2(const void* pData); - virtual void Write1(const void* pData); -}; - -//----------------------------------------------------------------------------- - -// Packet header -struct PackedHeader -{ - // Estimation (or better yet, exact value) of how much data this header will take when written. - // Please make sure that actual size after serialization is not bigger than this value. - static const uint32 kSerializationSize = sizeof(uint8) + sizeof(uint32) + sizeof(uint32); - - // Magic value that identifies command messages vs raw messages - static const uint32 kMagic = 0xABBAF00D; - - // Command type - // Keep the values unchanged as this may break the protocol - enum ECommand - { - // Server class list mapping - eCommand_ClassList = 0, - - // Command data - eCommand_Command = 1, - - // Disconnect signal - eCommand_Disconnect = 2, - - // ACK packet - eCommand_ACK = 3, - }; - - uint32 magic; - uint8 msgType; - uint32 count; - - // serialization operator - template< class T > - friend T& operator<<(T& stream, PackedHeader& header) - { - stream << header.magic; - stream << header.msgType; - stream << header.count; - return stream; - } -}; - -// Header sent with every command -struct CommandHeader -{ - uint32 commandId; - uint32 classId; - uint32 size; - - CommandHeader() - : commandId(0) - , classId(0) - , size(0) - {} - - // serialization operator - template< class T > - friend T& operator<<(T& stream, CommandHeader& header) - { - stream << header.commandId; - stream << header.classId; - stream << header.size; - return stream; - } -}; - -// General Response/ACK header -struct ResponseHeader -{ - uint32 magic; - uint8 msgType; - uint32 lastCommandReceived; - uint32 lastCommandExecuted; - - ResponseHeader() - : lastCommandReceived(0) - , lastCommandExecuted(0) - , msgType(PackedHeader::eCommand_ACK) - {} - - // serialization operator - template< class T > - friend T& operator<<(T& stream, ResponseHeader& header) - { - stream << header.magic; - stream << header.msgType; - stream << header.lastCommandReceived; - stream << header.lastCommandExecuted; - return stream; - } -}; - -//----------------------------------------------------------------------------- - -#endif // CRYINCLUDE_CRYSYSTEM_REMOTECOMMANDHELPERS_H diff --git a/Code/CryEngine/CrySystem/RemoteCommandServer.cpp b/Code/CryEngine/CrySystem/RemoteCommandServer.cpp deleted file mode 100644 index 362a9faf1a..0000000000 --- a/Code/CryEngine/CrySystem/RemoteCommandServer.cpp +++ /dev/null @@ -1,832 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Remote command system implementation (server) - -#include "CrySystem_precompiled.h" -#include "IServiceNetwork.h" -#include "RemoteCommand.h" -#include "RemoteCommandHelpers.h" - -//----------------------------------------------------------------------------- - -// remote system internal logging -#ifdef RELEASE -#define LOG_VERBOSE(level, txt, ...) -#else -#define LOG_VERBOSE(level, txt, ...) if (GetManager()->CheckVerbose(level)) { GetManager()->Log(txt, __VA_ARGS__); } -#endif - -//----------------------------------------------------------------------------- - -CRemoteCommandServer::WrappedCommand::WrappedCommand(IRemoteCommand* pCommand, const uint32 commandId) - : m_pCommand(pCommand) - , m_refCount(1) - , m_commandID(commandId) -{ -} - -CRemoteCommandServer::WrappedCommand::~WrappedCommand() -{ - CRY_ASSERT(m_refCount == 0); - m_pCommand->Delete(); -} - -void CRemoteCommandServer::WrappedCommand::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CRemoteCommandServer::WrappedCommand::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -//----------------------------------------------------------------------------- - -CRemoteCommandServer::Endpoint::Endpoint(CRemoteCommandManager* pManager, class CRemoteCommandServer* pServer, IServiceNetworkConnection* pConnection) - : m_pConnection(pConnection) - , m_pManager(pManager) - , m_pServer(pServer) - , m_lastReceivedCommand(0) - , m_lastExecutedCommand(0) - , m_lastReceivedCommandACKed(0) - , m_lastExecutedCommandACKed(0) - , m_bHasReceivedClassList(false) -{ -} - -CRemoteCommandServer::Endpoint::~Endpoint() -{ - // release commands that were not yet executed - // this will release the command memory buffers (if they are not referenced elsewhere) - while (!m_pCommandsToExecute.empty()) - { - WrappedCommand* pCommand = m_pCommandsToExecute.pop(); - pCommand->Release(); - } - - // make sure the network connection is closed - if (NULL != m_pConnection) - { - // send the disconnect message - { - CDataWriteStreamBuffer writer; - - // format messages - PackedHeader header; - header.magic = PackedHeader::kMagic; - header.msgType = PackedHeader::eCommand_Disconnect; - header.count = 0; - writer << header; - - // Send the message - IServiceNetworkMessage* pMessage = writer.BuildMessage(); - if (NULL != pMessage) - { - m_pConnection->SendMsg(pMessage); - pMessage->Release(); - } - } - - // close the connection (but try to send messages out) - m_pConnection->FlushAndClose(IServiceNetworkConnection::kDefaultFlushTime); - m_pConnection->Release(); - m_pConnection = NULL; - } -} - -const char* CRemoteCommandServer::Endpoint::GetClassName(const uint32 classId) const -{ - // class index is out of bounds - if (classId >= m_pLocalClassFactories.size()) - { - return "InvalidClassID"; - } - - // get class factory for the class ID - IRemoteCommandClass* theClass = m_pLocalClassFactories[ classId ]; - if (NULL == theClass) - { - // ID is valid but we do not support this class - // Can happen, usually due to version mismatch between client and server binaries - return "UnsupportedClassID"; - } - - return theClass->GetName(); -} - -IRemoteCommand* CRemoteCommandServer::Endpoint::CreateObject(const uint32 classId) const -{ - // class index is out of bounds - if (classId >= m_pLocalClassFactories.size()) - { - return NULL; - } - - // get class factory for given class index - IRemoteCommandClass* theClass = m_pLocalClassFactories[ classId ]; - if (NULL == theClass) - { - // ID is valid but we do not support this class - // Can happen, usually due to version mismatch between client and server binaries - return NULL; - } - - // use the class definition to create the instance of the remote command object - return theClass->CreateObject(); -} - -void CRemoteCommandServer::Endpoint::Execute() -{ - uint32 idOfLastExecutedCommand = 0; - - // Process the commands on the execution list - while (!m_pCommandsToExecute.empty()) - { - // Pop the command from the stack - WrappedCommand* pCommand = m_pCommandsToExecute.pop(); - - LOG_VERBOSE(3, "Executing command '%s', ID %d", - pCommand->GetCommand()->GetClass()->GetName(), - pCommand->GetId()); - - // Here is where the magic happens - { - pCommand->GetCommand()->Execute(); - } - - // Keep track of the command ID executed so far (so we can update the ACK later) - CRY_ASSERT(pCommand->GetId() > idOfLastExecutedCommand); - idOfLastExecutedCommand = pCommand->GetId(); - - // Command was executed, we can release it - pCommand->Release(); - } - - // Update the ACK data (if it's needed) - if (idOfLastExecutedCommand != 0) - { - CryAutoLock lock(m_accessLock); - - LOG_VERBOSE(3, "Updating LastExecutedCommandID %d->%d", - m_lastExecutedCommand, - idOfLastExecutedCommand); - - // Well, it only makes sens if the current command ID is greater that the last one executed - CRY_ASSERT(idOfLastExecutedCommand > m_lastExecutedCommand); - if (idOfLastExecutedCommand > m_lastExecutedCommand) - { - m_lastExecutedCommand = idOfLastExecutedCommand; - } - } -} - -bool CRemoteCommandServer::Endpoint::Update() -{ - // Check connection status - if (!m_pConnection->IsAlive()) - { - // Signal the owner that this endpoint should be deleted - return false; - } - - // Receive and deserialize the commands - // Note that this is done asynchronously so commands can be decoded even if the main thread is busy - // Note that execution is DEFERRED to the main thread (I wouldn't risk doing it from this thread ;-)) - bool bDisconnectReceived = false; - IServiceNetworkMessage* pMsg = m_pConnection->ReceiveMsg(); - while (NULL != pMsg && !bDisconnectReceived) - { - CDataReadStreamFormMessage reader(pMsg); - - // read back the packet header - PackedHeader packetHeader; - reader << packetHeader; - - // Is this a command system messages ? - if (packetHeader.magic == PackedHeader::kMagic) - { - switch (packetHeader.msgType) - { - // Class list, usually sent as first thing after connection - case PackedHeader::eCommand_ClassList: - { - // deserialize class names - std::vector< string > classNames; - reader << classNames; - - // sync the command ID to the current value on the client - const uint32 firstCommandID = packetHeader.count; - m_lastExecutedCommand = firstCommandID; - m_lastExecutedCommandACKed = firstCommandID; - m_lastReceivedCommand = firstCommandID; - m_lastReceivedCommandACKed = firstCommandID; - m_bHasReceivedClassList = true; - - LOG_VERBOSE(3, "Received class list packet, count=%d, first message=%d from '%s'", - classNames.size(), - packetHeader.count, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // create class mapping between remote client and this server - GetManager()->BuildClassMapping(classNames, m_pLocalClassFactories); - break; - } - - // Actual command packets - case PackedHeader::eCommand_Command: - { - LOG_VERBOSE(3, "Received packet, count=%d from '%s'", - packetHeader.count, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // load the serialized commands - const uint32 numCommands = packetHeader.count; - for (uint32 i = 0; i < numCommands; ++i) - { - // Each command is prefixed with header - CommandHeader header; - reader << header; - - // We must be able to skip to the end of the command data because sometimes - // some data can be omitted - either by dropping the command altogether or - // by faulty deserialization. Don't trust the user. - const uint32 offset = reader.GetOffset(); - const uint32 endOffset = offset + header.size; // here is where we can skip - - LOG_VERBOSE(3, "Received command ID=%d (class id=%d, size=%d) from '%s'", - header.commandId, - header.classId, - header.size, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // Do not process commands out of order. - // This should not happen if network is in good health, but we cannot assume that, never-ever. - // This code will cause our side to stop executing new commands until the remote side to resend the missing ones. - // Typically it is better than executing commands out of order. - const uint32 expectedNextCommand = m_lastReceivedCommand + 1; - if (header.commandId > expectedNextCommand) - { - LOG_VERBOSE(0, "Out of order command ID (%d > %d) received from '%s'", - header.commandId, - expectedNextCommand, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // next commands will be even older, no need to check them - break; - } - - // Do not process the old commands - // This may happen pretty often when command is resent while the ACK is "in-flight" - // Just drop the data and go on. - if (header.commandId <= m_lastReceivedCommand) - { - // getting old command is not an error, it just means that we have large enough lag - // that the client started resending old commands. - LOG_VERBOSE(1, "Old command (%d <= %d) received from '%s'", - header.commandId, - m_lastReceivedCommand, - m_pConnection->GetRemoteAddress().ToString().c_str()); - } - else - { - // next command received, we are very strict about matchig the command IDs here - CRY_ASSERT(header.commandId == expectedNextCommand); - m_lastReceivedCommand = expectedNextCommand; - - // create the command - IRemoteCommand* pCommand = CreateObject(header.classId); - if (NULL != pCommand) - { - // Fine-grain logging - LOG_VERBOSE(3, "Received command '%s', classId=%d, commandId=%d from '%s'", - pCommand->GetClass()->GetName(), - header.classId, - header.commandId, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - // Deserialize the command data from network message - pCommand->LoadFromStream(reader); - - // Add to list of commands to execute - { - m_pCommandsToExecute.push(new WrappedCommand(pCommand, header.commandId)); - } - } - else - { - LOG_VERBOSE(0, "ClassId %d not recognized. Skipping command ID%d from '%s'", - header.classId, - header.commandId, - m_pConnection->GetRemoteAddress().ToString().c_str()); - } - - // Update the last command ID - m_lastReceivedCommand = header.commandId; - } - - // Sync the message stream to popper position - CRY_ASSERT(reader.GetOffset() <= endOffset); - reader.SetPosition(endOffset); - } - - break; - } - - // request to disconnect (graceful) - case PackedHeader::eCommand_Disconnect: - { - LOG_VERBOSE(3, "Received disconnect request from '%s'", - m_pConnection->GetRemoteAddress().ToString().c_str()); - - m_pConnection->Close(); - bDisconnectReceived = true; - - break; - } - - // should not happen - default: - { - LOG_VERBOSE(0, "Invalid message type '%s' received from '%s'", - packetHeader.msgType, - m_pConnection->GetRemoteAddress().ToString().c_str()); - - break; - } - } - } - else - { - // This is a raw message, try to process immediately using async listeners. - // If it fails, add to the queue for processing on the main thread by sync listeners. - m_pServer->ProcessRawMessageAsync(pMsg, m_pConnection); - } - - // Release the message data - pMsg->Release(); - - // Get the next message from network - if (!bDisconnectReceived) - { - pMsg = m_pConnection->ReceiveMsg(); - } - } - - // The value of lastExecutedCommand can change outside this thread, - // so capture it one and keep it constant for the duration of the logic in this function. - const uint32 snapshotLastExecutedCommand = m_lastExecutedCommand; - - // Determine if we should send generate the ACK signal - if ((snapshotLastExecutedCommand != m_lastExecutedCommandACKed) || - (m_lastReceivedCommand != m_lastReceivedCommandACKed)) // this can - { - ResponseHeader header; - header.magic = PackedHeader::kMagic; - header.msgType = PackedHeader::eCommand_ACK; - header.lastCommandReceived = m_lastReceivedCommand; - header.lastCommandExecuted = snapshotLastExecutedCommand; // note that we use the captured values - - LOG_VERBOSE(3, "Sending ACK to '%s' with LastReceived=%d, LastExecuted=%d", - m_pConnection->GetRemoteAddress().ToString().c_str(), - header.lastCommandReceived, - header.lastCommandExecuted); - - // Write header into the message - CDataWriteStreamBuffer writer; - writer << header; - - // Extract the message - IServiceNetworkMessage* pMessage = writer.BuildMessage(); - if (NULL != pMessage) - { - // Send it back over the connection (works as ACK) - if (m_pConnection->SendMsg(pMessage)) - { - // Only after the message is accepted by the network we can assume that we have ACKed it properly - // This can still leave a possibility that this message gets eaten in the network but we will resend newer ACK - // soon enough that we don't need to bother with this. - m_lastExecutedCommandACKed = header.lastCommandExecuted; - m_lastReceivedCommandACKed = header.lastCommandReceived; - } - - pMessage->Release(); - } - } - - // Continue - return true; -} - -//----------------------------------------------------------------------------- - -CRemoteCommandServer::CRemoteCommandServer(CRemoteCommandManager* pManager, IServiceNetworkListener* pListener) - : m_pManager(pManager) - , m_pListener(pListener) - , m_bCloseThread(false) - , m_suppressionCounter(0) - , m_bIsSuppressed(false) -{ - // Start processing thread (receiving from network, deserialization, etc) - m_pThread = new TRemoteServerThread(); - m_pThread->Start(*this); -} - -CRemoteCommandServer::~CRemoteCommandServer() -{ - // Stop the thread, assumes that thread is responsive - if (NULL != m_pThread) - { - m_pThread->Cancel(); - m_pThread->Stop(); - m_pThread->WaitForThread(); - delete m_pThread; - } - - // Cleanup the clients endpoints - for (TEndpoints::const_iterator it = m_pEndpoints.begin(); - it != m_pEndpoints.end(); ++it) - { - delete (*it); - } - m_pEndpoints.clear(); - - // Cleanup the clients that were not yet deleted but are dead - for (TEndpoints::const_iterator it = m_pEndpointToDelete.begin(); - it != m_pEndpointToDelete.end(); ++it) - { - delete (*it); - } - m_pEndpointToDelete.clear(); - - // Cleanup the raw messages - while (!m_pRawMessages.empty()) - { - delete m_pRawMessages.pop(); - } - - // Properly close the listening socket - if (m_pListener != NULL) - { - m_pListener->Close(); - m_pListener->Release(); - m_pListener = NULL; - } -} - -void CRemoteCommandServer::ProcessRawMessageAsync(IServiceNetworkMessage* pMessage, IServiceNetworkConnection* pConnection) -{ - // we lock for the whole duration of the function - I think that's the safest. - // this function is being called from remote command server thread and even if it locks for a moment that's not a tragic situation. - CryAutoLock lock(m_rawMessagesLock); - - // Process the message using async listeners - bool bWasProcessed = false; - for (TRawMessageListenersAsync::const_iterator it = m_pRawListenersAsync.begin(); - it != m_pRawListenersAsync.end(); ++it) - { - CDataReadStreamFormMessage reader(pMessage); - CDataWriteStreamBuffer writer; - - // Request the listener to process this message - if ((*it)->OnRawMessageAsync(pConnection->GetRemoteAddress(), reader, writer)) - { - // Send response back using the source connection - if (writer.GetSize() > 0) - { - IServiceNetworkMessage* pNewMessage = writer.BuildMessage(); - if (NULL != pNewMessage) - { - pConnection->SendMsg(pNewMessage); - pNewMessage->Release(); - } - } - - // mark as processed - bWasProcessed = true; - break; - } - } - - // Stats - if (bWasProcessed) - { - LOG_VERBOSE(3, "Raw message from '%s', size %d ASYNC, PROCESSED", - pConnection->GetRemoteAddress().ToString().c_str(), - pMessage->GetSize()); - } - else - { - LOG_VERBOSE(3, "Raw message from '%s', size %d ASYNC, NOT PROCESSED", - pConnection->GetRemoteAddress().ToString().c_str(), - pMessage->GetSize()); - } - - // If we have sync listeners add the raw message for processing on the main thread - if (!bWasProcessed && !m_pRawListenersSync.empty()) - { - m_pRawMessages.push(new RawMessage(pConnection, pMessage)); - } -} - -void CRemoteCommandServer::ProcessRawMessagesSync() -{ - // get messages - TRawMessageListenersSync listeners; - { - CryAutoLock lock(m_rawMessagesLock); - listeners = m_pRawListenersSync; - } - - // process each message - while (!m_pRawMessages.empty()) - { - RawMessage* pMsg = m_pRawMessages.pop(); - - // Process messages only from alive connection (they could die before we got a chance to process the message) - if (pMsg && pMsg->m_pConnection->IsAlive()) - { - // Try to process by on of the listeners - bool bWasProcessed = false; - for (TRawMessageListenersSync::const_iterator jt = listeners.begin(); - jt != listeners.end(); ++jt) - { - CDataReadStreamFormMessage reader(pMsg->m_pMessage); - CDataWriteStreamBuffer writer; - - // Request the listener to process this message - if ((*jt)->OnRawMessageSync(pMsg->m_pConnection->GetRemoteAddress(), reader, writer)) - { - // Send response back using the source connection - if (writer.GetSize() > 0) - { - IServiceNetworkMessage* pMessage = writer.BuildMessage(); - if (NULL != pMessage) - { - pMsg->m_pConnection->SendMsg(pMessage); - pMessage->Release(); - } - } - - // mark as processed - bWasProcessed = true; - break; - } - } - - // Stats - if (bWasProcessed) - { - LOG_VERBOSE(3, "Raw message from '%s', size %d SYNC PROCESSED", - pMsg->m_pConnection->GetRemoteAddress().ToString().c_str(), - pMsg->m_pMessage->GetSize()); - } - else - { - LOG_VERBOSE(3, "Raw message from '%s', size %d SYNC NOT PROCESSED", - pMsg->m_pConnection->GetRemoteAddress().ToString().c_str(), - pMsg->m_pMessage->GetSize()); - } - } - - /// Cleanup - delete pMsg; - } -} - -void CRemoteCommandServer::Delete() -{ - delete this; -} - -void CRemoteCommandServer::FlushCommandQueue() -{ - // Always process raw messages, even if commands are suspended - ProcessRawMessagesSync(); - - // When the command server is suppressed externally, well, then don't execute any commands - // This is usually used when the main thread is doing some heavy stuff. - // TODO: Consider signaling the clients about this condition. - if (m_bIsSuppressed) - { - LOG_VERBOSE(4, "FlushCommandQueue: suppressed (counter=%d)", - m_suppressionCounter); - - return; - } - - // Update the endpoints from a copy of the list - { - CryAutoLock lock(m_accessLock); - m_pUpdateEndpoints = m_pEndpoints; - } - - // Execute the commands for each endpoint - for (TEndpoints::const_iterator it = m_pUpdateEndpoints.begin(); - it != m_pUpdateEndpoints.end(); ++it) - { - (*it)->Execute(); - } - - // Delete endpoints that were discarded within the thread (due to network errors) - // We couldn't do that there because we would need to lock to much inside the mutex (bad idea) - if (!m_pEndpointToDelete.empty()) - { - // TODO: consider using different CS for pDeletedEnpoints array - CryAutoLock lock(m_accessLock); - - // delete the endpoint structured (deferred) - for (size_t i = 0; i < m_pEndpointToDelete.size(); ++i) - { - delete m_pEndpointToDelete[i]; - } - - m_pEndpointToDelete.clear(); - } -} - -void CRemoteCommandServer::SuppressCommands() -{ - if (CryInterlockedIncrement(&m_suppressionCounter) > 0) - { - m_bIsSuppressed = true; - } -} - -void CRemoteCommandServer::ResumeCommands() -{ - if (CryInterlockedDecrement(&m_suppressionCounter) == 0) - { - m_bIsSuppressed = false; - } -} - -void CRemoteCommandServer::Run() -{ - TEndpoints updateList; - - CryThreadSetName(-1, "RemoteCommandThread"); - -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(RemoteCommandServer_cpp) -#endif - - while (!m_bCloseThread) - { - // Accept new connections - { - IServiceNetworkConnection* pNewConnection = m_pListener->Accept(); - if (NULL != pNewConnection) - { - LOG_VERBOSE(2, "New endpoint created with connection '%s'", - pNewConnection->GetRemoteAddress().ToString().c_str()); - - // Create endpoint wrapper - Endpoint* pEndPoint = new Endpoint(GetManager(), this, pNewConnection); - - // Add to endpoint list - { - CryAutoLock lock(m_accessLock); - m_pEndpoints.push_back(pEndPoint); - } - } - } - - // Get the current endpoint table (for update) - { - CryAutoLock lock(m_accessLock); - updateList = m_pEndpoints; - } - - // Update endpoints - for (TEndpoints::iterator it = updateList.begin(); - it != updateList.end(); ++it) - { - Endpoint* ep = (*it); - if (!ep->Update()) - { - LOG_VERBOSE(2, "RemoteCommand endpoint '%s' closed", - ep->GetConnection()->GetRemoteAddress().ToString().c_str()); - - // remove the endpoint from the original list - { - CryAutoLock lock(m_accessLock); - - // it's safe to remove from the endpoints list - we are iterating over a copy - m_pEndpoints.erase(std::find(m_pEndpoints.begin(), m_pEndpoints.end(), ep)); - - // don't delete the endpoint structure now (it may still be executed on main thread) - // instead add it to a list that will be processed at the end of execution so this endpoint can get deleted - m_pEndpointToDelete.push_back(ep); - } - } - } - - // Limit the CPU usage - // TODO: consider using some event based mechanism since the only source of - // work for this thread is the network we can esily be triggered by that. - Sleep(5); - } -} - -void CRemoteCommandServer::Cancel() -{ - m_bCloseThread = true; -} - -void CRemoteCommandServer::RegisterSyncMessageListener(IRemoteCommandListenerSync* pListener) -{ - CryAutoLock lock(m_rawMessagesLock); - m_pRawListenersSync.push_back(pListener); -} - -void CRemoteCommandServer::UnregisterSyncMessageListener(IRemoteCommandListenerSync* pListener) -{ - CryAutoLock lock(m_rawMessagesLock); - - TRawMessageListenersSync::iterator it = std::find(m_pRawListenersSync.begin(), m_pRawListenersSync.end(), pListener); - if (it != m_pRawListenersSync.end()) - { - m_pRawListenersSync.erase(it); - } -} - -void CRemoteCommandServer::RegisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener) -{ - CryAutoLock lock(m_rawMessagesLock); - m_pRawListenersAsync.push_back(pListener); -} - -void CRemoteCommandServer::UnregisterAsyncMessageListener(IRemoteCommandListenerAsync* pListener) -{ - CryAutoLock lock(m_rawMessagesLock); - - TRawMessageListenersAsync::iterator it = std::find(m_pRawListenersAsync.begin(), m_pRawListenersAsync.end(), pListener); - if (it != m_pRawListenersAsync.end()) - { - m_pRawListenersAsync.erase(it); - } -} - -void CRemoteCommandServer::Broadcast(IServiceNetworkMessage* pMessage) -{ - if (NULL != pMessage && pMessage->GetSize() > 0) - { - CryAutoLock lock(m_rawMessagesLock); - for (TEndpoints::const_iterator jt = m_pEndpoints.begin(); - jt != m_pEndpoints.end(); ++jt) - { - Endpoint* pEndpoint = (*jt); - if (pEndpoint->HasReceivedClassList()) - { - IServiceNetworkConnection* pConnection = pEndpoint->GetConnection(); - if (NULL != pConnection) - { - pConnection->SendMsg(pMessage); - } - } - } - } -} - -bool CRemoteCommandServer::HasConnectedClients() const -{ - CryAutoLock lock(m_rawMessagesLock); - - for (TEndpoints::const_iterator jt = m_pEndpoints.begin(); - jt != m_pEndpoints.end(); ++jt) - { - Endpoint* pEndpoint = (*jt); - if (pEndpoint->HasReceivedClassList()) - { - IServiceNetworkConnection* pConnection = pEndpoint->GetConnection(); - if (pConnection->IsAlive()) - { - return true; - } - } - } - - return false; -} - -//----------------------------------------------------------------------------- - -// Do not remove (can mess up the uber file builds) -#undef LOG_VERBOSE - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/Serialization/ArchiveHost.cpp b/Code/CryEngine/CrySystem/Serialization/ArchiveHost.cpp deleted file mode 100644 index f7ed4ae46c..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/ArchiveHost.cpp +++ /dev/null @@ -1,239 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include -#include "JSONIArchive.h" -#include "JSONOArchive.h" -#include "BinArchive.h" -#include "XmlIArchive.h" -#include "XmlOArchive.h" -#include - -namespace Serialization -{ - bool LoadFile(std::vector& content, const char* filename) - { - AZ::IO::HandleType fileHandle = gEnv->pCryPak->FOpen(filename, "rb"); - if (!fileHandle) - { - return false; - } - - gEnv->pCryPak->FSeek(fileHandle, 0, SEEK_END); - size_t size = gEnv->pCryPak->FTell(fileHandle); - gEnv->pCryPak->FSeek(fileHandle, 0, SEEK_SET); - - content.resize(size); - bool result = true; - if (size != 0) - { - result = gEnv->pCryPak->FRead(&content[0], size, fileHandle) == size; - } - gEnv->pCryPak->FClose(fileHandle); - return result; - } - - class CArchiveHost - : public IArchiveHost - { - public: - bool LoadJsonFile(const SStruct& obj, const char* filename) override - { - std::vector content; - if (!LoadFile(content, filename)) - { - return false; - } - JSONIArchive ia; - if (!ia.open(content.data(), content.size())) - { - return false; - } - return ia(obj); - } - - bool SaveJsonFile(const char* gameFilename, const SStruct& obj) override - { - char buffer[AZ::IO::IArchive::MaxPath]; - const char* filename = gEnv->pCryPak->AdjustFileName(gameFilename, buffer, AZ_ARRAY_SIZE(buffer), AZ::IO::IArchive::FLAGS_FOR_WRITING); - JSONOArchive oa; - if (!oa(obj)) - { - return false; - } - return oa.save(filename); - } - - bool LoadJsonBuffer(const SStruct& obj, const char* buffer, size_t bufferLength) override - { - if (bufferLength == 0) - { - return false; - } - JSONIArchive ia; - if (!ia.open(buffer, bufferLength)) - { - return false; - } - return ia(obj); - } - - bool SaveJsonBuffer(DynArray& buffer, const SStruct& obj) override - { - JSONOArchive oa; - if (!oa(obj)) - { - return false; - } - buffer.assign(oa.buffer(), oa.buffer() + oa.length()); - return true; - } - - - bool LoadBinaryFile(const SStruct& obj, const char* filename) override - { - std::vector content; - if (!LoadFile(content, filename)) - { - return false; - } - BinIArchive ia; - if (!ia.open(content.data(), content.size())) - { - return false; - } - return ia(obj); - } - - bool SaveBinaryFile(const char* gameFilename, const SStruct& obj) override - { - char buffer[AZ::IO::IArchive::MaxPath]; - const char* filename = gEnv->pCryPak->AdjustFileName(gameFilename, buffer, AZ_ARRAY_SIZE(buffer), AZ::IO::IArchive::FLAGS_FOR_WRITING); - BinOArchive oa; - obj(oa); - return oa.save(filename); - } - - bool LoadBinaryBuffer(const SStruct& obj, const char* buffer, size_t bufferLength) override - { - if (bufferLength == 0) - { - return false; - } - BinIArchive ia; - if (!ia.open(buffer, bufferLength)) - { - return false; - } - return ia(obj); - } - - bool SaveBinaryBuffer(DynArray& buffer, const SStruct& obj) override - { - BinOArchive oa; - obj(oa); - buffer.assign(oa.buffer(), oa.buffer() + oa.length()); - return true; - } - - bool CloneBinary(const SStruct& dest, const SStruct& src) override - { - BinOArchive oa; - src(oa); - BinIArchive ia; - if (!ia.open(oa.buffer(), oa.length())) - { - return false; - } - dest(ia); - return true; - } - - bool CompareBinary(const SStruct& lhs, const SStruct& rhs) override - { - BinOArchive oa1; - lhs(oa1); - BinOArchive oa2; - rhs(oa2); - if (oa1.length() != oa2.length()) - { - return false; - } - return memcmp(oa1.buffer(), oa2.buffer(), oa1.length()) == 0; - } - - bool SaveXmlFile(const char* filename, const SStruct& obj, const char* rootNodeName) override - { - XmlNodeRef node = SaveXmlNode(obj, rootNodeName); - if (!node) - { - return false; - } - return node->saveToFile(filename); - } - - bool LoadXmlFile(const SStruct& obj, const char* filename) override - { - XmlNodeRef node = gEnv->pSystem->LoadXmlFromFile(filename); - if (!node) - { - return false; - } - return LoadXmlNode(obj, node); - } - - XmlNodeRef SaveXmlNode(const SStruct& obj, const char* nodeName) override - { - CXmlOArchive oa; - XmlNodeRef node = gEnv->pSystem->CreateXmlNode(nodeName); - if (!node) - { - return XmlNodeRef(); - } - oa.SetXmlNode(node); - if (!obj(oa)) - { - return XmlNodeRef(); - } - return oa.GetXmlNode(); - } - - bool SaveXmlNode(XmlNodeRef& node, const SStruct& obj) override - { - if (!node) - { - return false; - } - CXmlOArchive oa; - oa.SetXmlNode(node); - return obj(oa); - } - - bool LoadXmlNode(const SStruct& obj, const XmlNodeRef& node) override - { - CXmlIArchive ia; - ia.SetXmlNode(node); - if (!obj(ia)) - { - return false; - } - return true; - } - }; - - IArchiveHost* CreateArchiveHost() - { - return new CArchiveHost; - } -} diff --git a/Code/CryEngine/CrySystem/Serialization/ArchiveHost.h b/Code/CryEngine/CrySystem/Serialization/ArchiveHost.h deleted file mode 100644 index 360dded0c7..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/ArchiveHost.h +++ /dev/null @@ -1,21 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include - -namespace Serialization -{ - IArchiveHost* CreateArchiveHost(); -} diff --git a/Code/CryEngine/CrySystem/Serialization/BinArchive.cpp b/Code/CryEngine/CrySystem/Serialization/BinArchive.cpp deleted file mode 100644 index f16c15cc96..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/BinArchive.cpp +++ /dev/null @@ -1,839 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "BinArchive.h" -#include -#include "Serialization/ClassFactory.h" - -namespace Serialization { - static const unsigned char SIZE16 = 254; - static const unsigned char SIZE32 = 255; - - static const unsigned int BIN_MAGIC = 0xb1a4c17f; - - //#ifdef _DEBUG - //typedef std::map HashMap; - //static HashMap hashMap; - //#endif - - BinOArchive::BinOArchive() - : IArchive(OUTPUT | BINARY) - { - clear(); - } - - void BinOArchive::clear() - { - stream_.clear(); - stream_.write((const char*)&BIN_MAGIC, sizeof(BIN_MAGIC)); - } - - size_t BinOArchive::length() const - { - return stream_.position(); - } - - bool BinOArchive::save(const char* filename) - { - FILE* f = nullptr; - azfopen(&f, filename, "wb"); - if (!f) - { - return false; - } - - if (fwrite(buffer(), 1, length(), f) != length()) - { - fclose(f); - return false; - } - - fclose(f); - return true; - } - - inline void BinOArchive::openNode(const char* name, bool size8) - { - if (!strlen(name)) - { - return; - } - - unsigned short hash = calcHash(name); - stream_.write(hash); - - blockSizeOffsets_.push_back(int(stream_.position())); - stream_.write((unsigned char)0); - if (!size8) - { - stream_.write((unsigned short)0); - } - -#ifdef _DEBUG - // HashMap::iterator i = hashMap.find(hash); - // if(i != hashMap.end() && i->second != name) - // ASSERT_STR(0, name); - // hashMap[hash] = name; -#endif - } - - inline void BinOArchive::closeNode(const char* name, bool size8) - { - if (!strlen(name)) - { - return; - } - - unsigned int offset = blockSizeOffsets_.back(); - unsigned int size = (unsigned int)(stream_.position() - offset - sizeof(unsigned char) - (size8 ? 0 : sizeof(unsigned short))); - blockSizeOffsets_.pop_back(); - unsigned char* sizePtr = (unsigned char*)(stream_.buffer() + offset); - - if (size < SIZE16) - { - *sizePtr = size; - if (!size8) - { - unsigned char* buffer = sizePtr + 3; - memmove(buffer - 2, buffer, size); - stream_.setPosition(stream_.position() - 2); - } - } - else - { - YASLI_ASSERT(!size8); - if (size < 0x10000) - { - *sizePtr = SIZE16; - *((unsigned short*)(sizePtr + 1)) = size; - } - else - { - unsigned char* buffer = sizePtr + 3; - stream_.write((unsigned short)0); - *sizePtr = SIZE32; - memmove(buffer + 2, buffer, size); - *((unsigned int*)(sizePtr + 1)) = size; - } - } - } - - bool BinOArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - bool size8 = strlen(value.get()) + 1 < SIZE16; - openNode(name, size8); - stream_ << value.get(); - stream_.write(char(0)); - closeNode(name, size8); - return true; - } - - bool BinOArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - bool size8 = (wcslen(value.get()) + 1) * 2 < SIZE16; - openNode(name, size8); - stream_ << value.get(); - stream_.write(short(0)); - closeNode(name, size8); - return true; - } - - bool BinOArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - ser(*this); - closeNode(name, false); - return true; - } - - bool BinOArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - - unsigned int size = (unsigned int)ser.size(); - if (size < SIZE16) - { - stream_.write((unsigned char)size); - } - else if (size < 0x10000) - { - stream_.write(SIZE16); - stream_.write((unsigned short)size); - } - else - { - stream_.write(SIZE32); - stream_.write(size); - } - - if (strlen(name)) - { - if (size > 0) - { - int i = 0; - do - { - char elementName[16]; - azitoa(i++, elementName, AZ_ARRAY_SIZE(elementName), 10); - ser(*this, elementName, ""); - } while (ser.next()); - } - - closeNode(name, false); - } - else - { - if (size > 0) - { - do - { - ser(*this, "", ""); - } - while (ser.next()); - } - } - - return true; - } - - bool BinOArchive::operator()(IPointer& ptr, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - - const char* typeName = ptr.registeredTypeName(); - if (!typeName) - { - typeName = ""; - } - if (typeName[0] == '\0' && ptr.get()) - { - CRY_ASSERT_MESSAGE(0, "Writing unregistered class. Use SERIALIZATION_CLASS_NAME macro for registration."); - } - - TypeID baseType = ptr.baseType(); - - if (ptr.get()) - { - stream_ << typeName; - stream_.write(char(0)); - ptr.serializer()(*this); - } - else - { - stream_.write(char(0)); - } - - closeNode(name, false); - return true; - } - - ////////////////////////////////////////////////////////////////////////// - - BinIArchive::BinIArchive() - : IArchive(INPUT | BINARY) - , loadedData_(0) - { - } - - BinIArchive::~BinIArchive() - { - close(); - } - - bool BinIArchive::load(const char* filename) - { - close(); - - FILE* f = nullptr; - azfopen(&f, filename, "rb"); - - if (!f) - { - return false; - } - fseek(f, 0, SEEK_END); - size_t length = ftell(f); - fseek(f, 0, SEEK_SET); - if (length == 0) - { - fclose(f); - return false; - } - loadedData_ = new char[length]; - if (fread((void*)loadedData_, 1, length, f) != length || !open(loadedData_, length)) - { - close(); - fclose(f); - return false; - } - fclose(f); - return true; - } - - bool BinIArchive::open(const char* buffer, size_t size) - { - if (size < sizeof(int)) - { - return false; - } - if (*(unsigned*)(buffer) != BIN_MAGIC) - { - return false; - } - buffer += sizeof(unsigned int); - size -= sizeof(unsigned int); - - blocks_.push_back(Block(buffer, (unsigned int)size)); - return true; - } - - void BinIArchive::close() - { - if (loadedData_) - { - delete[] loadedData_; - } - loadedData_ = 0; - } - - bool BinIArchive::openNode(const char* name) - { - Block block(0, 0); - if (currentBlock().get(name, block)) - { - blocks_.push_back(block); - return true; - } - return false; - } - - void BinIArchive::closeNode([[maybe_unused]] const char* name, [[maybe_unused]] bool check) - { - YASLI_ASSERT(!check || currentBlock().validToClose()); - blocks_.pop_back(); - } - - bool BinIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - string str; - read(str); - value.set(str.c_str()); - return true; - } - - if (!openNode(name)) - { - return false; - } - - string str; - read(str); - value.set(str.c_str()); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - wstring str; - read(str); - value.set(str.c_str()); - return true; - } - - if (!openNode(name)) - { - return false; - } - - wstring str; - read(str); - value.set(str.c_str()); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - - bool BinIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - ser(*this); - return true; - } - - if (!openNode(name)) - { - return false; - } - - ser(*this); - closeNode(name, false); - return true; - } - - bool BinIArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (strlen(name)) - { - if (!openNode(name)) - { - return false; - } - - size_t size = currentBlock().readPackedSize(); - ser.resize(size); - - if (size > 0) - { - int i = 0; - do - { - char elementName[16]; - azitoa(i++, elementName, AZ_ARRAY_SIZE(elementName), 10); - ser(*this, elementName, ""); - } - while (ser.next()); - } - closeNode(name); - return true; - } - else - { - size_t size = currentBlock().readPackedSize(); - ser.resize(size); - if (size > 0) - { - do - { - ser(*this, "", ""); - } - while (ser.next()); - } - return true; - } - } - - bool BinIArchive::operator()(IPointer& ptr, const char* name, [[maybe_unused]] const char* label) - { - if (strlen(name) && !openNode(name)) - { - return false; - } - - string typeName; - read(typeName); - if (ptr.get() && (typeName.empty() || strcmp(typeName.c_str(), ptr.registeredTypeName()) != 0)) - { - ptr.create(""); // 0 - } - if (!typeName.empty() && !ptr.get()) - { - ptr.create(typeName.c_str()); - } - - if (SStruct ser = ptr.serializer()) - { - ser(*this); - } - - if (strlen(name)) - { - closeNode(name); - } - return true; - } - - unsigned int BinIArchive::Block::readPackedSize() - { - unsigned char size8; - read(size8); - if (size8 < SIZE16) - { - return size8; - } - if (size8 == SIZE16) - { - unsigned short size16; - read(size16); - return size16; - } - unsigned int size32; - read(size32); - return size32; - } - - bool BinIArchive::Block::get(const char* name, Block& block) - { - if (begin_ == end_) - { - return false; - } - complex_ = true; - unsigned short hashName = calcHash(name); - const char* currInitial = curr_; - bool restarted = false; - for (;; ) - { - if (curr_ >= end_) - { - return false; - } - - unsigned short hash; - read(hash); - unsigned int size = readPackedSize(); - - const char* currPrev = curr_; - if ((curr_ += size) == end_) - { - if (restarted) - { - return false; - } - curr_ = begin_; - restarted = true; - } - - //ASSERT(curr_ < end_); - - if (hash == hashName) - { - block = Block(currPrev, size); - return true; - } - - if (curr_ == currInitial) - { - return false; - } - } - } -} diff --git a/Code/CryEngine/CrySystem/Serialization/BinArchive.h b/Code/CryEngine/CrySystem/Serialization/BinArchive.h deleted file mode 100644 index 2d7daba899..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/BinArchive.h +++ /dev/null @@ -1,180 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -// For tags 16-bit xor-hash is used, with check for uniquness in debug -// Block size is automatic: 8, 16 or 32 bits - -#include "Serialization/IArchive.h" -#include "MemoryWriter.h" - -namespace Serialization { - inline unsigned short calcHash(const char* str) - { - unsigned short hash = 0; - const unsigned short* p = (const unsigned short*)(str); - for (;; ) - { - unsigned short w = *p++; - if (!(w & 0xff)) - { - break; - } - hash ^= w; - if (!(w & 0xff00)) - { - break; - } - } - return hash; - } - - class BinOArchive - : public IArchive - { - public: - - BinOArchive(); - ~BinOArchive() {} - - void clear(); - size_t length() const; - const char* buffer() const { return stream_.buffer(); } - bool save(const char* fileName); - - bool operator()(bool& value, const char* name, const char* label); - bool operator()(IString& value, const char* name, const char* label); - bool operator()(IWString& value, const char* name, const char* label); - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(int8& value, const char* name, const char* label); - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - bool operator()(const SStruct& ser, const char* name, const char* label); - bool operator()(IContainer& ser, const char* name, const char* label); - bool operator()(IPointer& ptr, const char* name, const char* label); - - using IArchive::operator(); - - private: - void openContainer(const char* name, int size, const char* typeName); - void openNode(const char* name, bool size8 = true); - void closeNode(const char* name, bool size8 = true); - - std::vector blockSizeOffsets_; - MemoryWriter stream_; - }; - - ////////////////////////////////////////////////////////////////////////// - - class BinIArchive - : public IArchive - { - public: - - BinIArchive(); - ~BinIArchive(); - - bool load(const char* fileName); - bool open(const char* buffer, size_t length); // doesn't copy the buffer - bool open(const BinOArchive& ar) { return open(ar.buffer(), ar.length()); } - void close(); - - bool operator()(bool& value, const char* name, const char* label); - bool operator()(IString& value, const char* name, const char* label); - bool operator()(IWString& value, const char* name, const char* label); - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(int8& value, const char* name, const char* label); - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - bool operator()(const SStruct& ser, const char* name, const char* label); - bool operator()(IContainer& ser, const char* name, const char* label); - bool operator()(IPointer& ptr, const char* name, const char* label); - - using IArchive::operator(); - - private: - class Block - { - public: - Block(const char* data, int size) - : begin_(data) - , end_(data + size) - , curr_(data) - , complex_(false) {} - - bool get(const char* name, Block& block); - - void read(void* data, int size) - { - YASLI_ASSERT(curr_ + size <= end_); - memcpy(data, curr_, size); - curr_ += size; - } - - template - void read(T& x){ read(&x, sizeof(x)); } - - void read(string& s) - { - YASLI_ASSERT(curr_ + strlen(curr_) < end_); - s = curr_; - curr_ += strlen(curr_) + 1; - } - void read(wstring& s) - { - YASLI_ASSERT(curr_ + sizeof(wchar_t) * wcslen((wchar_t*)curr_) < end_); - s = (wchar_t*)curr_; - curr_ += (wcslen((wchar_t*)curr_) + 1) * sizeof(wchar_t); - } - - unsigned int readPackedSize(); - - bool validToClose() const { return complex_ || curr_ == end_; } - - private: - const char* begin_; - const char* end_; - const char* curr_; - bool complex_; - }; - - typedef std::vector Blocks; - Blocks blocks_; - const char* loadedData_; - - bool openNode(const char* name); - void closeNode(const char* name, bool check = true); - Block& currentBlock() { return blocks_.back(); } - template - void read(T& t) { currentBlock().read(t); } - }; -} diff --git a/Code/CryEngine/CrySystem/Serialization/JSONIArchive.cpp b/Code/CryEngine/CrySystem/Serialization/JSONIArchive.cpp deleted file mode 100644 index 8e323cc44c..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/JSONIArchive.cpp +++ /dev/null @@ -1,1525 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include -#include -#include -#include "Serialization/ClassFactory.h" -#include "Serialization/STL.h" -#include "JSONIArchive.h" -#include "Serialization/BlackBox.h" -#include "MemoryReader.h" -#include "MemoryWriter.h" - -#if 0 -# define DEBUG_TRACE(fmt, ...) printf(fmt "\n", __VA_ARGS__) -# define DEBUG_TRACE_TOKENIZER(fmt, ...) printf(fmt "\n", __VA_ARGS__) -#else -# define DEBUG_TRACE(...) -# define DEBUG_TRACE_TOKENIZER(...) -#endif - -namespace Serialization { - static char hexValueTable[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, - - 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - static void unescapeString(std::vector& buf, string& out, const char* begin, const char* end) - { - if (begin >= end) - { - out.clear(); - return; - } - // TODO: use stack string - buf.resize(end - begin); - char* ptr = &buf[0]; - while (begin != end) - { - if (*begin != '\\') - { - *ptr = *begin; - ++ptr; - } - else - { - ++begin; - if (begin == end) - { - break; - } - - switch (*begin) - { - case '0': - *ptr = '\0'; - ++ptr; - break; - case 't': - *ptr = '\t'; - ++ptr; - break; - case 'n': - *ptr = '\n'; - ++ptr; - break; - case 'r': - *ptr = '\r'; - ++ptr; - break; - case '\\': - *ptr = '\\'; - ++ptr; - break; - case '\"': - *ptr = '\"'; - ++ptr; - break; - case '\'': - *ptr = '\''; - ++ptr; - break; - case 'x': - if (begin + 2 < end) - { - *ptr = (hexValueTable[int(begin[1])] << 4) + hexValueTable[int(begin[2])]; - ++ptr; - begin += 2; - break; - } - default: - *ptr = *begin; - ++ptr; - break; - } - } - ++begin; - } - buf.resize(ptr - &buf[0]); - if (!buf.empty()) - { - out.assign(&buf[0], &buf[0] + buf.size()); - } - else - { - out.clear(); - } - } - - // --------------------------------------------------------------------------- - - class JSONTokenizer - { - public: - JSONTokenizer(); - - Token operator()(const char* text) const; - private: - inline bool isSpace(char c) const; - inline bool isWordPart(unsigned char c) const; - inline bool isComment(char c) const; - inline bool isQuoteOpen(int& quoteIndex, char c) const; - inline bool isQuoteClose(int quoteIndex, char c) const; - inline bool isQuote(char c) const; - }; - - JSONTokenizer::JSONTokenizer() - { - } - - inline bool JSONTokenizer::isSpace(char c) const - { - return c == ' ' || c == '\t' || c == '\n' || c == '\r'; - } - - inline bool JSONTokenizer::isComment(char c) const - { - return c == '#'; - } - - - inline bool JSONTokenizer::isQuote(char c) const - { - return c == '\"'; - } - - static const char charTypes[256] = { - 0 /* 0x00: */, - 0 /* 0x01: */, - 0 /* 0x02: */, - 0 /* 0x03: */, - 0 /* 0x04: */, - 0 /* 0x05: */, - 0 /* 0x06: */, - 0 /* 0x07: */, - 0 /* 0x08: */, - 0 /* 0x09: \t */, - 0 /* 0x0A: \n */, - 0 /* 0x0B: */, - 0 /* 0x0C: */, - 0 /* 0x0D: */, - 0 /* 0x0E: */, - 0 /* 0x0F: */, - - - 0 /* 0x10: */, - 0 /* 0x11: */, - 0 /* 0x12: */, - 0 /* 0x13: */, - 0 /* 0x14: */, - 0 /* 0x15: */, - 0 /* 0x16: */, - 0 /* 0x17: */, - 0 /* 0x18: */, - 0 /* 0x19: */, - 0 /* 0x1A: */, - 0 /* 0x1B: */, - 0 /* 0x1C: */, - 0 /* 0x1D: */, - 0 /* 0x1E: */, - 0 /* 0x1F: */, - - - 0 /* 0x20: */, - 0 /* 0x21: ! */, - 0 /* 0x22: " */, - 0 /* 0x23: # */, - 0 /* 0x24: $ */, - 0 /* 0x25: % */, - 0 /* 0x26: & */, - 0 /* 0x27: ' */, - 0 /* 0x28: ( */, - 0 /* 0x29: ) */, - 0 /* 0x2A: * */, - 0 /* 0x2B: + */, - 0 /* 0x2C: , */, - 1 /* 0x2D: - */, - 1 /* 0x2E: . */, - 0 /* 0x2F: / */, - - - 1 /* 0x30: 0 */, - 1 /* 0x31: 1 */, - 1 /* 0x32: 2 */, - 1 /* 0x33: 3 */, - 1 /* 0x34: 4 */, - 1 /* 0x35: 5 */, - 1 /* 0x36: 6 */, - 1 /* 0x37: 7 */, - 1 /* 0x38: 8 */, - 1 /* 0x39: 9 */, - 0 /* 0x3A: : */, - 0 /* 0x3B: ; */, - 0 /* 0x3C: < */, - 0 /* 0x3D: = */, - 0 /* 0x3E: > */, - 0 /* 0x3F: ? */, - - - 0 /* 0x40: @ */, - 1 /* 0x41: A */, - 1 /* 0x42: B */, - 1 /* 0x43: C */, - 1 /* 0x44: D */, - 1 /* 0x45: E */, - 1 /* 0x46: F */, - 1 /* 0x47: G */, - 1 /* 0x48: H */, - 1 /* 0x49: I */, - 1 /* 0x4A: J */, - 1 /* 0x4B: K */, - 1 /* 0x4C: L */, - 1 /* 0x4D: M */, - 1 /* 0x4E: N */, - 1 /* 0x4F: O */, - - - 1 /* 0x50: P */, - 1 /* 0x51: Q */, - 1 /* 0x52: R */, - 1 /* 0x53: S */, - 1 /* 0x54: T */, - 1 /* 0x55: U */, - 1 /* 0x56: V */, - 1 /* 0x57: W */, - 1 /* 0x58: X */, - 1 /* 0x59: Y */, - 1 /* 0x5A: Z */, - 0 /* 0x5B: [ */, - 0 /* 0x5C: \ */, - 0 /* 0x5D: ] */, - 0 /* 0x5E: ^ */, - 1 /* 0x5F: _ */, - - - 0 /* 0x60: ` */, - 1 /* 0x61: a */, - 1 /* 0x62: b */, - 1 /* 0x63: c */, - 1 /* 0x64: d */, - 1 /* 0x65: e */, - 1 /* 0x66: f */, - 1 /* 0x67: g */, - 1 /* 0x68: h */, - 1 /* 0x69: i */, - 1 /* 0x6A: j */, - 1 /* 0x6B: k */, - 1 /* 0x6C: l */, - 1 /* 0x6D: m */, - 1 /* 0x6E: n */, - 1 /* 0x6F: o */, - - - 1 /* 0x70: p */, - 1 /* 0x71: q */, - 1 /* 0x72: r */, - 1 /* 0x73: s */, - 1 /* 0x74: t */, - 1 /* 0x75: u */, - 1 /* 0x76: v */, - 1 /* 0x77: w */, - 1 /* 0x78: x */, - 1 /* 0x79: y */, - 1 /* 0x7A: z */, - 0 /* 0x7B: { */, - 0 /* 0x7C: | */, - 0 /* 0x7D: } */, - 0 /* 0x7E: ~ */, - 0 /* 0x7F: */, - - - 0 /* 0x80: */, - 0 /* 0x81: */, - 0 /* 0x82: */, - 0 /* 0x83: */, - 0 /* 0x84: */, - 0 /* 0x85: */, - 0 /* 0x86: */, - 0 /* 0x87: */, - 0 /* 0x88: */, - 0 /* 0x89: */, - 0 /* 0x8A: */, - 0 /* 0x8B: */, - 0 /* 0x8C: */, - 0 /* 0x8D: */, - 0 /* 0x8E: */, - 0 /* 0x8F: */, - - - 0 /* 0x90: */, - 0 /* 0x91: */, - 0 /* 0x92: */, - 0 /* 0x93: */, - 0 /* 0x94: */, - 0 /* 0x95: */, - 0 /* 0x96: */, - 0 /* 0x97: */, - 0 /* 0x98: */, - 0 /* 0x99: */, - 0 /* 0x9A: */, - 0 /* 0x9B: */, - 0 /* 0x9C: */, - 0 /* 0x9D: */, - 0 /* 0x9E: */, - 0 /* 0x9F: */, - - - 0 /* 0xA0: */, - 0 /* 0xA1: */, - 0 /* 0xA2: */, - 0 /* 0xA3: */, - 0 /* 0xA4: */, - 0 /* 0xA5: */, - 0 /* 0xA6: */, - 0 /* 0xA7: */, - 0 /* 0xA8: */, - 0 /* 0xA9: */, - 0 /* 0xAA: */, - 0 /* 0xAB: */, - 0 /* 0xAC: */, - 0 /* 0xAD: */, - 0 /* 0xAE: */, - 0 /* 0xAF: */, - - - 0 /* 0xB0: */, - 0 /* 0xB1: */, - 0 /* 0xB2: */, - 0 /* 0xB3: */, - 0 /* 0xB4: */, - 0 /* 0xB5: */, - 0 /* 0xB6: */, - 0 /* 0xB7: */, - 0 /* 0xB8: */, - 0 /* 0xB9: */, - 0 /* 0xBA: */, - 0 /* 0xBB: */, - 0 /* 0xBC: */, - 0 /* 0xBD: */, - 0 /* 0xBE: */, - 0 /* 0xBF: */, - - - 0 /* 0xC0: */, - 0 /* 0xC1: */, - 0 /* 0xC2: */, - 0 /* 0xC3: */, - 0 /* 0xC4: */, - 0 /* 0xC5: */, - 0 /* 0xC6: */, - 0 /* 0xC7: */, - 0 /* 0xC8: */, - 0 /* 0xC9: */, - 0 /* 0xCA: */, - 0 /* 0xCB: */, - 0 /* 0xCC: */, - 0 /* 0xCD: */, - 0 /* 0xCE: */, - 0 /* 0xCF: */, - - - 0 /* 0xD0: */, - 0 /* 0xD1: */, - 0 /* 0xD2: */, - 0 /* 0xD3: */, - 0 /* 0xD4: */, - 0 /* 0xD5: */, - 0 /* 0xD6: */, - 0 /* 0xD7: */, - 0 /* 0xD8: */, - 0 /* 0xD9: */, - 0 /* 0xDA: */, - 0 /* 0xDB: */, - 0 /* 0xDC: */, - 0 /* 0xDD: */, - 0 /* 0xDE: */, - 0 /* 0xDF: */, - - - 0 /* 0xE0: */, - 0 /* 0xE1: */, - 0 /* 0xE2: */, - 0 /* 0xE3: */, - 0 /* 0xE4: */, - 0 /* 0xE5: */, - 0 /* 0xE6: */, - 0 /* 0xE7: */, - 0 /* 0xE8: */, - 0 /* 0xE9: */, - 0 /* 0xEA: */, - 0 /* 0xEB: */, - 0 /* 0xEC: */, - 0 /* 0xED: */, - 0 /* 0xEE: */, - 0 /* 0xEF: */, - - - 0 /* 0xF0: */, - 0 /* 0xF1: */, - 0 /* 0xF2: */, - 0 /* 0xF3: */, - 0 /* 0xF4: */, - 0 /* 0xF5: */, - 0 /* 0xF6: */, - 0 /* 0xF7: */, - 0 /* 0xF8: */, - 0 /* 0xF9: */, - 0 /* 0xFA: */, - 0 /* 0xFB: */, - 0 /* 0xFC: */, - 0 /* 0xFD: */, - 0 /* 0xFE: */, - 0 /* 0xFF: */ - }; - - inline bool JSONTokenizer::isWordPart(unsigned char c) const - { - return charTypes[c] != 0; - } - - Token JSONTokenizer::operator()(const char* ptr) const - { - while (isSpace(*ptr)) - { - ++ptr; - } - Token cur(ptr, ptr); - while (!cur && *ptr != '\0') - { - while (isComment(*cur.end)) - { -#if 0 - const char* commentStart = ptr; -#endif - while (*cur.end && *cur.end != '\n') - { - ++cur.end; - } - while (isSpace(*cur.end)) - { - ++cur.end; - } - DEBUG_TRACE_TOKENIZER("Got comment: '%s'", string(commentStart, cur.end).c_str()); - cur.start = cur.end; - } - CRY_ASSERT(!isSpace(*cur.end)); - if (isQuote(*cur.end)) - { - ++cur.end; - while (*cur.end) - { - if (*cur.end == '\\') - { - ++cur.end; - if (*cur.end) - { - if (*cur.end != 'x' && *cur.end != 'X') - { - ++cur.end; - } - else - { - ++cur.end; - if (*cur.end) - { - ++cur.end; - } - } - } - } - if (isQuote(*cur.end)) - { - ++cur.end; - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - else - { - ++cur.end; - } - } - } - else - { - if (!*cur.end) - { - return cur; - } - - DEBUG_TRACE_TOKENIZER("%c", *cur.end); - if (isWordPart(*cur.end)) - { - do - { - ++cur.end; - } while (isWordPart(*cur.end) != 0); - } - else - { - ++cur.end; - return cur; - } - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - } - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - - - // --------------------------------------------------------------------------- - - JSONIArchive::JSONIArchive() - : IArchive(INPUT | TEXT) - , buffer_(0) - { - } - - JSONIArchive::~JSONIArchive() - { - if (buffer_) - { - free(buffer_); - buffer_ = 0; - } - stack_.clear(); - reader_.reset(); - } - - bool JSONIArchive::open(const char* buffer, size_t length, bool free) - { - if (!length) - { - return false; - } - - if (buffer) - { - reader_.reset(new MemoryReader(buffer, length, free)); - } - buffer_ = 0; - - token_ = Token(reader_->begin(), reader_->begin()); - stack_.clear(); - - stack_.push_back(Level()); - readToken(); - putToken(); - stack_.back().start = token_.end; - return true; - } - - - bool JSONIArchive::load(const char* filename) - { - FILE* file = nullptr; - azfopen(&file, filename, "rb"); - if (file) - { - fseek(file, 0, SEEK_END); - long fileSize = ftell(file); - fseek(file, 0, SEEK_SET); - - void* buffer = 0; - if (fileSize > 0) - { - buffer = CryModuleMalloc(fileSize + 1); - CRY_ASSERT(buffer != 0); - memset(buffer, 0, fileSize + 1); - size_t elementsRead = fread(buffer, fileSize, 1, file); - CRY_ASSERT(((char*)(buffer))[fileSize] == '\0'); - if (elementsRead != 1) - { - CryModuleFree(buffer); - return false; - } - } - fclose(file); - - filename_ = filename; - buffer_ = buffer; - if (fileSize > 0) - { - return open((char*)buffer, fileSize, false); - } - else - { - return false; - } - } - else - { - return false; - } - } - - void JSONIArchive::readToken() - { - JSONTokenizer tokenizer; - token_ = tokenizer(token_.end); - DEBUG_TRACE(" ~ read token '%s' at %i", token_.str().c_str(), token_.start - reader_->begin()); - } - - void JSONIArchive::putToken() - { - DEBUG_TRACE(" putToken: '%s'", token_.str().c_str()); - token_ = Token(token_.start, token_.start); - } - - int JSONIArchive::line(const char* position) const - { - return int(std::count(reader_->begin(), position, '\n') + 1); - } - - bool JSONIArchive::isName(Token token) const - { - if (!token) - { - return false; - } - char firstChar = token.start[0]; - if (firstChar == '"') - { - return true; - } - return false; - } - - - bool JSONIArchive::expect(char token) - { - if (token_ != token) - { - const char* lineEnd = token_.start; - while (lineEnd && *lineEnd != '\0' && *lineEnd != '\r' && *lineEnd != '\n') - { - ++lineEnd; - } - - MemoryWriter msg; - msg << "Error parsing file, expected ':' at line " << line(token_.start) << ":\n" - << string(token_.start, lineEnd).c_str(); - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - return true; - } - - void JSONIArchive::skipBlock() - { - DEBUG_TRACE("Skipping block from %i ...", token_.end - reader_->begin()); - if (openBracket() || openContainerBracket()) - { - closeBracket(); // Skipping entire block - } - else - { - readToken(); // Skipping value - } - readToken(); - if (token_ != ',') - { - putToken(); - } - DEBUG_TRACE(" ...till %i", token_.end - reader_->begin()); - } - - bool JSONIArchive::findName(const char* name, Token* outName) - { - DEBUG_TRACE(" * finding name '%s'", name); - DEBUG_TRACE(" started at byte %i", int(token_.start - reader_->begin())); - if (stack_.empty()) - { - // TODO: diagnose - return false; - } - if (stack_.back().isKeyValue) - { - return true; - } - const char* start = 0; - const char* blockBegin = stack_.back().start; - if (*blockBegin == '\0') - { - return false; - } - - readToken(); - if (token_ == ',') - { - readToken(); - } - if (!token_) - { - start = blockBegin; - token_.set(blockBegin, blockBegin); - readToken(); - } - - if (stack_.size() == 1 || stack_.back().isContainer || outName != 0) - { - if (token_ == ']' || token_ == '}') - { - DEBUG_TRACE("Got close bracket..."); - putToken(); - return false; - } - else - { - DEBUG_TRACE("Got unnamed value: '%s'", token_.str().c_str()); - putToken(); - return true; - } - } - else - { - if (isName(token_)) - { - DEBUG_TRACE("Seems to be a name '%s'", token_.str().c_str()); - Token nameContent(token_.start + 1, token_.end - 1); - if (nameContent == name) - { - readToken(); - expect(':'); - DEBUG_TRACE("Got one"); - return true; - } - else - { - start = token_.start; - - readToken(); - expect(':'); - skipBlock(); - } - } - else - { - start = token_.start; - if (token_ == ']' || token_ == '}') - { - token_ = Token(blockBegin, blockBegin); - } - else - { - putToken(); - skipBlock(); - } - } - } - - while (true) - { - readToken(); - if (!token_) - { - token_.set(blockBegin, blockBegin); - continue; - } - //return false; // Reached end of file while searching for name - DEBUG_TRACE("'%s'", token_.str().c_str()); - DEBUG_TRACE("Checking for loop: %i and %i", token_.start - reader_->begin(), start - reader_->begin()); - CRY_ASSERT(start != 0); - if (token_.start == start) - { - putToken(); - DEBUG_TRACE("unable to find..."); - return false; // Reached a full circle: unable to find name - } - - if (token_ == '}' || token_ == ']') // CONVERSION - { - DEBUG_TRACE("Going to begin of block, from %i", token_.start - reader_->begin()); - token_ = Token(blockBegin, blockBegin); - DEBUG_TRACE(" to %i", token_.start - reader_->begin()); - continue; // Reached '}' or ']' while searching for name, continue from begin of block - } - - if (name[0] == '\0') - { - if (isName(token_)) - { - readToken(); - if (!token_) - { - return false; // Reached end of file while searching for name - } - expect(':'); - skipBlock(); - } - else - { - putToken(); // Not a name - put it back - return true; - } - } - else - { - if (isName(token_)) - { - Token nameContent(token_.start + 1, token_.end - 1); - readToken(); - expect(':'); - if (nameContent == name) - { - return true; - } - else - { - skipBlock(); - } - } - else - { - putToken(); - skipBlock(); - } - } - } - - return false; - } - - bool JSONIArchive::openBracket() - { - readToken(); - if (token_ == '{') - { - return true; - } - putToken(); - return false; - } - - bool JSONIArchive::closeBracket() - { - int relativeLevel = 0; - while (true) - { - readToken(); - if (token_ == ',') - { - readToken(); - } - if (!token_) - { - MemoryWriter msg; - CRY_ASSERT(!stack_.empty()); - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while no matching bracket found"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - else if (token_ == '}' || token_ == ']') // CONVERSION - { - if (relativeLevel == 0) - { - return true; - } - else - { - --relativeLevel; - } - } - else if (token_ == '{' || token_ == '[') // CONVERSION - { - ++relativeLevel; - } - } - return false; - } - - bool JSONIArchive::openContainerBracket() - { - readToken(); - if (token_ == '[') - { - return true; - } - putToken(); - return false; - } - - bool JSONIArchive::closeContainerBracket() - { - readToken(); - if (token_ == ']') - { - DEBUG_TRACE("closeContainerBracket(): ok"); - return true; - } - else - { - DEBUG_TRACE("closeContainerBracket(): failed ('%s')", token_.str().c_str()); - putToken(); - return false; - } - } - - bool JSONIArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - } - else if (openContainerBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - stack_.back().isContainer = true; - } - else - { - return false; - } - - ser(*this); - CRY_ASSERT(!stack_.empty()); - stack_.pop_back(); -#if !defined(NDEBUG) - bool closed = -#endif - closeBracket(); - CRY_ASSERT(closed); - return true; - } - return false; - } - - bool JSONIArchive::operator()(const SBlackBox& box, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket() || openContainerBracket()) - { - const char* start = token_.start; - putToken(); - skipBlock(); - const char* end = token_.start; - if (end < start) - { - CRY_ASSERT(0); - return false; - } - while (end > start && - (*(end - 1) == ' ' - || *(end - 1) == '\r' - || *(end - 1) == '\n' - || *(end - 1) == '\t')) - { - --end; - } - // box has to be const in the interface so we can serialize - // temporary variables (i.e. function call result or structures - // constructed on the stack) - const_cast(box).set("json", (void*)start, end - start); - return true; - } - } - return false; - } - - bool JSONIArchive::operator()(IKeyValue& keyValue, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) - { - Token nextName; - if (!stack_.empty() && stack_.back().isContainer) - { - readToken(); - if (isName(token_) && checkStringValueToken()) - { - string key; - unescapeString(unescapeBuffer_, key, token_.start + 1, token_.end - 1); - keyValue.set(key.c_str()); - readToken(); - if (!expect(':')) - { - return false; - } - if (!keyValue.serializeValue(*this, "", 0)) - { - return false; - } - return true; - } - else - { - putToken(); - return false; - } - } - else if (findName("", &nextName)) - { - string key; - unescapeString(unescapeBuffer_, key, nextName.start + 1, nextName.end - 1); - keyValue.set(key.c_str()); - stack_.push_back(Level()); - stack_.back().isKeyValue = true; - - bool result = keyValue.serializeValue(*this, "", 0); - if (stack_.empty()) - { - // TODO: diagnose - return false; - } - stack_.pop_back(); - return result; - } - return false; - } - - - bool JSONIArchive::operator()(IPointer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - stack_.back().isKeyValue = true; - - readToken(); - if (isName(token_)) - { - if (checkStringValueToken()) - { - string typeName; - unescapeString(unescapeBuffer_, typeName, token_.start + 1, token_.end - 1); - - if (typeName != ser.registeredTypeName()) - { - ser.create(typeName.c_str()); - } - readToken(); - expect(':'); - operator()(ser.serializer(), "", 0); - } - } - else - { - putToken(); - - ser.create(""); - } - closeBracket(); - stack_.pop_back(); - return true; - } - } - return false; - } - - - bool JSONIArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - bool containerBracket = openContainerBracket(); - bool dictionaryBracket = false; - if (!containerBracket) - { - dictionaryBracket = openBracket(); - } - if (containerBracket || dictionaryBracket) - { - stack_.push_back(Level()); - stack_.back().isContainer = true; - stack_.back().start = token_.end; - - std::size_t size = ser.size(); - std::size_t index = 0; - - while (true) - { - readToken(); - if (token_ == ',') - { - readToken(); - } - if (token_ == '}' || token_ == ']') - { - break; - } - else if (!token_) - { - CRY_ASSERT(0 && "Reached end of file while reading container!"); - return false; - } - putToken(); - if (index == size) - { - size = index + 1; - } - if (index < size) - { - if (!ser(*this, "", "")) - { - // We've got a named item within a container, - // i.e. looks like a dictionary but not a container. - // Bail out, it is nothing we can do here. - closeBracket(); - break; - } - } - else - { - skipBlock(); - } - ser.next(); - ++index; - } - if (size > index) - { - ser.resize(index); - } - - CRY_ASSERT(!stack_.empty()); - stack_.pop_back(); - return true; - } - } - return false; - } - - void JSONIArchive::checkValueToken() - { - if (!token_) - { - CRY_ASSERT(!stack_.empty()); - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while reading element's value"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - } - } - - bool JSONIArchive::checkStringValueToken() - { - if (!token_) - { - return false; - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while reading element's value"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - if (token_.start[0] != '"' || token_.end[-1] != '"') - { - return false; - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": Expected string"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - return true; - } - - bool JSONIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = strtoul(token_.start, 0, 10); - return true; - } - return false; - } - - - bool JSONIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (int16)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (uint16)strtoul(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = _strtoi64(token_.start, 0, 10); -#else - value = strtoll(token_.start, 0, 10); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = _strtoui64(token_.start, 0, 10); -#else - value = strtoull(token_.start, 0, 10); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = float(std::atof(token_.str().c_str())); -#else - value = strtof(token_.start, 0); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = std::atof(token_.str().c_str()); -#else - value = strtod(token_.start, 0); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - if (checkStringValueToken()) - { - string buf; - unescapeString(unescapeBuffer_, buf, token_.start + 1, token_.end - 1); - value.set(buf.c_str()); - } - else - { - return false; - } - return true; - } - return false; - } - - - inline size_t utf8InUtf16Len(const char* p) - { - size_t result = 0; - - for (; *p; ++p) - { - unsigned char ch = (unsigned char)(*p); - - if (ch < 0x80 || (ch >= 0xC0 && ch < 0xFC)) - { - ++result; - } - } - - return result; - } - - inline const char* readUtf16FromUtf8(unsigned int* ch, const char* s) - { - const unsigned char byteMark = 0x80; - const unsigned char byteMaskRead = 0x3F; - - const unsigned char* str = (const unsigned char*)s; - - size_t len; - if (*str < byteMark) - { - *ch = *str; - return s + 1; - } - else if (*str < 0xC0) - { - *ch = ' '; - return s + 1; - } - else if (*str < 0xE0) - { - len = 2; - } - else if (*str < 0xF0) - { - len = 3; - } - else if (*str < 0xF8) - { - len = 4; - } - else if (*str < 0xFC) - { - len = 5; - } - else - { - *ch = ' '; - return s + 1; - } - - const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - *ch = (*str++ & ~firstByteMark[len]); - - switch (len) - { - case 5: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 4: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 3: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 2: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - } - - return (const char*)str; - } - - - inline void utf8ToUtf16(wstring* out, const char* in) - { - out->clear(); - out->reserve(utf8InUtf16Len(in)); - - for (; *in; ) - { - unsigned int character; - in = readUtf16FromUtf8(&character, in); - (*out) += (wchar_t)character; - } - } - - - bool JSONIArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - if (checkStringValueToken()) - { - string buf; - unescapeString(unescapeBuffer_, buf, token_.start + 1, token_.end - 1); - wstring wbuf; - utf8ToUtf16(&wbuf, buf.c_str()); - value.set(wbuf.c_str()); - } - else - { - return false; - } - return true; - } - return false; - } - - bool JSONIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - if (token_ == "true") - { - value = true; - } - else if (token_ == "false") - { - value = false; - } - else - { - CRY_ASSERT(0 && "Invalid boolean value"); - } - return true; - } - return false; - } - - bool JSONIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (int8)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (uint8)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (char)strtol(token_.start, 0, 10); - return true; - } - return false; - } -} -// vim:ts=4 sw=4: diff --git a/Code/CryEngine/CrySystem/Serialization/JSONIArchive.h b/Code/CryEngine/CrySystem/Serialization/JSONIArchive.h deleted file mode 100644 index b38476a597..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/JSONIArchive.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "Serialization/IArchive.h" -#include "MemoryReader.h" -#include "Token.h" -#include - -namespace Serialization { - class MemoryReader; - - class JSONIArchive - : public IArchive - { - public: - JSONIArchive(); - ~JSONIArchive(); - - bool load(const char* filename); - bool open(const char* buffer, size_t length, bool free = false); - - // virtuals: - bool operator()(bool& value, const char* name = "", const char* label = 0); - bool operator()(IString& value, const char* name = "", const char* label = 0); - bool operator()(IWString& value, const char* name = "", const char* label = 0); - bool operator()(float& value, const char* name = "", const char* label = 0); - bool operator()(double& value, const char* name = "", const char* label = 0); - bool operator()(int16& value, const char* name = "", const char* label = 0); - bool operator()(uint16& value, const char* name = "", const char* label = 0); - bool operator()(int32& value, const char* name = "", const char* label = 0); - bool operator()(uint32& value, const char* name = "", const char* label = 0); - bool operator()(int64& value, const char* name = "", const char* label = 0); - bool operator()(uint64& value, const char* name = "", const char* label = 0); - - bool operator()(int8& value, const char* name = "", const char* label = 0); - bool operator()(uint8& value, const char* name = "", const char* label = 0); - bool operator()(char& value, const char* name = "", const char* label = 0); - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0); - bool operator()(const SBlackBox& ser, const char* name = "", const char* label = 0); - bool operator()(IContainer& ser, const char* name = "", const char* label = 0); - bool operator()(IKeyValue& ser, const char* name = "", const char* label = 0); - bool operator()(IPointer& ser, const char* name = "", const char* label = 0); - - using IArchive::operator(); - private: - bool findName(const char* name, Token* outName = 0); - bool openBracket(); - bool closeBracket(); - - bool openContainerBracket(); - bool closeContainerBracket(); - - void checkValueToken(); - bool checkStringValueToken(); - void readToken(); - void putToken(); - int line(const char* position) const; - bool isName(Token token) const; - - bool expect(char token); - void skipBlock(); - - struct Level - { - const char* start; - const char* firstToken; - bool isContainer; - bool isKeyValue; - Level() - : isContainer(false) - , isKeyValue(false) {} - }; - typedef std::vector Stack; - Stack stack_; - - std::unique_ptr reader_; - Token token_; - std::vector unescapeBuffer_; - string filename_; - void* buffer_; - }; -} diff --git a/Code/CryEngine/CrySystem/Serialization/JSONOArchive.cpp b/Code/CryEngine/CrySystem/Serialization/JSONOArchive.cpp deleted file mode 100644 index d1aef5601e..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/JSONOArchive.cpp +++ /dev/null @@ -1,828 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "JSONOArchive.h" -#include "MemoryWriter.h" -#include "Serialization/KeyValue.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/BlackBox.h" -#include - -namespace Serialization { - // Some of non-latin1 characters here are not escaped to - // keep compatibility with 8-bit local encoding (e.g. windows-1251) - static const char* escapeTable[256] = { - "\\0" /* 0x00: */, - "\\x01" /* 0x01: */, - "\\x02" /* 0x02: */, - "\\x03" /* 0x03: */, - "\\x04" /* 0x04: */, - "\\x05" /* 0x05: */, - "\\x06" /* 0x06: */, - "\\x07" /* 0x07: */, - "\\x08" /* 0x08: */, - "\\t" /* 0x09: \t */, - "\\n" /* 0x0A: \n */, - "\\x0B" /* 0x0B: */, - "\\x0C" /* 0x0C: */, - "\\r" /* 0x0D: */, - "\\x0E" /* 0x0E: */, - "\\x0F" /* 0x0F: */, - - - "\\x10" /* 0x10: */, - "\\x11" /* 0x11: */, - "\\x12" /* 0x12: */, - "\\x13" /* 0x13: */, - "\\x14" /* 0x14: */, - "\\x15" /* 0x15: */, - "\\x16" /* 0x16: */, - "\\x17" /* 0x17: */, - "\\x18" /* 0x18: */, - "\\x19" /* 0x19: */, - "\\x1A" /* 0x1A: */, - "\\x1B" /* 0x1B: */, - "\\x1C" /* 0x1C: */, - "\\x1D" /* 0x1D: */, - "\\x1E" /* 0x1E: */, - "\\x1F" /* 0x1F: */, - - - " " /* 0x20: */, - "!" /* 0x21: ! */, - "\\\"" /* 0x22: " */, - "#" /* 0x23: # */, - "$" /* 0x24: $ */, - "%" /* 0x25: % */, - "&" /* 0x26: & */, - "'" /* 0x27: ' */, - "(" /* 0x28: ( */, - ")" /* 0x29: ) */, - "*" /* 0x2A: * */, - "+" /* 0x2B: + */, - "," /* 0x2C: , */, - "-" /* 0x2D: - */, - "." /* 0x2E: . */, - "/" /* 0x2F: / */, - - - "0" /* 0x30: 0 */, - "1" /* 0x31: 1 */, - "2" /* 0x32: 2 */, - "3" /* 0x33: 3 */, - "4" /* 0x34: 4 */, - "5" /* 0x35: 5 */, - "6" /* 0x36: 6 */, - "7" /* 0x37: 7 */, - "8" /* 0x38: 8 */, - "9" /* 0x39: 9 */, - ":" /* 0x3A: : */, - ";" /* 0x3B: ; */, - "<" /* 0x3C: < */, - "=" /* 0x3D: = */, - ">" /* 0x3E: > */, - "?" /* 0x3F: ? */, - - - "@" /* 0x40: @ */, - "A" /* 0x41: A */, - "B" /* 0x42: B */, - "C" /* 0x43: C */, - "D" /* 0x44: D */, - "E" /* 0x45: E */, - "F" /* 0x46: F */, - "G" /* 0x47: G */, - "H" /* 0x48: H */, - "I" /* 0x49: I */, - "J" /* 0x4A: J */, - "K" /* 0x4B: K */, - "L" /* 0x4C: L */, - "M" /* 0x4D: M */, - "N" /* 0x4E: N */, - "O" /* 0x4F: O */, - - - "P" /* 0x50: P */, - "Q" /* 0x51: Q */, - "R" /* 0x52: R */, - "S" /* 0x53: S */, - "T" /* 0x54: T */, - "U" /* 0x55: U */, - "V" /* 0x56: V */, - "W" /* 0x57: W */, - "X" /* 0x58: X */, - "Y" /* 0x59: Y */, - "Z" /* 0x5A: Z */, - "[" /* 0x5B: [ */, - "\\\\" /* 0x5C: \ */, - "]" /* 0x5D: ] */, - "^" /* 0x5E: ^ */, - "_" /* 0x5F: _ */, - - - "`" /* 0x60: ` */, - "a" /* 0x61: a */, - "b" /* 0x62: b */, - "c" /* 0x63: c */, - "d" /* 0x64: d */, - "e" /* 0x65: e */, - "f" /* 0x66: f */, - "g" /* 0x67: g */, - "h" /* 0x68: h */, - "i" /* 0x69: i */, - "j" /* 0x6A: j */, - "k" /* 0x6B: k */, - "l" /* 0x6C: l */, - "m" /* 0x6D: m */, - "n" /* 0x6E: n */, - "o" /* 0x6F: o */, - - - "p" /* 0x70: p */, - "q" /* 0x71: q */, - "r" /* 0x72: r */, - "s" /* 0x73: s */, - "t" /* 0x74: t */, - "u" /* 0x75: u */, - "v" /* 0x76: v */, - "w" /* 0x77: w */, - "x" /* 0x78: x */, - "y" /* 0x79: y */, - "z" /* 0x7A: z */, - "{" /* 0x7B: { */, - "|" /* 0x7C: | */, - "}" /* 0x7D: } */, - "~" /* 0x7E: ~ */, - "\x7F" /* 0x7F: */, // for utf-8 - - - "\x80" /* 0x80: */, - "\x81" /* 0x81: */, - "\x82" /* 0x82: */, - "\x83" /* 0x83: */, - "\x84" /* 0x84: */, - "\x85" /* 0x85: */, - "\x86" /* 0x86: */, - "\x87" /* 0x87: */, - "\x88" /* 0x88: */, - "\x89" /* 0x89: */, - "\x8A" /* 0x8A: */, - "\x8B" /* 0x8B: */, - "\x8C" /* 0x8C: */, - "\x8D" /* 0x8D: */, - "\x8E" /* 0x8E: */, - "\x8F" /* 0x8F: */, - - - "\x90" /* 0x90: */, - "\x91" /* 0x91: */, - "\x92" /* 0x92: */, - "\x93" /* 0x93: */, - "\x94" /* 0x94: */, - "\x95" /* 0x95: */, - "\x96" /* 0x96: */, - "\x97" /* 0x97: */, - "\x98" /* 0x98: */, - "\x99" /* 0x99: */, - "\x9A" /* 0x9A: */, - "\x9B" /* 0x9B: */, - "\x9C" /* 0x9C: */, - "\x9D" /* 0x9D: */, - "\x9E" /* 0x9E: */, - "\x9F" /* 0x9F: */, - - - "\xA0" /* 0xA0: */, - "\xA1" /* 0xA1: */, - "\xA2" /* 0xA2: */, - "\xA3" /* 0xA3: */, - "\xA4" /* 0xA4: */, - "\xA5" /* 0xA5: */, - "\xA6" /* 0xA6: */, - "\xA7" /* 0xA7: */, - "\xA8" /* 0xA8: */, - "\xA9" /* 0xA9: */, - "\xAA" /* 0xAA: */, - "\xAB" /* 0xAB: */, - "\xAC" /* 0xAC: */, - "\xAD" /* 0xAD: */, - "\xAE" /* 0xAE: */, - "\xAF" /* 0xAF: */, - - - "\xB0" /* 0xB0: */, - "\xB1" /* 0xB1: */, - "\xB2" /* 0xB2: */, - "\xB3" /* 0xB3: */, - "\xB4" /* 0xB4: */, - "\xB5" /* 0xB5: */, - "\xB6" /* 0xB6: */, - "\xB7" /* 0xB7: */, - "\xB8" /* 0xB8: */, - "\xB9" /* 0xB9: */, - "\xBA" /* 0xBA: */, - "\xBB" /* 0xBB: */, - "\xBC" /* 0xBC: */, - "\xBD" /* 0xBD: */, - "\xBE" /* 0xBE: */, - "\xBF" /* 0xBF: */, - - - "\xC0" /* 0xC0: */, - "\xC1" /* 0xC1: */, - "\xC2" /* 0xC2: */, - "\xC3" /* 0xC3: */, - "\xC4" /* 0xC4: */, - "\xC5" /* 0xC5: */, - "\xC6" /* 0xC6: */, - "\xC7" /* 0xC7: */, - "\xC8" /* 0xC8: */, - "\xC9" /* 0xC9: */, - "\xCA" /* 0xCA: */, - "\xCB" /* 0xCB: */, - "\xCC" /* 0xCC: */, - "\xCD" /* 0xCD: */, - "\xCE" /* 0xCE: */, - "\xCF" /* 0xCF: */, - - - "\xD0" /* 0xD0: */, - "\xD1" /* 0xD1: */, - "\xD2" /* 0xD2: */, - "\xD3" /* 0xD3: */, - "\xD4" /* 0xD4: */, - "\xD5" /* 0xD5: */, - "\xD6" /* 0xD6: */, - "\xD7" /* 0xD7: */, - "\xD8" /* 0xD8: */, - "\xD9" /* 0xD9: */, - "\xDA" /* 0xDA: */, - "\xDB" /* 0xDB: */, - "\xDC" /* 0xDC: */, - "\xDD" /* 0xDD: */, - "\xDE" /* 0xDE: */, - "\xDF" /* 0xDF: */, - - - "\xE0" /* 0xE0: */, - "\xE1" /* 0xE1: */, - "\xE2" /* 0xE2: */, - "\xE3" /* 0xE3: */, - "\xE4" /* 0xE4: */, - "\xE5" /* 0xE5: */, - "\xE6" /* 0xE6: */, - "\xE7" /* 0xE7: */, - "\xE8" /* 0xE8: */, - "\xE9" /* 0xE9: */, - "\xEA" /* 0xEA: */, - "\xEB" /* 0xEB: */, - "\xEC" /* 0xEC: */, - "\xED" /* 0xED: */, - "\xEE" /* 0xEE: */, - "\xEF" /* 0xEF: */, - - - "\xF0" /* 0xF0: */, - "\xF1" /* 0xF1: */, - "\xF2" /* 0xF2: */, - "\xF3" /* 0xF3: */, - "\xF4" /* 0xF4: */, - "\xF5" /* 0xF5: */, - "\xF6" /* 0xF6: */, - "\xF7" /* 0xF7: */, - "\xF8" /* 0xF8: */, - "\xF9" /* 0xF9: */, - "\xFA" /* 0xFA: */, - "\xFB" /* 0xFB: */, - "\xFC" /* 0xFC: */, - "\xFD" /* 0xFD: */, - "\xFE" /* 0xFE: */, - "\xFF" /* 0xFF: */ - }; - - static void escapeString(MemoryWriter& dest, const char* begin, const char* end) - { - while (begin != end) - { - const char* str = escapeTable[(unsigned char)(*begin)]; - dest.write(str); - ++begin; - } - } - - // --------------------------------------------------------------------------- - - static const int TAB_WIDTH = 2; - - JSONOArchive::JSONOArchive(int textWidth, const char* header) - : IArchive(OUTPUT | TEXT) - , header_(header) - , textWidth_(textWidth) - , compactOffset_(0) - { - buffer_.reset(new MemoryWriter(1024, true)); - if (header_) - { - (*buffer_) << header_; - } - - YASLI_ASSERT(stack_.empty()); - stack_.push_back(Level(false, 0, 0)); - } - - JSONOArchive::~JSONOArchive() - { - } - - bool JSONOArchive::save(const char* fileName) - { - YASLI_ESCAPE(fileName && strlen(fileName) > 0, return false); - YASLI_ESCAPE(stack_.size() == 1, return false); - YASLI_ESCAPE(buffer_.get() != 0, return false); - YASLI_ESCAPE(buffer_->position() <= buffer_->size(), return false); - stack_.pop_back(); - FILE* file = nullptr; - azfopen(&file, fileName, "wb"); - if (file) - { - if (fwrite(buffer_->c_str(), 1, buffer_->position(), file) != buffer_->position()) - { - fclose(file); - return false; - } - fclose(file); - return true; - } - else - { - return false; - } - } - - const char* JSONOArchive::c_str() const - { - return buffer_->c_str(); - } - - size_t JSONOArchive::length() const - { - return buffer_->position(); - } - - void JSONOArchive::openBracket() - { - *buffer_ << "{"; - } - - void JSONOArchive::closeBracket() - { - *buffer_ << "}"; - } - - void JSONOArchive::openContainerBracket() - { - *buffer_ << "["; - } - - void JSONOArchive::closeContainerBracket() - { - *buffer_ << "]"; - } - - void JSONOArchive::placeName(const char* name) - { - if (stack_.back().isKeyValue) - { - return; - } - if ((name[0] != '\0' || !stack_.back().isContainer) && stack_.size() > 1) - { - *buffer_ << "\""; - *buffer_ << name; - *buffer_ << "\": "; - stack_.back().nameIndex += 1; - } - } - - void JSONOArchive::placeIndent(bool putComma) - { - if (stack_.back().isKeyValue) - { - return; - } - if (putComma && stack_.back().elementIndex > 0) - { - *buffer_ << ","; - } - if (buffer_->position() > 0) - { - *buffer_ << "\n"; - } - int count = int(stack_.size() - 1); - stack_.back().indentCount += count; - stack_.back().elementIndex += 1; - for (int i = 0; i < count; ++i) - { - *buffer_ << "\t"; - } - compactOffset_ = 0; - } - - void JSONOArchive::placeIndentCompact(bool putComma) - { - if (stack_.back().isKeyValue) - { - return; - } - if (putComma && stack_.back().elementIndex > 0) - { - *buffer_ << ","; - } - if ((compactOffset_ % 32) != 0 && stack_.back().isContainer) - { - *buffer_ << " "; - compactOffset_ += 1; - stack_.back().elementIndex += 1; - } - else if (buffer_->size()) - { - *buffer_ << "\n"; - int count = int(stack_.size() - 1); - stack_.back().indentCount += count /* * TAB_WIDTH*/; - stack_.back().elementIndex += 1; - for (int i = 0; i < count; ++i) - { - *buffer_ << "\t"; - } - compactOffset_ = 1; - } - } - - bool JSONOArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - *buffer_ << (value ? "true" : "false"); - return true; - } - - - bool JSONOArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - (*buffer_) << "\""; - const char* str = value.get(); - escapeString(*buffer_, str, str + strlen(value.get())); - (*buffer_) << "\""; - return true; - } - - inline char* writeUtf16ToUtf8(char* s, unsigned int ch) - { - const unsigned char byteMark = 0x80; - const unsigned char byteMask = 0xBF; - - size_t len; - - if (ch < 0x80) - { - len = 1; - } - else if (ch < 0x800) - { - len = 2; - } - else if (ch < 0x10000) - { - len = 3; - } - else if (ch < 0x200000) - { - len = 4; - } - else - { - return s; - } - - s += len; - - const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - switch (len) - { - case 4: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 3: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 2: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 1: - *--s = (char)(ch | firstByteMark[len]); - } - - return s + len; - } - - bool JSONOArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - (*buffer_) << "\""; - - const wchar_t* in = value.get(); - for (; *in; ++in) - { - char buf[6]; - escapeString(*buffer_, buf, writeUtf16ToUtf8(buf, *in)); - } - - (*buffer_) << "\""; - return true; - } - - bool JSONOArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - std::size_t position = buffer_->position(); - openBracket(); - stack_.push_back(Level(false, position, int(strlen(name) + 2 * (name[0] & 1) + (stack_.size() - 1) * TAB_WIDTH + 2))); - - YASLI_ASSERT(ser); - ser(*this); - - bool joined = joinLinesIfPossible(); - bool noNames = stack_.back().nameIndex == 0; - if (noNames) - { - if (stack_.size() != 2) - { - buffer_->buffer()[stack_.back().startPosition] = '['; - } - } - stack_.pop_back(); - if (!joined) - { - placeIndent(false); - } - else - { - *buffer_ << " "; - } - if (noNames) - { - closeContainerBracket(); - } - else - { - closeBracket(); - } - return true; - } - - bool JSONOArchive::operator()(const SBlackBox& box, const char* name, [[maybe_unused]] const char* label) - { - if (strcmp(box.format, "json") != 0) - { - return false; - } - if (box.size == 0) - { - return false; - } - - placeIndent(); - placeName(name); - return buffer_->write(box.data, box.size); - } - - bool JSONOArchive::operator()(IKeyValue& keyValue, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - - *buffer_ << "\""; - *buffer_ << keyValue.get(); - *buffer_ << "\": "; - stack_.back().nameIndex += 1; - - stack_.back().isKeyValue = true; - keyValue.serializeValue(*this, "", 0); - stack_.back().isKeyValue = false; - if (stack_.back().isContainer) - { - stack_.back().isDictionary = true; - } - return true; - } - - bool JSONOArchive::operator()(IPointer& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - openBracket(); - const char* registeredTypeName = ser.registeredTypeName(); - if (registeredTypeName && registeredTypeName[0] != '\0') - { - *buffer_ << " "; - placeName(registeredTypeName); - stack_.back().isKeyValue = true; - operator()(ser.serializer(), ""); - stack_.back().isKeyValue = false; - *buffer_ << " "; - } - closeBracket(); - return true; - } - - bool JSONOArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - std::size_t position = buffer_->position(); - openContainerBracket(); - stack_.push_back(Level(true, position, int(strlen(name) + 2 * (name[0] & 1) + stack_.size() - 1 * TAB_WIDTH + 2))); - - std::size_t size = ser.size(); - if (size > 0) - { - do - { - ser(*this, "", ""); - } while (ser.next()); - } - - bool joined = joinLinesIfPossible(); - bool isDictionary = stack_.back().isDictionary; - if (isDictionary) - { - buffer_->buffer()[stack_.back().startPosition] = '{'; - } - stack_.pop_back(); - if (!joined) - { - placeIndent(false); - } - else - { - *buffer_ << " "; - } - - if (isDictionary) - { - closeBracket(); - } - else - { - closeContainerBracket(); - } - return true; - } - - static char* joinLines(char* start, char* end) - { - YASLI_ASSERT(start <= end); - char* next = start; - while (next != end) - { - if (*next != '\t' && *next != '\r') - { - if (*next != '\n') - { - *start = *next; - } - else - { - *start = ' '; - } - ++start; - } - ++next; - } - return start; - } - - bool JSONOArchive::joinLinesIfPossible() - { - YASLI_ASSERT(!stack_.empty()); - std::size_t startPosition = stack_.back().startPosition; - YASLI_ASSERT(startPosition < buffer_->size()); - int indentCount = stack_.back().indentCount; - //YASLI_ASSERT(startPosition >= indentCount); - if (buffer_->position() - startPosition - indentCount < std::size_t(textWidth_)) - { - char* buffer = buffer_->buffer(); - char* start = buffer + startPosition; - char* end = buffer + buffer_->position(); - end = joinLines(start, end); - std::size_t newPosition = end - buffer; - YASLI_ASSERT(newPosition <= buffer_->position()); - buffer_->setPosition(newPosition); - return true; - } - return false; - } -} -// vim:ts=4 sw=4: diff --git a/Code/CryEngine/CrySystem/Serialization/JSONOArchive.h b/Code/CryEngine/CrySystem/Serialization/JSONOArchive.h deleted file mode 100644 index 5701c992ac..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/JSONOArchive.h +++ /dev/null @@ -1,102 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include -#include "Serialization/IArchive.h" -#include "Serialization/MemoryWriter.h" - -namespace Serialization { - class MemoryWriter; - - class JSONOArchive - : public IArchive - { - public: - // header = 0 - default header, use "" to omit - JSONOArchive(int textWidth = 80, const char* header = 0); - ~JSONOArchive(); - - bool save(const char* fileName); - - const char* c_str() const; - const char* buffer() const { return c_str(); } - size_t length() const; - - // from Archive: - bool operator()(bool& value, const char* name = "", const char* label = 0); - bool operator()(IString& value, const char* name = "", const char* label = 0); - bool operator()(IWString& value, const char* name = "", const char* label = 0); - bool operator()(float& value, const char* name = "", const char* label = 0); - bool operator()(double& value, const char* name = "", const char* label = 0); - bool operator()(int16& value, const char* name = "", const char* label = 0); - bool operator()(uint16& value, const char* name = "", const char* label = 0); - bool operator()(int32& value, const char* name = "", const char* label = 0); - bool operator()(uint32& value, const char* name = "", const char* label = 0); - bool operator()(int64& value, const char* name = "", const char* label = 0); - bool operator()(uint64& value, const char* name = "", const char* label = 0); - - bool operator()(char& value, const char* name = "", const char* label = 0); - bool operator()(int8& value, const char* name = "", const char* label = 0); - bool operator()(uint8& value, const char* name = "", const char* label = 0); - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0); - bool operator()(const SBlackBox& box, const char* name = "", const char* label = 0); - bool operator()(IContainer& ser, const char* name = "", const char* label = 0); - bool operator()(IKeyValue& keyValue, const char* name = "", const char* label = 0); - bool operator()(IPointer& ser, const char* name = "", const char* label = 0); - // ^^^ - - using IArchive::operator(); - private: - void openBracket(); - void closeBracket(); - void openContainerBracket(); - void closeContainerBracket(); - void placeName(const char* name); - void placeIndent(bool putComma = true); - void placeIndentCompact(bool putComma = true); - - bool joinLinesIfPossible(); - - struct Level - { - Level(bool _isContainer, std::size_t position, int column) - : isKeyValue(false) - , isContainer(_isContainer) - , isDictionary(false) - , startPosition(position) - , nameIndex(0) - , elementIndex(0) - , indentCount(-column) - {} - bool isKeyValue; - bool isContainer; - bool isDictionary; - std::size_t startPosition; - int nameIndex; - int elementIndex; - int indentCount; - }; - - typedef std::vector Stack; - Stack stack_; - std::unique_ptr buffer_; - const char* header_; - int textWidth_; - string fileName_; - int compactOffset_; - bool isKeyValue_; - }; -} diff --git a/Code/CryEngine/CrySystem/Serialization/MemoryReader.cpp b/Code/CryEngine/CrySystem/Serialization/MemoryReader.cpp deleted file mode 100644 index ee424d065f..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/MemoryReader.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include -#include "Serialization/Assert.h" -#include "MemoryReader.h" -#include -#include - -namespace Serialization { - MemoryReader::MemoryReader() - : size_(0) - , position_(0) - , memory_(0) - , ownedMemory_(false) - { - } - - - MemoryReader::MemoryReader(const void* memory, std::size_t size, bool ownAndFree) - : size_(size) - , position_((const char*)(memory)) - , memory_((const char*)(memory)) - , ownedMemory_(ownAndFree) - { - } - - MemoryReader::~MemoryReader() - { - if (ownedMemory_) - { - free(const_cast(memory_)); - memory_ = 0; - size_ = 0; - } - } - - void MemoryReader::setPosition(const char* position) - { - position_ = position; - } - - void MemoryReader::read(void* data, std::size_t size) - { - YASLI_ASSERT(memory_ && position_); - YASLI_ASSERT(position_ - memory_ + size <= size_); - memcpy(data, position_, size); - position_ += size; - } - - bool MemoryReader::checkedRead(void* data, std::size_t size) - { - if (!memory_ || !position_) - { - return false; - } - if (position_ - memory_ + size > size_) - { - return false; - } - - memcpy(data, position_, size); - position_ += size; - return true; - } - - bool MemoryReader::checkedSkip(std::size_t size) - { - if (!memory_ || !position_) - { - return false; - } - if (position_ - memory_ + size > size_) - { - return false; - } - - position_ += size; - return true; - } -} diff --git a/Code/CryEngine/CrySystem/Serialization/MemoryReader.h b/Code/CryEngine/CrySystem/Serialization/MemoryReader.h deleted file mode 100644 index 88ae1d0060..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/MemoryReader.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include - -namespace Serialization { - class MemoryReader - { - public: - - MemoryReader(); - MemoryReader(const void* memory, size_t size, bool ownAndFree = false); - ~MemoryReader(); - - void setPosition(const char* position); - const char* position(){ return position_; } - - template - void read(T& value) - { - read(reinterpret_cast(&value), sizoef(value)); - } - void read(void* data, size_t size); - bool checkedSkip(size_t size); - bool checkedRead(void* data, size_t size); - template - bool checkedRead(T& t) - { - return checkedRead((void*)&t, sizeof(t)); - } - - const char* buffer() const{ return memory_; } - size_t size() const{ return size_; } - - const char* begin() const{ return memory_; } - const char* end() const{ return memory_ + size_; } - private: - size_t size_; - const char* position_; - const char* memory_; - bool ownedMemory_; - }; -} -// vim:ts=4 sw=4: diff --git a/Code/CryEngine/CrySystem/Serialization/MemoryWriter.cpp b/Code/CryEngine/CrySystem/Serialization/MemoryWriter.cpp deleted file mode 100644 index c426119812..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/MemoryWriter.cpp +++ /dev/null @@ -1,236 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include -#include "Serialization/Assert.h" -#include -#include -#include -#include -#ifdef _MSC_VER -# include -# define isnan _isnan -#endif - -#include "MemoryWriter.h" - -#undef YASLI_ASSERT -#define YASLI_ASSERT(x) - -namespace Serialization { - MemoryWriter::MemoryWriter(std::size_t size, bool reallocate) - : size_(size) - , reallocate_(reallocate) - , digits_(5) - { - allocate(size); - } - - MemoryWriter::~MemoryWriter() - { - position_ = 0; - CryModuleFree(memory_); - } - - void MemoryWriter::allocate(std::size_t initialSize) - { - memory_ = (char*)CryModuleMalloc(initialSize + 1); - position_ = memory_; - } - - void MemoryWriter::reallocate(std::size_t newSize) - { - YASLI_ASSERT(newSize > size_); - std::size_t pos = position(); - // Supressing the warning as we generally don't handle malloc errors. - // cppcheck-suppress memleakOnRealloc - memory_ = (char*)CryModuleRealloc(memory_, newSize + 1); - YASLI_ASSERT(memory_ != 0); - position_ = memory_ + pos; - size_ = newSize; - } - - MemoryWriter& MemoryWriter::operator<<(int value) - { - // TODO: optimize - char buffer[12]; - sprintf_s(buffer, "%i", value); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(long value) - { - // TODO: optimize - char buffer[12]; -#ifdef _MSC_VER - sprintf_s(buffer, "%i", value); -#else - sprintf_s(buffer, "%li", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned long value) - { - // TODO: optimize - char buffer[12]; -#ifdef _MSC_VER - sprintf_s(buffer, "%u", value); -#else - sprintf_s(buffer, "%lu", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(long long value) - { - // TODO: optimize - char buffer[24]; -#ifdef _MSC_VER - sprintf_s(buffer, "%I64i", value); -#else - sprintf_s(buffer, "%lli", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned long long value) - { - // TODO: optimize - char buffer[24]; - sprintf_s(buffer, "%llu", value); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned int value) - { - // TODO: optimize - char buffer[12]; - sprintf_s(buffer, "%u", value); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(signed char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - inline void cutRightZeros(const char* str) - { - for (char* p = (char*)str + strlen(str) - 1; p >= str; --p) - { - if (*p == '0') - { - *p = 0; - } - else - { - return; - } - } - } - - MemoryWriter& MemoryWriter::operator<<(double value) - { - YASLI_ASSERT(!isnan(value)); - - char buf[64] = { 0 }; - sprintf_s(buf, "%f", value); - operator<<(buf); - return *this; - } - - MemoryWriter& MemoryWriter::operator<<(const char* value) - { - write((void*)value, strlen(value)); - YASLI_ASSERT(position() < size()); - *position_ = '\0'; - return *this; - } - - MemoryWriter& MemoryWriter::operator<<(const wchar_t* value) - { - write((void*)value, wcslen(value) * sizeof(wchar_t)); - YASLI_ASSERT(position() < size()); - *position_ = '\0'; - return *this; - } - - void MemoryWriter::setPosition(std::size_t pos) - { - YASLI_ASSERT(pos < size_); - YASLI_ASSERT(memory_ + pos <= position_); - position_ = memory_ + pos; - } - - void MemoryWriter::write(const char* value) - { - write((void*)value, strlen(value)); - } - - bool MemoryWriter::write(const void* data, std::size_t size) - { - YASLI_ASSERT(memory_ <= position_); - YASLI_ASSERT(position() < this->size()); - if (size_ - position() > size) - { - memcpy(position_, data, size); - position_ += size; - } - else - { - if (!reallocate_) - { - return false; - } - - reallocate(size_ * 2); - write(data, size); - } - YASLI_ASSERT(position() < this->size()); - return true; - } - - void MemoryWriter::write(char c) - { - if (size_ - position() > 1) - { - *(char*)(position_) = c; - ++position_; - } - else - { - YASLI_ESCAPE(reallocate_, return ); - reallocate(size_ * 2); - write(c); - } - YASLI_ASSERT(position() < this->size()); - } -} diff --git a/Code/CryEngine/CrySystem/Serialization/MemoryWriter.h b/Code/CryEngine/CrySystem/Serialization/MemoryWriter.h deleted file mode 100644 index 314a39c2d8..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/MemoryWriter.h +++ /dev/null @@ -1,72 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include - -namespace Serialization { - class MemoryWriter - { - public: - MemoryWriter(std::size_t size = 128, bool reallocate = true); - ~MemoryWriter(); - - const char* c_str() { return memory_; }; - const wchar_t* w_str() { return (wchar_t*)memory_; }; - char* buffer() { return memory_; } - const char* buffer() const { return memory_; } - std::size_t size() const{ return size_; } - void clear() { position_ = memory_; } - - // String interface (after this calls '\0' is always written) - MemoryWriter& operator<<(int value); - MemoryWriter& operator<<(long value); - MemoryWriter& operator<<(unsigned long value); - MemoryWriter& operator<<(unsigned int value); - MemoryWriter& operator<<(long long value); - MemoryWriter& operator<<(unsigned long long value); - MemoryWriter& operator<<(float value) { return (*this) << double(value); } - MemoryWriter& operator<<(double value); - MemoryWriter& operator<<(signed char value); - MemoryWriter& operator<<(unsigned char value); - MemoryWriter& operator<<(char value); - MemoryWriter& operator<<(const char* value); - MemoryWriter& operator<<(const wchar_t* value); - - // Binary interface (does not writes trailing '\0') - template - void write(const T& value) - { - write(reinterpret_cast(&value), sizeof(value)); - } - void write(char c); - void write(const char* str); - bool write(const void* data, std::size_t size); - - std::size_t position() const{ return position_ - memory_; } - void setPosition(std::size_t pos); - - MemoryWriter& setDigits(int digits) { digits_ = (unsigned char)digits; return *this; } - - private: - void allocate(std::size_t initialSize); - void reallocate(std::size_t newSize); - - std::size_t size_; - char* position_; - char* memory_; - bool reallocate_; - unsigned char digits_; - }; -} diff --git a/Code/CryEngine/CrySystem/Serialization/Test_ArchiveHost.cpp b/Code/CryEngine/CrySystem/Serialization/Test_ArchiveHost.cpp deleted file mode 100644 index 9608da72c6..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/Test_ArchiveHost.cpp +++ /dev/null @@ -1,492 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include - -#include - -#include "ArchiveHost.h" -#include -#include -#include -#include -#include - -namespace Serialization -{ - struct SMember - { - string name; - float weight; - - SMember() - : weight(0.0f) - {} - - void CheckEquality(const SMember& copy) const - { - EXPECT_TRUE(name == copy.name); - EXPECT_TRUE(weight == copy.weight); - } - - void Change(int index) - { - name = "Changed name "; - name += (index % 10) + '0'; - weight = float(index); - } - - void Serialize(IArchive& ar) - { - ar(name, "name"); - ar(weight, "weight"); - } - }; - - class CPolyBase - : public _i_reference_target_t - { - public: - CPolyBase() - { - baseMember = "Regular base member"; - } - - virtual void Change() - { - baseMember = "Changed base member"; - } - - virtual void Serialize(IArchive& ar) - { - ar(baseMember, "baseMember"); - } - - virtual void CheckEquality(const CPolyBase* copy) const - { - EXPECT_TRUE(baseMember == copy->baseMember); - } - - virtual bool IsDerivedA() const - { - return false; - } - virtual bool IsDerivedB() const - { - return false; - } - protected: - string baseMember; - }; - - class CPolyDerivedA - : public CPolyBase - { - public: - void Serialize(IArchive& ar) - { - CPolyBase::Serialize(ar); - ar(derivedMember, "derivedMember"); - } - - bool IsDerivedA() const override - { - return true; - } - - void CheckEquality(const CPolyBase* copyBase) const - { - EXPECT_TRUE(copyBase->IsDerivedA()); - const CPolyDerivedA* copy = (CPolyDerivedA*)copyBase; - EXPECT_TRUE(derivedMember == copy->derivedMember); - - CPolyBase::CheckEquality(copyBase); - } - protected: - string derivedMember; - }; - - class CPolyDerivedB - : public CPolyBase - { - public: - CPolyDerivedB() - : derivedMember("B Derived") - {} - - bool IsDerivedB() const override - { - return true; - } - - void Serialize(IArchive& ar) - { - CPolyBase::Serialize(ar); - ar(derivedMember, "derivedMember"); - } - - void CheckEquality(const CPolyBase* copyBase) const - { - EXPECT_TRUE(copyBase->IsDerivedB()); - const CPolyDerivedB* copy = (const CPolyDerivedB*)copyBase; - EXPECT_TRUE(derivedMember == copy->derivedMember); - - CPolyBase::CheckEquality(copyBase); - } - protected: - string derivedMember; - }; - - struct SNumericTypes - { - SNumericTypes() - : m_bool(false) - , m_char(0) - , m_int8(0) - , m_uint8(0) - , m_int16(0) - , m_uint16(0) - , m_int32(0) - , m_uint32(0) - , m_int64(0) - , m_uint64(0) - , m_float(0.0f) - , m_double(0.0) - {} - - void Change() - { - m_bool = true; - m_char = -1; - m_int8 = -2; - m_uint8 = 0xff - 3; - m_int16 = -6; - m_uint16 = 0xff - 7; - m_int32 = -4; - m_uint32 = -5; - m_int64 = -8ll; - m_uint64 = 9ull; - m_float = -10.0f; - m_double = -11.0; - } - - void Serialize(IArchive& ar) - { - ar(m_bool, "bool"); - ar(m_char, "char"); - ar(m_int8, "int8"); - ar(m_uint8, "uint8"); - ar(m_int16, "int16"); - ar(m_uint16, "uint16"); - ar(m_int32, "int32"); - ar(m_uint32, "uint32"); - ar(m_int64, "int64"); - ar(m_uint64, "uint64"); - ar(m_float, "float"); - ar(m_double, "double"); - } - - void CheckEquality(const SNumericTypes& rhs) const - { - EXPECT_TRUE(m_bool == rhs.m_bool); - EXPECT_TRUE(m_char == rhs.m_char); - EXPECT_TRUE(m_int8 == rhs.m_int8); - EXPECT_TRUE(m_uint8 == rhs.m_uint8); - EXPECT_TRUE(m_int16 == rhs.m_int16); - EXPECT_TRUE(m_uint16 == rhs.m_uint16); - EXPECT_TRUE(m_int32 == rhs.m_int32); - EXPECT_TRUE(m_uint32 == rhs.m_uint32); - EXPECT_TRUE(m_int64 == rhs.m_int64); - EXPECT_TRUE(m_uint64 == rhs.m_uint64); - EXPECT_TRUE(m_float == rhs.m_float); - EXPECT_TRUE(m_double == rhs.m_double); - } - - bool m_bool; - - char m_char; - int8 m_int8; - uint8 m_uint8; - - int16 m_int16; - uint16 m_uint16; - - int32 m_int32; - uint32 m_uint32; - - int64 m_int64; - uint64 m_uint64; - - float m_float; - double m_double; - }; - - class CComplexClass - { - public: - CComplexClass() - : index(0) - { - name = "Foo"; - stringList.push_back("Choice 1"); - stringList.push_back("Choice 2"); - stringList.push_back("Choice 3"); - - polyPtr.reset(new CPolyDerivedA()); - - polyVector.push_back(new CPolyDerivedB); - polyVector.push_back(new CPolyBase); - - SMember& a = stringToStructMap["a"]; - a.name = "A"; - SMember& b = stringToStructMap["b"]; - b.name = "B"; - - members.resize(13); - - intToString.push_back(std::make_pair(1, "one")); - intToString.push_back(std::make_pair(2, "two")); - intToString.push_back(std::make_pair(3, "three")); - stringToInt.push_back(std::make_pair("one", 1)); - stringToInt.push_back(std::make_pair("two", 2)); - stringToInt.push_back(std::make_pair("three", 3)); - } - - void Change() - { - name = "Slightly changed name"; - index = 2; - polyPtr.reset(new CPolyDerivedB()); - polyPtr->Change(); - - for (size_t i = 0; i < members.size(); ++i) - { - members[i].Change(int(i)); - } - - members.erase(members.begin()); - - for (size_t i = 0; i < polyVector.size(); ++i) - { - polyVector[i]->Change(); - } - - polyVector.resize(4); - polyVector.push_back(new CPolyBase()); - polyVector[4]->Change(); - - const size_t arrayLen = sizeof(array) / sizeof(array[0]); - for (size_t i = 0; i < arrayLen; ++i) - { - array[i].Change(int(arrayLen - i)); - } - - numericTypes.Change(); - - vectorOfStrings.push_back("str1"); - vectorOfStrings.push_back("2str"); - vectorOfStrings.push_back("thirdstr"); - - stringToStructMap.erase("a"); - SMember& c = stringToStructMap["c"]; - c.name = "C"; - - intToString.push_back(std::make_pair(4, "four")); - stringToInt.push_back(std::make_pair("four", 4)); - } - - void Serialize(IArchive& ar) - { - ar(name, "name"); - ar(polyPtr, "polyPtr"); - ar(polyVector, "polyVector"); - ar(members, "members"); - { - StringListValue value(stringList, stringList[index]); - ar(value, "stringList"); - index = value.index(); - if (index == -1) - { - index = 0; - } - } - ar(array, "array"); - ar(numericTypes, "numericTypes"); - ar(vectorOfStrings, "vectorOfStrings"); - ar(stringToInt, "stringToInt"); - } - - void CheckEquality(const CComplexClass& copy) const - { - EXPECT_TRUE(name == copy.name); - EXPECT_TRUE(index == copy.index); - - EXPECT_TRUE(polyPtr != 0); - EXPECT_TRUE(copy.polyPtr != 0); - polyPtr->CheckEquality(copy.polyPtr); - - EXPECT_TRUE(members.size() == copy.members.size()); - for (size_t i = 0; i < members.size(); ++i) - { - members[i].CheckEquality(copy.members[i]); - } - - EXPECT_TRUE(polyVector.size() == copy.polyVector.size()); - for (size_t i = 0; i < polyVector.size(); ++i) - { - if (polyVector[i] == 0) - { - EXPECT_TRUE(copy.polyVector[i] == 0); - continue; - } - EXPECT_TRUE(copy.polyVector[i] != 0); - polyVector[i]->CheckEquality(copy.polyVector[i]); - } - - const size_t arrayLen = sizeof(array) / sizeof(array[0]); - for (size_t i = 0; i < arrayLen; ++i) - { - array[i].CheckEquality(copy.array[i]); - } - - numericTypes.CheckEquality(copy.numericTypes); - - EXPECT_TRUE(stringToInt.size() == copy.stringToInt.size()); - for (size_t i = 0; i < stringToInt.size(); ++i) - { - EXPECT_TRUE(stringToInt[i] == copy.stringToInt[i]); - } - } - protected: - string name; - typedef std::vector Members; - std::vector vectorOfStrings; - std::vector > intToString; - std::vector > stringToInt; - Members members; - int32 index; - SNumericTypes numericTypes; - - StringListStatic stringList; - std::vector< _smart_ptr > polyVector; - _smart_ptr polyPtr; - - std::map stringToStructMap; - - SMember array[5]; - }; - - struct ArchiveHostTests - : ::testing::Test - { - public: - void SetUp() override - { - AZ::AllocatorInstance::Create(); - AZ::AllocatorInstance::Create(); - - m_classFactoryRTTI = AZStd::make_unique(); - } - - void TearDown() - { - m_classFactoryRTTI.reset(); - - AZ::AllocatorInstance::Destroy(); - AZ::AllocatorInstance::Destroy(); - } - - struct ClassFactoryRTTI - { - ClassFactoryRTTI() - : CPolyBaseCPolyBase_DerivedDescription("base", "Base") - , CPolyBaseCPolyBase_Creator(&CPolyBaseCPolyBase_DerivedDescription) - , TypeCPolyBase_DerivedDescription("derived_a", "Derived A") - , TypeCPolyBase_Creator(&TypeCPolyBase_DerivedDescription) - , CPolyDerivedBCPolyBase_DerivedDescription("derived_b", "Derived B") - , CPolyDerivedBCPolyBase_Creator(&CPolyDerivedBCPolyBase_DerivedDescription) - {} - - ~ClassFactoryRTTI() - { - Serialization::ClassFactory::destroy(); - } - - const Serialization::TypeDescription CPolyBaseCPolyBase_DerivedDescription; - Serialization::ClassFactory::Creator CPolyBaseCPolyBase_Creator; - - const Serialization::TypeDescription TypeCPolyBase_DerivedDescription; - Serialization::ClassFactory::Creator TypeCPolyBase_Creator; - - const Serialization::TypeDescription CPolyDerivedBCPolyBase_DerivedDescription; - Serialization::ClassFactory::Creator CPolyDerivedBCPolyBase_Creator; - }; - AZStd::unique_ptr m_classFactoryRTTI; - }; - - TEST_F(ArchiveHostTests, JsonBasicTypes) - { - std::unique_ptr host(CreateArchiveHost()); - - DynArray bufChanged; - CComplexClass objChanged; - objChanged.Change(); - host->SaveJsonBuffer(bufChanged, SStruct(objChanged)); - EXPECT_TRUE(!bufChanged.empty()); - - DynArray bufResaved; - { - CComplexClass obj; - - EXPECT_TRUE(host->LoadJsonBuffer(SStruct(obj), bufChanged.data(), bufChanged.size())); - EXPECT_TRUE(host->SaveJsonBuffer(bufResaved, SStruct(obj))); - EXPECT_TRUE(!bufResaved.empty()); - - obj.CheckEquality(objChanged); - } - EXPECT_TRUE(bufChanged.size() == bufResaved.size()); - for (size_t i = 0; i < bufChanged.size(); ++i) - { - EXPECT_TRUE(bufChanged[i] == bufResaved[i]); - } - } - - TEST_F(ArchiveHostTests, BinBasicTypes) - { - std::unique_ptr host(CreateArchiveHost()); - - DynArray bufChanged; - CComplexClass objChanged; - objChanged.Change(); - host->SaveBinaryBuffer(bufChanged, SStruct(objChanged)); - EXPECT_TRUE(!bufChanged.empty()); - - DynArray bufResaved; - { - CComplexClass obj; - - EXPECT_TRUE(host->LoadBinaryBuffer(SStruct(obj), bufChanged.data(), bufChanged.size())); - EXPECT_TRUE(host->SaveBinaryBuffer(bufResaved, SStruct(obj))); - EXPECT_TRUE(!bufResaved.empty()); - - obj.CheckEquality(objChanged); - } - EXPECT_TRUE(bufChanged.size() == bufResaved.size()); - for (size_t i = 0; i < bufChanged.size(); ++i) - { - EXPECT_TRUE(bufChanged[i] == bufResaved[i]); - } - } -} - diff --git a/Code/CryEngine/CrySystem/Serialization/Token.h b/Code/CryEngine/CrySystem/Serialization/Token.h deleted file mode 100644 index 4f730054e4..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/Token.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include - -#include "Serialization/Strings.h" - -namespace Serialization { - struct Token - { - Token(const char* _str = 0) - : start(_str) - , end(_str ? _str + strlen(_str) : 0) - { - } - - Token(const char* _str, size_t _len) - : start(_str) - , end(_str + _len) {} - Token(const char* _start, const char* _end) - : start(_start) - , end(_end) {} - - void set(const char* _start, const char* _end) { start = _start; end = _end; } - std::size_t length() const{ return end - start; } - - bool operator==(const Token& rhs) const - { - if (length() != rhs.length()) - { - return false; - } - return memcmp(start, rhs.start, length()) == 0; - } - bool operator==(const string& rhs) const - { - if (length() != rhs.size()) - { - return false; - } - return memcmp(start, rhs.c_str(), length()) == 0; - } - - bool operator==(const char* text) const - { - if (strncmp(text, start, length()) == 0) - { - return text[length()] == '\0'; - } - return false; - } - bool operator!=(const char* text) const - { - if (strncmp(text, start, length()) == 0) - { - return text[length()] != '\0'; - } - return true; - } - bool operator==(char c) const - { - return length() == 1 && *start == c; - } - bool operator!=(char c) const - { - return length() != 1 || *start != c; - } - - operator bool() const{ - return start != end; - } - string str() const{ return string(start, end); } - - const char* start; - const char* end; - }; -} diff --git a/Code/CryEngine/CrySystem/Serialization/XmlIArchive.cpp b/Code/CryEngine/CrySystem/Serialization/XmlIArchive.cpp deleted file mode 100644 index 914b7857e0..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/XmlIArchive.cpp +++ /dev/null @@ -1,297 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "CryExtension/Impl/ClassWeaver.h" - -#include -#include - -#include "XmlIArchive.h" - -#include -#include - -namespace XmlUtil -{ - int g_hintSuccess = 0; - int g_hintFail = 0; - - - XmlNodeRef FindChildNode(XmlNodeRef pParent, const int childIndexOverride, int& childIndexHint, const char* const name) - { - CRY_ASSERT(pParent); - - if (0 <= childIndexOverride) - { - CRY_ASSERT(childIndexOverride < pParent->getChildCount()); - return pParent->getChild(childIndexOverride); - } - else - { - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - CRY_ASSERT(0 <= childIndexHint); - - const int childCount = pParent->getChildCount(); - const bool hasValidChildHint = (childIndexHint < childCount); - if (hasValidChildHint) - { - XmlNodeRef pChildNode = pParent->getChild(childIndexHint); - if (pChildNode->isTag(name)) - { - g_hintSuccess++; - const int nextChildIndexHint = childIndexHint + 1; - childIndexHint = (nextChildIndexHint < childCount) ? nextChildIndexHint : 0; - return pChildNode; - } - else - { - g_hintFail++; - } - } - - for (int i = 0; i < childCount; ++i) - { - XmlNodeRef pChildNode = pParent->getChild(i); - if (pChildNode->isTag(name)) - { - const int nextChildIndexHint = i + 1; - childIndexHint = (nextChildIndexHint < childCount) ? nextChildIndexHint : 0; - return pChildNode; - } - } - } - return XmlNodeRef(); - } - - - template< typename T, typename TOut > - bool ReadChildNodeAs(XmlNodeRef pParent, const int childIndexOverride, int& childIndexHint, const char* const name, TOut& valueOut) - { - XmlNodeRef pChild = FindChildNode(pParent, childIndexOverride, childIndexHint, name); - if (pChild) - { - T tmp; - const bool readValueSuccess = pChild->getAttr("value", tmp); - if (readValueSuccess) - { - valueOut = tmp; - } - return readValueSuccess; - } - return false; - } - - - template< typename T > - bool ReadChildNode(XmlNodeRef pParent, const int childIndexOverride, int& childIndexHint, const char* const name, T& valueOut) - { - return ReadChildNodeAs< T >(pParent, childIndexOverride, childIndexHint, name, valueOut); - } -} - - -Serialization::CXmlIArchive::CXmlIArchive() - : IArchive(INPUT | NO_EMPTY_NAMES) - , m_childIndexOverride(-1) - , m_childIndexHint(0) -{ -} - - -Serialization::CXmlIArchive::CXmlIArchive(XmlNodeRef pRootNode) - : IArchive(INPUT | NO_EMPTY_NAMES) - , m_pRootNode(pRootNode) - , m_childIndexOverride(-1) - , m_childIndexHint(0) -{ - CRY_ASSERT(m_pRootNode); -} - - -Serialization::CXmlIArchive::~CXmlIArchive() -{ -} - - -void Serialization::CXmlIArchive::SetXmlNode(XmlNodeRef pNode) -{ - m_pRootNode = pNode; -} - - -XmlNodeRef Serialization::CXmlIArchive::GetXmlNode() const -{ - return m_pRootNode; -} - - -bool Serialization::CXmlIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) -{ - XmlNodeRef pChild = XmlUtil::FindChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name); - if (pChild) - { - const char* const stringValue = pChild->getAttr("value"); - if (stringValue) - { - value = (strcmp("true", stringValue) == 0); - value = value || (strcmp("1", stringValue) == 0); - return true; - } - return false; - } - return false; -} - - -bool Serialization::CXmlIArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) -{ - XmlNodeRef pChild = XmlUtil::FindChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name); - if (pChild) - { - const char* const stringValue = pChild->getAttr("value"); - if (stringValue) - { - value.set(stringValue); - return true; - } - return false; - } - return false; -} - - -bool Serialization::CXmlIArchive::operator()([[maybe_unused]] IWString& value, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) -{ - CryFatalError("CXmlIArchive::operator() with IWString is not implemented"); - return false; -} - - -bool Serialization::CXmlIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNodeAs< int >(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNodeAs< uint >(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNodeAs< int >(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNodeAs< uint >(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::ReadChildNodeAs< int >(m_pRootNode, m_childIndexOverride, m_childIndexHint, name, value); -} - - -bool Serialization::CXmlIArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - - XmlNodeRef pChild = XmlUtil::FindChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name); - if (pChild) - { - CXmlIArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - const bool serializeSuccess = ser(childArchive); - return serializeSuccess; - } - return false; -} - - -bool Serialization::CXmlIArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) -{ - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - - bool serializeSuccess = true; - - XmlNodeRef pChild = XmlUtil::FindChildNode(m_pRootNode, m_childIndexOverride, m_childIndexHint, name); - if (pChild) - { - const int elementCount = pChild->getChildCount(); - ser.resize(elementCount); - - if (0 < elementCount) - { - CXmlIArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - for (int i = 0; i < elementCount; ++i) - { - childArchive.m_childIndexOverride = i; - - serializeSuccess &= ser(childArchive, "Element", "Element"); - ser.next(); - } - } - } - - return serializeSuccess; -} diff --git a/Code/CryEngine/CrySystem/Serialization/XmlIArchive.h b/Code/CryEngine/CrySystem/Serialization/XmlIArchive.h deleted file mode 100644 index dd23febef6..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/XmlIArchive.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef __XML_I_ARCHIVE__H__ -#define __XML_I_ARCHIVE__H__ - -#include - -namespace Serialization -{ - class CXmlIArchive - : public IArchive - { - public: - CXmlIArchive(); - CXmlIArchive(XmlNodeRef pRootNode); - ~CXmlIArchive(); - - void SetXmlNode(XmlNodeRef pNode); - XmlNodeRef GetXmlNode() const; - - // IArchive - bool operator()(bool& value, const char* name = "", const char* label = 0) override; - bool operator()(IString& value, const char* name = "", const char* label = 0) override; - bool operator()(IWString& value, const char* name = "", const char* label = 0) override; - bool operator()(float& value, const char* name = "", const char* label = 0) override; - bool operator()(double& value, const char* name = "", const char* label = 0) override; - bool operator()(int16& value, const char* name = "", const char* label = 0) override; - bool operator()(uint16& value, const char* name = "", const char* label = 0) override; - bool operator()(int32& value, const char* name = "", const char* label = 0) override; - bool operator()(uint32& value, const char* name = "", const char* label = 0) override; - bool operator()(int64& value, const char* name = "", const char* label = 0) override; - bool operator()(uint64& value, const char* name = "", const char* label = 0) override; - - bool operator()(int8& value, const char* name = "", const char* label = 0) override; - bool operator()(uint8& value, const char* name = "", const char* label = 0) override; - bool operator()(char& value, const char* name = "", const char* label = 0) override; - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0) override; - bool operator()(IContainer& ser, const char* name = "", const char* label = 0) override; - // ~IArchive - - using IArchive::operator(); - - private: - XmlNodeRef m_pRootNode; - int m_childIndexOverride; - int m_childIndexHint; - }; -} - -#endif diff --git a/Code/CryEngine/CrySystem/Serialization/XmlOArchive.cpp b/Code/CryEngine/CrySystem/Serialization/XmlOArchive.cpp deleted file mode 100644 index 1133a7e51e..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/XmlOArchive.cpp +++ /dev/null @@ -1,213 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "CrySystem_precompiled.h" -#include "CryExtension/Impl/ClassWeaver.h" - -#include -#include - -#include "XmlOArchive.h" - -#include -#include - -namespace XmlUtil -{ - XmlNodeRef CreateChildNode(XmlNodeRef pParent, const char* const name) - { - CRY_ASSERT(pParent); - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - - XmlNodeRef pChild = pParent->createNode(name); - CRY_ASSERT(pChild); - - pParent->addChild(pChild); - return pChild; - } - - template < typename T, typename TIn > - bool WriteChildNodeAs(XmlNodeRef pParent, const char* const name, const TIn& value) - { - XmlNodeRef pChild = XmlUtil::CreateChildNode(pParent, name); - CRY_ASSERT(pChild); - - pChild->setAttr("value", static_cast< T >(value)); - return true; - } - - template < typename T > - bool WriteChildNode(XmlNodeRef pParent, const char* const name, const T& value) - { - return WriteChildNodeAs< T >(pParent, name, value); - } -} - -Serialization::CXmlOArchive::CXmlOArchive() - : IArchive(OUTPUT | NO_EMPTY_NAMES) -{ -} - - -Serialization::CXmlOArchive::CXmlOArchive(XmlNodeRef pRootNode) - : IArchive(OUTPUT | NO_EMPTY_NAMES) - , m_pRootNode(pRootNode) -{ - CRY_ASSERT(m_pRootNode); -} - - -Serialization::CXmlOArchive::~CXmlOArchive() -{ -} - - -void Serialization::CXmlOArchive::SetXmlNode(XmlNodeRef pNode) -{ - m_pRootNode = pNode; -} - - -XmlNodeRef Serialization::CXmlOArchive::GetXmlNode() const -{ - return m_pRootNode; -} - - -bool Serialization::CXmlOArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) -{ - const char* const stringValue = value ? "true" : "false"; - return XmlUtil::WriteChildNode(m_pRootNode, name, stringValue); -} - - -bool Serialization::CXmlOArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) -{ - const char* const stringValue = value.get(); - return XmlUtil::WriteChildNode(m_pRootNode, name, stringValue); -} - - -bool Serialization::CXmlOArchive::operator()([[maybe_unused]] IWString& value, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) -{ - CryFatalError("CXmlOArchive::operator() with IWString is not implemented"); - return false; -} - - -bool Serialization::CXmlOArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNodeAs< int >(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNodeAs< uint >(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNode(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNodeAs< int >(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNodeAs< uint >(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) -{ - return XmlUtil::WriteChildNodeAs< int >(m_pRootNode, name, value); -} - - -bool Serialization::CXmlOArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - - XmlNodeRef pChild = XmlUtil::CreateChildNode(m_pRootNode, name); - CXmlOArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - const bool serializeSuccess = ser(childArchive); - - return serializeSuccess; -} - - -bool Serialization::CXmlOArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) -{ - CRY_ASSERT(name); - CRY_ASSERT(name[ 0 ]); - - bool serializeSuccess = true; - - XmlNodeRef pChild = XmlUtil::CreateChildNode(m_pRootNode, name); - CXmlOArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - const size_t containerSize = ser.size(); - if (0 < containerSize) - { - do - { - serializeSuccess &= ser(childArchive, "Element", "Element"); - } while (ser.next()); - } - - return serializeSuccess; -} diff --git a/Code/CryEngine/CrySystem/Serialization/XmlOArchive.h b/Code/CryEngine/CrySystem/Serialization/XmlOArchive.h deleted file mode 100644 index 4451d2ba75..0000000000 --- a/Code/CryEngine/CrySystem/Serialization/XmlOArchive.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef __XML_O_ARCHIVE__H__ -#define __XML_O_ARCHIVE__H__ - -#include - -namespace Serialization -{ - class CXmlOArchive - : public IArchive - { - public: - CXmlOArchive(); - CXmlOArchive(XmlNodeRef pRootNode); - ~CXmlOArchive(); - - void SetXmlNode(XmlNodeRef pNode); - XmlNodeRef GetXmlNode() const; - - // IArchive - bool operator()(bool& value, const char* name = "", const char* label = 0) override; - bool operator()(IString& value, const char* name = "", const char* label = 0) override; - bool operator()(IWString& value, const char* name = "", const char* label = 0) override; - bool operator()(float& value, const char* name = "", const char* label = 0) override; - bool operator()(double& value, const char* name = "", const char* label = 0) override; - bool operator()(int16& value, const char* name = "", const char* label = 0) override; - bool operator()(uint16& value, const char* name = "", const char* label = 0) override; - bool operator()(int32& value, const char* name = "", const char* label = 0) override; - bool operator()(uint32& value, const char* name = "", const char* label = 0) override; - bool operator()(int64& value, const char* name = "", const char* label = 0) override; - bool operator()(uint64& value, const char* name = "", const char* label = 0) override; - - bool operator()(int8& value, const char* name = "", const char* label = 0) override; - bool operator()(uint8& value, const char* name = "", const char* label = 0) override; - bool operator()(char& value, const char* name = "", const char* label = 0) override; - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0) override; - bool operator()(IContainer& ser, const char* name = "", const char* label = 0) override; - // ~IArchive - - using IArchive::operator(); - - private: - XmlNodeRef m_pRootNode; - }; -} - -#endif diff --git a/Code/CryEngine/CrySystem/ServiceNetwork.cpp b/Code/CryEngine/CrySystem/ServiceNetwork.cpp deleted file mode 100644 index 4ead14bcba..0000000000 --- a/Code/CryEngine/CrySystem/ServiceNetwork.cpp +++ /dev/null @@ -1,2035 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Service network implementation - - -#include "CrySystem_precompiled.h" -#include "ServiceNetwork.h" -#include "RemoteCommandHelpers.h" - -#include - -//----------------------------------------------------------------------------- - -// network system internal logging -#ifdef RELEASE - #define LOG_VERBOSE(level, txt, ...) -#else - #define LOG_VERBOSE(level, txt, ...) if (GetManager()->CheckVerbose(level)) { GetManager()->Log(txt, __VA_ARGS__); } -#endif - -//----------------------------------------------------------------------------- - -namespace -{ - union AddValueConv - { - struct - { - uint8 ip0, ip1, ip2, ip3; - } bytes; - - uint32 u32; - }; - - inline void TranslateAddress(const ServiceNetworkAddress& addr, AZ::AzSock::AzSocketAddress& outAddr) - { - AddValueConv addr_value; - addr_value.bytes.ip0 = addr.GetAddress().m_ip0; - addr_value.bytes.ip1 = addr.GetAddress().m_ip1; - addr_value.bytes.ip2 = addr.GetAddress().m_ip2; - addr_value.bytes.ip3 = addr.GetAddress().m_ip3; - - outAddr.SetAddress(addr_value.u32, addr.GetAddress().m_port); - } - - inline void TranslateAddress(const AZ::AzSock::AzSocketAddress& addr, ServiceNetworkAddress& outAddr) - { - AddValueConv addr_value; - - const AZSOCKADDR_IN* addrIn = reinterpret_cast(addr.GetTargetAddress()); - addr_value.u32 = AZ::AzSock::NetToHostLong((*addrIn).sin_addr.s_addr); - - outAddr = ServiceNetworkAddress( - addr_value.bytes.ip0, - addr_value.bytes.ip1, - addr_value.bytes.ip2, - addr_value.bytes.ip3, - addr.GetAddrPort()); - } - - inline bool SocketConnectionsFull(AZ::AzSock::AzSockError error) - { - return (error == AZ::AzSock::AzSockError::eASE_NO_ERROR || error == AZ::AzSock::AzSockError::eASE_EWOULDBLOCK || error == AZ::AzSock::AzSockError::eASE_EWOULDBLOCK_CONN); - } -} - -//----------------------------------------------------------------------------- - -CServiceNetworkMessage::CServiceNetworkMessage(const uint32 id, const uint32 size) - : m_refCount(1) - , m_size(size) - , m_id(id) -{ - // Allocate buffer memory - m_pData = CryModuleMalloc(size); -} - -CServiceNetworkMessage::~CServiceNetworkMessage() -{ - // Release the memory buffer - CryModuleFree(m_pData); - m_pData = NULL; -} - -uint32 CServiceNetworkMessage::GetSize() const -{ - return m_size; -} - -uint32 CServiceNetworkMessage::GetId() const -{ - return m_id; -} - -void* CServiceNetworkMessage::GetPointer() -{ - return m_pData; -} - -const void* CServiceNetworkMessage::GetPointer() const -{ - return m_pData; -} - -void CServiceNetworkMessage::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CServiceNetworkMessage::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -IDataReadStream* CServiceNetworkMessage::CreateReader() const -{ - return new CDataReadStreamFormMessage(this); -} - -//----------------------------------------------------------------------------- - -void CServiceNetworkConnection::Header::Swap() -{ - // if we are on big endian system swap data to LE - // NOTE: this is a little bit confusing so see how the eLittleEndian and eBigEndian is defined - SwapEndian(m_size, eLittleEndian); -} - -void CServiceNetworkConnection::InitHeader::Swap() -{ - // if we are on big endian system swap data to LE - // NOTE: this is a little bit confusing so see how the eLittleEndian and eBigEndian is defined - SwapEndian(m_tryCount, eLittleEndian); - SwapEndian(m_guid0, eLittleEndian); - SwapEndian(m_guid1, eLittleEndian); -} - -//----------------------------------------------------------------------------- - -CServiceNetworkConnection::CServiceNetworkConnection( - class CServiceNetwork* manager, - EEndpoint endpointType, - AZSOCKET socket, - const CryGUID& connectionID, - const ServiceNetworkAddress& localAddress, - const ServiceNetworkAddress& remoteAddress) - - : m_pManager(manager) - , m_connectionID(connectionID) - , m_socket(socket) - , m_localAddress(localAddress) - , m_remoteAddress(remoteAddress) - , m_endpointType(endpointType) - , m_state(eState_Initializing) - , m_sendQueueDataSize(0) - , m_receiveQueueDataSize(0) - , m_messageDataSentSoFar(0) - , m_messageDataReceivedSoFar(0) - , m_bCloseRequested(false) - , m_pCurrentReceiveMessage(NULL) - , m_messageReceiveLength(0) - , m_messageDummyReadLength(0) - , m_reconnectTryCount(0) - , m_bDisableCommunication(false) - , m_pSendedMessages(NULL) - , m_refCount(1) -{ - // put the socket back in non blocking mode - AZ::AzSock::SetSocketBlockingMode(m_socket, false); - - // reset stats - m_statsNumDataSend = 0; - m_statsNumDataReceived = 0; - m_statsNumPacketsSend = 0; - m_statsNumPacketsReceived = 0; - - // reset timers to values at the creation time - const uint64 currentNetworkTime = m_pManager->GetNetworkTime(); - m_lastReconnectTime = currentNetworkTime; - m_lastMessageReceivedTime = currentNetworkTime; - m_lastInitializationSendTime = currentNetworkTime; - - // make sure keep alive messages are sent as soon as possible - m_lastKeepAliveSendTime = currentNetworkTime - kKeepAlivePeriod; - - LOG_VERBOSE(3, "Connection(): local='%s', remote='%s', this=%p", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); -} - -CServiceNetworkConnection::~CServiceNetworkConnection() -{ - // in here we must be already closed! - CRY_ASSERT(m_state == eState_Closed); - - LOG_VERBOSE(3, "~Connection(): local='%s', remote='%s', this=%p", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // can happen - if (m_pCurrentReceiveMessage != NULL) - { - m_pCurrentReceiveMessage->Release(); - m_pCurrentReceiveMessage = NULL; - } -} - -void CServiceNetworkConnection::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CServiceNetworkConnection::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -void CServiceNetworkConnection::Close() -{ - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: close requested", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - m_bCloseRequested = true; - m_bDisableCommunication = true; -} - -void CServiceNetworkConnection::FlushAndClose(const uint32 timeout) -{ - if (!m_bDisableCommunication) - { - // We don't have any messages on the waiting list, we can close immediately - if (m_pSendQueue.empty()) - { - // Normal close - Close(); - } - else - { - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: flush and close requested", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // Disable communication layer so no more new messages can be transmitted - m_bDisableCommunication = true; - - // Register in the manager list of connections to close after sending queue is empty - m_pManager->RegisterForDeferredClose(*this, timeout); - } - } -} - -void CServiceNetworkConnection::FlushAndWait() -{ - // Disable communication layer so no more new messages can be transmitted - m_bDisableCommunication = true; - - // Wait for the connection to be empty - while (IsAlive() && !m_pSendQueue.empty()) - { - Sleep(1); - } - - // Resume communication layer - m_bDisableCommunication = false; -} - -const CryGUID& CServiceNetworkConnection::GetGUID() const -{ - return m_connectionID; -} - -const ServiceNetworkAddress& CServiceNetworkConnection::GetRemoteAddress() const -{ - return m_remoteAddress; -} - -const ServiceNetworkAddress& CServiceNetworkConnection::GetLocalAddress() const -{ - return m_localAddress; -} - -void CServiceNetworkConnection::Reset() -{ - if (m_state == eState_Initializing || m_state == eState_Valid) - { - // Close the socket (we wont be able to use it anyway) - if (AZ::AzSock::IsAzSocketValid(m_socket)) - { - AZ::AzSock::Shutdown(m_socket, SD_BOTH); - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - } - - // Reset messages buffers pointers - m_messageDataSentSoFar = 0; - m_messageDataReceivedSoFar = 0; - - // release current in-flight message - if (m_pCurrentReceiveMessage != NULL) - { - m_pCurrentReceiveMessage->Release(); - m_pCurrentReceiveMessage = NULL; - } - - // reset reconnection timer - m_lastMessageReceivedTime = m_pManager->GetNetworkTime(); - m_lastReconnectTime = m_pManager->GetNetworkTime(); - - // we are in the lost state now, we can try to reconnect - m_state = eState_Lost; - - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: LOST!", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } -} - -void CServiceNetworkConnection::Shutdown() -{ - // Close the socket - if (AZ::AzSock::IsAzSocketValid(m_socket)) - { - AZ::AzSock::Shutdown(m_socket, SD_BOTH); - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - } - - // Release all pending messages (they wont be sent anyway) - while (!m_pSendQueue.empty()) - { - CServiceNetworkMessage* message = m_pSendQueue.pop(); - message->Release(); - } - - // release current in-flight message - if (m_pCurrentReceiveMessage != NULL) - { - m_pCurrentReceiveMessage->Release(); - m_pCurrentReceiveMessage = NULL; - } - - // Reset internal send/recv state - m_messageDataSentSoFar = 0; - m_messageDataReceivedSoFar = 0; - - // Force the state - m_state = eState_Closed; - - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: CLOSED!", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); -} - -void CServiceNetworkConnection::Update() -{ - const uint64 currentNetworkTime = m_pManager->GetNetworkTime(); - - // We requested to close the socket - if (m_bCloseRequested) - { - m_bCloseRequested = false; - Shutdown(); - return; - } - - // State machine - switch (m_state) - { - // Connection is closed, nothing to do - case eState_Closed: - { - break; - } - - // We are still not initialized fully - case eState_Initializing: - { - // receive messages when waiting for connection - ProcessReceivingQueue(); - - // if we are a client send the connection initialization messages - if (m_endpointType == eEndpoint_Client) - { - // General timeout handling - if (HandleTimeout(currentNetworkTime)) - { - // do not send to often - if ((currentNetworkTime - m_lastInitializationSendTime) > kInitializationPerior) - { - // send the initialization message - if (TryInitialize()) - { - // message was sent, wait a moment before sending next one - m_lastInitializationSendTime = currentNetworkTime; - } - } - } - } - else if (m_endpointType == eEndpoint_Server) - { - // Server side when waiting for full initialization is sending the "keep alive" messages - // Note that we cannot time out on this end - ProcessKeepAlive(); - } - - break; - } - - // Connection is lost - case eState_Lost: - { - // if we are the client endpoint we can try to reconnect to the server - if (m_endpointType == eEndpoint_Client) - { - // do not try to reconnect to often (floods the network) - if ((currentNetworkTime - m_lastReconnectTime) > kReconnectTryPerior) - { - // reset timer - m_lastReconnectTime = currentNetworkTime; - - // try to reconnect - if (TryReconnect()) - { - // put the socket back in non blocking mode - AZ::AzSock::SetSocketBlockingMode(m_socket, false); - - // give us some slack with timeout after reconnection - m_lastMessageReceivedTime = currentNetworkTime; - - // yeah, we got reconnected, try to reinitialize the connection - m_messageDataReceivedSoFar = 0; - m_state = eState_Initializing; - } - } - } - else if (m_endpointType == eEndpoint_Server) - { - // wait for the reconnection timeout - if ((currentNetworkTime - m_lastMessageReceivedTime) > hReconnectTimeOut) - { - // reconnection time out has occurred - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: reconnection timeout", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // Close - Shutdown(); - } - } - - break; - } - - // Valid connection - case eState_Valid: - { - // Is it time to send a keep alive message? - ProcessKeepAlive(); - - // Process the queue of messages - ProcessSendingQueue(); - ProcessReceivingQueue(); - - // General timeout handling - if (m_endpointType == eEndpoint_Client) - { - HandleTimeout(currentNetworkTime); - } - - break; - } - - default: - { - // should not happen - break; - } - } -} - -bool CServiceNetworkConnection::HandleTimeout(const uint64 currentNetworkTime) -{ - // Connections never time out when there is a debugger attached -#if defined(WIN32) || defined(WIN64) - if (IsDebuggerPresent()) - { - // connection is still alive - return true; - } -#endif - - // Connection time out when there is a long time without any activity from server side (no keep alive or other messages) - const uint64 timeSinceLastMessage = currentNetworkTime - m_lastMessageReceivedTime; - if (timeSinceLastMessage > kTimeout) - { - // Connection has timed out - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: timed out", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // Put in lost state, wait a while before reconnecting - m_lastReconnectTime = currentNetworkTime; - m_state = eState_Lost; - - // Close the socket now - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - - // Connection was lost - return false; - } - - // Connection still alive - return true; -} - -bool CServiceNetworkConnection::TryInitialize() -{ - // This is sent only be clients trying to establish connection with server - // Connection ID is sent over to the server so he can easily identify re connections (even when port changes) - - // Initialization data header - InitHeader header; - header.m_cmd = eCommand_Initialize; - header.m_pad0 = 0; - header.m_pad1 = 0; - header.m_pad2 = 0; - header.m_tryCount = m_reconnectTryCount; - header.m_guid0 = m_connectionID.lopart; - header.m_guid1 = m_connectionID.hipart; - - // Swap the endianess in header (for sending) - header.Swap(); - - // Try send - const bool autoHandleErrors = false; // we do not need errors here - const uint32 dataLeft = sizeof(header) - m_messageDataSentSoFar; - const uint32 ret = TrySend(&header, dataLeft, autoHandleErrors); - m_messageDataSentSoFar += ret; - - // Full packet was sent - if (m_messageDataSentSoFar == sizeof(header)) - { - // We sent the initialization message - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: init message sent, try counter=%d", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_reconnectTryCount); - - // we sent the initialization packet, reset - m_messageDataSentSoFar = 0; - return true; - } - - // Still not valid - return false; -} - -bool CServiceNetworkConnection::TryReconnect() -{ - // We can't reconnect with disabled communication - if (m_bDisableCommunication) - { - return false; - } - - // Create new socket if needed - if (!AZ::AzSock::IsAzSocketValid(m_socket)) - { - m_socket = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(m_socket)) - { - // We sent the initialization message - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: failed to recreate socket", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - return false; - } - } - - // Translate remote address - AZ::AzSock::AzSocketAddress addr; - TranslateAddress(m_remoteAddress, addr); - - // When reconnecting always use the blocking mode - AZ::AzSock::SetSocketBlockingMode(m_socket, true); - - // every time we reconnect increment the internal counter so the receiving end (server) - // will be able to identity the up-to-date connection (and discard the older one) - CRY_ASSERT(m_endpointType == eEndpoint_Client); - m_reconnectTryCount += 1; - - // Connect (blocking) - const int result = AZ::AzSock::Connect(m_socket, addr); - if (result == 0) - { - // Spew to log (important info) - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: SUCCESSFULLY RECONNECTED", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // When connected put socket in the non blocking mode - AZ::AzSock::SetSocketBlockingMode(m_socket, false); - - // connected! - return true; - } - - // not connection, should not happen often - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: failed to reconnect", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // still not connected - return false; -} - -void CServiceNetworkConnection::SendKeepAlive(const uint64 currentNetworkTime) -{ - // Keep alive message is just ONE byte (makes it easier) - uint8 message = eCommand_KeepAlive; - if (1 == TrySend(&message, 1, false)) - { - // Throttle the sending - m_lastKeepAliveSendTime = currentNetworkTime; - - // At high verbose level we need even this :) - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: keep alive SENT", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } -} - -void CServiceNetworkConnection::ProcessSendingQueue() -{ - // Get the top message from the send queue - if (NULL == m_pSendedMessages) - { - m_pSendedMessages = m_pSendQueue.pop(); - if (NULL == m_pSendedMessages) - { - return; - } - } - - // Get the size of the data to transmit - const uint32 messageSize = m_pSendedMessages->GetSize(); - const uint32 headerSize = sizeof(Header); - - // Nothing sent yet, send header - if (m_messageDataSentSoFar < headerSize) - { - // prepare header - endian safe - Header header; - header.m_cmd = eCommand_Data; - header.m_size = messageSize; - - // Swap the header for reading - header.Swap(); - - // send the header - const uint32 dataLeft = headerSize - m_messageDataSentSoFar; - const uint32 sent = TrySend((const char*)&header + m_messageDataSentSoFar, dataLeft, true); - m_messageDataSentSoFar += sent; - } - - // Send message data - const uint32 endOfDataOffset = messageSize + headerSize; - if (m_messageDataSentSoFar >= headerSize && m_messageDataSentSoFar < endOfDataOffset) - { - // send and advance - const uint32 dataLeft = endOfDataOffset - m_messageDataSentSoFar; - const uint32 dataOffset = m_messageDataSentSoFar - headerSize; - const uint32 sent = TrySend((const char*)m_pSendedMessages->GetPointer() + dataOffset, dataLeft, true); - m_messageDataSentSoFar += sent; - } - - // All the data from the message was sent, release the message from this queue - // Note: this message may still be in some other sent queues for connections - if (m_messageDataSentSoFar >= endOfDataOffset) - { - // At high verbose level we need even this :) - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: message ID %d (size=%d) removed from queue", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_pSendedMessages->GetId(), - m_pSendedMessages->GetSize()); - - CryInterlockedAdd(&m_sendQueueDataSize, -(int)m_pSendedMessages->GetSize()); - - // stats (not collected in release builds) -#ifndef RELEASE - CryInterlockedIncrement((volatile int*) &m_statsNumPacketsSend); -#endif - - // release local message reference - m_pSendedMessages->Release(); - m_pSendedMessages = NULL; - - // rewind to zero to indicate fresh message - m_messageDataSentSoFar = 0; - } -} - -void CServiceNetworkConnection::ProcessKeepAlive() -{ - const uint64 currentNetworkTime = m_pManager->GetNetworkTime(); - if ((currentNetworkTime - m_lastKeepAliveSendTime) > kKeepAlivePeriod) - { - // Well, if we are in the middle of something make sure we do not interrupt it with KeepAlive - if (m_messageDataSentSoFar == 0) - { - SendKeepAlive(currentNetworkTime); - } - } -} - -void CServiceNetworkConnection::ProcessReceivingQueue() -{ - // To much data already, do not process - const uint32 kReceivedDataLimit = m_pManager->GetReceivedDataQueueLimit(); - if (m_receiveQueueDataSize > kReceivedDataLimit) - { - return; - } - - // Internal offset - const uint32 kOffsetHeader = 1; - const uint32 kOffsetData = 5; - - // Dummy receive - while (m_messageDummyReadLength > 0) - { - // batch size - const uint32 kTempBufferSize = 256; - - // read dummy data - uint8 tempBuffer[ kTempBufferSize ]; - const uint32 maxRead = min(kTempBufferSize, m_messageDummyReadLength); - const uint32 readCount = TryReceive(tempBuffer, maxRead, false); - m_messageDummyReadLength -= readCount; - - // got less - if (readCount < maxRead) - { - break; - } - } - - // Do not process normal messages until we receive all of the bogus data - if (m_messageDummyReadLength > 0) - { - return; - } - - // First byte - header - if (m_messageDataReceivedSoFar == 0) - { - // message header, read type - uint8 messageType = 0; - const int result = TryReceive(&messageType, 1, true); - if (result == 1) - { - // keep alive received, if we are not yet fully initialized it's the signal that we are :) - if (messageType == eCommand_KeepAlive) - { - // we got confirmed by server - if (m_state == eState_Initializing) - { - // change state - CRY_ASSERT(m_endpointType == eEndpoint_Client); - m_state = eState_Valid; - - // At high verbose level we need even this :) - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: connection confirmed by server", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } - else - { - // At low-level verbose log even this - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: keep alive RECEIVED", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } - - // update the keep alive data timer - m_lastKeepAliveSendTime = m_pManager->GetNetworkTime(); - m_lastMessageReceivedTime = m_pManager->GetNetworkTime(); - } - else if (messageType == eCommand_Data) - { - // wait for the message length - m_messageReceiveLength = 0; - m_messageDataReceivedSoFar = kOffsetHeader; - m_lastMessageReceivedTime = m_pManager->GetNetworkTime(); - - // At low-level verbose log even this - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: got data message header", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } - else if (messageType == eCommand_Initialize) - { - // let the system process the message - m_messageDummyReadLength = sizeof(InitHeader) - 1; - - // At low-level verbose log even this - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: outdated initheader received", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - } - else - { - // Serious error - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: received invalid command (%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - messageType); - - // reset the connection - Reset(); - } - } - } - - // Message length - if (m_messageDataReceivedSoFar >= kOffsetHeader && m_messageDataReceivedSoFar < kOffsetData) - { - // receive the message length - const uint32 dataOffset = m_messageDataReceivedSoFar - kOffsetHeader; - const uint32 dataLeft = sizeof(uint32) - dataOffset; - const uint32 len = TryReceive((char*)&m_messageReceiveLength + dataOffset, dataLeft, true); - m_messageDataReceivedSoFar += len; - - // Update last message time - if (len > 0) - { - m_lastMessageReceivedTime = m_pManager->GetNetworkTime(); - } - - // full length received - if (m_messageDataReceivedSoFar == 5) - { - // Swap endianess (for BE platforms) - // NOTE: if this is a little bit confusing, see how the eLittleEndian and eBigEndian are defined - SwapEndian(m_messageReceiveLength, eLittleEndian); - - // Sanity check on the message size - if (m_messageReceiveLength > kMaximumMessageSize) - { - // Serious error - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: unsupported message size (%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_messageReceiveLength); - - Reset(); - } - else if (m_messageReceiveLength > 0) - { - // Create new message that we will add the data into - CRY_ASSERT(m_pCurrentReceiveMessage == NULL); - m_pCurrentReceiveMessage = static_cast< CServiceNetworkMessage* >(m_pManager->AllocMessageBuffer(m_messageReceiveLength)); - CRY_ASSERT(m_pCurrentReceiveMessage != NULL); - - // Serious error - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: created receive buffer ID %d, (size=%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_pCurrentReceiveMessage ? m_pCurrentReceiveMessage->GetId() : 0, - m_messageReceiveLength); - } - } - } - - // Message data - if (m_messageDataReceivedSoFar >= kOffsetData) - { - CRY_ASSERT(m_pCurrentReceiveMessage != NULL); - PREFAST_ASSUME(m_pCurrentReceiveMessage); - - // Message fully received, put in the receive queue (at the end!) - const uint32 dataOffset = m_messageDataReceivedSoFar - kOffsetData; - const uint32 dataLeft = m_pCurrentReceiveMessage->GetSize() - dataOffset; - const uint32 len = TryReceive((char*)m_pCurrentReceiveMessage->GetPointer() + dataOffset, dataLeft, true); - m_messageDataReceivedSoFar += len; - - // connection got lost - if (m_state == eState_Lost) - { - return; - } - - // Update last message time - if (len > 0) - { - m_lastMessageReceivedTime = m_pManager->GetNetworkTime(); - } - - // Full message received! - if (m_messageDataReceivedSoFar == (kOffsetData + m_pCurrentReceiveMessage->GetSize())) - { - // Serious error - LOG_VERBOSE(2, "Connection local='%s', remote='%s', this=%p: full message received(%d), adding to queue", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_pCurrentReceiveMessage->GetSize()); - - // Put in the receive queue, only if no communication is disabled - if (m_bDisableCommunication) - { - m_pCurrentReceiveMessage->Release(); - } - else - { - m_pReceiveQueue.push(m_pCurrentReceiveMessage); - } - - // Stats (not collected in release builds) -#ifndef RELEASE - CryInterlockedIncrement((volatile int*) &m_statsNumPacketsReceived); -#endif - - // Reset - m_pCurrentReceiveMessage = NULL; - m_messageDataReceivedSoFar = 0; - } - } -} - -uint32 CServiceNetworkConnection::TrySend(const void* dataBuffer, uint32 dataSize, bool autoHandleErrors /*=true*/) -{ - // Send the data - const int ret = AZ::AzSock::Send(m_socket, (const char*) dataBuffer, dataSize, 0); - if (AZ::AzSock::SocketErrorOccured(ret)) - { - // We would block, that's not an error - if (ret == static_cast(AZ::AzSock::AzSockError::eASE_EWOULDBLOCK)) - { - return 0; - } - - // Report connection problems - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: send() error: %d", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - ret); - - // Put connection in the lost state - if (autoHandleErrors) - { - Reset(); - } - - // Nothing was sent (according to our logic) - return 0; - } - - // Update stats -#ifndef RELEASE - CryInterlockedAdd((volatile int*) &m_statsNumDataSend, ret); -#endif - - // Return the true amount of data sent - return ret; -} - -uint32 CServiceNetworkConnection::TryReceive(void* dataBuffer, uint32 dataSize, bool autoHandleErrors) -{ - // Send the data - const int ret = AZ::AzSock::Recv(m_socket, (char*) dataBuffer, dataSize, 0); - if (AZ::AzSock::SocketErrorOccured(ret)) - { - // We would block, that's not an error - if (ret == static_cast(AZ::AzSock::AzSockError::eASE_EWOULDBLOCK)) - { - return 0; - } - - // Connection was closed - if (ret == static_cast(AZ::AzSock::AzSockError::eASE_ECONNRESET)) - { - // Report connection problems - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: CLOSED BY PEER", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // Shutdown socket - Shutdown(); - return 0; - } - - // Report connection problems - LOG_VERBOSE(1, "Connection local='%s', remote='%s', this=%p: recv() error: %d", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - ret); - - // Put connection in the lost state - if (autoHandleErrors) - { - Reset(); - } - - // Nothing was sent (according to our logic) - return 0; - } - - // Update stats -#ifndef RELEASE - CryInterlockedAdd((volatile int*) &m_statsNumDataReceived, ret); -#endif - - // Return the true amount of data sent - return ret; -} - -bool CServiceNetworkConnection::SendMsg(IServiceNetworkMessage* message) -{ - // Invalid message - if (NULL == message || message->GetSize() == 0) - { - return false; - } - - // Communication layer is disabled, not possible to send any more messages - if (m_bDisableCommunication) - { - return false; - } - - // Process data size limits - { - const uint32 sizeAfterThisMessage = m_sendQueueDataSize + message->GetSize(); - const uint32 sendQueueLimit = m_pManager->GetSendDataQueueLimit(); - if (sizeAfterThisMessage > sendQueueLimit) - { - // Report connection problems - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: to much data on send queue", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this); - - // To much data on the queue already, we will not be sending this message - return false; - } - - // Keep the local reference so the source data does not get deleted - message->AddRef(); - - // Update the queue data size - CryInterlockedAdd(&m_sendQueueDataSize, message->GetSize()); - - // Append the message to the sending queue - m_pSendQueue.push(static_cast< CServiceNetworkMessage* >(message)); - } - - // Well, we can't tell any more than that - return true; -} - -IServiceNetworkMessage* CServiceNetworkConnection::ReceiveMsg() -{ - // Anything on the queue ? - IServiceNetworkMessage* message = NULL; - if (!m_pReceiveQueue.empty()) - { - message = m_pReceiveQueue.pop(); - - // Report connection problems - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: message ID %d (size=%d) popped by receive end", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - message->GetId(), - message->GetSize()); - } - - return message; -} - -bool CServiceNetworkConnection::IsAlive() const -{ - return m_state != eState_Closed; -} - -uint32 CServiceNetworkConnection::GetMessageSendCount() const -{ - return m_statsNumPacketsSend; -} - -uint32 CServiceNetworkConnection::GetMessageReceivedCount() const -{ - return m_statsNumPacketsReceived; -} - -uint64 CServiceNetworkConnection::GetMessageSendDataSize() const -{ - return m_statsNumDataSend; -} - -uint64 CServiceNetworkConnection::GetMessageReceivedDataSize() const -{ - return m_statsNumDataReceived; -} - -bool CServiceNetworkConnection::HandleReconnect(AZSOCKET socket, const uint32 tryCount) -{ - CRY_ASSERT(m_endpointType == eEndpoint_Server); - - // connection is older - if (tryCount < m_reconnectTryCount) - { - LOG_VERBOSE(3, "Connection local='%s', remote='%s', this=%p: reconnection request OLDER (%d<%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - tryCount, - m_reconnectTryCount); - - return false; - } - - // should not happen - if (tryCount == m_reconnectTryCount) - { - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: reconnection request COLLISION (%d==%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - tryCount, - m_reconnectTryCount); - - return false; - } - - // newer connection, close current socket - AZ::AzSock::Shutdown(m_socket, SD_BOTH); - AZ::AzSock::CloseSocket(m_socket); - - // reset send/receive counters (will resend last message from the queue) - m_messageDataReceivedSoFar = 0; - m_messageDataSentSoFar = 0; - - // Set new socket and update reconnection counter - m_socket = socket; - m_reconnectTryCount = tryCount; - - // revive the connection - m_state = eState_Valid; - - LOG_VERBOSE(0, "Connection local='%s', remote='%s', this=%p: successfull reconnection with counter (%d)", - m_localAddress.ToString().c_str(), - m_remoteAddress.ToString().c_str(), - (UINT_PTR) this, - m_reconnectTryCount); - - // processed - return true; -} - -//----------------------------------------------------------------------------- - -CServiceNetworkListener::CServiceNetworkListener(CServiceNetwork* pManager, AZSOCKET socket, const ServiceNetworkAddress& address) - : m_pManager(pManager) - , m_socket(socket) - , m_localAddress(address) - , m_closeRequestReceived(false) - , m_refCount(1) -{ - LOG_VERBOSE(3, "Listener() local='%s', this=%p", - m_localAddress.ToString().c_str(), - (UINT_PTR) this); -} - -CServiceNetworkListener::~CServiceNetworkListener() -{ - AZ_Assert(!AZ::AzSock::IsAzSocketValid(m_socket), "AZSocket still valid on ServiceNetworkListener destructor"); - - LOG_VERBOSE(3, "~Listener() local='%s', this=%p", - m_localAddress.ToString().c_str(), - (UINT_PTR) this); -} - -void CServiceNetworkListener::Update() -{ - // We requested to close this listener - if (m_closeRequestReceived) - { - LOG_VERBOSE(3, "Listener local='%s', this=%p: closing due to request", - m_localAddress.ToString().c_str(), - (UINT_PTR) this); - - // Close the socket - if (AZ::AzSock::IsAzSocketValid(m_socket)) - { - AZ::AzSock::CloseSocket(m_socket); - m_socket = AZ_SOCKET_INVALID; - } - - // Close all connections - for (TConnectionList::iterator it = m_pLocalConnections.begin(); - it != m_pLocalConnections.end(); ++it) - { - (*it)->Close(); - (*it)->Release(); - } - - m_pLocalConnections.clear(); - m_closeRequestReceived = false; - - return; - } - - // Process connection requests - ProcessIncomingConnections(); - - // Service the pending connection - ProcessPendingConnections(); - - // Remove any local connection that got dead - for (TConnectionList::iterator it = m_pLocalConnections.begin(); - it != m_pLocalConnections.end(); /*++it*/) - { - if (!(*it)->IsAlive()) - { - LOG_VERBOSE(2, "Listener local='%s', this=%p: removing dead connection '%s' (%p)", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - (*it)->GetRemoteAddress().ToString().c_str(), - (UINT_PTR) (*it)); - - (*it)->Release(); - it = m_pLocalConnections.erase(it); - } - else - { - ++it; - } - } -} - -const ServiceNetworkAddress& CServiceNetworkListener::GetLocalAddress() const -{ - return m_localAddress; -} - -uint32 CServiceNetworkListener::GetConnectionCount() const -{ - // not safe ? - return m_pLocalConnections.size(); -} - -IServiceNetworkConnection* CServiceNetworkListener::Accept() -{ - // Look for any connection on the list that is in the "initialized" state - { - CryAutoLock lock(m_accessLock); - for (TConnectionList::iterator it = m_pLocalConnections.begin(); - it != m_pLocalConnections.end(); ++it) - { - // we are looking for connections in the "eState_Initializing" which mean that they are valid but not yet recognized by the outside world - CServiceNetworkConnection* con = (*it); - if (con->m_state == CServiceNetworkConnection::eState_Initializing) - { - LOG_VERBOSE(1, "Listener local='%s', this=%p: accepting connection from '%s' (%p)", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - con->GetRemoteAddress().ToString().c_str(), - (UINT_PTR) con); - - // switch state to "valid" - con->m_state = CServiceNetworkConnection::eState_Valid; - - // when returning outside increment the ref count (we still want to keep our internal reference) - con->AddRef(); - return con; - } - } - } - - // No pending connections - return NULL; -} - -bool CServiceNetworkListener::IsAlive() const -{ - return AZ::AzSock::IsAzSocketValid(m_socket); -} - -void CServiceNetworkListener::AddRef() -{ - CryInterlockedIncrement(&m_refCount); -} - -void CServiceNetworkListener::Release() -{ - if (0 == CryInterlockedDecrement(&m_refCount)) - { - delete this; - } -} - -void CServiceNetworkListener::Close() -{ - LOG_VERBOSE(2, "Listener local='%s', this=%p: close requested", - m_localAddress.ToString().c_str(), - (UINT_PTR) this); - - m_closeRequestReceived = true; -} - -void CServiceNetworkListener::ProcessIncomingConnections() -{ - // Accept all possible connections as soon as possible (the connect side is blocking) - for (;; ) - { - // Get the pending connection from TCP/IP layers - AZ::AzSock::AzSocketAddress remoteAddrInet; - AZSOCKET sock = AZ::AzSock::Accept(m_socket, remoteAddrInet); - - // No more connections - if (SocketConnectionsFull(AZ::AzSock::AzSockError(sock))) - { - break; - } - - // Different error - if (!AZ::AzSock::IsAzSocketValid(sock)) - { - // Connection has other problems - LOG_VERBOSE(1, "Listener local='%s', this=%p: accept() error: %d", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - (int)sock); - - break; - } - - // Get the remote address - ServiceNetworkAddress remoteAddress; - TranslateAddress(remoteAddrInet, remoteAddress); - - // Any way create a new pending connection information - PendingConnection* pendingConnection = new PendingConnection; - pendingConnection->m_remoteAddress = remoteAddress; - pendingConnection->m_dataReceivedSoFar = 0; - pendingConnection->m_socket = sock; - - // Connection has other problems - LOG_VERBOSE(2, "Listener local='%s', this=%p: new pending connection from '%s'", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - remoteAddress.ToString().c_str()); - - // Add to list (not locked because its used only from net thread) - m_pPendingConnections.push_back(pendingConnection); - } -} - -void CServiceNetworkListener::ProcessPendingConnections() -{ - // Process only pending connections, not locked because its used only from net thread - for (TPendingConnectionList::iterator it = m_pPendingConnections.begin(); - it != m_pPendingConnections.end(); /*++it*/) - { - PendingConnection& con = *(*it); - - // Read the incoming data - CRY_ASSERT(con.m_dataReceivedSoFar < sizeof(con.m_initHeader)); - const uint32 dataLeft = sizeof(con.m_initHeader) - con.m_dataReceivedSoFar; - const int size = AZ::AzSock::Recv(con.m_socket, (char*)&con.m_initHeader + con.m_dataReceivedSoFar, dataLeft, 0); - - // The only no-action case: no data yet - if (size == static_cast(AZ::AzSock::AzSockError::eASE_EWOULDBLOCK)) - { - ++it; - continue; - } - - // Something more important - if (AZ::AzSock::SocketErrorOccured(size)) - { - // well, some problem on the way, remove the pending connection from the list (client will resend) - LOG_VERBOSE(1, "Listener local='%s', this=%p: pending connection from '%s' lost: %d", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - con.m_remoteAddress.ToString().c_str(), - (int)size); - } - else - { - // data was received - CRY_ASSERT(size < (int)dataLeft); - con.m_dataReceivedSoFar += size; - - // still not enough data - if (con.m_dataReceivedSoFar < sizeof(con.m_initHeader)) - { - ++it; - continue; - } - - // validate header - if (con.m_initHeader.m_cmd == CServiceNetworkConnection::eCommand_Initialize) - { - // Swap the header after reading - con.m_initHeader.Swap(); - - // Extract the connection ID - const CryGUID connectionId = CryGUID::Construct(con.m_initHeader.m_guid0, con.m_initHeader.m_guid1); - - // try find existing connection with the same connection GUID (reconnection) - CServiceNetworkConnection* existingConnection = NULL; - for (TConnectionList::const_iterator jt = m_pLocalConnections.begin(); - jt != m_pLocalConnections.end(); ++jt) - { - if ((*jt)->GetGUID() == connectionId) - { - existingConnection = *jt; - break; - } - } - - // if existing connection was found that we probably were trying to reconnect - if (existingConnection != NULL) - { - // we already have this connection on our list and we got reconnected with the some GUID - // this usually means that the client has lost communication with server for some time - LOG_VERBOSE(1, "Listener local='%s', this=%p: reconnection from '%s'", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - con.m_remoteAddress.ToString().c_str()); - - // substitute the connection with newer one (if it is really newer) - if (!existingConnection->HandleReconnect(con.m_socket, con.m_initHeader.m_tryCount)) - { - // well, we didn't use this connect (it was older than the current one, close it) - AZ::AzSock::Shutdown(con.m_socket, SD_BOTH); - AZ::AzSock::CloseSocket(con.m_socket); - } - else - { - // add to global list of active debug connections (so we can start receiving data) - m_pManager->RegisterConnection(*existingConnection); - } - } - else - { - // no previous connection registered, create one now - CServiceNetworkConnection* newConnection = new CServiceNetworkConnection( - m_pManager, - CServiceNetworkConnection::eEndpoint_Server, // this connection is created from listener side which is considered the "server" - con.m_socket, - connectionId, - m_localAddress, - con.m_remoteAddress); - - // this is the first time we see this connection on set the proper connection counter - newConnection->m_reconnectTryCount = con.m_initHeader.m_tryCount; - - // happy moment, log it - LOG_VERBOSE(0, "Listener local='%s', this=%p: confirmed connection from '%s'", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - con.m_remoteAddress.ToString().c_str()); - - // make sure connection is in valid state - CRY_ASSERT(newConnection->m_state == CServiceNetworkConnection::eState_Initializing); - - // add to local list - CRY_ASSERT(newConnection->IsInitialized() == false); - { - CryAutoLock lock(m_accessLock); - m_pLocalConnections.push_back(newConnection); - newConnection->AddRef(); - } - - // add to global list of active debug connections (so we can start receiving data) - m_pManager->RegisterConnection(*newConnection); - } - } - else - { - // well, some problem on the way, remove the pending connection from the list (client will resend) - LOG_VERBOSE(0, "Listener local='%s', this=%p: invalid connection data received from '%s'", - m_localAddress.ToString().c_str(), - (UINT_PTR) this, - con.m_remoteAddress.ToString().c_str()); - - // close the socket - AZ::AzSock::Shutdown(con.m_socket, SD_BOTH); - AZ::AzSock::CloseSocket(con.m_socket); - } - } - - // any way, delete the connection from the pending list - delete (*it); - it = m_pPendingConnections.erase(it); - } -} - -//----------------------------------------------------------------------------- - -CServiceNetwork::CServiceNetwork() - : m_networkTime(0) - , m_bExitRequested(false) - , m_bufferID(1) -{ - // Create the CVAR - m_pVerboseLevel = gEnv->pConsole->RegisterInt("net_debugVerboseLevel", 0, VF_DEV_ONLY); - - // Send/receive Queue size limits - m_pReceiveDataQueueLimit = gEnv->pConsole->RegisterInt("net_receiveQueueSize", 20 << 20, VF_DEV_ONLY); - m_pSendDataQueueLimit = gEnv->pConsole->RegisterInt("net_sendQueueSize", 5 << 20, VF_DEV_ONLY); - - // Reinitialize the random number generator with independent seed value - m_guidGenerator.Seed((uint32)GetNetworkTime()); - - // Start thread - m_pThread = new TServiceNetworkThread(); - m_pThread->Start(*this); -} - -CServiceNetwork::~CServiceNetwork() -{ - // Signal the network thread to stop - if (NULL != m_pThread) - { - m_pThread->Cancel(); - m_pThread->WaitForThread(); - delete m_pThread; - } - - // Release all closeing connections - for (TConnectionsToCloseArray::const_iterator it = m_connectionsToClose.begin(); - it != m_connectionsToClose.end(); ++it) - { - (*it).pConnection->Release(); - } - - // Release and close all connections - for (TConnectionArray::const_iterator it = m_pConnections.begin(); - it != m_pConnections.end(); ++it) - { - (*it)->Close(); - (*it)->Release(); - } - - // Release all listeners - for (TListenerArray::const_iterator it = m_pListeners.begin(); - it != m_pListeners.end(); ++it) - { - (*it)->Release(); - } - - // Release the CVars - SAFE_RELEASE(m_pVerboseLevel); - SAFE_RELEASE(m_pReceiveDataQueueLimit); - SAFE_RELEASE(m_pSendDataQueueLimit); -} - -#ifndef RELEASE -bool CServiceNetwork::CheckVerbose(const uint32 level) const -{ - const int verboseLevel = m_pVerboseLevel->GetIVal(); - return (int)level < verboseLevel; -} - -void CServiceNetwork::Log(const char* txt, ...) const -{ - // format the print buffer - char buffer[512]; - va_list ap; - va_start(ap, txt); - vsprintf_s(buffer, sizeof(buffer), txt, ap); - va_end(ap); - - // pass to log - gEnv->pLog->LogAlways(buffer); -} -#endif - -void CServiceNetwork::Cancel() -{ - m_bExitRequested = true; - - if (m_pThread) - { - m_pThread->Stop(); - } -} - -void CServiceNetwork::Run() -{ - CryThreadSetName(THREADID_NULL, "ServiceNetworkThread"); - -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(ServiceNetwork_cpp) -#endif - - TListenerArray updatingListeners; - TConnectionArray updatingConnections; - TConnectionsToCloseArray updatingConnectionsToClose; - - // Process messages - while (!m_bExitRequested) - { - // Well, copy the lists for the duration of update - { - CryAutoLock lock(m_accessMutex); - updatingListeners = m_pListeners; - updatingConnections = m_pConnections; - updatingConnectionsToClose = m_connectionsToClose; - } - - if ((!gEnv) || (!gEnv->pTimer)) - { - Sleep(5); - continue; - } - - // Update network time - m_networkTime = gEnv->pTimer->GetAsyncTime().GetMilliSecondsAsInt64(); - - // Process the listeners (accepts and pending connections) - for (TListenerArray::const_iterator it = updatingListeners.begin(); - it != updatingListeners.end(); ++it) - { - (*it)->Update(); - - // Remove dead listeners from the main list - if (!(*it)->IsAlive()) - { - CryAutoLock lock(m_accessMutex); - - // remove from array - TListenerArray::iterator jt = std::find(m_pListeners.begin(), m_pListeners.end(), *it); - CRY_ASSERT(jt != m_pListeners.end()); - m_pListeners.erase(jt); - - // release internal reference (may delete object if no longer used on main thread) - (*it)->Release(); - } - } - - - // Process the closing connections - for (TConnectionsToCloseArray::const_iterator it = updatingConnectionsToClose.begin(); - it != updatingConnectionsToClose.end(); ++it) - { - const ConnectionToClose& info = *it; - - bool bTimeout = false; - if (info.maxWaitTime && m_networkTime > info.maxWaitTime) - { - bTimeout = true; - } - - // should we close it now ? - if (bTimeout || !it->pConnection->IsAlive() || it->pConnection->IsSendingQueueEmpty()) - { - info.pConnection->Close(); - info.pConnection->Release(); - - // erase from list - { - CryAutoLock lock(m_accessMutex); - for (TConnectionsToCloseArray::iterator jt = m_connectionsToClose.begin(); - jt != m_connectionsToClose.end(); ++jt) - { - if ((*jt).pConnection == info.pConnection) - { - m_connectionsToClose.erase(jt); - break; - } - } - } - } - } - - // Process the connections - for (TConnectionArray::const_iterator it = updatingConnections.begin(); - it != updatingConnections.end(); ++it) - { - (*it)->Update(); - - // Remove dead connections from the main list - if (!(*it)->IsAlive()) - { - CryAutoLock lock(m_accessMutex); - - // remove from array - TConnectionArray::iterator jt = std::find(m_pConnections.begin(), m_pConnections.end(), *it); - CRY_ASSERT(jt != m_pConnections.end()); - m_pConnections.erase(jt); - - // release internal reference (may delete object if no longer used on main thread) - (*it)->Release(); - } - } - - // Internal delay - // TODO: this is guess work right now - Sleep(5); - } -} - -void CServiceNetwork::SetVerbosityLevel(const uint32 level) -{ - // propagate the value to CVar (so it is consistent across the engine) - if (NULL != m_pVerboseLevel) - { - m_pVerboseLevel->Set((int)level); - } -} - -IServiceNetworkMessage* CServiceNetwork::AllocMessageBuffer(const uint32 size) -{ - // Allocate message with new ID - const uint32 bufferID = CryInterlockedIncrement(&m_bufferID); - return new CServiceNetworkMessage(bufferID, size); -} - -IDataWriteStream* CServiceNetwork::CreateMessageWriter() -{ - return new CDataWriteStreamBuffer(); -} - -IDataReadStream* CServiceNetwork::CreateMessageReader(const void* pData, const uint32 dataSize) -{ - if (pData != NULL && dataSize > 0) - { - return new CDataReadStreamMemoryBuffer(pData, dataSize); - } - - return NULL; -} - -ServiceNetworkAddress CServiceNetwork::GetHostAddress(const string& addressString, uint16 optionalPort /*=0*/) const -{ - // cut the address into base and port part - string hostname = addressString.c_str(); - - const int pos = addressString.rfind(':'); - if (pos != -1) - { - // substitute the port number from the part in string - if (optionalPort == 0) - { - const char* portNumberStr = addressString.c_str() + pos + 1; - optionalPort = (uint16)atoi(portNumberStr); - } - - // remove the port part from base address - hostname = addressString.Left(pos); - } - - AZ::AzSock::AzSocketAddress socketAddress; - socketAddress.SetAddress(hostname.c_str(), optionalPort); - - // log on hi verbose mode - LOG_VERBOSE(3, "GetHostAddress(%s) -> %s", addressString.c_str(), socketAddress.GetAddress().c_str()); - - // format the network address - ServiceNetworkAddress out; - TranslateAddress(socketAddress, out); - return out; -} - -IServiceNetworkListener* CServiceNetwork::CreateListener(uint16 localPort) -{ - // Create socket - AZSOCKET createdSocket = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(createdSocket)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): socket() failed: %s", localPort, AZ::AzSock::GetStringForError(createdSocket)); - return NULL; - } - - // Disable merging of small blocks to fight high latency connection - // NOTE: consoles support this mode by default - const int ret3 = AZ::AzSock::EnableTCPNoDelay(createdSocket, true); - if (AZ::AzSock::SocketErrorOccured(ret3)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): setsockopt() failed: %s", localPort, AZ::AzSock::GetStringForError(ret3)); - - AZ::AzSock::CloseSocket(createdSocket); - return NULL; - } - - // Reuse address - { - const int optRet = AZ::AzSock::SetSocketOption(createdSocket, AZ::AzSock::AzSocketOption::REUSEADDR, true); - if (AZ::AzSock::SocketErrorOccured(optRet)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): setsockopt() (reuse) failed", localPort); - - // cleanup - AZ::AzSock::CloseSocket(createdSocket); - return NULL; - } - } - - // Put the listener socket in the non blocking mode - if (!AZ::AzSock::SetSocketBlockingMode(createdSocket, false)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): setsockopt() failed", localPort); - - // cleanup - AZ::AzSock::CloseSocket(createdSocket); - return NULL; - } - - // Setup local bind address - AZ::AzSock::AzSocketAddress service; - service.SetAddrPort(localPort); - - // Bind socket - const int ret = AZ::AzSock::Bind(createdSocket, service); - if (AZ::AzSock::SocketErrorOccured(ret)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): bind() failed: %s", localPort, AZ::AzSock::GetStringForError(createdSocket)); - - // cleanup - AZ::AzSock::CloseSocket(createdSocket); - return NULL; - } - - // Listen for incoming connection requests on the created socket - const int ret2 = AZ::AzSock::Listen(createdSocket, 64 /*backLogSize*/); - if (AZ::AzSock::SocketErrorOccured(ret2)) - { - // Connection has other problems - LOG_VERBOSE(0, "CreateListener(%d): listen() failed: %s", localPort, AZ::AzSock::GetStringForError(createdSocket)); - - // cleanup - AZ::AzSock::CloseSocket(createdSocket); - return NULL; - } - - // Get our local address - AZ::AzSock::AzSocketAddress localAddressInet; - AZ::AzSock::GetSockName(createdSocket, localAddressInet); - - // Translate to debug network address data - ServiceNetworkAddress localAddress; - TranslateAddress(localAddressInet, localAddress); - - // Spew to log (important info) - LOG_VERBOSE(0, "bind() to '%s'", localAddress.ToString().c_str()); - - // Create the listener wrapper - CServiceNetworkListener* listener = new CServiceNetworkListener(this, createdSocket, localAddress); - - // Listener was created - LOG_VERBOSE(0, "CreateListener(%d): listener created, local address=%s", localPort, listener->GetLocalAddress().ToString().c_str()); - - // Add to list of local listeners - { - CryAutoLock lock(m_accessMutex); - m_pListeners.push_back(listener); - listener->AddRef(); - } - - // Return wrapping interface - return listener; -} - -void CServiceNetwork::RegisterConnection(CServiceNetworkConnection& con) -{ - CryAutoLock lock(m_accessMutex); - - // Make sure to register each connection only once - TConnectionArray::const_iterator it = std::find(m_pConnections.begin(), m_pConnections.end(), &con); - if (it == m_pConnections.end()) - { - // Low-level info - LOG_VERBOSE(3, "RegisterConnection(): registered connection from '%s' to '%s', %p", - con.GetLocalAddress().ToString().c_str(), - con.GetRemoteAddress().ToString().c_str(), - (UINT_PTR) &con); - - // add to connections list, that means we need to also increment the refcount - m_pConnections.push_back(&con); - con.AddRef(); - } -} - -void CServiceNetwork::RegisterForDeferredClose(CServiceNetworkConnection& con, const uint32 timeout) -{ - CryAutoLock lock(m_accessMutex); - - // Low-level info - LOG_VERBOSE(3, "RegisterConnection(): registered connection from '%s' to '%s', %p for defered close, timeout=%d", - con.GetLocalAddress().ToString().c_str(), - con.GetRemoteAddress().ToString().c_str(), - (UINT_PTR) &con, - timeout); - - // Add to connections list, that means we need to also increment the refcount - ConnectionToClose info; - info.pConnection = &con; - info.maxWaitTime = (timeout > 0) ? (GetNetworkTime() + timeout) : 0; - m_connectionsToClose.push_back(info); - - // Keep internal reference - con.AddRef(); -} - -IServiceNetworkConnection* CServiceNetwork::Connect(const ServiceNetworkAddress& remoteAddress) -{ - // Create new socket if needed - AZSOCKET socket = AZ::AzSock::Socket(); - if (!AZ::AzSock::IsAzSocketValid(socket)) - { - // Connection has problems - LOG_VERBOSE(0, "Connect(%s): socket() failed: %s", remoteAddress.ToString().c_str(), AZ::AzSock::GetStringForError(socket)); - return NULL; - } - - // Translate remote address - AZ::AzSock::AzSocketAddress addr; - TranslateAddress(remoteAddress, addr); - - // Spew to log (important info) - LOG_VERBOSE(1, "Connecting to '%s'...", remoteAddress.ToString().c_str()); - - // Connect (blocking) - const int result = AZ::AzSock::Connect(socket, addr); - if (AZ::AzSock::SocketErrorOccured(result)) - { - // Spew to log (important info) - LOG_VERBOSE(0, "connect() to '%s' failed: %s", remoteAddress.ToString().c_str(), AZ::AzSock::GetStringForError(result)); - return NULL; - } - - // Get the address of local socket endpoint - // Get our local address - AZ::AzSock::AzSocketAddress localAddressInet; - AZ::AzSock::GetSockName(socket, localAddressInet); - - // Translate to debug network address data - ServiceNetworkAddress localAddress; - TranslateAddress(localAddressInet, localAddress); - - // Spew to log (important info) - LOG_VERBOSE(1, "connected() from '%s' to '%s'", localAddress.ToString().c_str(), remoteAddress.ToString().c_str()); - - // Allocate some connection ID - const uint64 loPart = m_guidGenerator.GenerateUint64(); - const uint64 hiPart = m_guidGenerator.GenerateUint64(); - const CryGUID connectionID = CryGUID::Construct(loPart, hiPart); - - // Spew to log (important info) - LOG_VERBOSE(3, "New connection GUID: %08x-%08x-%08x-%08x", (uint64)(hiPart >> 32), (uint64)(hiPart & 0xFFFFFFFF), (uint64)(loPart >> 32), (uint64)(loPart & 0xFFFFFFFF)); - - // Create connection wrapper - CServiceNetworkConnection* newConnection = new CServiceNetworkConnection( - this, - CServiceNetworkConnection::eEndpoint_Client, // we are the client, we are connecting to remove destination - socket, - connectionID, - localAddress, - remoteAddress); - - // Add to list of connections - { - CryAutoLock lock(m_accessMutex); - m_pConnections.push_back(newConnection); - - // since we add the object to our internal list keep an extra reference to it - newConnection->AddRef(); - } - - // Well, good luck and have fun :) - return newConnection; -} - -//----------------------------------------------------------------------------- - -// Do not remove (can mess up the uber file builds) -#undef LOG_VERBOSE - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/ServiceNetwork.h b/Code/CryEngine/CrySystem/ServiceNetwork.h deleted file mode 100644 index 23c3500082..0000000000 --- a/Code/CryEngine/CrySystem/ServiceNetwork.h +++ /dev/null @@ -1,475 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// Description : Service network implementation - - -#pragma once - - -//----------------------------------------------------------------------------- - -#include "IServiceNetwork.h" -#include - -class CServiceNetwork; - -//----------------------------------------------------------------------------- - -// General message buffer -class CServiceNetworkMessage - : public IServiceNetworkMessage -{ -private: - void* m_pData; - uint32 m_id; - uint32 m_size; - int volatile m_refCount; - -public: - CServiceNetworkMessage(const uint32 id, const uint32 size); - virtual ~CServiceNetworkMessage(); - - // IServiceNetworMessage interface - virtual uint32 GetId() const; - virtual uint32 GetSize() const; - virtual void* GetPointer(); - virtual const void* GetPointer() const; - virtual struct IDataReadStream* CreateReader() const; - virtual void AddRef(); - virtual void Release(); -}; - -//----------------------------------------------------------------------------- - -// General network TCP/IP connection -class CServiceNetworkConnection - : public IServiceNetworkConnection -{ -public: - friend class CServiceNetworkListener; - - // maximum size of a single message (0.5MB by default) - static const uint32 kMaximumMessageSize = 5 << 19; - - // initialization message send period (ms) - static const uint64 kInitializationPerior = 1000; - - // keep alive period (ms), by default every 2s - static const uint64 kKeepAlivePeriod = 2000; - - // reconnection retries period (ms) - static const uint64 kReconnectTryPerior = 1000; - - // timeout for assuming server side connection dead (reconnection timeout) - static const uint64 hReconnectTimeOut = 30 * 1000; - - // communication time out (ms) - static const uint64 kTimeout = 5000; - - // Type of endpoint - enum EEndpoint - { - // This is the server side of the connection (on the side of the listening socket) - eEndpoint_Server, - - // This is the client side of the connection (we connected to the listening socket) - eEndpoint_Client, - }; - - // Internal state machine - enum EState - { - // Connection is initializing - eState_Initializing, - - // Connection is valid - eState_Valid, - - // Operation on the socket failed (we may need to reconnect) - eState_Lost, - - // Connection is closed - eState_Closed, - }; - - // Command IDs, do not change the numerical values - enum ECommand - { - // Data block command - eCommand_Data = 1, - - // Keep alive command - eCommand_KeepAlive = 2, - - // Initialize communication channel (sent only once) - eCommand_Initialize = 3, - }; - - #pragma pack(push) - #pragma pack(1) - - struct Header - { - uint8 m_cmd; - uint32 m_size; - - void Swap(); - }; - - struct InitHeader - { - uint8 m_cmd; - uint8 m_pad0; - uint8 m_pad1; - uint8 m_pad2; - uint32 m_tryCount; - uint64 m_guid0; - uint64 m_guid1; - - void Swap(); - }; - - #pragma pack(pop) - -private: - CServiceNetwork* m_pManager; - - // Type of endpoint (client/server) - EEndpoint m_endpointType; - - // Connection state (internal) - EState m_state; - - // Reference count (updated using CryInterlocked* functions) - int volatile m_refCount; - - // Internal socket data - AZSOCKET m_socket; - - // Local address - ServiceNetworkAddress m_localAddress; - - // Remote connection address - ServiceNetworkAddress m_remoteAddress; - - // Internal connection ID (unique) - CryGUID m_connectionID; - - // Internal time counters - uint64 m_lastReconnectTime; - uint64 m_lastKeepAliveSendTime; - uint64 m_lastMessageReceivedTime; - uint64 m_lastInitializationSendTime; - uint32 m_reconnectTryCount; - - // Statistics (updated from threads using CryIntelocked* functions) - volatile uint32 m_statsNumPacketsSend; - volatile uint32 m_statsNumPacketsReceived; - volatile uint32 m_statsNumDataSend; - volatile uint32 m_statsNumDataReceived; - - // Queue of messages to send (thread access possible) - typedef CryMT::CLocklessPointerQueue< CServiceNetworkMessage > TSendQueue; - CServiceNetworkMessage* m_pSendedMessages; - TSendQueue m_pSendQueue; - uint32 m_messageDataSentSoFar; - volatile int m_sendQueueDataSize; - - // Queue of received message - typedef CryMT::CLocklessPointerQueue< CServiceNetworkMessage > TReceiveQueue; - TReceiveQueue m_pReceiveQueue; - uint32 m_receiveQueueDataSize; - uint32 m_messageDataReceivedSoFar; - uint32 m_messageReceiveLength; - - // Message being received "right now" - CServiceNetworkMessage* m_pCurrentReceiveMessage; - uint32 m_messageDummyReadLength; - - // External request to close this connection was issued - bool m_bCloseRequested; - - // Do not accept any new data for sending or receiving - bool m_bDisableCommunication; - -public: - ILINE bool IsInitialized() const - { - return m_state != eState_Initializing; - } - - ILINE bool IsSendingQueueEmpty() const - { - return m_pSendQueue.empty(); - } - - ILINE CServiceNetwork* GetManager() const - { - return m_pManager; - } - -public: - CServiceNetworkConnection( - class CServiceNetwork* manager, - EEndpoint endpointType, - AZSOCKET socket, - const CryGUID& connectionID, - const ServiceNetworkAddress& localAddress, - const ServiceNetworkAddress& remoteAddress); - - virtual ~CServiceNetworkConnection(); - - // IServiceNetworkConnection interface implementation - virtual const ServiceNetworkAddress& GetRemoteAddress() const; - virtual const ServiceNetworkAddress& GetLocalAddress() const; - virtual const CryGUID& GetGUID() const; - virtual bool IsAlive() const; - virtual uint32 GetMessageSendCount() const; - virtual uint32 GetMessageReceivedCount() const; - virtual uint64 GetMessageSendDataSize() const; - virtual uint64 GetMessageReceivedDataSize() const; - virtual bool SendMsg(IServiceNetworkMessage* message); - virtual IServiceNetworkMessage* ReceiveMsg(); - virtual void FlushAndClose(const uint32 timeout); - virtual void FlushAndWait(); - virtual void Close(); - virtual void AddRef(); - virtual void Release(); - - // All remote connections are updated on the client side - // This is called from service network update thread, try not to call by hand :) - void Update(); - -private: - void ProcessSendingQueue(); - void ProcessReceivingQueue(); - - // Keep alive message handling - void ProcessKeepAlive(); - void SendKeepAlive(const uint64 currentNetworkTime); - bool HandleTimeout(const uint64 currentNetworkTime); - - // Handle the reconnection request - bool HandleReconnect(AZSOCKET socket, const uint32 tryCount); - - // General send/receive functions with error handling. - // If socket error occurs the connection will be put in the lost state. - uint32 TrySend(const void* dataBuffer, uint32 dataSize, bool autoHandleErrors); - - // Internal receive function with error handling - uint32 TryReceive(void* dataBuffer, uint32 dataSize, bool autoHandleErrors); - - // Try to reconnect to the remote address - bool TryReconnect(); - - // Try to send the initialization header - bool TryInitialize(); - - // Low-level socket shutdown (hash way) - void Shutdown(); - - // Reset the connection (put in the lost state and reconnect) - void Reset(); -}; - -//----------------------------------------------------------------------------- - -// TCP/IP listener -class CServiceNetworkListener - : public IServiceNetworkListener -{ - typedef CServiceNetworkConnection::InitHeader TInitHeader; - - struct PendingConnection - { - // Connection socket - AZSOCKET m_socket; - - // Initialization of initialization header received so far - uint32 m_dataReceivedSoFar; - - // Initialization header - TInitHeader m_initHeader; - - // Remote address (as returned from accept) - ServiceNetworkAddress m_remoteAddress; - }; - -protected: - // Owner (the manager) - CServiceNetwork* m_pManager; - - // Reference count, updated using CryInterlocked* functions - int volatile m_refCount; - - // Listening socket - AZSOCKET m_socket; - - // Local address (usually has the IP in 127.0.0.1:port form) - ServiceNetworkAddress m_localAddress; - - // Request to close this listener was received - bool m_closeRequestReceived; - - // Pending connections (but not yet initialized) - typedef std::vector< PendingConnection* > TPendingConnectionList; - TPendingConnectionList m_pPendingConnections; - - // All active connections spawned from this listener - typedef std::vector< CServiceNetworkConnection* > TConnectionList; - TConnectionList m_pLocalConnections; - - // Access lock for the class members (thread safe) - CryMutex m_accessLock; - -public: - ILINE CServiceNetwork* GetManager() const - { - return m_pManager; - } - -public: - CServiceNetworkListener(CServiceNetwork* pManager, AZSOCKET socket, const ServiceNetworkAddress& address); - virtual ~CServiceNetworkListener(); - - void Update(); - - // IServiceNetworkListener interface implementation - virtual const ServiceNetworkAddress& GetLocalAddress() const; - virtual uint32 GetConnectionCount() const; - virtual IServiceNetworkConnection* Accept(); - virtual bool IsAlive() const; - virtual void AddRef(); - virtual void Release(); - virtual void Close(); - -private: - void ProcessIncomingConnections(); - void ProcessPendingConnections(); -}; - -//----------------------------------------------------------------------------- - -// TCP/IP manager for service connection channels -class CServiceNetwork - : public IServiceNetwork - , public CryRunnable -{ -#if defined(AZ_RESTRICTED_PLATFORM) -#include AZ_RESTRICTED_FILE(ServiceNetwork_h) -#endif - -protected: - struct ConnectionToClose - { - CServiceNetworkConnection* pConnection; - - // timeout for forded close - uint64 maxWaitTime; - }; - -protected: - // Local listeners - typedef std::vector< CServiceNetworkListener* > TListenerArray; - TListenerArray m_pListeners; - - // Local connections - typedef std::vector< CServiceNetworkConnection* > TConnectionArray; - TConnectionArray m_pConnections; - - // Connections that are waiting for all of their data to be sent before closing - typedef std::vector< ConnectionToClose > TConnectionsToCloseArray; - TConnectionsToCloseArray m_connectionsToClose; - - // We are running on threads, needed to sync the access to arrays - CryMutex m_accessMutex; - - // Current network time (ms) - uint64 m_networkTime; - - // Exit was requested - bool m_bExitRequested; - - // Message verbose level - ICVar* m_pVerboseLevel; - - // Thread - typedef CryThread< CServiceNetwork > TServiceNetworkThread; - TServiceNetworkThread* m_pThread; - - // Buffer ID allocator (unique, incremented atomically using CryInterlockedIncrement) - volatile int m_bufferID; - - // Random number generator for GUID creation - CRndGen m_guidGenerator; - - // Send/Receive queue size limit - ICVar* m_pReceiveDataQueueLimit; - ICVar* m_pSendDataQueueLimit; - -public: - ILINE const uint64 GetNetworkTime() const - { - return m_networkTime; - } - - ILINE const CServiceNetwork* GetManager() const - { - return this; - } - - ILINE const uint32 GetReceivedDataQueueLimit() const - { - return m_pReceiveDataQueueLimit->GetIVal(); - } - - ILINE const uint32 GetSendDataQueueLimit() const - { - return m_pSendDataQueueLimit->GetIVal(); - } - -public: - CServiceNetwork(); - virtual ~CServiceNetwork(); - - // IServiceNetwork interface implementation - virtual void SetVerbosityLevel(const uint32 level); - virtual IServiceNetworkMessage* AllocMessageBuffer(const uint32 size); - virtual struct IDataWriteStream* CreateMessageWriter(); - virtual struct IDataReadStream* CreateMessageReader(const void* pData, const uint32 dataSize); - virtual ServiceNetworkAddress GetHostAddress(const string& addressString, uint16 optionalPort = 0) const; - virtual IServiceNetworkListener* CreateListener(uint16 localPort); - virtual IServiceNetworkConnection* Connect(const ServiceNetworkAddress& remoteAddress); - - // CryRunnable - virtual void Run(); - virtual void Cancel(); - - // Register connection in the connection list (thread safe) - void RegisterConnection(CServiceNetworkConnection& con); - - // Register connection for closing one all of the outgoing messages are sent - void RegisterForDeferredClose(CServiceNetworkConnection& con, const uint32 timeout); - - // Debug print -#ifdef RELEASE - void Log([[maybe_unused]] const char* txt, ...) const {}; - bool CheckVerbose([[maybe_unused]] const uint32 level) const { return false; } -#else - void Log(const char* txt, ...) const; - bool CheckVerbose(const uint32 level) const; -#endif -}; - -//----------------------------------------------------------------------------- diff --git a/Code/CryEngine/CrySystem/System.cpp b/Code/CryEngine/CrySystem/System.cpp index 31eb286a17..8a8cf14d91 100644 --- a/Code/CryEngine/CrySystem/System.cpp +++ b/Code/CryEngine/CrySystem/System.cpp @@ -121,7 +121,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include #include -#include #include #include #include @@ -145,7 +144,6 @@ LRESULT WINAPI WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) #include "LocalizedStringManager.h" #include "XML/XmlUtils.h" -#include "Serialization/ArchiveHost.h" #include "SystemEventDispatcher.h" #include "ServerThrottle.h" #include "ResourceManager.h" @@ -445,7 +443,6 @@ CSystem::CSystem(SharedEnvironmentInstance* pSharedEnvironment) m_pXMLUtils = new CXmlUtils(this); - m_pArchiveHost = Serialization::CreateArchiveHost(); m_pMemoryManager = CryGetIMemoryManager(); m_pThreadTaskManager = new CThreadTaskManager; m_pResourceManager = new CResourceManager; @@ -499,7 +496,6 @@ CSystem::~CSystem() CRY_ASSERT(m_windowMessageHandlers.empty() && "There exists a dangling window message handler somewhere"); SAFE_DELETE(m_pXMLUtils); - SAFE_DELETE(m_pArchiveHost); SAFE_DELETE(m_pThreadTaskManager); SAFE_DELETE(m_pResourceManager); SAFE_DELETE(m_pSystemEventDispatcher); @@ -671,7 +667,6 @@ void CSystem::ShutDown() SAFE_DELETE(m_env.pResourceCompilerHelper); SAFE_RELEASE(m_env.pMovieSystem); - SAFE_DELETE(m_env.pServiceNetwork); SAFE_RELEASE(m_env.pLyShine); SAFE_RELEASE(m_env.pCryFont); if (m_env.pConsole) diff --git a/Code/CryEngine/CrySystem/System.h b/Code/CryEngine/CrySystem/System.h index 5f87fd1ad1..c4f3bfabd6 100644 --- a/Code/CryEngine/CrySystem/System.h +++ b/Code/CryEngine/CrySystem/System.h @@ -42,7 +42,6 @@ namespace AzFramework struct IConsoleCmdArgs; class CServerThrottle; -struct ICryFactoryRegistryImpl; struct IZLibCompressor; class CWatchdogThread; class CThreadManager; @@ -486,8 +485,6 @@ public: virtual IXmlUtils* GetXmlUtils(); ////////////////////////////////////////////////////////////////////////// - virtual Serialization::IArchiveHost* GetArchiveHost() const { return m_pArchiveHost; } - void SetViewCamera(CCamera& Camera){ m_ViewCamera = Camera; } CCamera& GetViewCamera() { return m_ViewCamera; } @@ -584,15 +581,11 @@ public: // static as memReplay needs it before CSystem has been setup - expose a ISystem interface to this function if you need it outside CrySystem static void debug_GetCallStackRaw(void** callstack, uint32& callstackLength); - virtual ICryFactoryRegistry* GetCryFactoryRegistry() const; - public: #if !defined(RELEASE) void SetVersionInfo(const char* const szVersion); #endif - virtual bool InitializeEngineModule(const char* dllName, const char* moduleClassName, const SSystemInitParams& initParams) override; - virtual bool UnloadEngineModule(const char* dllName, const char* moduleClassName); virtual const IImageHandler* GetImageHandler() const override { return m_imageHandler.get(); } void ShutdownModuleLibraries(); @@ -809,8 +802,6 @@ private: // ------------------------------------------------------ // XML Utils interface. class CXmlUtils* m_pXMLUtils; - Serialization::IArchiveHost* m_pArchiveHost; - int m_iApplicationInstance; //! to hold the values stored in system.cfg diff --git a/Code/CryEngine/CrySystem/SystemInit.cpp b/Code/CryEngine/CrySystem/SystemInit.cpp index 83ef4fcd2b..8bf2fb8930 100644 --- a/Code/CryEngine/CrySystem/SystemInit.cpp +++ b/Code/CryEngine/CrySystem/SystemInit.cpp @@ -46,8 +46,6 @@ #include #include -#include -#include #include // for AZ_MAX_PATH_LEN #include #include @@ -113,16 +111,12 @@ #include "ResourceManager.h" #include "MTSafeAllocator.h" #include "NotificationNetwork.h" -#include "ExtensionSystem/CryFactoryRegistryImpl.h" -#include "ExtensionSystem/TestCases/TestExtensions.h" #include "ProfileLogSystem.h" #include "SoftCode/SoftCodeMgr.h" #include "ZLibCompressor.h" #include "ZLibDecompressor.h" #include "ZStdDecompressor.h" #include "LZ4Decompressor.h" -#include "ServiceNetwork.h" -#include "RemoteCommand.h" #include "LevelSystem/LevelSystem.h" #include "LevelSystem/SpawnableLevelSystem.h" #include "ViewSystem/ViewSystem.h" @@ -856,148 +850,6 @@ bool CSystem::UnloadDLL(const char* dllName) return isSuccess; } -////////////////////////////////////////////////////////////////////////// -bool CSystem::InitializeEngineModule(const char* dllName, const char* moduleClassName, const SSystemInitParams& initParams) -{ - bool bResult = false; - - stack_string msg; - msg = "Initializing "; - AZStd::string dll = dllName; - - // Strip off Cry if the dllname is Cry - if (dll.find("Cry") == 0) - { - msg += dll.substr(3).c_str(); - } - else - { - msg += dllName; - } - msg += "..."; - - if (m_pUserCallback) - { - m_pUserCallback->OnInitProgress(msg.c_str()); - } - AZ_TracePrintf(moduleClassName, "%s", msg.c_str()); - - IMemoryManager::SProcessMemInfo memStart, memEnd; - if (GetIMemoryManager()) - { - GetIMemoryManager()->GetProcessMemInfo(memStart); - } - else - { - ZeroStruct(memStart); - } - - stack_string dllfile = ""; - - -#if defined(AZ_RESTRICTED_PLATFORM) -#define AZ_RESTRICTED_SECTION SYSTEMINIT_CPP_SECTION_16 -#include AZ_RESTRICTED_FILE(SystemInit_cpp) -#endif -#if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) -#undef AZ_RESTRICTED_SECTION_IMPLEMENTED -#else - - dllfile.append(dllName); - -#if defined(LINUX) - dllfile = "lib" + PathUtil::ReplaceExtension(dllfile, "so"); -#ifndef LINUX - dllfile.MakeLower(); -#endif -#elif defined(AZ_PLATFORM_MAC) - dllfile = "lib" + PathUtil::ReplaceExtension(dllfile, "dylib"); -#elif defined(AZ_PLATFORM_IOS) - PathUtil::RemoveExtension(dllfile); -#else - dllfile = PathUtil::ReplaceExtension(dllfile, "dll"); -#endif - -#endif - -#if !defined(AZ_MONOLITHIC_BUILD) - - m_moduleDLLHandles.insert(std::make_pair(dllfile.c_str(), LoadDLL(dllfile.c_str()))); - if (!m_moduleDLLHandles[dllfile.c_str()]) - { - return bResult; - } - -#endif // #if !defined(AZ_MONOLITHIC_BUILD) - - AZStd::shared_ptr pModule; - if (CryCreateClassInstance(moduleClassName, pModule)) - { - bResult = pModule->Initialize(m_env, initParams); - - // After initializing the module, give it a chance to register any AZ console vars - // declared within the module. - pModule->RegisterConsoleVars(); - } - - if (GetIMemoryManager()) - { - GetIMemoryManager()->GetProcessMemInfo(memEnd); - -#if defined(AZ_ENABLE_TRACING) - uint64 memUsed = memEnd.WorkingSetSize - memStart.WorkingSetSize; -#endif - AZ_TracePrintf(AZ_TRACE_SYSTEM_WINDOW, "Initializing %s %s, MemUsage=%uKb", dllName, pModule ? "done" : "failed", uint32(memUsed / 1024)); - } - - return bResult; -} - -////////////////////////////////////////////////////////////////////////// -bool CSystem::UnloadEngineModule(const char* dllName, const char* moduleClassName) -{ - bool isSuccess = false; - - // Remove the factory. - ICryFactoryRegistryImpl* const pReg = static_cast(GetCryFactoryRegistry()); - - if (pReg != nullptr) - { - ICryFactory* pICryFactory = pReg->GetFactory(moduleClassName); - - if (pICryFactory != nullptr) - { - pReg->UnregisterFactory(pICryFactory); - } - } - - stack_string msg; - msg = "Unloading "; - msg += dllName; - msg += "..."; - - AZ_TracePrintf(AZ_TRACE_SYSTEM_WINDOW, "%s", msg.c_str()); - - stack_string dllfile = dllName; - -#if defined(LINUX) - dllfile = "lib" + PathUtil::ReplaceExtension(dllfile, "so"); -#ifndef LINUX - dllfile.MakeLower(); -#endif -#elif defined(APPLE) - dllfile = "lib" + PathUtil::ReplaceExtension(dllfile, "dylib"); -#else - dllfile = PathUtil::ReplaceExtension(dllfile, "dll"); -#endif - -#if !defined(AZ_MONOLITHIC_BUILD) - isSuccess = UnloadDLL(dllfile.c_str()); -#endif // #if !defined(AZ_MONOLITHIC_BUILD) - - return isSuccess; -} - ////////////////////////////////////////////////////////////////////////// void CSystem::ShutdownModuleLibraries() { @@ -1872,12 +1724,6 @@ bool CSystem::Init(const SSystemInitParams& startupParams) AZ_Assert(CryMemory::IsHeapValid(), "Memory heap must be valid before continuing SystemInit."); -#ifdef EXTENSION_SYSTEM_INCLUDE_TESTCASES - TestExtensions(&CCryFactoryRegistryImpl::Access()); -#endif - - //_controlfp(0, _EM_INVALID|_EM_ZERODIVIDE | _PC_64 ); - #if defined(WIN32) || defined(WIN64) // check OS version - we only want to run on XP or higher - talk to Martin Mittring if you want to change this { @@ -2412,8 +2258,6 @@ AZ_POP_DISABLE_WARNING } InlineInitializationProcessing("CSystem::Init InitShine"); - - ////////////////////////////////////////////////////////////////////////// // CONSOLE ////////////////////////////////////////////////////////////////////////// if (!InitConsole()) @@ -2421,22 +2265,6 @@ AZ_POP_DISABLE_WARNING return false; } - ////////////////////////////////////////////////////////////////////////// - // SERVICE NETWORK - ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bSkipNetwork && !startupParams.bMinimal) - { - m_env.pServiceNetwork = new CServiceNetwork(); - } - - ////////////////////////////////////////////////////////////////////////// - // REMOTE COMMAND SYTSTEM - ////////////////////////////////////////////////////////////////////////// - if (!startupParams.bSkipNetwork && !startupParams.bMinimal) - { - m_env.pRemoteCommandManager = new CRemoteCommandManager(); - } - if (m_pUserCallback) { m_pUserCallback->OnInitProgress("Initializing additional systems..."); diff --git a/Code/CryEngine/CrySystem/XConsole.cpp b/Code/CryEngine/CrySystem/XConsole.cpp index ee5b500b0b..3b30a7eeed 100644 --- a/Code/CryEngine/CrySystem/XConsole.cpp +++ b/Code/CryEngine/CrySystem/XConsole.cpp @@ -28,7 +28,6 @@ #include #include #include -#include #include #include "ConsoleHelpGen.h" // CConsoleHelpGen diff --git a/Code/CryEngine/CrySystem/crysystem_files.cmake b/Code/CryEngine/CrySystem/crysystem_files.cmake index 0b62483e43..5dc8a68f8b 100644 --- a/Code/CryEngine/CrySystem/crysystem_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_files.cmake @@ -55,13 +55,7 @@ set(FILES SystemScheduler.h UnixConsole.h SystemInit.h - Serialization/MemoryReader.h XML/ReadWriteXMLSink.h - Serialization/ArchiveHost.h - Serialization/MemoryWriter.h - Serialization/JSONIArchive.h - Serialization/JSONOArchive.h - Serialization/BinArchive.h AZCrySystemInitLogSink.h AZCoreLogSink.h CmdLine.h @@ -127,10 +121,6 @@ set(FILES ThreadConfigManager.h ThreadConfigManager.cpp SystemThreading.cpp - ExtensionSystem/CryFactoryRegistryImpl.cpp - ExtensionSystem/CryFactoryRegistryImpl.h - ExtensionSystem/TestCases/TestExtensions.cpp - ExtensionSystem/TestCases/TestExtensions.h ZLibCompressor.cpp ZLibCompressor.h SoftCode/SoftCodeMgr.cpp @@ -141,14 +131,6 @@ set(FILES RemoteConsole/RemoteConsole.h RemoteConsole/RemoteConsole_impl.inl RemoteConsole/RemoteConsole_none.inl - ServiceNetwork.cpp - ServiceNetwork.h - RemoteCommand.cpp - RemoteCommand.h - RemoteCommandHelpers.cpp - RemoteCommandHelpers.h - RemoteCommandServer.cpp - RemoteCommandClient.cpp ZLibDecompressor.h ZLibDecompressor.cpp LZ4Decompressor.h @@ -165,17 +147,6 @@ set(FILES ViewSystem/ViewSystem.h ZStdDecompressor.h ZStdDecompressor.cpp - Serialization/ArchiveHost.cpp - Serialization/BinArchive.cpp - Serialization/JSONIArchive.cpp - Serialization/JSONOArchive.cpp - Serialization/MemoryReader.cpp - Serialization/MemoryWriter.cpp - Serialization/Token.h - Serialization/XmlIArchive.cpp - Serialization/XmlIArchive.h - Serialization/XmlOArchive.cpp - Serialization/XmlOArchive.h StreamEngine/StreamAsyncFileRequest.cpp StreamEngine/StreamAsyncFileRequest_Jobs.cpp StreamEngine/StreamEngine.cpp diff --git a/Code/CryEngine/CrySystem/crysystem_test_files.cmake b/Code/CryEngine/CrySystem/crysystem_test_files.cmake index fc236afcf3..a57ba57f77 100644 --- a/Code/CryEngine/CrySystem/crysystem_test_files.cmake +++ b/Code/CryEngine/CrySystem/crysystem_test_files.cmake @@ -11,7 +11,6 @@ set(FILES Components/MathConversionTests.cpp - Serialization/Test_ArchiveHost.cpp Tests/Test_CLog.cpp Tests/Test_CommandRegistration.cpp Tests/Test_CryPrimitives.cpp diff --git a/Code/Sandbox/Editor/Controls/CurveEditorCtrl.cpp b/Code/Sandbox/Editor/Controls/CurveEditorCtrl.cpp deleted file mode 100644 index f66943b07d..0000000000 --- a/Code/Sandbox/Editor/Controls/CurveEditorCtrl.cpp +++ /dev/null @@ -1,821 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "CurveEditorCtrl.h" - -// Qt -#include -#include - -namespace CurveEditor -{ - const int kHandleSize = 6; - const int kHandleSizeHalf = kHandleSize / 2; - const int kDefaultPadding = 10; - const int kInfoFontSize = 7; - const int kGrid = 4; - const QColor kColor_SelectCross(132, 132, 132); - const QColor kColor_DisabledCross(90, 90, 90); - const QColor kColor_MiddleLines(80, 80, 80); - const QColor kColor_Background(41, 41, 41); - const QColor kColor_Disabled(60, 60, 60); - const QColor kColor_PaddingBorder(128, 128, 128); - const QColor kColor_Text(128, 128, 128); - const QColor kColor_TextCrtPos(187, 187, 187); - const QColor kColor_Curve(255, 0, 0); - const QColor kColor_SelHandle(200, 200, 200); - const QColor kColor_NormalHandle(30, 30, 30); - const QColor kColor_HandleLight(60, 60, 60); - const QColor kColor_HandleShadow(0, 0, 0); - const QColor kColor_MarkLines(0, 255, 0); -} - - -CCurveEditorCtrl::CCurveEditorCtrl(QWidget* parent) - : QWidget(parent) -{ - m_domainMinX = 0.0f; - m_domainMinY = 0.0f; - m_domainMaxX = 1.0f; - m_domainMaxY = 1.0f; - m_bMouseDown = m_bDragging = false; - m_bAllowMouse = true; - m_padding = CurveEditor::kDefaultPadding; - m_flags = eFlag_ShowVerticalRuler - | eFlag_ShowHorizontalRuler - | eFlag_ShowVerticalRulerText - | eFlag_ShowHorizontalRulerText - | eFlag_ShowPaddingBorder - | eFlag_ShowMovingPointAxis - | eFlag_ShowPointHandles; - m_gridSplits.set(CurveEditor::kGrid, CurveEditor::kGrid); - m_fntInfo.setFamily("Arial"); - m_fntInfo.setPointSize(CurveEditor::kInfoFontSize); - m_bHovered = false; - m_selCrossPen = QPen(CurveEditor::kColor_SelectCross); - - GenerateDefaultCurve(); -} - -CCurveEditorCtrl::~CCurveEditorCtrl() -{ -} - -void CCurveEditorCtrl::SetFlags(UINT aFlags) -{ - m_flags = aFlags; -} - -UINT CCurveEditorCtrl::GetFlags() const -{ - return m_flags; -} - -bool CCurveEditorCtrl::SetDomainBounds(float aMinX, float aMinY, float aMaxX, float aMaxY) -{ - assert(aMinX < aMaxX); - assert(aMinY < aMaxY); - - if (aMinX >= aMaxX) - { - return false; - } - - if (aMinY >= aMaxY) - { - return false; - } - - m_domainMinX = aMinX; - m_domainMinY = aMinY; - m_domainMaxX = aMaxX; - m_domainMaxY = aMaxY; - - return true; -} - -void CCurveEditorCtrl::GetDomainBounds(float& rMinX, float& rMinY, float& rMaxX, float& rMaxY) const -{ - rMinX = m_domainMinX; - rMinY = m_domainMinY; - rMaxX = m_domainMaxX; - rMaxY = m_domainMaxY; -} - -void CCurveEditorCtrl::SetGrid(UINT aHorizontalSplits, UINT aVerticalSplits, const QStringList& labelsX, const QStringList& labelsY) -{ - assert(aHorizontalSplits); - assert(aVerticalSplits); - - if (!aHorizontalSplits) - { - // defaults - aHorizontalSplits = 2; - } - - if (!aVerticalSplits) - { - // defaults - aVerticalSplits = 2; - } - - m_gridSplits.x = aHorizontalSplits; - m_gridSplits.y = aVerticalSplits; - - if (!labelsX.isEmpty()) - { - m_labelsX = labelsX; - } - - if (!labelsY.isEmpty()) - { - m_labelsY = labelsY; - } -} - -QPoint CCurveEditorCtrl::ProjectPoint(float x, float y) -{ - QPoint pt; - - pt.setX(m_padding + (width() - m_padding * 2) * (x - m_domainMinX) / (m_domainMaxX - m_domainMinX)); - pt.setY(m_padding + (height() - m_padding * 2) * (1.0f - (y - m_domainMinY) / (m_domainMaxY - m_domainMinY))); - - return pt; -} - -Vec2 CCurveEditorCtrl::UnprojectPoint(const QPoint& pt) -{ - Vec2 vec; - int y = height() - pt.y(); - float dx = (width() - m_padding * 2); - float dy = (height() - m_padding * 2); - const float kEpsilon = 0.00000001f; - - if (fabs(dx) <= kEpsilon) - { - dx = 1.0f; - } - - if (fabs(dy) <= kEpsilon) - { - dy = 1.0f; - } - - vec.x = m_domainMinX + (float)(pt.x() - m_padding) / dx * (m_domainMaxX - m_domainMinX); - vec.y = m_domainMinY + (float)(y - m_padding) / dy * (m_domainMaxY - m_domainMinY); - - return vec; -} - -void CCurveEditorCtrl::SetControlPointCount(UINT aCount) -{ - m_points.resize(aCount); - m_projectedPoints.clear(); -} - -UINT CCurveEditorCtrl::GetControlPointCount() const -{ - return m_points.size(); -} - -void CCurveEditorCtrl::AddControlPoint(const Vec2& rPosition) -{ - m_points.push_back(CurvePoint(rPosition.x, rPosition.y)); -} - -void CCurveEditorCtrl::ClearControlPoints() -{ - m_points.clear(); -} - -void CCurveEditorCtrl::SetControlPoint(UINT aIndex, const Vec2& rPosition) -{ - assert(aIndex < m_points.size()); - - if (aIndex >= m_points.size()) - { - return; - } - - m_points[aIndex].pos = rPosition; -} - -void CCurveEditorCtrl::SetControlPointTangents(UINT aIndex, const Vec2& rLeft, const Vec2& rRight) -{ - assert(aIndex < m_points.size()); - - if (aIndex >= m_points.size()) - { - return; - } - - m_points[aIndex].tanA = rLeft; - m_points[aIndex].tanB = rRight; -} - -void CCurveEditorCtrl::GetControlPoint(UINT aIndex, Vec2& rOutPosition) const -{ - assert(aIndex < m_points.size()); - - if (aIndex >= m_points.size()) - { - return; - } - - rOutPosition = m_points[aIndex].pos; -} - -void CCurveEditorCtrl::GetControlPointTangents(UINT aIndex, Vec2& rOutLeft, Vec2& rOutRight) const -{ - assert(aIndex < m_points.size()); - - if (aIndex >= m_points.size()) - { - return; - } - - rOutLeft = m_points[aIndex].tanA; - rOutRight = m_points[aIndex].tanB; -} - -void CCurveEditorCtrl::paintEvent(QPaintEvent* event) -{ - QWidget::paintEvent(event); - - QPainter dc(this); - - QRect rc = geometry(); - QString str; - QRect textSize; - - dc.setFont(m_fntInfo); - QFontMetrics fntMetrics(m_fntInfo); - - if (m_flags & eFlag_Disabled) - { - // If disabled, just draw a blank square. - dc.fillRect(rc, CurveEditor::kColor_Disabled); - - dc.setPen(CurveEditor::kColor_DisabledCross); - dc.drawLine(0, 0, rc.width(), rc.height()); - - dc.drawLine(rc.width(), 0, 0, rc.height()); - return; - } - - dc.fillRect(rc, CurveEditor::kColor_Background); - - dc.setPen(CurveEditor::kColor_MiddleLines); - - if (m_flags & eFlag_ShowVerticalRuler) - { - float y = m_domainMinY; - float grid = (m_domainMaxY - m_domainMinY) / m_gridSplits.y; - QPoint p; - - for (int i = 0; i <= m_gridSplits.y; ++i) - { - p = ProjectPoint(0, y); - dc.drawLine(m_padding, p.y(), rc.width() - m_padding, p.y()); - - if (m_flags & eFlag_ShowVerticalRulerText) - { - if (m_labelsY.empty()) - { - str.asprintf("%0.2f", y); - } - else - { - str = m_labelsY[i]; - } - textSize = fntMetrics.tightBoundingRect(str); - dc.drawText(2, p.y(), str); - } - - y += grid; - } - } - - if (m_flags & eFlag_ShowHorizontalRuler) - { - float x = m_domainMinX; - float grid = (m_domainMaxX - m_domainMinX) / m_gridSplits.x; - QPoint p; - - for (int i = 0; i <= m_gridSplits.x; ++i) - { - p = ProjectPoint(x, 0); - dc.drawLine(p.x(), m_padding, p.x(), rc.height() - m_padding); - - if (m_flags & eFlag_ShowHorizontalRulerText) - { - if (m_labelsX.empty()) - { - str.asprintf("%0.2f", x); - } - else - { - str = m_labelsX[i]; - } - textSize = fntMetrics.tightBoundingRect(str); - - p.setX(p.x() + 2); - - if (p.x() + textSize.width() > width()) - { - p.setX(width() - textSize.width()); - } - - dc.drawText(p.x(), height() - m_padding + textSize.height() + 2, str); - } - - x += grid; - } - } - - dc.setPen(CurveEditor::kColor_MarkLines); - - if (m_flags & eFlag_ShowVerticalRuler) - { - QPoint p; - for (size_t i = 0; i < m_marksY.size(); ++i) - { - float v = m_marksY[i]; - if (v < m_domainMinY || v > m_domainMaxY) - { - continue; - } - p = ProjectPoint(0, v); - dc.drawLine(m_padding, p.y(), width() - m_padding, p.y()); - } - } - - if (m_flags & eFlag_ShowHorizontalRuler) - { - QPoint p; - for (size_t i = 0; i < m_marksX.size(); ++i) - { - float v = m_marksX[i]; - if (v < m_domainMinX || v > m_domainMaxX) - { - continue; - } - p = ProjectPoint(v, 0); - dc.drawLine(p.x(), m_padding, p.x(), height() - m_padding); - } - } - - if (m_flags & eFlag_ShowPaddingBorder) - { - dc.setPen(CurveEditor::kColor_PaddingBorder); - dc.drawRect(m_padding, m_padding, width() - m_padding * 2, height() - m_padding * 2); - } - - if (m_bDragging - && !m_selectedIndices.empty() - && (m_flags & eFlag_ShowMovingPointAxis)) - { - const Vec2& crtPos = m_points[m_selectedIndices[0]].pos; - - dc.setBrush(CurveEditor::kColor_TextCrtPos); - str.asprintf("(%0.2f,%0.2f)", crtPos.x, crtPos.y); - textSize = fntMetrics.tightBoundingRect(str); - const int kOffsetFromPointer = 5; - QPoint txtPos(m_lastMousePoint.x() + kOffsetFromPointer, m_lastMousePoint.y() + kOffsetFromPointer); - - if (txtPos.x() + textSize.width() > width()) - { - txtPos.setX(width() - textSize.width()); - } - - if (txtPos.y() + textSize.height() > height()) - { - txtPos.setY(height() - textSize.height()); - } - - dc.drawText(txtPos, str); - } - - ComputeTangents(); - UpdateProjectedPoints(); - - // for curve debug, tangents poly, don't delete - // dc.setPen(Qt::black); - // dc.drawPolyline(m_projectedPoints.data(), m_projectedPoints.size()); - - dc.setPen(CurveEditor::kColor_Curve); - - // curve - QPainterPath bezierPath; - bezierPath.moveTo(m_projectedPoints[0]); - for (int i = 1; i < m_projectedPoints.size(); i += 3) - { - bezierPath.cubicTo(m_projectedPoints[i], m_projectedPoints[i + 1], m_projectedPoints[i + 2]); - } - dc.drawPath(bezierPath); - - // curve control point handles - if (m_flags & eFlag_ShowPointHandles) - { - for (size_t i = 0; i < m_points.size(); ++i) - { - QPoint ptProj = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - QRect rcHandle(0, 0, CurveEditor::kHandleSize, CurveEditor::kHandleSize); - rcHandle.moveCenter(ptProj); - - std::vector::iterator iter = - std::find(m_selectedIndices.begin(), m_selectedIndices.end(), i); - - bool bSelected = (iter != m_selectedIndices.end()); - - if (bSelected && m_bDragging) - { - dc.setPen(m_selCrossPen); - dc.drawLine(0, ptProj.y(), width(), ptProj.y()); - dc.drawLine(ptProj.x(), 0, ptProj.x(), height()); - } - - dc.fillRect(rcHandle, bSelected - ? CurveEditor::kColor_SelHandle - : CurveEditor::kColor_NormalHandle); - - dc.setPen(CurveEditor::kColor_HandleLight); - dc.drawLine(ptProj.x() - CurveEditor::kHandleSizeHalf, ptProj.y() - CurveEditor::kHandleSizeHalf, - ptProj.x() - CurveEditor::kHandleSizeHalf, ptProj.y() + CurveEditor::kHandleSizeHalf); - dc.drawLine(ptProj.x() - CurveEditor::kHandleSizeHalf, ptProj.y() + CurveEditor::kHandleSizeHalf, - ptProj.x() + CurveEditor::kHandleSizeHalf, ptProj.y() + CurveEditor::kHandleSizeHalf); - dc.setPen(CurveEditor::kColor_HandleShadow); - dc.drawLine(ptProj.x() + CurveEditor::kHandleSizeHalf, ptProj.y() + CurveEditor::kHandleSizeHalf, - ptProj.x() + CurveEditor::kHandleSizeHalf, ptProj.y() - CurveEditor::kHandleSizeHalf); - dc.drawLine(ptProj.x() + CurveEditor::kHandleSizeHalf, ptProj.y() - CurveEditor::kHandleSizeHalf, - ptProj.x() - CurveEditor::kHandleSizeHalf, ptProj.y() - CurveEditor::kHandleSizeHalf); - } - } -} - -void CCurveEditorCtrl::ComputeTangents() -{ - for (size_t i = 0; i < m_points.size(); ++i) - { - m_points[i].tanA = m_points[i].pos; - m_points[i].tanB = m_points[i].pos; - } - - int maxIndex = m_points.size() - 1; - - for (size_t i = 0; i < m_points.size(); ++i) - { - if (i > maxIndex) - { - break; - } - - Vec2& p2 = m_points[i].pos; - Vec2& back = m_points[i].tanA; - Vec2& forw = m_points[i].tanB; - const float kEpsilon = 0.000001f; - - // first point - if (i == 0) - { - back = p2; - - if (maxIndex == 1) - { - Vec2& p3 = m_points[i + 1].pos; - forw = p2 + (p3 - p2) / 3.0f; - } - else if (maxIndex > 0) - { - Vec2& p3 = m_points[i + 1].pos; - Vec2& pb3 = m_points[i + 1].tanA; - - float lenOsn = (pb3 - p2).GetLength(); - float lenb = (p3 - p2).GetLength(); - - if (lenOsn > kEpsilon && lenb > kEpsilon) - { - forw = p2 + (pb3 - p2) / (lenOsn / lenb * 3.0f); - } - else - { - forw = p2; - } - } - } - - if (i == maxIndex) - { - forw = p2; - - if (i > 0) - { - Vec2& p1 = m_points[i - 1].pos; - Vec2& pf1 = m_points[i - 1].tanB; - - float lenOsn = (pf1 - p2).GetLength(); - float lenf = (p1 - p2).GetLength(); - - if (lenOsn > kEpsilon && lenf > kEpsilon) - { - back = p2 + (pf1 - p2) / (lenOsn / lenf * 3.0f); - } - else - { - back = p2; - } - } - } - else if (i >= 1 && i <= maxIndex - 1) - { - Vec2& p1 = m_points[i - 1].pos; - Vec2& p3 = m_points[i + 1].pos; - - float lenOsn = (p3 - p1).GetLength(); - float lenb = (p1 - p2).GetLength(); - float lenf = (p3 - p2).GetLength(); - - if (lenOsn > kEpsilon - && lenf > kEpsilon - && lenb > kEpsilon) - { - back = p2 + (p1 - p3) * (lenb / lenOsn / 3.0f); - forw = p2 + (p3 - p1) * (lenf / lenOsn / 3.0f); - } - } - - ClampToDomain(back); - ClampToDomain(forw); - } - - // fix tangents in relation of one to another - for (size_t i = 0; i < m_points.size(); ++i) - { - Vec2& p = m_points[i].pos; - Vec2& tanA = m_points[i].tanA; - Vec2& tanB = m_points[i].tanB; - - if (i < m_points.size() - 1) - { - if (tanB.x > m_points[i + 1].tanA.x) - { - tanB.x = (m_points[i + 1].pos.x + p.x) * 0.5f; - } - } - if (i > 0) - { - if (tanA.x < m_points[i - 1].tanB.x) - { - tanA.x = (m_points[i - 1].pos.x + p.x) * 0.5f; - } - } - } -} - -void CCurveEditorCtrl::UpdateProjectedPoints() -{ - m_projectedPoints.resize(m_points.size() * 3 - 2); - - int numPts = 0; - - for (size_t i = 0; i < m_points.size(); ++i) - { - if (i == 0) - { - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].tanB.x, m_points[i].tanB.y); - } - else if (i == m_points.size() - 1) - { - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].tanA.x, m_points[i].tanA.y); - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - } - else - { - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].tanA.x, m_points[i].tanA.y); - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - m_projectedPoints[numPts++] = ProjectPoint(m_points[i].tanB.x, m_points[i].tanB.y); - } - } -} - -void CCurveEditorCtrl::ClampToDomain(Vec2& rVec) -{ - if (rVec.x < m_domainMinX) - { - rVec.x = m_domainMinX; - } - else if (rVec.x > m_domainMaxX) - { - rVec.x = m_domainMaxX; - } - - if (rVec.y < m_domainMinY) - { - rVec.y = m_domainMinY; - } - else if (rVec.y > m_domainMaxY) - { - rVec.y = m_domainMaxY; - } -} - -void CCurveEditorCtrl::GenerateDefaultCurve() -{ - m_points.clear(); - m_domainMinX = 0.0f; - m_domainMinY = 0.0f; - m_domainMaxX = 1.0f; - m_domainMaxY = 1.0f; - m_points.push_back(CurvePoint(0.00f, 0.00f)); - m_points.push_back(CurvePoint(0.25f, 0.25f)); - m_points.push_back(CurvePoint(0.50f, 0.50f)); - m_points.push_back(CurvePoint(0.75f, 0.75f)); - m_points.push_back(CurvePoint(1.00f, 1.00f)); -} - -void CCurveEditorCtrl::mousePressEvent(QMouseEvent* event) -{ - QWidget::mousePressEvent(event); - if (event->button() != Qt::LeftButton) - { - return; - } - - const QPoint point = event->pos(); - if (m_bAllowMouse) - { - bool bSimpleSelect = !(event->modifiers() & Qt::ShiftModifier) && !(event->modifiers() & Qt::ControlModifier); - - if (bSimpleSelect) - { - m_selectedIndices.clear(); - } - - for (size_t i = 0; i < m_points.size(); ++i) - { - QPoint ptProj = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - - QRect rcHandle(0, 0, CurveEditor::kHandleSize, CurveEditor::kHandleSize); - rcHandle.moveCenter(ptProj); - - if (rcHandle.contains(point)) - { - if (bSimpleSelect) - { - m_selectedIndices.push_back(i); - break; - } - - if (event->modifiers() & Qt::ShiftModifier) - { - m_selectedIndices.push_back(i); - } - else if (event->modifiers() & Qt::ControlModifier) - { - std::vector::iterator iter = - std::find(m_selectedIndices.begin(), m_selectedIndices.end(), i); - - if (iter == m_selectedIndices.end()) - { - m_selectedIndices.push_back(i); - } - else - { - m_selectedIndices.erase(iter); - } - } - } - } - - m_bMouseDown = true; - m_lastMousePoint = point; - } - - grabMouse(); - update(); -} - -void CCurveEditorCtrl::mouseReleaseEvent(QMouseEvent* event) -{ - QWidget::mouseReleaseEvent(event); - if (event->button() != Qt::LeftButton) - { - return; - } - - m_bMouseDown = false; - m_bDragging = false; - m_selectedIndices.clear(); - - releaseMouse(); - update(); -} - -void CCurveEditorCtrl::mouseMoveEvent(QMouseEvent* event) -{ - if (m_bMouseDown && !m_bDragging) - { - m_bDragging = true; - } - - m_bHovered = true; - if (m_flags & eFlag_ShowCursorAlways) - { - m_bHovered = true; - } - else - { - m_bHovered = false; - - for (size_t i = 0; i < m_points.size(); ++i) - { - QPoint ptProj = ProjectPoint(m_points[i].pos.x, m_points[i].pos.y); - QRect rcHandle(0, 0, CurveEditor::kHandleSize, CurveEditor::kHandleSize); - rcHandle.moveCenter(ptProj); - - if (rcHandle.contains(event->pos())) - { - m_bHovered = true; - break; - } - } - } - - if (m_bDragging) - { - Vec2 v1 = UnprojectPoint(m_lastMousePoint); - Vec2 v2 = UnprojectPoint(event->pos()); - Vec2 v = v1 - v2; - - for (size_t i = 0; i < m_selectedIndices.size(); ++i) - { - int index = m_selectedIndices[i]; - CurvePoint& cpt = m_points[index]; - - // do not move first and last points on X - if (index > 0 && index < m_points.size() - 1) - { - cpt.pos.x -= v.x; - } - - cpt.pos.y -= v.y; - - // lets check if the point is overlapping its neighbours - if (index > 0 && (index - 1) > 0) - { - if (cpt.pos.x < m_points[index - 1].pos.x) - { - CurvePoint p = m_points[index]; - - // swap! - m_points[index] = m_points[index - 1]; - m_points[index - 1] = p; - m_selectedIndices[i] = index - 1; - } - } - - if (index < m_points.size() - 1 && (index + 1) < m_points.size() - 1) - { - if (cpt.pos.x > m_points[index + 1].pos.x) - { - CurvePoint p = m_points[index]; - - // swap! - m_points[index] = m_points[index + 1]; - m_points[index + 1] = p; - m_selectedIndices[i] = index + 1; - } - } - - ClampToDomain(cpt.pos); - } - - update(); - m_lastMousePoint = event->pos(); - } - - QWidget::mouseMoveEvent(event); -} - -void CCurveEditorCtrl::MarkX(float value) -{ - m_marksX.push_back(value); -} - -void CCurveEditorCtrl::MarkY(float value) -{ - m_marksY.push_back(value); -} diff --git a/Code/Sandbox/Editor/Controls/CurveEditorCtrl.h b/Code/Sandbox/Editor/Controls/CurveEditorCtrl.h deleted file mode 100644 index 52082febd7..0000000000 --- a/Code/Sandbox/Editor/Controls/CurveEditorCtrl.h +++ /dev/null @@ -1,112 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITOR_CONTROLS_CURVEEDITORCTRL_H -#define CRYINCLUDE_EDITOR_CONTROLS_CURVEEDITORCTRL_H -#pragma once -#include "Util/GdiUtil.h" -#include -#include - - -class CCurveEditorCtrl - : public QWidget -{ -public: - enum EFlags - { - eFlag_ShowVerticalRuler = (1 << 0), - eFlag_ShowHorizontalRuler = (1 << 1), - eFlag_ShowVerticalRulerText = (1 << 2), - eFlag_ShowHorizontalRulerText = (1 << 3), - eFlag_ShowPaddingBorder = (1 << 4), - eFlag_ShowMovingPointAxis = (1 << 5), - eFlag_ShowPointHandles = (1 << 6), - eFlag_ShowCursorAlways = (1 << 7), - eFlag_Disabled = (1 << 8) // special case, when disabling preview window. - }; - - CCurveEditorCtrl(QWidget* parent); - virtual ~CCurveEditorCtrl(); - - void SetFlags(UINT aFlags); - UINT GetFlags() const; - void SetMouseEnable(bool bEnable = true) { m_bAllowMouse = bEnable; } - bool GetMouseEnable() const {return m_bAllowMouse; } - bool SetDomainBounds(float aMinX, float aMinY, float aMaxX, float aMaxY); - void GetDomainBounds(float& rMinX, float& rMinY, float& rMaxX, float& rMaxY) const; - // labelsX/labelsY must be null (to use default labels) - // or contain aHorizontalSplits+1/aVerticalSplits+1 items. - void SetGrid(UINT aHorizontalSplits, UINT aVerticalSplits, const QStringList& labelsX = QStringList(), const QStringList& labelsY = QStringList()); - void SetPadding(float padding) { m_padding = padding; } - void MarkX(float value); - void MarkY(float value); - void AddControlPoint(const Vec2& rPosition); - void ClearControlPoints(); - void SetControlPointCount(UINT aCount); - UINT GetControlPointCount() const; - void SetControlPoint(UINT aIndex, const Vec2& rPosition); - void SetControlPointTangents(UINT aIndex, const Vec2& rLeft, const Vec2& rRight); - void GetControlPoint(UINT aIndex, Vec2& rOutPosition) const; - void GetControlPointTangents(UINT aIndex, Vec2& rOutLeft, Vec2& rOutRight) const; - QPoint ProjectPoint(float x, float y); - Vec2 UnprojectPoint(const QPoint& pt); - void UpdateProjectedPoints(); - -protected: - struct CurvePoint - { - CurvePoint(float aX = 0.0f, float aY = 0.0f) - { - pos.x = aX; - pos.y = aY; - } - - Vec2 pos; - Vec2 tanA, tanB; - }; - - void ComputeTangents(); - void ClampToDomain(Vec2& rVec); - void GenerateDefaultCurve(); - - void paintEvent(QPaintEvent* event) override; - - std::vector m_points; - std::vector m_projectedPoints; - float m_domainMinX; - float m_domainMinY; - float m_domainMaxX; - float m_domainMaxY; - Vec2 m_gridSplits; - int m_padding; - bool m_bMouseDown, m_bDragging, m_bAllowMouse; - bool m_bHovered; - QPoint m_lastMousePoint; - std::vector m_selectedIndices; - QFont m_fntInfo; - QPen m_pen, m_selCrossPen; - UINT m_flags; - QStringList m_labelsX; - QStringList m_labelsY; - std::vector m_marksX; - std::vector m_marksY; - - void mousePressEvent(QMouseEvent* event) override; - void mouseReleaseEvent(QMouseEvent* event) override; - void mouseMoveEvent(QMouseEvent* event) override; -}; - - - -#endif // CRYINCLUDE_EDITOR_CONTROLS_CURVEEDITORCTRL_H diff --git a/Code/Sandbox/Editor/EditorViewportWidget.cpp b/Code/Sandbox/Editor/EditorViewportWidget.cpp index db37653cf1..8afcddd144 100644 --- a/Code/Sandbox/Editor/EditorViewportWidget.cpp +++ b/Code/Sandbox/Editor/EditorViewportWidget.cpp @@ -659,9 +659,6 @@ CBaseObject* EditorViewportWidget::GetCameraObject() const ////////////////////////////////////////////////////////////////////////// void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) { - static ICVar* outputToHMD = gEnv->pConsole->GetCVar("output_to_hmd"); - AZ_Assert(outputToHMD, "cvar output_to_hmd is undeclared"); - switch (event) { case eNotify_OnBeginGameMode: @@ -683,7 +680,6 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (deviceInfo) { // Note: This may also need to adjust the viewport size - outputToHMD->Set(1); SetActiveWindow(); SetFocus(); SetSelected(true); @@ -703,10 +699,6 @@ void EditorViewportWidget::OnEditorNotifyEvent(EEditorNotifyEvent event) if (GetIEditor()->GetViewManager()->GetGameViewport() == this) { SetCurrentCursor(STD_CURSOR_DEFAULT); - if (gSettings.bEnableGameModeVR) - { - outputToHMD->Set(0); - } m_bInRotateMode = false; m_bInMoveMode = false; m_bInOrbitMode = false; diff --git a/Code/Sandbox/Editor/IEditorImpl.cpp b/Code/Sandbox/Editor/IEditorImpl.cpp index 95091a5992..fb9b737733 100644 --- a/Code/Sandbox/Editor/IEditorImpl.cpp +++ b/Code/Sandbox/Editor/IEditorImpl.cpp @@ -71,7 +71,6 @@ AZ_POP_DISABLE_WARNING #include "EditorFileMonitor.h" #include "MainStatusBar.h" -#include "SettingsBlock.h" #include "ResourceSelectorHost.h" #include "Util/FileUtil_impl.h" #include "Util/ImageUtil_impl.h" @@ -1624,8 +1623,6 @@ ESystemConfigPlatform CEditorImpl::GetEditorConfigPlatform() const void CEditorImpl::InitFinished() { - SProjectSettingsBlock::Load(); - if (!m_bInitialized) { m_bInitialized = true; diff --git a/Code/Sandbox/Editor/Include/IResourceSelectorHost.h b/Code/Sandbox/Editor/Include/IResourceSelectorHost.h index f9245f97a4..43586f6cba 100644 --- a/Code/Sandbox/Editor/Include/IResourceSelectorHost.h +++ b/Code/Sandbox/Editor/Include/IResourceSelectorHost.h @@ -28,16 +28,6 @@ // } // REGISTER_RESOURCE_SELECTOR("Sound", SoundFileSelector, "Icons/sound_16x16.png") // -// To expose it to serialization: -// -// #include "Serialization/Decorators/Resources.h" -// template -// ResourceSelector SoundName(TString& s) { return ResourceSelector(s, "Sound"); } -// -// To use in serialization: -// -// ar(Serialization::SoundName(soundString), "soundString", "Sound String"); -// // Here is how it can be invoked directly: // // SResourceSelectorContext x; @@ -56,19 +46,7 @@ // // QString SoundFileSelector(const SResourceSelectorContext& x, const QString& previousValue, // SoundFileList* list) // your context argument -// -// And provide this value through serialization context: -// -// struct SourceFileList -// { -// void Serialize(IArchive& ar) -// { -// Serialization::SContext context(ar, this); -// ... -// } -// } -#include #include class QWidget; @@ -82,7 +60,6 @@ struct SResourceSelectorContext unsigned int entityId; void* contextObject; - Serialization::TypeID contextObjectType; SResourceSelectorContext() : parentWidget(0) @@ -107,7 +84,6 @@ struct IResourceSelectorHost virtual ~IResourceSelectorHost() = default; virtual QString SelectResource(const SResourceSelectorContext& context, const QString& previousValue) = 0; virtual const char* ResourceIconPath(const char* typeName) const = 0; - virtual Serialization::TypeID ResourceContextType(const char* typeName) const = 0; virtual void RegisterResourceSelector(const SStaticResourceSelectorEntry* entry) = 0; @@ -128,7 +104,6 @@ struct SStaticResourceSelectorEntry TResourceSelectionFunction function; TResourceSelectionFunctionWithContext functionWithContext; const char* iconPath; - Serialization::TypeID contextType; static SStaticResourceSelectorEntry*& GetFirst() { static SStaticResourceSelectorEntry* first; return first; } SStaticResourceSelectorEntry* next; @@ -150,7 +125,6 @@ struct SStaticResourceSelectorEntry , functionWithContext(TResourceSelectionFunctionWithContext(function)) , iconPath(icon) { - contextType = Serialization::TypeID::get(); next = GetFirst(); GetFirst() = this; } diff --git a/Code/Sandbox/Editor/ResourceSelectorHost.cpp b/Code/Sandbox/Editor/ResourceSelectorHost.cpp index 6711af0af0..cf08d7f4d4 100644 --- a/Code/Sandbox/Editor/ResourceSelectorHost.cpp +++ b/Code/Sandbox/Editor/ResourceSelectorHost.cpp @@ -72,16 +72,6 @@ public: return ""; } - Serialization::TypeID ResourceContextType(const char* typeName) const override - { - TTypeMap::const_iterator it = m_typeMap.find(typeName); - if (it != m_typeMap.end()) - { - return it->second->contextType; - } - return Serialization::TypeID(); - } - void RegisterResourceSelector(const SStaticResourceSelectorEntry* entry) override { m_typeMap[entry->typeName] = entry; diff --git a/Code/Sandbox/Editor/Serialization.h b/Code/Sandbox/Editor/Serialization.h deleted file mode 100644 index 85dfc35dc6..0000000000 --- a/Code/Sandbox/Editor/Serialization.h +++ /dev/null @@ -1,26 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITOR_SERIALIZATION_H -#define CRYINCLUDE_EDITOR_SERIALIZATION_H - -#include -#include -#include -#include -#include - -using Serialization::IArchive; - -#endif // CRYINCLUDE_EDITOR_SERIALIZATION_H diff --git a/Code/Sandbox/Editor/Serialization/VariableIArchive.cpp b/Code/Sandbox/Editor/Serialization/VariableIArchive.cpp deleted file mode 100644 index 235ec9a6b0..0000000000 --- a/Code/Sandbox/Editor/Serialization/VariableIArchive.cpp +++ /dev/null @@ -1,283 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "VariableIArchive.h" - -// Editor -#include "Serialization/Decorators/Resources.h" -#include "Serialization/Decorators/Range.h" - - -using Serialization::CVariableIArchive; - -namespace VarUtil -{ - _smart_ptr< IVariable > FindChildVariable(const _smart_ptr< IVariable >& pParent, const int childIndexOverride, const char* const name) - { - if (0 <= childIndexOverride) - { - return pParent->GetVariable(childIndexOverride); - } - else - { - const bool shouldSearchRecursively = false; - return pParent->FindVariable(name, shouldSearchRecursively); - } - } - - - template< typename T, typename TOut > - bool ReadChildVariableAs(const _smart_ptr< IVariable >& pParent, const int childIndexOverride, const char* const name, TOut& valueOut) - { - _smart_ptr< IVariable > pVariable = FindChildVariable(pParent, childIndexOverride, name); - if (pVariable) - { - T tmp; - pVariable->Get(tmp); - valueOut = static_cast< TOut >(tmp); - return true; - } - return false; - } - - - template< typename T > - bool ReadChildVariable(const _smart_ptr< IVariable >& pParent, const int childIndexOverride, const char* const name, T& valueOut) - { - return ReadChildVariableAs< T >(pParent, childIndexOverride, name, valueOut); - } -} - - - -CVariableIArchive::CVariableIArchive(const _smart_ptr< IVariable >& pVariable) - : IArchive(IArchive::INPUT | IArchive::EDIT | IArchive::NO_EMPTY_NAMES) - , m_pVariable(pVariable) - , m_childIndexOverride(-1) -{ - CRY_ASSERT(m_pVariable); - - m_structHandlers[ TypeID::get < Serialization::IResourceSelector > ().name() ] = &CVariableIArchive::SerializeResourceSelector; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < float >> ().name() ] = &CVariableIArchive::SerializeRangeFloat; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < int >> ().name() ] = &CVariableIArchive::SerializeRangeInt; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < unsigned int >> ().name() ] = &CVariableIArchive::SerializeRangeUInt; - m_structHandlers[ TypeID::get < StringListStaticValue > ().name() ] = &CVariableIArchive::SerializeStringListStaticValue; -} - - -CVariableIArchive::~CVariableIArchive() -{ -} - - -bool CVariableIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< bool >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(Serialization::IString& value, const char* name, [[maybe_unused]] const char* label) -{ - QString stringValue; - const bool readSuccess = VarUtil::ReadChildVariableAs< QString >(m_pVariable, m_childIndexOverride, name, stringValue); - if (readSuccess) - { - value.set(stringValue.toUtf8().data()); - return true; - } - return false; -} - - -bool CVariableIArchive::operator()([[maybe_unused]] Serialization::IWString& value, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) -{ - CryFatalError("CVariableIArchive::operator() with IWString is not implemented"); - return false; -} - - -bool CVariableIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< float >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< float >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) -{ - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, value); -} - - -bool CVariableIArchive::operator()(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const char* const typeName = ser.type().name(); - HandlersMap::const_iterator it = m_structHandlers.find(typeName); - const bool handlerFound = (it != m_structHandlers.end()); - if (handlerFound) - { - StructHandlerFunctionPtr pHandler = it->second; - return (this->*pHandler)(ser, name, label); - } - - return SerializeStruct(ser, name, label); -} - - -bool CVariableIArchive::operator()(Serialization::IContainer& ser, const char* name, [[maybe_unused]] const char* label) -{ - _smart_ptr< IVariable > pChild = VarUtil::FindChildVariable(m_pVariable, m_childIndexOverride, name); - if (pChild) - { - const int elementCount = pChild->GetNumVariables(); - ser.resize(elementCount); - - if (0 < elementCount) - { - CVariableIArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - for (int i = 0; i < elementCount; ++i) - { - childArchive.m_childIndexOverride = i; - - ser(childArchive, "", ""); - ser.next(); - } - } - return true; - } - return false; -} - - -bool CVariableIArchive::SerializeStruct(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - _smart_ptr< IVariable > pChild = VarUtil::FindChildVariable(m_pVariable, m_childIndexOverride, name); - if (pChild) - { - CVariableIArchive childArchive(pChild); - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - ser(childArchive); - return true; - } - return false; -} - -bool CVariableIArchive::SerializeResourceSelector(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - Serialization::IResourceSelector* pSelector = reinterpret_cast< Serialization::IResourceSelector* >(ser.pointer()); - - QString stringValue; - const bool readSuccess = VarUtil::ReadChildVariableAs< QString >(m_pVariable, m_childIndexOverride, name, stringValue); - if (readSuccess) - { - pSelector->SetValue(stringValue.toUtf8().data()); - return true; - } - return false; -} - - -bool CVariableIArchive::SerializeStringListStaticValue(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - StringListStaticValue* const pStringListStaticValue = reinterpret_cast< StringListStaticValue* >(ser.pointer()); - - _smart_ptr< IVariable > pChild = VarUtil::FindChildVariable(m_pVariable, m_childIndexOverride, name); - if (pChild) - { - int index = -1; - pChild->Get(index); - *pStringListStaticValue = index; - return true; - } - return false; -} - - -bool CVariableIArchive::SerializeRangeFloat(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - const Serialization::RangeDecorator< float >* const pRange = reinterpret_cast< Serialization::RangeDecorator< float >* >(ser.pointer()); - return VarUtil::ReadChildVariableAs< float >(m_pVariable, m_childIndexOverride, name, *pRange->value); -} - - -bool CVariableIArchive::SerializeRangeInt(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - const Serialization::RangeDecorator< int >* const pRange = reinterpret_cast< Serialization::RangeDecorator< int >* >(ser.pointer()); - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, *pRange->value); -} - -bool CVariableIArchive::SerializeRangeUInt(const Serialization::SStruct& ser, const char* name, [[maybe_unused]] const char* label) -{ - const Serialization::RangeDecorator< unsigned int >* const pRange = reinterpret_cast< Serialization::RangeDecorator< unsigned int >* >(ser.pointer()); - return VarUtil::ReadChildVariableAs< int >(m_pVariable, m_childIndexOverride, name, *pRange->value); -} diff --git a/Code/Sandbox/Editor/Serialization/VariableIArchive.h b/Code/Sandbox/Editor/Serialization/VariableIArchive.h deleted file mode 100644 index ac7c0532e4..0000000000 --- a/Code/Sandbox/Editor/Serialization/VariableIArchive.h +++ /dev/null @@ -1,71 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "Util/Variable.h" -#include "Serialization.h" - -namespace Serialization -{ - class CVariableIArchive - : public IArchive - { - public: - CVariableIArchive(const _smart_ptr< IVariable >& pVariable); - virtual ~CVariableIArchive(); - - // IArchive - virtual bool operator()(bool& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(IString& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(IWString& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(float& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(double& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int16& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint16& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int32& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint32& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int64& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint64& value, const char* name = "", const char* label = 0) override; - - virtual bool operator()(int8& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint8& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(char& value, const char* name = "", const char* label = 0); - - virtual bool operator()(const SStruct& ser, const char* name = "", const char* label = 0) override; - virtual bool operator()(IContainer& ser, const char* name = "", const char* label = 0) override; - //virtual bool operator()( IPointer& ptr, const char* name = "", const char* label = 0 ) override; - // ~IArchive - - using IArchive::operator(); - - private: - bool SerializeResourceSelector(const SStruct& ser, const char* name, const char* label); - - bool SerializeStruct(const SStruct& ser, const char* name, const char* label); - - bool SerializeStringListStaticValue(const SStruct& ser, const char* name, const char* label); - - bool SerializeRangeFloat(const SStruct& ser, const char* name, const char* label); - bool SerializeRangeInt(const SStruct& ser, const char* name, const char* label); - bool SerializeRangeUInt(const SStruct& ser, const char* name, const char* label); - - private: - _smart_ptr< IVariable > m_pVariable; - int m_childIndexOverride; - - typedef bool ( CVariableIArchive::* StructHandlerFunctionPtr )(const SStruct&, const char*, const char*); - typedef std::map< string, StructHandlerFunctionPtr > HandlersMap; - HandlersMap m_structHandlers; // TODO: have only one of these. - }; -} diff --git a/Code/Sandbox/Editor/Serialization/VariableOArchive.cpp b/Code/Sandbox/Editor/Serialization/VariableOArchive.cpp deleted file mode 100644 index d5c53d1966..0000000000 --- a/Code/Sandbox/Editor/Serialization/VariableOArchive.cpp +++ /dev/null @@ -1,416 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "VariableOArchive.h" - -// Editor -#include "Serialization/Decorators/Resources.h" -#include "Serialization/Decorators/Range.h" - - -using Serialization::CVariableOArchive; - -namespace VarUtil -{ - template< typename T > - _smart_ptr< IVariable > AddChildVariable(const _smart_ptr< IVariable >& pVariableArray, const T& value, const char* const name, const char* label) - { - CRY_ASSERT(pVariableArray); - - _smart_ptr< IVariable > pVariable = new CVariable< T >(); - pVariable->SetName(name); - pVariable->SetHumanName(label); - pVariable->Set(value); - - pVariableArray->AddVariable(pVariable); - - return pVariable; - } - - template< typename TMin, typename TMax > - void SetLimits(const _smart_ptr< IVariable >& pVariable, const TMin minValue, const TMax maxValue) - { - pVariable->SetLimits(static_cast< float >(minValue), static_cast< float >(maxValue)); - } -} - -CVariableOArchive::CVariableOArchive() - : IArchive(IArchive::OUTPUT | IArchive::EDIT | IArchive::NO_EMPTY_NAMES) - , m_pVariable(new CVariableArray()) -{ - m_resourceHandlers[ "Animation" ] = &CVariableOArchive::SerializeAnimationName; - m_resourceHandlers[ "Sound" ] = &CVariableOArchive::SerializeSoundName; - m_resourceHandlers[ "Model" ] = &CVariableOArchive::SerializeObjectFilename; - - m_structHandlers[ TypeID::get < Serialization::IResourceSelector > ().name() ] = &CVariableOArchive::SerializeIResourceSelector; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < float >> ().name() ] = &CVariableOArchive::SerializeRangeFloat; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < int >> ().name() ] = &CVariableOArchive::SerializeRangeInt; - m_structHandlers[ TypeID::get < Serialization::RangeDecorator < unsigned int >> ().name() ] = &CVariableOArchive::SerializeRangeUInt; - m_structHandlers[ TypeID::get < StringListStaticValue > ().name() ] = &CVariableOArchive::SerializeStringListStaticValue; -} - - -CVariableOArchive::~CVariableOArchive() -{ -} - - -_smart_ptr< IVariable > CVariableOArchive::GetIVariable() const -{ - return m_pVariable; -} - - -CVarBlockPtr CVariableOArchive::GetVarBlock() const -{ - CVarBlockPtr pVarBlock = new CVarBlock(); - pVarBlock->AddVariable(m_pVariable); - return pVarBlock; -} - - -bool CVariableOArchive::operator()(bool& value, const char* name, const char* label) -{ - VarUtil::AddChildVariable< bool >(m_pVariable, value, name, label); - return true; -} - - -bool CVariableOArchive::operator()(Serialization::IString& value, const char* name, const char* label) -{ - const QString valueString = value.get(); - VarUtil::AddChildVariable< QString >(m_pVariable, valueString, name, label); - return true; -} - - -bool CVariableOArchive::operator()([[maybe_unused]] Serialization::IWString& value, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) -{ - CryFatalError("CVarBlockOArchive::operator() with IWString is not implemented"); - return false; -} - - -bool CVariableOArchive::operator()(float& value, const char* name, const char* label) -{ - VarUtil::AddChildVariable< float >(m_pVariable, value, name, label); - return true; -} - - -bool CVariableOArchive::operator()(double& value, const char* name, const char* label) -{ - VarUtil::AddChildVariable< float >(m_pVariable, value, name, label); - return true; -} - - -bool CVariableOArchive::operator()(int16& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, SHRT_MIN, SHRT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(uint16& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, 0, USHRT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(int32& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, INT_MIN, INT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(uint32& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, 0, INT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(int64& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, INT_MIN, INT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(uint64& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, 0, INT_MAX); - return true; -} - - -bool CVariableOArchive::operator()(int8& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, SCHAR_MIN, SCHAR_MAX); - return true; -} - - -bool CVariableOArchive::operator()(uint8& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, 0, UCHAR_MAX); - return true; -} - - -bool CVariableOArchive::operator()(char& value, const char* name, const char* label) -{ - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, value, name, label); - VarUtil::SetLimits(pVariable, CHAR_MIN, CHAR_MAX); - return true; -} - - -bool CVariableOArchive::operator()(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const char* const typeName = ser.type().name(); - HandlersMap::const_iterator it = m_structHandlers.find(typeName); - const bool handlerFound = (it != m_structHandlers.end()); - if (handlerFound) - { - StructHandlerFunctionPtr pHandler = it->second; - return (this->*pHandler)(ser, name, label); - } - - return SerializeStruct(ser, name, label); -} - -static const char* gVec4Names[] = { "X", "Y", "Z", "W" }; -static const char* gEmptyNames[] = { "" }; - -bool CVariableOArchive::operator()(Serialization::IContainer& ser, const char* name, const char* label) -{ - CVariableOArchive childArchive; - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - _smart_ptr< IVariable > pChildVariable = childArchive.GetIVariable(); - pChildVariable->SetName(name); - pChildVariable->SetHumanName(label); - - m_pVariable->AddVariable(pChildVariable); - - const size_t containerSize = ser.size(); - - const char** nameArray = gEmptyNames; - size_t nameArraySize = 1; - if (containerSize >= 2 && containerSize <= 4) - { - nameArray = gVec4Names; - nameArraySize = containerSize; - } - - size_t index = 0; - if (0 < containerSize) - { - do - { - ser(childArchive, nameArray[index % nameArraySize], nameArray[index % nameArraySize]); - ++index; - } while (ser.next()); - } - - return true; -} - - -bool CVariableOArchive::SerializeStruct(const Serialization::SStruct& ser, const char* name, const char* label) -{ - CVariableOArchive childArchive; - childArchive.SetFilter(GetFilter()); - childArchive.SetInnerContext(GetInnerContext()); - - _smart_ptr< IVariable > pChildVariable = childArchive.GetIVariable(); - pChildVariable->SetName(name); - pChildVariable->SetHumanName(label); - - m_pVariable->AddVariable(pChildVariable); - - const bool serializeSuccess = ser(childArchive); - - return serializeSuccess; -} - - -bool CVariableOArchive::SerializeAnimationName(const Serialization::IResourceSelector* pSelector, const char* name, const char* label) -{ - const QString valueString = pSelector->GetValue(); - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< QString >(m_pVariable, valueString, name, label); - pVariable->SetDataType(IVariable::DT_ANIMATION); - - return true; -} - - -bool CVariableOArchive::SerializeSoundName(const Serialization::IResourceSelector* pSelector, const char* name, const char* label) -{ - const QString valueString = pSelector->GetValue(); - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< QString >(m_pVariable, valueString, name, label); - pVariable->SetDataType(IVariable::DT_AUDIO_TRIGGER); - - return true; -} - -void CVariableOArchive::CreateChildEnumVariable(const QStringList& enumValues, const QString& value, const char* name, const char* label) -{ - if (enumValues.empty()) - { - VarUtil::AddChildVariable< QString >(m_pVariable, value, name, label); - } - else - { - _smart_ptr< CVariableEnum< QString > > pVariable = new CVariableEnum< QString >(); - pVariable->SetName(name); - pVariable->SetHumanName(label); - - pVariable->AddEnumItem("", ""); - - const size_t enumValuesCount = enumValues.size(); - for (size_t i = 0; i < enumValuesCount; ++i) - { - pVariable->AddEnumItem(enumValues[ i ], enumValues[ i ]); - } - - pVariable->Set(value); - - m_pVariable->AddVariable(pVariable); - } -} - -bool CVariableOArchive::SerializeObjectFilename(const Serialization::IResourceSelector* pSelector, const char* name, const char* label) -{ - const QString valueString = pSelector->GetValue(); - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< QString >(m_pVariable, valueString, name, label); - pVariable->SetDataType(IVariable::DT_OBJECT); - - return true; -} - - -bool CVariableOArchive::SerializeStringListStaticValue(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const StringListStaticValue* const pStringListStaticValue = reinterpret_cast< StringListStaticValue* >(ser.pointer()); - const StringListStatic& stringListStatic = pStringListStaticValue->stringList(); - const int index = pStringListStaticValue->index(); - - _smart_ptr< CVariableEnum< int > > pVariable = new CVariableEnum< int >(); - pVariable->SetName(name); - pVariable->SetHumanName(label); - - const size_t stringListStaticSize = stringListStatic.size(); - for (size_t i = 0; i < stringListStaticSize; ++i) - { - pVariable->AddEnumItem(stringListStatic[ i ], static_cast< int >(i)); - } - - if (0 <= index) - { - CRY_ASSERT(index < stringListStaticSize); - pVariable->Set(static_cast< int >(index)); - } - - m_pVariable->AddVariable(pVariable); - - return true; -} - -bool CVariableOArchive::SerializeIResourceSelector(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const Serialization::IResourceSelector* pSelector = reinterpret_cast< Serialization::IResourceSelector* >(ser.pointer()); - - ResourceHandlersMap::iterator it = m_resourceHandlers.find(pSelector->resourceType); - if (it != m_resourceHandlers.end()) - { - return (this->*(it->second))(pSelector, name, label); - } - return false; -} - -template -static void SetLimits(IVariable* pVariable, const Serialization::RangeDecorator* pRange, float stepValue) -{ - if (pRange->softMin != std::numeric_limits::lowest() || pRange->softMax != std::numeric_limits::max()) - { - float minimal = (float)pRange->softMin; - float maximal = (float)pRange->softMax; - bool hardMin = false; - bool hardMax = false; - if (pRange->hardMin != std::numeric_limits::lowest()) - { - minimal = pRange->hardMin; - hardMin = true; - } - if (pRange->hardMax != std::numeric_limits::max()) - { - maximal = pRange->hardMax; - hardMax = true; - } - pVariable->SetLimits(minimal, maximal, stepValue, hardMin, hardMax); - } - else - { - float minimal = 0.0f; - float maximal = 0.0f; - float oldStep = 0.0f; - bool hardMin = false; - bool hardMax = false; - pVariable->GetLimits(minimal, maximal, oldStep, hardMin, hardMax); - pVariable->SetLimits(minimal, maximal, stepValue, hardMin, hardMax); - } -} - -bool CVariableOArchive::SerializeRangeFloat(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const Serialization::RangeDecorator< float >* const pRange = reinterpret_cast< Serialization::RangeDecorator< float >* >(ser.pointer()); - - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< float >(m_pVariable, *pRange->value, name, label); - - SetLimits(pVariable.get(), pRange, 0.01f); - return true; -} - -bool CVariableOArchive::SerializeRangeInt(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const Serialization::RangeDecorator< int >* const pRange = reinterpret_cast< Serialization::RangeDecorator< int >* >(ser.pointer()); - - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, *pRange->value, name, label); - SetLimits(pVariable.get(), pRange, 1.0f); - return true; -} - -bool CVariableOArchive::SerializeRangeUInt(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const Serialization::RangeDecorator< unsigned int >* const pRange = reinterpret_cast< Serialization::RangeDecorator< unsigned int >* >(ser.pointer()); - - _smart_ptr< IVariable > pVariable = VarUtil::AddChildVariable< int >(m_pVariable, *pRange->value, name, label); - SetLimits(pVariable, pRange, 1.0f); - return true; -} diff --git a/Code/Sandbox/Editor/Serialization/VariableOArchive.h b/Code/Sandbox/Editor/Serialization/VariableOArchive.h deleted file mode 100644 index 60de8f84ac..0000000000 --- a/Code/Sandbox/Editor/Serialization/VariableOArchive.h +++ /dev/null @@ -1,83 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "Util/Variable.h" -#include "Serialization.h" - - -namespace Serialization -{ - struct IResourceSelector; - - class CVariableOArchive - : public IArchive - { - public: - CVariableOArchive(); - virtual ~CVariableOArchive(); - - _smart_ptr< IVariable > GetIVariable() const; - CVarBlockPtr GetVarBlock() const; - - // IArchive - virtual bool operator()(bool& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(IString& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(IWString& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(float& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(double& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int16& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint16& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int32& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint32& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(int64& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint64& value, const char* name = "", const char* label = 0) override; - - virtual bool operator()(int8& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(uint8& value, const char* name = "", const char* label = 0) override; - virtual bool operator()(char& value, const char* name = "", const char* label = 0); - - virtual bool operator()(const SStruct& ser, const char* name = "", const char* label = 0) override; - virtual bool operator()(IContainer& ser, const char* name = "", const char* label = 0) override; - //virtual bool operator()( IPointer& ptr, const char* name = "", const char* label = 0 ) override; - // ~IArchive - - using IArchive::operator(); - - private: - bool SerializeStruct(const SStruct& ser, const char* name, const char* label); - bool SerializeStringListStaticValue(const SStruct& ser, const char* name, const char* label); - bool SerializeRangeFloat(const SStruct& ser, const char* name, const char* label); - bool SerializeRangeInt(const SStruct& ser, const char* name, const char* label); - bool SerializeRangeUInt(const SStruct& ser, const char* name, const char* label); - bool SerializeIResourceSelector(const SStruct& ser, const char* name, const char* label); - - bool SerializeAnimationName(const IResourceSelector* pSelector, const char* name, const char* label); - bool SerializeSoundName(const IResourceSelector* pSelector, const char* name, const char* label); - bool SerializeObjectFilename(const IResourceSelector* pSelector, const char* name, const char* label); - - void CreateChildEnumVariable(const QStringList& enumValues, const QString& value, const char* name, const char* label); - - private: - _smart_ptr< IVariable > m_pVariable; - - typedef bool ( CVariableOArchive::* StructHandlerFunctionPtr )(const SStruct&, const char*, const char*); - typedef std::map< string, StructHandlerFunctionPtr > HandlersMap; - HandlersMap m_structHandlers; // TODO: have only one of these. - - typedef bool ( CVariableOArchive::* ResourceHandlerFunctionPtr )(const IResourceSelector*, const char*, const char*); - typedef std::map< string, ResourceHandlerFunctionPtr > ResourceHandlersMap; - ResourceHandlersMap m_resourceHandlers; - }; -} diff --git a/Code/Sandbox/Editor/SettingsBlock.cpp b/Code/Sandbox/Editor/SettingsBlock.cpp deleted file mode 100644 index d9f596c2d0..0000000000 --- a/Code/Sandbox/Editor/SettingsBlock.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorDefs.h" - -#include "SettingsBlock.h" - -// CryCommon -#include -#include - -// Editor -#include "Serialization.h" - -using std::vector; - -SProjectSettingsBlock* SProjectSettingsBlock::s_pLastBlock; - -SProjectSettingsBlock::SProjectSettingsBlock(const char* name, const char* label) - : m_name(name) - , m_label(label) -{ - m_pPrevious = s_pLastBlock; - s_pLastBlock = this; -} - - -struct SAllSettingsSerializer -{ - void Serialize(Serialization::IArchive& ar) - { - SProjectSettingsBlock* pCurrent = SProjectSettingsBlock::s_pLastBlock; - while (pCurrent != 0) - { - ar(*pCurrent, pCurrent->GetName(), pCurrent->GetLabel()); - pCurrent = pCurrent->m_pPrevious; - } - } -} static gAllSettingsSerializer; - -void SProjectSettingsBlock::GetAllSettingsSerializer(Serialization::SStruct* pSerializer) -{ - *pSerializer = Serialization::SStruct(gAllSettingsSerializer); -} - -SProjectSettingsBlock* SProjectSettingsBlock::Find(const char* blockName) -{ - SProjectSettingsBlock* pCurrent = SProjectSettingsBlock::s_pLastBlock; - while (pCurrent != 0) - { - if (_stricmp(pCurrent->GetName(), blockName) == 0) - { - return pCurrent; - } - } - return 0; -} - -static bool ReadFileContent(vector* pBuffer, const char* filename) -{ - AZ::IO::HandleType fileHandle = gEnv->pCryPak->FOpen(filename, "rb"); - if (fileHandle == AZ::IO::InvalidHandle) - { - return false; - } - - size_t size = gEnv->pCryPak->FGetSize(fileHandle); - pBuffer->resize(size); - - bool result = true; - if (gEnv->pCryPak->FRead(&(*pBuffer)[0], size, fileHandle) != size) - { - result = false; - } - gEnv->pCryPak->FClose(fileHandle); - return result; -} - -static bool SaveFileContent(const char* filename, const char* pBuffer, size_t length) -{ - string fullpath = Path::GamePathToFullPath(filename).toUtf8().data(); - - AZ::IO::HandleType fileHandle = AZ::IO::InvalidHandle; - if (!gEnv->pFileIO->Open(fullpath.c_str(), AZ::IO::GetOpenModeFromStringMode("wb"), fileHandle)) - { - return false; - } - - bool result = true; - if (!gEnv->pFileIO->Write(fileHandle, pBuffer, length)) - { - result = false; - } - - gEnv->pFileIO->Close(fileHandle); - return result; -} - -static bool SaveFileContentIfDiffers(const char* filename, const char* pBuffer, size_t length) -{ - vector content; - ReadFileContent(&content, filename); - - bool needToWrite = true; - if (!content.empty() && content.size() == length) - { - needToWrite = memcmp(&content[0], pBuffer, length) != 0; - } - - if (needToWrite) - { - return SaveFileContent(filename, pBuffer, length); - } - else - { - return true; - } -} - -bool SProjectSettingsBlock::Load() -{ - const char* filename = GetFilename(); - - vector content; - if (!ReadFileContent(&content, filename)) - { - return false; - } - - auto pArchive(Serialization::CreateTextInputArchive()); - if (!pArchive) - { - return false; - } - - if (!pArchive->AttachMemory(&content[0], content.size())) - { - return false; - } - - Serialization::SStruct serializer; - GetAllSettingsSerializer(&serializer); - serializer(*pArchive); - return true; -} - -bool SProjectSettingsBlock::Save() -{ - const char* filename = GetFilename(); - auto pArchive(Serialization::CreateTextOutputArchive()); - if (!pArchive) - { - return false; - } - - Serialization::SStruct serializer; - GetAllSettingsSerializer(&serializer); - serializer(*pArchive); - - return SaveFileContentIfDiffers(filename, pArchive->GetBuffer(), pArchive->GetBufferLength()); -} - -const char* SProjectSettingsBlock::GetFilename() -{ - return "SandboxSettings.json"; -} - diff --git a/Code/Sandbox/Editor/SettingsBlock.h b/Code/Sandbox/Editor/SettingsBlock.h deleted file mode 100644 index b67e1d3d7e..0000000000 --- a/Code/Sandbox/Editor/SettingsBlock.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -// --------------------------------------------------------------------------- -// Following utility can be used to add blocks of per-project settings. -// Example: -// -// MyComponent.cpp: -// -// struct SProjectSettingsMy : SProjectSettingsBlock -// { -// bool bMyOption; -// -// SProjectSettingsMy() -// : SProjectSettingsBlock("my", "My") -// , bMyOption(false) -// {} -// -// void Serialize(Serialization::IArchive& ar) -// { -// ar(bMyOption, "myOption", "My Option"); -// } -// -// } static gMySettings; -// -// -// Now gMySettings will be loaded and saved automatically and available for -// editing through: -// -// GetIEditor()->OpenProjectSettings("my"); -// -// --------------------------------------------------------------------------- -#ifndef CRYINCLUDE_EDITOR_SETTINGSBLOCK_H -#define CRYINCLUDE_EDITOR_SETTINGSBLOCK_H - -namespace Serialization -{ - class IArchive; - struct SStruct; -}; - -struct SProjectSettingsBlock -{ - SProjectSettingsBlock(const char* name, const char* label); - - virtual void Serialize(Serialization::IArchive& ar) = 0; - - const char* GetName() const{ return m_name; } - const char* GetLabel() const{ return m_label; } - - static void GetAllSettingsSerializer(Serialization::SStruct* serializer); - static SProjectSettingsBlock* Find(const char* name); - static bool Load(); - static bool Save(); - static const char* GetFilename(); -private: - const char* m_name; - const char* m_label; - SProjectSettingsBlock* m_pPrevious; - static SProjectSettingsBlock* s_pLastBlock; - friend struct SAllSettingsSerializer; -}; - -#endif // CRYINCLUDE_EDITOR_SETTINGSBLOCK_H diff --git a/Code/Sandbox/Editor/editor_lib_files.cmake b/Code/Sandbox/Editor/editor_lib_files.cmake index 4832e2b8c2..3d6112d186 100644 --- a/Code/Sandbox/Editor/editor_lib_files.cmake +++ b/Code/Sandbox/Editor/editor_lib_files.cmake @@ -357,8 +357,6 @@ set(FILES Controls/ConsoleSCB.h Controls/ConsoleSCB.ui Controls/ConsoleSCB.qrc - Controls/CurveEditorCtrl.cpp - Controls/CurveEditorCtrl.h Controls/FolderTreeCtrl.cpp Controls/FolderTreeCtrl.h Controls/HotTrackingTreeCtrl.cpp @@ -575,11 +573,6 @@ set(FILES QtUI/WaitCursor.cpp RenderHelpers/AxisHelper.cpp RenderHelpers/AxisHelper.h - Serialization.h - Serialization/VariableOArchive.cpp - Serialization/VariableOArchive.h - Serialization/VariableIArchive.cpp - Serialization/VariableIArchive.h CustomizeKeyboardDialog.h CustomizeKeyboardDialog.cpp CustomizeKeyboardDialog.ui @@ -738,8 +731,6 @@ set(FILES TrackView/TrackViewEventNode.h ConfigGroup.cpp ConfigGroup.h - SettingsBlock.cpp - SettingsBlock.h Util/AffineParts.h Util/AutoLogTime.cpp Util/AutoLogTime.h diff --git a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp index e5ad2a2872..54ac71db16 100644 --- a/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp +++ b/Code/Sandbox/Plugins/ComponentEntityEditorPlugin/ComponentEntityEditorPlugin.cpp @@ -15,7 +15,6 @@ #include #include "IResourceSelectorHost.h" -#include "CryExtension/ICryFactoryRegistry.h" #include "UI/QComponentEntityEditorMainWindow.h" #include "UI/QComponentEntityEditorOutlinerWindow.h" diff --git a/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.cpp b/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.cpp deleted file mode 100644 index 0dc7a8e7dc..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.cpp +++ /dev/null @@ -1,357 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "BatchFileDialog.h" -#include "QPropertyTree/QPropertyDialog.h" -#include "Serialization/StringList.h" -#include "Serialization/STL.h" -#include "Serialization/IArchive.h" -#include "Serialization/STLImpl.h" -#include "IEditor.h" -#include "Pak/CryPakUtils.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -struct SBatchFileItem -{ - bool selected; - string path; - bool checkable = false; - - bool operator<(const SBatchFileItem& rhs) const { return path < rhs.path; } - - void Serialize(Serialization::IArchive& ar) - { - // ------------------------------------------------------------------- - // Note: The property tree label modifiers used below indicate... - // ! - Readonly, you can't modify the path - // ^ - Raise location to the parent (the index indicator) - // < - Take up the rest of the space - // ------------------------------------------------------------------- - if (!checkable) - { - ar(selected, "selected", "^"); - } - - auto gamePath = PathUtil::MakeGamePath(path); - ar(gamePath, "path", "!^<"); - } -}; -typedef std::vector SBatchFileItems; - -struct CBatchFileDialog::SContent -{ - SBatchFileItems items; - string listLabel; - - SContent(const char* itemsLabelText, bool readonlyList) - { - // Respect the readonly settings - if (readonlyList) - { - listLabel += "!"; - } - - // Label Size (5px per character) - auto labelSize = static_cast(strlen(itemsLabelText)) * 5; - { - // Format is: >#>+ where the >#> indicates the label size, and the + indicates end of all row formatting - char buffer[16]; - sprintf_s(buffer, sizeof(buffer), ">%i>+", labelSize); - listLabel += buffer; - } - - // Add the actual label text (the text that is seen) - listLabel += itemsLabelText; - } - - void Serialize(Serialization::IArchive& ar) - { - ar(items, "items", listLabel.c_str()); - } -}; - -static bool ReadFile(std::vector* buffer, const char* path) -{ - FILE* f = nullptr; - azfopen(&f, path, "rb"); - if (!f) - { - return false; - } - fseek(f, 0, SEEK_END); - size_t len = (size_t)ftell(f); - fseek(f, 0, SEEK_SET); - - buffer->resize(len); - bool result = true; - if (len) - { - result = fread(&(*buffer)[0], 1, len, f) == len; - } - fclose(f); - return result; -} - -static void SplitLines(std::vector* lines, const char* start, const char* end) -{ - const char* p = start; - const char* lineStart = start; - while (true) - { - if (p == end || *p == '\r' || *p == '\n') - { - if (p != lineStart) - { - string line(lineStart, p); - bool hasPrintableChars = false; - for (size_t i = 0; i < line.size(); ++i) - { - if (!isspace(line[i])) - { - hasPrintableChars = true; - } - } - if (hasPrintableChars) - { - lines->push_back(line); - } - } - lineStart = p + 1; - if (p == end) - { - break; - } - } - ++p; - } -} - -static string NormalizePath(const char* path) -{ - string result = path; - result.replace('\\', '/'); - result.MakeLower(); - - // strip .phys extensions in case list of .cdf is provided - string::size_type dotPos = result.rfind('.'); - if (dotPos != string::npos) - { - if (_stricmp(result.c_str() + dotPos, ".phys")) - { - result.erase(dotPos, 5); - } - } - return result; -} - -static bool IsEquivalentPath(const char* pathA, const char* pathB) -{ - string normalizedA = NormalizePath(pathA); - string normalizedB = NormalizePath(pathB); - return normalizedA == normalizedB; -} - -void CBatchFileDialog::OnLoadList() -{ - QString existingFile = QFileDialog::getOpenFileName(m_dialog, "Load file list...", QString(), QString("Text Files (*.txt)")); - if (existingFile.isEmpty()) - { - return; - } - - string path = existingFile.toLocal8Bit().data(); - std::vector content; - ReadFile(&content, path.c_str()); - - std::vector lines; - SplitLines(&lines, &content[0], &content[0] + content.size()); - - for (size_t i = 0; i < m_content->items.size(); ++i) - { - m_content->items[i].selected = false; - } - - for (size_t i = 0; i < lines.size(); ++i) - { - const char* line = lines[i].c_str(); - for (size_t j = 0; j < m_content->items.size(); ++j) - { - const char* itemPath = m_content->items[j].path.c_str(); - if (IsEquivalentPath(line, itemPath)) - { - m_content->items[j].selected = true; - break; - } - } - } - - m_dialog->revert(); -} - -void CBatchFileDialog::OnSelectAll() -{ - for (size_t i = 0; i < m_content->items.size(); ++i) - { - m_content->items[i].selected = true; - } - - m_dialog->revert(); -} - -void CBatchFileDialog::OnSelectNone() -{ - for (size_t i = 0; i < m_content->items.size(); ++i) - { - m_content->items[i].selected = false; - } - - m_dialog->revert(); -} - -bool EDITOR_COMMON_API ShowBatchFileDialog(Serialization::StringList* result, const SBatchFileSettings& settings, QWidget* parent) -{ - QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); - - CBatchFileDialog::SContent content(settings.listLabel, settings.readonlyList); - if (settings.scanExtension[0] != '\0') - { - if (settings.useCryPak) - { - AZStd::vector files; - - string mask = "*."; - mask += settings.scanExtension; - SDirectoryEnumeratorHelper helper; - helper.ScanDirectoryRecursive(gEnv->pCryPak, Path::GetEditingGameDataFolder().c_str(), "", mask.c_str(), files); - - for (int k = 0; k < files.size(); ++k) - { - SBatchFileItem item; - item.checkable = settings.filesAreCheckable; - item.selected = true; - item.path = { files[k].data(), files[k].size() }; - content.items.push_back(item); - } - } - else - { - string gameFolder = Path::GetEditingGameDataFolder().c_str(); - string gamePrefix = GetIEditor()->GetPrimaryCDFolder().toUtf8().data(); - if (!gamePrefix.empty() && gamePrefix[gamePrefix.size() - 1] != '\\') - { - gamePrefix += "\\"; - } - gamePrefix += gameFolder; - if (!gamePrefix.empty() && gamePrefix[gamePrefix.size() - 1] != '\\') - { - gamePrefix += "\\"; - } - gamePrefix.replace('/', '\\'); - - QString mask = "*." + QString(settings.scanExtension); - QDirIterator dirIterator(QString(gamePrefix), QStringList() << mask, QDir::Files, QDirIterator::Subdirectories); - while (dirIterator.hasNext()) - { - SBatchFileItem item; - item.selected = true; - QByteArray array = dirIterator.next().toUtf8(); - item.path = string(array); - item.path.replace('/', '\\'); - content.items.push_back(item); - } - - } - } - - content.items.reserve(content.items.size() + settings.explicitFileList.size()); - for (size_t i = 0; i < settings.explicitFileList.size(); ++i) - { - SBatchFileItem item; - item.path = settings.explicitFileList[i].c_str(); - item.selected = true; - content.items.push_back(item); - } - - - std::sort(content.items.begin(), content.items.end()); - QApplication::restoreOverrideCursor(); - - QPropertyDialog dialog(parent); - dialog.setSerializer(Serialization::SStruct(content)); - dialog.setWindowTitle(settings.title); - dialog.setWindowStateFilename(settings.stateFilename); - dialog.setSizeHint(QSize(settings.defaultWidth, settings.defaultHeight)); - dialog.setMinimumSize(QSize(540, 250)); - - CBatchFileDialog handler; - handler.m_dialog = &dialog; - handler.m_content = &content; - - QBoxLayout* topRow = new QBoxLayout(QBoxLayout::LeftToRight); - QLabel* label = new QLabel(settings.descriptionText); - QFont font; - font.setBold(true); - label->setFont(font); - topRow->addWidget(label, 1); - { - if (settings.allowListLoading && !settings.readonlyList) - { - QPushButton* loadListButton = new QPushButton("Load List..."); - QObject::connect(loadListButton, SIGNAL(pressed()), &handler, SLOT(OnLoadList())); - topRow->addWidget(loadListButton); - } - QPushButton* selectAllButton = new QPushButton("Select All"); - QObject::connect(selectAllButton, SIGNAL(pressed()), &handler, SLOT(OnSelectAll())); - topRow->addWidget(selectAllButton); - QPushButton* selectNoneButton = new QPushButton("Select None"); - QObject::connect(selectNoneButton, SIGNAL(pressed()), &handler, SLOT(OnSelectNone())); - topRow->addWidget(selectNoneButton); - } - dialog.layout()->insertLayout(0, topRow); - - if (parent) - { - QPoint center = parent->rect().center(); - dialog.window()->move(max(0, center.x() - dialog.width() / 2), - max(0, center.y() - dialog.height() / 2)); - } - - std::vector failedFiles; - if (dialog.exec() == QDialog::Accepted) - { - result->clear(); - for (size_t i = 0; i < content.items.size(); ++i) - { - if (content.items[i].selected) - { - const char* path = content.items[i].path.c_str(); - result->push_back(path); - } - } - return true; - } - return false; -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.h b/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.h deleted file mode 100644 index 3c1b071bca..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/BatchFileDialog.h +++ /dev/null @@ -1,77 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_BATCHFILEDIALOG_H -#define CRYINCLUDE_EDITORCOMMON_BATCHFILEDIALOG_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "EditorCommonAPI.h" -#include -#include -#endif - -// Private class, should not be used directly -class QWidget; -class QPropertyDialog; -class CBatchFileDialog - : public QObject -{ - Q_OBJECT - -public slots: - void OnSelectAll(); - void OnSelectNone(); - void OnLoadList(); - -public: - QPropertyDialog* m_dialog; - struct SContent; - SContent* m_content; -}; -// ^^^ - -struct SBatchFileSettings -{ - const char* scanExtension; - const char* scanFolder; - const char* title; - const char* descriptionText; - const char* listLabel; - const char* stateFilename; - bool useCryPak; - bool allowListLoading; - bool readonlyList; - bool filesAreCheckable; - Serialization::StringList explicitFileList; - int defaultWidth; - int defaultHeight; - - SBatchFileSettings() - : useCryPak(true) - , readonlyList(true) - , filesAreCheckable(false) - , allowListLoading(true) - , descriptionText("Batch Selected Files") - , listLabel("Files") - , stateFilename("batchFileDialog.state") - , title("Batch Files") - , scanFolder("") - , scanExtension("*") - { - } -}; - -bool EDITOR_COMMON_API ShowBatchFileDialog(Serialization::StringList* filenames, const SBatchFileSettings& settings, QWidget* parent); - -#endif // CRYINCLUDE_EDITORCOMMON_BATCHFILEDIALOG_H diff --git a/Code/Sandbox/Plugins/EditorCommon/CMakeLists.txt b/Code/Sandbox/Plugins/EditorCommon/CMakeLists.txt index b0450d6b3d..001f0c65d5 100644 --- a/Code/Sandbox/Plugins/EditorCommon/CMakeLists.txt +++ b/Code/Sandbox/Plugins/EditorCommon/CMakeLists.txt @@ -13,8 +13,6 @@ if(NOT PAL_TRAIT_BUILD_HOST_TOOLS) return() endif() -ly_get_list_relative_pal_filename(pal_dir ${CMAKE_CURRENT_LIST_DIR}/Platform/${PAL_PLATFORM_NAME}) - # Header only target to prevent linkage against editor libraries when it is not needed. Eventually the targets that depend # on editor headers should cleanup dependencies and interact with the editor through buses or other mechanisms ly_add_target( @@ -34,7 +32,6 @@ ly_add_target( AUTORCC FILES_CMAKE editorcommon_files.cmake - ${pal_dir}/platform_${PAL_PLATFORM_NAME_LOWERCASE}_files.cmake INCLUDE_DIRECTORIES PUBLIC . diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditor.cpp b/Code/Sandbox/Plugins/EditorCommon/CurveEditor.cpp deleted file mode 100644 index e5426b78e4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditor.cpp +++ /dev/null @@ -1,2459 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "CurveEditor.h" -#include "CurveEditorControl.h" -#include "DrawingPrimitives/TimeSlider.h" -#include "DrawingPrimitives/Ruler.h" - -AZ_PUSH_DISABLE_WARNING(4251, "-Wunknown-warning-option") // class '...' needs to have dll-interface to be used by clients of class '...' -#include -#include -#include -#include -#include -#include -#include -#include -#include -AZ_POP_DISABLE_WARNING - -// C6201: buffer overrun for , which is possibly stack allocated: index is out of valid index range to -#if defined(__clang__) -#define INDEX_NOT_OUT_OF_RANGE _Pragma("clang diagnostic ignored \"-Warray-bounds\"") -#else -#define INDEX_NOT_OUT_OF_RANGE PREFAST_SUPPRESS_WARNING(6201) -#endif - -#define NO_BUFFER_OVERRUN PREFAST_SUPPRESS_WARNING(6385 6386) -#include -#include "Cry_LegacyPhysUtils.h" - -namespace CurveEditorHelpers -{ - const uint numColors = 4; - ColorB colors[numColors] = - { - ColorB(243, 126, 121), - ColorB(121, 152, 243), - ColorB(187, 243, 121), - ColorB(243, 121, 223), - }; - - ColorB GetCurveColor(const uint n) - { - return colors[n % numColors]; - } - - QColor LerpColor(const QColor& a, const QColor& b, float k) - { - float mk = 1.0f - k; - return QColor(aznumeric_cast(a.red() * mk + b.red() * k), - aznumeric_cast(a.green() * mk + b.green() * k), - aznumeric_cast(a.blue() * mk + b.blue() * k), - aznumeric_cast(a.alpha() * mk + b.alpha() * k)); - } -} - -namespace -{ - const int kRulerHeight = 16; - const int kRulerShadowHeight = 6; - const int kRulerMarkHeight = 8; - const int kTextXOffset = -1; - const int kTextYOffset = 16; - const int kTangentLength = 24; - - const float kHitDistance = 15.0f; - const float kMinZoom = 0.001f; - const float kMaxZoom = 1000.0f; - const float kFitMargin = 16.0f; - - const QPointF kPointRectExtent = QPointF(2.5f, 2.5f); - - Vec2 TransformPointToScreen(const Vec2 zoom, const Vec2 translation, QRect curveArea, Vec2 point) - { - Vec2 transformedPoint = Vec2(point.x * zoom.x, point.y * -zoom.y) + translation; - transformedPoint.x *= curveArea.width(); - transformedPoint.y *= curveArea.height(); - return Vec2(transformedPoint.x + curveArea.left(), transformedPoint.y + curveArea.top()); - } - - Vec2 TransformPointFromScreen(const Vec2 zoom, const Vec2 translation, QRect curveArea, Vec2 point) - { - Vec2 transformedPoint = Vec2((point.x - curveArea.left()) / curveArea.width(), (point.y - curveArea.top()) / curveArea.height()) - translation; - transformedPoint.x /= zoom.x; - transformedPoint.y /= -zoom.y; - return Vec2(transformedPoint.x, transformedPoint.y); - } - - float EvaluateBezier(float t, float p0, float p1, float p2, float p3) - { - const float a = 1 - t; - const float aSq = a * a; - const float tSq = t * t; - return (aSq * a * p0) + (3.0f * aSq * t * p1) + (3.0f * a * tSq * p2) + (tSq * t * p3); - } - - void SplitBezier(SCurveEditorKey& newKey, SCurveEditorKey& leftKey, SCurveEditorKey& rightKey) - { - // use De Casteljau's algorithm to find the - float normalizedTime = (newKey.m_time - leftKey.m_time) / (rightKey.m_time - leftKey.m_time); - - Vec2 p0 = Vec2(leftKey.m_time, leftKey.m_value); - Vec2 p3 = Vec2(rightKey.m_time, rightKey.m_value); - Vec2 p1 = p0 + leftKey.m_outTangent; - Vec2 p2 = p3 + rightKey.m_inTangent; - - Vec2 q0 = p0 + (p1 - p0) * normalizedTime; - Vec2 q1 = p1 + (p2 - p1) * normalizedTime; - Vec2 q2 = p2 + (p3 - p2) * normalizedTime; - - Vec2 r0 = q0 + (q1 - q0) * normalizedTime; - Vec2 r1 = q1 + (q2 - q1) * normalizedTime; - - Vec2 s0 = r0 + (r1 - r0) * normalizedTime; - - newKey.m_inTangent = r0 - s0; - newKey.m_outTangent = r1 - s0; - - leftKey.m_outTangent = q0 - p0; - rightKey.m_inTangent = q2 - p3; - } - - QPointF Vec2ToPoint(Vec2 point) - { - return QPointF(point.x, point.y); - } - - Vec2 PointToVec2(QPointF point) - { - return Vec2(aznumeric_cast(point.x()), aznumeric_cast(point.y())); - } - - // This function returns a new key with position and weights affected by eTangentType_Smooth, eTangentType_Linear and eTangentType_Step for the outgoing tangent - SCurveEditorKey ApplyOutTangentFlags(const SCurveEditorKey& key, [[maybe_unused]] const SCurveEditorKey* pLeftKey, const SCurveEditorKey& rightKey) - { - SCurveEditorKey newKey = key; - - if (rightKey.m_inTangentType == SCurveEditorKey::eTangentType_Step - && key.m_outTangentType != SCurveEditorKey::eTangentType_Step) - { - newKey.m_outTangent.y = 0.0f; - return newKey; - } - - switch (key.m_outTangentType) - { - case SCurveEditorKey::eTangentType_Linear: - newKey.m_outTangent.y = (rightKey.m_value - key.m_value) / 3.0f; - break; - case SCurveEditorKey::eTangentType_Step: - newKey.m_outTangent.x = 0.0f; - newKey.m_outTangent.y = 0.0f; - newKey.m_value = rightKey.m_value; - break; - default: - const float oneThirdDeltaTime = (rightKey.m_time - newKey.m_time) / 3.0f; - float ratio = oneThirdDeltaTime / newKey.m_outTangent.x; - newKey.m_outTangent *= ratio; - break; - } - - return newKey; - } - - // This function returns a new key with position and weights affected by eTangentType_Smooth, eTangentType_Linear and eTangentType_Step for the incoming tangent - SCurveEditorKey ApplyInTangentFlags(const SCurveEditorKey& key, const SCurveEditorKey& leftKey, [[maybe_unused]] const SCurveEditorKey* pRightKey) - { - SCurveEditorKey newKey = key; - - if (leftKey.m_outTangentType == SCurveEditorKey::eTangentType_Step) - { - newKey.m_inTangent.y = 0.0f; - return newKey; - } - - switch (key.m_inTangentType) - { - case SCurveEditorKey::eTangentType_Linear: - newKey.m_inTangent.y = (leftKey.m_value - key.m_value) / 3.0f; - break; - case SCurveEditorKey::eTangentType_Step: - newKey.m_inTangent.x = 0.0f; - newKey.m_inTangent.y = 0.0f; - newKey.m_value = leftKey.m_value; - break; - default: - const float oneThirdDeltaTime = (newKey.m_time - leftKey.m_time) / 3.0f; - float ratio = oneThirdDeltaTime / -newKey.m_inTangent.x; - newKey.m_inTangent *= ratio; - break; - } - - return newKey; - } - - QPainterPath CreatePathFromCurve(const SCurveEditorCurve& curve, - ECurveEditorCurveType curveType, AZStd::function transformFunc) - { - QPainterPath path; - - const Vec2 startPoint(curve.m_keys[0].m_time, curve.m_keys[0].m_value); - const Vec2 startTransformed = transformFunc(startPoint); - path.moveTo(startTransformed.x, startTransformed.y); - - const auto endIter = curve.m_keys.end() - 1; - - if (curve.m_customInterpolator && curve.m_keys.size() > 1) - { - const float range_start = curve.m_customInterpolator->GetKeyTime(0); - const float range_end = curve.m_customInterpolator->GetKeyTime(curve.m_customInterpolator->GetKeyCount() - 1); - const float range_delta = range_end - range_start; - - if (range_delta > 0) - { - const int drawResolution = (int)ceil_tpl(transformFunc(Vec2(range_end, 0.0f)).x - - transformFunc(Vec2(range_start, 0.0f)).x); - - const float increment = range_delta / drawResolution; - std::vector drawList; - drawList.reserve(512); - float value; - for (float time = range_start; time < range_end; time += increment) - { - curve.m_customInterpolator->InterpolateFloat(time, value); - drawList.push_back(Vec2(time, value)); - } - - path.moveTo(Vec2ToPoint(transformFunc(drawList.front()))); - for (int i = 1; i < drawList.size(); i++) - { - path.lineTo(Vec2ToPoint(transformFunc(drawList[i]))); - } - } - } - else if (curveType == eCECT_Bezier) - { - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Vec2 p0 = Vec2(segmentStartKey.m_time, segmentStartKey.m_value); - const Vec2 p3 = Vec2(segmentEndKey.m_time, segmentEndKey.m_value); - - // Need to compute tangents for x so that the cubic 2D Bezier does a linear interpolation in - // that dimension, because we actually want to draw a cubic 1D Bezier curve - //const float outTangentX = (2.0f * p0.x + p3.x) / 3.0f; // p1 = (2 * p0 + p3) / 3 - //const float inTangentX = (p0.x + 2.0f * p3.x) / 3.0f; // p2 = (p0 + 2 * p3) / 3 - - const Vec2 p1 = p0 + segmentStartKey.m_outTangent; // Vec2(inTangentX, p0.y + segmentStartKey.m_outTangent.y); - const Vec2 p2 = p3 + segmentEndKey.m_inTangent; // Vec2(inTangentX, p3.y + segmentEndKey.m_inTangent.y); - - const QPointF p0Transformed = Vec2ToPoint(transformFunc(p0)); - const QPointF p1Transformed = Vec2ToPoint(transformFunc(p1)); - const QPointF p2Transformed = Vec2ToPoint(transformFunc(p2)); - const QPointF p3Transformed = Vec2ToPoint(transformFunc(p3)); - path.moveTo(p0Transformed); - path.cubicTo(p1Transformed, p2Transformed, p3Transformed); - } - } - else if (curveType == eCECT_2DBezier) - { - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey& segmentStartKey = *iter; - const SCurveEditorKey& segmentEndKey = *(iter + 1); - - const Vec2 p0 = Vec2(segmentStartKey.m_time, segmentStartKey.m_value); - const Vec2 p3 = Vec2(segmentEndKey.m_time, segmentEndKey.m_value); - const Vec2 p1 = p0 + segmentStartKey.m_outTangent; - const Vec2 p2 = p3 + segmentEndKey.m_inTangent; - - const QPointF p1Transformed = Vec2ToPoint(transformFunc(p1)); - const QPointF p2Transformed = Vec2ToPoint(transformFunc(p2)); - const QPointF p3Transformed = Vec2ToPoint(transformFunc(p3)); - path.cubicTo(p1Transformed, p2Transformed, p3Transformed); - } - } - - return path; - } - - // Renders path outside of the current range of the curve - QPainterPath CreateExtrapolatedPathFromCurve(const SCurveEditorCurve& curve, AZStd::function transformFunc, float windowWidth) - { - QPainterPath path; - - if (curve.m_keys.size() > 0) - { - const Vec2 startPoint = Vec2(curve.m_keys[0].m_time, curve.m_keys[0].m_value); - const Vec2 startTransformed = transformFunc(startPoint); - if (startTransformed.x > 0.0f) - { - path.moveTo(std::min(startTransformed.x, windowWidth), startTransformed.y); - path.lineTo(0.0f, startTransformed.y); - } - - const Vec2 endPoint(curve.m_keys.back().m_time, curve.m_keys.back().m_value); - const Vec2 endTransformed = transformFunc(endPoint); - if (endTransformed.x < windowWidth) - { - path.moveTo(std::max(endTransformed.x, 0.0f), endTransformed.y); - path.lineTo(windowWidth, endTransformed.y); - } - } - else - { - const Vec2 pointOnCurve = Vec2(0.0f, curve.m_defaultValue); - const Vec2 pointOnTransformed = transformFunc(pointOnCurve); - path.moveTo(0.0, pointOnTransformed.y); - path.lineTo(windowWidth, pointOnTransformed.y); - } - - QVector dashPattern; - dashPattern << 16 << 8; - - QPainterPathStroker stroker; - stroker.setCapStyle(Qt::RoundCap); - stroker.setDashPattern(dashPattern); - stroker.setWidth(0.5); - - return stroker.createStroke(path); - } - - // Renders line between discontinuous path when step mode is used for a control point - QPainterPath CreateDiscontinuinityPathFromCurve(const SCurveEditorCurve& curve, ECurveEditorCurveType curveType, AZStd::function transformFunc) - { - QPainterPath path; - - if (curve.m_keys.size() > 0) - { - const auto endIter = curve.m_keys.end() - 1; - - if (curveType == eCECT_Bezier && !curve.m_customInterpolator) - { - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - if (segmentStartKey.m_value != iter->m_value) - { - const Vec2 start = Vec2(segmentStartKey.m_time, segmentStartKey.m_value); - const Vec2 end = Vec2(iter->m_time, iter->m_value); - - const QPointF startTransformed = Vec2ToPoint(transformFunc(start)); - const QPointF endTransformed = Vec2ToPoint(transformFunc(end)); - - path.moveTo(startTransformed); - path.lineTo(endTransformed); - } - - if (segmentEndKey.m_value != (iter + 1)->m_value) - { - const Vec2 start = Vec2(segmentEndKey.m_time, segmentEndKey.m_value); - const Vec2 end = Vec2((iter + 1)->m_time, (iter + 1)->m_value); - - const QPointF startTransformed = Vec2ToPoint(transformFunc(start)); - const QPointF endTransformed = Vec2ToPoint(transformFunc(end)); - - path.moveTo(startTransformed); - path.lineTo(endTransformed); - } - } - } - } - - QVector dashPattern; - dashPattern << 2 << 10; - - QPainterPathStroker stroker; - stroker.setCapStyle(Qt::RoundCap); - stroker.setDashPattern(dashPattern); - stroker.setWidth(0.5); - - return stroker.createStroke(path); - } - - void DrawPointRect(QPainter& painter, QPointF point, const QColor& color) - { - painter.setBrush(QBrush(color)); - painter.setPen(QColor(0, 0, 0)); - painter.drawRect(QRectF(point - kPointRectExtent, point + kPointRectExtent)); - } - - void ForEachKey(SCurveEditorContent& content, AZStd::function fun) - { - for (auto iter = content.m_curves.begin(); iter != content.m_curves.end(); ++iter) - { - SCurveEditorCurve& curve = *iter; - for (size_t i = 0; i < curve.m_keys.size(); ++i) - { - fun(curve, curve.m_keys[i]); - } - } - } - - Vec2 ClosestPointOnBezierSegment(const Vec2 point, const float t0, const float t1, const float p0, const float p1, const float p2, const float p3) - { - using namespace LegacyCryPhysicsUtils; - - // If values are too close the distance function is too flat to be useful. We just assume the curve is flat then - if ((p0 * p0 + p1 * p1 + p2 * p2 + p3 * p3) < 1e-10f) - { - return Vec2(point.x, p0); - } - - const float deltaTime = (t1 - t0); - const float deltaTimeSq = deltaTime * deltaTime; - - // Those are just the normal cubic Bezier formulas B(t) and B'(t) in collected polynomial form - const P3f cubicBezierPoly = P3f(-p0 + 3.0f * p1 - 3.0f * p2 + p3) + P2f(3.0f * p0 - 6.0f * p1 + 3.0f * p2) + P1f(3.0f * p1 - 3.0f * p0) + p0; - const P2f cubicBezierDerivativePoly = P2f(-3.0f * p0 + 9.0f * p1 - 6.0f * p2 + 3.0f * (p3 - p2)) + P1f(6.0f * p0 - 12.0f * p1 + 6.0f * p2) - 3.0f * p0 + 3.0f * p1; - - // lerp(t, t0, t1) in polynomial form - const P1f timePoly = P1f(deltaTime) + t0; - - // Derivative of the distance function (cubicBezierPoly - point.y) ^ 2 + (timePoly - point.x) ^ 2 - const auto distanceDerivativePoly = (cubicBezierDerivativePoly * (cubicBezierPoly - point.y) + (timePoly - point.x) * deltaTime) * 2.0f; - - // The point of minimum distance must be at one of the roots of the distance derivative or at the start/end of the segment - float checkPoints[7]; - const uint numRoots = distanceDerivativePoly.findroots(0.0f, 1.0f, checkPoints + 2); - // Start and end of segment - checkPoints[0] = 0.0f; - checkPoints[1] = 1.0f; - - // Find the closest point under all the candidates - Vec2 closestPoint; - float minDistanceSq = std::numeric_limits::max(); - for (uint i = 0; i < numRoots + 2; ++i) - { - const Vec2 rootPoint(Lerp(t0, t1, checkPoints[i]), EvaluateBezier(checkPoints[i], p0, p1, p2, p3)); - const float deltaX = rootPoint.x - point.x; - const float deltaY = rootPoint.y - point.y; - const float distSq = deltaX * deltaX + deltaY * deltaY; - if (distSq < minDistanceSq) - { - closestPoint = rootPoint; - minDistanceSq = distSq; - } - } - - return closestPoint; - } - - Range GetBezierSegmentValueRange(const SCurveEditorKey& startKey, const SCurveEditorKey& endKey) - { - using namespace LegacyCryPhysicsUtils; - - const float p0 = startKey.m_value; - const float p1 = p0 + startKey.m_outTangent.y; - const float p3 = endKey.m_value; - const float p2 = p3 + endKey.m_inTangent.y; - - Range valueRange(std::min(p0, p3), std::max(p0, p3)); - const P2f cubicBezierDerivativePoly = P2f(-3.0f * p0 + 9.0f * p1 - 6.0f * p2 + 3.0f * (p3 - p2)) + P1f(6.0f * p0 - 12.0f * p1 + 6.0f * p2) - 3.0f * p0 + 3.0f * p1; - - float roots[2]; - const uint numRoots = cubicBezierDerivativePoly.findroots(0.0f, 1.0f, roots); - for (uint i = 0; i < numRoots; ++i) - { - const float rootValue = EvaluateBezier(roots[i], p0, p1, p2, p3); - valueRange.start = std::min(valueRange.start, rootValue); - valueRange.end = std::max(valueRange.end, rootValue); - } - return valueRange; - } - - float DistanceTo2DBezierSegment([[maybe_unused]] const Vec2 point, [[maybe_unused]] const SCurveEditorKey& startKey, [[maybe_unused]] const SCurveEditorKey& endKey) - { - return std::numeric_limits::max(); - } - - - void SmoothTangents(const SCurveEditorKey& key, Vec2& inTangent, Vec2& outTangent, SCurveEditorKey* pLeftKey, SCurveEditorKey* pRightKey, bool applyInverseSegmentLengthFactor) - { - inTangent.Normalize(); - outTangent.Normalize(); - - if (!pLeftKey && !pRightKey) - { - return; - } - else if (!pLeftKey) - { - inTangent = -outTangent; - } - else if (!pRightKey) - { - outTangent = -inTangent; - } - else - { - const float deltaTime = pRightKey->m_time - pLeftKey->m_time; - const float ratio = (key.m_time - pLeftKey->m_time) / deltaTime; - - Vec2 smoothedTangent = Vec2::CreateLerp(-inTangent, outTangent, applyInverseSegmentLengthFactor ? ratio : 0.5f); - inTangent = -smoothedTangent; - outTangent = smoothedTangent; - } - - if (pLeftKey) - { - float leftSegmentTime = key.m_time - pLeftKey->m_time; - float inFactor = (leftSegmentTime / -inTangent.x) / 3.0f; - inTangent *= inFactor; - } - if (pRightKey) - { - float rightSegmentTime = pRightKey->m_time - key.m_time; - float outFactor = (rightSegmentTime / outTangent.x) / 3.0f; - outTangent *= outFactor; - } - } - - Vec2 GetSmoothInTangent(SCurveEditorKey& key, Vec2 inTangent, Vec2 outTangent, SCurveEditorKey* pLeftKey, SCurveEditorKey* pRightKey, bool applyInverseSegmentLengthFactor) - { - SmoothTangents(key, inTangent, outTangent, pLeftKey, pRightKey, applyInverseSegmentLengthFactor); - return inTangent; - } - - Vec2 GetSmoothOutTangent(SCurveEditorKey& key, Vec2 inTangent, Vec2 outTangent, SCurveEditorKey* pLeftKey, SCurveEditorKey* pRightKey, bool applyInverseSegmentLengthFactor) - { - SmoothTangents(key, inTangent, outTangent, pLeftKey, pRightKey, applyInverseSegmentLengthFactor); - return outTangent; - } -} - -void showTooltip(const SCurveEditorKey& key, const QPoint& pos, QWidget* parent, QString tipOverride = QString()) -{ - if (!tipOverride.isEmpty()) - { - return QToolTip::showText(pos, tipOverride, parent); - } - - QString tip = QString().asprintf("%s <- [%5.2f, %5.2f] -> %s", - CCurveEditor::TangentTypeToString(key.m_inTangentType).toUtf8().data(), - key.m_time, key.m_time, - CCurveEditor::TangentTypeToString(key.m_outTangentType).toUtf8().data()); - - QToolTip::showText(pos, tip, parent); -} - -struct CCurveEditor::SSelectionHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - QPoint m_startPoint; - QRect m_rect; - bool m_bAdd; - - SSelectionHandler(CCurveEditor* pCurveEditor, bool bAdd) - : m_pCurveEditor(pCurveEditor) - , m_bAdd(bAdd) {} - - void mousePressEvent(QMouseEvent* pEvent) override - { - m_startPoint = pEvent->pos(); - m_rect = QRect(m_startPoint, m_startPoint + QPoint(1, 1)); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - m_rect = QRect(m_startPoint, pEvent->pos() + QPoint(1, 1)); - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* pEvent) override - { - m_pCurveEditor->SelectInRect(m_rect); - } - - void paintOver(QPainter& painter) override - { - painter.save(); - QColor highlightColor = m_pCurveEditor->palette().color(QPalette::Highlight); - QColor highlightColorA = QColor(highlightColor.red(), highlightColor.green(), highlightColor.blue(), 128); - painter.setPen(QPen(highlightColor)); - painter.setBrush(QBrush(highlightColorA)); - painter.drawRect(QRectF(m_rect)); - painter.restore(); - } -}; - -struct CCurveEditor::SPanHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - QPoint m_startPoint; - Vec2 m_startTranslation; - - SPanHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* pEvent) override - { - if (m_pCurveEditor->m_optOutFlags & EOptOutZoomingAndPanning) - { - return; - } - m_startPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - m_startTranslation = m_pCurveEditor->m_translation; - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - if (m_pCurveEditor->m_optOutFlags & EOptOutZoomingAndPanning) - { - return; - } - const Vec2 windowSize((float)m_pCurveEditor->size().width(), (float)m_pCurveEditor->size().height()); - - const int pixelDeltaX = pEvent->x() - m_startPoint.x(); - const int pixelDeltaY = pEvent->y() - m_startPoint.y(); - - float deltaX = float(pixelDeltaX) / (windowSize.x); - float deltaY = float(pixelDeltaY) / (windowSize.y); - - if (m_pCurveEditor->IsTimeRangeEnforced()) - { - deltaX = 0; - } - - const Vec2 delta(deltaX, deltaY); - m_pCurveEditor->m_translation = m_startTranslation + delta; - m_pCurveEditor->update(); - } -}; - -struct CCurveEditor::SZoomHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - QPoint m_lastPoint; - - SZoomHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* pEvent) override - { - if (m_pCurveEditor->m_optOutFlags & EOptOutZoomingAndPanning) - { - return; - } - m_lastPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - if (m_pCurveEditor->m_optOutFlags & EOptOutZoomingAndPanning) - { - return; - } - const Vec2 windowSize((float)m_pCurveEditor->size().width(), (float)m_pCurveEditor->size().height()); - - const int pixelDeltaX = pEvent->x() - m_lastPoint.x(); - const int pixelDeltaY = pEvent->y() - m_lastPoint.y(); - - m_lastPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - - m_pCurveEditor->m_zoom.x *= pow(1.2f, (float)pixelDeltaX * 0.03f); - m_pCurveEditor->m_zoom.y *= pow(1.2f, (float)pixelDeltaY * 0.03f); - - m_pCurveEditor->m_zoom.x = clamp_tpl(m_pCurveEditor->m_zoom.x, kMinZoom, kMaxZoom); - m_pCurveEditor->m_zoom.y = clamp_tpl(m_pCurveEditor->m_zoom.y, kMinZoom, kMaxZoom); - - m_pCurveEditor->update(); - } -}; - -struct CCurveEditor::SScrubHandler - : SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - float m_startThumbPosition; - QPoint m_startPoint; - - SScrubHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* ev) override - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - const Vec2 pointInCurveSpace = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(point)); - - m_pCurveEditor->m_time = pointInCurveSpace.x; - m_startThumbPosition = m_pCurveEditor->m_time; - m_startPoint = point; - - m_pCurveEditor->SignalScrub(); - } - - void Apply(QMouseEvent* ev, [[maybe_unused]] bool continuous) - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - bool shift = ev->modifiers().testFlag(Qt::ShiftModifier); - bool control = ev->modifiers().testFlag(Qt::ControlModifier); - - const float deltaX = (float)(point.x() - m_startPoint.x()); - const float width = (float)m_pCurveEditor->size().width(); - float delta = float(deltaX) / (width * m_pCurveEditor->m_zoom.x); - - if (shift) - { - delta *= 0.01f; - } - - if (control) - { - delta *= 0.1f; - } - - m_pCurveEditor->m_time = m_startThumbPosition + delta; - m_pCurveEditor->SignalScrub(); - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - Apply(ev, true); - } - - void mouseReleaseEvent(QMouseEvent* ev) override - { - Apply(ev, false); - } -}; - -struct CCurveEditor::SMoveKeyHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - bool m_bCycleSelection; - Vec2 m_startPoint; - std::vector m_keyPositions; - bool m_clamp; - QRectF m_range; - - SMoveKeyHandler(CCurveEditor* pCurveEditor, bool bCycleSelection, QRectF* clampRange = nullptr) - : m_pCurveEditor(pCurveEditor) - , m_bCycleSelection(bCycleSelection) - , m_startPoint(0.0f, 0.0f) - , m_clamp(clampRange ? true : false) - , m_range(clampRange ? *clampRange : QRectF()) - {} - - void mousePressEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - m_startPoint = TransformPointFromScreen(m_pCurveEditor->m_zoom, - m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - StoreKeyPositions(); - m_pCurveEditor->SignalKeyMoveStarted(); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - RestoreKeyPositions(); - const QPoint currentPos = pEvent->pos(); - Vec2 transformedPos = TransformPointFromScreen(m_pCurveEditor->m_zoom, - m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - - const Vec2 offset = transformedPos - m_startPoint; - - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - iter->m_time += offset.x; - iter->m_value += offset.y; - if (m_clamp) - { - iter->m_time = clamp_tpl(iter->m_time, (float)m_range.left(), (float)m_range.right()); - iter->m_value = clamp_tpl(iter->m_value, (float)m_range.bottom(), (float)m_range.top()); - } - iter->m_bModified = true; - } - } - - m_pCurveEditor->SortKeys(curve); - } - - m_pCurveEditor->SignalKeyMoved(); - } - - void focusOutEvent([[maybe_unused]] QFocusEvent* pEvent) override - { - RestoreKeyPositions(); - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* pEvent) override - { - m_pCurveEditor->ContentChanged(); - } - - void StoreKeyPositions() - { - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - m_keyPositions.push_back(Vec2(iter->m_time, iter->m_value)); - } - } - } - } - - void RestoreKeyPositions() - { - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - auto posIter = m_keyPositions.begin(); - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - iter->m_time = posIter->x; - iter->m_value = (posIter++)->y; - } - } - } - } -}; - -struct CCurveEditor::SRotateTangentHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - CCurveEditorTangentControl* m_pSelectedTangent; - Vec2 m_StartPoint; - Vec2 m_InitialInTangent; - SCurveEditorKey::ETangentType m_InitialInTangentType; - Vec2 m_InitialOutTangent; - SCurveEditorKey::ETangentType m_InitialOutTangentType; - - SRotateTangentHandler(CCurveEditor* pCurveEditor, CCurveEditorTangentControl* pTangentControl) - : m_pCurveEditor(pCurveEditor) - , m_pSelectedTangent(pTangentControl) - , m_StartPoint(0.0f, 0.0f) - {} - - void mousePressEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - m_StartPoint = m_pCurveEditor->TransformFromScreenCoordinates(PointToVec2(currentPos)); - - StoreTangents(); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - const Vec2 transformedPos = m_pCurveEditor->TransformFromScreenCoordinates(PointToVec2(currentPos)); - const Vec2 offset = transformedPos - m_StartPoint; - - SCurveEditorKey& key = m_pSelectedTangent->GetControl().GetKey(); - Vec2 keyPos(key.m_time, key.m_value); - - bool isInTangent = m_pSelectedTangent->GetTangentDirection() == ETangent_In; - bool shouldTangentsBePaired = key.m_inTangentType == key.m_outTangentType - && (key.m_inTangentType == SCurveEditorKey::eTangentType_Standard - || key.m_inTangentType == SCurveEditorKey::eTangentType_Smooth - || key.m_inTangentType == SCurveEditorKey::eTangentType_Flat); - - float tangentEpsilon = 1e-6f; - - // strictly left or right of key - have a fairly large epsilon to avoid weird floating point innaccuracies in editor - bool leftOfKey = (transformedPos.x - keyPos.x) < -tangentEpsilon; - bool rightOfKey = (transformedPos.x - keyPos.x) > tangentEpsilon; - bool tangentVertical = !(leftOfKey || rightOfKey); - - if ((isInTangent && leftOfKey) || (shouldTangentsBePaired && !tangentVertical)) - { - Vec2 newInTangent = transformedPos - keyPos; - if (rightOfKey) - { - // mirror tangent - newInTangent *= -1; - } - float scale = key.m_inTangent.x / newInTangent.x; - newInTangent *= scale; - key.m_inTangent = newInTangent; - - key.m_inTangentType = shouldTangentsBePaired ? SCurveEditorKey::eTangentType_Standard : key.m_inTangentType; - } - - if ((!isInTangent && rightOfKey) || (shouldTangentsBePaired && !tangentVertical)) - { - Vec2 newOutTangent = transformedPos - keyPos; - if (leftOfKey) - { - // mirror tangent - newOutTangent *= -1; - } - float scale = key.m_outTangent.x / newOutTangent.x; - newOutTangent *= scale; - key.m_outTangent = newOutTangent; - - key.m_outTangentType = shouldTangentsBePaired ? SCurveEditorKey::eTangentType_Standard : key.m_outTangentType; - } - } - - void focusOutEvent([[maybe_unused]] QFocusEvent* pEvent) override - { - RestoreTangents(); - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* pEvent) override - { - m_pCurveEditor->ContentChanged(); - } - - void StoreTangents() - { - SCurveEditorKey& key = m_pSelectedTangent->GetControl().GetKey(); - - m_InitialInTangent = key.m_inTangent; - m_InitialInTangentType = key.m_inTangentType; - - m_InitialOutTangent = key.m_outTangent; - m_InitialOutTangentType = key.m_outTangentType; - } - - void RestoreTangents() - { - SCurveEditorKey& key = m_pSelectedTangent->GetControl().GetKey(); - - key.m_inTangent = m_InitialInTangent; - key.m_inTangentType = m_InitialInTangentType; - - key.m_outTangent = m_InitialOutTangent; - key.m_outTangentType = m_InitialOutTangentType; - } -}; - -CCurveEditor::CCurveEditor(QWidget* parent) - : QWidget(parent) - , m_pContent(nullptr) - , m_pMouseHandler(nullptr) - , m_curveType(eCECT_Bezier) - , m_bWeighted(false) - , m_bHandlesVisible(true) - , m_bRulerVisible(true) - , m_bTimeSliderVisible(true) - , m_time(0.0f) - , m_zoom(0.5f, 0.5f) - , m_translation(0.5f, 0.5f) - , m_timeRange(0, 1) - , m_timeRangeEnforced(false) - , m_valueRange(0, 1) - , m_optOutFlags(0) -{ - setMouseTracking(true); - //EnforceTimeRange(0.0f, 1.0f); - SetTimeRange(0, 1); - SetValueRange(0, 1); - ZoomToTimeRange(-0.1f, 1.1f); - ZoomToValueRange(-0.1f, 1.1f); - SetRulerVisible(true); - QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - setSizePolicy(sizePolicy); -} - -CCurveEditor::~CCurveEditor() -{ -} - -void CCurveEditor::SetContent(SCurveEditorContent* pContent) -{ - m_pContent = pContent; - - ContentChanged(); - - update(); -} - -void CCurveEditor::SetTime(const float time) -{ - m_time = time; - update(); -} - -void CCurveEditor::SetTimeRange(const float start, const float end) -{ - SetTimeRange(start, end, false); -} - -void CCurveEditor::EnforceTimeRange(const float start, const float end) -{ - SetTimeRange(start, end, true); - ZoomToTimeRange(start, end); -} - -bool CCurveEditor::IsTimeRangeEnforced() const -{ - return m_timeRangeEnforced; -} - -void CCurveEditor::SetTimeRange(const float start, const float end, bool enforce) -{ - if (start <= end) - { - m_timeRangeEnforced = enforce; - m_timeRange = Range(start, end); - update(); - } -} - -void CCurveEditor::SetValueRange(const float min, const float max) -{ - if (min <= max) - { - m_valueRange = Range(min, max); - update(); - } -} - -void CCurveEditor::ZoomToTimeRange(const float start, const float end) -{ - if (start < end) - { - m_zoom.x = 1.0f / (end - start); - m_translation.x = start / (start - end); - } -} - -void CCurveEditor::ZoomToValueRange(const float min, const float max) -{ - if (min < max) - { - m_zoom.y = 1.0f / (max - min); - m_translation.y = max / (max - min); - } -} - -void CCurveEditor::paintEvent([[maybe_unused]] QPaintEvent* pEvent) -{ - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - painter.translate(0.5f, 0.5f); - - const QPalette& palette = this->palette(); - - auto transformFunc = [&](Vec2 point) - { - return TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), point); - }; - - auto invTransformFunc = [&](Vec2 screenPoint) - { - return TransformPointFromScreen(m_zoom, m_translation, GetCurveArea(), screenPoint); - }; - - const QColor rangeHighlightColor = CurveEditorHelpers::LerpColor(palette.color(QPalette::WindowText), palette.color(QPalette::Window), 0.95f); - const QRectF rangesRect(Vec2ToPoint(transformFunc(Vec2(m_timeRange.start, m_valueRange.start))), Vec2ToPoint(transformFunc(Vec2(m_timeRange.end, m_valueRange.end)))); - painter.setPen(QPen(Qt::NoPen)); - if ((m_optOutFlags & EOptOutBackground)) - { - painter.setBrush(Qt::transparent); - } - else - { - painter.setBrush(rangeHighlightColor); - } - - if ((m_optOutFlags & EOptOutRuler)) - { - painter.drawRect(rangesRect); - } - else - { - painter.drawRect(rect()); - } - - if (m_pContent) - { - const QPen extrapolatedCurvePen = QPen(palette.color(QPalette::Highlight)); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - QColor penColor = QColor(curve.m_color.r, curve.m_color.g, curve.m_color.b, curve.m_color.a); - - if (!(m_optOutFlags & EOptOutCustomPenColor) && m_penColor.isValid()) - { - penColor = m_penColor; - } - - painter.setBrush(QBrush(Qt::NoBrush)); - const QPen curvePen = QPen(penColor, 2); - const QPen narrowCurvePen = QPen(penColor); - if (!(m_optOutFlags & eOptOutDashedPath)) - { - const QPainterPath extrapolatedPath = CreateExtrapolatedPathFromCurve(curve, transformFunc, aznumeric_cast(width())); - painter.setPen(narrowCurvePen); - painter.drawPath(extrapolatedPath); - } - - const QPainterPath discontinuinityPath = CreateDiscontinuinityPathFromCurve(curve, m_curveType, transformFunc); - painter.setPen(narrowCurvePen); - painter.drawPath(discontinuinityPath); - - if (curve.m_keys.size() > 0) - { - UpdateTangents(); - const QPainterPath path = CreatePathFromCurve(curve, m_curveType, transformFunc); - painter.setPen(curvePen); - painter.drawPath(path); - } - } - } - - if (!(m_optOutFlags & EOptOutSelectionKey)) - { - if ((m_optOutFlags & EOptOutKeyIcon)) - { - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - pControlKey->Paint(painter, palette, !(m_optOutFlags & EOptOutSelectionInOutTangent)); - } - } - else - { - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - pControlKey->PaintIcon(painter, palette, !(m_optOutFlags & EOptOutSelectionInOutTangent)); - } - } - } - - if (m_pMouseHandler) - { - m_pMouseHandler->paintOver(painter); - } - if (!(m_optOutFlags & EOptOutRuler)) - { - DrawingPrimitives::SRulerOptions rulerOptions; - rulerOptions.m_rect = QRect(0, -1, size().width(), kRulerHeight + 2); - rulerOptions.m_visibleRange = Range(-m_translation.x / m_zoom.x, (1.0f - m_translation.x) / m_zoom.x); - rulerOptions.m_rulerRange = rulerOptions.m_visibleRange; - rulerOptions.m_markHeight = kRulerMarkHeight; - rulerOptions.m_shadowSize = kRulerShadowHeight; - rulerOptions.m_textXOffset = kTextXOffset; - rulerOptions.m_textYOffset = kTextYOffset; - - int rulerPrecision; - DrawingPrimitives::DrawRuler(painter, palette, rulerOptions, &rulerPrecision); - - if (m_pContent && isEnabled() && !(m_optOutFlags & EOptOutTimeSlider)) - { - DrawingPrimitives::STimeSliderOptions timeSliderOptions; - timeSliderOptions.m_rect = rect(); - timeSliderOptions.m_precision = rulerPrecision; - timeSliderOptions.m_position = aznumeric_cast(transformFunc(Vec2(m_time, 0.0f)).x); - timeSliderOptions.m_time = m_time; - timeSliderOptions.m_bHasFocus = hasFocus(); - DrawingPrimitives::DrawTimeSlider(painter, palette, timeSliderOptions); - } - } -} - -void CCurveEditor::mousePressEvent(QMouseEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return QWidget::mousePressEvent(pEvent); - } - setFocus(); - - if (pEvent->button() == Qt::LeftButton) - { - LeftButtonMousePressEvent(pEvent); - } - else if (pEvent->button() == Qt::MiddleButton) - { - MiddleButtonMousePressEvent(pEvent); - } - else if (pEvent->button() == Qt::RightButton) - { - RightButtonMousePressEvent(pEvent); - } -} - -void CCurveEditor::mouseDoubleClickEvent(QMouseEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return QWidget::mouseDoubleClickEvent(pEvent); - } - if (pEvent->button() == Qt::LeftButton) - { - auto curveHitPair = HitDetectCurve(pEvent->pos()); - if (curveHitPair.first) - { - if (AddPointToCurve(curveHitPair.second, curveHitPair.first)) - { - setCursor(QCursor(Qt::SizeAllCursor)); - } - } - } -} - -void CCurveEditor::LeftButtonMousePressEvent(QMouseEvent* pEvent) -{ - const bool bCtrlPressed = (pEvent->modifiers() & Qt::CTRL) != 0; - const bool bAltPressed = (pEvent->modifiers() & Qt::ALT) != 0; - - if (pEvent->y() < kRulerHeight && !(m_optOutFlags & EOptOutRuler)) - { - m_pMouseHandler.reset(new SScrubHandler(this)); - m_pMouseHandler->mousePressEvent(pEvent); - } - else - { - if (bCtrlPressed) - { - auto curveHitPair = HitDetectCurve(pEvent->pos()); - if (curveHitPair.first) - { - if (AddPointToCurve(curveHitPair.second, curveHitPair.first)) - { - setCursor(QCursor(Qt::SizeAllCursor)); - } - } - } - else if (bAltPressed) - { - auto pCurveKey = HitDetectKey(pEvent->pos()); - if (pCurveKey) - { - pCurveKey->MarkKeyForRemoval(); - ContentChanged(); - } - } - else - { - auto pTangentKey = HitDetectTangent(pEvent->pos()); - if (pTangentKey) - { - SelectTangent(pTangentKey); - - m_pMouseHandler.reset(new SRotateTangentHandler(this, pTangentKey)); - } - else - { - auto pCurveKey = HitDetectKey(pEvent->pos()); - if (pCurveKey) - { - SelectKey(pCurveKey, false); - - QRectF range; - range.setLeft(m_timeRange.start); - range.setRight(m_timeRange.end); - range.setBottom(m_valueRange.start); - range.setTop(m_valueRange.end); - - m_pMouseHandler.reset(new SMoveKeyHandler(this, false, - m_timeRangeEnforced ? &range : nullptr)); - } - else - { - m_pMouseHandler.reset(new SSelectionHandler(this, false)); - } - } - - m_pMouseHandler->mousePressEvent(pEvent); - } - } - - update(); -} - -void CCurveEditor::MiddleButtonMousePressEvent(QMouseEvent* pEvent) -{ - const bool bShiftPressed = (pEvent->modifiers() & Qt::SHIFT) != 0; - - if (!bShiftPressed) - { - m_pMouseHandler.reset(new SPanHandler(this)); - } - else - { - m_pMouseHandler.reset(new SZoomHandler(this)); - } - - m_pMouseHandler->mousePressEvent(pEvent); - update(); -} - -void CCurveEditor::RightButtonMousePressEvent(QMouseEvent* pEvent) -{ - CCurveEditorControl* pCurveKey = HitDetectKey(pEvent->pos()); - if (pCurveKey) - { - SelectKey(pCurveKey, false); - update(); //Repaint so that we see that the key is selected - - QMenu* pMenu = new QMenu(this); - PopulateControlContextMenu(pMenu); - pMenu->popup(pEvent->globalPos()); - } - else - { - return QWidget::mousePressEvent(pEvent); - } -} - -void CCurveEditor::mouseMoveEvent(QMouseEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return QWidget::mouseMoveEvent(pEvent); - } - const CCurveEditorControl* control = HitDetectKey(pEvent->pos()); - if (control) - { - if (!(m_optOutFlags & EOptOutDefaultTooltip)) - { - showTooltip(control->GetKey(), pEvent->globalPos(), this, control->GetToolTip()); - } - setCursor(QCursor(Qt::SizeAllCursor)); - } - else - { - if (!(m_optOutFlags & EOptOutDefaultTooltip)) - { - QToolTip::hideText(); - } - setCursor(QCursor()); - } - - if (m_pMouseHandler) - { - m_pMouseHandler->mouseMoveEvent(pEvent); - } - - update(); -} - -void CCurveEditor::mouseReleaseEvent(QMouseEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return QWidget::mouseReleaseEvent(pEvent); - } - if (m_pMouseHandler) - { - m_pMouseHandler->mouseReleaseEvent(pEvent); - m_pMouseHandler.reset(); - update(); - } -} - -void CCurveEditor::focusOutEvent(QFocusEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return focusOutEvent(pEvent); - } - if (m_pMouseHandler) - { - m_pMouseHandler->focusOutEvent(pEvent); - m_pMouseHandler.reset(); - update(); - } -} - -void CCurveEditor::wheelEvent(QWheelEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls || m_optOutFlags & EOptOutZoomingAndPanning) - { - return QWidget::wheelEvent(pEvent); - } - Vec2 windowSize((float)size().width(), (float)size().height()); - windowSize.y = (windowSize.y > 0.0f) ? windowSize.y : 1.0f; - - const QRect curveArea = GetCurveArea(); - const float mouseXNormalized = (float)(pEvent->position().x() - curveArea.left()) / (float)curveArea.width(); - const float mouseYNormalized = (float)(pEvent->position().y() - curveArea.top()) / (float)curveArea.height(); - - const float pivotX = (mouseXNormalized - m_translation.x) / m_zoom.x; - const float pivotY = (mouseYNormalized - m_translation.y) / m_zoom.y; - - float zoomFactor = pow(1.2f, (float)pEvent->angleDelta().y() * 0.01f); - - if (!m_timeRangeEnforced) - { - m_zoom.x *= zoomFactor; - } - m_zoom.y *= zoomFactor; - - m_zoom.x = clamp_tpl(m_zoom.x, kMinZoom, kMaxZoom); - m_zoom.y = clamp_tpl(m_zoom.y, kMinZoom, kMaxZoom); - - // Adjust translation so pivot point stays at same x and y position on screen - m_translation.x += ((mouseXNormalized - m_translation.x) / m_zoom.x - pivotX) * m_zoom.x; - m_translation.y += ((mouseYNormalized - m_translation.y) / m_zoom.y - pivotY) * m_zoom.y; - - update(); -} - -void CCurveEditor::keyPressEvent(QKeyEvent* pEvent) -{ - if (m_optOutFlags & EOptOutControls) - { - return QWidget::keyPressEvent(pEvent); - } - if (!m_pContent) - { - return; - } - - QKeySequence key(pEvent->key()); - - if (key == QKeySequence(Qt::Key_Delete)) - { - OnDeleteSelectedKeys(); - } - - update(); -} - -void CCurveEditor::SetCurveType(ECurveEditorCurveType curveType) -{ - m_curveType = curveType; -} - -void CCurveEditor::SetHandlesVisible(bool bVisible) -{ - m_bHandlesVisible = bVisible; - update(); -} - -void CCurveEditor::SetRulerVisible(bool bVisible) -{ - m_bRulerVisible = bVisible; - update(); -} - -void CCurveEditor::SetTimeSliderVisible(bool bVisible) -{ - m_bTimeSliderVisible = bVisible; - update(); -} - -std::pair CCurveEditor::HitDetectCurve(const QPoint point) -{ - if (!m_pContent) - { - return std::make_pair(nullptr, Vec2(ZERO)); - } - - SCurveEditorCurve* pNearestCurve = nullptr; - Vec2 closestPoint = Vec2(ZERO); - - float nearestDistance = std::numeric_limits::max(); - for (auto iter = m_pContent->m_curves.rbegin(); iter != m_pContent->m_curves.rend(); ++iter) - { - SCurveEditorCurve& curve = *iter; - const Vec2 closestPointOnCurve = ClosestPointOnCurve(PointToVec2(point), curve, m_curveType); - - const float distance = (PointToVec2(point) - closestPointOnCurve).GetLength(); - if (distance < nearestDistance) - { - nearestDistance = distance; - pNearestCurve = &curve; - closestPoint = closestPointOnCurve; - } - } - - if (nearestDistance <= kHitDistance) - { - return std::make_pair(pNearestCurve, TransformPointFromScreen(m_zoom, m_translation, GetCurveArea(), closestPoint)); - } - - return std::make_pair(nullptr, Vec2(ZERO)); -} - -CCurveEditorControl* CCurveEditor::GetSelectedCurveKey() -{ - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - if (pControlKey->IsSelected()) - { - return pControlKey; - } - } - return nullptr; -} - - -CCurveEditorControl* CCurveEditor::HitDetectKey(const QPoint point) -{ - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - if (pControlKey->IsMouseWithinControl(point)) - { - return pControlKey; - } - } - - return NULL; -} - -CCurveEditorTangentControl* CCurveEditor::HitDetectTangent(const QPoint point) -{ - if (m_optOutFlags & EOptOutSelectionInOutTangent) - { - return NULL; - } - - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - if (pControlKey->GetInTangent().IsMouseWithinControl(point)) - { - return &pControlKey->GetInTangent(); - } - else if (pControlKey->GetOutTangent().IsMouseWithinControl(point)) - { - return &pControlKey->GetOutTangent(); - } - } - - return NULL; -} - -void CCurveEditor::SelectKey(CCurveEditorControl* pControlToSelect, bool addToExistingSelection) -{ - bool wasSelected = pControlToSelect->IsSelected(); - - if (!wasSelected) - { - if (!addToExistingSelection) - { - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - pControlKey->SetSelected(false); - } - } - pControlToSelect->SetSelected(true); - //update key selection style - updateCurveKeyShapeColor(); - emit SignalKeySelected(pControlToSelect); - } -} - -void CCurveEditor::SelectTangent(CCurveEditorTangentControl* pTangentToSelect) -{ - bool wasSelected = pTangentToSelect->IsSelected(); - if (!wasSelected) - { - for (CCurveEditorControl* pControlKey : m_pControlKeys) - { - pControlKey->SetSelected(false); - pControlKey->GetInTangent().SetSelected(false); - pControlKey->GetOutTangent().SetSelected(false); - } - pTangentToSelect->GetControl().SetSelected(true); - pTangentToSelect->SetSelected(true); - } -} - -void CCurveEditor::SelectInRect(const QRect& rect) -{ - if (!m_pContent || (m_optOutFlags & EOptOutSelectionKey)) - { - return; - } - - ForEachKey(*m_pContent, [&]([[maybe_unused]] SCurveEditorCurve& curve, SCurveEditorKey& key) - { - const Vec2 screenPoint = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), Vec2(key.m_time, key.m_value)); - key.m_bSelected = rect.contains((int)screenPoint.x, (int)screenPoint.y); - }); - - update(); -} - -// Input and output are in screen space -Vec2 CCurveEditor::ClosestPointOnCurve(const Vec2 point, const SCurveEditorCurve& curve, const ECurveEditorCurveType curveType) -{ - auto transformFunc = [&](Vec2 point) - { - return TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), point); - }; - - if (curve.m_keys.size() == 0) - { - const Vec2 pointOnCurve = transformFunc(Vec2(0.0f, curve.m_defaultValue)); - return Vec2(point.x, pointOnCurve.y); - } - - Vec2 closestPoint; - float minDistance = std::numeric_limits::max(); - - const Vec2 startKeyTransformed = transformFunc(Vec2(curve.m_keys.front().m_time, curve.m_keys.front().m_value)); - if (point.x < startKeyTransformed.x) - { - const float distanceToCurve = std::abs(point.y - startKeyTransformed.y); - if (distanceToCurve < minDistance) - { - closestPoint = Vec2(point.x, startKeyTransformed.y); - minDistance = distanceToCurve; - } - } - - const Vec2 endKeyTransformed = transformFunc(Vec2(curve.m_keys.back().m_time, curve.m_keys.back().m_value)); - if (point.x > endKeyTransformed.x) - { - const float distanceToCurve = std::abs(point.y - endKeyTransformed.y); - if (distanceToCurve < minDistance) - { - closestPoint = Vec2(point.x, endKeyTransformed.y); - minDistance = distanceToCurve; - } - } - - int numCustomKeys = curve.m_customInterpolator ? curve.m_customInterpolator->GetKeyCount() : 0; - if (numCustomKeys > 1 - && transformFunc(Vec2(curve.m_customInterpolator->GetKeyTime(0), 0)).x <= point.x - && transformFunc(Vec2(curve.m_customInterpolator->GetKeyTime(numCustomKeys - 1), 0)).x >= point.x) - { - const int sampleCount = 5; - for (int sample = 0; sample < sampleCount; sample++) - { - float value; - float offset = (float)sample - floorf((float)sampleCount / 2.0f); - float t = TransformPointFromScreen(m_zoom, m_translation, GetCurveArea(), Vec2(point.x + offset, point.y)).x; - curve.m_customInterpolator->InterpolateFloat(t, value); - value = transformFunc(Vec2(0, value)).y; - const Vec2 closestOnSegment = Vec2(point.x, value); - const float distanceToSegment = (closestOnSegment - point).GetLength(); - if (distanceToSegment < minDistance) - { - closestPoint = closestOnSegment; - minDistance = distanceToSegment; - } - } - } - else - { - const auto endIter = curve.m_keys.end() - 1; - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - if (curveType == eCECT_Bezier) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Vec2 p0 = transformFunc(Vec2(segmentStartKey.m_time, segmentStartKey.m_value)); - const Vec2 p3 = transformFunc(Vec2(segmentEndKey.m_time, segmentEndKey.m_value)); - const Vec2 p1 = transformFunc(Vec2(0.0f, segmentStartKey.m_value + segmentStartKey.m_outTangent.y)); - const Vec2 p2 = transformFunc(Vec2(0.0f, segmentEndKey.m_value + segmentEndKey.m_inTangent.y)); - - const Vec2 closestOnSegment = ClosestPointOnBezierSegment(point, p0.x, p3.x, p0.y, p1.y, p2.y, p3.y); - const float distanceToSegment = (closestOnSegment - point).GetLength(); - if (distanceToSegment < minDistance) - { - closestPoint = closestOnSegment; - minDistance = distanceToSegment; - } - } - } - } - - return closestPoint; -} - -void CCurveEditor::ContentChanged() -{ - DeleteMarkedKeys(); - - while (!m_pControlKeys.isEmpty()) - { - delete m_pControlKeys.takeFirst(); - } - - for (auto iter = m_pContent->m_curves.begin(); iter != m_pContent->m_curves.end(); ++iter) - { - SCurveEditorCurve& curve = *iter; - for (size_t i = 0; i < curve.m_keys.size(); ++i) - { - SCurveEditorKey& key = curve.m_keys[i]; - key.m_bModified = false; - - CCurveEditorControl* pControlKey = new CCurveEditorControl(*this, curve, key); - pControlKey->SetSelected(key.m_bSelected); - - m_pControlKeys.append(pControlKey); - } - } - - UpdateTangents(); - - update(); - - SignalContentChanged(); -} - -void CCurveEditor::DeleteMarkedKeys() -{ - if (m_pContent) - { - bool changed = false; - // just delete the underlying key from the data model - the UI controls will be automatically updated to match the new model - for (auto iter = m_pContent->m_curves.begin(); iter != m_pContent->m_curves.end(); ++iter) - { - SCurveEditorCurve& curve = *iter; - for (auto keyIter = curve.m_keys.begin(); keyIter != curve.m_keys.end(); ) - { - if (keyIter->m_bDeleted) - { - keyIter = curve.m_keys.erase(keyIter); - changed = true; - } - else - { - ++keyIter; - } - } - } - } -} - -bool CCurveEditor::AddPointToCurve(const Vec2 point, SCurveEditorCurve* pCurve) -{ - assert(pCurve); - - // Makes sure that a new point can be only added at a safe distance - if (pCurve->m_customInterpolator) - { - const float w = aznumeric_cast(kPointRectExtent.x() * 2); - const float h = aznumeric_cast(kPointRectExtent.y() * 2); - const float minDist = w * w + h * h; - auto keys = pCurve->m_keys; - for (int i = 0; i < keys.size(); i++) - { - const SCurveEditorKey& k = keys[i]; - const Vec2 scrP0 = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), Vec2(k.m_time, k.m_value)); - const Vec2 scrP1 = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), point); - const float sqrDist = (scrP1 - scrP0).GetLength2(); - if (sqrDist <= minDist) - { - return false; - } - } - } - - SCurveEditorKey key; - key.m_bAdded = true; - key.m_time = point.x; - float yValue; - pCurve->m_customInterpolator->InterpolateFloat(point.x, yValue); - key.m_value = pCurve->m_customInterpolator ? yValue : point.y; - - // Set in/out tangents based on neighboring keys - const SCurveEditorKey* closestFromLeft = nullptr; - float closestTimeFromLeft = -std::numeric_limits::max(); - const SCurveEditorKey* closestFromRight = nullptr; - float closestTimeFromRight = std::numeric_limits::max(); - for (const SCurveEditorKey& k : pCurve->m_keys) - { - // Check left - if (k.m_time > closestTimeFromLeft && k.m_time < key.m_time) - { - closestTimeFromLeft = k.m_time; - closestFromLeft = &k; - } - - // Check right - if (k.m_time < closestTimeFromRight && k.m_time > key.m_time) - { - closestTimeFromRight = k.m_time; - closestFromRight = &k; - } - } - - if (closestFromLeft) - { - key.m_inTangentType = SCurveEditorKey::eTangentType_Bezier; - float value; - pCurve->m_customInterpolator->EvalInTangentFloat(key.m_time, value); - key.m_inTangent = Vec2(1.0f, value); - - } - - if (closestFromRight) - { - key.m_outTangentType = SCurveEditorKey::eTangentType_Bezier; - float value; - pCurve->m_customInterpolator->EvalOutTangentFloat(key.m_time, value); - key.m_outTangent = Vec2(1.0f, value); - } - - pCurve->m_keys.push_back(key); - - SortKeys(*pCurve); - - ContentChanged(); - return true; -} - -void CCurveEditor::SortKeys(SCurveEditorCurve& curve) -{ - std::stable_sort(curve.m_keys.begin(), curve.m_keys.end(), [](const SCurveEditorKey& a, const SCurveEditorKey& b) - { - return a.m_time < b.m_time; - }); -} - -QString CCurveEditor::TangentTypeToString(SCurveEditorKey::ETangentType type) -{ - switch (type) - { - case SCurveEditorKey::eTangentType_Standard: // Tangent freely rotates but will stay in sync with its pair if its pair is also standard - return tr("Standard"); - case SCurveEditorKey::eTangentType_Free: // Tangent is completely free moving (does not sync with its pair) - return tr("Free"); - case SCurveEditorKey::eTangentType_Step: // Step immediately to value of next control point in tangent direction - return tr("Step"); - case SCurveEditorKey::eTangentType_Linear: // Tangent always points to next control point - return tr("Linear"); - case SCurveEditorKey::eTangentType_Smooth: // Tangent is smoothed automatically based on direction/distance to neighboring controls - return tr("Smooth"); - case SCurveEditorKey::eTangentType_Flat: // Tangent is flattened (y = 0) - will still sync with its pair if both are flat - return tr("Flat"); - case SCurveEditorKey::eTangentType_Bezier: // Tangent is free moving and can be justified by user. Curve defined by Bz - return tr("Bezier"); - default: - break; - } - - return tr("Undefined tangent!"); -} - -void CCurveEditor::OnDeleteSelectedKeys() -{ - ForEachKey(*m_pContent, []([[maybe_unused]] SCurveEditorCurve& curve, SCurveEditorKey& key) - { - key.m_bDeleted = key.m_bDeleted || key.m_bSelected; - }); - - ContentChanged(); -} - -void CCurveEditor::OnSetSelectedKeysTangentStandard() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Standard); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Standard); - - SmoothSelectedKeys(); -} - -void CCurveEditor::OnSetSelectedKeysTangentSmooth() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Smooth); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Smooth); -} - -void CCurveEditor::OnSetSelectedKeysTangentFree() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Free); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Free); -} - -void CCurveEditor::OnSetSelectedKeysTangentBezier() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Bezier); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Bezier); -} - -void CCurveEditor::OnSetSelectedKeysTangentFlat() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Flat); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Flat); -} - -void CCurveEditor::OnSetSelectedKeysTangentLinear() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Linear); - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Linear); -} - -void CCurveEditor::OnSetSelectedKeysInTangentFree() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Free); -} - -void CCurveEditor::OnSetSelectedKeysInTangentFlat() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Flat); -} - -void CCurveEditor::OnSetSelectedKeysInTangentLinear() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Linear); -} - -void CCurveEditor::OnSetSelectedKeysInTangentStep() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Step); -} - -void CCurveEditor::OnSetSelectedKeysInTangentBezier() -{ - SetSelectedKeysTangentType(ETangent_In, SCurveEditorKey::eTangentType_Bezier); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentFree() -{ - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Free); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentFlat() -{ - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Flat); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentStep() -{ - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Step); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentLinear() -{ - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Linear); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentBezier() -{ - SetSelectedKeysTangentType(ETangent_Out, SCurveEditorKey::eTangentType_Bezier); -} - -void CCurveEditor::OnFitCurvesHorizontally() -{ - if (m_timeRangeEnforced) - { - return; - } - if (m_pContent) - { - bool bAnyKeyFound = false; - float timeMin = std::numeric_limits::max(); - float timeMax = -std::numeric_limits::max(); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - if (curve.m_keys.size() > 0) - { - bAnyKeyFound = true; - timeMin = std::min(curve.m_keys.front().m_time, timeMin); - timeMax = std::max(curve.m_keys.back().m_time, timeMax); - } - } - - if (bAnyKeyFound) - { - ZoomToTimeRange(timeMin, timeMax); - - // Adjust zoom and translation depending on kFitMargin - const float pivot = (0.5f - m_translation.x) / m_zoom.x; - m_zoom.x /= 1.0f + 2.0f * (kFitMargin / GetCurveArea().width()); - m_translation.x += ((0.5f - m_translation.x) / m_zoom.x - pivot) * m_zoom.x; - - update(); - } - } -} - -void CCurveEditor::OnFitCurvesVertically() -{ - if (m_pContent) - { - bool bAnyKeyFound = false; - float valueMin = std::numeric_limits::max(); - float valueMax = -std::numeric_limits::max(); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - - if (m_curveType == eCECT_Bezier && curve.m_keys.size() > 0 && !curve.m_customInterpolator) - { - const auto endIter = curve.m_keys.end() - 1; - - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - bAnyKeyFound = true; - - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Range valueRange = GetBezierSegmentValueRange(segmentStartKey, segmentEndKey); - valueMin = std::min(valueMin, valueRange.start); - valueMax = std::max(valueMax, valueRange.end); - } - } - } - - if (bAnyKeyFound) - { - ZoomToValueRange(valueMin, valueMax); - - // Adjust zoom and translation depending on kFitMargin - const float pivot = (0.5f - m_translation.y) / m_zoom.y; - m_zoom.y /= 1.0f + 2.0f * (kFitMargin / GetCurveArea().height()); - m_translation.y += ((0.5f - m_translation.y) / m_zoom.y - pivot) * m_zoom.y; - - update(); - } - } -} - -void CCurveEditor::SetSelectedKeysTangentType(const ETangent tangent, const SCurveEditorKey::ETangentType type) -{ - if (m_pContent) - { - ForEachKey(*m_pContent, [&]([[maybe_unused]] SCurveEditorCurve& curve, SCurveEditorKey& key) - { - if (key.m_bSelected) - { - if (tangent == ETangent_In) - { - key.m_inTangentType = type; - } - else - { - key.m_outTangentType = type; - } - } - }); - - UpdateTangents(); - - update(); - - SignalContentChanged(); - } -} - -void CCurveEditor::SmoothSelectedKeys() -{ - if (m_pContent) - { - for (SCurveEditorCurve& curve : m_pContent->m_curves) - { - for (int keyIx = 0; keyIx < curve.m_keys.size(); ++keyIx) - { - SCurveEditorKey& key = curve.m_keys[keyIx]; - if (key.m_bSelected) - { - SCurveEditorKey* pLeftKey = (keyIx > 0) ? &curve.m_keys[keyIx - 1] : nullptr; - SCurveEditorKey* pRightKey = (keyIx + 1 < curve.m_keys.size()) ? &curve.m_keys[keyIx + 1] : nullptr; - SmoothTangents(key, key.m_inTangent, key.m_outTangent, pLeftKey, pRightKey, false); - } - } - } - - UpdateTangents(); - - update(); - } -} - -void CCurveEditor::UpdateTangents() -{ - for (SCurveEditorCurve& curve : m_pContent->m_curves) - { - for (int keyIx = 0; keyIx < curve.m_keys.size(); ++keyIx) - { - SCurveEditorKey& key = curve.m_keys[keyIx]; - - if (key.m_bAdded) - { - if (curve.m_keys.size() == 1) - { - return; - } - if (keyIx == 0) - { - SCurveEditorKey& nextKey = curve.m_keys[keyIx + 1]; - key.m_outTangent = Vec2(nextKey.m_time - key.m_time, nextKey.m_value - key.m_value) / 3.0f; - key.m_inTangent = -key.m_outTangent; - } - else if (keyIx + 1 == curve.m_keys.size()) - { - SCurveEditorKey& prevKey = curve.m_keys[keyIx - 1]; - key.m_inTangent = Vec2(prevKey.m_time - key.m_time, prevKey.m_value - key.m_value) / 3.0f; - key.m_outTangent = -key.m_outTangent; - } - key.m_bAdded = false; - } - if (keyIx > 0) - { - SCurveEditorKey& prevKey = curve.m_keys[keyIx - 1]; - - switch (key.m_inTangentType) - { - case SCurveEditorKey::eTangentType_Smooth: - { - if (keyIx + 1 >= curve.m_keys.size()) - { - key.m_inTangent = Vec2(prevKey.m_time - key.m_time, prevKey.m_value - key.m_value) / 3.0f; - break; - } - SCurveEditorKey& nextKey = curve.m_keys[keyIx + 1]; - const float deltaTime = nextKey.m_time - prevKey.m_time; - if (deltaTime > 0.0f) - { - Vec2 normalizedIn = Vec2(prevKey.m_time - key.m_time, prevKey.m_value - key.m_value); - Vec2 normalizedOut = Vec2(nextKey.m_time - key.m_time, nextKey.m_value - key.m_value); - - key.m_inTangent = GetSmoothInTangent(key, normalizedIn, normalizedOut, &prevKey, &nextKey, true); - } - break; - } - case SCurveEditorKey::eTangentType_Flat: - { - key.m_inTangent = Vec2(prevKey.m_time - key.m_time, 0.0f) / 3.0f; - break; - } - case SCurveEditorKey::eTangentType_Step: - { - //key.m_inTangent = Vec2(0.0f, 0.0f); - break; - } - case SCurveEditorKey::eTangentType_Linear: - { - key.m_inTangent = Vec2(prevKey.m_time - key.m_time, prevKey.m_value - key.m_value) / 3.0f; - break; - } - default: - { - const float oneThirdDeltaTime = (key.m_time - prevKey.m_time) / 3.0f; - float ratio = oneThirdDeltaTime / -key.m_inTangent.x; - key.m_inTangent *= ratio; - break; - } - } - } - if (keyIx + 1 < curve.m_keys.size()) - { - SCurveEditorKey& nextKey = curve.m_keys[keyIx + 1]; - - switch (key.m_outTangentType) - { - case SCurveEditorKey::eTangentType_Smooth: - { - if (keyIx <= 0) - { - key.m_outTangent = Vec2(nextKey.m_time - key.m_time, nextKey.m_value - key.m_value) / 3.0f; - } - if (keyIx > 0) - { - SCurveEditorKey& prevKey = curve.m_keys[keyIx - 1]; - const float deltaTime = nextKey.m_time - prevKey.m_time; - if (deltaTime > 0.0f) - { - Vec2 normalizedIn = Vec2(prevKey.m_time - key.m_time, prevKey.m_value - key.m_value); - Vec2 normalizedOut = Vec2(nextKey.m_time - key.m_time, nextKey.m_value - key.m_value); - - key.m_outTangent = GetSmoothOutTangent(key, normalizedIn, normalizedOut, &prevKey, &nextKey, true); - } - } - break; - } - case SCurveEditorKey::eTangentType_Flat: - { - key.m_outTangent = Vec2(nextKey.m_time - key.m_time, 0.0f) / 3.0f; - break; - } - case SCurveEditorKey::eTangentType_Step: - { - //key.m_outTangent = Vec2(0.0f, 0.0f); - break; - } - case SCurveEditorKey::eTangentType_Linear: - { - key.m_outTangent = Vec2(nextKey.m_time - key.m_time, nextKey.m_value - key.m_value) / 3.0f; - break; - } - default: - { - const float oneThirdDeltaTime = (nextKey.m_time - key.m_time) / 3.0f; - float ratio = oneThirdDeltaTime / key.m_outTangent.x; - key.m_outTangent *= ratio; - break; - } - } - } - } - } -} - -QRect CCurveEditor::GetCurveArea() -{ - const uint rulerAreaHeight = m_bRulerVisible ? kRulerHeight : 0; - return QRect(0, rulerAreaHeight, width(), height() - rulerAreaHeight); -} - -Vec2 CCurveEditor::TransformToScreenCoordinates(Vec2 graphPoint) -{ - return TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), graphPoint); -} - -Vec2 CCurveEditor::TransformFromScreenCoordinates(Vec2 screenPoint) -{ - return TransformPointFromScreen(m_zoom, m_translation, GetCurveArea(), screenPoint); -} - -void CCurveEditor::SetOptOutFlags(int flags) -{ - m_optOutFlags = flags; - if (m_optOutFlags & EOptOutRuler) - { - m_bRulerVisible = false; - } -} - -void CCurveEditor::PopulateControlContextMenu(QMenu* pMenu) -{ - #define OPTOUT(BITS) ((m_optOutFlags & (BITS))) - - bool needsSeperator = false; - - pMenu->addAction("Delete selected keys", this, SLOT(OnDeleteSelectedKeys())); - pMenu->addSeparator(); - - // standard and smooth should only be available for both - flat, free, step, and linear should be available for all - const int flagsFreeStep = EOptOutFree | EOptOutStep; - if (OPTOUT(flagsFreeStep) != flagsFreeStep) - { - pMenu->addAction("Standard", this, SLOT(OnSetSelectedKeysTangentStandard())); - pMenu->addAction("Auto Smooth", this, SLOT(OnSetSelectedKeysTangentSmooth())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFree)) - { - pMenu->addAction("Free", this, SLOT(OnSetSelectedKeysTangentFree())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutBezier)) - { - pMenu->addAction("Bezier", this, SLOT(OnSetSelectedKeysTangentBezier())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFlat)) - { - pMenu->addAction("Flat", this, SLOT(OnSetSelectedKeysTangentFlat())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutLinear)) - { - pMenu->addAction("Linear", this, SLOT(OnSetSelectedKeysTangentLinear())); - needsSeperator = true; - } - - if (needsSeperator) - { - pMenu->addSeparator(); - } - needsSeperator = false; - - if (!OPTOUT(EOptOutBezier)) - { - pMenu->addAction("IN Tangent - Bezier", this, SLOT(OnSetSelectedKeysInTangentBezier())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFree)) - { - pMenu->addAction("IN Tangent - Free", this, SLOT(OnSetSelectedKeysInTangentFree())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFlat)) - { - pMenu->addAction("IN Tangent - Flat", this, SLOT(OnSetSelectedKeysInTangentFlat())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutLinear)) - { - pMenu->addAction("IN Tangent - Linear", this, SLOT(OnSetSelectedKeysInTangentLinear())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutStep)) - { - pMenu->addAction("IN Tangent - Step", this, SLOT(OnSetSelectedKeysInTangentStep())); - needsSeperator = true; - } - - if (needsSeperator) - { - pMenu->addSeparator(); - } - needsSeperator = false; - - if (!OPTOUT(EOptOutBezier)) - { - pMenu->addAction("OUT Tangent - Bezier", this, SLOT(OnSetSelectedKeysOutTangentBezier())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFree)) - { - pMenu->addAction("OUT Tangent - Free", this, SLOT(OnSetSelectedKeysOutTangentFree())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFlat)) - { - pMenu->addAction("OUT Tangent - Flat", this, SLOT(OnSetSelectedKeysOutTangentFlat())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutLinear)) - { - pMenu->addAction("OUT Tangent - Linear", this, SLOT(OnSetSelectedKeysOutTangentLinear())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutStep)) - { - pMenu->addAction("OUT Tangent - Step", this, SLOT(OnSetSelectedKeysOutTangentStep())); - needsSeperator = true; - } - - if (!OPTOUT(EOptOutFitCurvesContextMenuOptions)) - { - if (needsSeperator) - { - pMenu->addSeparator(); - } - needsSeperator = false; - pMenu->addAction("Fit curves horizontally", this, SLOT(OnFitCurvesHorizontally())); - pMenu->addAction("Fit curves vertically", this, SLOT(OnFitCurvesVertically())); - } -} - -void CCurveEditor::setPenColor(QColor color) -{ - if (color.isValid()) - { - m_penColor = color; - } - else if (!m_penColor.isValid()) - { - m_penColor = palette().highlight().color(); - } -} - -void CCurveEditor::updateCurveKeyShapeColor() -{ - for (CCurveEditorControl* key : m_pControlKeys) - { - QColor color = key->IsSelected() ? QColor(Qt::yellow) : QColor(Qt::white); - key->SetIconShapeColor(color); - } -} - -void CCurveEditor::SetIconShapeColor(unsigned int key, QColor color) -{ - m_pControlKeys[key]->SetIconShapeColor(color); -} - -void CCurveEditor::SetIconFillColor(unsigned int key, QColor color) -{ - m_pControlKeys[key]->SetIconFillColor(color); -} - -void CCurveEditor::SetIconImage(QString str) -{ - for (auto* key : m_pControlKeys) - { - key->SetIconImage(str); - } -} - -void CCurveEditor::SetIconShapeMask(QColor color) -{ - for (auto* key : m_pControlKeys) - { - key->SetIconShapeMask(color); - } -} - -void CCurveEditor::SetIconFillMask(QColor color) -{ - for (auto* key : m_pControlKeys) - { - key->SetIconFillMask(color); - } -} - -void CCurveEditor::SetIconToolTip(unsigned int key, QString str) -{ - m_pControlKeys[key]->SetIconToolTip(str); -} - -void CCurveEditor::SetIconSize(unsigned int key, unsigned int size) -{ - m_pControlKeys[key]->SetIconSize(size); - m_pControlKeys[key]->SetVisualSize(size); - m_pControlKeys[key]->SetClickableSize(size); -} - - diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditor.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditor.h deleted file mode 100644 index 60d5608005..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditor.h +++ /dev/null @@ -1,233 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "CurveEditorContent.h" -#include -#include - -class QMenu; -class CCurveEditorControl; -class CCurveEditorTangentControl; -struct ISplineInterpolator; - -enum ETangent -{ - ETangent_In, - ETangent_Out -}; - -enum ECurveEditorCurveType -{ - eCECT_Bezier, - // 2D Bezier curves are used for better curve control, the editor - // will enforce that the resulting curve is always 1D. - eCECT_2DBezier, -}; - -namespace CurveEditorHelpers -{ - // Picks a nice color value for a curve. Wraps around after 4. - EDITOR_COMMON_API ColorB GetCurveColor(const uint n); - EDITOR_COMMON_API QColor LerpColor(const QColor& a, const QColor& b, float k); -} - -class EDITOR_COMMON_API CCurveEditor - : public QWidget -{ - Q_OBJECT -public: - enum EOptOutFlags - { - EOptOutFree = 1 << 0, - EOptOutFlat = 1 << 1, - EOptOutLinear = 1 << 2, - EOptOutStep = 1 << 3, - EOptOutBezier = 1 << 4, - EOptOutSelectionKey = 1 << 5, - EOptOutSelectionInOutTangent = 1 << 6, - //steven@conffx added some optout options to allow easier graphical customization - EOptOutKeyIcon = 1 << 7, - EOptOutRuler = 1 << 8, - EOptOutTimeSlider = 1 << 9, - EOptOutBackground = 1 << 10, - EOptOutCustomPenColor = 1 << 11, - EOptOutControls = 1 << 12, - eOptOutDashedPath = 1 << 13, - EOptOutDefaultTooltip = 1 << 14, - EOptOutFitCurvesContextMenuOptions = 1 << 15, - EOptOutZoomingAndPanning = 1 << 16 - }; - - CCurveEditor(QWidget* parent); - ~CCurveEditor(); - - void SetContent(SCurveEditorContent* pContent); - SCurveEditorContent* Content() const { return m_pContent; } - - void SetTime(const float time); - - // The background in the time and value range will be drawn a bit brighter to indicate where keys - // should be placed. The curve editor does not enforce that the curves actually stay in those ranges. - void SetTimeRange(const float start, const float end); - void SetValueRange(const float min, const float max); - - // Points cannot be added outside of the time range and the view will not move horizontally...zooming will only be done on the vertical axis - void EnforceTimeRange(const float start, const float end); - bool IsTimeRangeEnforced() const; - - void ZoomToTimeRange(const float start, const float end); - void ZoomToValueRange(const float min, const float max); - - void SetCurveType(ECurveEditorCurveType curveType); - void SetWeighted(bool bWeighted); - void SetHandlesVisible(bool bVisible); - void SetRulerVisible(bool bVisible); - void SetTimeSliderVisible(bool bVisible); - - Vec2 TransformToScreenCoordinates(Vec2 graphPoint); - Vec2 TransformFromScreenCoordinates(Vec2 screenPoint); - - // Removes parts of the popup-menu, use CCurveEditor::EMenuOptOutFlags - void SetOptOutFlags(int flags); - - // Tools added to tool bar depend on options above - void PopulateControlContextMenu(QMenu* pToolBar); - - virtual void paintEvent(QPaintEvent* pEvent) override; - void mousePressEvent(QMouseEvent* pEvent) override; - void mouseDoubleClickEvent(QMouseEvent* pEvent) override; - void mouseMoveEvent(QMouseEvent* pEvent) override; - void mouseReleaseEvent(QMouseEvent* pEvent) override; - void focusOutEvent(QFocusEvent* pEvent) override; - void wheelEvent(QWheelEvent* pEvent) override; - void keyPressEvent(QKeyEvent* pEvent) override; - - QString static TangentTypeToString(SCurveEditorKey::ETangentType type); - - void updateCurveKeyShapeColor(); // loop through curve keys and set shape color for them - void SetIconShapeColor(unsigned int key, QColor color); - void SetIconFillColor(unsigned int key, QColor color); - void SetIconImage(QString str); - void SetIconShapeMask(QColor color); - void SetIconFillMask(QColor color); - void SetIconToolTip(unsigned int key, QString str); - void SetIconSize(unsigned int key, unsigned int size); - - void setPenColor(QColor color); - void ContentChanged(); - void SortKeys(SCurveEditorCurve& curve); - - std::pair HitDetectCurve(const QPoint point); - CCurveEditorControl* HitDetectKey(const QPoint point); - CCurveEditorTangentControl* HitDetectTangent(const QPoint point); - - CCurveEditorControl* GetSelectedCurveKey(); - QRectF GetBackgroundRect(); - - void SelectKey(CCurveEditorControl* pKeyToSelect, bool addToExistingSelection); - void SelectTangent(CCurveEditorTangentControl* pTangentToSelect); - void SelectInRect(const QRect& rect); - -signals: - void SignalContentChanged(); - void SignalScrub(); - void SignalKeyMoved(); - void SignalKeyMoveStarted(); - void SignalKeySelected(CCurveEditorControl* selectedKey); - -public slots: - void OnDeleteSelectedKeys(); - void OnSetSelectedKeysTangentStandard(); - void OnSetSelectedKeysTangentSmooth(); - void OnSetSelectedKeysTangentFree(); - void OnSetSelectedKeysTangentBezier(); - void OnSetSelectedKeysTangentFlat(); - void OnSetSelectedKeysTangentLinear(); - - void OnSetSelectedKeysInTangentFree(); - void OnSetSelectedKeysInTangentFlat(); - void OnSetSelectedKeysInTangentLinear(); - void OnSetSelectedKeysInTangentStep(); - void OnSetSelectedKeysInTangentBezier(); - - void OnSetSelectedKeysOutTangentFree(); - void OnSetSelectedKeysOutTangentFlat(); - void OnSetSelectedKeysOutTangentLinear(); - void OnSetSelectedKeysOutTangentStep(); - void OnSetSelectedKeysOutTangentBezier(); - - void OnFitCurvesHorizontally(); - void OnFitCurvesVertically(); - -protected: - struct SMouseHandler - { - virtual ~SMouseHandler() = default; - virtual void mousePressEvent([[maybe_unused]] QMouseEvent* pEvent) {} - virtual void mouseDoubleClickEvent([[maybe_unused]] QMouseEvent* pEvent) {} - virtual void mouseMoveEvent([[maybe_unused]] QMouseEvent* pEvent) {} - virtual void mouseReleaseEvent([[maybe_unused]] QMouseEvent* pEvent) {} - virtual void focusOutEvent([[maybe_unused]] QFocusEvent* pEvent) {} - virtual void paintOver([[maybe_unused]] QPainter& painter) {} - }; - struct SSelectionHandler; - struct SPanHandler; - struct SZoomHandler; - struct SMoveKeyHandler; - struct SRotateTangentHandler; - struct SScrubHandler; - QColor m_penColor; - - void LeftButtonMousePressEvent(QMouseEvent* pEvent); - void MiddleButtonMousePressEvent(QMouseEvent* pEvent); - void RightButtonMousePressEvent(QMouseEvent* pEvent); - - void DeleteMarkedKeys(); - - void SetTimeRange(const float start, const float end, bool enforce); - - Vec2 ClosestPointOnCurve(const Vec2 point, const SCurveEditorCurve& curve, const ECurveEditorCurveType curveType); - - bool AddPointToCurve(Vec2 point, SCurveEditorCurve* pCurve); - - QRect GetCurveArea(); - - void SetSelectedKeysTangentType(const ETangent tangent, const SCurveEditorKey::ETangentType type); - void SmoothSelectedKeys(); - - void UpdateTangents(); - SCurveEditorContent* m_pContent; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::unique_ptr m_pMouseHandler; - - ECurveEditorCurveType m_curveType; - bool m_bWeighted; - bool m_bHandlesVisible; - bool m_bRulerVisible; - bool m_bTimeSliderVisible; - - float m_time; - Vec2 m_zoom; - Vec2 m_translation; - Range m_timeRange; - bool m_timeRangeEnforced; - Range m_valueRange; - - int m_optOutFlags; -public: - QList m_pControlKeys; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent.h deleted file mode 100644 index 49acc62f67..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent.h +++ /dev/null @@ -1,155 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include -#include - -#include "Serialization/Strings.h" -#include "Serialization/SmartPtr.h" -#include "Serialization/Color.h" -#include "Serialization.h" - -struct ISplineInterpolator; - -struct SCurveEditorKey -{ - SCurveEditorKey() - : m_bSelected(false) - , m_bModified(false) - , m_bAdded(false) - , m_bDeleted(false) - , m_time(0.0f) - , m_value(0.0f) - , m_inTangentType(eTangentType_Standard) - , m_outTangentType(eTangentType_Standard) - , m_inTangent(ZERO) - , m_outTangent(ZERO) - { - } - - enum ETangentType - { - eTangentType_Standard, // Tangent freely rotates but will stay in sync with its pair if its pair is also standard - eTangentType_Free, // Tangent is completely free moving (does not sync with its pair) - eTangentType_Step, // Step immediately to value of next control point in tangent direction - eTangentType_Linear, // Tangent always points to next control point - eTangentType_Bezier, // Tangent is free moving and can be justified by user - eTangentType_Smooth, // Tangent is smoothed automatically based on direction/distance to neighboring controls - eTangentType_Flat, // Tangent is flattened (y = 0) - will still sync with its pair if both are flat - }; - - void Serialize(IArchive& ar) - { - ar(m_inTangentType, "inTangentType"); - ar(m_outTangentType, "outTangentType"); - ar(m_time, "time"); - ar(m_value, "value"); - ar(m_inTangent, "inTangent"); - ar(m_outTangent, "outTangent"); - } - - bool m_bSelected : 1; - bool m_bModified : 1; - bool m_bAdded : 1; - bool m_bDeleted : 1; - - ETangentType m_inTangentType : 4; - ETangentType m_outTangentType : 4; - - float m_time; - float m_value; - - // For 1D Bezier only the Y component is used - Vec2 m_inTangent; - Vec2 m_outTangent; - - - bool operator==(const SCurveEditorKey& rhs) const - { - return (m_inTangentType == rhs.m_inTangentType - && m_outTangentType == rhs.m_outTangentType - && m_time == rhs.m_time - && m_value == rhs.m_value - && m_inTangent == rhs.m_inTangent - && m_outTangent == rhs.m_outTangent); - } - - bool operator!=(const SCurveEditorKey& rhs) const - { - return !(*this == rhs); - } -}; - -struct SCurveEditorCurve -{ - SCurveEditorCurve() - : m_bModified(false) - , m_defaultValue(0.0f) - , m_color(255, 255, 255) - , m_customInterpolator(nullptr) - {} - - void Serialize(IArchive& ar) - { - ar(m_keys, "keys"); - ar(m_defaultValue, "defaultValue"); - ar(m_color, "color"); - } - - bool m_bModified : 1; - float m_defaultValue; - ColorB m_color; - - // Setting m_customInterpolator will override spline-draw code. - // When used, its up to developer to fill and update all necessary keys. - ISplineInterpolator* m_customInterpolator; - - std::vector m_keys; - - bool operator==(const SCurveEditorCurve& rhs) const - { - if (m_defaultValue != rhs.m_defaultValue - || m_color != rhs.m_color - || m_keys.size() != rhs.m_keys.size()) - { - return false; - } - - for (int i = 0; i < m_keys.size(); i++) - { - if (m_keys[i] != rhs.m_keys[i]) - return false; - } - - return true; - } - - bool operator!=(const SCurveEditorCurve& rhs) const - { - return !(*this == rhs); - } -}; - -typedef std::vector TCurveEditorCurves; - -struct SCurveEditorContent -{ - void Serialize(IArchive& ar) - { - ar(m_curves, "curves"); - } - - TCurveEditorCurves m_curves; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_38.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_38.h deleted file mode 100644 index f11a135c80..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_38.h +++ /dev/null @@ -1,84 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include -#include -#include -#include - -#include "Serialization/Strings.h" -#include "Serialization/SmartPtr.h" -#include "Serialization/Color.h" -#include "Serialization.h" - -struct SCurveEditorKey -{ - SCurveEditorKey() - : m_time(0) - , m_bSelected(false) - , m_bModified(false) - , m_bAdded(false) - , m_bDeleted(false) - { - } - - void Serialize(IArchive& ar) - { - ar(m_time); - ar(m_controlPoint); - } - - SAnimTime m_time; - SBezierControlPoint m_controlPoint; - - bool m_bSelected : 1; - bool m_bModified : 1; - bool m_bAdded : 1; - bool m_bDeleted : 1; -}; - -struct SCurveEditorCurve -{ - SCurveEditorCurve() - : m_bModified(false) - , m_defaultValue(0.0f) - , m_color(255, 255, 255) - {} - - void Serialize(IArchive& ar) - { - ar(m_keys, "keys"); - ar(m_defaultValue, "defaultValue"); - ar(m_color, "color"); - } - - bool m_bModified : 1; - float m_defaultValue; - ColorB m_color; - - DynArray userSideLoad; - - std::vector m_keys; -}; - -typedef std::vector TCurveEditorCurves; - -struct SCurveEditorContent -{ - void Serialize(IArchive& ar) - { - ar(m_curves, "curves"); - } - - TCurveEditorCurves m_curves; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_impl.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_impl.h deleted file mode 100644 index 9d2bdd796a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditorContent_impl.h +++ /dev/null @@ -1,20 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "CurveEditorContent.h" - -SERIALIZATION_ENUM_BEGIN_NESTED(SCurveEditorKey, ETangentType, "TangentType") -SERIALIZATION_ENUM_VALUE_NESTED(SCurveEditorKey, eTangentType_Custom, "Custom") -SERIALIZATION_ENUM_VALUE_NESTED(SCurveEditorKey, eTangentType_Auto, "Smooth") -SERIALIZATION_ENUM_VALUE_NESTED(SCurveEditorKey, eTangentType_Zero, "Zero") -SERIALIZATION_ENUM_VALUE_NESTED(SCurveEditorKey, eTangentType_Step, "Step") -SERIALIZATION_ENUM_VALUE_NESTED(SCurveEditorKey, eTangentType_Linear, "Linear") -SERIALIZATION_ENUM_END() diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.cpp b/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.cpp deleted file mode 100644 index 0b0359a0ad..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.cpp +++ /dev/null @@ -1,352 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "EditorCommon_precompiled.h" -#include "CurveEditorControl.h" - -#include -#include -#include - -#include - -#include "CurveEditor.h" - -namespace -{ - const int kDefaultControlVisualSize = 8; - const int kDefaultControlClickableSize = 10; - const int kDefaultTangentControlVisualSize = 6; - const int kDefaultTangentControlClickableSize = 8; - const int kDefaultTangentControlDistanceFromControl = 30; - - void DrawPointRect(QPainter& painter, QPointF point, const QColor& color, int size) - { - painter.setBrush(QBrush(color)); - painter.setPen(QColor(0, 0, 0)); - float halfSize = size / 2.0f; - QPointF extents = QPointF(halfSize, halfSize); - painter.drawRect(QRectF(point - extents, point + extents)); - } -} - -CCurveEditorControl::CCurveEditorControl(CCurveEditor& curveEditor, SCurveEditorCurve& curve, SCurveEditorKey& key) - : m_CurveEditor(curveEditor) - , m_Curve(curve) - , m_Key(key) - , m_VisualSize(kDefaultControlVisualSize) - , m_ClickableSize(kDefaultControlClickableSize) - , m_pInTangent(new CCurveEditorTangentControl(*this, ETangent_In)) - , m_pOutTangent(new CCurveEditorTangentControl(*this, ETangent_Out)) - , m_filledPxr(kDefaultControlVisualSize, kDefaultControlVisualSize) - , m_shapePxr(kDefaultControlVisualSize, kDefaultControlVisualSize) - , m_icon(kDefaultControlVisualSize, kDefaultControlVisualSize) - , m_originalPxr(kDefaultControlVisualSize, kDefaultControlVisualSize) - , m_tip("") - , m_iconsize(16) -{ -} - -CCurveEditorControl::~CCurveEditorControl() -{ - delete m_pInTangent; - delete m_pOutTangent; -} - -CCurveEditor& CCurveEditorControl::GetCurveEditor() const -{ - return m_CurveEditor; -} - -SCurveEditorCurve& CCurveEditorControl::GetCurve() const -{ - return m_Curve; -} - -SCurveEditorKey& CCurveEditorControl::GetKey() const -{ - return m_Key; -} - -CCurveEditorTangentControl& CCurveEditorControl::GetInTangent() -{ - return *m_pInTangent; -} - -CCurveEditorTangentControl& CCurveEditorControl::GetOutTangent() -{ - return *m_pOutTangent; -} - -bool CCurveEditorControl::IsSelected() const -{ - return m_Key.m_bSelected; -} - -void CCurveEditorControl::SetSelected(bool selected) -{ - m_Key.m_bSelected = selected; - m_pInTangent->SetVisible(selected); - m_pOutTangent->SetVisible(selected); -} - -bool CCurveEditorControl::IsKeyMarkedForRemoval() const -{ - return m_Key.m_bDeleted; -} - -void CCurveEditorControl::MarkKeyForRemoval() -{ - m_Key.m_bDeleted = true; -} - -void CCurveEditorControl::Paint(QPainter& painter, const QPalette& palette, const bool& paintInOutTangents) -{ - const QColor pointColor = m_Key.m_bSelected ? palette.color(QPalette::Highlight) : QColor(255, 255, 255, 255); - - if (paintInOutTangents) - { - m_pInTangent->Paint(painter, palette); - m_pOutTangent->Paint(painter, palette); - } - - DrawPointRect(painter, GetScreenPosition(), pointColor, m_VisualSize); -} -void CCurveEditorControl::PaintIcon(QPainter& painter, const QPalette& palette, const bool& paintInOutTangents) -{ - if (paintInOutTangents) - { - m_pInTangent->Paint(painter, palette); - m_pOutTangent->Paint(painter, palette); - } - - QPointF pos = GetScreenPosition(); - float halfSize = m_iconsize / 2.0f; - QPointF extents = QPointF(halfSize, halfSize); - painter.drawPixmap(QRectF(GetScreenPosition() - extents, GetScreenPosition() + extents), m_icon, QRectF(0, 0, m_iconsize, m_iconsize)); -} - -bool CCurveEditorControl::IsMouseWithinControl(QPointF screenPos) const -{ - QPointF keyPosition = GetScreenPosition(); - QPointF deltaPos = screenPos - keyPosition; - - float halfClickSize = m_ClickableSize / 2.0f; - - return abs(deltaPos.x()) <= halfClickSize && abs(deltaPos.y()) <= halfClickSize; -} - -QPointF CCurveEditorControl::GetScreenPosition() const -{ - Vec2 screenPosition = m_CurveEditor.TransformToScreenCoordinates(Vec2(m_Key.m_time, m_Key.m_value)); - return QPointF(screenPosition.x, screenPosition.y); -} - -void CCurveEditorControl::BuildIcon() -{ - m_filledPxr = QPixmap(m_originalPxr.size()); - m_shapePxr = QPixmap(m_originalPxr.size()); - m_shapePxr.fill(m_shapeColor); - m_filledPxr.fill(m_fillColor); - m_shapePxr.setMask(m_originalPxr.createMaskFromColor(m_shapeMask).createMaskFromColor(m_fillMask)); - m_filledPxr.setMask(m_originalPxr.createMaskFromColor(m_fillMask, Qt::MaskOutColor)); - QPainter painter(&m_shapePxr); - painter.drawPixmap(0, 0, m_filledPxr); - m_icon = m_shapePxr.scaled(m_iconsize, m_iconsize, Qt::IgnoreAspectRatio, Qt::SmoothTransformation); -} - -void CCurveEditorControl::SetIconFillMask(QColor color) -{ - m_fillMask = color; - BuildIcon(); -} - -void CCurveEditorControl::SetIconShapeMask(QColor color) -{ - m_shapeMask = color; - BuildIcon(); -} - -void CCurveEditorControl::SetIconImage(QString str) -{ - m_originalPxr.load(str); - BuildIcon(); -} - -void CCurveEditorControl::SetIconFillColor(QColor color) -{ - m_fillColor = color; - BuildIcon(); -} - -void CCurveEditorControl::SetIconShapeColor(QColor color) -{ - m_shapeColor = color; - BuildIcon(); -} - - -CCurveEditorTangentControl::CCurveEditorTangentControl(CCurveEditorControl& control, ETangent tangentDirection) - : m_Control(control) - , m_TangentDirection(tangentDirection) - , m_Visible(false) - , m_Selected(false) - , m_VisualSize(kDefaultTangentControlVisualSize) - , m_ClickableSize(kDefaultTangentControlClickableSize) - , m_DistanceFromControl(kDefaultTangentControlDistanceFromControl) -{ -} - -CCurveEditorTangentControl::~CCurveEditorTangentControl() -{ -} - -CCurveEditorControl& CCurveEditorTangentControl::GetControl() -{ - return m_Control; -} - -ETangent CCurveEditorTangentControl::GetTangentDirection() const -{ - return m_TangentDirection; -} - -bool CCurveEditorTangentControl::IsVisible() const -{ - if (!m_Visible) - { - return false; - } - SCurveEditorKey::ETangentType tangentType; - - if (m_TangentDirection == ETangent_In) - { - tangentType = m_Control.GetKey().m_inTangentType; - } - else - { - tangentType = m_Control.GetKey().m_outTangentType; - } - - if (tangentType == SCurveEditorKey::eTangentType_Step) - { - return false; - } - - // first in - if ((*m_Control.GetCurve().m_keys.begin()).m_time == m_Control.GetKey().m_time && m_TangentDirection == ETangent_In) - { - return false; - } - - // last out - if ((*(m_Control.GetCurve().m_keys.end() - 1)).m_time == m_Control.GetKey().m_time && m_TangentDirection == ETangent_Out) - { - return false; - } - - return true; -} - -void CCurveEditorTangentControl::SetVisible(bool visible) -{ - m_Visible = visible; -} - -bool CCurveEditorTangentControl::IsSelected() const -{ - return m_Selected; -} - -void CCurveEditorTangentControl::SetSelected(bool selected) -{ - m_Selected = selected; -} - -void CCurveEditorTangentControl::SetVisualSize(int visualSize) -{ - m_VisualSize = visualSize; -} - -void CCurveEditorTangentControl::SetClickableSize(int clickableSize) -{ - m_ClickableSize = clickableSize; -} - -void CCurveEditorTangentControl::SetDistanceFromControl(int distanceFromControl) -{ - m_DistanceFromControl = distanceFromControl; -} - -void CCurveEditorTangentControl::Paint(QPainter& painter, const QPalette& palette) -{ - if (!IsVisible()) - { - return; - } - - QPointF controlPosition = m_Control.GetScreenPosition(); - QPointF tangentPosition = GetScreenPosition(); - - float highlightPercent; - if (m_Selected) - { - highlightPercent = 0.0f; - } - else - { - highlightPercent = 0.5f; - } - const QColor tangentColor = CurveEditorHelpers::LerpColor(palette.color(QPalette::Highlight), palette.color(QPalette::Window), highlightPercent); - const QPen tangentPen = QPen(tangentColor); - - painter.setPen(tangentPen); - painter.drawLine(controlPosition, tangentPosition); - - const QColor tangentControlColor = m_Selected ? palette.color(QPalette::Highlight) : palette.color(QPalette::Dark); - DrawPointRect(painter, tangentPosition, tangentControlColor, m_VisualSize); -} - -bool CCurveEditorTangentControl::IsMouseWithinControl(QPointF screenPos) const -{ - if (!IsVisible()) - { - return false; - } - - QPointF keyPosition = GetScreenPosition(); - QPointF deltaPos = screenPos - keyPosition; - - float halfClickSize = m_ClickableSize / 2.0f; - - return abs(deltaPos.x()) <= halfClickSize && abs(deltaPos.y()) <= halfClickSize; -} - -QPointF CCurveEditorTangentControl::GetScreenPosition() const -{ - QPointF controlPosition = m_Control.GetScreenPosition(); - - Vec2 tangent; - if (m_TangentDirection == ETangent_In) - { - tangent = m_Control.GetKey().m_inTangent; - } - else - { - tangent = m_Control.GetKey().m_outTangent; - } - - Vec2 tangentScreenPosition = m_Control.GetCurveEditor().TransformToScreenCoordinates(Vec2(m_Control.GetKey().m_time + tangent.x, m_Control.GetKey().m_value + tangent.y)); - Vec2 transformedTangentDelta = (tangentScreenPosition - Vec2(aznumeric_cast(controlPosition.x()), aznumeric_cast(controlPosition.y()))).Normalize() * aznumeric_cast(m_DistanceFromControl); - - return controlPosition + QPointF(transformedTangentDelta.x, transformedTangentDelta.y); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.h deleted file mode 100644 index 5cc12cbfcf..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditorControl.h +++ /dev/null @@ -1,150 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include "CurveEditor.h" - -#include - -class CCurveEditor; -class CCurveEditorTangentControl; -class QMouseEvent; - -class QPainter; - -class EDITOR_COMMON_API CCurveEditorControl -{ -public: - CCurveEditorControl(CCurveEditor& curveEditor, SCurveEditorCurve& curve, SCurveEditorKey& key); - ~CCurveEditorControl(); - - CCurveEditor& GetCurveEditor() const; - SCurveEditorCurve& GetCurve() const; - SCurveEditorKey& GetKey() const; - - CCurveEditorTangentControl& GetInTangent(); - CCurveEditorTangentControl& GetOutTangent(); - - void SetVisualSize(int visualSize) - { - m_VisualSize = visualSize; - } - void SetClickableSize(int clickableSize) - { - m_ClickableSize = clickableSize; - } - - bool IsSelected() const; - void SetSelected(bool selected); - - bool IsKeyMarkedForRemoval() const; - void MarkKeyForRemoval(); - - void Paint(QPainter& painter, const QPalette& palette, const bool& paintInOutTangents); - void PaintIcon(QPainter& painter, const QPalette& palette, const bool& paintInOutTangents); - - bool IsMouseWithinControl(QPointF screenPos) const; - - QPointF GetScreenPosition() const; - - QRect GetRect() const - { - return QRect(aznumeric_cast(GetScreenPosition().x() - (m_VisualSize / 2)), aznumeric_cast(GetScreenPosition().y() - (m_VisualSize / 2)), m_VisualSize, m_VisualSize); - } - - void SetIconShapeColor(QColor color); - - void SetIconFillColor(QColor color); - - void SetIconImage(QString str); - - void SetIconShapeMask(QColor color); - - void SetIconFillMask(QColor color); - - void SetIconToolTip(QString str) - { - m_tip = str; - } - - void SetIconSize(int size) - { - m_iconsize = size; - BuildIcon(); - } - - QString GetToolTip() const { return m_tip; } - -protected: - void BuildIcon(); - -private: - QPixmap m_icon; - QPixmap m_filledPxr; - QPixmap m_shapePxr; - QPixmap m_originalPxr; - QColor m_fillColor; - QColor m_shapeColor; - QColor m_fillMask; - QColor m_shapeMask; - QString m_tip; - int m_iconsize; - - CCurveEditor& m_CurveEditor; - SCurveEditorCurve& m_Curve; - SCurveEditorKey& m_Key; - - int m_VisualSize; - int m_ClickableSize; - - CCurveEditorTangentControl* m_pInTangent; - CCurveEditorTangentControl* m_pOutTangent; -}; - -class EDITOR_COMMON_API CCurveEditorTangentControl -{ -public: - CCurveEditorTangentControl(CCurveEditorControl& curveControl, ETangent tangentDirection); - ~CCurveEditorTangentControl(); - - CCurveEditorControl& GetControl(); - ETangent GetTangentDirection() const; - - bool IsVisible() const; - void SetVisible(bool visible); - - bool IsSelected() const; - void SetSelected(bool selected); - - void SetVisualSize(int visualSize); - void SetClickableSize(int clickableSize); - void SetDistanceFromControl(int distanceFromControl); - - void Paint(QPainter& painter, const QPalette& palette); - - bool IsMouseWithinControl(QPointF screenPos) const; - -private: - - QPointF GetScreenPosition() const; - - CCurveEditorControl& m_Control; - ETangent m_TangentDirection; - - bool m_Selected; - - int m_VisualSize; - int m_ClickableSize; - int m_DistanceFromControl; - - bool m_Visible; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.cpp b/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.cpp deleted file mode 100644 index 60a61b930f..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.cpp +++ /dev/null @@ -1,1825 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "EditorCommon_precompiled.h" -#include "CurveEditor.h" -#include "DrawingPrimitives/TimeSlider.h" -#include "DrawingPrimitives/Ruler.h" - -#include -#include -#include -#include -#include - -#pragma warning (push) -#pragma warning (disable : 4554) - -#define INDEX_NOT_OUT_OF_RANGE PREFAST_SUPPRESS_WARNING(6201) -#define NO_BUFFER_OVERRUN PREFAST_SUPPRESS_WARNING(6385 6386) -#include "Cry_LegacyPhysUtils.h" - -#pragma warning (pop) - -namespace CurveEditorHelpers -{ - const uint numColors = 4; - ColorB colors[numColors] = - { - ColorB(243, 126, 121), - ColorB(121, 152, 243), - ColorB(187, 243, 121), - ColorB(243, 121, 223), - }; - - ColorB GetCurveColor(const uint n) - { - return colors[n % numColors]; - } - - QColor Interpolate(const QColor& a, const QColor& b, float k) - { - float mk = 1.0f - k; - return QColor(a.red() * mk + b.red() * k, - a.green() * mk + b.green() * k, - a.blue() * mk + b.blue() * k, - a.alpha() * mk + b.alpha() * k); - } -} - -namespace -{ - using namespace LegacyCryPhysicsUtils; - - const int kRulerHeight = 16; - const int kRulerShadowHeight = 6; - const int kRulerMarkHeight = 8; - const float kHitDistance = 5.0f; - const float kMinZoom = 0.00001f; - const float kMaxZoom = 1000.0f; - const float kFitMargin = 30.0f; - - const QPointF kPointRectExtent = QPointF(2.5f, 2.5f); - - Vec2 TransformPointToScreen(const Vec2 zoom, const Vec2 translation, QRect curveArea, Vec2 point) - { - Vec2 transformedPoint = Vec2(point.x * zoom.x, point.y * -zoom.y) + translation; - transformedPoint.x *= curveArea.width(); - transformedPoint.y *= curveArea.height(); - return Vec2(transformedPoint.x + curveArea.left(), transformedPoint.y + curveArea.top()); - } - - Vec2 TransformPointFromScreen(const Vec2 zoom, const Vec2 translation, QRect curveArea, Vec2 point) - { - Vec2 transformedPoint = Vec2((point.x - curveArea.left()) / curveArea.width(), (point.y - curveArea.top()) / curveArea.height()) - translation; - transformedPoint.x /= zoom.x; - transformedPoint.y /= -zoom.y; - return Vec2(transformedPoint.x, transformedPoint.y); - } - - QPointF Vec2ToPoint(Vec2 point) - { - return QPointF(point.x, point.y); - } - - Vec2 PointToVec2(QPointF point) - { - return Vec2(point.x(), point.y()); - } - - // This function returns a new key with position and weights affected by eTangentType_Smooth, eTangentType_Linear and eTangentType_Step for the incoming tangent - SCurveEditorKey ApplyInTangentFlags(const SCurveEditorKey& key, const SCurveEditorKey& leftKey, const SCurveEditorKey* pRightKey) - { - SCurveEditorKey newKey = key; - - if (leftKey.m_controlPoint.m_outTangentType == SBezierControlPoint::eTangentType_Step) - { - newKey.m_controlPoint.m_inTangent = Vec2(0.0f, 0.0f); - return newKey; - } - else if (key.m_controlPoint.m_inTangentType != SBezierControlPoint::eTangentType_Step) - { - const SAnimTime leftTime = leftKey.m_time; - const SAnimTime rightTime = pRightKey ? pRightKey->m_time : key.m_time; - - // Rebase to [0, rightTime - leftTime] to increase float precision - const float floatTime = (key.m_time - leftTime).ToFloat(); - const float floatLeftTime = 0.0f; - const float floatRightTime = (rightTime - leftTime).ToFloat(); - - newKey.m_controlPoint = Bezier::CalculateInTangent(floatTime, key.m_controlPoint, - floatLeftTime, &leftKey.m_controlPoint, - floatRightTime, pRightKey ? &pRightKey->m_controlPoint : nullptr); - } - else - { - newKey.m_controlPoint.m_inTangent = Vec2(0.0f, 0.0f); - newKey.m_controlPoint.m_value = leftKey.m_controlPoint.m_value; - } - - return newKey; - } - - // This function returns a new key with position and weights affected by eTangentType_Smooth, eTangentType_Linear and eTangentType_Step for the outgoing tangent - SCurveEditorKey ApplyOutTangentFlags(const SCurveEditorKey& key, const SCurveEditorKey* pLeftKey, const SCurveEditorKey& rightKey) - { - SCurveEditorKey newKey = key; - - if (rightKey.m_controlPoint.m_inTangentType == SBezierControlPoint::eTangentType_Step - && key.m_controlPoint.m_outTangentType != SBezierControlPoint::eTangentType_Step) - { - newKey.m_controlPoint.m_outTangent = Vec2(0.0f, 0.0f); - } - else if (key.m_controlPoint.m_outTangentType != SBezierControlPoint::eTangentType_Step) - { - const SAnimTime leftTime = pLeftKey ? pLeftKey->m_time : key.m_time; - const SAnimTime rightTime = rightKey.m_time; - - // Rebase to [0, rightTime - leftTime] to increase float precision - const float floatTime = (key.m_time - leftTime).ToFloat(); - const float floatLeftTime = 0.0f; - const float floatRightTime = (rightTime - leftTime).ToFloat(); - - newKey.m_controlPoint = Bezier::CalculateOutTangent(floatTime, key.m_controlPoint, - floatLeftTime, pLeftKey ? &pLeftKey->m_controlPoint : nullptr, - floatRightTime, &rightKey.m_controlPoint); - } - else - { - newKey.m_controlPoint.m_outTangent = Vec2(0.0f, 0.0f); - newKey.m_controlPoint.m_value = rightKey.m_controlPoint.m_value; - } - - return newKey; - } - - QPainterPath CreatePathFromCurve(const SCurveEditorCurve& curve, ECurveEditorCurveType curveType, AZStd::function transformFunc) - { - QPainterPath path; - - const Vec2 startPoint(curve.m_keys[0].m_time.ToFloat(), curve.m_keys[0].m_controlPoint.m_value); - const Vec2 startTransformed = transformFunc(startPoint); - path.moveTo(startTransformed.x, startTransformed.y); - - const auto endIter = curve.m_keys.end() - 1; - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Vec2 p0 = Vec2(segmentStartKey.m_time.ToFloat(), segmentStartKey.m_controlPoint.m_value); - const Vec2 p3 = Vec2(segmentEndKey.m_time.ToFloat(), segmentEndKey.m_controlPoint.m_value); - - Vec2 p1, p2; - if (curveType == eCECT_Bezier) - { - // Need to compute tangents for x so that the cubic 2D Bezier does a linear interpolation in - // that dimension, because we actually want to draw a cubic 1D Bezier curve - const float outTangentX = (2.0f * p0.x + p3.x) / 3.0f; // p1 = (2 * p0 + p3) / 3 - const float inTangentX = (p0.x + 2.0f * p3.x) / 3.0f; // p2 = (p0 + 2 * p3) / 3 - - p1 = Vec2(outTangentX, p0.y + segmentStartKey.m_controlPoint.m_outTangent.y); - p2 = Vec2(inTangentX, p3.y + segmentEndKey.m_controlPoint.m_inTangent.y); - } - else if (curveType == eCECT_2DBezier) - { - p1 = p0 + segmentStartKey.m_controlPoint.m_outTangent; - p2 = p3 + segmentEndKey.m_controlPoint.m_inTangent; - } - - const QPointF p0Transformed = Vec2ToPoint(transformFunc(p0)); - const QPointF p1Transformed = Vec2ToPoint(transformFunc(p1)); - const QPointF p2Transformed = Vec2ToPoint(transformFunc(p2)); - const QPointF p3Transformed = Vec2ToPoint(transformFunc(p3)); - path.moveTo(p0Transformed); - path.cubicTo(p1Transformed, p2Transformed, p3Transformed); - } - - return path; - } - - QPainterPath CreateExtrapolatedPathFromCurve(const SCurveEditorCurve& curve, AZStd::function transformFunc, float windowWidth) - { - QPainterPath path; - - if (curve.m_keys.size() > 0) - { - const Vec2 startPoint = Vec2(curve.m_keys[0].m_time.ToFloat(), curve.m_keys[0].m_controlPoint.m_value); - const Vec2 startTransformed = transformFunc(startPoint); - if (startTransformed.x > 0.0f) - { - path.moveTo(std::min(startTransformed.x, windowWidth), startTransformed.y); - path.lineTo(0.0f, startTransformed.y); - } - - const Vec2 endPoint(curve.m_keys.back().m_time.ToFloat(), curve.m_keys.back().m_controlPoint.m_value); - const Vec2 endTransformed = transformFunc(endPoint); - if (endTransformed.x < windowWidth) - { - path.moveTo(std::max(endTransformed.x, 0.0f), endTransformed.y); - path.lineTo(windowWidth, endTransformed.y); - } - } - else - { - const Vec2 pointOnCurve = Vec2(0.0f, curve.m_defaultValue); - const Vec2 pointOnTransformed = transformFunc(pointOnCurve); - path.moveTo(0.0, pointOnTransformed.y); - path.lineTo(windowWidth, pointOnTransformed.y); - } - - QVector dashPattern; - dashPattern << 16 << 8; - - QPainterPathStroker stroker; - stroker.setCapStyle(Qt::RoundCap); - stroker.setDashPattern(dashPattern); - stroker.setWidth(0.5); - - return stroker.createStroke(path); - } - - QPainterPath CreateDiscontinuityPathFromCurve(const SCurveEditorCurve& curve, ECurveEditorCurveType curveType, AZStd::function transformFunc) - { - QPainterPath path; - - if (curve.m_keys.size() > 0) - { - const auto endIter = curve.m_keys.end() - 1; - - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - if (segmentStartKey.m_controlPoint.m_value != iter->m_controlPoint.m_value) - { - const Vec2 start = Vec2(segmentStartKey.m_time.ToFloat(), segmentStartKey.m_controlPoint.m_value); - const Vec2 end = Vec2(iter->m_time.ToFloat(), iter->m_controlPoint.m_value); - - const QPointF startTransformed = Vec2ToPoint(transformFunc(start)); - const QPointF endTransformed = Vec2ToPoint(transformFunc(end)); - - path.moveTo(startTransformed); - path.lineTo(endTransformed); - } - - if (segmentEndKey.m_controlPoint.m_value != (iter + 1)->m_controlPoint.m_value) - { - const Vec2 start = Vec2(segmentEndKey.m_time.ToFloat(), segmentEndKey.m_controlPoint.m_value); - const Vec2 end = Vec2((iter + 1)->m_time.ToFloat(), (iter + 1)->m_controlPoint.m_value); - - const QPointF startTransformed = Vec2ToPoint(transformFunc(start)); - const QPointF endTransformed = Vec2ToPoint(transformFunc(end)); - - path.moveTo(startTransformed); - path.lineTo(endTransformed); - } - } - } - - QVector dashPattern; - dashPattern << 2 << 10; - - QPainterPathStroker stroker; - stroker.setCapStyle(Qt::RoundCap); - stroker.setDashPattern(dashPattern); - stroker.setWidth(0.5); - - return stroker.createStroke(path); - } - - void DrawPointRect(QPainter& painter, QPointF point, const QColor& color) - { - painter.setBrush(QBrush(color)); - painter.setPen(QColor(0, 0, 0)); - painter.drawRect(QRectF(point - kPointRectExtent, point + kPointRectExtent)); - } - - void DrawKeys(QPainter& painter, const QPalette& palette, const SCurveEditorCurve& curve, ECurveEditorCurveType curveType, AZStd::function transformFunc, const bool bDrawHandles) - { - const QColor tangentColor = CurveEditorHelpers::Interpolate(QColor(), QColor(curve.m_color.r, curve.m_color.g, curve.m_color.b, curve.m_color.a), 0.3f); - const QPen tangentPen = QPen(tangentColor, 2.5); - - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - SCurveEditorKey key = *iter; - - const Vec2 keyPoint = Vec2(key.m_time.ToFloat(), key.m_controlPoint.m_value); - const QPointF transformedKeyPoint = Vec2ToPoint(transformFunc(keyPoint)); - - const bool bIsFirstKey = (iter == curve.m_keys.begin()); - const bool bIsLastKey = (iter == (curve.m_keys.end() - 1)); - const SCurveEditorKey* pLeftKey = (!bIsFirstKey) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pRightKey = (!bIsLastKey) ? &*(iter + 1) : nullptr; - key = pRightKey ? ApplyOutTangentFlags(key, pLeftKey, *pRightKey) : key; - key = pLeftKey ? ApplyInTangentFlags(key, *pLeftKey, pRightKey) : key; - - // For 1D Bezier, we need to ignore the X component - const Vec2 inTangent = (curveType == eCECT_Bezier) ? Vec2(0.0f, key.m_controlPoint.m_inTangent.y) : key.m_controlPoint.m_inTangent; - const Vec2 outTangent = (curveType == eCECT_Bezier) ? Vec2(0.0f, key.m_controlPoint.m_outTangent.y) : key.m_controlPoint.m_outTangent; - - if (key.m_bSelected && (key.m_controlPoint.m_inTangentType != SBezierControlPoint::eTangentType_Step) && !bIsFirstKey && bDrawHandles) - { - // Draw incoming tangent - const Vec2 tangentHandlePoint = keyPoint + inTangent; - const QPointF transformedTangentHandlePoint = Vec2ToPoint(transformFunc(tangentHandlePoint)); - painter.setPen(tangentPen); - painter.drawLine(transformedKeyPoint, transformedTangentHandlePoint); - DrawPointRect(painter, transformedTangentHandlePoint, palette.color(QPalette::Dark)); - } - - if (key.m_bSelected && (key.m_controlPoint.m_outTangentType != SBezierControlPoint::eTangentType_Step) && !bIsLastKey && bDrawHandles) - { - // Draw outgoing tangent - const Vec2 tangentHandlePoint = keyPoint + outTangent; - const QPointF transformedTangentHandlePoint = Vec2ToPoint(transformFunc(tangentHandlePoint)); - painter.setPen(tangentPen); - painter.drawLine(transformedKeyPoint, transformedTangentHandlePoint); - DrawPointRect(painter, transformedTangentHandlePoint, palette.color(QPalette::Dark)); - } - - const QColor pointColor = key.m_bSelected ? palette.color(QPalette::Highlight) : palette.color(QPalette::Dark); - DrawPointRect(painter, transformedKeyPoint, pointColor); - } - } - - void ForEachKey(SCurveEditorContent& content, AZStd::function fun) - { - for (auto iter = content.m_curves.begin(); iter != content.m_curves.end(); ++iter) - { - SCurveEditorCurve& curve = *iter; - for (size_t i = 0; i < curve.m_keys.size(); ++i) - { - fun(curve, curve.m_keys[i]); - } - } - } - -#pragma warning (push) -#pragma warning (disable : 4554) - - Vec2 ClosestPointOnBezierSegment(const Vec2 point, const float t0, const float t1, const float p0, const float p1, const float p2, const float p3) - { - // If values are too close the distance function is too flat to be useful. We just assume the curve is flat then - if ((p0 * p0 + p1 * p1 + p2 * p2 + p3 * p3) < 1e-10f) - { - return Vec2(point.x, p0); - } - - const float deltaTime = (t1 - t0); - const float deltaTimeSq = deltaTime * deltaTime; - - // Those are just the normal cubic Bezier formulas B(t) and B'(t) in collected polynomial form - const P3f cubicBezierPoly = P3f(-p0 + 3.0f * p1 - 3.0f * p2 + p3) + P2f(3.0f * p0 - 6.0f * p1 + 3.0f * p2) + P1f(3.0f * p1 - 3.0f * p0) + p0; - const P2f cubicBezierDerivativePoly = P2f(-3.0f * p0 + 9.0f * p1 - 6.0f * p2 + 3.0f * (p3 - p2)) + P1f(6.0f * p0 - 12.0f * p1 + 6.0f * p2) - 3.0f * p0 + 3.0f * p1; - - // lerp(t, t0, t1) in polynomial form - const P1f timePoly = P1f(deltaTime) + t0; - - // Derivative of the distance function (cubicBezierPoly - point.y) ^ 2 + (timePoly - point.x) ^ 2 - const auto distanceDerivativePoly = (cubicBezierDerivativePoly * (cubicBezierPoly - point.y) + (timePoly - point.x) * deltaTime) * 2.0f; - - // The point of minimum distance must be at one of the roots of the distance derivative or at the start/end of the segment - float checkPoints[7]; - const uint numRoots = distanceDerivativePoly.findroots(0.0f, 1.0f, checkPoints + 2); - - // Start and end of segment - checkPoints[0] = 0.0f; - checkPoints[1] = 1.0f; - - // Find the closest point among all the candidates - Vec2 closestPoint; - float minDistanceSq = std::numeric_limits::max(); - for (uint i = 0; i < numRoots + 2; ++i) - { - const Vec2 rootPoint(Lerp(t0, t1, checkPoints[i]), Bezier::Evaluate(checkPoints[i], p0, p1, p2, p3)); - const float deltaX = rootPoint.x - point.x; - const float deltaY = rootPoint.y - point.y; - const float distSq = deltaX * deltaX + deltaY * deltaY; - if (distSq < minDistanceSq) - { - closestPoint = rootPoint; - minDistanceSq = distSq; - } - } - - return closestPoint; - } - - Vec2 ClosestPointOn2DBezierSegment(const Vec2 point, const Vec2 p0, const Vec2 p1, const Vec2 p2, const Vec2 p3) - { - // If values are too close the distance function is too flat to be useful. We just assume the curve is flat then - if ((p0.y * p0.y + p1.y * p1.y + p2.y * p2.y + p3.y * p3.y) < 1e-10f) - { - return Vec2(point.x, p0.y); - } - - // Those are just the normal cubic Bezier formulas B(t) and B'(t) in collected polynomial form - const P3f xCubicBezierPoly = P3f(-p0.x + 3.0f * p1.x - 3.0f * p2.x + p3.x) + P2f(3.0f * p0.x - 6.0f * p1.x + 3.0f * p2.x) + P1f(3.0f * p1.x - 3.0f * p0.x) + p0.x; - const P2f xCubicBezierDerivativePoly = P2f(-3.0f * p0.x + 9.0f * p1.x - 6.0f * p2.x + 3.0f * (p3.x - p2.x)) + P1f(6.0f * p0.x - 12.0f * p1.x + 6.0f * p2.x) - 3.0f * p0.x + 3.0f * p1.x; - const P3f yCubicBezierPoly = P3f(-p0.y + 3.0f * p1.y - 3.0f * p2.y + p3.y) + P2f(3.0f * p0.y - 6.0f * p1.y + 3.0f * p2.y) + P1f(3.0f * p1.y - 3.0f * p0.y) + p0.y; - const P2f yCubicBezierDerivativePoly = P2f(-3.0f * p0.y + 9.0f * p1.y - 6.0f * p2.y + 3.0f * (p3.y - p2.y)) + P1f(6.0f * p0.y - 12.0f * p1.y + 6.0f * p2.y) - 3.0f * p0.y + 3.0f * p1.y; - - // Derivative of the distance function (yCubicBezierPoly - point.y) ^ 2 + (xCubicBezierPoly - point.x) ^ 2 - const auto distanceDerivativePoly = yCubicBezierDerivativePoly * (yCubicBezierPoly - point.y) + xCubicBezierDerivativePoly * (xCubicBezierPoly - point.x); - - // The point of minimum distance must be at one of the roots of the distance derivative or at the start/end of the segment - float checkPoints[7]; - const uint numRoots = distanceDerivativePoly.findroots(0.0f, 1.0f, checkPoints + 2); - - // Start and end of segment - checkPoints[0] = 0.0f; - checkPoints[1] = 1.0f; - - // Find the closest point among all the candidates - Vec2 closestPoint; - float minDistanceSq = std::numeric_limits::max(); - for (uint i = 0; i < numRoots + 2; ++i) - { - const Vec2 rootPoint(Bezier::Evaluate(checkPoints[i], p0.x, p1.x, p2.x, p3.x), Bezier::Evaluate(checkPoints[i], p0.y, p1.y, p2.y, p3.y)); - const float deltaX = rootPoint.x - point.x; - const float deltaY = rootPoint.y - point.y; - const float distSq = deltaX * deltaX + deltaY * deltaY; - if (distSq < minDistanceSq) - { - closestPoint = rootPoint; - minDistanceSq = distSq; - } - } - - return closestPoint; - } - - // This works for 1D and 2D bezier because the y range of values is not affected by the x bezier in the 2D case. - Range GetBezierSegmentValueRange(const SCurveEditorKey& startKey, const SCurveEditorKey& endKey) - { - const float p0 = startKey.m_controlPoint.m_value; - const float p1 = p0 + startKey.m_controlPoint.m_outTangent.y; - const float p3 = endKey.m_controlPoint.m_value; - const float p2 = p3 + endKey.m_controlPoint.m_inTangent.y; - - Range valueRange(std::min(p0, p3), std::max(p0, p3)); - - const P2f cubicBezierDerivativePoly = P2f(-3.0f * p0 + 9.0f * p1 - 6.0f * p2 + 3.0f * (p3 - p2)) + P1f(6.0f * p0 - 12.0f * p1 + 6.0f * p2) - 3.0f * p0 + 3.0f * p1; - - float roots[2]; - const uint numRoots = cubicBezierDerivativePoly.findroots(0.0f, 1.0f, roots); - for (uint i = 0; i < numRoots; ++i) - { - const float rootValue = Bezier::Evaluate(roots[i], p0, p1, p2, p3); - valueRange.start = std::min(valueRange.start, rootValue); - valueRange.end = std::max(valueRange.end, rootValue); - } - - return valueRange; - } -} - -#pragma warning (pop) - -struct CCurveEditor::SMouseHandler -{ - virtual ~SMouseHandler() = default; - virtual void mousePressEvent(QMouseEvent* pEvent) {} - virtual void mouseDoubleClickEvent(QMouseEvent* pEvent) {} - virtual void mouseMoveEvent(QMouseEvent* pEvent) {} - virtual void mouseReleaseEvent(QMouseEvent* pEvent) {} - virtual void focusOutEvent(QFocusEvent* pEvent) {} - virtual void paintOver(QPainter& painter) {} -}; - -struct CCurveEditor::SSelectionHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - QPoint m_startPoint; - QRect m_rect; - bool m_bAdd; - - SSelectionHandler(CCurveEditor* pCurveEditor, bool bAdd) - : m_pCurveEditor(pCurveEditor) - , m_bAdd(bAdd) {} - - void mousePressEvent(QMouseEvent* pEvent) override - { - m_startPoint = pEvent->pos(); - m_rect = QRect(m_startPoint, m_startPoint + QPoint(1, 1)); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - m_rect = QRect(m_startPoint, pEvent->pos() + QPoint(1, 1)); - } - - void mouseReleaseEvent(QMouseEvent* pEvent) override - { - m_pCurveEditor->SelectInRect(m_rect); - } - - void paintOver(QPainter& painter) override - { - painter.save(); - QColor highlightColor = m_pCurveEditor->palette().color(QPalette::Highlight); - QColor highlightColorA = QColor(highlightColor.red(), highlightColor.green(), highlightColor.blue(), 128); - painter.setPen(QPen(highlightColor)); - painter.setBrush(QBrush(highlightColorA)); - painter.drawRect(QRectF(m_rect)); - painter.restore(); - } -}; - -struct CCurveEditor::SPanHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - QPoint m_startPoint; - Vec2 m_startTranslation; - - SPanHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* pEvent) override - { - m_startPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - m_startTranslation = m_pCurveEditor->m_translation; - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - const Vec2 windowSize((float)m_pCurveEditor->size().width(), (float)m_pCurveEditor->size().height()); - - const int pixelDeltaX = pEvent->x() - m_startPoint.x(); - const int pixelDeltaY = pEvent->y() - m_startPoint.y(); - - const float deltaX = float(pixelDeltaX) / (windowSize.x); - const float deltaY = float(pixelDeltaY) / (windowSize.y); - - const Vec2 delta(deltaX, deltaY); - m_pCurveEditor->m_translation = m_startTranslation + delta; - m_pCurveEditor->update(); - } -}; - -struct CCurveEditor::SZoomHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - Vec2 m_pivot; - QPoint m_lastPoint; - - SZoomHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* pEvent) override - { - m_lastPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - - const QRect curveArea = m_pCurveEditor->GetCurveArea(); - const float pivotXNormalized = (float)(m_lastPoint.x() - curveArea.left()) / (float)curveArea.width(); - const float pivotYNormalized = (float)(m_lastPoint.y() - curveArea.top()) / (float)curveArea.height(); - m_pivot = Vec2(pivotXNormalized, pivotYNormalized); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - const Vec2 windowSize((float)m_pCurveEditor->size().width(), (float)m_pCurveEditor->size().height()); - - const int pixelDeltaX = pEvent->x() - m_lastPoint.x(); - const int pixelDeltaY = -(pEvent->y() - m_lastPoint.y()); - m_lastPoint = QPoint(int(pEvent->x()), int(pEvent->y())); - - Vec2& translation = m_pCurveEditor->m_translation; - Vec2& zoom = m_pCurveEditor->m_zoom; - - const float pivotX = (m_pivot.x - translation.x) / zoom.x; - const float pivotY = (m_pivot.y - translation.y) / zoom.y; - - zoom.x *= pow(1.2f, (float)pixelDeltaX * 0.03f); - zoom.y *= pow(1.2f, (float)pixelDeltaY * 0.03f); - - zoom.x = clamp_tpl(zoom.x, kMinZoom, kMaxZoom); - zoom.y = clamp_tpl(zoom.y, kMinZoom, kMaxZoom); - - // Adjust translation so pivot point stays at same x and y position on screen - translation.x += ((m_pivot.x - translation.x) / zoom.x - pivotX) * zoom.x; - translation.y += ((m_pivot.y - translation.y) / zoom.y - pivotY) * zoom.y; - - m_pCurveEditor->update(); - } -}; - -struct CCurveEditor::SScrubHandler - : SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - SAnimTime m_startThumbPosition; - QPoint m_startPoint; - - SScrubHandler(CCurveEditor* pCurveEditor) - : m_pCurveEditor(pCurveEditor) - { - } - - void mousePressEvent(QMouseEvent* ev) override - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - const Vec2 pointInCurveSpace = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(point)); - - m_pCurveEditor->m_time = clamp_tpl(SAnimTime(pointInCurveSpace.x), m_pCurveEditor->m_timeRange.start, m_pCurveEditor->m_timeRange.end); - m_startThumbPosition = m_pCurveEditor->m_time; - m_startPoint = point; - - m_pCurveEditor->SignalScrub(); - } - - void Apply(QMouseEvent* ev, bool continuous) - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - bool shift = ev->modifiers().testFlag(Qt::ShiftModifier); - bool control = ev->modifiers().testFlag(Qt::ControlModifier); - - const float deltaX = (float)(point.x() - m_startPoint.x()); - const float width = (float)m_pCurveEditor->size().width(); - float delta = float(deltaX) / (width * m_pCurveEditor->m_zoom.x); - - if (shift) - { - delta *= 0.01f; - } - - if (control) - { - delta *= 0.1f; - } - - m_pCurveEditor->m_time = clamp_tpl(m_startThumbPosition + SAnimTime(delta), m_pCurveEditor->m_timeRange.start, m_pCurveEditor->m_timeRange.end); - m_pCurveEditor->SignalScrub(); - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - Apply(ev, true); - } - - void mouseReleaseEvent(QMouseEvent* ev) override - { - Apply(ev, false); - } -}; - -struct CCurveEditor::SMoveHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - bool m_bCycleSelection; - Vec2 m_startPoint; - SAnimTime m_minSelectedTime; - std::vector m_keyTimes; - std::vector m_keyValues; - - SMoveHandler(CCurveEditor* pCurveEditor, bool bCycleSelection) - : m_pCurveEditor(pCurveEditor) - , m_bCycleSelection(bCycleSelection) - , m_startPoint(0.0f, 0.0f) - {} - - void mousePressEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - m_startPoint = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - StoreKeyPositions(); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - RestoreKeyPositions(); - - const QPoint currentPos = pEvent->pos(); - const Vec2 transformedPos = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - const Vec2 offset = transformedPos - m_startPoint; - - SAnimTime deltaTime = SAnimTime(offset.x); - if (m_pCurveEditor->m_bSnapKeys) - { - SAnimTime newMinKeyTime = m_minSelectedTime + deltaTime; - newMinKeyTime = newMinKeyTime.SnapToNearest(m_pCurveEditor->m_frameRate); - deltaTime = newMinKeyTime - m_minSelectedTime; - } - - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - iter->m_time += deltaTime; - iter->m_controlPoint.m_value += offset.y; - iter->m_bModified = true; - } - } - - m_pCurveEditor->SortKeys(curve); - } - } - - void focusOutEvent(QFocusEvent* pEvent) override - { - RestoreKeyPositions(); - } - - void mouseReleaseEvent(QMouseEvent* pEvent) override - { - m_pCurveEditor->ContentChanged(); - } - - void StoreKeyPositions() - { - m_minSelectedTime = SAnimTime::Max(); - - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - m_keyTimes.push_back(iter->m_time); - m_keyValues.push_back(iter->m_controlPoint.m_value); - m_minSelectedTime = min(m_minSelectedTime, iter->m_time); - } - } - } - } - - void RestoreKeyPositions() - { - SCurveEditorContent* pContent = m_pCurveEditor->m_pContent; - - auto timeIter = m_keyTimes.begin(); - auto valueIter = m_keyValues.begin(); - - for (auto curveIter = pContent->m_curves.begin(); curveIter != pContent->m_curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - if (iter->m_bSelected) - { - iter->m_time = *(timeIter++); - iter->m_controlPoint.m_value = *(valueIter++); - iter->m_bModified = false; - } - } - } - } -}; - -struct CCurveEditor::SHandleMoveHandler - : public CCurveEditor::SMouseHandler -{ - CCurveEditor* m_pCurveEditor; - SCurveEditorKey m_appliedHandlesKey; - SCurveEditorKey* m_pKey; - CCurveEditor::ETangent m_tangent; - Vec2 m_startPoint; - Vec2 m_inTangentStartPosition; - Vec2 m_outTangentStartPosition; - SBezierControlPoint::ETangentType m_inTangentStartType; - SBezierControlPoint::ETangentType m_outTangentStartType; - float m_inTangentStartLength; - float m_outTangentStartLength; - - SHandleMoveHandler(CCurveEditor* pCurveEditor, SCurveEditorKey appliedHandlesKey, SCurveEditorKey* pKey, CCurveEditor::ETangent tangent) - : m_pCurveEditor(pCurveEditor) - , m_appliedHandlesKey(appliedHandlesKey) - , m_pKey(pKey) - , m_tangent(tangent) - , m_inTangentStartPosition(ZERO) - , m_inTangentStartType(SBezierControlPoint::eTangentType_Auto) - , m_inTangentStartLength(0.0f) - , m_outTangentStartPosition(ZERO) - , m_outTangentStartType(SBezierControlPoint::eTangentType_Auto) - , m_outTangentStartLength(0.0f) - { - } - - void mousePressEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - m_startPoint = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - - m_inTangentStartPosition = m_appliedHandlesKey.m_controlPoint.m_inTangent; - m_inTangentStartType = m_appliedHandlesKey.m_controlPoint.m_inTangentType; - m_inTangentStartLength = m_inTangentStartPosition.GetLength(); - m_outTangentStartPosition = m_appliedHandlesKey.m_controlPoint.m_outTangent; - m_outTangentStartType = m_appliedHandlesKey.m_controlPoint.m_outTangentType; - m_outTangentStartLength = m_outTangentStartPosition.GetLength(); - } - - void mouseMoveEvent(QMouseEvent* pEvent) override - { - const QPoint currentPos = pEvent->pos(); - const Vec2 transformedPos = TransformPointFromScreen(m_pCurveEditor->m_zoom, m_pCurveEditor->m_translation, m_pCurveEditor->GetCurveArea(), PointToVec2(currentPos)); - - if (m_tangent == CCurveEditor::ETangent_In) - { - const Vec2 newPos = m_inTangentStartPosition + (transformedPos - m_startPoint); - - m_pKey->m_controlPoint.m_inTangent = newPos; - m_pKey->m_controlPoint.m_inTangentType = SBezierControlPoint::eTangentType_Custom; - - if (!m_pKey->m_controlPoint.m_bBreakTangents) - { - m_pKey->m_controlPoint.m_outTangent = -newPos.GetNormalizedSafe() * m_outTangentStartLength; - m_pKey->m_controlPoint.m_outTangentType = SBezierControlPoint::eTangentType_Custom; - } - } - else - { - const Vec2 newPos = m_outTangentStartPosition + (transformedPos - m_startPoint); - - m_pKey->m_controlPoint.m_outTangent = newPos; - m_pKey->m_controlPoint.m_outTangentType = SBezierControlPoint::eTangentType_Custom; - - if (!m_pKey->m_controlPoint.m_bBreakTangents) - { - m_pKey->m_controlPoint.m_inTangent = -newPos.GetNormalizedSafe() * m_inTangentStartLength; - m_pKey->m_controlPoint.m_inTangentType = SBezierControlPoint::eTangentType_Custom; - } - } - - m_pKey->m_bModified = true; - } - - void focusOutEvent(QFocusEvent* pEvent) override - { - m_pKey->m_controlPoint.m_inTangent = m_inTangentStartPosition; - m_pKey->m_controlPoint.m_inTangentType = m_inTangentStartType; - m_pKey->m_controlPoint.m_outTangent = m_outTangentStartPosition; - m_pKey->m_controlPoint.m_outTangentType = m_outTangentStartType; - m_pKey->m_bModified = false; - } - - void mouseReleaseEvent(QMouseEvent* pEvent) override - { - m_pCurveEditor->ContentChanged(); - } -}; - -CCurveEditor::CCurveEditor(QWidget* parent) - : QWidget(parent) - , m_pContent(nullptr) - , m_pMouseHandler(nullptr) - , m_curveType(eCECT_Bezier) - , m_frameRate(SAnimTime::eFrameRate_30fps) - , m_bWeighted(false) - , m_bHandlesVisible(true) - , m_bRulerVisible(true) - , m_bTimeSliderVisible(true) - , m_bGridVisible(false) - , m_bSnapTime(false) - , m_bSnapKeys(false) - , m_time(SAnimTime(0)) - , m_zoom(0.5f, 0.5f) - , m_translation(0.5f, 0.5f) - , m_timeRange(SAnimTime::Min(), SAnimTime::Max()) - , m_valueRange(-1e10f, 1e10f) -{ - setMouseTracking(true); -} - -CCurveEditor::~CCurveEditor() -{ -} - -void CCurveEditor::SetContent(SCurveEditorContent* pContent) -{ - m_pContent = pContent; - update(); -} - -void CCurveEditor::SetTime(const SAnimTime time) -{ - m_time = clamp_tpl<>(time, m_timeRange.start, m_timeRange.end); - update(); -} - -void CCurveEditor::SetTimeRange(const SAnimTime start, const SAnimTime end) -{ - if (start <= end) - { - m_timeRange = TRange(start, end); - update(); - } -} - -void CCurveEditor::SetValueRange(const float min, const float max) -{ - if (min <= max) - { - m_valueRange = Range(min, max); - update(); - } -} - -void CCurveEditor::ZoomToTimeRange(const float start, const float end) -{ - const float delta = (end - start); - - if (delta > 1e-10f) - { - m_zoom.x = 1.0f / (end - start); - m_translation.x = start / (start - end); - } - else - { - // Just center around value with zoom = 1.0f - m_zoom.x = 1.0f; - m_translation.x = 0.5f - start; - } -} - -void CCurveEditor::ZoomToValueRange(const float min, const float max) -{ - const float delta = (max - min); - - if (delta > 1e-10f) - { - m_zoom.y = 1.0f / (max - min); - m_translation.y = max / (max - min); - } - else - { - // Just center around value with zoom = 1.0f - m_zoom.y = 1.0f; - m_translation.y = 0.5f + min; - } -} - -void CCurveEditor::paintEvent(QPaintEvent* pEvent) -{ - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - painter.translate(0.5f, 0.5f); - - const QPalette& palette = this->palette(); - - auto transformFunc = [&](Vec2 point) - { - return TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), point); - }; - - const QColor rangeHighlightColor = CurveEditorHelpers::Interpolate(palette.color(QPalette::Foreground), palette.color(QPalette::Background), 0.95f); - const QRectF rangesRect(Vec2ToPoint(transformFunc(Vec2(m_timeRange.start.ToFloat(), m_valueRange.start))), Vec2ToPoint(transformFunc(Vec2(m_timeRange.end.ToFloat(), m_valueRange.end)))); - painter.setPen(QPen(Qt::NoPen)); - painter.setBrush(rangeHighlightColor); - painter.drawRect(rangesRect); - - if (m_bGridVisible) - { - DrawGrid(painter, palette); - } - - if (m_pContent) - { - const QPen extrapolatedCurvePen = QPen(palette.color(QPalette::Highlight)); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - - painter.setBrush(QBrush(Qt::NoBrush)); - const QPen curvePen = QPen(QColor(curve.m_color.r, curve.m_color.g, curve.m_color.b, curve.m_color.a), 2); - const QPen narrowCurvePen = QPen(QColor(curve.m_color.r, curve.m_color.g, curve.m_color.b, curve.m_color.a)); - - const QPainterPath extrapolatedPath = CreateExtrapolatedPathFromCurve(curve, transformFunc, width()); - painter.setPen(narrowCurvePen); - painter.drawPath(extrapolatedPath); - - const QPainterPath discontinuityPath = CreateDiscontinuityPathFromCurve(curve, m_curveType, transformFunc); - painter.setPen(narrowCurvePen); - painter.drawPath(discontinuityPath); - - if (curve.m_keys.size() > 0) - { - const QPainterPath path = CreatePathFromCurve(curve, m_curveType, transformFunc); - painter.setPen(curvePen); - painter.drawPath(path); - - DrawKeys(painter, palette, curve, m_curveType, transformFunc, m_bHandlesVisible); - } - } - } - - if (m_pMouseHandler) - { - m_pMouseHandler->paintOver(painter); - } - - DrawingPrimitives::SRulerOptions rulerOptions; - rulerOptions.m_rect = QRect(0, -1, size().width(), kRulerHeight + 2); - rulerOptions.m_visibleRange = Range(-m_translation.x / m_zoom.x, (1.0f - m_translation.x) / m_zoom.x); - rulerOptions.m_rulerRange = rulerOptions.m_visibleRange; - rulerOptions.m_markHeight = kRulerMarkHeight; - rulerOptions.m_shadowSize = kRulerShadowHeight; - - int rulerPrecision; - DrawingPrimitives::DrawRuler(painter, palette, rulerOptions, &rulerPrecision); - - if (m_pContent && isEnabled()) - { - DrawingPrimitives::STimeSliderOptions timeSliderOptions; - timeSliderOptions.m_rect = rect(); - timeSliderOptions.m_precision = rulerPrecision; - timeSliderOptions.m_position = transformFunc(Vec2(m_time.ToFloat(), 0.0f)).x; - timeSliderOptions.m_time = m_time.ToFloat(); - timeSliderOptions.m_bHasFocus = hasFocus(); - DrawingPrimitives::DrawTimeSlider(painter, palette, timeSliderOptions); - } -} - -void CCurveEditor::mousePressEvent(QMouseEvent* pEvent) -{ - setFocus(); - - if (pEvent->button() == Qt::LeftButton) - { - LeftButtonMousePressEvent(pEvent); - } - else if (pEvent->button() == Qt::MiddleButton) - { - MiddleButtonMousePressEvent(pEvent); - } - else if (pEvent->button() == Qt::RightButton) - { - RightButtonMousePressEvent(pEvent); - } -} - -void CCurveEditor::mouseDoubleClickEvent(QMouseEvent* pEvent) -{ - if (pEvent->button() == Qt::LeftButton) - { - auto curveHitPair = HitDetectCurve(pEvent->pos()); - if (curveHitPair.first) - { - AddPointToCurve(curveHitPair.second, curveHitPair.first); - setCursor(QCursor(Qt::SizeAllCursor)); - } - } -} - -void CCurveEditor::DrawGrid(QPainter& painter, const QPalette& palette) -{ - using namespace DrawingPrimitives; - - QColor gridColor = CurveEditorHelpers::Interpolate(palette.color(QPalette::Dark), palette.color(QPalette::Button), 0.5f); - gridColor.setAlpha(128); - const QColor textColor = palette.color(QPalette::BrightText); - - const Range horizontalVisibleRange = Range(-m_translation.x / m_zoom.x, (1.0f - m_translation.x) / m_zoom.x); - const Range verticalVisibleRange = Range((m_translation.y - 1.0f) / m_zoom.y, m_translation.y / m_zoom.y); - - const int height = size().height(); - const int width = size().width(); - - int verticalRulerPrecision; - - std::vector horizontalTicks = CalculateTicks(width, horizontalVisibleRange, horizontalVisibleRange, nullptr, nullptr); - std::vector verticalTicks = CalculateTicks(height, verticalVisibleRange, verticalVisibleRange, &verticalRulerPrecision, nullptr); - - char format[16] = ""; - sprintf_s(format, "%%.%df", verticalRulerPrecision); - - const QPen gridPen(gridColor, 1.0); - painter.setPen(gridPen); - - for (const STick& tick : horizontalTicks) - { - if (!tick.m_bTenth) - { - const int x = tick.m_position; - painter.drawLine(x, kRulerHeight, x, height); - } - } - - for (const STick& tick : verticalTicks) - { - if (!tick.m_bTenth) - { - const int y = height - tick.m_position; - painter.drawLine(0, y, width, y); - } - } - - const QPen textPen(textColor); - painter.setPen(textPen); - - QString str; - for (const STick& tick : verticalTicks) - { - if (!tick.m_bTenth) - { - const int y = height - tick.m_position; - str.sprintf(format, tick.m_value); - painter.drawText(5, y - 4, str); - } - } -} - -void CCurveEditor::LeftButtonMousePressEvent(QMouseEvent* pEvent) -{ - const bool bCtrlPressed = (pEvent->modifiers() & Qt::CTRL) != 0; - const bool bAltPressed = (pEvent->modifiers() & Qt::ALT) != 0; - - if (pEvent->y() < kRulerHeight) - { - m_pMouseHandler.reset(new SScrubHandler(this)); - m_pMouseHandler->mousePressEvent(pEvent); - } - else - { - if (bCtrlPressed) - { - auto curveHitPair = HitDetectCurve(pEvent->pos()); - if (curveHitPair.first) - { - AddPointToCurve(curveHitPair.second, curveHitPair.first); - setCursor(QCursor(Qt::SizeAllCursor)); - } - } - else if (bAltPressed) - { - auto curveKeyPair = HitDetectKey(pEvent->pos()); - if (curveKeyPair.first) - { - curveKeyPair.second->m_bDeleted = true; - ContentChanged(); - } - } - else - { - auto curveKeyPair = HitDetectKey(pEvent->pos()); - auto handleKeyTuple = HitDetectHandle(pEvent->pos()); - - if (std::get<0>(handleKeyTuple)) - { - m_pMouseHandler.reset(new SHandleMoveHandler(this, std::get<1>(handleKeyTuple), std::get<2>(handleKeyTuple), std::get<3>(handleKeyTuple))); - } - else if (curveKeyPair.first) - { - bool useExistingSelection = curveKeyPair.second->m_bSelected; - if (!useExistingSelection) - { - ForEachKey(*m_pContent, [](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - key.m_bSelected = false; - }); - curveKeyPair.second->m_bSelected = true; - } - - m_pMouseHandler.reset(new SMoveHandler(this, false)); - } - else - { - m_pMouseHandler.reset(new SSelectionHandler(this, false)); - } - - m_pMouseHandler->mousePressEvent(pEvent); - } - } - - update(); -} - -void CCurveEditor::MiddleButtonMousePressEvent(QMouseEvent* pEvent) -{ - const bool bShiftPressed = (pEvent->modifiers() & Qt::SHIFT) != 0; - - if (!bShiftPressed) - { - m_pMouseHandler.reset(new SPanHandler(this)); - } - else - { - m_pMouseHandler.reset(new SZoomHandler(this)); - } - - m_pMouseHandler->mousePressEvent(pEvent); - update(); -} - -void CCurveEditor::RightButtonMousePressEvent(QMouseEvent* pEvent) -{ -} - -void CCurveEditor::mouseMoveEvent(QMouseEvent* pEvent) -{ - if (m_pMouseHandler) - { - m_pMouseHandler->mouseMoveEvent(pEvent); - } - else - { - if (HitDetectKey(pEvent->pos()).first || std::get<0>(HitDetectHandle(pEvent->pos()))) - { - setCursor(QCursor(Qt::SizeAllCursor)); - } - else - { - setCursor(QCursor()); - } - } - - update(); -} - -void CCurveEditor::mouseReleaseEvent(QMouseEvent* pEvent) -{ - if (m_pMouseHandler) - { - m_pMouseHandler->mouseReleaseEvent(pEvent); - m_pMouseHandler.reset(); - update(); - } -} - -void CCurveEditor::focusOutEvent(QFocusEvent* pEvent) -{ - if (m_pMouseHandler) - { - m_pMouseHandler->focusOutEvent(pEvent); - m_pMouseHandler.reset(); - update(); - } -} - -void CCurveEditor::wheelEvent(QWheelEvent* pEvent) -{ - Vec2 windowSize((float)size().width(), (float)size().height()); - windowSize.y = (windowSize.y > 0.0f) ? windowSize.y : 1.0f; - - const QRect curveArea = GetCurveArea(); - const float mouseXNormalized = (float)(pEvent->x() - curveArea.left()) / (float)curveArea.width(); - const float mouseYNormalized = (float)(pEvent->y() - curveArea.top()) / (float)curveArea.height(); - - const float pivotX = (mouseXNormalized - m_translation.x) / m_zoom.x; - const float pivotY = (mouseYNormalized - m_translation.y) / m_zoom.y; - - m_zoom *= pow(1.2f, (float)pEvent->delta() * 0.01f); - m_zoom.x = clamp_tpl(m_zoom.x, kMinZoom, kMaxZoom); - m_zoom.y = clamp_tpl(m_zoom.y, kMinZoom, kMaxZoom); - - // Adjust translation so pivot point stays at same x and y position on screen - m_translation.x += ((mouseXNormalized - m_translation.x) / m_zoom.x - pivotX) * m_zoom.x; - m_translation.y += ((mouseYNormalized - m_translation.y) / m_zoom.y - pivotY) * m_zoom.y; - - update(); -} - -void CCurveEditor::keyPressEvent(QKeyEvent* pEvent) -{ - if (!m_pContent) - { - return; - } - - QKeySequence key(pEvent->key()); - - if (key == QKeySequence(Qt::Key_Delete)) - { - OnDeleteSelectedKeys(); - } - - update(); -} - -void CCurveEditor::SetCurveType(ECurveEditorCurveType curveType) -{ - m_curveType = curveType; - update(); -} - -void CCurveEditor::SetHandlesVisible(bool bVisible) -{ - m_bHandlesVisible = bVisible; - update(); -} - -void CCurveEditor::SetRulerVisible(bool bVisible) -{ - m_bRulerVisible = bVisible; - update(); -} - -void CCurveEditor::SetTimeSliderVisible(bool bVisible) -{ - m_bTimeSliderVisible = bVisible; - update(); -} - -void CCurveEditor::SetGridVisible(bool bVisible) -{ - m_bGridVisible = bVisible; - update(); -} - -void CCurveEditor::SelectInRect(const QRect& rect) -{ - if (!m_pContent) - { - return; - } - - ForEachKey(*m_pContent, [&](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - const Vec2 screenPoint = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), Vec2(key.m_time.ToFloat(), key.m_controlPoint.m_value)); - key.m_bSelected = rect.contains((int)screenPoint.x, (int)screenPoint.y); - }); - - update(); - SignalContentChanged(); -} - -std::pair CCurveEditor::HitDetectCurve(const QPoint point) -{ - if (!m_pContent) - { - return std::make_pair(nullptr, Vec2(ZERO)); - } - - SCurveEditorCurve* pNearestCurve = nullptr; - Vec2 closestPoint = Vec2(ZERO); - - float nearestDistance = std::numeric_limits::max(); - for (auto iter = m_pContent->m_curves.rbegin(); iter != m_pContent->m_curves.rend(); ++iter) - { - SCurveEditorCurve& curve = *iter; - const Vec2 closestPointOnCurve = ClosestPointOnCurve(PointToVec2(point), curve, m_curveType); - - const float distance = (PointToVec2(point) - closestPointOnCurve).GetLength(); - if (distance < nearestDistance) - { - nearestDistance = distance; - pNearestCurve = &curve; - closestPoint = closestPointOnCurve; - } - } - - if (nearestDistance <= kHitDistance) - { - return std::make_pair(pNearestCurve, TransformPointFromScreen(m_zoom, m_translation, GetCurveArea(), closestPoint)); - } - - return std::make_pair(nullptr, Vec2(ZERO)); -} - -std::pair CCurveEditor::HitDetectKey(const QPoint point) -{ - if (!m_pContent) - { - return std::make_pair(nullptr, nullptr); - } - - for (auto curvesIter = m_pContent->m_curves.rbegin(); curvesIter != m_pContent->m_curves.rend(); ++curvesIter) - { - SCurveEditorCurve& curve = *curvesIter; - for (auto iter = curve.m_keys.rbegin(); iter != curve.m_keys.rend(); ++iter) - { - SCurveEditorKey& key = *iter; - const Vec2 keyPoint = Vec2(key.m_time.ToFloat(), key.m_controlPoint.m_value); - const Vec2 transformedPoint = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), keyPoint); - if ((transformedPoint - PointToVec2(point)).GetLength() <= kHitDistance) - { - return std::make_pair(&curve, &key); - } - } - } - - return std::make_pair(nullptr, nullptr); -} - -std::tuple CCurveEditor::HitDetectHandle(const QPoint point) -{ - if (!m_pContent || !m_bHandlesVisible) - { - return std::make_tuple(nullptr, SCurveEditorKey(), nullptr, ETangent_In); - } - - for (auto curvesIter = m_pContent->m_curves.rbegin(); curvesIter != m_pContent->m_curves.rend(); ++curvesIter) - { - SCurveEditorCurve& curve = *curvesIter; - for (auto iter = curve.m_keys.begin(); iter != curve.m_keys.end(); ++iter) - { - SCurveEditorKey key = *iter; - - const bool bIsFirstKey = (iter == curve.m_keys.begin()); - const bool bIsLastKey = (iter == (curve.m_keys.end() - 1)); - const SCurveEditorKey* pLeftKey = (!bIsFirstKey) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pRightKey = (!bIsLastKey) ? &*(iter + 1) : nullptr; - key = pRightKey ? ApplyOutTangentFlags(key, pLeftKey, *pRightKey) : key; - key = pLeftKey ? ApplyInTangentFlags(key, *pLeftKey, pRightKey) : key; - - const Vec2 inTangent = (m_curveType == eCECT_Bezier) ? Vec2(0.0f, key.m_controlPoint.m_inTangent.y) : key.m_controlPoint.m_inTangent; - const Vec2 outTangent = (m_curveType == eCECT_Bezier) ? Vec2(0.0f, key.m_controlPoint.m_outTangent.y) : key.m_controlPoint.m_outTangent; - - const Vec2 keyPoint = Vec2(key.m_time.ToFloat(), key.m_controlPoint.m_value); - - if (!bIsFirstKey && (key.m_controlPoint.m_inTangentType != SBezierControlPoint::eTangentType_Step)) - { - const Vec2 tangentHandlePoint = keyPoint + inTangent; - const Vec2 transformedTangentHandlePoint = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), tangentHandlePoint); - if ((transformedTangentHandlePoint - PointToVec2(point)).GetLength() <= kHitDistance) - { - return std::make_tuple(&curve, key, &(*iter), ETangent_In); - } - } - - if (!bIsLastKey && (key.m_controlPoint.m_outTangentType != SBezierControlPoint::eTangentType_Step)) - { - const Vec2 tangentHandlePoint = keyPoint + outTangent; - const Vec2 transformedTangentHandlePoint = TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), tangentHandlePoint); - if ((transformedTangentHandlePoint - PointToVec2(point)).GetLength() <= kHitDistance) - { - return std::make_tuple(&curve, key, &(*iter), ETangent_Out); - } - } - } - } - - return std::make_tuple(nullptr, SCurveEditorKey(), nullptr, ETangent_In); -} - -// Input and output are in screen space -Vec2 CCurveEditor::ClosestPointOnCurve(const Vec2 point, const SCurveEditorCurve& curve, const ECurveEditorCurveType curveType) -{ - auto transformFunc = [&](Vec2 point) - { - return TransformPointToScreen(m_zoom, m_translation, GetCurveArea(), point); - }; - - if (curve.m_keys.size() == 0) - { - const Vec2 pointOnCurve = transformFunc(Vec2(0.0f, curve.m_defaultValue)); - return Vec2(point.x, pointOnCurve.y); - } - - Vec2 closestPoint; - float minDistance = std::numeric_limits::max(); - - const Vec2 startKeyTransformed = transformFunc(Vec2(curve.m_keys.front().m_time.ToFloat(), curve.m_keys.front().m_controlPoint.m_value)); - if (point.x < startKeyTransformed.x) - { - const float distanceToCurve = std::abs(point.y - startKeyTransformed.y); - if (distanceToCurve < minDistance) - { - closestPoint = Vec2(point.x, startKeyTransformed.y); - minDistance = distanceToCurve; - } - } - - const Vec2 endKeyTransformed = transformFunc(Vec2(curve.m_keys.back().m_time.ToFloat(), curve.m_keys.back().m_controlPoint.m_value)); - if (point.x > endKeyTransformed.x) - { - const float distanceToCurve = std::abs(point.y - endKeyTransformed.y); - if (distanceToCurve < minDistance) - { - closestPoint = Vec2(point.x, endKeyTransformed.y); - minDistance = distanceToCurve; - } - } - - const auto endIter = curve.m_keys.end() - 1; - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Vec2 p0 = transformFunc(Vec2(segmentStartKey.m_time.ToFloat(), segmentStartKey.m_controlPoint.m_value)); - const Vec2 p3 = transformFunc(Vec2(segmentEndKey.m_time.ToFloat(), segmentEndKey.m_controlPoint.m_value)); - const Vec2 p1 = transformFunc(Vec2(segmentStartKey.m_time.ToFloat() + segmentStartKey.m_controlPoint.m_outTangent.x, - segmentStartKey.m_controlPoint.m_value + segmentStartKey.m_controlPoint.m_outTangent.y)); - const Vec2 p2 = transformFunc(Vec2(segmentEndKey.m_time.ToFloat() + segmentEndKey.m_controlPoint.m_inTangent.x, - segmentEndKey.m_controlPoint.m_value + segmentEndKey.m_controlPoint.m_inTangent.y)); - - const Vec2 closestOnSegment = (curveType == eCECT_Bezier) ? ClosestPointOnBezierSegment(point, p0.x, p3.x, p0.y, p1.y, p2.y, p3.y) : ClosestPointOn2DBezierSegment(point, p0, p1, p2, p3); - const float distanceToSegment = (closestOnSegment - point).GetLength(); - if (distanceToSegment < minDistance) - { - closestPoint = closestOnSegment; - minDistance = distanceToSegment; - } - } - - return closestPoint; -} - -void CCurveEditor::ContentChanged() -{ - SignalContentChanged(); - - DeleteMarkedKeys(); - - ForEachKey(*m_pContent, [](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - key.m_bModified = false; - }); - - update(); -} - -void CCurveEditor::DeleteMarkedKeys() -{ - if (m_pContent) - { - for (auto iter = m_pContent->m_curves.begin(); iter != m_pContent->m_curves.end(); ++iter) - { - SCurveEditorCurve& curve = *iter; - for (auto keyIter = curve.m_keys.begin(); keyIter != curve.m_keys.end(); ) - { - if (keyIter->m_bDeleted) - { - keyIter = curve.m_keys.erase(keyIter); - } - else - { - ++keyIter; - } - } - } - } -} - -void CCurveEditor::AddPointToCurve(const Vec2 point, SCurveEditorCurve* pCurve) -{ - SCurveEditorKey key; - key.m_time = SAnimTime(point.x); - if (m_bSnapKeys) - { - key.m_time.SnapToNearest(m_frameRate); - } - key.m_controlPoint.m_value = point.y; - key.m_bAdded = true; - pCurve->m_keys.push_back(key); - - SortKeys(*pCurve); - ContentChanged(); -} - -void CCurveEditor::SortKeys(SCurveEditorCurve& curve) -{ - std::stable_sort(curve.m_keys.begin(), curve.m_keys.end(), [](const SCurveEditorKey& a, const SCurveEditorKey& b) - { - return a.m_time < b.m_time; - }); -} - -void CCurveEditor::OnDeleteSelectedKeys() -{ - ForEachKey(*m_pContent, [](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - key.m_bDeleted = key.m_bDeleted || key.m_bSelected; - }); - - ContentChanged(); -} - -void CCurveEditor::OnSetSelectedKeysTangentAuto() -{ - SetSelectedKeysTangentType(ETangent_In, SBezierControlPoint::eTangentType_Auto); - SetSelectedKeysTangentType(ETangent_Out, SBezierControlPoint::eTangentType_Auto); -} - -void CCurveEditor::OnSetSelectedKeysInTangentZero() -{ - SetSelectedKeysTangentType(ETangent_In, SBezierControlPoint::eTangentType_Zero); -} - -void CCurveEditor::OnSetSelectedKeysInTangentStep() -{ - SetSelectedKeysTangentType(ETangent_In, SBezierControlPoint::eTangentType_Step); -} - -void CCurveEditor::OnSetSelectedKeysInTangentLinear() -{ - SetSelectedKeysTangentType(ETangent_In, SBezierControlPoint::eTangentType_Linear); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentZero() -{ - SetSelectedKeysTangentType(ETangent_Out, SBezierControlPoint::eTangentType_Zero); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentStep() -{ - SetSelectedKeysTangentType(ETangent_Out, SBezierControlPoint::eTangentType_Step); -} - -void CCurveEditor::OnSetSelectedKeysOutTangentLinear() -{ - SetSelectedKeysTangentType(ETangent_Out, SBezierControlPoint::eTangentType_Linear); -} - -void CCurveEditor::OnFitCurvesHorizontally() -{ - if (m_pContent) - { - bool bAnyKeyFound = false; - SAnimTime timeMin = SAnimTime::Max(); - SAnimTime timeMax = SAnimTime::Min(); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - if (curve.m_keys.size() > 0) - { - bAnyKeyFound = true; - timeMin = std::min(curve.m_keys.front().m_time, timeMin); - timeMax = std::max(curve.m_keys.back().m_time, timeMax); - } - } - - if (!bAnyKeyFound) - { - timeMin = m_timeRange.start; - timeMax = m_timeRange.end; - } - - ZoomToTimeRange(timeMin.ToFloat(), timeMax.ToFloat()); - - // Adjust zoom and translation depending on kFitMargin - const float pivot = (0.5f - m_translation.x) / m_zoom.x; - m_zoom.x /= 1.0f + 2.0f * (kFitMargin / GetCurveArea().width()); - m_translation.x += ((0.5f - m_translation.x) / m_zoom.x - pivot) * m_zoom.x; - } - - update(); -} - -void CCurveEditor::OnFitCurvesVertically() -{ - if (m_pContent) - { - bool bAnyKeyFound = false; - float valueMin = std::numeric_limits::max(); - float valueMax = -std::numeric_limits::max(); - - TCurveEditorCurves& curves = m_pContent->m_curves; - for (auto curveIter = curves.begin(); curveIter != curves.end(); ++curveIter) - { - SCurveEditorCurve& curve = *curveIter; - - if (curve.m_keys.size() > 1) - { - const auto endIter = curve.m_keys.end() - 1; - - for (auto iter = curve.m_keys.begin(); iter != endIter; ++iter) - { - bAnyKeyFound = true; - - const SCurveEditorKey* pKeyLeftOfSegment = (iter != curve.m_keys.begin()) ? &*(iter - 1) : nullptr; - const SCurveEditorKey* pKeyRightOfSegment = (iter != (curve.m_keys.end() - 2)) ? &*(iter + 2) : nullptr; - - const SCurveEditorKey segmentStartKey = ApplyOutTangentFlags(*iter, pKeyLeftOfSegment, *(iter + 1)); - const SCurveEditorKey segmentEndKey = ApplyInTangentFlags(*(iter + 1), *iter, pKeyRightOfSegment); - - const Range valueRange = GetBezierSegmentValueRange(segmentStartKey, segmentEndKey); - valueMin = std::min(valueMin, valueRange.start); - valueMax = std::max(valueMax, valueRange.end); - } - } - else if (curve.m_keys.size() == 1) - { - bAnyKeyFound = true; - valueMin = valueMax = curve.m_keys[0].m_controlPoint.m_value; - } - } - - if (!bAnyKeyFound) - { - valueMin = -0.5f; - valueMax = 0.5f; - } - - ZoomToValueRange(valueMin, valueMax); - - // Adjust zoom and translation depending on kFitMargin - const float pivot = (0.5f - m_translation.y) / m_zoom.y; - m_zoom.y /= 1.0f + 2.0f * (kFitMargin / GetCurveArea().height()); - m_translation.y += ((0.5f - m_translation.y) / m_zoom.y - pivot) * m_zoom.y; - } - - update(); -} - -void CCurveEditor::OnBreakTangents() -{ - if (m_pContent) - { - ForEachKey(*m_pContent, [&](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - if (key.m_bSelected) - { - key.m_controlPoint.m_bBreakTangents = true; - } - }); - } - - SignalContentChanged(); -} - -void CCurveEditor::OnUnifyTangents() -{ - if (m_pContent) - { - ForEachKey(*m_pContent, [&](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - if (key.m_bSelected) - { - key.m_controlPoint.m_bBreakTangents = false; - } - }); - } - - SignalContentChanged(); -} - -void CCurveEditor::SetSelectedKeysTangentType(const ETangent tangent, const SBezierControlPoint::ETangentType type) -{ - if (m_pContent) - { - ForEachKey(*m_pContent, [&](SCurveEditorCurve& curve, SCurveEditorKey& key) - { - if (key.m_bSelected) - { - if (tangent == ETangent_In) - { - key.m_controlPoint.m_inTangentType = type; - } - else - { - key.m_controlPoint.m_outTangentType = type; - } - } - }); - - update(); - } - - SignalContentChanged(); -} - -QRect CCurveEditor::GetCurveArea() -{ - const uint rulerAreaHeight = m_bRulerVisible ? kRulerHeight : 0; - return QRect(0, rulerAreaHeight, width(), height() - rulerAreaHeight); -} - -void CCurveEditor::FillWithCurveToolsAndConnect(QToolBar* pToolBar) -{ - pToolBar->addAction(QIcon(":/Icons/CurveEditor/auto.png"), "Set in and out tangents to auto", this, SLOT(OnSetSelectedKeysTangentAuto())); - pToolBar->addSeparator(); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/zero_in.png"), "Set in tangent to zero", this, SLOT(OnSetSelectedKeysInTangentZero())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/step_in.png"), "Set in tangent to step", this, SLOT(OnSetSelectedKeysInTangentStep())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/linear_in.png"), "Set in tangent to linear", this, SLOT(OnSetSelectedKeysInTangentLinear())); - pToolBar->addSeparator(); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/zero_out.png"), "Set out tangent to zero", this, SLOT(OnSetSelectedKeysOutTangentZero())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/step_out.png"), "Set out tangent to step", this, SLOT(OnSetSelectedKeysOutTangentStep())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/linear_out.png"), "Set out tangent to linear", this, SLOT(OnSetSelectedKeysOutTangentLinear())); - pToolBar->addSeparator(); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/fit_horizontal.png"), "Fit curves horizontally", this, SLOT(OnFitCurvesHorizontally())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/fit_vertical.png"), "Fit curves vertically", this, SLOT(OnFitCurvesVertically())); - pToolBar->addSeparator(); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/break.png"), "Break tangents", this, SLOT(OnBreakTangents())); - pToolBar->addAction(QIcon(":/Icons/CurveEditor/unify.png"), "Unify tangents", this, SLOT(OnUnifyTangents())); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.h b/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.h deleted file mode 100644 index f0c5da608b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/CurveEditor_38.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -#include "CurveEditorContent.h" -#include -#include -#include - -class QToolBar; - -enum ECurveEditorCurveType -{ - eCECT_Bezier, - // 2D Bezier curves are used for better curve control, the editor - // will enforce that the resulting curve is always 1D. - eCECT_2DBezier, -}; - -namespace CurveEditorHelpers -{ - // Picks a nice color value for a curve. Wraps around after 4. - EDITOR_COMMON_API ColorB GetCurveColor(const uint n); -} - -class EDITOR_COMMON_API CCurveEditor - : public QWidget -{ - Q_OBJECT -public: - CCurveEditor(QWidget* parent); - ~CCurveEditor(); - - void SetContent(SCurveEditorContent* pContent); - SCurveEditorContent* Content() const { return m_pContent; } - - SAnimTime Time() const { return m_time; } - void SetTime(const SAnimTime time); - - // The background in the time and value range will be drawn a bit brighter to indicate where keys - // should be placed. The curve editor does not enforce that the curves actually stay in those ranges. - void SetTimeRange(const SAnimTime start, const SAnimTime end); - void SetValueRange(const float min, const float max); - - void ZoomToTimeRange(const float start, const float end); - void ZoomToValueRange(const float min, const float max); - - void SetCurveType(ECurveEditorCurveType curveType); - void SetWeighted(bool bWeighted); - void SetHandlesVisible(bool bVisible); - void SetRulerVisible(bool bVisible); - void SetTimeSliderVisible(bool bVisible); - void SetGridVisible(bool bVisible); - void SetFrameRate(SAnimTime::EFrameRate frameRate) { m_frameRate = frameRate; } - void SetTimeSnapping(bool snapTime) { m_bSnapTime = snapTime; } - void SetKeySnapping(bool snapKeys) { m_bSnapKeys = snapKeys; } - - // Tools added to tool bar depend on options above - void FillWithCurveToolsAndConnect(QToolBar* pToolBar); - - void paintEvent(QPaintEvent* pEvent) override; - void mousePressEvent(QMouseEvent* pEvent) override; - void mouseDoubleClickEvent(QMouseEvent* pEvent) override; - void mouseMoveEvent(QMouseEvent* pEvent) override; - void mouseReleaseEvent(QMouseEvent* pEvent) override; - void focusOutEvent(QFocusEvent* pEvent) override; - void wheelEvent(QWheelEvent* pEvent) override; - void keyPressEvent(QKeyEvent* pEvent) override; - -signals: - void SignalContentChanged(); - void SignalScrub(); - -public slots: - void OnDeleteSelectedKeys(); - void OnSetSelectedKeysTangentAuto(); - void OnSetSelectedKeysInTangentZero(); - void OnSetSelectedKeysInTangentStep(); - void OnSetSelectedKeysInTangentLinear(); - void OnSetSelectedKeysOutTangentZero(); - void OnSetSelectedKeysOutTangentStep(); - void OnSetSelectedKeysOutTangentLinear(); - void OnFitCurvesHorizontally(); - void OnFitCurvesVertically(); - void OnBreakTangents(); - void OnUnifyTangents(); - -private: - struct SMouseHandler; - struct SSelectionHandler; - struct SPanHandler; - struct SZoomHandler; - struct SMoveHandler; - struct SHandleMoveHandler; - struct SScrubHandler; - enum ETangent; - - void DrawGrid(QPainter& painter, const QPalette& palette); - - void LeftButtonMousePressEvent(QMouseEvent* pEvent); - void MiddleButtonMousePressEvent(QMouseEvent* pEvent); - void RightButtonMousePressEvent(QMouseEvent* pEvent); - - void SelectInRect(const QRect& rect); - - void ContentChanged(); - void DeleteMarkedKeys(); - - std::pair HitDetectCurve(const QPoint point); - std::pair HitDetectKey(const QPoint point); - std::tuple HitDetectHandle(const QPoint point); - Vec2 ClosestPointOnCurve(const Vec2 point, const SCurveEditorCurve& curve, const ECurveEditorCurveType curveType); - - void AddPointToCurve(Vec2 point, SCurveEditorCurve* pCurve); - void SortKeys(SCurveEditorCurve& curve); - - QRect GetCurveArea(); - - enum ETangent - { - ETangent_In, - ETangent_Out - }; - - void SetSelectedKeysTangentType(const ETangent tangent, const SBezierControlPoint::ETangentType type); - - SCurveEditorContent* m_pContent; - std::unique_ptr m_pMouseHandler; - - ECurveEditorCurveType m_curveType; - SAnimTime::EFrameRate m_frameRate; - bool m_bWeighted : 1; - bool m_bHandlesVisible : 1; - bool m_bRulerVisible : 1; - bool m_bTimeSliderVisible : 1; - bool m_bGridVisible : 1; - bool m_bSnapTime : 1; - bool m_bSnapKeys : 1; - - SAnimTime m_time; - Vec2 m_zoom; - Vec2 m_translation; - TRange m_timeRange; - Range m_valueRange; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.cpp b/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.cpp deleted file mode 100644 index 3d6a33fd6a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.cpp +++ /dev/null @@ -1,194 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "EditorCommon_precompiled.h" -//Cry -#include - -//Editor -#include -#include - -//Local -#include "QViewport.h" -#include "DisplayViewportAdapter.h" - -CDisplayViewportAdapter::CDisplayViewportAdapter(QViewport* viewport) - : m_viewport(viewport) -{ - m_screenMatrix.SetIdentity(); -} - -void CDisplayViewportAdapter::Update() -{ -} - -const Matrix34& CDisplayViewportAdapter::GetScreenTM() const -{ - return m_screenMatrix; -} - -float CDisplayViewportAdapter::GetScreenScaleFactor(const Vec3& position) const -{ - float dist = m_viewport->Camera()->GetPosition().GetDistance(position); - if (dist < m_viewport->Camera()->GetNearPlane()) - { - dist = m_viewport->Camera()->GetNearPlane(); - } - return dist; -} - -float CDisplayViewportAdapter::GetScreenScaleFactor([[maybe_unused]] const CCamera& camera, [[maybe_unused]] const Vec3& object_position) -{ - return 1; -} - -bool CDisplayViewportAdapter::HitTestLine(const Vec3& lineP1, const Vec3& lineP2, const QPoint& hitpoint, int pixelRadius, float* pToCameraDistance) const -{ - float dist = GetDistanceToLine(lineP1, lineP2, hitpoint); - if (dist <= pixelRadius) - { - if (pToCameraDistance) - { - Vec3 raySrc, rayDir; - ViewToWorldRay(hitpoint, raySrc, rayDir); - Vec3 rayTrg = raySrc + rayDir * 10000.0f; - - Vec3 pa, pb; - float mua, mub; - LineLineIntersect(lineP1, lineP2, raySrc, rayTrg, pa, pb, mua, mub); - *pToCameraDistance = mub; - } - - return true; - } - - return false; -} - -float CDisplayViewportAdapter::GetDistanceToLine(const Vec3& lineP1, const Vec3& lineP2, const QPoint& point) const -{ - QPoint p1 = WorldToView(lineP1); - QPoint p2 = WorldToView(lineP2); - - return PointToLineDistance2D( - Vec3(float(p1.x()), float(p1.y()), 0), - Vec3(float(p2.x()), float(p2.y()), 0), - Vec3(float(point.x()), float(point.y()), 0)); -} - -CBaseObjectsCache* CDisplayViewportAdapter::GetVisibleObjectsCache() -{ - return 0; -} - -bool CDisplayViewportAdapter::IsBoundsVisible([[maybe_unused]] const AABB& box) const -{ - return false; -} - -void CDisplayViewportAdapter::GetPerpendicularAxis(EAxis* axis, bool* is2D) const -{ - *axis = AXIS_NONE; - *is2D = false; -} - -const Matrix34& CDisplayViewportAdapter::GetViewTM() const -{ - m_viewMatrix = m_viewport->Camera()->GetViewMatrix(); - return m_viewMatrix; -} - -QPoint CDisplayViewportAdapter::WorldToView(const Vec3& worldPoint) const -{ - return m_viewport->ProjectToScreen(worldPoint); -} - -QPoint CDisplayViewportAdapter::WorldToViewParticleEditor(const Vec3& worldPoint, [[maybe_unused]] int width, [[maybe_unused]] int height) const -{ - return m_viewport->ProjectToScreen(worldPoint); -} - -Vec3 CDisplayViewportAdapter::WorldToView3D([[maybe_unused]] const Vec3& worldPoint, [[maybe_unused]] int flags) const -{ - return Vec3(0.0f, 0.0f, 0.0f); -} - -Vec3 CDisplayViewportAdapter::ViewToWorld([[maybe_unused]] const QPoint& vp, [[maybe_unused]] bool* collideWithTerrain, [[maybe_unused]] bool onlyTerrain, [[maybe_unused]] bool bSkipVegetation, [[maybe_unused]] bool bTestRenderMesh, [[maybe_unused]] bool* collideWithObject) const -{ - return Vec3(0.0f, 0.0f, 0.0f); -} - -void CDisplayViewportAdapter::ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const -{ - Ray ray; - // this can fail for number of reasons - if (!m_viewport->ScreenToWorldRay(&ray, vp.x(), vp.y())) - { - // return some "safe" default that will not cause FPE - raySrc = m_viewport->Camera()->GetPosition(); - rayDir = m_viewport->Camera()->GetViewdir(); - - // the interface should be changed to accommodate for error - return; - } - raySrc = ray.origin; - rayDir = ray.direction; -} - -float CDisplayViewportAdapter::GetGridStep() const -{ - return 1.0f; -} - -float CDisplayViewportAdapter::GetAspectRatio() const -{ - int w, h; - GetDimensions(&w, &h); - if (h != 0) - { - return float(w) / h; - } - else - { - return 1.0f; - } -} - -const Plane* CDisplayViewportAdapter::GetConstructionPlane() const -{ - return 0; -} - -void CDisplayViewportAdapter::ScreenToClient([[maybe_unused]] QPoint& pt) const -{ -} - -void CDisplayViewportAdapter::GetDimensions(int* width, int* height) const -{ - if (width) - { - *width = m_viewport->Width(); - } - if (height) - { - *height = m_viewport->Height(); - } -} - -void CDisplayViewportAdapter::setRay([[maybe_unused]] QPoint& vp, [[maybe_unused]] Vec3& raySrc, [[maybe_unused]] Vec3& rayDir) -{ -} - -void CDisplayViewportAdapter::setHitcontext([[maybe_unused]] QPoint& vp, [[maybe_unused]] Vec3& raySrc, [[maybe_unused]] Vec3& rayDir) -{ -} diff --git a/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.h b/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.h deleted file mode 100644 index 9b1d8bc27b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/DisplayViewportAdapter.h +++ /dev/null @@ -1,64 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - -//Cry -#include -#include "Cry_Matrix34.h" -#include "Cry_Vector3.h" - -//Editor -#include "Include/IDisplayViewport.h" - -//Local -#include "EditorCommonAPI.h" - -class EDITOR_COMMON_API QViewport; - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -class EDITOR_COMMON_API CDisplayViewportAdapter - : public ::IDisplayViewport -{ -public: -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING - CDisplayViewportAdapter(QViewport* viewport); - - void Update() override; - const Matrix34& GetScreenTM() const override; - float GetScreenScaleFactor(const Vec3& position) const override; - float GetScreenScaleFactor(const CCamera& camera, const Vec3& object_position) override; - bool HitTestLine(const Vec3& lineP1, const Vec3& lineP2, const QPoint& hitpoint, int pixelRadius, float* pToCameraDistance = 0) const override; - float GetDistanceToLine(const Vec3& lineP1, const Vec3& lineP2, const QPoint& point) const override; - CBaseObjectsCache* GetVisibleObjectsCache() override; - bool IsBoundsVisible(const AABB& box) const override; - void GetPerpendicularAxis(EAxis* axis, bool* is2D) const override; - const Matrix34& GetViewTM() const override; - QPoint WorldToView(const Vec3& worldPoint) const override; - QPoint WorldToViewParticleEditor(const Vec3& worldPoint, int width, int height) const override; - Vec3 WorldToView3D(const Vec3& worldPoint, int flags = 0) const override; - Vec3 ViewToWorld(const QPoint& vp, bool* collideWithTerrain = nullptr, bool onlyTerrain = false, bool bSkipVegetation = false, bool bTestRenderMesh = false, bool* collideWithObject = nullptr) const override; - void ViewToWorldRay(const QPoint& vp, Vec3& raySrc, Vec3& rayDir) const override; - float GetGridStep() const override; - float GetAspectRatio() const override; - const Plane* GetConstructionPlane() const override; - void ScreenToClient(QPoint& pt) const override; - void GetDimensions(int* width, int* height) const override; - void setRay(QPoint& vp, Vec3& raySrc, Vec3& rayDir) override; - void setHitcontext(QPoint& vp, Vec3& raySrc, Vec3& rayDir) override; - -private: - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - mutable Matrix34 m_viewMatrix; - Matrix34 m_screenMatrix; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - QViewport* m_viewport; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/DockTitleBarWidget.cpp b/Code/Sandbox/Plugins/EditorCommon/DockTitleBarWidget.cpp index e7de4904d1..06b3c29104 100644 --- a/Code/Sandbox/Plugins/EditorCommon/DockTitleBarWidget.cpp +++ b/Code/Sandbox/Plugins/EditorCommon/DockTitleBarWidget.cpp @@ -16,13 +16,16 @@ #include #include -static QColor Interpolate(const QColor& a, const QColor& b, float k) +namespace DockTitleBarInterpolate { - float mk = 1.0f - k; - return QColor(aznumeric_cast(a.red() * mk + b.red() * k), - aznumeric_cast(a.green() * mk + b.green() * k), - aznumeric_cast(a.blue() * mk + b.blue() * k), - aznumeric_cast(a.alpha() * mk + b.alpha() * k)); + static QColor Interpolate(const QColor& a, const QColor& b, float k) + { + float mk = 1.0f - k; + return QColor(aznumeric_cast(a.red() * mk + b.red() * k), + aznumeric_cast(a.green() * mk + b.green() * k), + aznumeric_cast(a.blue() * mk + b.blue() * k), + aznumeric_cast(a.alpha() * mk + b.alpha() * k)); + } } class CDockWidgetTitleButton @@ -60,7 +63,7 @@ public: p.setRenderHint(QPainter::Antialiasing, true); QRect r = rect().adjusted(2, 2, -3, -3); p.translate(0.5f, 0.5f); - QColor color = Interpolate(palette().color(QPalette::Window), palette().color(QPalette::Shadow), 0.2f); + QColor color = DockTitleBarInterpolate::Interpolate(palette().color(QPalette::Window), palette().color(QPalette::Shadow), 0.2f); p.setBrush(QBrush(color)); p.setPen(Qt::NoPen); p.drawRoundedRect(r, 4, 4, Qt::AbsoluteSize); diff --git a/Code/Sandbox/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp b/Code/Sandbox/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp index 18439e3aa4..6a070b364b 100644 --- a/Code/Sandbox/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp +++ b/Code/Sandbox/Plugins/EditorCommon/DrawingPrimitives/Ruler.cpp @@ -101,7 +101,7 @@ namespace DrawingPrimitives void DrawTicks(const std::vector& ticks, QPainter& painter, const QPalette& palette, const STickOptions& options) { - QColor midDark = Interpolate(palette.color(QPalette::Dark), palette.color(QPalette::Button), 0.5f); + QColor midDark = DrawingPrimitives::Interpolate(palette.color(QPalette::Dark), palette.color(QPalette::Button), 0.5f); painter.setPen(QPen(midDark)); const int height = options.m_rect.height(); @@ -149,13 +149,13 @@ namespace DrawingPrimitives painter.fillRect(shadowRect, upperBrush); } - painter.fillRect(options.m_rect, Interpolate(palette.color(QPalette::Button), palette.color(QPalette::Midlight), 0.25f)); + painter.fillRect(options.m_rect, DrawingPrimitives::Interpolate(palette.color(QPalette::Button), palette.color(QPalette::Midlight), 0.25f)); if (options.m_drawBackgroundCallback) { options.m_drawBackgroundCallback(); } - QColor midDark = Interpolate(palette.color(QPalette::Dark), palette.color(QPalette::Button), 0.5f); + QColor midDark = DrawingPrimitives::Interpolate(palette.color(QPalette::Dark), palette.color(QPalette::Button), 0.5f); painter.setPen(QPen(midDark)); QFont font; diff --git a/Code/Sandbox/Plugins/EditorCommon/EditorCommon.qrc b/Code/Sandbox/Plugins/EditorCommon/EditorCommon.qrc deleted file mode 100644 index c9dc7c4283..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/EditorCommon.qrc +++ /dev/null @@ -1,15 +0,0 @@ - - - Icons/CurveEditor/auto.png - Icons/CurveEditor/fit_horizontal.png - Icons/CurveEditor/fit_vertical.png - Icons/CurveEditor/linear_in.png - Icons/CurveEditor/linear_out.png - Icons/CurveEditor/step_in.png - Icons/CurveEditor/step_out.png - Icons/CurveEditor/zero_in.png - Icons/CurveEditor/zero_out.png - Icons/CurveEditor/break.png - Icons/CurveEditor/unify.png - - diff --git a/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.cpp b/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.cpp deleted file mode 100644 index 793cd119f0..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.cpp +++ /dev/null @@ -1,144 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "EventManager.h" -#include "Serialization/JSONIArchive.h" -#include "Serialization/JSONOArchive.h" - -CEventManager* CEventManager::ms_pEventManager; - -CEventManager::CEventManager() - : m_nextAddress(0) - , m_nextHandlerId(0) -{ - if (ms_pEventManager) - { - CryFatalError("There should be only one event manager instance"); - } - - ms_pEventManager = this; -} - -void CEventManager::Init([[maybe_unused]] SSystemGlobalEnvironment* env) -{ -} - -CEventManager* CEventManager::GetInstance() -{ - return ms_pEventManager; -} - -uint CEventManager::GetAddressId(const char* name) -{ - auto findIter = m_nameToAddressMap.find(name); - if (findIter != m_nameToAddressMap.end()) - { - return findIter->second; - } - - uint newId = m_nextAddress++; - m_nameToAddressMap[name] = newId; - return newId; -} - -uint CEventManager::GetUniqueAddressId() -{ - return m_nextAddress++; -} - -void CEventManager::SendEventRaw(const uint address, const char* eventName, const char* message) const -{ - SendEventImplementation(address, eventName, message, DynArray()); -} - -void CEventManager::SendEventRaw(const uint address, const char* eventName, const char* message, const DynArray& excludedHandlers) const -{ - SendEventImplementation(address, eventName, message, excludedHandlers); -} - -void CEventManager::SendEventImplementation(const uint address, const string& eventName, const string& message, const DynArray& excludedHandlers) const -{ - auto handlerFindIter = m_messageRoutingMap.find(std::make_pair(address, eventName)); - if (handlerFindIter != m_messageRoutingMap.end()) - { - const std::vector >& handlers = handlerFindIter->second; - - for (uint i = 0; i < handlers.size(); ++i) - { - if (!stl::find(excludedHandlers, handlers[i].first)) - { - handlers[i].second(message); - } - } - } -} - -bool CEventManager::CanDeliverRaw(const uint address, const char* eventName) const -{ - auto handlerFindIter = m_messageRoutingMap.find(std::make_pair(address, eventName)); - if (handlerFindIter != m_messageRoutingMap.end()) - { - const std::vector >& handlers = handlerFindIter->second; - return !handlers.empty(); - } - - return false; -} - -CEventConnection CEventManager::AddEventCallbackRaw(const uint address, const char* eventName, TEventHandlerFunc callback) -{ - const uint handlerId = m_nextHandlerId++; - m_messageRoutingMap[std::make_pair(address, eventName)].push_back(std::make_pair(handlerId, callback)); - return CEventConnection(address, eventName, handlerId); -} - -string CEventManager::SerializeMessageToJSON(const Serialization::SStruct& ref) const -{ - Serialization::JSONOArchive oArchive; - oArchive(ref); - return oArchive.buffer(); -} - -void CEventManager::DeserializeFromJSON(const Serialization::SStruct& ref, const string& json) -{ - Serialization::JSONIArchive iArchive; - if (iArchive.open(json.data(), json.size())) - { - iArchive(ref); - } -} - -void CEventConnection::Disconnect() -{ - if (m_bConnected) - { - auto& messageMap = CEventManager::GetInstance()->m_messageRoutingMap; - auto findIter = messageMap.find(std::make_pair(m_address, m_eventName)); - - if (findIter != messageMap.end()) - { - stl::find_and_erase_if(findIter->second, [=](const std::pair& h) - { - return h.first == m_handlerId; - }); - } - - if (findIter->second.empty()) - { - messageMap.erase(findIter); - } - - Reset(); - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.h b/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.h deleted file mode 100644 index ad35d4e0e8..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Events/EventManager.h +++ /dev/null @@ -1,204 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_EVENTS_EVENTMANAGER_H -#define CRYINCLUDE_EDITORCOMMON_EVENTS_EVENTMANAGER_H -#pragma once - - -#include "platform.h" - -#include "EditorCommonAPI.h" -#include "IEditor.h" - -#include "Serialization/IArchive.h" - -struct SSystemGlobalEnvironment; - -class CEventConnection -{ - friend class CEventManager; - friend class CScopedEventConnection; - -public: - CEventConnection() - : m_bConnected(false) {} - - EDITOR_COMMON_API void Disconnect(); - - uint GetHandlerId() const { return m_handlerId; } - -private: - CEventConnection(const uint address, const string& eventName, const uint handlerId) - : m_address(address) - , m_eventName(eventName) - , m_handlerId(handlerId) - , m_bConnected(true) {} - - void Reset() - { - m_bConnected = false; - m_address = 0; - m_handlerId = 0; - m_eventName.clear(); - } - - void Move(CEventConnection& other) - { - m_bConnected = other.m_bConnected; - m_address = other.m_address; - m_handlerId = other.m_handlerId; - m_eventName.swap(other.m_eventName); - other.Reset(); - } - - bool m_bConnected; - uint m_address; - uint m_handlerId; - string m_eventName; -}; - -class CScopedEventConnection - : public CEventConnection -{ -public: - CScopedEventConnection() - : CEventConnection() {} - - CScopedEventConnection(CScopedEventConnection&& connection) - { - Move(connection); - } - - CScopedEventConnection(CEventConnection&& connection) - { - Move(connection); - } - - CScopedEventConnection& operator =(CEventConnection&& connection) - { - if (&connection != this) - { - Disconnect(); - Move(connection); - } - return *this; - } - - ~CScopedEventConnection() { Disconnect(); } - -private: - CScopedEventConnection(const CScopedEventConnection&); // no implementation - CScopedEventConnection& operator =(const CScopedEventConnection&); // no implementation -}; - -class EDITOR_COMMON_API CEventManager -{ - friend class CEventConnection; - -public: - CEventManager(); - - static CEventManager* GetInstance(); - - void Init(SSystemGlobalEnvironment* pEnv); - - // Registers an address and returns its ID. Multiple event handlers can listen to the same address, allowing broadcasts. - uint GetAddressId(const char* name); - - // Registers a new unique address - uint GetUniqueAddressId(); - -public: - - // Sends an event to an address - // - // TMessageType must be a serializable struct - // - template - void SendEvent(const uint address, const TMessageType& message) - { - const string json = SerializeMessageToJSON(Serialization::SStruct(message)); - SendEventRaw(address, TMessageType::GetName(), json); - } - - template - void SendEvent(const uint address, const TMessageType& message, const DynArray& excludedHandlers) const - { - const string json = SerializeMessageToJSON(Serialization::SStruct(message)); - SendEventRaw(address, TMessageType::GetName(), json, excludedHandlers); - } - - // For sending a raw JSON message. - void SendEventRaw(const uint address, const char* eventName, const char* message) const; - void SendEventRaw(const uint address, const char* eventName, const char* message, const DynArray& excludedHandlers) const; - - // Tests if a call to SendEvent would actually send a message (there is someone listening to this message) - bool CanDeliverRaw(const uint address, const char* eventName) const; - template - bool CanDeliver(const uint address) const - { - const char* pEventName = TMessageType::GetName(); - return CanDeliverRaw(address, pEventName); - } - - // This should be the most common way to add an event callback - // - // This example will install an event handler for OnEvent(const SMessageType &message) that is sent to a specific address: - // CEventManager::GetInstance()->AddEventCallback(componentId, this, &CEventHandler::OnEvent); - // - // TMessageType must be a serializable struct - // - // Returns a CEventConnection. The callback is removed when this object is destroyed. - // - template - CEventConnection AddEventCallback(const uint address, TClassType* pThis, void (TClassType::* pMethod)(const TMessageType&)) - { - return AddEventCallback(address, std::bind(pMethod, pThis, std::placeholders::_1)); - } - - // Same as above, but you can pass in any function object that takes TMessageType& as an argument directly. - // - template - CEventConnection AddEventCallback(const uint address, std::function callback) - { - return AddEventCallbackRaw(address, TMessageType::GetName(), [=](const string& json) - { - TMessageType message; - DeserializeFromJSON(Serialization::SStruct(message), json); - callback(message); - }); - } - - // This can be used if raw parsing of JSON is preferred. - typedef std::function TEventHandlerFunc; - CEventConnection AddEventCallbackRaw(const uint componentId, const char* eventName, TEventHandlerFunc callback); - -private: - void SendEventImplementation(const uint address, const string& eventName, const string& message, const DynArray& excludedHandlers) const; - - string SerializeMessageToJSON(const Serialization::SStruct& ref) const; - void DeserializeFromJSON(const Serialization::SStruct& ref, const string& json); - - uint m_nextAddress; - uint m_nextHandlerId; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::map > m_nameToAddressMap; - std::map, std::vector > > m_messageRoutingMap; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - static CEventManager* ms_pEventManager; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_EVENTS_EVENTMANAGER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.cpp b/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.cpp deleted file mode 100644 index 13c0bf5d50..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.cpp +++ /dev/null @@ -1,224 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/Pointers.h" -#include "Serialization/IArchive.h" -#include "ListSelectionDialog.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "IResourceSelectorHost.h" - -#include "DeepFilterProxyModel.h" - -// --------------------------------------------------------------------------- - -ListSelectionDialog::ListSelectionDialog(QWidget* parent) - : QDialog(parent) - , m_currentColumn(0) -{ - setWindowTitle("Choose..."); - setWindowModality(Qt::ApplicationModal); - - QBoxLayout* layout = new QBoxLayout(QBoxLayout::TopToBottom); - setLayout(layout); - - QBoxLayout* filterBox = new QBoxLayout(QBoxLayout::LeftToRight); - layout->addLayout(filterBox); - { - filterBox->addWidget(new QLabel("Filter:", this), 0); - filterBox->addWidget(m_filterEdit = new QLineEdit(this), 1); - connect(m_filterEdit, SIGNAL(textChanged(const QString&)), this, SLOT(onFilterChanged(const QString&))); - m_filterEdit->installEventFilter(this); - } - - QBoxLayout* infoBox = new QBoxLayout(QBoxLayout::LeftToRight); - layout->addLayout(infoBox); - - m_model = new QStandardItemModel(); - m_model->setColumnCount(1); - m_model->setHeaderData(0, Qt::Horizontal, "Name", Qt::DisplayRole); - - m_filterModel = new DeepFilterProxyModel(this); - m_filterModel->setSourceModel(m_model); - m_filterModel->setDynamicSortFilter(true); - - m_tree = new QTreeView(this); - //m_tree->setColumnCount(3); - m_tree->setModel(m_filterModel); - - m_tree->header()->setStretchLastSection(false); -#if QT_VERSION >= 0x50000 - m_tree->header()->setSectionResizeMode(0, QHeaderView::Stretch); -#else - m_tree->header()->setResizeMode(0, QHeaderView::Stretch); -#endif - //m_tree->header()->resizeSection(0, 80); - connect(m_tree, SIGNAL(activated(const QModelIndex&)), this, SLOT(onActivated(const QModelIndex&))); - - layout->addWidget(m_tree, 1); - - QDialogButtonBox* buttons = new QDialogButtonBox(this); - buttons->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttons, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttons, SIGNAL(rejected()), this, SLOT(reject())); - layout->addWidget(buttons, 0); -} - -bool ListSelectionDialog::eventFilter(QObject* obj, QEvent* event) -{ - if (obj == m_filterEdit && event->type() == QEvent::KeyPress) - { - QKeyEvent* keyEvent = (QKeyEvent*)event; - if (keyEvent->key() == Qt::Key_Down || - keyEvent->key() == Qt::Key_Up || - keyEvent->key() == Qt::Key_PageDown || - keyEvent->key() == Qt::Key_PageUp) - { - QCoreApplication::sendEvent(m_tree, event); - return true; - } - } - return QDialog::eventFilter(obj, event); -} - -void ListSelectionDialog::onFilterChanged(const QString& str) -{ - m_filterModel->setFilterString(str); - m_filterModel->invalidate(); - m_tree->expandAll(); - - QModelIndex currentSource = m_filterModel->mapToSource(m_tree->selectionModel()->currentIndex()); - if (!currentSource.isValid() || !m_filterModel->matchFilter(currentSource.row(), currentSource.parent())) - { - QModelIndex firstMatchingIndex = m_filterModel->findFirstMatchingIndex(QModelIndex()); - if (firstMatchingIndex.isValid()) - { - m_tree->selectionModel()->setCurrentIndex(firstMatchingIndex, QItemSelectionModel::SelectCurrent); - } - } -} - -void ListSelectionDialog::onActivated(const QModelIndex& index) -{ - m_tree->setCurrentIndex(index); - accept(); -} - -QSize ListSelectionDialog::sizeHint() const -{ - return QSize(600, 900); -} - -void ListSelectionDialog::SetColumnText(int column, const char* text) -{ - if (column >= m_model->columnCount()) - { - int oldColumnCount = m_model->columnCount(); - m_model->setColumnCount(column + 1); - for (int i = oldColumnCount; i <= column; ++i) - { -#if QT_VERSION >= 0x50000 - m_tree->header()->setSectionResizeMode(i, QHeaderView::Interactive); - #else - m_tree->header()->setResizeMode(i, QHeaderView::Interactive); - #endif - m_tree->header()->resizeSection(i, 40); - } - } - m_model->setHeaderData(column, Qt::Horizontal, text, Qt::DisplayRole); -} - -void ListSelectionDialog::SetColumnWidth(int column, int width) -{ - if (column >= m_model->columnCount()) - { - return; - } - m_tree->header()->resizeSection(column, width); -} - - -void ListSelectionDialog::AddRow(const char* name) -{ - AddRow(name, QIcon()); -} - -void ListSelectionDialog::AddRow(const char* name, const QIcon& icon) -{ - QStandardItem* item = new QStandardItem(name); - item->setEditable(false); - item->setData(name); - item->setIcon(icon); - - QList items; - items.append(item); - - m_model->appendRow(items); - m_currentColumn = 1; - m_firstColumnToItem[name] = item; -} - -void ListSelectionDialog::AddRowColumn(const char* text) -{ - int itemCount = m_model->rowCount(QModelIndex()); - if (itemCount == 0) - { - return; - } - - QStandardItem* item = new QStandardItem(); - item->setText(QString::fromLocal8Bit(text)); - if (QStandardItem* lastItem = m_model->item(itemCount - 1, 0)) - { - item->setData(lastItem->data()); - } - item->setEditable(false); - m_model->setItem(itemCount - 1, m_currentColumn, item); - ++m_currentColumn; -} - -QString ListSelectionDialog::ChooseItem(const QString& currentValue) -{ - m_tree->expandAll(); - - if (exec() == QDialog::Accepted && m_tree->selectionModel()->currentIndex().isValid()) - { - QModelIndex currentIndex = m_tree->selectionModel()->currentIndex(); - QModelIndex sourceCurrentIndex = m_filterModel->mapToSource(currentIndex); - QStandardItem* item = m_model->itemFromIndex(sourceCurrentIndex); - if (item) - { - m_chosenItem = item->data().toString().toUtf8(); - return m_chosenItem.constData(); - } - } - return currentValue; -} - -// --------------------------------------------------------------------------- - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.h b/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.h deleted file mode 100644 index 5a21d92b5d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/ListSelectionDialog.h +++ /dev/null @@ -1,73 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_LISTSELECTIONDIALOG_H -#define CRYINCLUDE_EDITORCOMMON_LISTSELECTIONDIALOG_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "EditorCommonAPI.h" -#include -#include -#endif - -class DeepFilterProxyModel; -class QLineEdit; -class QModelIndex; -class QStandardItemModel; -class QStandardItem; -class QString; -class QTreeView; -class QWidget; -class QByteArray; - -class EDITOR_COMMON_API ListSelectionDialog - : public QDialog -{ - Q_OBJECT - -public: - ListSelectionDialog(QWidget* parent); - void SetColumnText(int column, const char* text); - void SetColumnWidth(int column, int width); - - void AddRow(const char* firstColumnValue); - void AddRow(const char* firstColumnValue, const QIcon& icon); - void AddRowColumn(const char* value); - - QString ChooseItem(const QString& currentValue); - - QSize sizeHint() const override; - -protected slots: - void onActivated(const QModelIndex& index); - void onFilterChanged(const QString&); - -protected: - bool eventFilter(QObject* obj, QEvent* event); - -private: - QTreeView* m_tree; - QStandardItemModel* m_model; - DeepFilterProxyModel* m_filterModel; - typedef QMap StringToItem; - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - StringToItem m_firstColumnToItem; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - QLineEdit* m_filterEdit; - QByteArray m_chosenItem; - int m_currentColumn; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_LISTSELECTIONDIALOG_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp b/Code/Sandbox/Plugins/EditorCommon/Platform/Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp deleted file mode 100644 index 89ab3276f9..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp +++ /dev/null @@ -1,29 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#include - -#include -#include - -string fromWideChar(const wchar_t* wstr) -{ - return QString::fromWCharArray(wstr).toUtf8().data(); -} - -wstring toWideChar(const char* str) -{ - QString s = QString::fromUtf8(str); - - std::vector result(s.size()+1); - s.toWCharArray(&result[0]); - return &result[0]; -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake b/Code/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake deleted file mode 100644 index 5bfcbe55a6..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Linux/platform_linux_files.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ../Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp -) diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake b/Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake deleted file mode 100644 index 5bfcbe55a6..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Mac/platform_mac_files.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - ../Common/UnixLike/QPropertyTree/Unicode_UnixLike.cpp -) diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/QPropertyTree/Unicode_Windows.cpp b/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/QPropertyTree/Unicode_Windows.cpp deleted file mode 100644 index a8bd6b92ed..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/QPropertyTree/Unicode_Windows.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#include - -#include - -string fromWideChar(const wchar_t* wstr) -{ - // We have different implementation for windows as Qt for windows - // is built with wchar_t of diferent size (4 bytes, as on linux). - // Therefore we avoid calling any wchar_t functions in Qt. - const unsigned int codepage = CP_UTF8; - int len = WideCharToMultiByte(codepage, 0, wstr, -1, NULL, 0, 0, 0); - char* buf = (char*)alloca(len); - if (len > 1) { - WideCharToMultiByte(codepage, 0, wstr, -1, buf, len, 0, 0); - return string(buf, len - 1); - } - return string(); -} - -wstring toWideChar(const char* str) -{ - const unsigned int codepage = CP_UTF8; - int len = MultiByteToWideChar(codepage, 0, str, -1, NULL, 0); - wchar_t* buf = (wchar_t*)alloca(len * sizeof(wchar_t)); - if (len > 1) { - MultiByteToWideChar(codepage, 0, str, -1, buf, len); - return wstring(buf, len - 1); - } - return wstring(); -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake b/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake deleted file mode 100644 index 4c6a5b0644..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Platform/Windows/platform_windows_files.cmake +++ /dev/null @@ -1,14 +0,0 @@ -# -# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -# its licensors. -# -# For complete copyright and license terms please see the LICENSE at the root of this -# distribution (the "License"). All use of this software is governed by the License, -# or, if provided, by the license below or the license accompanying this file. Do not -# remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# - -set(FILES - QPropertyTree/Unicode_Windows.cpp -) diff --git a/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.cpp b/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.cpp deleted file mode 100644 index d7ccd1d8e5..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include - - -QAbstractQVariantTreeDataModel::Item* QAbstractQVariantTreeDataModel::itemFromIndex(const QModelIndex& index) const -{ - if (index.isValid()) - { - return (Item*)index.internalPointer(); - } - return m_root.get(); -} - -QModelIndex QAbstractQVariantTreeDataModel::indexFromItem(QAbstractQVariantTreeDataModel::Item* item, int col /*= 0*/) const -{ - if (0 == item) - { - return QModelIndex(); - } - if (!item->m_parent || !item->m_parent->asFolder()) - { - return QModelIndex(); - } - int row = item->m_parent->asFolder()->row(item); - return createIndex(row, col, item); -} - -QModelIndex QAbstractQVariantTreeDataModel::index(int row, int column, const QModelIndex& parent /*= QModelIndex()*/) const -{ - Item* parentItem = itemFromIndex(parent); - if (parentItem && parentItem->asFolder() && row < parentItem->asFolder()->m_children.size()) - { - Item* item = parentItem->asFolder()->m_children[row].get(); - return createIndex(row, column, item); - } - return QModelIndex(); -} - -QModelIndex QAbstractQVariantTreeDataModel::parent(const QModelIndex& child) const -{ - Item* item = itemFromIndex(child); - return item && item->m_parent && item->m_parent->asFolder() ? indexFromItem(item->m_parent) : QModelIndex(); -} - -bool QAbstractQVariantTreeDataModel::hasChildren(const QModelIndex& parent /* = QModelIndex() */) const -{ - Item* item = itemFromIndex(parent); - return item && item->asFolder() && item->asFolder()->m_children.size(); -} - -int QAbstractQVariantTreeDataModel::rowCount(const QModelIndex& parent /*= QModelIndex()*/) const -{ - Item* item = itemFromIndex(parent); - int res = 0; - if (item && item->asFolder()) - { - res = (int) item->asFolder()->m_children.size(); - } - return res; -} - -int QAbstractQVariantTreeDataModel::columnCount([[maybe_unused]] const QModelIndex& parent /*= QModelIndex()*/) const -{ - return 1; -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.h b/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.h deleted file mode 100644 index bdc8979c27..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QAbstractQVariantTreeDataModel.h +++ /dev/null @@ -1,87 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef QABSTRACTQVARIANTTREEDATAMODEL_H -#define QABSTRACTQVARIANTTREEDATAMODEL_H - -#include -#include -#include - -#include "EditorCommonAPI.h" - - -class EDITOR_COMMON_API QAbstractQVariantTreeDataModel - : public QAbstractItemModel -{ -public: - QAbstractQVariantTreeDataModel(QObject* parent) - : QAbstractItemModel(parent) { } - - QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override; - QModelIndex parent(const QModelIndex& child) const override; - bool hasChildren(const QModelIndex& parent = QModelIndex()) const override; - - int rowCount(const QModelIndex& parent = QModelIndex()) const override; - int columnCount(const QModelIndex& parent = QModelIndex()) const override; - -protected: - struct Folder; - - struct Item - { - Item() - : m_parent(0) { } - - QMap m_data; - Folder* m_parent; - - virtual ~Item() = default; - virtual const Folder* asFolder() const { return 0; } // need this as we don't have RTTI - }; - - struct Folder - : public Item - { - Folder(const QString& name) - { - m_data.insert(Qt::DisplayRole, name); - } - std::vector < std::shared_ptr > m_children; - const Folder* asFolder() const override { return this; } // need this as we don't have RTTI - - int row(Item* item) const - { - for (int i = 0; i < m_children.size(); ++i) - { - if (m_children[i].get() == item) - { - return i; - } - } - return -1; - } - void addChild(std::shared_ptr item) - { - item->m_parent = this; - m_children.push_back(item); - } - }; - - Item* itemFromIndex(const QModelIndex& index) const; - QModelIndex indexFromItem(Item* item, int col = 0) const; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::shared_ptr m_root; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; - -#endif // QABSTRACTQVARIANTTREEDATAMODEL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.cpp b/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.cpp deleted file mode 100644 index f0bbf572df..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "QParentWndWidget.h" -#include -#include -#include -#include - -#include "QParentWndWidget.h" - -#include - -#if QT_VERSION >= 0x050000 -#include -#endif -static HWND FindTopmostWindow(HWND child, bool considerWsChild) -{ - if (child == GetDesktopWindow()) - { - return 0; - } - HWND current = child; - while (GetParent(current) != 0) - { - if (considerWsChild && (GetWindowLongW(current, GWL_STYLE) & WS_CHILD) == 0) - { - break; - } - current = GetParent(current); - } - - return current; -} - -QParentWndWidget::QParentWndWidget(HWND parent) - : m_parent(parent) - , m_previousFocus(0) - , m_modalityRoot(0) - , m_parentToCenterOn(0) -{ - if (m_parent) - { - SetWindowLongA((HWND)winId(), GWL_STYLE, WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_TABSTOP); - -#if QT_VERSION >= 0x50000 - QWindow* window = windowHandle(); - window->setProperty("_q_embedded_native_parent_handle", (WId)m_parent); - SetParent((HWND)winId(), m_parent); - window->setFlags(Qt::FramelessWindowHint); -#else - SetParent((HWND)winId(), m_parent); -#endif - QEvent e(QEvent::EmbeddingControl); - QApplication::sendEvent(this, &e); - } - - m_parentToCenterOn = FindTopmostWindow(m_parent, true); - m_modalityRoot = FindTopmostWindow(m_parent, false); -} - -void QParentWndWidget::childEvent(QChildEvent* ev) -{ - QObject* child = ev->child(); - if (child->isWidgetType()) - { - if (ev->added()) - { - if (child->isWidgetType()) - { - child->installEventFilter(this); - } - } - else if (ev->removed() && m_parentWasDisabled) - { - m_parentWasDisabled = false; - EnableWindow(m_modalityRoot, true); - child->removeEventFilter(this); - } - } - QWidget::childEvent(ev); -} - -void QParentWndWidget::show() -{ - if (!m_previousFocus) - { - m_previousFocus = ::GetFocus(); - } - if (!m_previousFocus) - { - m_previousFocus = parentWindow(); - } - - QWidget::show(); -} -void QParentWndWidget::hide() -{ - QWidget::hide(); -} - -void QParentWndWidget::center() -{ - const QWidget* child = findChild(); - - RECT rect; - GetWindowRect(m_parentToCenterOn, &rect); - setGeometry((rect.right - rect.left) / 2 + rect.left, - (rect.bottom - rect.top) / 2 + rect.top, 0, 0); -} - -#if QT_VERSION >= 0x50000 -bool QParentWndWidget::nativeEvent(const QByteArray&, void* message, long* result) -#else -bool QParentWndWidget::winEvent(MSG* msg, long* result) -#endif -{ -#if QT_VERSION >= 0x50000 - MSG* msg = (MSG*)message; -#endif - if (msg->message == WM_SETFOCUS) - { - Qt::FocusReason reason; - if (::GetKeyState(VK_LBUTTON) < 0 || - ::GetKeyState(VK_RBUTTON) < 0) - { - reason = Qt::MouseFocusReason; - } - else if (::GetKeyState(VK_SHIFT) < 0) - { - reason = Qt::BacktabFocusReason; - } - else - { - reason = Qt::TabFocusReason; - } - QFocusEvent ev(QEvent::FocusIn, reason); - QApplication::sendEvent(this, &ev); - } - if (msg->message == WM_GETDLGCODE) - { - *result = DLGC_WANTARROWS | DLGC_WANTTAB; - return(true); - } - - return false; -} - -bool QParentWndWidget::eventFilter(QObject* obj, QEvent* ev) -{ - QWidget* widget = (QWidget*)obj; - switch (ev->type()) - { - case QEvent::WindowDeactivate: - { - if (widget->isModal() && isHidden()) - { - BringWindowToTop(m_parent); - } - break; - } - case QEvent::Show: - { - if (widget->isWindow()) - { - if (!m_previousFocus) - { - m_previousFocus = ::GetFocus(); - } - if (!m_previousFocus) - { - m_previousFocus = parentWindow(); - } - hide(); - if (widget->isModal() && !m_parentWasDisabled) - { - EnableWindow(m_modalityRoot, false); - m_parentWasDisabled = true; - } - } - break; - } - case QEvent::Hide: - { - if (m_parentWasDisabled) - { - EnableWindow(m_modalityRoot, true); - m_parentWasDisabled = false; - } - if (m_previousFocus) - { - ::SetFocus(m_previousFocus); - } - else - { - ::SetFocus(parentWindow()); - } - if (widget->testAttribute(Qt::WA_DeleteOnClose) && widget->isWindow()) - { - deleteLater(); - } - break; - } - case QEvent::Close: - { - ::SetActiveWindow(m_parent); - if (widget->testAttribute(Qt::WA_DeleteOnClose)) - { - deleteLater(); - } - break; - } - default: - break; - } - ; - - return QWidget::eventFilter(obj, ev); -} - -void QParentWndWidget::focusInEvent(QFocusEvent* ev) -{ - QWidget* candidate = this; - - if (ev->reason() == Qt::TabFocusReason || ev->reason() == Qt::BacktabFocusReason) - { - while (candidate && (candidate->focusPolicy() & Qt::TabFocus) == 0) - { - candidate = candidate->nextInFocusChain(); - if (candidate == this) - { - candidate = 0; - } - } - if (candidate) - { - candidate->setFocus(ev->reason()); - candidate->setAttribute(Qt::WA_KeyboardFocusChange); - candidate->window()->setAttribute(Qt::WA_KeyboardFocusChange); - if (ev->reason() == Qt::BacktabFocusReason) - { - QWidget::focusNextPrevChild(false); - } - } - } -} - -bool QParentWndWidget::focusNextPrevChild(bool next) -{ - QWidget* current = focusWidget(); - if (next) - { - QWidget* nextFocus = current; - while (true) - { - nextFocus = nextFocus->nextInFocusChain(); - if (nextFocus->isWindow()) - { - break; - } - if (nextFocus->focusPolicy() & Qt::TabFocus) - { - return QWidget::focusNextPrevChild(true); - } - } - } - else - { - if (!current->isWindow()) - { - QWidget* nextFocus = current->nextInFocusChain(); - QWidget* prevFocus = 0; - QWidget* topLevel = 0; - while (nextFocus != current) - { - if ((nextFocus->focusPolicy() & Qt::TabFocus) != 0) - { - prevFocus = nextFocus; - topLevel = 0; - } - else if (nextFocus->isWindow()) - { - topLevel = nextFocus; - } - nextFocus = nextFocus->nextInFocusChain(); - } - - if (!topLevel) - { - return QWidget::focusNextPrevChild(false); - } - } - } - - ::SetFocus(m_parent); - return true; -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.h b/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.h deleted file mode 100644 index a608261b9b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QParentWndWidget.h +++ /dev/null @@ -1,67 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_QPARENTWNDWIDGET_H -#define CRYINCLUDE_EDITORCOMMON_QPARENTWNDWIDGET_H - -#if !defined(Q_MOC_RUN) -#include - -#include "EditorCommonAPI.h" -#endif - -// QParentWndWidget can be used to show Qt popup windows/dialogs on top on -// Win32/MFC windows. -// -// Example of usage: -// QParentWndWidget parent(parentHwnd); -// -// QDialog dialog(parent); -// dialog.exec(...); -class EDITOR_COMMON_API QParentWndWidget - : public QWidget -{ - Q_OBJECT -public: - QParentWndWidget(HWND parent); - - void show(); - void hide(); - void center(); - - HWND parentWindow() const { return m_parent; } - -protected: - void childEvent(QChildEvent* e) override; - void focusInEvent(QFocusEvent* ev) override; - bool focusNextPrevChild(bool next) override; - - bool eventFilter(QObject* o, QEvent* e) override; -#if QT_VERSION >= 0x50000 - bool nativeEvent(const QByteArray&, void* message, long*); -#else - bool winEvent(MSG* msg, long*); -#endif - -private: - HWND m_parent; - HWND m_parentToCenterOn; - HWND m_modalityRoot; - - HWND m_previousFocus; - - bool m_parentWasDisabled; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPARENTWNDWIDGET_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyCtrl.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyCtrl.h deleted file mode 100644 index 5cea9535a1..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyCtrl.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#pragma once - - -#include "EditorCommonAPI.h" -#include "Controls/PropertyCtrl.h" -#include - -template -class TemplatePropertyCtrl - : public QWinHost -{ -public: - TemplatePropertyCtrl(QWidget* parent) - : QWinHost(parent) { } - - T m_props; -protected: - virtual HWND createWindow(HWND parent, HINSTANCE instance) - { - CWnd* parentWindow = CWnd::FromHandle(parent); - m_props.Create(WS_CHILD | WS_VISIBLE, CRect(0, 0, 100, 100), parentWindow /*, IDC_GRAPH_PROPERTIES*/); - m_props.ModifyStyleEx(0, WS_EX_CLIENTEDGE); - m_props.SetParent(parentWindow); - return m_props.m_hWnd; - } -}; - -class QPropertyCtrl - : public TemplatePropertyCtrl -{ -public: - QPropertyCtrl(QWidget* parent) - : TemplatePropertyCtrl(parent) - { - } -}; - - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.cpp deleted file mode 100644 index f8ce31ae66..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.cpp +++ /dev/null @@ -1,123 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "Color.h" -#include "Serialization/IArchive.h" -#include -#include "MathUtils.h" - - -// HSV -// h=0..360, s=0..1, v=0..1 -inline void HSVtoRGB(float h,float s,float v, - float& r,float& g,float& b) -{ - const float min=1e-5f; - int i; - float f,m,n,k; - - if(s=360.0f) - h=0; - else - h=h/60.0f; - - i=xround(floor(h)); - f=h-i; - m=v*(1-s); - n=v*(1-s*f); - k=v*(1-s*(1-f)); - - switch(i){ - case 0: - r=v; g=k; b=m; - break; - case 1: - r=n; g=v; b=m; - break; - case 2: - r=m; g=v; b=k; - break; - case 3: - r=m; g=n; b=v; - break; - case 4: - r=k; g=m; b=v; - break; - case 5: - r=v; g=m; b=n; - break; - default: - YASLI_ASSERT(0); - } - } - - YASLI_ASSERT(r>=0 && r<=1); - YASLI_ASSERT(g>=0 && g<=1); - YASLI_ASSERT(b>=0 && b<=1); -} - -void Color::setHSV(float h,float s,float v, unsigned char alpha) -{ - float rf,gf,bf; - HSVtoRGB(h,s,v, rf,gf,bf); - r = xround(rf*255); - g = xround(gf*255); - b = xround(bf*255); - a = alpha; -} - - -void Color::toHSV(float& h,float& s,float& v) -{ - float rf = r/255.f; - float gf = g/255.f; - float bf = b/255.f; - v = max(max(rf,gf),bf); - float temp=min(min(rf,gf),bf); - if(v==0) - s=0; - else - s=(v-temp)/v; - - if(s==0) - h=0; - else { - float Cr=(v-rf)/(v-temp); - float Cg=(v-gf)/(v-temp); - float Cb=(v-bf)/(v-temp); - - if(rf==v) { - h=Cb-Cg; - } - else if(gf==v) { - h=2+Cr-Cb; - } - else if(bf==v) { - h=4+Cg-Cr; - } - - h=60*h; - if(h<0)h+=360; - } -} - -void Color::Serialize(Serialization::IArchive& ar) -{ - ar(r, "", "^R"); - ar(g, "", "^G"); - ar(b, "", "^B"); - ar(a, "", "^A"); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.h deleted file mode 100644 index 57c12d53dc..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Color.h +++ /dev/null @@ -1,66 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_COLOR_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_COLOR_H -#pragma once - - -namespace Serialization { - class IArchive; -} - -struct Color -{ - unsigned char b, g, r, a; - - Color() : r(255), g(255), b(255), a(255) { } - Color(unsigned char _r, unsigned char _g, unsigned char _b, unsigned char _a = 255) { r=_r; g=_g; b=_b; a=_a; } - explicit Color(unsigned long _argb) { argb() = _argb; } - void set(int rc,int gc,int bc,int ac = 255) { r=rc; g=gc; b=bc; a=ac; } - - Color& setGDI(unsigned long color) { - b = (unsigned char)(color >> 16); - g = (unsigned char)(color >> 8); - r = (unsigned char)(color); - a = 255; - return *this; - } - - void setHSV(float h,float s,float v, unsigned char alpha = 255); - void toHSV(float& h,float& s, float& v); - - Color& operator*= (float f) { r=int(r*f); g=int(g*f); b=int(b*f); a=int(a*f); return *this; } - Color& operator+= (Color &p) { r+=p.r; g+=p.g; b+=p.b; a+=p.a; return *this; } - Color& operator-= (Color &p) { r-=p.r; g-=p.g; b-=p.b; a-=p.a; return *this; } - Color operator+ (Color &p) { return Color(r+p.r,g+p.g,b+p.b,a+p.a); } - Color operator- (Color &p) { return Color(r-p.r,g-p.g,b-p.b,a-p.a); } - Color operator* (float f) const { return Color(int(r*f), int(g*f), int(b*f), int(a*f)); } - Color operator* (int f) const { return Color(r*f,g*f,b*f,a*f); } - Color operator/ (int f) const { if(f!=0) f=(1<<16)/f; else f=1<<16; return Color((r*f)>>16,(g*f)>>16,(b*f)>>16,(a*f)>>16); } - - bool operator==(const Color& rhs) const { return argb() == rhs.argb(); } - bool operator!=(const Color& rhs) const { return argb() != rhs.argb(); } - - unsigned long argb() const { return *reinterpret_cast(this); } - unsigned long& argb() { return *reinterpret_cast(this); } - unsigned long rgb() const { return r | g << 8 | b << 16; } - unsigned long rgba() const { return r | g << 8 | b << 16 | a << 24; } - unsigned char& operator[](int i) { return ((unsigned char*)this)[i];} - Color interpolate(const Color &v, float f) const - { - return Color(int(r+int(v.r-r)*f), - int(g+int(v.g-g)*f), - int(b+int(v.b-b)*f), - int(a+(v.a-a)*f)); - } - void Serialize(Serialization::IArchive& ar); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_COLOR_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.cpp deleted file mode 100644 index 15900bcbe4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "ConstStringList.h" -#include -#include "Serialization/STL.h" -#include "Serialization/IArchive.h" -#include "Serialization/STLImpl.h" - -ConstStringList globalConstStringList; - -const char* ConstStringList::findOrAdd(const char* string) -{ - // TODO: try sorted vector of const char* - Strings::iterator it = std::find(strings_.begin(), strings_.end(), string); - if (it == strings_.end()) { - strings_.push_back(string); - return strings_.back().c_str(); - } - else { - return it->c_str(); - } -} - - -ConstStringWrapper::ConstStringWrapper(ConstStringList* list, const char*& string) - : list_(list ? list : &globalConstStringList) - , string_(string) -{ - YASLI_ASSERT(string_); -} - -using Serialization::string; - -bool Serialize(Serialization::IArchive& ar, ConstStringWrapper& val, const char* name, const char* label) -{ - if (ar.IsOutput()) { - YASLI_ASSERT(val.string_); - string out = val.string_; - return ar(out, name, label); - } - else { - string in; - bool result = ar(in, name, label); - - val.string_ = val.list_->findOrAdd(in.c_str()); - return result; - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.h deleted file mode 100644 index 709c85d6b4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ConstStringList.h +++ /dev/null @@ -1,46 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - // Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONSTSTRINGLIST_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONSTSTRINGLIST_H -#pragma once - - -#include -#include -#include "EditorCommonAPI.h" - -class ConstStringWrapper; - -namespace Serialization { class IArchive; } - -bool Serialize(Serialization::IArchive& ar, ConstStringWrapper &wrapper, const char* name, const char* label); - -class ConstStringList{ -public: - const char* findOrAdd(const char* string); -protected: - typedef std::list Strings; - Strings strings_; -}; - -class ConstStringWrapper { -public: - ConstStringWrapper(ConstStringList* list, const char*& string); -protected: - ConstStringList* list_; - const char*& string_; - friend bool ::Serialize(Serialization::IArchive& ar, ConstStringWrapper &wrapper, const char* name, const char* label); -}; - -extern ConstStringList globalConstStringList; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONSTSTRINGLIST_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ContextList.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ContextList.h deleted file mode 100644 index 47d8558a0b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ContextList.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONTEXTLIST_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONTEXTLIST_H -#pragma once - -#include - -namespace Serialization -{ - class CContextList - { - public: - template - void Update(T* contextObject) - { - for (size_t i = 0; i < links_.size(); ++i) - { - if (links_[i]->type == TypeID::get()) - { - links_[i]->contextObject = (void*)contextObject; - return; - } - } - - SContextLink* newLink = new SContextLink; - newLink->type = TypeID::get(); - newLink->outer = links_.empty() ? connectedList_ : links_.back(); - newLink->contextObject = (void*)contextObject; - tail_.outer = newLink; - links_.push_back(newLink); - } - - CContextList() - { - tail_.outer = 0; - tail_.contextObject = 0; - connectedList_ = 0; - } - - explicit CContextList(SContextLink* connectedList) - { - tail_.outer = 0; - tail_.contextObject = 0; - connectedList_ = connectedList; - } - - ~CContextList() - { - for (size_t i = 0; i < links_.size(); ++i) - { - delete links_[i]; - } - links_.clear(); - } - - SContextLink* Tail() { return &tail_; } - private: - SContextLink tail_; - std::vector links_; - SContextLink* connectedList_; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_CONTEXTLIST_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Factory.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Factory.h deleted file mode 100644 index 83f8ef3ad3..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Factory.h +++ /dev/null @@ -1,156 +0,0 @@ -/** - * yasli - Serialization Library. - * Copyright (C) 2007-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_FACTORY_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_FACTORY_H -#pragma once - -#include -#include -#include "Serialization/Assert.h" - -template> -class Factory { -public: - typedef AZStd::map<_Key, AZStd::function<_Product *()>, _KeyPred, AZ::StdLegacyAllocator> Creators; - typedef _Product* (*ProductConstructionFunction)(void); - - Factory() {} - - struct Creator - { - Creator() - { - if (s_creatorsHead) - { - m_next = s_creatorsHead; - } - s_creatorsHead = this; - } - - Creator(Factory& factory, _Key key, ProductConstructionFunction construction_function_) - : Creator() - { - // capture key and construction_function_ by value so the lazy load won't try to access possibly deleted data - Register = [&, key, construction_function_]() - { - factory.add(key, construction_function_); - }; - } - - Creator(_Key key, ProductConstructionFunction construction_function_) - : Creator() - { - // capture key and construction_function_ by value so the lazy load won't try to access possibly deleted data - Register = [&, key, construction_function_]() - { - Factory::the().add(key, construction_function_); - }; - } - - AZStd::function Register; - Creator* m_next = nullptr; - }; - - void add(const _Key& key, AZStd::function<_Product *()> creator) { - YASLI_ASSERT(creators_.find(key) == creators_.end()); - YASLI_ASSERT(creator); - creators_[key] = creator; - } - - void remove(const _Key& key) { - auto& entry = creators_.find(key); - if (entry != creators_.end()) { - creators_.erase(entry); - } - } - - _Product* create(const _Key& key) const - { - lazyRegisterCreators(); - typename Creators::const_iterator it = creators_.find(key); - if (it != creators_.end()) { - return it->second(); - } - else - return 0; - } - - std::size_t size() const - { - lazyRegisterCreators(); - return creators_.size(); - } - - _Product* createByIndex(int index) const - { - lazyRegisterCreators(); - YASLI_ASSERT(index >= 0 && index < creators_.size()); - typename Creators::const_iterator it = creators_.begin(); - std::advance(it, index); - return it->second(); - } - - - const Creators& creators() const - { - lazyRegisterCreators(); - return creators_; - } - - static Factory& the() - { - static Factory* genericFactory = nullptr; - static AZStd::aligned_storage_for_t s_storage; - if (!genericFactory) - { - genericFactory = new(&s_storage) Factory(); - } - return *genericFactory; - } - -private: - void lazyRegisterCreators() const - { - if (s_creatorsHead) - { - Creator* creator = s_creatorsHead; - while (creator) - { - creator->Register(); - creator = creator->m_next; - } - s_creatorsHead = nullptr; - } - } - -protected: - Creators creators_; - - static Creator* s_creatorsHead; -}; - -template -typename Factory<_Key, _Product, _KeyPred>::Creator* Factory<_Key, _Product, _KeyPred>::s_creatorsHead = nullptr; - -#define REGISTER_IN_FACTORY(factory, key, product, construction_function) \ - static factory::Creator factory##product##Creator(key, construction_function); - -#define REGISTER_IN_FACTORY_INSTANCE(factory, factoryType, key, product) \ - static factoryType::Creator factoryType##product##Creator(factory, key); - -#define DECLARE_SEGMENT(fileName) int dataSegment##fileName; - -#define FORCE_SEGMENT(fileName) \ - extern int dataSegment##fileName; \ - int* dataSegmentPtr##fileName = &dataSegment##fileName; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_FACTORY_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/MathUtils.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/MathUtils.h deleted file mode 100644 index 82c49a8806..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/MathUtils.h +++ /dev/null @@ -1,54 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_MATHUTILS_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_MATHUTILS_H -#pragma once - -inline int xround(float v) -{ - return int(v + 0.5f); -} - -inline int min(int a, int b) -{ - return a < b ? a : b; -} - -inline int max(int a, int b) -{ - return a > b ? a : b; -} - -inline float min(float a, float b) -{ - return a < b ? a : b; -} - -inline float max(float a, float b) -{ - return a > b ? a : b; -} - -inline float clamp(float value, float min, float max) -{ - return ::min(::max(min, value), max); -} - -inline int clamp(int value, int min, int max) -{ - return ::min(::max(min, value), max); -} - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_MATHUTILS_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.cpp deleted file mode 100644 index b13c89464d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.cpp +++ /dev/null @@ -1,466 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyDrawContext.h" -#include -#include "QPropertyTree.h" -#include "Serialization/Decorators/IconXPM.h" -#include "Unicode.h" -#include -#include -#include -#include - -// required to create context for the draw calls -#include -#include -#include - -#include - -#ifndef _MSC_VER -# define _stricmp strcasecmp -#endif - -// --------------------------------------------------------------------------- - -QColor interpolateColor(const QColor& a, const QColor& b, float k); - -IconXPMCache::~IconXPMCache() -{ - flush(); -} - - -void IconXPMCache::flush() -{ - IconToBitmap::iterator it; - for (it = iconToImageMap_.begin(); it != iconToImageMap_.end(); ++it) - delete it->second.bitmap; - iconToImageMap_.clear(); -} - -struct RGBAImage -{ - int width_; - int height_; - std::vector pixels_; - - RGBAImage() : width_(0), height_(0) {} -}; - -bool IconXPMCache::parseXPM(RGBAImage* out, const Serialization::IconXPM& icon) -{ - if (icon.lineCount < 3) { - return false; - } - - // parse values - std::vector pixels; - int width = 0; - int height = 0; - int charsPerPixel = 0; - int colorCount = 0; - int hotSpotX = -1; - int hotSpotY = -1; - - int scanResult = azsscanf(icon.source[0], "%d %d %d %d %d %d", &width, &height, &colorCount, &charsPerPixel, &hotSpotX, &hotSpotY); - if (scanResult != 4 && scanResult != 6) - return false; - - if (charsPerPixel > 4) - return false; - - if (icon.lineCount != 1 + colorCount + height) { - YASLI_ASSERT(0 && "Wrong line count"); - return false; - } - - // parse colors - std::vector > colors; - colors.resize(colorCount); - - for (int colorIndex = 0; colorIndex < colorCount; ++colorIndex) { - const char* p = icon.source[colorIndex + 1]; - int code = 0; - for (int charIndex = 0; charIndex < charsPerPixel; ++charIndex) { - if (*p == '\0') - return false; - code = (code << 8) | *p; - ++p; - } - colors[colorIndex].first = code; - - while (*p == '\t' || *p == ' ') - ++p; - - if (*p == '\0') - return false; - - if (*p != 'c' && *p != 'g') - return false; - ++p; - - while (*p == '\t' || *p == ' ') - ++p; - - if (*p == '\0') - return false; - - if (*p == '#') { - ++p; - if (strlen(p) == 6) { - int colorCode; - if (azsscanf(p, "%x", &colorCode) != 1) - return false; - Color color((colorCode & 0xff0000) >> 16, - (colorCode & 0xff00) >> 8, - (colorCode & 0xff), - 255); - colors[colorIndex].second = color; - } - } - else { - if (_stricmp(p, "None") == 0) - colors[colorIndex].second = Color(0, 0, 0, 0); - else if (_stricmp(p, "Black") == 0) - colors[colorIndex].second = Color(0, 0, 0, 255); - else { - // unknown color - colors[colorIndex].second = Color(255, 0, 0, 255); - } - } - } - - // parse pixels - pixels.resize(width * height); - int pi = 0; - for (int y = 0; y < height; ++y) { - const char* p = icon.source[1 + colorCount + y]; - if (strlen(p) != width * charsPerPixel) - return false; - - for (int x = 0; x < width; ++x) { - int code = 0; - for (int i = 0; i < charsPerPixel; ++i) { - code = (code << 8) | *p; - ++p; - } - - for (size_t i = 0; i < size_t(colorCount); ++i) - if (colors[i].first == code) - pixels[pi] = colors[i].second; - ++pi; - } - } - - out->pixels_.swap(pixels); - out->width_ = width; - out->height_ = height; - return true; -} - - -QImage* IconXPMCache::getImageForIcon(const Serialization::IconXPM& icon) -{ - IconToBitmap::iterator it = iconToImageMap_.find(icon.source); - if (it != iconToImageMap_.end()) - return it->second.bitmap; - - RGBAImage image; - if (!parseXPM(&image, icon)) - return 0; - - BitmapCache& cache = iconToImageMap_[icon.source]; - cache.pixels.swap(image.pixels_); - cache.bitmap = new QImage((unsigned char*)&cache.pixels[0], image.width_, image.height_, QImage::Format_ARGB32); - return cache.bitmap; -} - -// --------------------------------------------------------------------------- - -void drawRoundRectangle(QPainter& p, const QRect &_r, unsigned int color, int radius, [[maybe_unused]] int width) -{ - QRect r = _r; - int dia = 2 * radius; - - p.setPen(QColor(color)); - p.drawRoundedRect(r, dia, dia); -} - -void fillRoundRectangle(QPainter& p, const QBrush& brush, const QRect& _r, const QColor& border, int radius) -{ - bool wasAntialisingSet = p.renderHints().testFlag(QPainter::Antialiasing); - p.setRenderHints(QPainter::Antialiasing, true); - - p.setBrush(brush); - QPen pen(QBrush(border), 1.0, Qt::SolidLine); - p.setPen(pen); - QRectF adjustedRect = _r; - adjustedRect.adjust(0.5f, 0.5f, -0.5f, -0.5f); - p.drawRoundedRect(adjustedRect, radius, radius); - - p.setRenderHints(QPainter::Antialiasing, wasAntialisingSet); -} - -// --------------------------------------------------------------------------- - -void PropertyDrawContext::drawIcon(const QRect& rect, const Serialization::IconXPM& icon) const -{ - QImage* image = tree->_iconCache()->getImageForIcon(icon); - if (!image) - return; - int x = rect.left() + (rect.width() - image->width()) / 2; - int y = rect.top() + (rect.height() - image->height()) / 2; - painter->drawImage(x, y, *image); -} - -void PropertyDrawContext::drawCheck(const QRect& rect, bool disabled, CheckState checked) const -{ - QStyleOptionButton option; - if (!disabled) - option.state |= QStyle::State_Enabled; - else { - option.state |= QStyle::State_ReadOnly; - option.palette.setCurrentColorGroup(QPalette::Disabled); - } - if (checked == CHECK_SET) - option.state |= QStyle::State_On; - else if (checked == CHECK_IN_BETWEEN) - option.state |= QStyle::State_NoChange; - else - option.state |= QStyle::State_Off; - - // create a widget so that the style sheet has context for its draw calls - QCheckBox forContext; - QSize checkboxSize = tree->style()->subElementRect(QStyle::SE_CheckBoxIndicator, &option, &forContext).size(); - option.rect = QRect(rect.left(), rect.center().y() - checkboxSize.height() / 2, checkboxSize.width(), checkboxSize.height()); - tree->style()->drawPrimitive(QStyle::PE_IndicatorCheckBox, &option, painter, &forContext); - if (disabled) { - // With Fusion theme difference between disabled and enabled checkbox is very subtle, let's amplify it - QColor readOnlyOverlay = tree->backgroundColor(); - readOnlyOverlay.setAlpha(128); - painter->fillRect(option.rect, QBrush(readOnlyOverlay)); - } -} - -void PropertyDrawContext::drawButton(const QRect& rect, const wchar_t* text, int buttonFlags, const QFont* font, const Color* colorOverride) const -{ - QPushButton button; - button.ensurePolished(); - QStyleOptionButton option; - option.initFrom(&button); - if (buttonFlags & BUTTON_DISABLED) { - option.state |= QStyle::State_ReadOnly; - option.palette.setCurrentColorGroup(QPalette::Disabled); - } - else - option.state |= QStyle::State_Enabled; - if (buttonFlags & BUTTON_PRESSED) { - option.state |= QStyle::State_On; - option.state |= QStyle::State_Sunken; - } - else - option.state |= QStyle::State_Raised; - - if (buttonFlags & BUTTON_FOCUSED) - option.state |= QStyle::State_HasFocus; - option.rect = rect.adjusted(0, 0, -1, -1); - - QWidget* pseudoDrawWidget = &button; - - if (colorOverride) { - QPalette& palette = option.palette; - palette.setCurrentColorGroup(QPalette::Normal); - QColor tintTarget(colorOverride->r, colorOverride->g, colorOverride->b, colorOverride->a); - - QPalette::ColorRole groups[] = { QPalette::Button, QPalette::Light, QPalette::Dark, QPalette::Midlight, QPalette::Mid, QPalette::Shadow }; - for (int i = 0; i < sizeof(groups) / sizeof(groups[0]); ++i) - palette.setColor(groups[i], interpolateColor(palette.color(groups[i]), tintTarget, 0.11f)); - - tree->style()->drawControl(QStyle::CE_PushButtonBevel, &option, painter, pseudoDrawWidget); - } - else - { - // Previously, a temporary QPushButton widget was used as the drawing aid - // for this control. However, our stylesheets didn't seem to affect the - // QPushButton as intended, which left some of them with incorrect background - // colors. It seemed to work to let the tree be the drawing aid, but we should - // probably revisit this in the future. - tree->style()->drawControl(QStyle::CE_PushButtonBevel, &option, painter, pseudoDrawWidget); - } - - QRect textRect; - if ((buttonFlags & BUTTON_DISABLED) == 0 && buttonFlags & BUTTON_POPUP_ARROW) - { - QStyleOption arrowOption; - arrowOption.rect = QRect(rect.right() - 11, rect.top(), 8, rect.height()); - arrowOption.state |= QStyle::State_Enabled; - - // part of the above context change - tree->style()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &arrowOption, painter, tree); - - textRect = rect.adjusted(0, 0, -8, 0); - } - else - { - textRect = rect; - } - - if (buttonFlags & BUTTON_PRESSED) - { - textRect = textRect.adjusted(1, 0, 1, 0); - } - if ((buttonFlags & BUTTON_CENTER) == 0) - { - textRect.adjust(4, 0, -5, 0); - } - - QColor textColor; - if (colorOverride && !(buttonFlags & BUTTON_DISABLED)) - { - textColor = interpolateColor(tree->palette().color(QPalette::Normal, QPalette::ButtonText), - QColor(colorOverride->r, colorOverride->g, colorOverride->b, colorOverride->a), 0.4f); - } - else - { - textColor = tree->palette().color((buttonFlags & BUTTON_DISABLED) ? QPalette::Disabled : QPalette::Normal, QPalette::ButtonText); - } - tree->_drawRowValue(*painter, text, font, textRect, textColor, false, (buttonFlags & BUTTON_CENTER) != 0); -} - -void PropertyDrawContext::drawButtonWithIcon(const QIcon& icon, const QRect& rect, const wchar_t* text, bool selected, bool pressed, bool focused, bool enabled, bool showButtonFrame, const QFont* font) const -{ - QStyleOptionButton option; - if (enabled) - option.state |= QStyle::State_Enabled; - else - option.state |= QStyle::State_ReadOnly; - if (pressed) { - option.state |= QStyle::State_On; - option.state |= QStyle::State_Sunken; - } - else - option.state |= QStyle::State_Raised; - - if (focused) - option.state |= QStyle::State_HasFocus; - option.rect = rect.adjusted(0, 0, -1, -1); - - // See the comment in the drawButton method above for why we don't use the - // QPushButton as the drawing aid for this control - if (showButtonFrame) - tree->style()->drawControl(QStyle::CE_PushButton, &option, painter, tree); - - int iconSize = 16; - QRect iconRect(rect.topLeft(), QPoint(rect.left() + iconSize, rect.bottom())); - QRect textRect; - if (enabled) - textRect = rect.adjusted(iconSize, 0, -8, 0); - else - textRect = rect.adjusted(iconSize, 0, 0, 0); - - if (pressed) - { - textRect.adjust(5, 0, 1, 0); - iconRect.adjust(4, 0, 4, 0); - } - else - { - textRect.adjust(4, 0, 0, 0); - iconRect.adjust(3, 0, 3, 0); - } - icon.paint(painter, iconRect); - - QColor textColor = tree->palette().color(enabled ? QPalette::Active : QPalette::Disabled, selected && !showButtonFrame ? QPalette::HighlightedText : QPalette::ButtonText); - tree->_drawRowValue(*painter, text, font, textRect, textColor, false, false); -} - -void PropertyDrawContext::drawValueText(bool highlighted, const wchar_t* text) const -{ - QColor textColor = highlighted ? tree->palette().highlight().color() : tree->palette().buttonText().color(); - QRect textRect(widgetRect.left() + 3, widgetRect.top() + 2, widgetRect.width() - 6, widgetRect.height() - 4); - tree->_drawRowValue(*painter, text, &tree->font(), textRect, textColor, false, false); -} - -void PropertyDrawContext::drawEntry(const wchar_t* text, bool pathEllipsis, bool grayBackground, int trailingOffset) const -{ - QRect rt = widgetRect; - rt.adjust(0, 0, -trailingOffset, 0); - - // the drawing context requires context so that the style sheet can be used: - QFrame frameForContext; - QLineEdit forContext; -#if (QT_VERSION < QT_VERSION_CHECK(5, 11, 0)) - QStyleOptionFrameV2 option; - option.features = QStyleOptionFrameV2::None; -#else - QStyleOptionFrame option; - option.features = QStyleOptionFrame::None; -#endif - option.state = QStyle::State_Sunken; - option.lineWidth = tree->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &option, &frameForContext); - option.midLineWidth = 0; - if (!grayBackground) - option.state |= QStyle::State_Enabled; - else { - option.palette.setCurrentColorGroup(QPalette::Disabled); - } - if (captured) - option.state |= QStyle::State_HasFocus; - option.rect = rt; // option.rect is the rectangle to be drawn on. - QRect textRect = tree->style()->subElementRect(QStyle::SE_LineEditContents, &option, &forContext); - if (!textRect.isValid()) - { - textRect = rt; - textRect.adjust(3, 1, -3, -2); - } - else { - textRect.adjust(2, 1, -2, -1); - } - - // make sure the context control is polished (ie, ready for rendering) since we need to use its color palette: - forContext.ensurePolished(); - - // some styles rely on default pens - painter->setPen(QPen(forContext.palette().color(QPalette::Text))); - painter->setBrush(QBrush(forContext.palette().color(QPalette::Base))); - - tree->style()->drawPrimitive(QStyle::PE_PanelLineEdit, &option, painter, &forContext); - tree->_drawRowValue(*painter, text, &tree->font(), textRect, forContext.palette().color(QPalette::Text), pathEllipsis, false); - // end amazno changes -} - - -QFont* propertyTreeDefaultFont() -{ - static QFont font; - return &font; -} - -QFont* propertyTreeDefaultBoldFont() -{ - static QFont font; - font.setBold(true); - return &font; -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.h deleted file mode 100644 index 611216eb73..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyDrawContext.h +++ /dev/null @@ -1,98 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - // Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYDRAWCONTEXT_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYDRAWCONTEXT_H -#pragma once - - -#include -#include -#include -#include "Color.h" -#include "EditorCommonAPI.h" - -class QPainter; -class QImage; -class QBrush; -class QRect; -class QIcon; -class QColor; -class QFont; -struct RGBAImage; -namespace Serialization { struct IconXPM; } -struct Color; - -struct IconXPMCache -{ - void initialize(); - void finalize(); - void flush(); - - ~IconXPMCache(); - - QImage* getImageForIcon(const Serialization::IconXPM& icon); -private: - struct BitmapCache { - std::vector pixels; - QImage* bitmap; - }; - - static bool parseXPM(RGBAImage* out, const Serialization::IconXPM& xpm); - typedef std::map IconToBitmap; - IconToBitmap iconToImageMap_; -}; - - -void fillRoundRectangle(QPainter& p, const QBrush& brush, const QRect& r, const QColor& borderColor, int radius); -void drawRoundRectangle(QPainter& p, const QRect &_r, unsigned int color, int radius, int width); - - -enum CheckState { - CHECK_SET, - CHECK_NOT_SET, - CHECK_IN_BETWEEN -}; - -enum { - BUTTON_POPUP_ARROW = 1 << 0, - BUTTON_DISABLED = 1 << 1, - BUTTON_FOCUSED = 1 << 2, - BUTTON_PRESSED = 1 << 3, - BUTTON_CENTER = 1 << 4 -}; - -class QPropertyTree; -struct EDITOR_COMMON_API PropertyDrawContext { - const QPropertyTree* tree; - QPainter* painter; - QRect widgetRect; - QRect lineRect; - bool captured; - bool m_pressed; - - void drawIcon(const QRect& rect, const Serialization::IconXPM& icon) const; - void drawCheck(const QRect& rect, bool disabled, CheckState checked) const; - void drawButton(const QRect& rect, const wchar_t* text, int buttonFlags, const QFont* font, const Color* optionalColorOverride = 0) const; - void drawButtonWithIcon(const QIcon& icon, const QRect& rect, const wchar_t* text, bool selected, bool pressed, bool focused, bool enabled, bool showButtonFrame, const QFont* font) const; - void drawValueText(bool highlighted, const wchar_t* text) const; - void drawEntry(const wchar_t* text, bool pathEllipsis, bool grayBackground, int trailingOffset) const; - - PropertyDrawContext() - : tree(0) - , painter(0) - , captured(false) - , m_pressed(false) - { - } -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYDRAWCONTEXT_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.cpp deleted file mode 100644 index 4b03246db5..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.cpp +++ /dev/null @@ -1,377 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "Serialization.h" -#include "Serialization/Enum.h" -#include "Serialization/Callback.h" -#include "PropertyTreeModel.h" -#include "PropertyIArchive.h" -#include "PropertyRowBool.h" -#include "PropertyRowString.h" -#include "PropertyRowNumber.h" -#include "PropertyRowPointer.h" -#include "PropertyRowObject.h" -#include "Unicode.h" - -using Serialization::TypeID; - -PropertyIArchive::PropertyIArchive(PropertyTreeModel* model, PropertyRow* root) -: IArchive(INPUT | EDIT) -, model_(model) -, currentNode_(0) -, lastNode_(0) -, root_(root) -{ - stack_.push_back(Level()); - - if (!root_) - root_ = model_->root(); - else - currentNode_ = root; -} - -bool PropertyIArchive::operator()(Serialization::IString& value, const char* name, const char* label) -{ - if(openRow(name, label, "string")){ - if(PropertyRowString* row = static_cast(currentNode_)) - value.set(fromWideChar(row->value().c_str()).c_str()); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(Serialization::IWString& value, const char* name, const char* label) -{ - if(openRow(name, label, "string")){ - if(PropertyRowString* row = static_cast(currentNode_)) { - value.set(row->value().c_str()); - } - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(bool& value, const char* name, const char* label) -{ - if(openRow(name, label, "bool")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(char& value, const char* name, const char* label) -{ - if(openRow(name, label, "char")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -// Signed types -bool PropertyIArchive::operator()(int8& value, const char* name, const char* label) -{ - if(openRow(name, label, "int8")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(int16& value, const char* name, const char* label) -{ - if(openRow(name, label, "int16")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(int32& value, const char* name, const char* label) -{ - if(openRow(name, label, "int32")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(int64& value, const char* name, const char* label) -{ - if(openRow(name, label, "int64")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -// Unsigned types -bool PropertyIArchive::operator()(uint8& value, const char* name, const char* label) -{ - if(openRow(name, label, "uint8")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(uint16& value, const char* name, const char* label) -{ - if(openRow(name, label, "uint16")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(uint32& value, const char* name, const char* label) -{ - if(openRow(name, label, "uint32")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(uint64& value, const char* name, const char* label) -{ - if(openRow(name, label, "uint64")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(float& value, const char* name, const char* label) -{ - if(openRow(name, label, "float")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(double& value, const char* name, const char* label) -{ - if(openRow(name, label, "double")){ - currentNode_->assignToPrimitive(&value, sizeof(value)); - closeRow(name); - return true; - } - else - return false; -} - -bool PropertyIArchive::operator()(Serialization::IContainer& ser, const char* name, const char* label) -{ - const char* typeName = ser.containerType().name(); - if(!openRow(name, label, typeName)) - return false; - - size_t size = 0; - if(currentNode_->multiValue()) - size = ser.size(); - else{ - size = currentNode_->count(); - size = ser.resize(size); - } - - stack_.push_back(Level()); - - size_t index = 0; - if(ser.size() > 0) - while(index < size) - { - ser(*this, "", "<"); - ser.next(); - ++index; - } - - stack_.pop_back(); - - closeRow(name); - return true; -} - -bool PropertyIArchive::operator()(const Serialization::SStruct& ser, const char* name, const char* label) -{ - PropertyRow* nonLeafNode = 0; - if(openRow(name, label, ser.type().name())){ - if (currentNode_->isLeaf()) { - if(!currentNode_->isRoot()){ - currentNode_->assignTo(ser); - closeRow(name); - return true; - } - } - else - nonLeafNode = currentNode_; - } - else - return false; - - stack_.push_back(Level()); - - ser(*this); - - stack_.pop_back(); - - if (nonLeafNode) - nonLeafNode->closeNonLeaf(ser, *this); - closeRow(name); - return true; -} - - -bool PropertyIArchive::operator()(Serialization::IPointer& ser, const char* name, const char* label) -{ - const char* baseName = ser.baseType().name(); - - if(openRow(name, label, baseName)){ - if (!currentNode_->isPointer()) { - closeRow(name); - return false; - } - - YASLI_ASSERT(currentNode_); - PropertyRowPointer* row = static_cast(currentNode_); - if(!row){ - closeRow(name); - return false; - } - row->assignTo(ser); - } - else - return false; - - stack_.push_back(Level()); - - if(ser.get() != 0) - ser.serializer()( *this ); - - stack_.pop_back(); - - closeRow(name); - return true; -} - -bool PropertyIArchive::operator()(Serialization::ICallback& callback, const char* name, const char* label) -{ - return callback.SerializeValue(*this, name, label); -} - -bool PropertyIArchive::operator()(Serialization::Object& obj, const char* name, const char* label) -{ - if(openRow(name, label, obj.type().name())){ - bool result = false; - if (currentNode_->isObject()) { - PropertyRowObject* rowObj = static_cast(currentNode_); - result = rowObj->assignTo(&obj); - } - closeRow(name); - return result; - } - else - return false; -} - -bool PropertyIArchive::OpenBlock(const char* name, const char* label) -{ - if(openRow(name, label, "block")){ - stack_.push_back(Level()); - return true; - } - else - return false; -} - -void PropertyIArchive::CloseBlock() -{ - closeRow("block"); - stack_.pop_back(); -} - -bool PropertyIArchive::openRow(const char* name, [[maybe_unused]] const char* label, const char* typeName) -{ - if(!name) - return false; - - if(!currentNode_){ - lastNode_ = currentNode_ = model_->root(); - YASLI_ASSERT(currentNode_); - if (currentNode_ && strcmp(currentNode_->typeName(), typeName) != 0) - return false; - return true; - } - - YASLI_ESCAPE(currentNode_, return false); - - if(currentNode_->empty()) - return false; - - Level& level = stack_.back(); - - PropertyRow* node = 0; - if(currentNode_->isContainer()){ - if (level.rowIndex < int(currentNode_->children_.size())) - node = currentNode_->children_[level.rowIndex]; - ++level.rowIndex; - } - else { - node = currentNode_->findFromIndex(&level.rowIndex, name, typeName, level.rowIndex); - ++level.rowIndex; - } - - if(node){ - lastNode_ = node; - if(node->isContainer() || !node->multiValue()){ - currentNode_ = node; - if (currentNode_ && strcmp(currentNode_->typeName(), typeName) != 0) - return false; - return true; - } - } - return false; -} - -void PropertyIArchive::closeRow([[maybe_unused]] const char* name) -{ - YASLI_ESCAPE(currentNode_, return); - currentNode_ = currentNode_->parent(); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.h deleted file mode 100644 index 265a819cf7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyIArchive.h +++ /dev/null @@ -1,80 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYIARCHIVE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYIARCHIVE_H -#pragma once - - -#include "Serialization/IArchive.h" - -namespace Serialization{ - class CEnumDescription; - class Object; -} - -class PropertyRow; -class PropertyTreeModel; - -class PropertyIArchive : public Serialization::IArchive{ -public: - PropertyIArchive(PropertyTreeModel* model, PropertyRow* root); - -protected: - bool operator()(Serialization::IString& value, const char* name, const char* label); - bool operator()(Serialization::IWString& value, const char* name, const char* label); - bool operator()(bool& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - // Signed types - bool operator()(int8& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - // Unsigned types - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - - bool operator()(const Serialization::SStruct& ser, const char* name, const char* label); - bool operator()(Serialization::IPointer& ser, const char* name, const char* label); - bool operator()(Serialization::IContainer& ser, const char* name, const char* label); - bool operator()(Serialization::Object& obj, const char* name, const char* label); - bool operator()(Serialization::ICallback& callback, const char* name, const char* label); - using Serialization::IArchive::operator(); - - bool OpenBlock(const char* name, const char* label); - void CloseBlock(); - -protected: - bool needDefaultArchive([[maybe_unused]] const char* baseName) const { return false; } -private: - bool openRow(const char* name, const char* label, const char* typeName); - void closeRow(const char* name); - - struct Level { - int rowIndex; - Level() : rowIndex(0) {} - }; - - vector stack_; - - PropertyTreeModel* model_; - PropertyRow* currentNode_; - PropertyRow* lastNode_; - PropertyRow* root_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYIARCHIVE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.cpp deleted file mode 100644 index fd6773f4da..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.cpp +++ /dev/null @@ -1,487 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include -#include - -#include "PropertyTreeModel.h" -#include "QPropertyTree.h" - -#include "PropertyRowContainer.h" -#include "PropertyRowBool.h" -#include "PropertyRowString.h" -#include "PropertyRowNumber.h" -#include "PropertyRowPointer.h" -#include "PropertyRowObject.h" -#include "ConstStringList.h" -#include "Unicode.h" - -#include "Serialization.h" -#include "PropertyOArchive.h" -#include "Serialization/Callback.h" -using Serialization::TypeID; - - -PropertyOArchive::PropertyOArchive(PropertyTreeModel* model, PropertyRow* root, ValidatorBlock* validator) -: IArchive(OUTPUT | EDIT | VALIDATION | DOCUMENTATION) -, model_(model) -, currentNode_(root) -, lastNode_(0) -, updateMode_(false) -, defaultValueCreationMode_(false) -, rootNode_(root) -, outlineMode_(false) -, validator_(validator) -{ - stack_.push_back(Level()); - YASLI_ASSERT(model != 0); - if(!rootNode_->empty()){ - updateMode_ = true; - stack_.back().oldRows.swap(rootNode_->children_); - } -} - - - -PropertyOArchive::PropertyOArchive(PropertyTreeModel* model, bool forDefaultType) -: IArchive(OUTPUT | EDIT | VALIDATION | DOCUMENTATION) -, model_(model) -, currentNode_(0) -, lastNode_(0) -, updateMode_(false) -, defaultValueCreationMode_(forDefaultType) -, rootNode_(0) -, outlineMode_(false) -, validator_(0) -{ - rootNode_ = new PropertyRow(); - rootNode_->setName("root"); - currentNode_ = rootNode_.get(); - stack_.push_back(Level()); -} - -PropertyOArchive::~PropertyOArchive() -{ -} - -PropertyRow* PropertyOArchive::defaultValueRootNode() -{ - if (!rootNode_) - return 0; - return rootNode_->childByIndex(0); -} - -void PropertyOArchive::enterNode(PropertyRow* row) -{ - currentNode_ = row; - - stack_.push_back(Level()); - Level& level = stack_.back(); - level.oldRows.swap(row->children_); - row->children_.reserve(level.oldRows.size()); -} - -void PropertyOArchive::closeStruct([[maybe_unused]] const char* name) -{ - stack_.pop_back(); - - if(currentNode_){ - lastNode_ = currentNode_; - currentNode_ = currentNode_->parent(); - } -} - -static PropertyRow* findRow(int* index, PropertyRows& rows, const char* name, const char* typeName, int startIndex) -{ - int count = int(rows.size()); - for(int i = startIndex; i < count; ++i){ - PropertyRow* row = rows[i]; - if (!row) - continue; - if(((row->name() == name) || strcmp(row->name(), name) == 0) && - (row->typeName() == typeName || strcmp(row->typeName(), typeName) == 0)) { - *index = (int)i; - return row; - } - } - for(int i = 0; i < startIndex; ++i){ - PropertyRow* row = rows[i]; - if (!row) - continue; - if(((row->name() == name) || strcmp(row->name(), name) == 0) && - (row->typeName() == typeName || strcmp(row->typeName(), typeName) == 0)) { - *index = (int)i; - return row; - } - } - return 0; -} - -template -RowType* PropertyOArchive::updateRow(const char* name, const char* label, const char* typeName, const ValueType& value) -{ - SharedPtr newRow; - if(currentNode_ == 0){ - if (rootNode_) - newRow = static_cast(rootNode_.get()); - else - newRow.reset(new RowType()); - newRow->setNames(name, label, typeName); - if(updateMode_){ - model_->setRoot(newRow); - return newRow; - } - else{ - if(defaultValueCreationMode_) - rootNode_ = newRow; - else - model_->setRoot(newRow); - newRow->setValueAndContext(value, *this); - return newRow; - } - } - else{ - - Level& level = stack_.back(); - int rowIndex; - PropertyRow* oldRow = findRow(&rowIndex, level.oldRows, name, typeName, level.rowIndex); - - const char* oldLabel = 0; - if(oldRow){ - oldRow->setMultiValue(false); - newRow = static_cast(oldRow); - level.oldRows[rowIndex] = 0; - level.rowIndex = rowIndex + 1; - oldLabel = oldRow->label(); - newRow->setNames(name, label, typeName); - } - else{ - PropertyRowFactory& factory = PropertyRowFactory::the(); - newRow = static_cast(factory.create(typeName)); - if(!newRow) - newRow.reset(new RowType()); - newRow->setNames(name, label, typeName); - if(model_->expandLevels() != 0 && (model_->expandLevels() == -1 || model_->expandLevels() >= currentNode_->level())) - newRow->_setExpanded(true); - } - currentNode_->add(newRow); - if (!oldRow || oldLabel != label) { - // for new rows we should mark all parents with labelChanged_ - newRow->setLabelChanged(); - newRow->setLabelChangedToChildren(); - } - newRow->setValueAndContext(value, *this); - return newRow; - } -} - -template -PropertyRow* PropertyOArchive::updateRowPrimitive(const char* name, const char* label, const char* typeName, const ValueType& value, const void* handle, const Serialization::TypeID& typeId) -{ - SharedPtr newRow; - - if(currentNode_ == 0) - return 0; - - int rowIndex; - Level& level = stack_.back(); - PropertyRow* oldRow = findRow(&rowIndex, level.oldRows, name, typeName, level.rowIndex); - - const char* oldLabel = 0; - if(oldRow){ - oldRow->setMultiValue(false); - newRow.reset(static_cast(oldRow)); - level.oldRows[rowIndex] = 0; - level.rowIndex = rowIndex + 1; - oldLabel = oldRow->label(); - oldRow->setNames(name, label, typeName); - } - else{ - newRow = new RowType(); - newRow->setNames(name, label, typeName); - if(model_->expandLevels() != 0){ - if(model_->expandLevels() == -1 || model_->expandLevels() >= currentNode_->level()) - newRow->_setExpanded(true); - } - } - currentNode_->add(newRow); - if (!oldRow || oldLabel != label) - { - // for new rows we should mark all parents with labelChanged_ - newRow->setLabelChanged(); - } - - newRow->setValue(value, handle, typeId); - return newRow; -} - -bool PropertyOArchive::operator()(const Serialization::SStruct& ser, const char* name, const char* label) -{ - const char* typeName = ser.type().name(); - - lastNode_ = currentNode_; - bool hideChildren = outlineMode_ && currentNode_ && currentNode_->isContainer(); - PropertyRow* row = updateRow(name, label, typeName, ser); - row->setHideChildren(hideChildren); - - PropertyRow* nonLeaf = 0; - if(!row->isLeaf() || currentNode_ == 0){ - enterNode(row); - - if(currentNode_->isLeaf()) - return false; - else - nonLeaf = currentNode_; - } - else{ - lastNode_ = row; - return true; - } - - if (ser) - ser(*this); - - if (nonLeaf) - nonLeaf->closeNonLeaf(ser, *this); - - closeStruct(name); - return true; -} - -bool PropertyOArchive::operator()(Serialization::IString& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive(name, label, "string", value.get(), value.handle(), value.type()); - return true; -} - -bool PropertyOArchive::operator()(Serialization::IWString& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive(name, label, "string", value.get(), value.handle(), value.type()); - return true; -} - -bool PropertyOArchive::operator()(bool& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive(name, label, "bool", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(char& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "char", value, &value, Serialization::TypeID::get()); - return true; -} - -// --- - -bool PropertyOArchive::operator()(int8& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "int8", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(int16& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "int16", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(int32& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "int32", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(int64& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "int64", value, &value, Serialization::TypeID::get()); - return true; -} - -// --- - -bool PropertyOArchive::operator()(uint8& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "uint8", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(uint16& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "uint16", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(uint32& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "uint32", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(uint64& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "uint64", value, &value, Serialization::TypeID::get()); - return true; -} - -// --- - -bool PropertyOArchive::operator()(float& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "float", value, &value, Serialization::TypeID::get()); - return true; -} - -bool PropertyOArchive::operator()(double& value, const char* name, const char* label) -{ - lastNode_ = updateRowPrimitive >(name, label, "double", value, &value, Serialization::TypeID::get()); - return true; -} - - -bool PropertyOArchive::operator()(Serialization::IContainer& ser, const char *name, const char *label) -{ - const char* elementTypeName = ser.elementType().name(); - enterNode(updateRow(name, label, ser.containerType().name(), ser)); - - if (!model_->defaultTypeRegistered(elementTypeName)) { - PropertyOArchive ar(model_, true); - ar.SetOutlineMode(outlineMode_); - ar.SetFilter(GetFilter()); - ar.SetInnerContext(GetInnerContext()); - model_->addDefaultType(0, elementTypeName); // add empty default to prevent recursion - ser.serializeNewElement(ar, "", (label&&*label=='!')?"!<":"<"); - if (ar.defaultValueRootNode() != 0) - model_->addDefaultType(ar.defaultValueRootNode(), elementTypeName); - } - if ( ser.size() > 0 ) - while( true ) { - ser(*this, "", (label&&*label=='!')?"!<":"<"); - if ( !ser.next() ) - break; - } - currentNode_->labelChanged(); - closeStruct(name); - return true; -} - -bool PropertyOArchive::operator()(Serialization::IPointer& ptr, const char *name, const char *label) -{ - lastNode_ = currentNode_; - - bool hideChildren = outlineMode_ && currentNode_ && currentNode_->isContainer(); - PropertyRow* row = updateRow(name, label, ptr.baseType().name(), ptr); - row->setHideChildren(hideChildren); - enterNode(row); - { - TypeID baseType = ptr.baseType(); - Serialization::IClassFactory* factory = ptr.factory(); - size_t count = factory->size(); - - const char* nullLabel = factory->nullLabel(); - if (!(nullLabel && nullLabel[0] == '\0')) - { - PropertyDefaultDerivedTypeValue nullValue; - nullValue.factory = factory; - nullValue.factoryIndex = -1; - nullValue.label = nullLabel ? nullLabel : "[ null ]"; - model_->addDefaultType(baseType, nullValue); - } - - for(size_t i = 0; i < count; ++i) { - const Serialization::TypeDescription *desc = factory->descriptionByIndex((int)i); - if (!model_->defaultTypeRegistered(baseType, desc->name())){ - PropertyOArchive ar(model_, true); - ar.SetOutlineMode(outlineMode_); - ar.SetInnerContext(GetInnerContext()); - ar.SetFilter(GetFilter()); - - PropertyDefaultDerivedTypeValue defaultValue; - defaultValue.registeredName = desc->name(); - defaultValue.factory = factory; - defaultValue.factoryIndex = int(i); - defaultValue.label = desc->label(); - - model_->addDefaultType(baseType, defaultValue); - factory->serializeNewByIndex(ar, (int)i, "name", "label"); - if (ar.defaultValueRootNode() != 0) { - ar.defaultValueRootNode()->setTypeName(desc->name()); - defaultValue.root = ar.defaultValueRootNode(); - model_->addDefaultType(baseType, defaultValue); - } - } - } - } - - if(Serialization::SStruct ser = ptr.serializer()) - ser(*this); - closeStruct(name); - return true; -} - -bool PropertyOArchive::operator()(Serialization::ICallback& callback, const char* name, const char* label) -{ - if (!callback.SerializeValue(*this, name, label)) - return false; - - lastNode_->setCallback(callback.Clone()); - return true; -} - -bool PropertyOArchive::operator()(Serialization::Object& obj, const char *name, const char *label) -{ - PropertyRowObject* row = 0; - row = updateRow(name, label, obj.type().name(), obj); - - lastNode_ = row; - return true; -} - -bool PropertyOArchive::OpenBlock(const char* name, const char* label) -{ - PropertyRow* row = updateRow(name, label, "block", Serialization::SStruct()); - lastNode_ = currentNode_; - enterNode(row); - return true; -} - -void PropertyOArchive::ValidatorMessage(bool error, const void* handle, const Serialization::TypeID& type, const char* message) -{ - if (validator_) - { - ValidatorEntry entry(error ? VALIDATOR_ENTRY_ERROR : VALIDATOR_ENTRY_WARNING, - handle, - type, - message); - validator_->AddEntry(entry); - } -} - -void PropertyOArchive::DocumentLastField(const char* message) -{ - if (lastNode_ && (!currentNode_ || lastNode_->parent() == currentNode_)) - lastNode_->setTooltip(message ? message : ""); - else if (currentNode_) - currentNode_->setTooltip(message ? message : ""); -} - -void PropertyOArchive::CloseBlock() -{ - closeStruct("block"); -} - -void PropertyOArchive::SetOutlineMode(bool outlineMode) -{ - outlineMode_ = outlineMode; -} - -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.h deleted file mode 100644 index 33be92466c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyOArchive.h +++ /dev/null @@ -1,112 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYOARCHIVE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYOARCHIVE_H -#pragma once - - -#include "Serialization/IArchive.h" -#include "Serialization/Pointers.h" - -namespace Serialization -{ - class CEnumDescription; - class Object; - struct ICallback; -} - -class PropertyRow; -class PropertyTreeModel; -class ValidatorBlock; - -using Serialization::SharedPtr; - -class PropertyOArchive : public Serialization::IArchive{ -public: - PropertyOArchive(PropertyTreeModel* model, PropertyRow* root, ValidatorBlock* validator); - ~PropertyOArchive(); - - void SetOutlineMode(bool outlineMode); - - inline const SharedPtr& currentNode() const { - return currentNode_; - } - -protected: - bool operator()(Serialization::IString& value, const char* name, const char* label); - bool operator()(Serialization::IWString& value, const char* name, const char* label); - bool operator()(bool& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - bool operator()(int8& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - - bool operator()(const Serialization::SStruct& ser, const char* name, const char* label); - bool operator()(Serialization::IPointer& ptr, const char *name, const char *label); - bool operator()(Serialization::IContainer& ser, const char *name, const char *label); - bool operator()(Serialization::Object& obj, const char *name, const char *label); - bool operator()(Serialization::ICallback& ser, const char *name, const char *label); - using Serialization::IArchive::operator(); - - bool OpenBlock(const char* name, const char* label); - void CloseBlock(); - void ValidatorMessage(bool error, const void* handle, const Serialization::TypeID& type, const char* message); - void DocumentLastField(const char* docString); - -protected: - PropertyOArchive(PropertyTreeModel* model, bool forDefaultType); - -private: - struct Level { - std::vector > oldRows; - int rowIndex; - Level() : rowIndex(0) {} - }; - std::vector stack_; - - template - PropertyRow* updateRowPrimitive(const char* name, const char* label, const char* typeName, const ValueType& value, const void* handle, const Serialization::TypeID& typeId); - - template - RowType* updateRow(const char* name, const char* label, const char* typeName, const ValueType& value); - - void enterNode(PropertyRow* row); // sets currentNode - void closeStruct(const char* name); - PropertyRow* defaultValueRootNode(); - - bool updateMode_; - bool defaultValueCreationMode_; - PropertyTreeModel* model_; - ValidatorBlock* validator_; - SharedPtr currentNode_; - SharedPtr lastNode_; - - // for defaultArchive - SharedPtr rootNode_; - std::string typeName_; - const char* derivedTypeName_; - std::string derivedTypeNameAlt_; - bool outlineMode_; -}; - -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYOARCHIVE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.cpp deleted file mode 100644 index 05b073cda6..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.cpp +++ /dev/null @@ -1,1906 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "QPropertyTree.h" -#include "QPropertyTreeStyle.h" -#include "PropertyTreeModel.h" -#include "PropertyRowContainer.h" -#include "PropertyDrawContext.h" -#include "Unicode.h" -#include "Serialization.h" -#include "Serialization/BinArchive.h" -#include "Serialization/Callback.h" -#include "Serialization/Decorators/IconXPM.h" - -#include -#include -#include -#include -#include -#include -#include "MathUtils.h" -#include "warning.xpm" -#include "error.xpm" - -#if 0 -# define DEBUG_TRACE(fmt, ...) printf(fmt "\n", __VA_ARGS__) -# define DEBUG_TRACE_ROW(fmt, ...) for(PropertyRow* zzzz = this; zzzz; zzzz = zzzz->parent()) printf(" "); printf(fmt "\n", __VA_ARGS__) -#else -# define DEBUG_TRACE(...) -# define DEBUG_TRACE_ROW(...) -#endif - -enum { TEXT_VALUE_SPACING = 3 }; - -QColor interpolateColor(const QColor& a, const QColor& b, float k) -{ - float mk = 1.0f - k; - return QColor(aznumeric_cast(a.red() * mk + b.red() * k), - aznumeric_cast(a.green() * mk + b.green() * k), - aznumeric_cast(a.blue() * mk + b.blue() * k), - aznumeric_cast(a.alpha() * mk + b.alpha() * k)); -} - -// --------------------------------------------------------------------------- - -template -static void visitPulledRows(PropertyRow* row, T& drawFunc) -{ - int count = (int)row->count(); - for (int i = 0; i < count; ++i) { - PropertyRow* child = row->childByIndex(i); - if (child->pulledUp() || child->pulledBefore()) { - drawFunc(child); - visitPulledRows(child, drawFunc); - } - } -}; - -// --------------------------------------------------------------------------- - -ConstStringList* PropertyRow::constStrings_ = 0; - -PropertyRow::PropertyRow() -{ - parent_ = 0; - callback_ = 0; - - expanded_ = false; - selected_ = false; - visible_ = true; - labelUndecorated_ = 0; - belongsToFilteredRow_ = false; - matchFilter_ = true; - - pos_ = QPoint(0, 0); - size_ = QPoint(-1, -1); - plusSize_ = 0; - textPos_ = 0; - textSizeInitial_ = 0; - textHash_ = 0; - textSize_ = 0; - widgetPos_ = 0; - widgetSize_ = 0; - userWidgetSize_ = -1; - heightIncludingChildren_ = 0; - - name_ = ""; - typeName_ = ""; - - pulledUp_ = false; - pulledBefore_ = false; - packedAfterPreviousRow_ = false; - hasPulled_ = false; - userReadOnly_ = false; - userReadOnlyRecurse_ = false; - userFullRow_ = false; - userPackCheckboxes_ = false; - userWidgetToContent_ = false; - multiValue_ = false; - fontWeight_ = FontWeight::Undefined; - userNonCopyable_ = false; - - label_ = ""; - labelChanged_ = true; - layoutChanged_ = true; - hideChildren_ = false; - validatorHasErrors_ = false; - validatorHasWarnings_ = false; - - tooltip_ = ""; -} - -PropertyRow::~PropertyRow() -{ - size_t count = children_.size(); - for (size_t i = 0; i < count; ++i) - if (children_[i]->parent() == this) - children_[i]->setParent(0); - if (callback_) - callback_->Release(); - callback_ = 0; -} - -void PropertyRow::setNames(const char* name, const char* label, const char* typeName) -{ - name_ = name; - label_ = label ? label : ""; - typeName_ = typeName; -} - -PropertyRow* PropertyRow::childByIndex(int index) -{ - if(index >= 0 && index < int(children_.size())) - return children_[index]; - else - return 0; -} - -const PropertyRow* PropertyRow::childByIndex(int index) const -{ - if(index >= 0 && index < int(children_.size())) - return children_[index]; - else - return 0; -} - -void PropertyRow::_setExpanded(bool expanded) -{ - expanded_ = expanded; - int numChildren = (int)children_.size(); - - for (int i = 0; i < numChildren; ++i) { - PropertyRow* child = children_[i]; - if(child->pulledUp()) - child->_setExpanded(expanded); - } - - layoutChanged_ = true; - setLayoutChangedToChildren(); - -} - -struct SetExpandedOp { - bool expanded_; - SetExpandedOp(bool expanded) : expanded_(expanded) {} - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(row->canBeToggled(tree)) - row->_setExpanded(expanded_); - return SCAN_CHILDREN_SIBLINGS; - } -}; - -void PropertyRow::setExpandedRecursive(QPropertyTree* tree, bool expanded) -{ - if(canBeToggled(tree)) - _setExpanded(expanded); - - SetExpandedOp op(expanded); - scanChildren(op, tree); -} - -int PropertyRow::childIndex(const PropertyRow* row) const -{ - YASLI_ASSERT(row); - Rows::const_iterator it = std::find(children_.begin(), children_.end(), row); - YASLI_ESCAPE(it != children_.end(), return -1); - return aznumeric_cast(std::distance(children_.begin(), it)); -} - -bool PropertyRow::isChildOf(const PropertyRow* row) const -{ - const PropertyRow* p = parent(); - while(p){ - if(p == row) - return true; - p = p->parent(); - } - return false; -} - -void PropertyRow::add(PropertyRow* row) -{ - children_.push_back(row); - row->setParent(this); -} - -void PropertyRow::addAfter(PropertyRow* row, PropertyRow* after) -{ - iterator it = std::find(children_.begin(), children_.end(), after); - if(it != children_.end()){ - ++it; - children_.insert(it, row); - } - else{ - children_.push_back(row); - } - - row->setParent(this); -} - -void PropertyRow::assignRowState(const PropertyRow& row, bool recurse) -{ - expanded_ = row.expanded_; - selected_ = row.selected_; - if(recurse){ - int numChildren = (int)children_.size(); - for (int i = 0; i < numChildren; ++i) { - PropertyRow* child = children_[i].get(); - YASLI_ESCAPE(child, continue); - int unusedIndex; - const PropertyRow* rhsChild = row.findFromIndex(&unusedIndex, child->name(), child->typeName(), i); - if(rhsChild) - child->assignRowState(*rhsChild, true); - } - } -} - -void PropertyRow::assignRowProperties(PropertyRow* row) -{ - YASLI_ESCAPE(row, return); - parent_ = row->parent_; - - userReadOnly_ = row->userReadOnly_; - userReadOnlyRecurse_ = row->userReadOnlyRecurse_; - userFixedWidget_ = row->userFixedWidget_; - pulledUp_ = row->pulledUp_; - pulledBefore_ = row->pulledBefore_; - size_ = row->size_; - pos_ = row->pos_; - plusSize_ = row->plusSize_; - textPos_ = row->textPos_; - textSizeInitial_ = row->textSizeInitial_; - textHash_ = row->textHash_; - textSize_ = row->textSize_; - widgetPos_ = row->widgetPos_; - widgetSize_ = row->widgetSize_; - userWidgetSize_ = row->userWidgetSize_; - userWidgetToContent_ = row->userWidgetToContent_; - callback_ = row->callback_; - row->callback_ = 0; - - assignRowState(*row, false); -} - -void PropertyRow::replaceAndPreserveState(PropertyRow* oldRow, PropertyRow* newRow, PropertyTreeModel* model) -{ - Rows::iterator it = std::find(children_.begin(), children_.end(), oldRow); - YASLI_ASSERT(it != children_.end()); - if(it != children_.end()){ - newRow->assignRowProperties(*it); - newRow->labelChanged_ = true; - *it = newRow; - if (model) - model->callRowCallback(newRow); - } -} - -void PropertyRow::erase(PropertyRow* row) -{ - PropertyRow* childToRemove = PropertyRow::findChildFromDescendant(row); - if(childToRemove) - { - childToRemove->setParent(nullptr); - children_.erase(std::find(children_.begin(), children_.end(), childToRemove)); - } -} - -void PropertyRow::swapChildren(PropertyRow* row, PropertyTreeModel* model) -{ - children_.swap(row->children_); - iterator it; - for( it = children_.begin(); it != children_.end(); ++it) - (**it).setParent(this); - for( it = row->children_.begin(); it != row->children_.end(); ++it) - (**it).setParent(row); - if (model){ - for(it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* child = *it; - if (PropertyRow* srcChild = row->find(child->name(), child->label(), child->typeName())) { - child->setCallback(srcChild->callback_); - srcChild->setCallback(0); - model->callRowCallback(child); - } - } - } -} - -void PropertyRow::addBefore(PropertyRow* row, PropertyRow* before) -{ - if(before == 0) - children_.insert(children_.begin(), row); - else{ - iterator it = std::find(children_.begin(), children_.end(), before); - if(it != children_.end()) - children_.insert(it, row); - else - children_.push_back(row); - } - row->setParent(this); -} - -wstring PropertyRow::valueAsWString() const -{ - return toWideChar(valueAsString().c_str()); -} - -string PropertyRow::valueAsString() const -{ - return string(); -} - -SharedPtr PropertyRow::clone(ConstStringList* constStrings) const -{ - PropertyRow::setConstStrings(constStrings); - Serialization::BinOArchive oa; - SharedPtr self(const_cast(this)); - oa(self, "row", "Row"); - - Serialization::BinIArchive ia; - ia.open(oa); - SharedPtr clonedRow; - ia(clonedRow, "row", "Row"); - PropertyRow::setConstStrings(0); - if (clonedRow) - clonedRow->setHideChildren(hideChildren_); - return clonedRow; -} - -void PropertyRow::drawStaticText([[maybe_unused]] QPainter& p, [[maybe_unused]] const QRect& widgetRect) -{ -} - -void PropertyRow::Serialize(IArchive& ar) -{ - serializeValue(ar); - - ar(ConstStringWrapper(constStrings_, name_), "name", "name"); - ar(ConstStringWrapper(constStrings_, label_), "label", "label"); - ar(ConstStringWrapper(constStrings_, typeName_), "type", "type"); - ar(reinterpret_cast >&>(children_), "children", "!^children"); - if(ar.IsInput()){ - labelChanged_ = true; - layoutChanged_ = true; - PropertyRow::iterator it; - for(it = begin(); it != end(); ){ - PropertyRow* row = *it; - if(row){ - row->setParent(this); - ++it; - } - else{ - YASLI_ASSERT_STR(false, "Missing property row"); - it = erase(it); - } - } - } -} - -bool PropertyRow::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason != e.REASON_RELEASE) - return e.tree->spawnWidget(this, e.force); - else - return false; -} - -void PropertyRow::setLabelChanged() -{ - for(PropertyRow* row = this; row != 0; row = row->parent()) - row->labelChanged_ = true; -} - -void PropertyRow::setLayoutChanged() -{ - layoutChanged_ = true; -} - -void PropertyRow::setLabelChangedToChildren() -{ - size_t numChildren = children_.size(); - for (size_t i = 0; i < numChildren; ++i) { - children_[i]->labelChanged_ = true; - children_[i]->setLabelChangedToChildren(); - } -} - -void PropertyRow::setLayoutChangedToChildren() -{ - size_t numChildren = children_.size(); - for (size_t i = 0; i < numChildren; ++i) { - children_[i]->layoutChanged_ = true; - children_[i]->setLayoutChangedToChildren(); - } -} - -void PropertyRow::setLabel(const char* label) -{ - if (!label) - label = ""; - if (label_ != label) { - label_ = label; - setLabelChanged(); - } -} - -void PropertyRow::propagateFlagsTopToBottom() -{ - // these flags are reset in parseControlCodes - if (!userReadOnly_ && !userWidgetToContent_) - return; - size_t numChildren = children_.size(); - for (size_t i = 0; i < numChildren; ++i) { - PropertyRow* r = children_[i]; - if (userReadOnly_) - r->userReadOnly_ = true; - if (userWidgetToContent_) { - r->userWidgetToContent_ = true; - r->userFixedWidget_ = true; - } - r->propagateFlagsTopToBottom(); - } -} - -void PropertyRow::setTooltip(const char* tooltip) -{ - tooltip_ = tooltip; -} - -bool PropertyRow::setValidatorEntry(int index, int count) -{ - if (index != validatorIndex_ || count != validatorCount_) { - validatorIndex_ = min(index, 0xffff); - validatorCount_ = min(count, 0xff); - validatorsHeight_ = 0; - return true; - } - return false; -} - -void PropertyRow::resetValidatorIcons() -{ - validatorHasWarnings_ = false; - validatorHasErrors_ = false; -} - -void PropertyRow::addValidatorIcons(bool hasWarnings, bool hasErrors) -{ - if (hasWarnings ) - validatorHasWarnings_ = true; - if (hasErrors) - validatorHasErrors_ = true; -} - -void PropertyRow::updateLabel(const QPropertyTree* tree, [[maybe_unused]] int index, bool parentHidesNonInlineChildren) -{ - if (!labelChanged_) { - if (pulledUp_) - parent()->hasPulled_ = true; - return; - } - - hasPulled_ = false; - - int numChildren = (int)children_.size(); - for (int i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - row->updateLabel(tree, i, hideChildren_); - } - - parseControlCodes(tree, label_, true); - bool hiddenByParentFlag = parentHidesNonInlineChildren && !pulledUp_; - visible_ = (*labelUndecorated_ != '\0' || userFullRow_ || pulledUp_ || isRoot()) && !hiddenByParentFlag; - - propagateFlagsTopToBottom(); - - if(pulledContainer()) - pulledContainer()->_setExpanded(expanded()); - - layoutChanged_ = true; - labelChanged_ = false; -} - -struct ResetSerializerOp{ - ScanResult operator()(PropertyRow* row) - { - row->setSerializer(SStruct()); - return SCAN_CHILDREN_SIBLINGS; - } -}; - -void PropertyRow::parseControlCodes(const QPropertyTree* tree, const char* ptr, bool changeLabel) -{ - if (changeLabel) { - userFullRow_ = false; - pulledUp_ = false; - pulledBefore_ = false; - userFixedWidget_ = false; - userPackCheckboxes_ = false; - userWidgetSize_ = -1; - userWidgetToContent_ = false; - fontWeight_ = FontWeight::Undefined; - userNonCopyable_ = false; - } - - while(true){ - if(*ptr == '^'){ - if(parent() && !parent()->isRoot()){ - if(pulledUp_) - pulledBefore_ = true; - pulledUp_ = true; - parent()->hasPulled_ = true; - - if(pulledUp() && isContainer()) - parent()->setPulledContainer(this); - } - } - else if(*ptr == '='){ - userWidgetToContent_ = true; - } - else if(*ptr == '+'){ - bool isFirstUpdate = labelUndecorated_ == 0; - if (isFirstUpdate) - _setExpanded(true); - } - else if(*ptr == '-'){ - bool isFirstUpdate = labelUndecorated_ == 0; - if (isFirstUpdate) - _setExpanded(false); - } - else if(*ptr == '<') - userFullRow_ = true; - else if(*ptr == '>'){ - userFixedWidget_ = true; - const char* p = ++ptr; - while(*p >= '0' && *p <= '9') - ++p; - if(*p == '>'){ - userWidgetSize_ = atoi(ptr); - ptr = ++p; - } - continue; - } - else if(*ptr == '~'){ - ResetSerializerOp op; - scanChildren(op); - } - else if(*ptr == '!'){ - if(userReadOnly_) - userReadOnlyRecurse_ = true; - userReadOnly_ = true; - } - else if(*ptr == '|'){ - userPackCheckboxes_ = true; - } - else if(*ptr == '['){ - ++ptr; - PropertyRow::iterator it; - for(it = children_.begin(); it != children_.end(); ++it) - (*it)->parseControlCodes(tree, ptr, false); - - int counter = 1; - while(*ptr){ - if(*ptr == ']' && !--counter) - break; - else if(*ptr == '[') - ++counter; - ++ptr; - } - } - else if(*ptr == '@'){ - switch (ptr[1]) - { - case 'b': case 'B': - fontWeight_ = FontWeight::Bold; - ++ptr; - break; - - case 'r': case 'R': - fontWeight_ = FontWeight::Regular; - ++ptr; - break; - - default: - break; - } - } - else if(*ptr == ':'){ - userNonCopyable_ = true; - } - else - break; - ++ptr; - } - - if (isContainer()) { - // automatically inline children for short arrays - PropertyRowContainer* container = static_cast(this); - int numChildren = (int)container->count(); - if (container->isFixedSize() && numChildren > 0 && numChildren <= 4) { - if (container->childByIndex(0)->inlineInShortArrays()) { - for(int i = 0; i < numChildren; ++i) { - PropertyRow* child = container->childByIndex(i); - child->pulledUp_ = true; - if (child->label_) - child->labelUndecorated_ = child->label_ + strlen(child->label_); - } - hasPulled_ = true; - container->setInlined(true); - } - } - } - - if (changeLabel) - labelUndecorated_ = ptr; - - labelChanged(); -} - -const char* PropertyRow::typeNameForFilter([[maybe_unused]] QPropertyTree* tree) const -{ - return typeName(); -} - -void PropertyRow::updateTextSizeInitial(const QPropertyTree* tree, int index, bool fontChanged) -{ - char containerLabel[1024] = ""; - const char* text = rowText(containerLabel, sizeof(containerLabel), tree, index); - if(text[0] == '\0' || widgetPlacement() == WIDGET_INSTEAD_OF_TEXT) { - textSizeInitial_ = 0; - textHash_ = 0; - } - else{ - unsigned hash = calculateHash(text); - const QFont* font = rowFont(tree); - hash = calculateHash(font, hash); - if(hash != textHash_ || fontChanged){ - QFontMetrics fm(*font); - textSizeInitial_ = fm.horizontalAdvance(text); - textHash_ = hash; - } - } -} - -void PropertyRow::calculateMinimalSize(const QPropertyTree* tree, int posX, int availableWidth, bool force, int* _extraSizeRemainder, int* _extraSize, int index) -{ - PropertyRow* nonPulled = nonPulledParent(); - if (!layoutChanged_ && !force && !nonPulled->layoutChanged_) { - DEBUG_TRACE_ROW("... skipping size for %s", label()); - return; - } - plusSize_ = 0; - if(isRoot()) - expanded_ = true; - else{ - if(nonPulled->isRoot() || (tree->treeStyle().compact && nonPulled->parent()->isRoot())) - _setExpanded(true); - else if(!pulledUp()) - plusSize_ = int(tree->treeStyle().firstLevelIndent * tree->_defaultRowHeight()); - - if(parent()->pulledUp()) - pulledBefore_ = false; - - if(!visible(tree) && !(isContainer() && pulledUp())){ - size_ = QPoint(0, 0); - DEBUG_TRACE_ROW("row '%s' got zero size", label()); - layoutChanged_ = false; - return; - } - } - - int minWidgetSize = widgetSizeMin(tree); - widgetSize_ = minWidgetSize; - if (_extraSizeRemainder && *_extraSizeRemainder) { - widgetSize_ += *_extraSizeRemainder; - *_extraSizeRemainder = 0; - } - - updateTextSizeInitial(tree, index, force); - - int height = isRoot() ? 0 : tree->_defaultRowHeight() + floorHeight(); - size_.setY(height); - - pos_.setX(posX); - posX += plusSize_; - - int extraSizeStorage = 0; - int& extraSize = !pulledUp() || !_extraSize ? extraSizeStorage : *_extraSize; - - int validatorIconsWidth = 0; - if (validatorHasErrors_) - validatorIconsWidth += tree->_defaultRowHeight(); - if (validatorHasWarnings_) - validatorIconsWidth += tree->_defaultRowHeight(); - - int freePulledChildren = 0; - if(!pulledUp()){ - int minTextSize = 0; - int totalMinimalWidth = 0; - calcPulledRows(&minTextSize, &freePulledChildren, &totalMinimalWidth, tree, index); - DEBUG_TRACE_ROW("%s minTextSize: %i, totalMinimalWidth: %i", label(), minTextSize, totalMinimalWidth); - size_.setX(totalMinimalWidth); - extraSize = (tree->rightBorder() - tree->leftBorder()) - totalMinimalWidth - posX - validatorIconsWidth; - DEBUG_TRACE_ROW("%s extraSize 0: %i", label(), extraSize); - - float textScale = 1.0f; - bool hideOwnText = false; - if(extraSize < 0){ - // hide container item text first - if (parent() && parent()->isContainer()){ - extraSize += textSizeInitial_; - minTextSize -= textSizeInitial_; - hideOwnText = true; - } - - textScale = minTextSize ? clamp(1.0f - float(-extraSize) / minTextSize, 0.0f, 1.0f) : 0; - } - setTextSize(tree, index, textScale); - - if (hideOwnText) { - textSize_ = 0; - DEBUG_TRACE_ROW("%s hideOwnText", label()); - } - } - - DEBUG_TRACE_ROW("%s extraSize 1: %i", label(), extraSize); - - WidgetPlacement widgetPlace = widgetPlacement(); - - int numChildren = (int)children_.size(); - - if(widgetPlace == WIDGET_ICON){ - if (tree->treeStyle().alignLabelsToRight && !pulledUp_ && !pulledBefore_ && !hasPulled_ && numChildren == 0) - widgetPos_ = widgetSize_ ? tree->leftBorder() + xround((tree->rightBorder() - tree->leftBorder())* (1.f - tree->treeStyle().valueColumnWidth)) : -1000; - else - widgetPos_ = widgetSize_ ? posX : -1000; - posX += widgetSize_; - if (tree->treeStyle().alignLabelsToRight) - textPos_ = widgetPos_ + widgetSize_ + TEXT_VALUE_SPACING; - else - textPos_ = posX; - posX += textSize_; - } - - bool hasPulledBefore = false; - if (hasPulled_) { - for (int i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(row->visible(tree) && row->pulledBefore()){ - row->calculateMinimalSize(tree, posX, availableWidth, force, 0, &extraSize, i); - posX += row->size_.x(); - hasPulledBefore = true; - } - } - if (hasPulledBefore) - posX += TEXT_VALUE_SPACING; - } - - if(widgetPlace != WIDGET_ICON){ - textPos_ = posX; - posX += textSize_; - } - - if(widgetPlace == WIDGET_AFTER_NAME){ - if (textSize_) - posX += TEXT_VALUE_SPACING; - widgetPos_ = posX; - posX += widgetSize_; - } - - if (widgetPlace == WIDGET_INSTEAD_OF_TEXT) - widgetPos_ = posX; - - if(widgetPlace == WIDGET_VALUE || widgetPlace == WIDGET_AFTER_PULLED || (freePulledChildren > 0)){ - if (textSize_) - posX += TEXT_VALUE_SPACING; - - if(!pulledUp() && extraSize > 0){ - // align widget value to value column - if(!isFullRow(tree)) - { - int oldX = posX; - - bool rightAlignment = tree->treeStyle().alignLabelsToRight && !hasPulledBefore; - int maxX = rightAlignment ? textSize_ + TEXT_VALUE_SPACING: posX; - int newX = max(tree->leftBorder() + xround((tree->rightBorder() - tree->leftBorder())* (1.f - tree->treeStyle().valueColumnWidth)), maxX); - - if (rightAlignment) { - textPos_ = newX - textSize_ - TEXT_VALUE_SPACING; - widgetPos_ = textPos_ - widgetSize_ - TEXT_VALUE_SPACING; - } - - int xDelta = newX - oldX; - if (xDelta <= extraSize) - { - extraSize -= xDelta; - posX = newX; - } - else - { - posX += extraSize; - extraSize = 0; - } - } - } - } - - int extraSizeRemainder = 0; - if (freePulledChildren > 0) { - extraSizeRemainder = extraSize % freePulledChildren; - extraSize = extraSize / freePulledChildren; - } - - if (widgetPlace == WIDGET_VALUE || widgetPlace == WIDGET_INSTEAD_OF_TEXT) { - if(minWidgetSize && !isWidgetFixed() && extraSize > 0) { - DEBUG_TRACE_ROW("%s widget extraSize: %i+%d", label(), extraSize, extraSizeRemainder); - widgetSize_ += extraSize + extraSizeRemainder; - extraSizeRemainder = 0; - } - - if (widgetPlace != WIDGET_INSTEAD_OF_TEXT) - widgetPos_ = posX; - DEBUG_TRACE_ROW("textSize: %i widgetPos: %i", int(textSize_), int(widgetPos_)); - posX += widgetSize_; - } - - size_.setX(textSize_ + (textSize_ ? TEXT_VALUE_SPACING : 0) + widgetSize_ + validatorIconsWidth); - - int childrenLeft = nonPulled->pos_.x(); - if (parent() != 0){ - if (parent()->parent() == 0) { - if (!tree->treeStyle().doNotIndentSecondLevel) - childrenLeft = aznumeric_cast(childrenLeft + tree->treeStyle().firstLevelIndent * tree->_defaultRowHeight()); - } - else - childrenLeft = aznumeric_cast(childrenLeft + tree->treeStyle().levelIndent * tree->_defaultRowHeight()); - } - - int checkBoxChildren = 0; - for (int i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(!row->visible(tree)) { - DEBUG_TRACE_ROW("skipping invisible child: %s", row->label()); - continue; - } - if(row->pulledUp()){ - if(!row->pulledBefore()){ - row->calculateMinimalSize(tree, posX, availableWidth, force, &extraSizeRemainder, &extraSize, i); - posX += row->size_.x(); - posX += TEXT_VALUE_SPACING; - } - size_.setX(size_.x() + TEXT_VALUE_SPACING + row->size_.x()); - size_.setY(max(size_.y(), row->size_.y())); - } - else if(expanded()){ - - row->calculateMinimalSize(tree, childrenLeft, availableWidth, force, 0, &extraSize, i); - if (row->widgetPlacement() == WIDGET_ICON && row->count() == 0) - ++checkBoxChildren; - } - } - - // align checkboxes into two columns - if (tree->packCheckboxes() || userPackCheckboxes_) { - if (expanded() && checkBoxChildren > 0 && hasVisibleChildren(tree)) { - int widthTotal = tree->rightBorder() - 16 - childrenLeft - plusSize_; - int widthNextToLastCheckbox = 0; - int left = childrenLeft + plusSize_; - PropertyRow* previousCheckbox = nullptr; - - std::vector checkboxesToRealign; - bool hasChanges = false; - - for (int i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(!row->visible(tree)) - continue; - if(row->widgetPlacement() != WIDGET_ICON || row->count() > 0) { - previousCheckbox = 0; - continue; - } - if(!row->pulledUp()){ - int checkboxWidth = row->textSize_ + tree->_defaultRowHeight()/* + TEXT_VALUE_SPACING*/; - - if (previousCheckbox && widthNextToLastCheckbox >= widthTotal / 2 && checkboxWidth < widthTotal / 2) { - row->packedAfterPreviousRow_ = true; - widthNextToLastCheckbox = 0; - - row->pos_.setX(left + widthTotal / 2); - row->widgetPos_ = row->pos_.x(); - row->textPos_ = row->pos_.x() + row->widgetSize_; - row->size_.setX(widthTotal / 2); - - previousCheckbox->size_.setX(widthTotal / 2); - previousCheckbox->pos_.setX(left); - previousCheckbox->widgetPos_ = left; - previousCheckbox->textPos_ = left + previousCheckbox->widgetSize_; - row->size_.setX(widthTotal / 2); - previousCheckbox = 0; - hasChanges = true; - } - else { - row->packedAfterPreviousRow_ = false; - widthNextToLastCheckbox = widthTotal - checkboxWidth; - previousCheckbox = row; - } - - if (previousCheckbox && tree->treeStyle().alignLabelsToRight) - checkboxesToRealign.push_back(previousCheckbox); - } - } - - if (hasChanges) { - for (int i = 0; i < checkboxesToRealign.size(); ++i) { - PropertyRow* row = checkboxesToRealign[i]; - row->size_.setX(widthTotal / 2); - row->pos_.setX(left); - row->widgetPos_ = left; - row->textPos_ = left + row->widgetSize_; - } - } - } - } - - if (widgetPlace == WIDGET_AFTER_PULLED) - { - posX += TEXT_VALUE_SPACING; - widgetPos_ = posX; - } - - if(!pulledUp()) - size_.setX(tree->rightBorder() - pos_.x()); - DEBUG_TRACE_ROW("calculateMinimalSize: '%s' %i %i (%s)", label(), size_.x(), size_.y(), isRoot() ? "root" : "non-root"); - layoutChanged_ = false; - - validatorsHeight_ = 0; - if (!pulledUp() && !pulledBefore() && (validatorCount_ != 0 || hasPulled_)) { - QFontMetrics fm(tree->font()); - int padding = aznumeric_cast(0.1f * tree->_defaultRowHeight()); - auto calculateValidatorHeight = [&](PropertyRow* row) { - const ValidatorEntry* entries = tree->_validatorBlock()->GetEntry(row->validatorIndex_, row->validatorCount_); - if (entries) { - for (int i = 0; i < row->validatorCount_; ++i) { - int startPos = pos_.x() + plusSize_; - QRect r = fm.boundingRect(0, 0, availableWidth - startPos - tree->_defaultRowHeight() - padding * 2, 0, - Qt::TextWordWrap|Qt::AlignTop, QString::fromUtf8(entries[i].message.c_str())); - validatorsHeight_ += max(tree->_defaultRowHeight(), r.height() + padding * 2) + padding * 3; - } - } - }; - calculateValidatorHeight(this); - visitPulledRows(this, calculateValidatorHeight); - } - - size_.setY(size_.y() + validatorsHeight_); -} - -void PropertyRow::adjustVerticalPosition(const QPropertyTree* tree, int& totalHeight) -{ - int defaultRowHeight = tree->_defaultRowHeight(); - pos_.setY(totalHeight); - int rowHeight = size_.y() + int(defaultRowHeight * (tree->treeStyle().rowSpacing - 1.0f) + 0.5f); - - if (packedAfterPreviousRow_) - pos_.setY(totalHeight - rowHeight); - else - pos_.setY(totalHeight); - - if(!pulledUp()) { - if (!packedAfterPreviousRow_) - totalHeight += rowHeight; - } - else{ - pos_.setY(parent()->pos_.y()); - expanded_ = parent()->expanded(); - } - PropertyRow* nonPulled = nonPulledParent(); - - DEBUG_TRACE_ROW("adjustRect: %s %i %i %i %i %s", label(), pos_.x(), pos_.y(), size_.x(), size_.y(), pulledUp() ? "pulled" : ""); - - if (expanded_ || hasPulled_) { - for(PropertyRows::iterator it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* row = *it; - if(row->visible(tree) && (nonPulled->expanded() || row->pulledUp())) - row->adjustVerticalPosition(tree, totalHeight); - } - } - int delta = totalHeight - pos_.y(); - if (delta > USHRT_MAX) - delta = USHRT_MAX; - heightIncludingChildren_ = delta; -} - -void PropertyRow::setTextSize(const QPropertyTree* tree, int index, float mult) -{ - updateTextSizeInitial(tree, index, false); - - textSize_ = int(textSizeInitial_ * mult); - - size_t numChildren = children_.size(); - for (size_t i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(row->pulledUp()) - row->setTextSize(tree, 0, mult); - } -} - -void PropertyRow::calcPulledRows(int* minTextSize, int* freePulledChildren, int* minimalWidth, const QPropertyTree *tree, int index) -{ - updateTextSizeInitial(tree, index, false); - - *minTextSize += textSizeInitial_; - WidgetPlacement widgetPlace = widgetPlacement(); - if((widgetPlace == WIDGET_VALUE || widgetPlace == WIDGET_INSTEAD_OF_TEXT || widgetPlace == WIDGET_AFTER_PULLED) && !isWidgetFixed()) - *freePulledChildren += 1; - *minimalWidth += textSizeInitial_ + widgetSizeMin(tree); // spacing - bool hasWidget = widgetPlace == WIDGET_VALUE || - widgetPlace == WIDGET_INSTEAD_OF_TEXT || - widgetPlace == WIDGET_AFTER_PULLED; - if (textSizeInitial_ && (hasWidget || hasPulled_)) - *minimalWidth += TEXT_VALUE_SPACING; - if (hasWidget && hasPulled_) - *minimalWidth += TEXT_VALUE_SPACING; - - size_t numChildren = children_.size(); - int pulledCount = 0; - for (size_t i = 0; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(row->pulledUp()) - { - ++pulledCount; - row->calcPulledRows(minTextSize, freePulledChildren, minimalWidth, tree, index); - } - } - if (hasPulled_) - *minimalWidth += (pulledCount - 1) * TEXT_VALUE_SPACING; -} - -PropertyRow* PropertyRow::findSelected() -{ - if(selected()) - return this; - iterator it; - for(it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* result = (*it)->findSelected(); - if(result) - return result; - } - return 0; -} - -PropertyRow* PropertyRow::find(const char* name, const char* nameAlt, const char* typeName) -{ - iterator it; - for(it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* row = *it; - if(((row->name() == name) || strcmp(row->name(), name) == 0) && - ((nameAlt == 0) || (row->label() != 0 && strcmp(row->label(), nameAlt) == 0)) && - ((typeName == 0) || (row->typeName() != 0 && strcmp(row->typeName(), typeName) == 0))) - return row; - } - return 0; -} - -PropertyRow* PropertyRow::findFromIndex(int* outIndex, const char* name, const char* typeName, int startIndex) const -{ - int numChildren = (int)children_.size(); - startIndex = min(startIndex, numChildren); - - for (int i = startIndex; i < numChildren; ++i) { - PropertyRow* row = children_[i]; - if(((row->name() == name) || strcmp(row->name(), name) == 0) && - ((row->typeName() == typeName || strcmp(row->typeName(), typeName) == 0))) { - *outIndex = i; - return row; - } - } - - for (int i = 0; i < startIndex; ++i) { - PropertyRow* row = children_[i]; - if(((row->name() == name) || strcmp(row->name(), name) == 0) && - ((row->typeName() == typeName || strcmp(row->typeName(), typeName) == 0))) { - *outIndex = i; - return row; - } - } - - *outIndex = -1; - return 0; -} - -const PropertyRow* PropertyRow::find(const char* name, const char* nameAlt, const char* typeName) const -{ - return const_cast(this)->find(name, nameAlt, typeName); -} - -bool PropertyRow::processesKey([[maybe_unused]] QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete && ev->modifiers() == Qt::NoModifier) - { - return true; - } - else if (ev->key() == Qt::Key_Insert && ev->modifiers() == Qt::SHIFT) - { - return true; - } - - return false; -} - -bool PropertyRow::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if(parent() && parent()->isContainer() && !parent()->userReadOnly()){ - PropertyRowContainer* container = static_cast(parent()); - std::unique_ptr menuHandler = - std::unique_ptr(createMenuHandler(tree, container)); - menuHandler->element = this; - if(ev->key() == Qt::Key_Delete && ev->modifiers() == Qt::NoModifier) { - menuHandler->onMenuChildRemove(); - return true; - } - else if(ev->key() == Qt::Key_Insert && ev->modifiers() == Qt::SHIFT){ - menuHandler->onMenuChildInsertBefore(); - return true; - } - } - return false; -} - -ContainerMenuHandler* PropertyRow::createMenuHandler(QPropertyTree* tree, PropertyRowContainer* container) -{ - return new ContainerMenuHandler(tree, container); -} - -bool PropertyRow::onContextMenu(QMenu &menu, QPropertyTree* tree) -{ - PropertyRowContainer* container = 0; - if (parent() && parent()->isContainer()) - container = static_cast(parent()); - if (!container) { - PropertyRow* nonPulled = nonPulledParent(); - if (nonPulled->parent() && nonPulled->parent()->isContainer()) - container = static_cast(nonPulled->parent()); - } - if(container){ - PropertyRow* containerElement = this; - ContainerMenuHandler* handler = createMenuHandler(tree, container); - handler->element = containerElement; - tree->addMenuHandler(handler); - if(!container->isFixedSize()){ - if(!menu.isEmpty()) - { - menu.addSeparator(); - } - - menu.addAction("Insert Before", handler, SLOT(onMenuChildInsertBefore()), QKeySequence("Shift+Insert"))->setEnabled(!container->userReadOnly()); - menu.addAction("Remove", handler, SLOT(onMenuChildRemove()), QKeySequence("Delete"))->setEnabled(!container->userReadOnly()); - } - } - - if(hasVisibleChildren(tree)){ - if(!menu.isEmpty()) - { - menu.addSeparator(); - } - - menu.addAction("Expand", tree, SLOT(expandAll())); - menu.addAction("Collapse", tree, SLOT(collapseAll())); - } - - return !menu.isEmpty(); -} - -int PropertyRow::level() const -{ - int result = 0; - const PropertyRow* row = this; - while(row){ - row = row->parent(); - ++result; - } - return result; -} - -PropertyRow* PropertyRow::nonPulledParent() -{ - PropertyRow* row = this; - while(row->pulledUp()) - row = row->parent(); - return row; -} - -bool PropertyRow::pulledSelected() const -{ - if(selected()) - return true; - const PropertyRow* row = this; - while(row->parent() && row->pulledUp()){ - row = row->parent(); - if(row->selected()) - return true; - } - return false; -} - - -const QFont* PropertyRow::rowFont(const QPropertyTree* tree) const -{ - switch (fontWeight_) - { - case FontWeight::Regular: - return &tree->font(); - - case FontWeight::Bold: - return &tree->_boldFont(); - - default: - // Bold for structures/containers - return hasVisibleChildren(tree) || (isContainer() && !static_cast(this)->isInlined()) ? &tree->_boldFont() : &tree->font(); - } -} - -QRect PropertyRow::rectIncludingChildren(const QPropertyTree* tree) const -{ - QRect r = rect(); - if (expanded()) - for (size_t i = 0; i < children_.size(); ++i) - if (children_[i]->visible(tree)) - r = r.united(children_[i]->rectIncludingChildren(tree)); - return r; -} - -static void drawVerticalGradient(QPainter& painter, const QRect& rect, const QColor& topColor, const QColor& bottomColor) -{ - QLinearGradient gradient(rect.left(), rect.top(), rect.left(), rect.bottom()); - gradient.setColorAt(0.0f, topColor); - gradient.setColorAt(1.0f, bottomColor); - painter.fillRect(rect, QBrush(gradient)); -} - - -void PropertyRow::drawRow(QPainter& painter, const QPropertyTree* tree, int index, bool selectionPass) -{ - QRect rowRect = rect(); - QRect selectionRect = rowRect; - if (!isRoot()) { - bool selectionDrawn = !tree->hideSelection() || tree->hasFocusOrInplaceHasFocus(); - if(!pulledUp()) - selectionRect = rowRect.adjusted(plusSize_ - (tree->treeStyle().compact ? 2 : 3), -2, 1, 1); - else - selectionRect = rowRect.adjusted(-2, -2, 2, 1); - if (selectionPass) { - if (tree->treeStyle().groupShadows && this->level() == 2 && !children_.empty()) { - QRect childrenRect = this->rectIncludingChildren(tree); - int top = rowRect.bottom() + 2; - if (top < childrenRect.bottom()) - { - childrenRect = QRect(-tree->leftBorder(), top, tree->width() - 16 + tree->leftBorder(), childrenRect.bottom() + 3 - top); - QColor windowColor = tree->palette().color(QPalette::Button); - QColor shadowColor = tree->palette().color(QPalette::Mid); - QColor backgroundColor(interpolateColor(windowColor, shadowColor, tree->treeStyle().groupShade)); - painter.fillRect(childrenRect, QBrush(backgroundColor)); - - int levelShadowOpacity = tree->treeStyle().levelShadowOpacity; - int h = int(tree->_defaultRowHeight() * 0.75f); - drawVerticalGradient(painter, QRect(childrenRect.left()+1, childrenRect.top(), childrenRect.width()-2, h), QColor(0, 0, 0, levelShadowOpacity), QColor(0, 0, 0, 0)); - drawVerticalGradient(painter, QRect(childrenRect.left(), childrenRect.top(), 1, h*2), QColor(0, 0, 0, levelShadowOpacity), QColor(0, 0, 0, 0)); - drawVerticalGradient(painter, QRect(childrenRect.width()-2, childrenRect.top(), 1, h*2), QColor(0, 0, 0, levelShadowOpacity), QColor(0, 0, 0, 0)); - - h = (int(tree->_defaultRowHeight() * 0.25f)); - drawVerticalGradient(painter, QRect(childrenRect.left() + 1, childrenRect.bottom() - h, childrenRect.width() - 2, h), QColor(0, 0, 0, 0), QColor(0, 0, 0, levelShadowOpacity)); - drawVerticalGradient(painter, QRect(childrenRect.left(), childrenRect.bottom() - h*2, 1, h*2), QColor(0, 0, 0, 0), QColor(0, 0, 0, levelShadowOpacity)); - drawVerticalGradient(painter, QRect(childrenRect.width()-2, childrenRect.bottom() - h*2, 1, h*2), QColor(0, 0, 0, 0), QColor(0, 0, 0, levelShadowOpacity)); - } - } - if (tree->treeStyle().groupRectangle && this->level() < 3 && (canBeToggled(tree) || isContainer() || widgetPlacement() == WIDGET_NONE)) - { - QColor windowColor = tree->palette().color(QPalette::Button); - QColor shadowColor = tree->palette().color(QPalette::Mid); - QColor backgroundColor(interpolateColor(windowColor, shadowColor, tree->treeStyle().groupShade)); - painter.setRenderHint(QPainter::Antialiasing, true); - painter.setBrush(QBrush(backgroundColor)); - painter.setPen(Qt::NoPen); - painter.drawRoundedRect(rowRect.adjusted(0, tree->_defaultRowHeight() / 8, 0, -tree->_defaultRowHeight() / 8), 4, 4); - painter.setRenderHint(QPainter::Antialiasing, false); - - } - } - else{ - PropertyDrawContext context; - context.tree = tree; - context.widgetRect = widgetRect(tree); - context.lineRect = floorRect(tree); - context.painter = &painter; - context.captured = tree->_isCapturedRow(this); - context.m_pressed = tree->_pressedRow() == this; - - QColor textColor = tree->palette().buttonText().color(); - - char containerLabel[1024] = ""; - wstring text = toWideChar(rowText(containerLabel, sizeof(containerLabel), tree, index)); - - if (tree->treeStyle().showHorizontalLines) { - if(textSize_ && !isStatic() && widgetPlacement() == WIDGET_VALUE && - !pulledUp() && !isFullRow(tree) && !hasPulled() && floorHeight() == 0) - { - QRect rect(textPos_ - 1, rowRect.bottom() - 2, context.lineRect.width() - (textPos_ - 1), 1); - - QLinearGradient gradient(rect.left(), rect.top(), rect.right(), rect.top()); - gradient.setColorAt(0.0f, tree->palette().color(QPalette::Button)); - gradient.setColorAt(0.6f, tree->palette().color(QPalette::Light)); - gradient.setColorAt(0.95f, tree->palette().color(QPalette::Light)); - gradient.setColorAt(1.0f, tree->palette().color(QPalette::Button)); - QBrush brush(gradient); - painter.fillRect(rect, brush); - } - } - - - if(selectionDrawn && pulledSelected()){ - textColor = tree->palette().highlight().color(); - } - else{ - overrideTextColor(textColor); - } - - if(!tree->treeStyle().compact || !parent()->isRoot()){ - if(hasVisibleChildren(tree)){ - drawPlus(painter, tree, plusRect(tree), expanded(), selected(), expanded()); - } - } - - if(!isStatic() && context.widgetRect.isValid()) - redraw(context); - - if(textSize_ > 0){ - const QFont* font = rowFont(tree); - tree->_drawRowLabel(painter, text.c_str(), font, textRect(tree), textColor); - } - - if (validatorHasWarnings_) { - QImage* icon = tree->_iconCache()->getImageForIcon(Serialization::IconXPM(warning_xpm)); - - QRect r = validatorWarningIconRect(tree); - r.setWidth(tree->_defaultRowHeight()); - painter.drawImage(r.center() - QPoint(icon->width() / 2, icon->height() / 2), *icon); - } - if (validatorHasErrors_) { - QImage* icon = tree->_iconCache()->getImageForIcon(Serialization::IconXPM(error_xpm)); - QRect r = validatorErrorIconRect(tree); - r.setWidth(tree->_defaultRowHeight()); - painter.drawImage(r.center() - QPoint(icon->width() / 2, icon->height() / 2), *icon); - } - } - } - - if (!selectionPass && validatorsHeight_ > 0) - { - QRect totalRect = validatorRect(tree); - QFontMetrics fm(tree->font()); - const int padding = aznumeric_cast(tree->_defaultRowHeight() * 0.1f); - int offset = padding; - auto drawFunc = [&](PropertyRow* row) { - if (const ValidatorEntry* validatorEntries = tree->_validatorBlock()->GetEntry(row->validatorIndex_, row->validatorCount_)) { - for (int i = 0; i < row->validatorCount_; ++i) { - const ValidatorEntry* validatorEntry = validatorEntries + i; - bool isError = validatorEntry->type == VALIDATOR_ENTRY_ERROR; - - QImage* icon = tree->_iconCache()->getImageForIcon(isError ? Serialization::IconXPM(error_xpm) : Serialization::IconXPM(warning_xpm)); - QColor brushColor = isError ? QColor(255, 64, 64, 192) : QPalette().color(QPalette::ToolTipBase); - QColor penColor = isError ? QColor(64, 0, 0, 255) : QPalette().color(QPalette::ToolTipText); - - QRect rect(totalRect.left(), totalRect.top() + offset, - totalRect.width(), totalRect.height() - offset); - QRect textRect = rect.adjusted(tree->_defaultRowHeight() + padding, padding, -padding, -padding); - const char* text = validatorEntry->message.c_str(); - int textHeight = max(tree->_defaultRowHeight(), - fm.boundingRect(textRect, Qt::TextWordWrap, text, 0, 0).height() + padding * 2); - rect.setHeight(textHeight + padding * 2); - textRect.setHeight(textHeight); - - QPen pen(penColor); - pen.setWidth(1); - painter.setPen(QPen(penColor)); - painter.setRenderHint(QPainter::Antialiasing); - painter.setBrush(brushColor); - painter.translate(-0.5f, -0.5f); - painter.drawRoundedRect(rect, 5, 5, Qt::AbsoluteSize); - painter.translate(0.5f, 0.5f); - painter.setPen(penColor); - painter.setBrush(QBrush()); - QTextOption opt; - opt.setWrapMode(QTextOption::WordWrap); - opt.setAlignment(Qt::AlignLeft | Qt::AlignVCenter); - painter.drawText(textRect, text, opt); - textRect.setHeight(0xffff); - QRect iconRect(rect.left(), rect.top(), tree->_defaultRowHeight(), rect.height()); - painter.drawImage(iconRect.center() - QPoint(icon->width() / 2, icon->height() / 2), *icon); - offset += rect.height() + padding; - } - } - }; - drawFunc(this); - visitPulledRows(this, drawFunc); - } -} - -void PropertyRow::drawPlus(QPainter& p, const QPropertyTree* tree, const QRect& rect, bool expanded, [[maybe_unused]] bool selected, [[maybe_unused]] bool grayed) const -{ - QStyleOption option; - option.rect = rect; - option.state = QStyle::State_Enabled | QStyle::State_Children; - if (expanded) - option.state |= QStyle::State_Open; - p.setPen(QPen()); - p.setBrush(QBrush()); - - // create a widget for context so that the stylesheet is applied: - QWidget tempWidgetForContext; - QStyle::PrimitiveElement elementToUse = QStyle::PE_IndicatorArrowRight; - if (expanded) - elementToUse = QStyle::PE_IndicatorArrowDown; - - tree->style()->drawPrimitive(elementToUse, &option, &p, &tempWidgetForContext); -} - -bool PropertyRow::visible(const QPropertyTree* tree) const -{ - if (tree->_isDragged(this)) - return false; - return ((visible_ || !tree->hideUntranslated()) && (matchFilter_ || belongsToFilteredRow_)); -} - -bool PropertyRow::canBeToggled(const QPropertyTree* tree) const -{ - if(!visible(tree)) - return false; - if((tree->treeStyle().compact && (parent() && parent()->isRoot())) || (isContainer() && pulledUp()) || !hasVisibleChildren(tree)) - return false; - return !empty(); -} - -bool PropertyRow::canBeDragged() const -{ - if(parent()){ - if(parent()->isContainer()) - return true; - } - return false; -} - -bool PropertyRow::canBeDroppedOn(const PropertyRow* parentRow, const PropertyRow* beforeChild, const QPropertyTree* tree) const -{ - YASLI_ASSERT(parentRow); - - if(parentRow->pulledContainer()) - parentRow = parentRow->pulledContainer(); - - if(parentRow->isContainer()){ - const PropertyRowContainer* container = static_cast(parentRow); - - if((container->isFixedSize() || container->userReadOnly()) && parent() != parentRow) - return false; - - if(beforeChild && beforeChild->parent() != parentRow) - return false; - - const PropertyRow* defaultRow = container->defaultRow(tree->model()); - if(defaultRow && strcmp(defaultRow->typeName(), typeName()) == 0) - return true; - } - return false; -} - -void PropertyRow::dropInto(PropertyRow* parentRow, PropertyRow* cursorRow, QPropertyTree* tree, bool before) -{ - SharedPtr ref(this); - - PropertyTreeModel* model = tree->model(); - PropertyTreeModel::UpdateLock lock = model->lockUpdate(); - if(parentRow->pulledContainer()) - parentRow = parentRow->pulledContainer(); - if(parentRow->isContainer()){ - tree->model()->rowAboutToBeChanged(tree->model()->root()); // FIXME: select optimal row - setSelected(false); - PropertyRow* oldParent = parent(); - TreePath oldParentPath = tree->model()->pathFromRow(oldParent); - oldParent->erase(this); - if(before) - parentRow->addBefore(this, cursorRow); - else - parentRow->addAfter(this, cursorRow); - model->selectRow(this, true); - TreePath thisPath = tree->model()->pathFromRow(this); - TreePath parentRowPath = tree->model()->pathFromRow(parentRow); - oldParent = tree->model()->rowFromPath(oldParentPath); - if (oldParent) - model->rowChanged(oldParent); // after this call we can get invalid this - if(PropertyRow* newThis = tree->model()->rowFromPath(thisPath)) { - TreeSelection selection; - selection.push_back(thisPath); - model->setSelection(selection); - - // we use path to obtain new row - tree->ensureVisible(newThis); - model->rowChanged(newThis); // after this call row pointers are invalidated - } - parentRow = tree->model()->rowFromPath(parentRowPath); - if (parentRow) - model->rowChanged(parentRow); // after this call row pointers are invalidated - } -} - -void PropertyRow::intersect(const PropertyRow* row) -{ - setMultiValue(multiValue() || row->multiValue() || valueAsString() != row->valueAsString()); - - - int indexSource = 0; - for(int i = 0; i < int(children_.size()); ++i) - { - PropertyRow* testRow = children_[i]; - PropertyRow* matchingRow = row->findFromIndex(&indexSource, testRow->name_, testRow->typeName_, indexSource); - ++indexSource; - if (matchingRow == 0) { - children_.erase(children_.begin() + i); - --i; - } - else { - children_[i]->intersect(matchingRow); - } - } -} - -const char* PropertyRow::rowText(char *containerLabelBuffer, size_t bufsiz, const QPropertyTree* tree, int index) const -{ - if(parent() && parent()->isContainer() && !pulledUp()){ - if (tree->showContainerIndices()) { - if (tree->showContainerIndexLabels()) { - azsnprintf(containerLabelBuffer, bufsiz, " %i. %s", - index + 1 - tree->containerIndicesZeroBased(), - labelUndecorated() ? labelUndecorated() : ""); - } - else { - azsnprintf(containerLabelBuffer, bufsiz, "%i.", - index + 1 - tree->containerIndicesZeroBased()); - } - return containerLabelBuffer; - } - else - return ""; - } - else - return labelUndecorated() ? labelUndecorated() : ""; -} - -bool PropertyRow::hasVisibleChildren(const QPropertyTree* tree, bool internalCall) const -{ - if(empty() || (!internalCall && pulledUp())) - return false; - - PropertyRow::const_iterator it; - for(it = children_.begin(); it != children_.end(); ++it){ - const PropertyRow* child = *it; - if(child->pulledUp()){ - if(child->hasVisibleChildren(tree, true)) - return true; - } - else if(child->visible(tree)) - return true; - } - return false; -} - -const PropertyRow* PropertyRow::hit(const QPropertyTree* tree, QPoint point) const -{ - return const_cast(this)->hit(tree, point); -} - -PropertyRow* PropertyRow::hit(const QPropertyTree* tree, QPoint point) -{ - bool expanded = this->expanded(); - if(isContainer() && pulledUp()) - expanded = parent() ? parent()->expanded() : true; - bool onlyPulled = !expanded; - PropertyRow::const_iterator it; - for(it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* child = *it; - if (!child->visible(tree)) - continue; - if(!onlyPulled || child->pulledUp()) - if(PropertyRow* result = child->hit(tree, point)) - return result; - } - if (QRect(pos_.x(), pos_.y(), size_.x(), size_.y()).contains(point)) - return this; - return 0; -} - -PropertyRow* PropertyRow::findByAddress(const void* addr) -{ - if(searchHandle() == addr) - return this; - else{ - Rows::iterator it; - for(it = children_.begin(); it != children_.end(); ++it){ - PropertyRow* result = it->get()->findByAddress(addr); - if(result) - return result; - } - } - return 0; -} - -const void* PropertyRow::searchHandle() const -{ - return serializer_.pointer(); -} - - -PropertyRow* PropertyRow::findChildFromDescendant(PropertyRow* row) const -{ - PropertyRow* child = row; - Rows::const_iterator it = std::find(children_.begin(), children_.end(), child); - while( it == children_.end() && child ) - { - child = child->parent(); - it = std::find(children_.begin(), children_.end(), child); - } - - return child; -} - -struct GetVerticalIndexOp{ - int index_; - const PropertyRow* row_; - - GetVerticalIndexOp(const PropertyRow* row) : row_(row), index_(0) {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(row == row_) - return SCAN_FINISHED; - if(row->visible(tree) && row->isSelectable() && !row->pulledUp() && !row->packedAfterPreviousRow()) - ++index_; - return row->expanded() ? SCAN_CHILDREN_SIBLINGS : SCAN_SIBLINGS; - } -}; - -int PropertyRow::verticalIndex(QPropertyTree* tree, PropertyRow* row) -{ - GetVerticalIndexOp op(row); - scanChildren(op, tree); - return op.index_; -} - - -struct RowByVerticalIndexOp{ - int index_; - PropertyRow* row_; - - RowByVerticalIndexOp(int index) : row_(0), index_(index) {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(row->visible(tree) && !row->pulledUp() && row->isSelectable() && !row->packedAfterPreviousRow()){ - row_ = row; - if(index_-- <= 0) - return SCAN_FINISHED; - } - return row->expanded() ? SCAN_CHILDREN_SIBLINGS : SCAN_SIBLINGS; - } -}; - -PropertyRow* PropertyRow::rowByVerticalIndex(QPropertyTree* tree, int index) -{ - RowByVerticalIndexOp op(index); - scanChildren(op, tree); - return op.row_; -} - -struct HorizontalIndexOp{ - int index_; - PropertyRow* row_; - bool pulledBefore_; - - HorizontalIndexOp(PropertyRow* row) : row_(row), index_(0), pulledBefore_(row->pulledBefore()) {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(!row->pulledUp()) - return SCAN_SIBLINGS; - if(row->visible(tree) && row->isSelectable() && row->pulledUp() && row->pulledBefore() == pulledBefore_){ - index_ += pulledBefore_ ? -1 : 1; - if(row == row_) - return SCAN_FINISHED; - } - return SCAN_CHILDREN_SIBLINGS; - } -}; - -int PropertyRow::horizontalIndex(QPropertyTree* tree, PropertyRow* row) -{ - if(row == this) - return 0; - HorizontalIndexOp op(row); - if(row->pulledBefore()) - scanChildrenReverse(op, tree); - else - scanChildren(op, tree); - return op.index_; -} - -struct RowByHorizontalIndexOp{ - int index_; - PropertyRow* row_; - bool pulledBefore_; - - RowByHorizontalIndexOp(int index) : row_(0), index_(index), pulledBefore_(index < 0) {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(!row->pulledUp()) - return SCAN_SIBLINGS; - if(row->visible(tree) && row->isSelectable() && row->pulledUp() && row->pulledBefore() == pulledBefore_){ - row_ = row; - if(pulledBefore_ ? ++index_ >= 0 : --index_ <= 0) - return SCAN_FINISHED; - } - return SCAN_CHILDREN_SIBLINGS; - } -}; - -PropertyRow* PropertyRow::rowByHorizontalIndex(QPropertyTree* tree, int index) -{ - if(!index) - return this; - RowByHorizontalIndexOp op(index); - if(index < 0) - scanChildrenReverse(op, tree); - else - scanChildren(op, tree); - return op.row_ ? op.row_ : this; -} - -void PropertyRow::redraw([[maybe_unused]] const PropertyDrawContext& context) -{ - -} - -bool PropertyRow::isFullRow(const QPropertyTree* tree) const -{ - if (tree->treeStyle().fullRowMode) - return true; - if (parent() && parent()->isContainer()) - return true; - return userFullRow(); -} - -QRect PropertyRow::textRect(const QPropertyTree* tree) const -{ - return QRect(textPos_, pos_.y(), textSize_ < textSizeInitial_ ? textSize_ - 1 : textSize_, tree->_defaultRowHeight()); -} - -QRect PropertyRow::widgetRect(const QPropertyTree* tree) const -{ - return QRect(widgetPos_, pos_.y(), widgetSize_, tree->_defaultRowHeight()); -} - -QRect PropertyRow::validatorRect([[maybe_unused]] const QPropertyTree* tree) const -{ - return QRect(pos_.x() + plusSize_, pos_.y() + size_.y() - validatorsHeight_, size_.x() - plusSize_, validatorsHeight_); -} - -QRect PropertyRow::validatorErrorIconRect(const QPropertyTree* tree) const -{ - int rowHeight = tree->_defaultRowHeight(); - int width = validatorHasErrors_ && !expanded_ ? rowHeight : 0; - int normalX = pos_.x() + size_.x() - width; - int minimalX = max(widgetPos_ + widgetSize_, textPos_ + textSize_); - return QRect(max(minimalX, normalX), pos_.y(), width, rowHeight); -} - -QRect PropertyRow::validatorWarningIconRect(const QPropertyTree* tree) const -{ - QRect r = validatorErrorIconRect(tree); - int width = validatorHasWarnings_ && !expanded_ ? r.height() : 0; - return QRect(r.left() - width, pos_.y(), width, r.height()); -} - -QRect PropertyRow::plusRect(const QPropertyTree* tree) const -{ - return QRect(pos_.x(), pos_.y(), plusSize_, tree->_defaultRowHeight()); -} - -QRect PropertyRow::floorRect(const QPropertyTree* tree) const -{ - return QRect(textPos_, pos_.y() + tree->_defaultRowHeight(), size_.x() - (textPos_ - pos_.x()) , size_.y() - tree->_defaultRowHeight()); -} - -void PropertyRow::setCallback(Serialization::ICallback* callback) -{ - callback_ = callback; -} - -SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRow, "PropertyRow", "Structure"); - -// --------------------------------------------------------------------------- - -EDITOR_COMMON_API PropertyRowFactory& GlobalPropertyRowFactory() -{ - return PropertyRowFactory::the(); -} - -EDITOR_COMMON_API Serialization::ClassFactory& GlobalPropertyRowClassFactory() -{ - return Serialization::ClassFactory::the(); -} - -// --------------------------------------------------------------------------- - -PropertyRowWidget::PropertyRowWidget(PropertyRow* row, QPropertyTree* tree) -: row_(row) -, model_(tree->model()) -, tree_(tree) -{ -} - -PropertyRowWidget::~PropertyRowWidget() -{ - if(actualWidget()) - actualWidget()->setParent(0); - tree_->setFocus(); -} - -// --------------------------------------------------------------------------- -Serialization::ClassFactory& GetPropertyRowClassFactory() -{ - return Serialization::ClassFactory::the(); -} -PropertyRowFactory& GetPropertyRowFactory() -{ - return PropertyRowFactory::the(); -} - -int RowWidthCache::getOrUpdate(const QPropertyTree* tree, const PropertyRow* rowForValue, int extraSpace) -{ - string value = rowForValue->valueAsString(); - const QFont* font = rowForValue->rowFont(tree); - unsigned int newHash = calculateHash(value.c_str()); - newHash = calculateHash(font, valueHash); - if (newHash != valueHash) - { - QFontMetrics fm(*font); - width = fm.horizontalAdvance(value.c_str()) + 6 + extraSpace; - if (width < 24) - width = 24; - valueHash = newHash; - } - return width; -} - -// --------------------------------------------------------------------------- - -FORCE_SEGMENT(PropertyRowNumber) -FORCE_SEGMENT(PropertyRowStringList) -/* -FORCE_SEGMENT(PropertyRowDecorators) -FORCE_SEGMENT(PropertyRowBitVector) -FORCE_SEGMENT(PropertyRowFileSelector) -FORCE_SEGMENT(PropertyRowColor) -FORCE_SEGMENT(PropertyRowHotkey) -FORCE_SEGMENT(PropertyRowSlider) -FORCE_SEGMENT(PropertyRowIcon) -*/ -#include - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.h deleted file mode 100644 index d5556857b7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRow.h +++ /dev/null @@ -1,575 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#pragma once - -#if !defined(Q_MOC_RUN) -#include -#include -#include "Serialization/Serializer.h" -#include "Serialization/StringList.h" -#include -#include "Factory.h" -#include "ConstStringList.h" -#include "Strings.h" -#include "../EditorCommonAPI.h" -#include "Serialization/ClassFactory.h" - -#include -#include -#include -#include -#endif - -namespace Serialization { struct ICallback; } - -class QWidget; -class QFont; -class QPainter; -class QMenu; -class QKeyEvent; - -using std::vector; -class QPropertyTree; -class PropertyRow; -class PropertyTreeModel; -class PopupMenuItem; -struct PropertyDrawContext; -struct EDITOR_COMMON_API ContainerMenuHandler; -class PropertyRowContainer; - -enum ScanResult { - SCAN_FINISHED, - SCAN_CHILDREN, - SCAN_SIBLINGS, - SCAN_CHILDREN_SIBLINGS, -}; - -struct EDITOR_COMMON_API PropertyRowMenuHandler : QObject -{ -public: - virtual ~PropertyRowMenuHandler() {} - -}; - -struct PropertyActivationEvent -{ - enum Reason - { - REASON_PRESS, - REASON_RELEASE, - REASON_DOUBLECLICK, - REASON_KEYBOARD, - REASON_NEW_ELEMENT - }; - - QPropertyTree* tree; - Reason reason; - bool force; - QPoint clickPoint; - - PropertyActivationEvent() - : force(false) - , clickPoint(0, 0) - , tree(0) - , reason(REASON_PRESS) - { - } -}; - -struct PropertyDragEvent -{ - QPropertyTree* tree; - QPoint pos; - QPoint start; - QPoint lastDelta; - QPoint totalDelta; -}; - -struct PropertyHoverInfo -{ - QCursor cursor; - QString toolTip; - - PropertyHoverInfo() - : cursor() - { - } -}; - -enum DragCheckBegin { - DRAG_CHECK_IGNORE, - DRAG_CHECK_SET, - DRAG_CHECK_UNSET -}; - -class PropertyRowWidget : public QObject -{ - Q_OBJECT -public: - PropertyRowWidget(PropertyRow* row, QPropertyTree* tree); - virtual ~PropertyRowWidget(); - virtual QWidget* actualWidget() { return 0; } - virtual void showPopup() {} - virtual void commit() = 0; - PropertyRow* row() { return row_; } - PropertyTreeModel* model() { return model_; } -protected: - PropertyRow* row_; - QPropertyTree* tree_; - PropertyTreeModel* model_; -}; - -class PropertyTreeTransaction; - -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -class EDITOR_COMMON_API PropertyRow : public Serialization::RefCounter -{ -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING -public: - enum WidgetPlacement { - WIDGET_NONE, - WIDGET_ICON, - WIDGET_AFTER_NAME, - WIDGET_VALUE, - WIDGET_AFTER_PULLED, - WIDGET_INSTEAD_OF_TEXT - }; - - typedef std::vector< Serialization::SharedPtr > Rows; - typedef Rows::iterator iterator; - typedef Rows::const_iterator const_iterator; - - PropertyRow(); - virtual ~PropertyRow(); - - void setNames(const char* name, const char* label, const char* typeName); - - bool selected() const{ return selected_; } - void setSelected(bool selected) { selected_ = selected; } - bool expanded() const{ return expanded_; } - void _setExpanded(bool expanded); // use QPropertyTree::expandRow - void setExpandedRecursive(QPropertyTree* tree, bool expanded); - - void setMatchFilter(bool matchFilter) { matchFilter_ = matchFilter; } - bool matchFilter() const { return matchFilter_; } - - void setBelongsToFilteredRow(bool belongs) { belongsToFilteredRow_ = belongs; } - bool belongsToFilteredRow() const { return belongsToFilteredRow_; } - - bool visible(const QPropertyTree* tree) const; - bool hasVisibleChildren(const QPropertyTree* tree, bool internalCall = false) const; - - const PropertyRow* hit(const QPropertyTree* tree, QPoint point) const; - PropertyRow* hit(const QPropertyTree* tree, QPoint point); - PropertyRow* parent() { return parent_; } - const PropertyRow* parent() const{ return parent_; } - void setParent(PropertyRow* row) { parent_ = row; } - bool isRoot() const { return !parent_; } - int level() const; - - void add(PropertyRow* row); - void addAfter(PropertyRow* row, PropertyRow* after); - void addBefore(PropertyRow* row, PropertyRow* before); - - template bool scanChildren(Op& op); - template bool scanChildren(Op& op, QPropertyTree* tree); - template bool scanChildrenReverse(Op& op, QPropertyTree* tree); - template bool scanChildrenBottomUp(Op& op, QPropertyTree* tree); - - PropertyRow* childByIndex(int index); - const PropertyRow* childByIndex(int index) const; - int childIndex(const PropertyRow* row) const; - bool isChildOf(const PropertyRow* row) const; - - bool empty() const{ return children_.empty(); } - iterator find(PropertyRow* row) { return std::find(children_.begin(), children_.end(), row); } - PropertyRow* findFromIndex(int* outIndex, const char* name, const char* typeName, int startIndex) const; - PropertyRow* findByAddress(const void* handle); - virtual const void* searchHandle() const; - iterator begin() { return children_.begin(); } - iterator end() { return children_.end(); } - const_iterator begin() const{ return children_.begin(); } - const_iterator end() const{ return children_.end(); } - std::size_t count() const{ return children_.size(); } - iterator erase(iterator it){ return children_.erase(it); } - void clear(){ children_.clear(); } - void erase(PropertyRow* row); - void swapChildren(PropertyRow* row, PropertyTreeModel* model); - - void assignRowState(const PropertyRow& row, bool recurse); - void assignRowProperties(PropertyRow* row); - void replaceAndPreserveState(PropertyRow* oldRow, PropertyRow* newRow, PropertyTreeModel* model); - - const char* name() const{ return name_; } - void setName(const char* name) { name_ = name; } - const char* label() const { return label_; } - const char* labelUndecorated() const { return labelUndecorated_; } - void setLabel(const char* label); - void setLabelChanged(); - void setTooltip(const char* tooltip); - bool setValidatorEntry(int index, int count); - int validatorCount() const{ return validatorCount_; } - int validatorIndex() const{ return validatorIndex_; } - void resetValidatorIcons(); - void addValidatorIcons(bool hasWarnings, bool hasErrors); - const char* tooltip() const { return tooltip_; } - void setLayoutChanged(); - void setLabelChangedToChildren(); - void setLayoutChangedToChildren(); - void setHideChildren(bool hideChildren) { hideChildren_ = hideChildren; } - bool hideChildren() const { return hideChildren_; } - void updateLabel(const QPropertyTree* tree, int index, bool parentHidesNonInlineChildren); - void updateTextSizeInitial(const QPropertyTree* tree, int index, bool force); - virtual void labelChanged() {} - void parseControlCodes(const QPropertyTree* tree, const char* label, bool changeLabel); - const char* typeName() const{ return typeName_; } - virtual const char* typeNameForFilter(QPropertyTree* tree) const; - void setTypeName(const char* typeName) { typeName_ = typeName; } - const char* rowText(char* containerLabelBuffer, size_t bufsiz, const QPropertyTree* tree, int rowIndex) const; - - PropertyRow* findSelected(); - PropertyRow* find(const char* name, const char* nameAlt, const char* typeName); - const PropertyRow* find(const char* name, const char* nameAlt, const char* typeName) const; - void intersect(const PropertyRow* row); - - int verticalIndex(QPropertyTree* tree, PropertyRow* row); - PropertyRow* rowByVerticalIndex(QPropertyTree* tree, int index); - int horizontalIndex(QPropertyTree* tree, PropertyRow* row); - PropertyRow* rowByHorizontalIndex(QPropertyTree* tree, int index); - - virtual bool assignToPrimitive([[maybe_unused]] void* object, [[maybe_unused]] size_t size) const{ return false; } - virtual bool assignTo([[maybe_unused]] const Serialization::SStruct& ser) const{ return false; } - virtual bool assignToByPointer(void* instance, const Serialization::TypeID& type) const{ return assignTo(Serialization::SStruct(type, instance, type.sizeOf(), 0)); } - virtual void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) { serializer_ = ser; } - virtual void handleChildrenChange() {} - virtual string valueAsString() const; - virtual wstring valueAsWString() const; - - int height() const{ return size_.y(); } - - virtual int widgetSizeMin(const QPropertyTree*) const { return userWidgetSize() >= 0 ? userWidgetSize() : 0; } - virtual int floorHeight() const{ return 0; } - - void calcPulledRows(int* minTextSize, int* freePulledChildren, int* minimalWidth, const QPropertyTree* tree, int index); - void calculateMinimalSize(const QPropertyTree* tree, int posX, int availableWidth, bool force, int* extraSizeRemainder, int* _extraSize, int index); - void setTextSize(const QPropertyTree* tree, int rowIndex, float multiplier); - void calculateTotalSizes(int* minTextSize); - void adjustVerticalPosition(const QPropertyTree* tree, int& totalHeight); - - virtual bool isWidgetFixed() const{ return userFixedWidget_ || (widgetPlacement() != WIDGET_VALUE && widgetPlacement() != WIDGET_INSTEAD_OF_TEXT); } - - virtual WidgetPlacement widgetPlacement() const{ return WIDGET_NONE; } - - QRect rect() const{ return QRect(pos_.x(), pos_.y(), size_.x(), size_.y()); } - QRect rectIncludingChildren(const QPropertyTree* tree) const; - QRect textRect(const QPropertyTree* tree) const; - QRect widgetRect(const QPropertyTree* tree) const; - QRect plusRect(const QPropertyTree* tree) const; - QRect floorRect(const QPropertyTree* tree) const; - QRect validatorRect(const QPropertyTree* tree) const; - QRect validatorWarningIconRect(const QPropertyTree* tree) const; - QRect validatorErrorIconRect(const QPropertyTree* tree) const; - void adjustHoveredRect(QRect& hoveredRect); - int heightIncludingChildren() const{ return heightIncludingChildren_; } - const QFont* rowFont(const QPropertyTree* tree) const; - - void drawRow(QPainter& painter, const QPropertyTree* tree, int rowIndex, bool selectionPass); - void drawPlus(QPainter& p, const QPropertyTree* tree, const QRect& rect, bool expanded, bool selected, bool grayed) const; - void drawStaticText(QPainter& p, const QRect& widgetRect); - - virtual void redraw(const PropertyDrawContext& context); - virtual PropertyRowWidget* createWidget([[maybe_unused]] QPropertyTree* tree) { return 0; } - - virtual bool isContainer() const{ return false; } - virtual bool isPointer() const{ return false; } - virtual bool isObject() const{ return false; } - - virtual bool isLeaf() const{ return false; } - virtual void closeNonLeaf([[maybe_unused]] const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) {} - virtual bool isStatic() const{ return pulledContainer_ == 0; } - virtual bool isSelectable() const{ return (!userReadOnly() && !userReadOnlyRecurse()) || (!pulledUp() && !pulledBefore()); } - virtual bool activateOnAdd() const{ return false; } - virtual bool inlineInShortArrays() const{ return false; } - - bool canBeToggled(const QPropertyTree* tree) const; - bool canBeDragged() const; - bool canBeDroppedOn(const PropertyRow* parentRow, const PropertyRow* beforeChild, const QPropertyTree* tree) const; - void dropInto(PropertyRow* parentRow, PropertyRow* cursorRow, QPropertyTree* tree, bool before); - virtual bool getHoverInfo(PropertyHoverInfo* hit, [[maybe_unused]] const QPoint& cursorPos, [[maybe_unused]] const QPropertyTree* tree) const { - hit->toolTip = QString::fromUtf8(tooltip_); - return true; - } - - virtual bool onActivate(const PropertyActivationEvent& e); - virtual bool processesKey(QPropertyTree* tree, const QKeyEvent* ev); // returns true if it wants to process key events; otherwise, they will get processed by shortcuts in some cases, like delete - virtual bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev); - virtual bool onMouseDown([[maybe_unused]] QPropertyTree* tree, [[maybe_unused]] QPoint point, [[maybe_unused]] bool& changed) { return false; } - virtual void onMouseDrag([[maybe_unused]] const PropertyDragEvent& e) {} - virtual void onMouseStill([[maybe_unused]] const PropertyDragEvent& e) {} - virtual void onMouseUp([[maybe_unused]] QPropertyTree* tree, [[maybe_unused]] QPoint point) {} - // "drag check" allows you to "paint" with the mouse through checkboxes to set all values at once - virtual DragCheckBegin onMouseDragCheckBegin() { return DRAG_CHECK_IGNORE; } - virtual bool onMouseDragCheck([[maybe_unused]] QPropertyTree* tree, [[maybe_unused]] bool value) { return false; } - virtual bool onContextMenu(QMenu &menu, QPropertyTree* tree); - virtual ContainerMenuHandler* createMenuHandler(QPropertyTree* tree, PropertyRowContainer* container); - - virtual bool isFullRow(const QPropertyTree* tree) const; - - // User states. - // Assigned using control codes (characters in the beginning of label) - // fixed widget doesn't expand automatically to occupy all available place - bool userFixedWidget() const{ return userFixedWidget_; } - bool userFullRow() const { return userFullRow_; } - void setUserReadOnly(bool userReadOnly) { userReadOnly_ = userReadOnly; } - virtual bool userReadOnly() const { return userReadOnly_; } - void propagateFlagsTopToBottom(); - virtual bool userReadOnlyRecurse() const { return userReadOnlyRecurse_; } - bool userWidgetToContent() const { return userWidgetToContent_; } - int userWidgetSize() const{ return userWidgetSize_; } - bool userNonCopyable() const { return userNonCopyable_; } - - // multiValue is used to edit properties of multiple objects simulateneously - bool multiValue() const { return multiValue_; } - void setMultiValue(bool multiValue) { multiValue_ = multiValue; } - - // pulledRow - is the one that is pulled up to the parents row - // (created with ^ in the beginning of label) - bool pulledUp() const { return pulledUp_; } - bool pulledBefore() const { return pulledBefore_; } - bool hasPulled() const { return hasPulled_; } - bool packedAfterPreviousRow() const { return packedAfterPreviousRow_; } - bool pulledSelected() const; - PropertyRow* nonPulledParent(); - void setPulledContainer(PropertyRow* container){ pulledContainer_ = container; } - PropertyRow* pulledContainer() { return pulledContainer_; } - const PropertyRow* pulledContainer() const{ return pulledContainer_; } - - Serialization::SharedPtr clone(ConstStringList* constStrings) const; - - Serialization::SStruct serializer() const{ return serializer_; } - virtual Serialization::TypeID typeId() const{ return serializer_.type(); } - void setSerializer(const Serialization::SStruct& ser) { serializer_ = ser; } - virtual void serializeValue([[maybe_unused]] Serialization::IArchive& ar) {} - void setCallback(Serialization::ICallback* callback); - Serialization::ICallback* callback() { return callback_; } - virtual void Serialize(Serialization::IArchive& ar); - - static void setConstStrings(ConstStringList* constStrings){ constStrings_ = constStrings; } - -protected: - void init(const char* name, const char* nameAlt, const char* typeName); - PropertyRow* findChildFromDescendant(PropertyRow* row) const; - - virtual void overrideTextColor([[maybe_unused]] QColor& textColor) {} - - const char* name_; - const char* label_; - const char* labelUndecorated_; - const char* typeName_; - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - Serialization::SStruct serializer_; - PropertyRow* parent_; - Serialization::ICallback* callback_; - const char* tooltip_; - Rows children_; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - unsigned int textHash_; - - // do we really need QPoint here? - QPoint pos_; - QPoint size_; - short int textPos_; - short int textSizeInitial_; - short int textSize_; - short int widgetPos_; // widget == icon! - short int widgetSize_; - short int userWidgetSize_; - unsigned short heightIncludingChildren_; - unsigned short validatorIndex_; - unsigned short validatorsHeight_; - unsigned char validatorCount_; - unsigned char plusSize_; - bool visible_ : 1; - bool matchFilter_ : 1; - bool belongsToFilteredRow_ : 1; - bool expanded_ : 1; - bool selected_ : 1; - bool labelChanged_ : 1; - bool layoutChanged_ : 1; - bool userReadOnly_ : 1; - bool userReadOnlyRecurse_ : 1; - bool userFixedWidget_ : 1; - bool userFullRow_ : 1; - bool userPackCheckboxes_ : 1; - bool userWidgetToContent_ : 1; - bool pulledUp_ : 1; - bool pulledBefore_ : 1; - bool packedAfterPreviousRow_ : 1; - bool hasPulled_ : 1; - bool multiValue_ : 1; - bool hideChildren_ : 1; - bool validatorHasErrors_ : 1; - bool validatorHasWarnings_ : 1; - bool userNonCopyable_ : 1; - enum class FontWeight - { - Undefined, - Bold, - Regular - }; - FontWeight fontWeight_; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - Serialization::SharedPtr pulledContainer_; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - static ConstStringList* constStrings_; - friend class PropertyOArchive; - friend class PropertyIArchive; -}; - -inline unsigned int calculateHash(const char* str, unsigned hash = 5381) -{ - while(*str) - hash = hash * 33 + (unsigned char)*str++; - return hash; -} - -template -inline unsigned int calculateHash(const T& t, unsigned hash = 5381) -{ - for (int i = 0; i < sizeof(T); i++) - hash = hash * 33 + ((unsigned char*)&t)[i]; - return hash; -} - -struct RowWidthCache -{ - unsigned int valueHash; - int width; - - RowWidthCache() : valueHash(0), width(-1) {} - int getOrUpdate(const QPropertyTree* tree, const PropertyRow* rowForValue, int extraSpace); -}; - -typedef vector > PropertyRows; - -template -struct StaticBool{ - enum { Value = value }; -}; - -struct LessStrCmp -{ - bool operator()(const char* a, const char* b) const { - return strcmp(a, b) < 0; - } -}; - -typedef Factory PropertyRowFactory; - -template -bool PropertyRow::scanChildren(Op& op) -{ - Rows::iterator it; - - for(it = children_.begin(); it != children_.end(); ++it){ - ScanResult result = op(*it); - if(result == SCAN_FINISHED) - return false; - if(result == SCAN_CHILDREN || result == SCAN_CHILDREN_SIBLINGS){ - if(!(*it)->scanChildren(op)) - return false; - if(result == SCAN_CHILDREN) - return false; - } - } - return true; -} - -template -bool PropertyRow::scanChildren(Op& op, QPropertyTree* tree) -{ - int numChildren = int(children_.size()); - for(int index = 0; index < numChildren; ++index){ - PropertyRow* child = children_[index]; - ScanResult result = op(child, tree, index); - if(result == SCAN_FINISHED) - return false; - if(result == SCAN_CHILDREN || result == SCAN_CHILDREN_SIBLINGS){ - if(!child->scanChildren(op, tree)) - return false; - if(result == SCAN_CHILDREN) - return false; - } - } - return true; -} - -template -bool PropertyRow::scanChildrenReverse(Op& op, QPropertyTree* tree) -{ - int numChildren = (int)children_.size(); - for(int index = numChildren - 1; index >= 0; --index){ - PropertyRow* child = children_[index]; - ScanResult result = op(child, tree, index); - if(result == SCAN_FINISHED) - return false; - if(result == SCAN_CHILDREN || result == SCAN_CHILDREN_SIBLINGS){ - if(!child->scanChildrenReverse(op, tree)) - return false; - if(result == SCAN_CHILDREN) - return false; - } - } - return true; -} - -template -bool PropertyRow::scanChildrenBottomUp(Op& op, QPropertyTree* tree) -{ - size_t numChildren = children_.size(); - for(size_t i = 0; i < numChildren; ++i) - { - PropertyRow* child = children_[i]; - if(!child->scanChildrenBottomUp(op, tree)) - return false; - ScanResult result = op(child, tree); - if(result == SCAN_FINISHED) - return false; - } - return true; -} - -EDITOR_COMMON_API PropertyRowFactory& GlobalPropertyRowFactory(); -EDITOR_COMMON_API Serialization::ClassFactory& GlobalPropertyRowClassFactory(); - -struct PropertyRowPtrSerializer : Serialization::SharedPtrSerializer -{ - PropertyRowPtrSerializer(Serialization::SharedPtr& ptr) : SharedPtrSerializer(ptr) {} - Serialization::ClassFactory* factory() const override { return &GlobalPropertyRowClassFactory(); } -}; - -inline bool Serialize(Serialization::IArchive& ar, Serialization::SharedPtr& ptr, const char* name, const char* label) -{ - PropertyRowPtrSerializer serializer(ptr); - return ar(static_cast(serializer), name, label); -} - -#define REGISTER_PROPERTY_ROW(DataType, RowType) \ - PropertyRow* _Factory_For_##RowType() {return new RowType; }; \ - REGISTER_IN_FACTORY(PropertyRowFactory, Serialization::TypeID::get().name(), RowType, _Factory_For_##RowType); \ - SERIALIZATION_CLASS_NAME_FOR_FACTORY(GlobalPropertyRowClassFactory(), PropertyRow, RowType, #DataType, #DataType); - -// Exposes the necessary class factories to extend the property tree -// Exposes the necessary class factories to extend the property tree -EDITOR_COMMON_API Serialization::ClassFactory& GetPropertyRowClassFactory(); -EDITOR_COMMON_API PropertyRowFactory& GetPropertyRowFactory(); diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowActionButton.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowActionButton.cpp deleted file mode 100644 index d268c87311..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowActionButton.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "platform.h" - -#include - -#include "Serialization/ClassFactory.h" -#include "PropertyDrawContext.h" -#include "PropertyRowImpl.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include "Color.h" -#include "Unicode.h" -#include "Serialization/Decorators/ActionButton.h" - -using Serialization::IActionButton; -using Serialization::IActionButtonPtr; - -class PropertyRowActionButton - : public PropertyRow -{ -public: - PropertyRowActionButton() - : underMouse_() - , pressed_() - , minimalWidth_() {} - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - bool isSelectable() const override { return true; } - - bool onActivate(const PropertyActivationEvent& e) override - { - if (e.reason == PropertyActivationEvent::REASON_KEYBOARD) - { - if (value_) - { - value_->Callback(); - } - } - return true; - } - - bool onMouseDown(QPropertyTree* tree, QPoint point, [[maybe_unused]] bool& changed) override - { - if (userReadOnly()) - { - return false; - } - if (widgetRect(tree).contains(point)) - { - underMouse_ = true; - pressed_ = true; - tree->update(); - return true; - } - return false; - } - - void onMouseDrag(const PropertyDragEvent& e) override - { - if (userReadOnly()) - { - return; - } - bool underMouse = widgetRect(e.tree).contains(e.pos); - if (underMouse != underMouse_) - { - underMouse_ = underMouse; - e.tree->update(); - } - } - - void onMouseUp(QPropertyTree* tree, QPoint point) override - { - if (userReadOnly()) - { - return; - } - if (widgetRect(tree).contains(point)) - { - pressed_ = false; - if (value_) - { - value_->Callback(); - } - tree->update(); - } - } - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - value_ = static_cast(ser.pointer())->Clone(); - const char* icon = value_->Icon(); - icon_ = icon && icon[0] ? QIcon() : QIcon(QString::fromLocal8Bit(icon)); - } - bool assignTo([[maybe_unused]] const Serialization::SStruct& ser) const override { return true; } - wstring valueAsWString() const override { return L""; } - WidgetPlacement widgetPlacement() const override { return WIDGET_INSTEAD_OF_TEXT; } - void serializeValue([[maybe_unused]] Serialization::IArchive& ar) override { } - - int widgetSizeMin(const QPropertyTree* tree) const override - { - if (minimalWidth_ == 0) - { - QFontMetrics fm(tree->font()); - minimalWidth_ = (int)fm.horizontalAdvance(QString::fromLocal8Bit(labelUndecorated())) + 6 + (icon_.isNull() ? 0 : 18); - } - return minimalWidth_; - } - - void redraw(const PropertyDrawContext& context) - { - QRect rect = context.widgetRect.adjusted(-1, -1, 1, 1); - bool pressed = pressed_ && underMouse_; - - wstring text = toWideChar(labelUndecorated()); - if (icon_.isNull()) - { - int buttonFlags = BUTTON_CENTER; - if (pressed) - { - buttonFlags |= BUTTON_PRESSED; - } - if (selected()) - { - buttonFlags |= BUTTON_FOCUSED; - } - if (userReadOnly()) - { - buttonFlags |= BUTTON_DISABLED; - } - context.drawButton(rect, text.c_str(), buttonFlags, &context.tree->font()); - } - else - { - context.drawButtonWithIcon(icon_, rect, text.c_str(), selected(), pressed, selected(), !userReadOnly(), true, &context.tree->font()); - } - } - bool isFullRow(const QPropertyTree* tree) const override - { - if (PropertyRow::isFullRow(tree)) - { - return true; - } - return !userFixedWidget(); - } -protected: - mutable int minimalWidth_; - bool underMouse_; - bool pressed_; - QIcon icon_; - IActionButtonPtr value_; -}; - -REGISTER_PROPERTY_ROW(IActionButton, PropertyRowActionButton); diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.cpp deleted file mode 100644 index a2704601b0..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowBool.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "PropertyDrawContext.h" -#include "Serialization/ClassFactory.h" -#include "Serialization.h" -#include - -SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRowBool, "PropertyRowBool", "bool"); - -PropertyRowBool::PropertyRowBool() - : value_(false) -{ -} - -bool PropertyRowBool::assignToPrimitive(void* object, [[maybe_unused]] size_t size) const -{ - YASLI_ASSERT(size == sizeof(bool)); - *reinterpret_cast(object) = value_; - return true; -} - -bool PropertyRowBool::assignToByPointer(void* instance, const Serialization::TypeID& type) const -{ - return assignToPrimitive(instance, type.sizeOf()); -} - -void PropertyRowBool::redraw(const PropertyDrawContext& context) -{ - context.drawCheck(widgetRect(context.tree), userReadOnly(), multiValue() ? CHECK_IN_BETWEEN : (value_ ? CHECK_SET : CHECK_NOT_SET)); -} - -bool PropertyRowBool::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (QKeySequence(ev->key()) == QKeySequence(Qt::Key_Space)) - { - return true; - } - - return PropertyRow::processesKey(tree, ev); -} - -bool PropertyRowBool::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (QKeySequence(ev->key()) == QKeySequence(Qt::Key_Space)) - { - PropertyActivationEvent e; - e.tree = tree; - e.reason = e.REASON_KEYBOARD; - onActivate(e); - return true; - } - - return PropertyRow::onKeyDown(tree, ev); -} - -bool PropertyRowBool::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason != e.REASON_RELEASE) - { - if (!this->userReadOnly()) - { - e.tree->model()->rowAboutToBeChanged(this); - value_ = !value_; - e.tree->model()->rowChanged(this); - return true; - } - } - return false; -} - -DragCheckBegin PropertyRowBool::onMouseDragCheckBegin() -{ - if (userReadOnly()) - { - return DRAG_CHECK_IGNORE; - } - return value_ ? DRAG_CHECK_UNSET : DRAG_CHECK_SET; -} - -bool PropertyRowBool::onMouseDragCheck(QPropertyTree* tree, bool value) -{ - if (value_ != value) - { - tree->model()->rowAboutToBeChanged(this); - value_ = value; - tree->model()->rowChanged(this); - return true; - } - return false; -} - -void PropertyRowBool::serializeValue(Serialization::IArchive& ar) -{ - ar(value_, "value", "Value"); -} - -int PropertyRowBool::widgetSizeMin(const QPropertyTree* tree) const -{ - return aznumeric_cast(tree->_defaultRowHeight() * 0.9f); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.h deleted file mode 100644 index 0900cd09e6..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowBool.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWBOOL_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWBOOL_H -#pragma once - -#include "PropertyRow.h" -#include "Unicode.h" - -class PropertyRowBool - : public PropertyRow -{ -public: - PropertyRowBool(); - bool assignToPrimitive(void* val, size_t size) const override; - bool assignToByPointer(void* instance, const Serialization::TypeID& type) const; - void setValue(bool value, const void* handle, [[maybe_unused]] const Serialization::TypeID& typeId) { value_ = value; serializer_.setPointer((void*)handle); serializer_.setType(Serialization::TypeID::get()); } - - void redraw(const PropertyDrawContext& context); - bool isLeaf() const{ return true; } - bool isStatic() const{ return false; } - - bool onActivate(const PropertyActivationEvent& e); - DragCheckBegin onMouseDragCheckBegin() override; - bool onMouseDragCheck(QPropertyTree* tree, bool value) override; - wstring valueAsWString() const{ return value_ ? L"true" : L"false"; } - string valueAsString() const{ return value_ ? "true" : "false"; } - WidgetPlacement widgetPlacement() const{ return WIDGET_ICON; } - void serializeValue(Serialization::IArchive& ar); - int widgetSizeMin(const QPropertyTree* tree) const override; - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; -protected: - bool value_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWBOOL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.cpp deleted file mode 100644 index f83dd6713e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.cpp +++ /dev/null @@ -1,241 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowColor.h" -#include "Serialization/ClassFactory.h" -#include -#include -#include -#include - -#include -#include - -using Serialization::Vec3AsColor; -typedef SerializableColor_tpl SerializableColorB; -typedef SerializableColor_tpl SerializableColorF; - -QColor ToQColor(const ColorB& v) -{ - return QColor(v.r, v.g, v.b, v.a); -} - -void FromQColor(SerializableColorB& vColor, QColor color) -{ - vColor.r = color.red(); - vColor.g = color.green(); - vColor.b = color.blue(); - vColor.a = color.alpha(); -} - - -QColor ToQColor(const Vec3AsColor& v) -{ - return QColor(int(v.v.x * 255.0f), int(v.v.y * 255.0f), int(v.v.z * 255.0f)); -} - -void FromQColor(Vec3AsColor& vColor, QColor color) -{ - vColor.v.x = color.red() / 255.0f; - vColor.v.y = color.green() / 255.0f; - vColor.v.z = color.blue() / 255.0f; -} - -QColor ToQColor(const SerializableColorF& v) -{ - return QColor::fromRgbF(v.r, v.g, v.b, v.a); -} - -void FromQColor(SerializableColorF& vColor, QColor color) -{ - vColor.r = aznumeric_cast(color.redF()); - vColor.g = aznumeric_cast(color.greenF()); - vColor.b = aznumeric_cast(color.blueF()); - vColor.a = aznumeric_cast(color.alphaF()); -} - - -template -bool PropertyRowColor::pickColor(QPropertyTree* tree) -{ - const AZ::Color initialColor = AzQtComponents::fromQColor(color_); - const AZ::Color color = AzQtComponents::ColorPicker::getColor(AzQtComponents::ColorPicker::Configuration::RGB, initialColor, QObject::tr("Select Color")); - - if (color != initialColor) - { - tree->model()->rowAboutToBeChanged(this); - color_.setRed(color.GetR8()); - color_.setGreen(color.GetG8()); - color_.setBlue(color.GetB8()); - colorChanged_ = true; - tree->model()->rowChanged(this); - return true; - } - - return false; -} - -template -bool PropertyRowColor::onActivate(const PropertyActivationEvent& e) -{ - return pickColor(e.tree); -} - -template -void PropertyRowColor::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] IArchive& ar) -{ - color_ = ToQColor(*(ColorClass*)ser.pointer()); - colorChanged_ = false; -} - -template -bool PropertyRowColor::assignTo(const Serialization::SStruct& ser) const -{ - FromQColor(*((ColorClass*)ser.pointer()), color_); - return true; -} - -template -string PropertyRowColor::valueAsString() const -{ - char buf[64]; - sprintf_s(buf, "%d %d %d", (int)color_.red(), (int)color_.green(), (int)color_.blue()); - return string(buf); -} - -template -bool PropertyRowColor::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - Serialization::SharedPtr selfPointer(this); - ColorMenuHandler* handler = new ColorMenuHandler(tree, this); - menu.addAction("Pick Color", handler, SLOT(onMenuPickColor())); - tree->addMenuHandler(handler); - return true; -} - -template -void PropertyRowColor::redraw(const PropertyDrawContext& context) -{ - static QImage checkboardPattern; - if (checkboardPattern.isNull()) - { - int size = 12; - static vector pixels(size * size); - for (int i = 0; i < pixels.size(); ++i) - { - pixels[i] = ((i / size) / (size / 2) + (i % size) / (size / 2)) % 2 ? 0xffffffff : 0x000000ff; - } - checkboardPattern = QImage((unsigned char*)pixels.data(), size, size, size * 4, QImage::Format_RGBA8888); - } - - QRect r = context.widgetRect.adjusted(0, 0, 0, -1); - - context.painter->save(); - context.painter->setPen(QPen(Qt::NoPen)); - context.painter->setRenderHint(QPainter::Antialiasing, true); - context.painter->setBrush(context.tree->palette().color(QPalette::Dark)); - context.painter->setPen(Qt::NoPen); - context.painter->drawRoundedRect(r, 2, 2); - r = r.adjusted(1, 1, -1, -1); - QRect cr = r.adjusted(0, 0, -r.width() / 2, 0); - context.painter->setBrushOrigin(cr.topRight() + QPoint(1, 0)); - context.painter->setBrush(QBrush(checkboardPattern)); - - context.painter->setRenderHint(QPainter::Antialiasing, false); - context.painter->drawRoundedRect(r, 2, 2); - - context.painter->setPen(QPen(Qt::NoPen)); - context.painter->setClipRect(cr); - context.painter->setBrush(QBrush(color_)); - context.painter->drawRoundedRect(r, 2, 2); - - cr = r.adjusted(r.width() / 2, 0, 0, 0); - context.painter->setClipRect(cr); - context.painter->setBrush(QBrush(QColor(color_.red(), color_.green(), color_.blue(), 255))); - context.painter->drawRoundedRect(r, 2, 2); - context.painter->restore(); -} - -template -void PropertyRowColor::closeNonLeaf(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - color_ = ToQColor(*(ColorClass*)ser.pointer()); -} - -static int componentFromRowValue(const char* str, ColorB*) -{ - return clamp_tpl(atoi(str), 0, 255); -} - -static int componentFromRowValue(const char* str, ColorF*) -{ - return clamp_tpl(int(atof(str) * 255.0f + 0.5f), 0, 255); -} - -static int componentFromRowValue(const char* str, Vec3AsColor*) -{ - return clamp_tpl(int(atof(str) * 255.0f + 0.5f), 0, 255); -} - -template -void PropertyRowColor::handleChildrenChange() -{ - // generally is not needed unless we are using callbacks - PropertyRow* rows[4] = { - childByIndex(0), - childByIndex(1), - childByIndex(2), - childByIndex(3) - }; - - if (rows[0]) - { - color_.setRed(componentFromRowValue(rows[0]->valueAsString().c_str(), (ColorClass*)0)); - } - if (rows[1]) - { - color_.setGreen(componentFromRowValue(rows[1]->valueAsString().c_str(), (ColorClass*)0)); - } - if (rows[2]) - { - color_.setBlue(componentFromRowValue(rows[2]->valueAsString().c_str(), (ColorClass*)0)); - } - if (rows[3]) - { - color_.setAlpha(componentFromRowValue(rows[3]->valueAsString().c_str(), (ColorClass*)0)); - } -} - - -ColorMenuHandler::ColorMenuHandler(QPropertyTree* tree, IPropertyRowColor* propertyRowColor) - : propertyRowColor(propertyRowColor) - , tree(tree) -{ -} - -void ColorMenuHandler::onMenuPickColor() -{ - propertyRowColor->pickColor(tree); -} - -typedef PropertyRowColor PropertyRowColorB; -typedef PropertyRowColor PropertyRowVec3AsColor; -typedef PropertyRowColor PropertyRowColorF; - -REGISTER_PROPERTY_ROW(SerializableColorB, PropertyRowColorB); -REGISTER_PROPERTY_ROW(Vec3AsColor, PropertyRowVec3AsColor); -REGISTER_PROPERTY_ROW(SerializableColorF, PropertyRowColorF); - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.h deleted file mode 100644 index 9859539b46..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColor.h +++ /dev/null @@ -1,75 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include -#endif - -struct IPropertyRowColor -{ - virtual bool pickColor(QPropertyTree* tree) = 0; -}; - -template -class PropertyRowColor - : public PropertyRow - , public IPropertyRowColor -{ -public: - PropertyRowColor() - : colorChanged_(false) {} - - bool isLeaf() const override { return colorChanged_; } - bool isStatic() const override { return false; } - WidgetPlacement widgetPlacement() const{ return WIDGET_AFTER_PULLED; } - int widgetSizeMin(const QPropertyTree* tree) const { return userWidgetSize() >= 0 ? userWidgetSize() : tree->_defaultRowHeight()* 2 - 4; } - void handleChildrenChange() override; - - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - void closeNonLeaf(const Serialization::SStruct& ser, Serialization::IArchive& ar); - - bool onActivate(const PropertyActivationEvent& ev) override; - - string valueAsString() const; - void redraw(const PropertyDrawContext& context); - - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - - bool pickColor(QPropertyTree* tree) override; - -private: - QColor color_; - bool colorChanged_; -}; - -struct ColorMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - IPropertyRowColor* propertyRowColor; - - ColorMenuHandler(QPropertyTree* tree, IPropertyRowColor* propertyRowColor); - ~ColorMenuHandler(){}; - -public slots: - void onMenuPickColor(); -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.cpp deleted file mode 100644 index 24650d9b89..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ - -#include "EditorCommon_precompiled.h" -#include "PropertyRowColorPicker.h" -#include "Serialization/ClassFactory.h" -#include -#include -#include -#include -#include - -#include -#include - -bool PropertyRowColorPicker::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE) - { - return false; - } - - // ColorF -> QColor. - AZ::Color initialColor; - initialColor.SetR(color_.r); - initialColor.SetG(color_.g); - initialColor.SetB(color_.b); - initialColor.SetA(color_.a); - - const AZ::Color colorFromDialog = AzQtComponents::ColorPicker::getColor(AzQtComponents::ColorPicker::Configuration::RGBA, - initialColor, - QObject::tr("Select Color")); - - if (initialColor == colorFromDialog) - { - // The user cancelled the dialog box. - // Nothing more to do. - return false; - } - - // QColor -> ColorF. - ColorF color(colorFromDialog.GetR(), - colorFromDialog.GetG(), - colorFromDialog.GetB(), - colorFromDialog.GetA()); - - e.tree->model()->rowAboutToBeChanged(this); - color_ = color; - e.tree->model()->rowChanged(this); - - return true; -} -void PropertyRowColorPicker::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - ColorPicker* value = (ColorPicker*)ser.pointer(); - color_ = *value->color; -} - -bool PropertyRowColorPicker::assignTo(const Serialization::SStruct& ser) const -{ - ((ColorPicker*)ser.pointer())->SetColor(&color_); - - return true; -} - -void PropertyRowColorPicker::serializeValue(Serialization::IArchive& ar) -{ - ar(color_, "color"); -} - -const QIcon& PropertyRowColorPicker::buttonIcon([[maybe_unused]] const QPropertyTree* tree, [[maybe_unused]] int index) const -{ - // Color-chip. - - QColor color((int)(color_.r * 255.0f), - (int)(color_.g * 255.0f), - (int)(color_.b * 255.0f)); - QPen pen(color); - QBrush brush(color); - - QPixmap pixmap(16, 16); - pixmap.fill(Qt::transparent); - - QPainter painter(&pixmap); - painter.setBrush(brush); - painter.setPen(pen); - painter.drawEllipse(0, 0, 15, 15); - - static QIcon icon; - icon.addPixmap(pixmap); - return icon; -} - -string PropertyRowColorPicker::valueAsString() const -{ - int r = (int)(255.0f * color_.r); - int g = (int)(255.0f * color_.g); - int b = (int)(255.0f * color_.b); - int a = (int)(255.0f * color_.a); - string value; - value.Format("#%02x%02x%02x%02x", r, g, b, a); - return value; -} - -void PropertyRowColorPicker::clear() -{ - color_ = Col_White; -} - -bool PropertyRowColorPicker::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - QAction* action = menu.addAction("Clear"); - QObject::connect(action, - &QAction::triggered, - tree, - [ this, tree ] - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - }); - return true; -} - -bool PropertyRowColorPicker::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (QKeySequence(ev->key()) == QKeySequence(Qt::Key_Delete)) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowColorPicker::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -REGISTER_PROPERTY_ROW(ColorPicker, PropertyRowColorPicker); -DECLARE_SEGMENT(PropertyRowColorPicker) - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.h deleted file mode 100644 index 90fb049a04..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowColorPicker.h +++ /dev/null @@ -1,56 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCOLORPICKER_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCOLORPICKER_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "PropertyRowField.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include -#include -#include -#endif - -using Serialization::ColorPicker; - -class PropertyRowColorPicker - : public PropertyRowField -{ -public: - void clear(); - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - bool onActivate(const PropertyActivationEvent& e) override; - - int buttonCount() const override { return 1; } - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - string valueAsString() const override; - void serializeValue(Serialization::IArchive& ar); - - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - ColorF color_; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCOLORPICKER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.cpp deleted file mode 100644 index c67c7fbd05..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.cpp +++ /dev/null @@ -1,439 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowContainer.h" -#include "PropertyRowPointer.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "PropertyDrawContext.h" -#include "Serialization.h" -#include "PropertyRowPointer.h" - -#include -#include - -// --------------------------------------------------------------------------- - -ContainerMenuHandler::ContainerMenuHandler(QPropertyTree* tree, PropertyRowContainer* container) - : element() - , container(container) - , tree(tree) - , pointerIndex(-1) -{ -} - - - -// --------------------------------------------------------------------------- -SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRowContainer, "PropertyRowContainer", "Container"); - -PropertyRowContainer::PropertyRowContainer() - : fixedSize_(false) - , elementTypeName_("") - , inlined_(false) -{ - buttonLabel_[0] = '\0'; -} - -struct ClassMenuItemAdderRowContainer - : ClassMenuItemAdder -{ - ClassMenuItemAdderRowContainer(PropertyRowContainer* row, QPropertyTree* tree, bool insert = false) - : row_(row) - , tree_(tree) - , insert_(insert) {} - - void addAction(QMenu& menu, const char* text, int index) override - { - ContainerMenuHandler* handler = row_->createMenuHandler(tree_, row_); - tree_->addMenuHandler(handler); - handler->pointerIndex = index; - - QAction* action = menu.addAction(text); - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuAppendPointerByIndex())); - } -protected: - PropertyRowContainer* row_; - QPropertyTree* tree_; - bool insert_; -}; - -void PropertyRowContainer::redraw(const PropertyDrawContext& context) -{ - QRect widgetRect = context.widgetRect; - if (widgetRect.width() == 0 || inlined_) - { - return; - } - QRect rt = widgetRect; - rt.adjust(0, 1, -1, -1); - QColor brushColor = context.tree->palette().button().color(); - QLinearGradient gradient(rt.left(), rt.top(), rt.left(), rt.bottom()); - gradient.setColorAt(0.0f, brushColor); - gradient.setColorAt(0.6f, brushColor); - gradient.setColorAt(1.0f, context.tree->palette().color(QPalette::Shadow)); - QBrush brush(gradient); - - const wchar_t* text = multiValue() ? L"..." : buttonLabel_; - int buttonFlags = BUTTON_CENTER | BUTTON_POPUP_ARROW; - if (userReadOnly()) - { - buttonFlags |= BUTTON_DISABLED; - } - if (context.m_pressed) - { - buttonFlags |= BUTTON_PRESSED; - } - context.drawButton(rt, text, buttonFlags, &context.tree->font()); -} - - -bool PropertyRowContainer::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE) - { - return false; - } - if (userReadOnly()) - { - return false; - } - if (inlined_) - { - return false; - } - QMenu menu; - generateMenu(menu, e.tree, true); - e.tree->_setPressedRow(this); - menu.exec(e.tree->_toScreen(QPoint(widgetPos_, pos_.y() + e.tree->_defaultRowHeight()))); - e.tree->_setPressedRow(0); - return true; -} - -ContainerMenuHandler* PropertyRowContainer::createMenuHandler(QPropertyTree* tree, PropertyRowContainer* container) -{ - return new ContainerMenuHandler(tree, container); -} - -void PropertyRowContainer::generateMenu(QMenu& menu, QPropertyTree* tree, bool addActions) -{ - ContainerMenuHandler* handler = createMenuHandler(tree, this); - tree->addMenuHandler(handler); - - if (fixedSize_) - { - if (!inlined_) - { - menu.addAction("[ Fixed Size Container ]")->setEnabled(false); - } - } - else if (userReadOnly()) - { - menu.addAction("[ Read Only Container ]")->setEnabled(false); - } - else - { - if (addActions) - { - PropertyRow* row = defaultRow(tree->model()); - if (row && row->isPointer()) - { - QMenu* createItem = menu.addMenu("Add"); - menu.addSeparator(); - - PropertyRowPointer* pointerRow = static_cast(row); - ClassMenuItemAdderRowContainer(this, tree).generateMenu(*createItem, tree->model()->typeStringList(pointerRow->baseType())); - } - else - { - menu.addAction("Insert", handler, SLOT(onMenuAddElement())); - menu.addAction("Add", handler, SLOT(onMenuAppendElement()), Qt::Key_Insert); - } - } - - if (!menu.isEmpty()) - { - menu.addSeparator(); - } - - QAction* removeAll = menu.addAction(pulledUp() ? "Remove Children" : "Remove All"); - removeAll->setShortcut(QKeySequence("Shift+Delete")); - removeAll->setEnabled(!userReadOnly()); - QObject::connect(removeAll, SIGNAL(triggered()), handler, SLOT(onMenuRemoveAll())); - } -} - -bool PropertyRowContainer::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - if (!menu.isEmpty()) - { - menu.addSeparator(); - } - - generateMenu(menu, tree, true); - - if (pulledUp()) - { - return !menu.isEmpty(); - } - - return PropertyRow::onContextMenu(menu, tree); -} - - -void ContainerMenuHandler::onMenuRemoveAll() -{ - tree->model()->rowAboutToBeChanged(container); - container->clear(); - tree->model()->rowChanged(container); -} - -PropertyRow* PropertyRowContainer::defaultRow(PropertyTreeModel* model) -{ - PropertyRow* defaultType = model->defaultType(elementTypeName_); - //YASLI_ASSERT(defaultType); - //YASLI_ASSERT(defaultType->numRef() == 1); - return defaultType; -} - -const PropertyRow* PropertyRowContainer::defaultRow(const PropertyTreeModel* model) const -{ - const PropertyRow* defaultType = model->defaultType(elementTypeName_); - return defaultType; -} - -void ContainerMenuHandler::onMenuAddElement() -{ - container->addElement(tree, false); -} - -void ContainerMenuHandler::onMenuAppendElement() -{ - container->addElement(tree, true); -} - -PropertyRow* PropertyRowContainer::addElement(QPropertyTree* tree, bool append) -{ - tree->model()->rowAboutToBeChanged(this); - PropertyRow* defaultType = defaultRow(tree->model()); - YASLI_ESCAPE(defaultType != 0, return 0); - SharedPtr clonedRow = defaultType->clone(tree->model()->constStrings()); - if (count() == 0) - { - tree->expandRow(this); - } - if (append) - { - add(clonedRow); - } - else - { - addBefore(clonedRow, 0); - } - clonedRow->setHideChildren(tree->outlineMode()); - clonedRow->setLabelChanged(); - clonedRow->setLabelChangedToChildren(); - setMultiValue(false); - if (expanded()) - { - tree->model()->selectRow(clonedRow, true); - } - tree->expandRow(clonedRow); - TreePath path = tree->model()->pathFromRow(clonedRow); - tree->model()->rowChanged(clonedRow); - clonedRow = tree->model()->rowFromPath(path); - tree->update(); - clonedRow = tree->model()->rowFromPath(path); - if (clonedRow) - { - PropertyTreeModel::Selection sel; - sel.push_back(path); - tree->model()->setSelection(sel); - if (clonedRow->activateOnAdd()) - { - PropertyActivationEvent e; - e.tree = tree; - e.reason = e.REASON_NEW_ELEMENT; - clonedRow->onActivate(e); - } - } - return clonedRow; -} - - -void ContainerMenuHandler::onMenuAppendPointerByIndex() -{ - PropertyRow* defaultType = container->defaultRow(tree->model()); - PropertyRowPointer* defaultTypePointer = static_cast(defaultType); - SharedPtr clonedRow = defaultType->clone(tree->model()->constStrings()); - if (container->count() == 0) - { - tree->expandRow(container); - } - container->add(clonedRow); - clonedRow->setLabelChanged(); - clonedRow->setLabelChangedToChildren(); - clonedRow->setHideChildren(tree->outlineMode()); - container->setMultiValue(false); - PropertyRowPointer* clonedRowPointer = static_cast(clonedRow.get()); - clonedRowPointer->setDerivedType(defaultTypePointer->derivedTypeName(), defaultTypePointer->factory()); - clonedRowPointer->setBaseType(defaultTypePointer->baseType()); - clonedRowPointer->setFactory(defaultTypePointer->factory()); - if (container->expanded()) - { - tree->model()->selectRow(clonedRow, true); - } - tree->expandRow(clonedRowPointer); - PropertyTreeModel::Selection sel = tree->model()->selection(); - - CreatePointerMenuHandler handler; - handler.tree = tree; - handler.row = clonedRowPointer; - handler.index = pointerIndex; - handler.onMenuCreateByIndex(); - tree->model()->setSelection(sel); - tree->update(); -} - -void ContainerMenuHandler::onMenuChildInsertBefore() -{ - tree->model()->rowAboutToBeChanged(container); - PropertyRow* defaultType = tree->model()->defaultType(container->elementTypeName()); - if (!defaultType) - { - return; - } - SharedPtr clonedRow = defaultType->clone(tree->model()->constStrings()); - clonedRow->setHideChildren(tree->outlineMode()); - element->setSelected(false); - container->addBefore(clonedRow, element); - container->setMultiValue(false); - tree->model()->selectRow(clonedRow, true); - PropertyTreeModel::Selection sel = tree->model()->selection(); - tree->model()->rowChanged(clonedRow); - tree->model()->setSelection(sel); - tree->update(); - clonedRow = tree->selectedRow(); - if (clonedRow->activateOnAdd()) - { - PropertyActivationEvent e; - e.tree = tree; - e.reason = PropertyActivationEvent::REASON_NEW_ELEMENT; - clonedRow->onActivate(e); - } -} - -void ContainerMenuHandler::onMenuChildRemove() -{ - tree->model()->rowAboutToBeChanged(container); - container->erase(element); - container->setMultiValue(false); - tree->model()->rowChanged(container); -} - - -void PropertyRowContainer::labelChanged() -{ - swprintf(buttonLabel_, sizeof(buttonLabel_) / sizeof(buttonLabel_[0]), L"%zi", count()); -} - -void PropertyRowContainer::serializeValue(IArchive& ar) -{ - ar(ConstStringWrapper(constStrings_, elementTypeName_), "elementTypeName", "ElementTypeName"); - ar(fixedSize_, "fixedSize", "fixedSize"); -} - -string PropertyRowContainer::valueAsString() const -{ - char buf[32] = { 0 }; - sprintf_s(buf, "%d", (int)children_.size()); - return string(buf); -} - -const char* PropertyRowContainer::typeNameForFilter(QPropertyTree* tree) const -{ - const PropertyRow* defaultType = defaultRow(tree->model()); - if (defaultType) - { - return defaultType->typeNameForFilter(tree); - } - else - { - return elementTypeName_; - } -} - -bool PropertyRowContainer::processesKeyContainer([[maybe_unused]] QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete && ev->modifiers() == Qt::SHIFT) - { - return true; - } - - if (ev->key() == Qt::Key_Insert && ev->modifiers() == Qt::NoModifier) - { - return true; - } - - return false; -} - -bool PropertyRowContainer::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (processesKeyContainer(tree, ev)) - { - return true; - } - - return PropertyRow::processesKey(tree, ev); -} - -bool PropertyRowContainer::onKeyDownContainer(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (userReadOnly()) - { - return false; - } - - std::unique_ptr handler(createMenuHandler(tree, this)); - if (ev->key() == Qt::Key_Delete && ev->modifiers() == Qt::SHIFT) - { - handler->onMenuRemoveAll(); - return true; - } - - if (ev->key() == Qt::Key_Insert && ev->modifiers() == Qt::NoModifier) - { - handler->onMenuAppendElement(); - return true; - } - - return false; -} - -bool PropertyRowContainer::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (onKeyDownContainer(tree, ev)) - { - return true; - } - return PropertyRow::onKeyDown(tree, ev); -} - -int PropertyRowContainer::widgetSizeMin(const QPropertyTree* tree) const -{ - return inlined_ ? 0 : (userWidgetSize() >= 0 ? userWidgetSize() : aznumeric_cast(tree->_defaultRowHeight() * 1.7f)); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.h deleted file mode 100644 index d4e8d2f6d3..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowContainer.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCONTAINER_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCONTAINER_H -#pragma once -#if !defined(Q_MOC_RUN) -#include "PropertyRow.h" -#endif - - -class EDITOR_COMMON_API PropertyRowContainer; -struct EDITOR_COMMON_API ContainerMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - - QPropertyTree * tree; - PropertyRowContainer* container; - PropertyRow* element; - int pointerIndex; - - ContainerMenuHandler(QPropertyTree* tree, PropertyRowContainer* container); - -public slots: - virtual void onMenuAddElement(); - virtual void onMenuAppendElement(); - virtual void onMenuAppendPointerByIndex(); - virtual void onMenuRemoveAll(); - virtual void onMenuChildInsertBefore(); - virtual void onMenuChildRemove(); -}; - -class EDITOR_COMMON_API PropertyRowContainer - : public PropertyRow -{ -public: - PropertyRowContainer(); - bool isContainer() const{ return true; } - bool onActivate(const PropertyActivationEvent& e); - bool onContextMenu(QMenu& item, QPropertyTree* tree); - virtual ContainerMenuHandler* createMenuHandler(QPropertyTree* tree, PropertyRowContainer* container) override; - void redraw(const PropertyDrawContext& context); - bool processesKeyContainer(QPropertyTree* tree, const QKeyEvent* ev); - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDownContainer(QPropertyTree* tree, const QKeyEvent* key); - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* key) override; - - void labelChanged() override; - bool isStatic() const{ return false; } - bool isSelectable() const{ return userWidgetSize() == 0 ? false : true; } - PropertyRow* addElement(QPropertyTree* tree, bool append); - void setInlined(bool inlined) { inlined_ = inlined; } - bool isInlined() const{ return inlined_; } - - PropertyRow* defaultRow(PropertyTreeModel* model); - const PropertyRow* defaultRow(const PropertyTreeModel* model) const; - void serializeValue(Serialization::IArchive& ar); - - const char* elementTypeName() const{ return elementTypeName_; } - using PropertyRow::setValueAndContext; - virtual void setValueAndContext(const Serialization::IContainer& value, [[maybe_unused]] Serialization::IArchive& ar) - { - fixedSize_ = value.isFixedSize(); - elementTypeName_ = value.elementType().name(); - serializer_.setPointer(value.pointer()); - serializer_.setType(value.containerType()); - } - const char* typeNameForFilter(QPropertyTree* tree) const override; - string valueAsString() const; - // C-array is an example of fixed size container - bool isFixedSize() const{ return fixedSize_; } - WidgetPlacement widgetPlacement() const override { return inlined_ ? WIDGET_NONE : WIDGET_AFTER_NAME; } - int widgetSizeMin(const QPropertyTree* tree) const override; - -protected: - virtual void generateMenu(QMenu& menu, QPropertyTree* tree, bool addActions); - - const char* elementTypeName_; - wchar_t buttonLabel_[8]; - bool fixedSize_; - bool inlined_; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWCONTAINER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.cpp deleted file mode 100644 index b91c4fb9b3..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.cpp +++ /dev/null @@ -1,84 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowField.h" -#include "PropertyDrawContext.h" -#include "QPropertyTree.h" -#include "QPropertyTreeStyle.h" -#include - -enum { BUTTON_SIZE = 16 }; - -QRect PropertyRowField::fieldRect(const QPropertyTree* tree) const -{ - QRect fieldRect = widgetRect(tree); - fieldRect.setRight(fieldRect.right() - buttonCount() * BUTTON_SIZE); - return fieldRect; -} - -bool PropertyRowField::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_PRESS) { - int buttonCount = this->buttonCount(); - QRect buttonsRect = widgetRect(e.tree); - buttonsRect.setLeft(buttonsRect.right() - buttonCount * BUTTON_SIZE); - - if (buttonsRect.contains(e.clickPoint)) { - int buttonIndex = buttonCount - (e.clickPoint.x() - buttonsRect.x()) / BUTTON_SIZE - 1; - if (buttonIndex >= 0 && buttonIndex < buttonCount) - { - if (onActivateButton(buttonIndex, e)) - return true; - } - } - } - - return PropertyRow::onActivate(e); -} - -void PropertyRowField::redraw(const PropertyDrawContext& context) -{ - int buttonCount = this->buttonCount(); - int offset = 0; - for (int i = 0; i < buttonCount; ++i) { - const QIcon& icon = buttonIcon(context.tree, i); - QRect iconRect(context.widgetRect.right() - offset - BUTTON_SIZE, context.widgetRect.top(), BUTTON_SIZE, context.widgetRect.height()); - icon.paint(context.painter, iconRect, Qt::AlignCenter, userReadOnly() ? QIcon::Disabled : QIcon::Normal); - offset += BUTTON_SIZE; - } - - int iconSpace = offset ? offset + 2 : 0; - if(multiValue()) - context.drawEntry(L" ... ", false, true, iconSpace); - else if(userReadOnly()) - context.drawValueText(pulledSelected(), valueAsWString().c_str()); - else - context.drawEntry(valueAsWString().c_str(), usePathEllipsis(), false, iconSpace); - -} - -const QIcon& PropertyRowField::buttonIcon([[maybe_unused]] const QPropertyTree* tree, [[maybe_unused]] int index) const -{ - static QIcon defaultIcon; - return defaultIcon; -} - -int PropertyRowField::widgetSizeMin(const QPropertyTree* tree) const -{ - if (userWidgetSize() >= 0) - return userWidgetSize(); - - if (userWidgetToContent_) - return widthCache_.getOrUpdate(tree, this, 0); - else - return 40; -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.h deleted file mode 100644 index a512fd330a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowField.h +++ /dev/null @@ -1,39 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWFIELD_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWFIELD_H -#pragma once - -#include "PropertyRow.h" -class QIcon; - -class PropertyRowField : public PropertyRow -{ -public: - WidgetPlacement widgetPlacement() const override{ return WIDGET_VALUE; } - int widgetSizeMin(const QPropertyTree* tree) const override; - - virtual int buttonCount() const{ return 0; } - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const; - virtual bool usePathEllipsis() const { return false; } - virtual bool onActivateButton([[maybe_unused]] int buttonIndex, [[maybe_unused]] const PropertyActivationEvent& e) { return false; } - - void redraw(const PropertyDrawContext& context) override; - bool onActivate(const PropertyActivationEvent& e) override; -protected: - QRect fieldRect(const QPropertyTree* tree) const; - void drawButtons(int* offset); - - mutable RowWidthCache widthCache_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWFIELD_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowIconXPM.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowIconXPM.cpp deleted file mode 100644 index 1227ec20d7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowIconXPM.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/** - * yasli - Serialization Library. - * Copyright (C) 2007-2013 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "Serialization/ClassFactory.h" - -#include "PropertyDrawContext.h" -#include "PropertyRowImpl.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include "Color.h" -#include "Serialization/Decorators/IconXPM.h" -using Serialization::IconXPM; -using Serialization::IconXPMToggle; - -class PropertyRowIconXPM : public PropertyRow{ -public: - void redraw(const PropertyDrawContext& context) - { - QRect rect = context.widgetRect; - context.drawIcon(rect, icon_); - } - - bool isLeaf() const{ return true; } - bool isStatic() const{ return false; } - bool isSelectable() const{ return false; } - - bool onActivate([[maybe_unused]] const PropertyActivationEvent& e) - { - return false; - } - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override { - YASLI_ESCAPE(ser.size() == sizeof(IconXPM), return); - icon_ = *(IconXPM*)(ser.pointer()); - } - wstring valueAsWString() const{ return L""; } - WidgetPlacement widgetPlacement() const{ return WIDGET_ICON; } - void serializeValue([[maybe_unused]] Serialization::IArchive& ar) {} - int widgetSizeMin(const QPropertyTree* tree) const override{ return tree->_defaultRowHeight(); } - int height() const{ return 16; } -protected: - IconXPM icon_; -}; - -class PropertyRowIconToggle : public PropertyRow{ -public: - void redraw(const PropertyDrawContext& context) override - { - IconXPM& icon = value_ ? iconTrue_ : iconFalse_; - context.drawIcon(context.widgetRect, icon); - } - - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override { - YASLI_ESCAPE(ser.size() == sizeof(IconXPMToggle), return); - const IconXPMToggle* icon = (IconXPMToggle*)(ser.pointer()); - iconTrue_ = icon->iconTrue_; - iconFalse_ = icon->iconFalse_; - value_ = icon->value_; - } - - bool assignTo(const Serialization::SStruct& ser) const override - { - IconXPMToggle* toggle = (IconXPMToggle*)ser.pointer(); - toggle->value_ = value_; - return true; - } - - bool isLeaf() const override{ return true; } - bool isStatic() const override{ return false; } - bool isSelectable() const override{ return true; } - bool onActivate(const PropertyActivationEvent& e) - { - if (e.reason != e.REASON_RELEASE) - { - e.tree->model()->rowAboutToBeChanged(this); - value_ = !value_; - e.tree->model()->rowChanged(this); - return true; - } - return false; - } - DragCheckBegin onMouseDragCheckBegin() override - { - if (userReadOnly()) - return DRAG_CHECK_IGNORE; - return value_ ? DRAG_CHECK_UNSET : DRAG_CHECK_SET; - } - bool onMouseDragCheck(QPropertyTree* tree, bool value) override - { - if (value_ != value) { - tree->model()->rowAboutToBeChanged(this); - value_ = value; - tree->model()->rowChanged(this); - return true; - } - return false; - } - wstring valueAsWString() const{ return value_ ? L"true" : L"false"; } - WidgetPlacement widgetPlacement() const{ return WIDGET_ICON; } - - int widgetSizeMin(const QPropertyTree* tree) const{ return tree->_defaultRowHeight(); } - int height() const{ return 16; } - - IconXPM iconTrue_; - IconXPM iconFalse_; - bool value_; -}; - -REGISTER_PROPERTY_ROW(IconXPM, PropertyRowIconXPM); -REGISTER_PROPERTY_ROW(IconXPMToggle, PropertyRowIconToggle); -DECLARE_SEGMENT(PropertyRowIconXPM) diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowImpl.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowImpl.h deleted file mode 100644 index 61cf50c9ad..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowImpl.h +++ /dev/null @@ -1,48 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWIMPL_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWIMPL_H -#pragma once - -#include "Serialization/STL.h" -#include "PropertyRowField.h" -#include "Serialization.h" - -template -class PropertyRowImpl; - -template -class PropertyRowImpl : public PropertyRowField{ -public: - bool assignTo(const Serialization::SStruct& ser) const override { - *reinterpret_cast(ser.pointer()) = value(); - return true; - } - bool isLeaf() const override{ return true; } - bool isStatic() const override{ return false; } - void setValue(const Type& value) { value_ = value; } - Type& value() { return value_; } - const Type& value() const{ return value_; } - - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override { - YASLI_ESCAPE(ser.size() == sizeof(Type), return); - value_ = *(Type*)(ser.pointer()); - } - - void serializeValue(Serialization::IArchive& ar) override{ - ar(value_, "value", "Value"); - } -protected: - Type value_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWIMPL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.cpp deleted file mode 100644 index 6d318aecde..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.cpp +++ /dev/null @@ -1,152 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowLocalFrame.h" -#include -#include -#include -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include -#include -#include "Serialization/ClassFactory.h" -#include "PropertyDrawContext.h" -#include "Serialization.h" -#include - -using Serialization::LocalPosition; - -void LocalFrameMenuHandler::onMenuReset() -{ - self->reset(tree); -} - -PropertyRowLocalFrameBase::PropertyRowLocalFrameBase() - : m_sink(0) - , m_gizmoIndex(-1) - , m_handle(0) - , m_reset(false) -{ -} - -PropertyRowLocalFrameBase::~PropertyRowLocalFrameBase() -{ - m_sink = 0; -} - -bool PropertyRowLocalFrameBase::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE) - { - return false; - } - return false; -} - -string PropertyRowLocalFrameBase::valueAsString() const -{ - return string(); -} - -bool PropertyRowLocalFrameBase::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - Serialization::SharedPtr selfPointer(this); - - LocalFrameMenuHandler* handler = new LocalFrameMenuHandler(tree, this); - - menu.addAction("Reset", handler, SLOT(onMenuReset())); - - tree->addMenuHandler(handler); - return true; -} - -void PropertyRowLocalFrameBase::reset(QPropertyTree* tree) -{ - tree->model()->rowAboutToBeChanged(this); - m_reset = true; - tree->model()->rowChanged(this); -} - -void PropertyRowLocalFrameBase::redraw(const PropertyDrawContext& context) -{ - static QIcon gizmo("Icons/animation/gizmo_location.png"); - gizmo.paint(context.painter, context.widgetRect.adjusted(1, 1, 1, 1), Qt::AlignRight); -} - -static void ResetTransform(Serialization::LocalPosition* l) { *l->value = ZERO; } -static void ResetTransform(Serialization::LocalOrientation* l) { *l->value = IDENTITY; } -static void ResetTransform(Serialization::LocalFrame* l) { *l->position = ZERO; *l->rotation = IDENTITY; } - -template -class PropertyRowLocalFrameImpl - : public PropertyRowLocalFrameBase -{ -public: - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override - { - serializer_ = ser; - - TLocal* value = (TLocal*)ser.pointer(); - m_handle = value->handle; - m_reset = false; - - if (label() && label()[0]) - { - m_sink = ar.FindContext(); - if (m_sink) - { - m_gizmoIndex = m_sink->Write(*value, m_gizmoFlags, m_handle); - } - } - } - - void closeNonLeaf(const Serialization::SStruct& ser, Serialization::IArchive& ar) override - { - if (label() && label()[0] && ar.IsInput()) - { - TLocal& value = *((TLocal*)ser.pointer()); - if (m_sink) - { - if (m_sink->CurrentGizmoIndex() == m_gizmoIndex) - { - m_sink->Read(&value, &m_gizmoFlags, m_handle); - } - else - { - m_sink->SkipRead(); - } - } - } - } - - bool assignTo(const Serialization::SStruct& ser) const - { - if (m_reset) - { - TLocal& value = *((TLocal*)ser.pointer()); - ResetTransform(&value); - } - return false; - } -}; - -typedef PropertyRowLocalFrameImpl PropertyRowLocalPosition; -typedef PropertyRowLocalFrameImpl PropertyRowLocalOrientation; -typedef PropertyRowLocalFrameImpl PropertyRowLocalFrame; - -REGISTER_PROPERTY_ROW(Serialization::LocalPosition, PropertyRowLocalPosition); -REGISTER_PROPERTY_ROW(Serialization::LocalOrientation, PropertyRowLocalOrientation); -REGISTER_PROPERTY_ROW(Serialization::LocalFrame, PropertyRowLocalFrame); - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.h deleted file mode 100644 index 44b0597542..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowLocalFrame.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWLOCALFRAME_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWLOCALFRAME_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "Serialization/Decorators/IGizmoSink.h" -#include "PropertyRowField.h" -#include "QPropertyTree.h" -#endif - -struct IGizmoSink; - -class PropertyRowLocalFrameBase - : public PropertyRow -{ -public: - PropertyRowLocalFrameBase(); - ~PropertyRowLocalFrameBase(); - - bool isLeaf() const override { return m_reset; } - bool isStatic() const override { return false; } - - bool onActivate(const PropertyActivationEvent& e) override; - - WidgetPlacement widgetPlacement() const override { return WIDGET_AFTER_PULLED; } - int widgetSizeMin(const QPropertyTree* tree) const override { return tree->_defaultRowHeight(); } - - string valueAsString() const override; - bool onContextMenu(QMenu& menu, QPropertyTree* tree) override; - const void* searchHandle() const override { return m_handle; } - void redraw(const PropertyDrawContext& context) override; - - void reset(QPropertyTree* tree); -protected: - Serialization::IGizmoSink* m_sink; - const void* m_handle; - int m_gizmoIndex; - mutable Serialization::GizmoFlags m_gizmoFlags; - bool m_reset; -}; - -struct LocalFrameMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowLocalFrameBase* self; - - LocalFrameMenuHandler(QPropertyTree* tree, PropertyRowLocalFrameBase* self) - : tree(tree) - , self(self) {} -public slots: - void onMenuReset(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWLOCALFRAME_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.cpp deleted file mode 100644 index 3ba58a83aa..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include "PropertyRowNumber.h" - -#define REGISTER_NUMBER_ROW(TypeName, postfix) \ - typedef PropertyRowNumber PropertyRow##postfix; \ - typedef Serialization::RangeDecorator RangeDecorator##postfix; \ - PropertyRow* TypeName##postfixFactory() { return new PropertyRow##postfix; }; \ - REGISTER_IN_FACTORY(PropertyRowFactory, Serialization::TypeID::get().name(), PropertyRow##postfix, TypeName##postfixFactory); \ - SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRow##postfix, "PropertyRow" #postfix, #TypeName); - -REGISTER_NUMBER_ROW(float, Float) -REGISTER_NUMBER_ROW(double , Double) - -REGISTER_NUMBER_ROW(char, Char) -REGISTER_NUMBER_ROW(int8, Int8) -REGISTER_NUMBER_ROW(uint8, Uint8) - -REGISTER_NUMBER_ROW(int16, Int16) -REGISTER_NUMBER_ROW(int32, Int32) -REGISTER_NUMBER_ROW(int64, Int64) -REGISTER_NUMBER_ROW(uint16, Uint16) -REGISTER_NUMBER_ROW(uint32, Uint32) -REGISTER_NUMBER_ROW(uint64, Uint64) - -#undef REGISTER_NUMBER_ROW - -DECLARE_SEGMENT(PropertyRowNumber) - -// --------------------------------------------------------------------------- diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.h deleted file mode 100644 index 8658f5d878..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumber.h +++ /dev/null @@ -1,237 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBER_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBER_H -#pragma once - - -#include "QPropertyTree.h" -#include "Serialization/MemoryWriter.h" -#include "Serialization/Decorators/Range.h" -#include "PropertyRowNumberField.h" - -#include -#include -#include - -template -string numberAsString(T value) -{ - Serialization::MemoryWriter buf; - buf << value; - return buf.c_str(); -} - -inline long long stringToSignedInteger(const char* str) -{ - long long value; -#ifdef _MSC_VER - value = _atoi64(str); -#else - char* endptr = (char*)str; - value = strtoll(str, &endptr, 10); -#endif - return value; -} - -inline unsigned long long stringToUnsignedInteger(const char* str) -{ - unsigned long long value; - if (*str == '-') { - value = 0; - } - else { -#ifdef _MSC_VER - char* endptr = (char*)str; - value = _strtoui64(str, &endptr, 10); -#else - char* endptr = (char*)str; - value = strtoull(str, &endptr, 10); -#endif - } - return value; -} - -template -Output clamp(Input value, Output min, Output max) -{ - if (value < Input(min)) - return min; - if (value > Input(max)) - return max; - return Output(value); -} - -template void clampToType(Out* out, In value) { *out = clamp(value, std::numeric_limits::lowest(), std::numeric_limits::max()); } - -inline void clampedNumberFromString(char* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(signed char* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(short* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(int* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(long* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(long long* value, const char* str) { clampToType(value, stringToSignedInteger(str)); } -inline void clampedNumberFromString(unsigned char* value, const char* str) { clampToType(value, stringToUnsignedInteger(str)); } -inline void clampedNumberFromString(unsigned short* value, const char* str) { clampToType(value, stringToUnsignedInteger(str)); } -inline void clampedNumberFromString(unsigned int* value, const char* str) { clampToType(value, stringToUnsignedInteger(str)); } -inline void clampedNumberFromString(unsigned long* value, const char* str) { clampToType(value, stringToUnsignedInteger(str)); } -inline void clampedNumberFromString(unsigned long long* value, const char* str) { clampToType(value, stringToUnsignedInteger(str)); } -inline void clampedNumberFromString(float* value, const char* str) -{ - double v = atof(str); - if (v > FLT_MAX) - v = FLT_MAX; - if (v < -FLT_MAX) - v = -FLT_MAX; - *value = float(v); -} - -inline void clampedNumberFromString(double* value, const char* str) -{ - *value = atof(str); -} - - -template -class PropertyRowNumber : public PropertyRowNumberField{ -public: - PropertyRowNumber() - { - softMin_ = std::numeric_limits::lowest(); - softMax_ = std::numeric_limits::max(); - hardMin_ = std::numeric_limits::lowest(); - hardMax_ = std::numeric_limits::max(); - } - - void setValue(Type value, const void* handle, const Serialization::TypeID& type) - { - value_ = value; - serializer_.setPointer((void*)handle); - serializer_.setType(type); - } - bool setValueFromString(const char* str) override{ - Type value = value_; - clampedNumberFromString(&value_, str); - return value_ != value; - } - string valueAsString() const override - { - return numberAsString(Type(value_)); - } - - bool assignToPrimitive(void* object, [[maybe_unused]] size_t size) const override - { - *reinterpret_cast(object) = value_; - return true; - } - - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - Serialization::RangeDecorator* range = (Serialization::RangeDecorator*)ser.pointer(); - serializer_.setPointer((void*)range->value); - serializer_.setType(Serialization::TypeID::get()); - value_ = *range->value; - softMin_ = range->softMin; - softMax_ = range->softMax; - hardMin_ = range->hardMin; - hardMax_ = range->hardMax; - } - - bool assignTo(const Serialization::SStruct& ser) const override - { - if (ser.type() == Serialization::TypeID::get>()) { - Serialization::RangeDecorator* range = (Serialization::RangeDecorator*)ser.pointer(); - *range->value = value_; - } - else if (ser.type() == Serialization::TypeID::get()) { - *(Type*)ser.pointer() = value_; - } - return true; - } - - void serializeValue(Serialization::IArchive& ar) - { - ar(value_, "value", "Value"); - ar(softMin_, "softMin", "SoftMin"); - ar(softMax_, "softMax", "SoftMax"); - ar(hardMin_, "hardMin", "HardMin"); - ar(hardMax_, "hardMax", "HardMax"); - } - - void startIncrement() override - { - incrementStartValue_ = value_; - } - - void endIncrement(QPropertyTree* tree) override - { - if (value_ != incrementStartValue_) { - Type value = value_; - value_ = incrementStartValue_; - value_ = value; - tree->model()->rowChanged(this, true); - } - } - - void incrementLog(float screenFraction, float valueFieldFraction) - { - bool bothSoftLimitsSet = (std::numeric_limits::lowest() == 0 || softMin_ != std::numeric_limits::lowest()) && softMax_ != std::numeric_limits::max(); - - if (bothSoftLimitsSet) - { - Type softRange = softMax_ - softMin_; - double newValue = incrementStartValue_ + softRange * valueFieldFraction; - value_ = clamp(newValue, hardMin_, hardMax_); - } - else - { - double screenFractionMultiplier = 1000.0; - if (Serialization::TypeID::get() == Serialization::TypeID::get() || - Serialization::TypeID::get() == Serialization::TypeID::get()) - screenFractionMultiplier = 10.0; - - double startPower = log10(fabs(double(incrementStartValue_)) + 1.0) - 3.0; - double power = startPower + fabs(screenFraction) * 10.0f; - double delta = pow(10.0, power) - pow(10.0, startPower) + screenFractionMultiplier * fabs(screenFraction); - double newValue; - if (screenFraction > 0.0f) - newValue = double(incrementStartValue_) + delta; - else - newValue = double(incrementStartValue_) - delta; -#ifdef _MSC_VER - if (_isnan(newValue)) { -#else - if (isnan(newValue)) { -#endif - if (screenFraction > 0.0f) - newValue = DBL_MAX; - else - newValue = -DBL_MAX; - } - value_ = clamp(newValue, hardMin_, hardMax_); - } - } - - double sliderPosition() const override - { - if ((softMin_ == std::numeric_limits::lowest() && softMax_ == std::numeric_limits::max() && softMax_ != Type(255)) || (softMin_ >= softMax_)) - return 0.0; - return clamp(double(value_ - softMin_) / (softMax_ - softMin_), 0.0, 1.0); - } -protected: - Type incrementStartValue_; - Type value_; - Type softMin_; - Type softMax_; - Type hardMin_; - Type hardMax_; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.cpp deleted file mode 100644 index 94b30fb2ab..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.cpp +++ /dev/null @@ -1,287 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "QPropertyTree.h" -#include "QPropertyTreeStyle.h" -#include "PropertyTreeModel.h" -#include "PropertyRowNumberField.h" -#include "PropertyDrawContext.h" -#include "MathUtils.h" -#include -#include -#include -#include -#include - -PropertyRowNumberField::PropertyRowNumberField() - : pressed_(false) - , dragStarted_(false) -{ -} - -PropertyRowWidget* PropertyRowNumberField::createWidget(QPropertyTree* tree) -{ - return new PropertyRowWidgetNumber(tree->model(), this, tree); -} - -QColor interpolateColor(const QColor& a, const QColor& b, float k); - -void PropertyRowNumberField::redraw(const PropertyDrawContext& context) -{ - if (multiValue()) - context.drawEntry(L" ... ", false, true, 0); - else if (userReadOnly()) - context.drawValueText(pulledSelected(), valueAsWString().c_str()); - else - { - QPainter* painter = context.painter; - const QPropertyTree* tree = context.tree; - - QRect rt = context.widgetRect; - rt.adjust(0, 0, 0, -1); - -#if (QT_VERSION < QT_VERSION_CHECK(5, 11, 0)) - QStyleOptionFrameV2 option; - option.features = QStyleOptionFrameV2::None; -#else - QStyleOptionFrame option; - option.features = QStyleOptionFrame::None; -#endif - - option.state = QStyle::State_Sunken; - - // We require a widget to use as context, so that the style sheet can work. - QLineEdit widgetForContext; - option.lineWidth = tree->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, &option, &widgetForContext); - - option.midLineWidth = 0; - - if (context.captured) { - option.state |= QStyle::State_HasFocus; - option.state |= QStyle::State_Active; - option.state |= QStyle::State_MouseOver; - } - else if (!userReadOnly()) { - option.state |= QStyle::State_Enabled; - } - option.rect = rt; // option.rect is the rectangle to be drawn on. - option.palette = tree->palette(); - option.fontMetrics = tree->fontMetrics(); - QRect textRect = tree->style()->subElementRect(QStyle::SE_LineEditContents, &option, &widgetForContext); - if (!textRect.isValid()) { - textRect = rt; - textRect.adjust(3, 1, -3, -2); - } - else { - textRect.adjust(2, 1, -2, -1); - } - - - widgetForContext.ensurePolished(); - option.palette = widgetForContext.palette(); - - painter->setPen(QPen(widgetForContext.palette().color(QPalette::WindowText))); - painter->setBrush(QBrush(widgetForContext.palette().color(QPalette::Base))); - tree->style()->drawPrimitive(QStyle::PE_PanelLineEdit, &option, painter, &widgetForContext); - - double sliderPos = sliderPosition(); - if (sliderPos != 0.0) - { - QRect r = textRect.adjusted(-2, -1, 2, 1); - QRect sliderOverlayRect(r.left(), r.top(), int(r.width() * sliderPos), r.height()); - QColor sliderOverlayColor = interpolateColor(tree->palette().color(QPalette::Window), tree->palette().color(QPalette::Highlight), tree->treeStyle().sliderSaturation); - sliderOverlayColor.setAlpha(192); - painter->setBrush(QBrush(sliderOverlayColor)); - painter->setPen(Qt::NoPen); - painter->drawRoundedRect(sliderOverlayRect, 1, 1); - - if (pressed_) { - painter->setPen(QColor(255, 255, 255)); - painter->setBrush(QBrush(QColor(255, 255, 255))); - painter->drawLine(sliderOverlayRect.right(), sliderOverlayRect.top(), sliderOverlayRect.right(), sliderOverlayRect.bottom()); - painter->setRenderHint(QPainter::Antialiasing, true); - painter->translate(0.5f, 0.5f); - int r2 = sliderOverlayRect.right(); - int t = sliderOverlayRect.top(); - int h = sliderOverlayRect.height(); - QPoint points[3] = { - QPoint(r2 - 1 - h / 8 - h / 3, t + h / 2), - QPoint(r2 - 1 - h / 8, t + h * 1 / 4), - QPoint(r2 - 1 - h / 8, t + h * 3 / 4) - }; - QPoint pointsR[3] = { - QPoint(r2 + 1 + h / 8 + h / 3, t + h / 2), - QPoint(r2 + 1 + h / 8, t + h * 1 / 4), - QPoint(r2 + 1 + h / 8, t + h * 3 / 4) - }; - painter->drawPolygon(points, 3); - painter->drawPolygon(pointsR, 3); - painter->setRenderHint(QPainter::Antialiasing, false); - painter->translate(-0.5f, -0.5f); - } - } - - painter->setPen(QPen(widgetForContext.palette().color(QPalette::WindowText))); - painter->setBrush(QBrush(widgetForContext.palette().color(QPalette::Base))); - painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, QString(valueAsString().c_str())); - - - } -} - -QCursor createSliderHoverCursor() -{ - QCursor arrow(Qt::ArrowCursor); - QPoint hotSpot = arrow.hotSpot(); - static QImage image = arrow.pixmap().toImage(); - if (image.isNull()) - return QCursor(Qt::SizeHorCursor); - - int w = image.width(); - int h = image.height(); - QImage empty(w * 2, h, QImage::Format_ARGB32); - empty.fill(Qt::transparent); - QPixmap pixmap = QPixmap::fromImage(empty); - if (pixmap.isNull()) - return QCursor(Qt::SizeHorCursor); - QPainter p(&pixmap); - p.drawImage(image.width() / 2, 0, image); - p.setRenderHint(QPainter::Antialiasing, true); - - QPoint points[3] = { - QPoint(w / 2 - w * 2 / 8, h / 2), - QPoint(w / 2 - w / 8, h * 3 / 8), - QPoint(w / 2 - w / 8, h * 5 / 8) - }; - QPoint pointsR[3] = { - QPoint(w, h * 3 / 8), - QPoint(w, h * 5 / 8), - QPoint(w + w / 8, h / 2), - }; - p.setBrush(QBrush(QColor(255, 255, 255))); - p.setPen(QPen(QColor(0, 0, 0))); - p.drawPolygon(points, 3); - p.drawPolygon(pointsR, 3); - return QCursor(pixmap, image.width() / 2 + hotSpot.x(), hotSpot.y()); -} - - -void PropertyRowNumberField::onMouseDrag(const PropertyDragEvent& e) -{ - if (!dragStarted_) { - e.tree->model()->rowAboutToBeChanged(this); - dragStarted_ = true; - } - QSize screenSize = QApplication::desktop()->screenGeometry(e.tree).size(); - float relativeDelta = float(e.totalDelta.x()) / screenSize.width(); - int fieldRectWidth = widgetRect(e.tree).width(); - if (fieldRectWidth < 16) - fieldRectWidth = aznumeric_cast(e.tree->treeSize().x() * e.tree->valueColumnWidth()); - float valueFieldFraction = fieldRectWidth < FLT_EPSILON ? 0 : float(e.totalDelta.x()) / fieldRectWidth; - incrementLog(relativeDelta, valueFieldFraction); - setMultiValue(false); -} - -bool PropertyRowNumberField::getHoverInfo(PropertyHoverInfo* hit, const QPoint& cursorPos, const QPropertyTree* tree) const -{ - if (pressed_ && !userReadOnly()) - hit->cursor = QCursor(Qt::BlankCursor); - else if (widgetRect(tree).contains(cursorPos) && !userReadOnly()) - hit->cursor = QCursor(createSliderHoverCursor()); - hit->toolTip = tooltip_; - return true; -} - -void PropertyRowNumberField::onMouseStill(const PropertyDragEvent& e) -{ - e.tree->model()->callRowCallback(this); - e.tree->apply(true); -} - -bool PropertyRowNumberField::onMouseDown(QPropertyTree* tree, QPoint point, bool& changed) -{ - changed = false; - if (widgetRect(tree).contains(point) && !userReadOnly()) { - startIncrement(); - pressed_ = true; - return true; - } - return false; -} - -void PropertyRowNumberField::onMouseUp(QPropertyTree* tree, [[maybe_unused]] QPoint point) -{ - tree->unsetCursor(); - pressed_ = false; - dragStarted_ = false; - - // endIncrement() can cause PropertyRow to be destroy, - // so no "this" members should be accessed after the call. - endIncrement(tree); -} - -bool PropertyRowNumberField::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE || e.reason == e.REASON_DOUBLECLICK) - return e.tree->spawnWidget(this, false); - return false; -} - -int PropertyRowNumberField::widgetSizeMin(const QPropertyTree* tree) const -{ - if (userWidgetSize() >= 0) - return userWidgetSize(); - - if (userWidgetToContent()) - return widthCache_.getOrUpdate(tree, this, 0); - else - return 40; -} - -// --------------------------------------------------------------------------- - -PropertyRowWidgetNumber::PropertyRowWidgetNumber([[maybe_unused]] PropertyTreeModel* model, PropertyRowNumberField* row, QPropertyTree* tree) - : PropertyRowWidget(row, tree) - , row_(row) - , entry_(new QLineEdit()) - , tree_(tree) -{ - entry_->setText(row_->valueAsString().c_str()); - connect(entry_, SIGNAL(editingFinished()), this, SLOT(onEditingFinished())); - connect(entry_, &QLineEdit::textChanged, this, [this, tree] { - QFontMetrics fm(entry_->font()); - int contentWidth = min((int)fm.horizontalAdvance(entry_->text()) + 8, tree->width() - entry_->x()); - if (contentWidth > entry_->width()) - entry_->resize(contentWidth, entry_->height()); - }); - - entry_->selectAll(); -} - - -void PropertyRowWidgetNumber::onEditingFinished() -{ - tree_->model()->rowAboutToBeChanged(row()); - string str = entry_->text().toLocal8Bit().data(); - if (row_->setValueFromString(str.c_str()) || row_->multiValue()) - tree_->model()->rowChanged(row()); - else - tree_->_cancelWidget(); -} - -void PropertyRowWidgetNumber::commit() -{ - if (entry_) - onEditingFinished(); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.h deleted file mode 100644 index 888fb204fe..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowNumberField.h +++ /dev/null @@ -1,75 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBERFIELD_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBERFIELD_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyRow.h" -#include -#endif - -class PropertyRowNumberField; -class PropertyRowWidgetNumber : public PropertyRowWidget -{ - Q_OBJECT -public: - PropertyRowWidgetNumber(PropertyTreeModel* mode, PropertyRowNumberField* numberField, QPropertyTree* tree); - ~PropertyRowWidgetNumber(){ - if (entry_) - entry_->setParent(0); - entry_->deleteLater(); - entry_ = 0; - } - - void commit(); - QWidget* actualWidget() { return entry_; } -public slots: - void onEditingFinished(); -protected: - QLineEdit* entry_; - PropertyRowNumberField* row_; - QPropertyTree* tree_; -}; - -// --------------------------------------------------------------------------- - -class PropertyRowNumberField : public PropertyRow -{ -public: - PropertyRowNumberField(); - WidgetPlacement widgetPlacement() const override{ return WIDGET_VALUE; } - int widgetSizeMin(const QPropertyTree* tree) const override; - - PropertyRowWidget* createWidget(QPropertyTree* tree) override; - bool isLeaf() const override{ return true; } - bool isStatic() const override{ return false; } - bool inlineInShortArrays() const override{ return true; } - void redraw(const PropertyDrawContext& context) override; - bool onActivate(const PropertyActivationEvent& e) override; - bool onMouseDown(QPropertyTree* tree, QPoint point, bool& changed) override; - void onMouseUp(QPropertyTree* tree, QPoint point) override; - void onMouseDrag(const PropertyDragEvent& e) override; - void onMouseStill(const PropertyDragEvent& e) override; - bool getHoverInfo(PropertyHoverInfo* hit, const QPoint& cursorPos, const QPropertyTree* tree) const; - - virtual void startIncrement() = 0; - virtual void endIncrement(QPropertyTree* tree) = 0; - virtual void incrementLog(float screenFraction, float valueFieldFraction) = 0; - virtual bool setValueFromString(const char* str) = 0; - virtual double sliderPosition() const = 0; - - mutable RowWidthCache widthCache_; - bool pressed_ : 1; - bool dragStarted_ : 1; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWNUMBERFIELD_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.cpp deleted file mode 100644 index 35ffd659f2..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowObject.h" -#include "PropertyTreeModel.h" - -PropertyRowObject::PropertyRowObject() - : model_(0) -{ -} - -bool PropertyRowObject::assignTo(Serialization::Object* obj) -{ - if (object_.type() == obj->type()) - { - *obj = object_; - return true; - } - return false; -} - -PropertyRowObject::~PropertyRowObject() -{ - object_ = Serialization::Object(); -} - -void PropertyRowObject::Serialize(Serialization::IArchive& ar) -{ - PropertyRow::Serialize(ar); -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.h deleted file mode 100644 index 8f6f44cc00..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowObject.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOBJECT_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOBJECT_H -#pragma once -#include "PropertyRow.h" -#include "Serialization/MemoryWriter.h" -#include "Serialization/Pointers.h" -#include "Serialization/Object.h" - -namespace Serialization { - class IArchive; - struct SStruct; - class MemoryWriter; -}; - -class PropertyRowObject - : public PropertyRow -{ -public: - PropertyRowObject(); - ~PropertyRowObject(); - - using PropertyRow::setValueAndContext; - using PropertyRow::assignTo; - - void setValueAndContext(const Serialization::Object& obj, [[maybe_unused]] Serialization::IArchive& ar) { object_ = obj; } - void setModel(PropertyTreeModel* model) { model_ = model; } - bool isObject() const override { return true; } - bool assignTo(Serialization::Object* obj); - void Serialize(Serialization::IArchive& ar); - const Serialization::Object& object() const{ return object_; } -protected: - - Serialization::Object object_; - PropertyTreeModel* model_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOBJECT_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.cpp deleted file mode 100644 index 545ba4a02d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowOutputFilePath.h" -#include "Serialization/ClassFactory.h" -#include -#ifndef SERIALIZATION_STANDALONE -#include -#include // for Getting game folder -#endif -#include -#include -#include -#include - -OutputFilePathMenuHandler::OutputFilePathMenuHandler(QPropertyTree* tree, PropertyRowOutputFilePath* self) - : self(self) - , tree(tree) -{ -} - - -void OutputFilePathMenuHandler::onMenuClear() -{ - tree->model()->rowAboutToBeChanged(self); - self->clear(); - tree->model()->rowChanged(self); -} - -QString convertMFCToQtFileFilter(QString* defaultSuffix, const char* mfcFilter) -{ - // convert filter from "All Files|*.*|Text files|*.txt||" - // format into "All files (*.*);;Text Files (*.txt)" - QString filterMFC = QString::fromLocal8Bit(mfcFilter); - QStringList filterItems = filterMFC.split("|"); - - if (defaultSuffix && filterItems.size() > 1) - { - QString extensions = filterItems[1]; - QRegExp re("\\*\\.(\\w*)"); - if (extensions.indexOf(re) >= 0) - { - *defaultSuffix = re.cap(1); - } - } - - QString filter; - for (int i = 0; i < int(filterItems.size()) / 2; ++i) - { - int bracketPos = filterItems[i].indexOf('('); - QString desc = bracketPos >= 0 ? filterItems[i].left(bracketPos) : filterItems[i]; - int extIndex = i * 2 + 1; - if (extIndex >= filterItems.size()) - { - break; - } - if (!filter.isEmpty()) - { - filter += ";;"; - } - filter += desc; - filter += " ("; - filter += filterItems[extIndex]; - filter += ")"; - } - - return filter; -} - -bool PropertyRowOutputFilePath::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE) - { - return false; - } -#ifndef SERIALIZATION_STANDALONE - if (!GetIEditor()) - { - return true; - } -#endif - - QString title; - if (labelUndecorated()) - { - title = QString("Choose file for '") + labelUndecorated() + "'"; - } - else - { - title = "Choose file"; - } - -#ifdef SERIALIZATION_STANDALONE - QString gameFolder; -#else - QString gameFolder = QString::fromLocal8Bit(Path::GetEditingGameDataFolder().c_str()); -#endif - QDir gameFolderDir(QDir::fromNativeSeparators(gameFolder)); - QString defaultSuffix; - QString filter = convertMFCToQtFileFilter(&defaultSuffix, filter_.c_str()); - QString existingFile = QString::fromLocal8Bit(path_.c_str()); - - QString existingFilePath = (existingFile.isEmpty() || QDir::isAbsolutePath(existingFile)) ? existingFile : gameFolderDir.absoluteFilePath(existingFile); - QString startFolder = QString::fromLocal8Bit(startFolder_.c_str()); - - // Not using QFileDialog().exec() as it implements custom file dialog that - // freezes for couple of seconds when being open. Scannign network drives? - QString result = QFileDialog::getSaveFileName(e.tree, title, existingFilePath.isEmpty() ? (gameFolder + "/" + startFolder) : existingFilePath, filter); - if (!result.isEmpty()) - { - e.tree->model()->rowAboutToBeChanged(this); - QString relativeFilename = gameFolderDir.relativeFilePath(result); - path_ = relativeFilename.toLocal8Bit().data(); - e.tree->model()->rowChanged(this); - } - return true; -} -void PropertyRowOutputFilePath::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - OutputFilePath* value = (OutputFilePath*)ser.pointer(); - path_ = value->m_path->c_str(); - filter_ = value->filter.c_str(); - startFolder_ = value->startFolder.c_str(); - handle_ = value->m_path; -} - -bool PropertyRowOutputFilePath::assignTo(const Serialization::SStruct& ser) const -{ - ((OutputFilePath*)ser.pointer())->SetPath(path_.c_str()); - return true; -} - -const QIcon& PropertyRowOutputFilePath::buttonIcon(const QPropertyTree* tree, [[maybe_unused]] int index) const -{ - #include "file_save.xpm" - static QIcon fileOpenIcon = QIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(file_save_xpm)))); - return fileOpenIcon; -} - -string PropertyRowOutputFilePath::valueAsString() const -{ - return path_; -} - - -void PropertyRowOutputFilePath::clear() -{ - path_.clear(); -} - -bool PropertyRowOutputFilePath::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - QAction* action = menu.addAction("Clear"); - Serialization::SharedPtr selfPointer(this); - - OutputFilePathMenuHandler* handler = new OutputFilePathMenuHandler(tree, this); - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuClear())); - tree->addMenuHandler(handler); - return true; -} - -void PropertyRowOutputFilePath::serializeValue(Serialization::IArchive& ar) -{ - ar(path_, "path"); - ar(filter_, "filter"); - ar(startFolder_, "startFolder"); -} - -bool PropertyRowOutputFilePath::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowOutputFilePath::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -REGISTER_PROPERTY_ROW(OutputFilePath, PropertyRowOutputFilePath); -DECLARE_SEGMENT(PropertyRowOutputFilePath) - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.h deleted file mode 100644 index d9f4cb1489..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowOutputFilePath.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOUTPUTFILEPATH_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOUTPUTFILEPATH_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "PropertyRowField.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include -#include -#endif - -using Serialization::OutputFilePath; - -class PropertyRowOutputFilePath - : public PropertyRowField -{ -public: - void clear(); - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - - bool onActivate(const PropertyActivationEvent& e) override; - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - string valueAsString() const; - void serializeValue(Serialization::IArchive& ar); - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - const void* searchHandle() const { return handle_; } - - int buttonCount() const override { return 1; } - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - virtual bool usePathEllipsis() const override { return true; } - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - string path_; - string filter_; - string startFolder_; - const void* handle_; -}; - -struct OutputFilePathMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowOutputFilePath* self; - - OutputFilePathMenuHandler(QPropertyTree* tree, PropertyRowOutputFilePath* container); -public slots: - void onMenuClear(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWOUTPUTFILEPATH_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.cpp deleted file mode 100644 index d11897b043..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.cpp +++ /dev/null @@ -1,346 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowPointer.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "PropertyDrawContext.h" -#include "Serialization.h" -#include "Unicode.h" -#include - - -// --------------------------------------------------------------------------- - -void ClassMenuItemAdder::generateMenu(QMenu& createItem, const StringList& comboStrings) -{ - StringList::const_iterator it; - int index = 0; - for (it = comboStrings.begin(); it != comboStrings.end(); ++it) - { - StringList path; - splitStringList(&path, it->c_str(), '\\'); - QMenu* item = &createItem; - //createItem.addMenu( - for (int level2 = 0; level2 < int(path.size()); ++level2) - { - const char* leaf = path[level2].c_str(); - if (level2 == path.size() - 1) - { - addAction(*item, leaf, index++); - } - else - { - if (QMenu* menu = item->findChild(leaf)) - { - item = menu; - } - else - { - item = addMenu(*item, leaf); //&item->add(leaf); - } - } - } - } -} - -void ClassMenuItemAdder::addAction(QMenu& menu, const char* text, [[maybe_unused]] int index) -{ - menu.addAction(text)->setEnabled(false); -} - -QMenu* ClassMenuItemAdder::addMenu(QMenu& menu, const char* text) -{ - QMenu* result = menu.addMenu(text); - result->setObjectName(text); - return result; -} - - -// --------------------------------------------------------------------------- - -SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRowPointer, "PropertyRowPointer", "SharedPtr"); - -PropertyRowPointer::PropertyRowPointer() - : factory_(0) - , searchHandle_(0) - , colorOverride_(0, 0, 0, 0) -{ -} - -void PropertyRowPointer::setDerivedType(const char* typeName, Serialization::IClassFactory* factory) -{ - if (!factory) - { - derivedTypeName_.clear(); - return; - } - derivedTypeName_ = typeName; -} - -bool PropertyRowPointer::assignTo(Serialization::IPointer& ptr) -{ - if (derivedTypeName_ != ptr.registeredTypeName()) - { - ptr.create(derivedTypeName_.c_str()); - } - - return true; -} - - -void CreatePointerMenuHandler::onMenuCreateByIndex() -{ - tree->model()->rowAboutToBeChanged(row); - if (index < 0) // NULL value - { - row->setDerivedType("", 0); - row->clear(); - } - else - { - const PropertyDefaultDerivedTypeValue* defaultValue = tree->model()->defaultType(row->baseType(), index); - SharedPtr clonedDefault = defaultValue->root->clone(tree->model()->constStrings()); - if (defaultValue && defaultValue->root) - { - YASLI_ASSERT(defaultValue->root->refCount() == 1); - if (useDefaultValue) - { - row->clear(); - row->swapChildren(clonedDefault, 0); - } - row->setDerivedType(defaultValue->registeredName.c_str(), row->factory()); - row->setLabelChanged(); - row->setLabelChangedToChildren(); - tree->expandRow(row); - } - else - { - row->setDerivedType("", 0); - row->clear(); - } - } - tree->model()->rowChanged(row); -} - - -string PropertyRowPointer::valueAsString() const -{ - string result; - const Serialization::TypeDescription* desc = 0; - if (factory_) - { - desc = factory_->descriptionByRegisteredName(derivedTypeName_.c_str()); - } - if (desc) - { - result = desc->label(); - } - else - { - result = derivedTypeName_; - } - - return result; -} - -wstring PropertyRowPointer::generateLabel() const -{ - if (multiValue()) - { - return L"..."; - } - - wstring str; - if (!derivedTypeName_.empty()) - { - const char* textStart = derivedTypeName_.c_str(); - if (factory_) - { - const Serialization::TypeDescription* desc = factory_->descriptionByRegisteredName(derivedTypeName_.c_str()); - - if (desc) - { - textStart = desc->label(); - } - } - const char* p = textStart + strlen(textStart); - while (p > textStart) - { - if (*(p - 1) == '\\') - { - break; - } - --p; - } - str = toWideChar(p); - if (p != textStart) - { - str += L" ("; - str += toWideChar(string(textStart, p - 1).c_str()); - str += L")"; - } - } - else - { - if (factory_) - { - str = toWideChar(factory_->nullLabel() ? factory_->nullLabel() : "[ null ]"); - } - else - { - str = L"[ null ]"; - } - } - return str; -} - -void PropertyRowPointer::redraw(const PropertyDrawContext& context) -{ - QRect widgetRect = context.widgetRect; - QRect rt = widgetRect; - rt.adjust(-1, 0, 0, 1); - wstring str = generateLabel(); - const QFont* font = derivedTypeName_.empty() ? &context.tree->font() : &context.tree->_boldFont(); - int buttonFlags = BUTTON_POPUP_ARROW; - if (userReadOnly()) - { - buttonFlags |= BUTTON_DISABLED; - } - if (context.m_pressed) - { - buttonFlags |= BUTTON_PRESSED; - } - context.drawButton(rt, str.c_str(), buttonFlags, font, colorOverride_.a != 0 ? &colorOverride_ : 0); -} - -struct ClassMenuItemAdderRowPointer - : ClassMenuItemAdder -{ - ClassMenuItemAdderRowPointer(PropertyRowPointer* row, QPropertyTree* tree) - : row_(row) - , tree_(tree) {} - void addAction(QMenu& menu, const char* text, int index) - { - CreatePointerMenuHandler* handler = new CreatePointerMenuHandler; - tree_->addMenuHandler(handler); - handler->row = row_; - handler->tree = tree_; - handler->index = index; - handler->useDefaultValue = !tree_->immediateUpdate(); - - QAction* action = menu.addAction(text); - - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuCreateByIndex())); - } -protected: - PropertyRowPointer* row_; - QPropertyTree* tree_; -}; - - -bool PropertyRowPointer::onActivate(QPropertyTree* tree, [[maybe_unused]] bool force) -{ - if (userReadOnly()) - { - return false; - } - QMenu menu; - ClassMenuItemAdderRowPointer(this, tree).generateMenu(menu, tree->model()->typeStringList(baseType())); - tree->_setPressedRow(this); - menu.exec(tree->_toScreen(QPoint(widgetPos_, pos_.y() + tree->_defaultRowHeight()))); - tree->_setPressedRow(0); - return true; -} - -bool PropertyRowPointer::onMouseDown(QPropertyTree* tree, QPoint point, bool& changed) -{ - if (widgetRect(tree).contains(point)) - { - if (onActivate(tree, false)) - { - changed = true; - } - } - return false; -} - -bool PropertyRowPointer::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - if (!menu.isEmpty()) - { - menu.addSeparator(); - } - if (!userReadOnly()) - { - QMenu* createItem = menu.addMenu("Set"); - ClassMenuItemAdderRowPointer(this, tree).generateMenu(*createItem, tree->model()->typeStringList(baseType())); - } - return PropertyRow::onContextMenu(menu, tree); -} - -void PropertyRowPointer::serializeValue(IArchive& ar) -{ - ar(derivedTypeName_, "derivedTypeName", "Derived Type Name"); -} - -int PropertyRowPointer::widgetSizeMin(const QPropertyTree* tree) const -{ - QFontMetrics fm(tree->_boldFont()); - QString str(fromWideChar(generateLabel().c_str()).c_str()); - return fm.horizontalAdvance(str) + 24; -} - -static Color parseColorString(const char* str) -{ - unsigned int color = 0; - if (azsscanf(str, "%x", &color) != 1) - { - return Color(0, 0, 0, 0); - } - Color result((color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff, 255); - return result; -} - -void PropertyRowPointer::setValueAndContext(const Serialization::IPointer& ptr, [[maybe_unused]] Serialization::IArchive& ar) -{ - baseType_ = ptr.baseType(); - factory_ = ptr.factory(); - serializer_ = ptr.serializer(); - pointerType_ = ptr.pointerType(); - searchHandle_ = ptr.handle(); - - const char* colorString = factory_->findAnnotation(ptr.registeredTypeName(), "color"); - if (colorString[0] != '\0') - { - colorOverride_ = parseColorString(colorString); - } - else - { - colorOverride_ = Color(0, 0, 0, 0); - } - - const Serialization::TypeDescription* desc = factory_->descriptionByRegisteredName(ptr.registeredTypeName()); - if (desc) - { - derivedTypeName_ = desc->name(); - } - else - { - derivedTypeName_.clear(); - } -} - -#include -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.h deleted file mode 100644 index aae8cb875a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowPointer.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWPOINTER_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWPOINTER_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "Color.h" -#include "Serialization/StringList.h" -using Serialization::StringList; - -#include "PropertyRow.h" -#endif - -class QPropertyTree; -class PropertyRowPointer; -struct CreatePointerMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowPointer* row; - int index; - bool useDefaultValue; -public slots: - void onMenuCreateByIndex(); -}; - -class QMenu; -struct ClassMenuItemAdder -{ - virtual void addAction(QMenu& menu, const char* text, int index); - virtual QMenu* addMenu(QMenu& menu, const char* text); - void generateMenu(QMenu& createItem, const StringList& comboStrings); -}; - -class PropertyRowPointer - : public PropertyRow -{ -public: - PropertyRowPointer(); - - bool assignTo(Serialization::IPointer& ptr); - void setValueAndContext(const Serialization::IPointer& ptr, Serialization::IArchive& ar); - using PropertyRow::assignTo; - using PropertyRow::setValueAndContext; - using PropertyRow::onActivate; - - Serialization::TypeID baseType() const{ return baseType_; } - void setBaseType(const Serialization::TypeID& baseType) { baseType_ = baseType; } - const char* derivedTypeName() const{ return derivedTypeName_.c_str(); } - void setDerivedType(const char* typeName, Serialization::IClassFactory* factory); - void setFactory(Serialization::IClassFactory* factory) { factory_ = factory; } - Serialization::IClassFactory* factory() const{ return factory_; } - bool onActivate(QPropertyTree* tree, bool force); - bool onMouseDown(QPropertyTree* tree, QPoint point, bool& changed); - bool onContextMenu(QMenu& root, QPropertyTree* tree); - bool isStatic() const{ return false; } - bool isPointer() const{ return true; } - int widgetSizeMin(const QPropertyTree* tree) const override; - wstring generateLabel() const; - string valueAsString() const; - const char* typeNameForFilter([[maybe_unused]] QPropertyTree* tree) const override { return baseType_.name(); } - void redraw(const PropertyDrawContext& context); - WidgetPlacement widgetPlacement() const{ return WIDGET_VALUE; } - void serializeValue(Serialization::IArchive& ar); - const void* searchHandle() const override { return searchHandle_; } - Serialization::TypeID typeId() const override { return pointerType_; } -protected: - - Serialization::TypeID baseType_; - string derivedTypeName_; - string derivedLabel_; - - // this member is available for instances deserialized from clipboard: - Serialization::IClassFactory* factory_; - const void* searchHandle_; - Serialization::TypeID pointerType_; - Color colorOverride_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWPOINTER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.cpp deleted file mode 100644 index f766520662..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.cpp +++ /dev/null @@ -1,177 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" - -#include - -#include "PropertyRowResourceFilePath.h" -#include "Serialization/ClassFactory.h" -#include -#include -#include -#include -#include -#include // for getting game folder. - -#include -#include -#include - -ResourceFilePathMenuHandler::ResourceFilePathMenuHandler(QPropertyTree* tree, PropertyRowResourceFilePath* self) - : self(self) - , tree(tree) -{ -} - - -void ResourceFilePathMenuHandler::onMenuClear() -{ - tree->model()->rowAboutToBeChanged(self); - self->clear(); - tree->model()->rowChanged(self); -} - -// Get filename relative to the asset folder, -// whether it came from the project or from a gem -QString AssetRelativePathFromAbsolutePath(const QString& absPath) -{ - return Path::FullPathToGamePath(absPath); -} - -bool PropertyRowResourceFilePath::onActivate(const PropertyActivationEvent& e) -{ - using namespace AzToolsFramework::AssetBrowser; - - if (e.reason == e.REASON_RELEASE) - { - return false; - } - - AssetSelectionModel selection; - if (m_group) - { - selection = AssetSelectionModel::AssetGroupSelection(filter_); - } - else - { - selection = AssetSelectionModel::AssetTypeSelection(filter_); - } - - AzToolsFramework::EditorRequests::Bus::Broadcast(&AzToolsFramework::EditorRequests::BrowseForAssets, selection); - if (!selection.IsValid()) - { - return true; - } - - auto product = azrtti_cast(selection.GetResult()); - if (!product) - { - return true; - } - - AZStd::string relativeFilename = product->GetRelativePath(); - - if (flags_ & ResourceFilePath::STRIP_EXTENSION) - { - size_t ext = relativeFilename.rfind('.'); - if (ext != relativeFilename.npos) - { - relativeFilename.erase(ext, relativeFilename.length() - ext); - } - } - - e.tree->model()->rowAboutToBeChanged(this); - path_ = relativeFilename.c_str(); - e.tree->model()->rowChanged(this); - return true; -} -void PropertyRowResourceFilePath::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - ResourceFilePath* value = (ResourceFilePath*)ser.pointer(); - filter_ = value->filter.c_str(); - path_ = value->m_path->c_str(); - flags_ = value->flags; - handle_ = value->m_path; - m_group = value->group; -} - -bool PropertyRowResourceFilePath::assignTo(const Serialization::SStruct& ser) const -{ - ((ResourceFilePath*)ser.pointer())->SetPath(path_.c_str()); - return true; -} - -void PropertyRowResourceFilePath::serializeValue(Serialization::IArchive& ar) -{ - ar(filter_, "filter"); - ar(path_, "path"); - ar(startFolder_, "startFolder"); - ar(m_group, "group"); -} - -const QIcon& PropertyRowResourceFilePath::buttonIcon(const QPropertyTree* tree, [[maybe_unused]] int index) const -{ - #include "file_open.xpm" - static QIcon fileOpenIcon = QIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(file_open_xpm)))); - return fileOpenIcon; -} - -string PropertyRowResourceFilePath::valueAsString() const -{ - return path_; -} - - -void PropertyRowResourceFilePath::clear() -{ - path_.clear(); -} - -bool PropertyRowResourceFilePath::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - QAction* action = menu.addAction("Clear"); - Serialization::SharedPtr selfPointer(this); - - ResourceFilePathMenuHandler* handler = new ResourceFilePathMenuHandler(tree, this); - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuClear())); - tree->addMenuHandler(handler); - return true; -} - -bool PropertyRowResourceFilePath::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowResourceFilePath::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -REGISTER_PROPERTY_ROW(ResourceFilePath, PropertyRowResourceFilePath); -DECLARE_SEGMENT(PropertyRowResourceFilePath) - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.h deleted file mode 100644 index 9a564a7bd9..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFilePath.h +++ /dev/null @@ -1,79 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFILEPATH_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFILEPATH_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "PropertyRowField.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include -#include -#include -#endif - -using Serialization::ResourceFilePath; - -class PropertyRowResourceFilePath - : public PropertyRowField -{ -public: - void clear(); - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - bool onActivate(const PropertyActivationEvent& e) override; - - int buttonCount() const override { return 1; } - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - virtual bool usePathEllipsis() const override { return true; } - string valueAsString() const; - void serializeValue(Serialization::IArchive& ar); - const void* searchHandle() const override { return handle_; } - Serialization::TypeID typeId() const override { return Serialization::TypeID::get(); } - - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - string filter_; - string path_; - string startFolder_; - bool m_group; - int flags_; - const void* handle_; -}; - -struct ResourceFilePathMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowResourceFilePath* self; - - ResourceFilePathMenuHandler(QPropertyTree* tree, PropertyRowResourceFilePath* container); -public slots: - void onMenuClear(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFILEPATH_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.cpp deleted file mode 100644 index c67f9e4bc3..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include -#include "PropertyRowResourceFolderPath.h" -#include "Serialization/ClassFactory.h" -#include -#include -#include -#include - -ResourceFolderPathMenuHandler::ResourceFolderPathMenuHandler(QPropertyTree* tree, PropertyRowResourceFolderPath* self) - : self(self) - , tree(tree) -{ -} - -void ResourceFolderPathMenuHandler::onMenuClear() -{ - tree->model()->rowAboutToBeChanged(self); - self->clear(); - tree->model()->rowChanged(self); -} - -bool PropertyRowResourceFolderPath::onActivate(const PropertyActivationEvent& e) -{ - if (e.reason == e.REASON_RELEASE) - { - return false; - } - if (!GetIEditor()) - { - return true; - } - - if (userReadOnly()) - { - return false; - } - - QString title; - if (labelUndecorated() && labelUndecorated()[0] != '\0') - { - title = QString("Choose folder for '") + QString::fromLocal8Bit(labelUndecorated()) + "'"; - } - else - { - title = "Choose folder"; - } - - QString gameFolder = QString::fromLocal8Bit(Path::GetEditingGameDataFolder().c_str()); - QString startFolder = gameFolder + QDir::separator(); - - if (path_.empty() || !QDir().exists(startFolder)) - { - startFolder += QString::fromLocal8Bit(startFolder_.c_str()); - } - else - { - startFolder += QString::fromLocal8Bit(path_.c_str()); - } - - QString filename = QFileDialog::getExistingDirectory(e.tree, title, startFolder, QFileDialog::ShowDirsOnly); - if (filename.isEmpty()) - { - return true; - } - - e.tree->model()->rowAboutToBeChanged(this); - QString result = QDir(gameFolder).relativeFilePath(filename); - path_ = result.toLocal8Bit().data(); - e.tree->model()->rowChanged(this); - return true; -} -void PropertyRowResourceFolderPath::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - ResourceFolderPath* value = (ResourceFolderPath*)(ser.pointer()); - path_ = value->m_path->c_str(); - startFolder_ = value->startFolder.c_str(); - handle_ = value->m_path; -} - -bool PropertyRowResourceFolderPath::assignTo(const Serialization::SStruct& ser) const -{ - ((ResourceFolderPath*)ser.pointer())->SetPath(path_.c_str()); - return true; -} - -const QIcon& PropertyRowResourceFolderPath::buttonIcon(const QPropertyTree* tree, [[maybe_unused]] int index) const -{ - #include "file_open.xpm" - static QIcon fileOpenIcon = QIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(file_open_xpm)))); - return fileOpenIcon; -} - -string PropertyRowResourceFolderPath::valueAsString() const -{ - return path_; -} - -void PropertyRowResourceFolderPath::clear() -{ - path_.clear(); -} - -void PropertyRowResourceFolderPath::serializeValue(Serialization::IArchive& ar) -{ - ar(path_, "path"); - ar(startFolder_, "startFolder"); -} - -bool PropertyRowResourceFolderPath::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - ResourceFolderPathMenuHandler* handler = new ResourceFolderPathMenuHandler(tree, this); - QAction* action = menu.addAction("Clear", handler, SLOT(onMenuClear())); - action->setEnabled(!userReadOnly()); - SharedPtr selfPointer(this); - - tree->addMenuHandler(handler); - return true; -} - -bool PropertyRowResourceFolderPath::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowResourceFolderPath::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -REGISTER_PROPERTY_ROW(ResourceFolderPath, PropertyRowResourceFolderPath); -DECLARE_SEGMENT(PropertyRowResourceFolderPath) - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.h deleted file mode 100644 index ed58c148e7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceFolderPath.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFOLDERPATH_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFOLDERPATH_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "PropertyRowImpl.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include -#include -#include -#include -#endif - -using Serialization::ResourceFolderPath; - -class PropertyRowResourceFolderPath - : public PropertyRowField -{ -public: - PropertyRowResourceFolderPath() - : handle_() {} - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - bool onActivate(const PropertyActivationEvent& e) override; - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - string valueAsString() const; - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - - int buttonCount() const override { return 1; } - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - virtual bool usePathEllipsis() const override { return true; } - void serializeValue(Serialization::IArchive& ar) override; - const void* searchHandle() const override { return handle_; } - Serialization::TypeID typeId() const override { return Serialization::TypeID::get(); } - void clear(); - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - string path_; - string startFolder_; - const void* handle_; -}; - -struct ResourceFolderPathMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowResourceFolderPath* self; - - ResourceFolderPathMenuHandler(QPropertyTree* tree, PropertyRowResourceFolderPath* container); -public slots: - void onMenuClear(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCEFOLDERPATH_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.cpp deleted file mode 100644 index 942691df04..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.cpp +++ /dev/null @@ -1,425 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowResourceSelector.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/Decorators/Resources.h" -#include "Serialization/Decorators/INavigationProvider.h" -#include "Serialization/Decorators/IconXPM.h" -#include -#include "IEditor.h" -#include -#include -#include -#include -#include - -enum Button -{ - BUTTON_PICK, - BUTTON_CREATE -}; - -ResourceSelectorMenuHandler::ResourceSelectorMenuHandler(QPropertyTree* tree, PropertyRowResourceSelector* self) - : self(self) - , tree(tree) -{ -} - - -void ResourceSelectorMenuHandler::onMenuClear() -{ - tree->model()->rowAboutToBeChanged(self); - self->clear(); - tree->model()->rowChanged(self); -} - -void ResourceSelectorMenuHandler::onMenuPickResource() -{ - self->pickResource(tree); -} - -void ResourceSelectorMenuHandler::onMenuCreateFile() -{ - self->createFile(tree); -} - -void ResourceSelectorMenuHandler::onMenuJumpTo() -{ - self->jumpTo(tree); -} - -bool PropertyRowResourceSelector::onActivate(const PropertyActivationEvent& e) -{ - if (PropertyRowField::onActivate(e)) - { - return true; - } - - bool canSelect = !userReadOnly() && !multiValue() && provider_ && provider_->CanSelect(type_.c_str(), value_.c_str(), id_); - - if (!userReadOnly() && e.reason == e.REASON_DOUBLECLICK && provider_ && provider_->CanPickFile(type_.c_str(), id_)) - { - return pickResource(e.tree); - } - - if (canSelect) - { - jumpTo(e.tree); - return true; - } - else if (!userReadOnly()) - { - if (!provider_ && !userReadOnly()) - { - pickResource(e.tree); - } - } - return false; -} - -int PropertyRowResourceSelector::buttonCount() const -{ - if (!provider_) - { - return 1; - } - - int result = 0; - if (provider_->CanPickFile(type_.c_str(), id_)) - { - result = 1; - if (!multiValue() && value_.empty() && provider_->CanCreate(type_.c_str(), id_)) - { - result = 2; - } - } - return result; -} - -bool PropertyRowResourceSelector::onActivateButton(int button, const PropertyActivationEvent& e) -{ - if (userReadOnly()) - { - return false; - } - if (button == BUTTON_PICK) - { - return pickResource(e.tree); - } - else if (button == BUTTON_CREATE) - { - return createFile(e.tree); - } - return true; -} - -bool PropertyRowResourceSelector::getHoverInfo(PropertyHoverInfo* hover, const QPoint& cursorPos, const QPropertyTree* tree) const -{ - if (fieldRect(tree).contains(cursorPos) && provider_ && provider_->CanSelect(type_.c_str(), value_.c_str(), id_) && !provider_->IsSelected(type_.c_str(), value_.c_str(), id_)) - { - hover->cursor = QCursor(Qt::PointingHandCursor); - } - else - { - hover->cursor = QCursor(); - } - hover->toolTip = QString::fromLocal8Bit(value_.c_str()); - return true; -} - -void PropertyRowResourceSelector::jumpTo([[maybe_unused]] QPropertyTree* tree) -{ - if (multiValue()) - { - return; - } - if (provider_) - { - provider_->Select(type_.c_str(), value_.c_str(), id_); - } - return; -} - -bool PropertyRowResourceSelector::pickResource(QPropertyTree* tree) -{ - if (!GetIEditor()) - { - return false; - } - - context_.typeName = type_.c_str(); - context_.parentWidget = tree; - QString filename = GetIEditor()->GetResourceSelectorHost()->SelectResource(context_, value_.c_str()); - - tree->model()->rowAboutToBeChanged(this); - value_ = filename.toUtf8().constData(); - tree->model()->rowChanged(this); - - return true; -} - -QString convertMFCToQtFileFilter(QString* defaultSuffix, const char* mfcFilter); - -bool PropertyRowResourceSelector::createFile(QPropertyTree* tree) -{ - if (!provider_) - { - return false; - } - - QString title; - if (labelUndecorated()) - { - title = QString("Create file for '") + labelUndecorated() + "'"; - } - else - { - title = "Choose file"; - } - - string originalFilter; - originalFilter = provider_->GetFileSelectorMaskForType(type_.c_str()); - - QString gameFolder = QString::fromLocal8Bit(Path::GetEditingGameDataFolder().c_str()); - QDir gameFolderDir(QDir::fromNativeSeparators(gameFolder)); - QString defaultSuffix; - QString filter = convertMFCToQtFileFilter(&defaultSuffix, originalFilter.c_str()); - QString existingFile = QString::fromLocal8Bit(PathUtil::ReplaceExtension(defaultPath_.empty() ? value_.c_str() : defaultPath_.c_str(), defaultSuffix.toLocal8Bit().data())); - - QString existingFilePath = (existingFile.isEmpty() || QDir::isAbsolutePath(existingFile)) ? existingFile : gameFolderDir.absoluteFilePath(existingFile); - - // Not using QFileDialog().exec() as it implements custom file dialog that - // freezes for couple of seconds when being open. Scannign network drives? - QString result = QFileDialog::getSaveFileName(tree, title, existingFilePath.isEmpty() ? (gameFolder + "/") : existingFilePath, filter); - if (!result.isEmpty()) - { - QString relativeFilename = gameFolderDir.relativeFilePath(result); - - if (provider_->Create(type_.c_str(), relativeFilename.toLocal8Bit().data(), id_)) - { - tree->model()->rowAboutToBeChanged(this); - value_ = relativeFilename.toLocal8Bit().data(); - tree->model()->rowChanged(this); - } - } - return true; -} - -void PropertyRowResourceSelector::setValueAndContext(const Serialization::SStruct& ser, IArchive& ar) -{ - IResourceSelector* value = (IResourceSelector*)ser.pointer(); - if (type_ != value->resourceType) - { - type_ = value->resourceType; - const char* resourceIconPath = GetIEditor()->GetResourceSelectorHost()->ResourceIconPath(type_.c_str()); - icon_ = resourceIconPath[0] ? QIcon(QString::fromLocal8Bit(resourceIconPath)) : QIcon(); - } - value_ = value->GetValue(); - id_ = value->GetId(); - searchHandle_ = value->GetHandle(); - wrappedType_ = value->GetType(); - - provider_ = ar.FindContext(); - if (!provider_ || !provider_->IsRegistered(type_)) - { - provider_ = 0; - } - - Serialization::TypeID contextObjectType = GetIEditor()->GetResourceSelectorHost()->ResourceContextType(type_.c_str()); - if (contextObjectType != Serialization::TypeID()) - { - context_.contextObject = ar.FindContextByType(contextObjectType); - context_.contextObjectType = contextObjectType; - } - - if (Serialization::SNavigationContext* navigationContext = ar.FindContext()) - { - defaultPath_ = navigationContext->path.c_str(); - } - else - { - defaultPath_.clear(); - } -} - -bool PropertyRowResourceSelector::assignTo(const Serialization::SStruct& ser) const -{ - ((IResourceSelector*)ser.pointer())->SetValue(value_.c_str()); - return true; -} - -void PropertyRowResourceSelector::serializeValue(Serialization::IArchive& ar) -{ - ar(type_, "type"); - ar(value_, "value"); - ar(id_, "index"); - - if (ar.IsInput()) - { - const char* resourceIconPath = GetIEditor()->GetResourceSelectorHost()->ResourceIconPath(type_.c_str()); - icon_ = resourceIconPath[0] ? QIcon(QString::fromLocal8Bit(resourceIconPath)) : QIcon(); - } -} - -const QIcon& PropertyRowResourceSelector::buttonIcon(const QPropertyTree* tree, int index) const -{ - switch (index) - { - case BUTTON_PICK: - { - if (provider_ != 0 || icon_.isNull()) - { - #include "file_open.xpm" - static QIcon defaultIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(file_open_xpm)))); - return defaultIcon; - } - else - { - return icon_; - } - } - case BUTTON_CREATE: - { - static QIcon addIcon("Icons/animation/add.png"); - ; - return addIcon; - } - default: - { - static QIcon defaultIcon; - return defaultIcon; - } - } -} - -string PropertyRowResourceSelector::valueAsString() const -{ - return value_; -} - -void PropertyRowResourceSelector::clear() -{ - value_.clear(); -} - -bool PropertyRowResourceSelector::onContextMenu(QMenu& menu, QPropertyTree* tree) -{ - Serialization::SharedPtr selfPointer(this); - - ResourceSelectorMenuHandler* handler = new ResourceSelectorMenuHandler(tree, this); - if (!multiValue() && provider_ && provider_->CanSelect(type_.c_str(), value_.c_str(), id_)) - { - QAction* jumpToAction = menu.addAction("Jump to", handler, SLOT(onMenuJumpTo())); - menu.setDefaultAction(jumpToAction); - } - if (!userReadOnly()) - { - if (!provider_ || provider_->CanPickFile(type_.c_str(), id_)) - { - menu.addAction(buttonIcon(tree, 0), "Pick Resource...", handler, SLOT(onMenuPickResource()))->setEnabled(!userReadOnly()); - } - if (provider_ && provider_->CanCreate(type_.c_str(), id_)) - { - menu.addAction(buttonIcon(tree, 1), "Create...", handler, SLOT(onMenuCreateFile())); - } - menu.addAction("Clear", handler, SLOT(onMenuClear()))->setEnabled(!userReadOnly()); - } - tree->addMenuHandler(handler); - - PropertyRow::onContextMenu(menu, tree); - return true; -} - -static const wchar_t* getFilenameFromPath(const wchar_t* path) -{ - const wchar_t* lastSep = wcsrchr(path, L'/'); - if (!lastSep) - { - return path; - } - return lastSep + 1; -} - -void PropertyRowResourceSelector::redraw(const PropertyDrawContext& context) -{ - ////! TOFIX: THIS CODE IS DUPLICATED IN PropertyRowField.cpp: PropertyRowField::redraw()!!! - // - int buttonCount = this->buttonCount(); - int offset = 0; - for (int i = 0; i < buttonCount; ++i) - { - const QIcon& icon = buttonIcon(context.tree, i); - int width = 16; - QRect iconRect(context.widgetRect.right() - offset - width, context.widgetRect.top(), width, context.widgetRect.height()); - icon.paint(context.painter, iconRect, Qt::AlignCenter, userReadOnly() ? QIcon::Disabled : QIcon::Normal); - offset += width; - } - - int iconSpace = offset ? offset + 2 : 0; - // - //// - - QRect rect = context.widgetRect; - rect.setRight(rect.right() - iconSpace); - bool pressed = context.m_pressed || (provider_ ? provider_->IsSelected(type_.c_str(), value_.c_str(), id_) : false); - bool active = !provider_ || provider_->IsActive(type_.c_str(), value_.c_str(), id_); - bool modified = provider_ && provider_->IsModified(type_.c_str(), value_.c_str(), id_); - QIcon icon = icon_; - if (provider_) - { - icon = QIcon(provider_->GetIcon(type_.c_str(), value_.c_str())); - } - bool canSelect = !multiValue() && provider_ && provider_->CanSelect(type_.c_str(), value_.c_str(), id_); - - wstring text = multiValue() ? L"..." : wstring(modified ? L"*" : L"") + getFilenameFromPath(valueAsWString()); - if (provider_) - { - if (canSelect || !text.empty()) - { - context.drawButtonWithIcon(icon, rect, text.c_str(), selected(), pressed, selected(), !userReadOnly(), canSelect, active ? &context.tree->_boldFont() : &context.tree->font()); - } - } - else - { - context.drawEntry(text.c_str(), true, false, iconSpace); - } -} - -bool PropertyRowResourceSelector::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowResourceSelector::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -REGISTER_PROPERTY_ROW(IResourceSelector, PropertyRowResourceSelector); -DECLARE_SEGMENT(PropertyRowResourceSelector) - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.h deleted file mode 100644 index 0a614cfaed..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowResourceSelector.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCESELECTOR_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCESELECTOR_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyDrawContext.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "PropertyRowField.h" -#include -#include "Serialization/Decorators/Resources.h" -#include "IResourceSelectorHost.h" -#include -#endif - -using Serialization::IResourceSelector; -namespace Serialization { - struct INavigationProvider; -} - -class PropertyRowResourceSelector - : public PropertyRowField -{ -public: - PropertyRowResourceSelector() - : provider_(0) - , id_(0) - , searchHandle_(0) {} - void clear(); - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - - void jumpTo(QPropertyTree* tree); - bool createFile(QPropertyTree* tree); - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - bool onActivate(const PropertyActivationEvent& ev) override; - bool onActivateButton(int button, const PropertyActivationEvent& e) override; - bool getHoverInfo(PropertyHoverInfo* hover, const QPoint& cursorPos, const QPropertyTree* tree) const override; - const void* searchHandle() const override { return searchHandle_; } - Serialization::TypeID typeId() const override { return wrappedType_; } - - int buttonCount() const override; - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - virtual bool usePathEllipsis() const override { return true; } - string valueAsString() const; - void serializeValue(Serialization::IArchive& ar); - void redraw(const PropertyDrawContext& context); - - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - bool pickResource(QPropertyTree* tree); - const char* typeNameForFilter([[maybe_unused]] QPropertyTree* tree) const override { return !type_.empty() ? type_.c_str() : "ResourceSelector"; } - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - SResourceSelectorContext context_; - Serialization::INavigationProvider* provider_; - const void* searchHandle_; - Serialization::TypeID wrappedType_; - QIcon icon_; - - string type_; - string value_; - string defaultPath_; - int id_; -}; - -struct ResourceSelectorMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - QPropertyTree * tree; - PropertyRowResourceSelector* self; - - ResourceSelectorMenuHandler(QPropertyTree* tree, PropertyRowResourceSelector* container); -public slots: - void onMenuCreateFile(); - void onMenuJumpTo(); - void onMenuClear(); - void onMenuPickResource(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWRESOURCESELECTOR_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSlider.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSlider.cpp deleted file mode 100644 index 6ac69973e0..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSlider.cpp +++ /dev/null @@ -1,521 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "Serialization/ClassFactory.h" -#include "PropertyTreeModel.h" -#include "PropertyRowNumber.h" -#include "MathUtils.h" - -#include -#include -#include -#include -#include "QPropertyTree.h" -#include "PropertyRow.h" -#include "PropertyDrawContext.h" - -#include "Serialization.h" -#include "Serialization/Decorators/Slider.h" -#include "Serialization/Decorators/SliderImpl.h" -#include - -using Serialization::SSliderF; -using Serialization::SSliderI; - -class PropertyRowSliderF - : public PropertyRowNumberField -{ -public: - static const bool Custom = true; - PropertyRowSliderF(); - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - int floorHeight() const override { return 18; } - void redraw(const PropertyDrawContext& context) override; - - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onMouseDown(QPropertyTree* tree, QPoint point, bool& changed) override; - void onMouseDrag(const PropertyDragEvent& e) override; - void onMouseUp(QPropertyTree* tree, QPoint point) override; - bool assignTo(const Serialization::SStruct& ser) const override - { - if (ser.size() != sizeof(SSliderF)) - { - return false; - } - SSliderF* slider = (SSliderF*)(ser.pointer()); - *slider->valuePointer = clamp(localValue_, slider->minLimit, slider->maxLimit); - return true; - } - bool handleMouse(QPropertyTree* tree, QPoint point); - - bool setValueFromString(const char* str) override - { - float newValue = aznumeric_cast(atof(str)); - if (localValue_ != newValue) - { - localValue_ = newValue; - return true; - } - else - { - return false; - } - } - - string valueAsString() const override - { - return numberAsString(localValue_); - } - - void startIncrement() override - { - incrementStartValue_ = localValue_; - } - - void endIncrement(QPropertyTree* tree) override - { - if (localValue_ != incrementStartValue_) - { - float localValue = localValue_; - localValue_ = incrementStartValue_; - tree->model()->rowAboutToBeChanged(this); - localValue_ = localValue; - tree->model()->rowChanged(this); - } - } - - void incrementLog(float screenFraction, [[maybe_unused]] float valueFieldFraction) - { - double startPower = log10(fabs(double(incrementStartValue_) + 1.0)) - 3.0; - double power = startPower + fabs(screenFraction) * 10.0f; - double delta = powf(10.0f, aznumeric_cast(power)) - powf(10.0f, aznumeric_cast(startPower)) + 10.0f * fabsf(screenFraction); - double newValue; - if (screenFraction > 0.0f) - { - newValue = double(incrementStartValue_) + delta; - } - else - { - newValue = double(incrementStartValue_) - delta; - } - if (_isnan(newValue)) - { - if (screenFraction > 0.0f) - { - newValue = DBL_MAX; - } - else - { - newValue = -DBL_MAX; - } - } - clampToType(&localValue_, newValue); - } - - void serializeValue(Serialization::IArchive& ar) - { - ar(value_.minLimit, "min"); - ar(value_.maxLimit, "max"); - ar(localValue_, "value"); - } - - double sliderPosition() const override { return 0.0; } - - SSliderF value_; - float localValue_; - float incrementStartValue_; - bool captured_; -}; - -bool PropertyRowSliderF::handleMouse(QPropertyTree* tree, QPoint point) -{ - QStyleOptionSlider slider; - slider.rect = floorRect(tree); - QSlider widgetForContext; - QRect sliderGroove = tree->style()->subControlRect(QStyle::CC_Slider, &slider, QStyle::SC_SliderGroove, &widgetForContext); - QRect sliderHandle = tree->style()->subControlRect(QStyle::CC_Slider, &slider, QStyle::SC_SliderHandle, &widgetForContext); - - int sliderLength = sliderGroove.width() - sliderHandle.width(); - - float valRelative = float(point.x() - (sliderGroove.left() + sliderHandle.width() / 2)) / sliderLength; - if (valRelative < 0.0f) - { - valRelative = 0.0f; - } - if (valRelative > 1.0f) - { - valRelative = 1.0f; - } - float newValue = float(valRelative * (value_.maxLimit - value_.minLimit) + value_.minLimit); - if (newValue != localValue_) - { - localValue_ = newValue; - setMultiValue(false); - return true; - } - else - { - return false; - } -} - -bool PropertyRowSliderF::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - float step = (value_.maxLimit - value_.minLimit) * 0.01f; - if (ev->key() == Qt::Key_Left) - { - tree->model()->rowAboutToBeChanged(this); - localValue_ = clamp(localValue_ - step, value_.minLimit, value_.maxLimit); - tree->model()->rowChanged(this); - return true; - } - if (ev->key() == Qt::Key_Right) - { - tree->model()->rowAboutToBeChanged(this); - localValue_ = clamp(localValue_ + step, value_.minLimit, value_.maxLimit); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowNumberField::onKeyDown(tree, ev); -} - -bool PropertyRowSliderF::onMouseDown(QPropertyTree* tree, QPoint point, [[maybe_unused]] bool& changed) -{ - if (floorRect(tree).contains(point) && !userReadOnly()) - { - tree->model()->rowAboutToBeChanged(this); - if (handleMouse(tree, point)) - { - tree->update(); - } - captured_ = true; - return true; - } - captured_ = false; - return true; -} - -void PropertyRowSliderF::onMouseDrag(const PropertyDragEvent& e) -{ - if (!captured_) - { - return; - } - if (userReadOnly()) - { - return; - } - if (handleMouse(e.tree, e.pos)) - { - e.tree->update(); - } -} - -void PropertyRowSliderF::onMouseUp(QPropertyTree* tree, QPoint point) -{ - if (!captured_) - { - return; - } - handleMouse(tree, point); - tree->model()->rowChanged(this); -} - -void PropertyRowSliderF::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - value_ = *(SSliderF*)ser.pointer(); - localValue_ = *value_.valuePointer; - value_.valuePointer = 0; -} - -static void drawSlider(const PropertyDrawContext& context, float relativeVal, bool userReadOnly, bool selected) -{ - // Eliminate x-shift offset in the control rect as it triggers a bug in - // Fusion theme, that causes blue area in the slider groove to stand out to - // the right from slider. - int xOffset = context.lineRect.left(); - context.painter->translate(xOffset, 0); - - QStyleOptionSlider sliderOptions; - sliderOptions.rect = context.lineRect.translated(-xOffset, 0); - sliderOptions.minimum = 0; - QSlider widgetForContext; - QRect sliderGroove = context.tree->style()->subControlRect(QStyle::CC_Slider, &sliderOptions, QStyle::SC_SliderGroove, &widgetForContext); - QRect sliderHandle = context.tree->style()->subControlRect(QStyle::CC_Slider, &sliderOptions, QStyle::SC_SliderHandle, &widgetForContext); - int width = sliderGroove.width() - sliderHandle.width() + 1; - sliderOptions.maximum = width; - sliderOptions.pageStep = width / 100; - sliderOptions.sliderPosition = aznumeric_cast(width * relativeVal); - sliderOptions.state = !userReadOnly ? (QStyle::State_Enabled | (selected ? QStyle::State_HasFocus : QStyle::State())) : QStyle::State(); - - context.tree->style()->drawComplexControl(QStyle::CC_Slider, &sliderOptions, context.painter, &widgetForContext); - - context.painter->translate(-xOffset, 0); -} - -void PropertyRowSliderF::redraw(const PropertyDrawContext& context) -{ - PropertyRowNumberField::redraw(context); - float val = localValue_; - float valRange = value_.maxLimit - value_.minLimit; - if (valRange == 0.0f) - { - valRange = 0.00001f; - } - float relativeVal = clamp((val - value_.minLimit) / valRange, 0.0f, 1.0f); - - drawSlider(context, relativeVal, userReadOnly(), selected()); -} - -PropertyRowSliderF::PropertyRowSliderF() - : captured_(false) - , localValue_() - , incrementStartValue_() -{ -} - -DECLARE_SEGMENT(PropertyRowSliderF) -REGISTER_PROPERTY_ROW(SSliderF, PropertyRowSliderF) - -// --------------------------------------------------------------------------- - -class PropertyRowSliderI - : public PropertyRowNumberField -{ -public: - static const bool Custom = true; - PropertyRowSliderI(); - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - int floorHeight() const override { return 18; } - void redraw(const PropertyDrawContext& context) override; - - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onMouseDown(QPropertyTree* tree, QPoint point, bool& changed) override; - void onMouseDrag(const PropertyDragEvent& e) override; - void onMouseUp(QPropertyTree* tree, QPoint point) override; - bool assignTo(const Serialization::SStruct& ser) const override - { - if (ser.size() != sizeof(SSliderI)) - { - return false; - } - SSliderI* slider = (SSliderI*)(ser.pointer()); - *slider->valuePointer = clamp(localValue_, slider->minLimit, slider->maxLimit); - return true; - } - bool handleMouse(QPropertyTree* tree, QPoint point); - - bool setValueFromString(const char* str) override - { - int newValue = atoi(str); - if (localValue_ != newValue) - { - localValue_ = newValue; - return true; - } - else - { - return false; - } - } - Serialization::string valueAsString() const override - { - return numberAsString(localValue_); - } - - void startIncrement() override - { - incrementStartValue_ = localValue_; - } - - void endIncrement(QPropertyTree* tree) override - { - if (localValue_ != incrementStartValue_) - { - int localValue = localValue_; - localValue_ = incrementStartValue_; - tree->model()->rowAboutToBeChanged(this); - localValue_ = localValue; - tree->model()->rowChanged(this); - } - } - - void incrementLog(float screenFraction, [[maybe_unused]] float valueFieldFraction) - { - double startPower = log10(fabs(double(incrementStartValue_) + 1.0)) - 3.0; - double power = startPower + fabs(screenFraction) * 10.0f; - double delta = powf(10.0f, aznumeric_cast(power)) - powf(10.0f, aznumeric_cast(startPower)) + 1000.0f * fabsf(screenFraction); - double newValue; - if (screenFraction > 0.0f) - { - newValue = double(incrementStartValue_) + delta; - } - else - { - newValue = double(incrementStartValue_) - delta; - } - if (_isnan(newValue)) - { - if (screenFraction > 0.0f) - { - newValue = DBL_MAX; - } - else - { - newValue = -DBL_MAX; - } - } - clampToType(&localValue_, newValue); - } - - void serializeValue(Serialization::IArchive& ar) - { - ar(value_.minLimit, "min"); - ar(value_.maxLimit, "max"); - ar(localValue_, "value"); - } - - double sliderPosition() const override { return 0.0; } - - SSliderI value_; - int localValue_; - int incrementStartValue_; - bool captured_; -}; - -bool PropertyRowSliderI::handleMouse(QPropertyTree* tree, QPoint point) -{ - QStyleOptionSlider slider; - slider.rect = floorRect(tree); - - QSlider widgetForContext; - QRect sliderGroove = tree->style()->subControlRect(QStyle::CC_Slider, &slider, QStyle::SC_SliderGroove, &widgetForContext); - QRect sliderHandle = tree->style()->subControlRect(QStyle::CC_Slider, &slider, QStyle::SC_SliderHandle, &widgetForContext); - - int sliderLength = sliderGroove.width() - sliderHandle.width(); - - float valRelative = float(point.x() - (sliderGroove.left() + sliderHandle.width() / 2)) / sliderLength; - if (valRelative < 0.0f) - { - valRelative = 0.0f; - } - if (valRelative > 1.0f) - { - valRelative = 1.0f; - } - int newValue = int(valRelative * (value_.maxLimit - value_.minLimit) + value_.minLimit); - if (newValue != localValue_) - { - localValue_ = newValue; - setMultiValue(false); - return true; - } - else - { - return false; - } -} - -bool PropertyRowSliderI::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - int step = aznumeric_cast((value_.maxLimit - value_.minLimit) * 0.01f); - if (ev->key() == Qt::Key_Left) - { - tree->model()->rowAboutToBeChanged(this); - localValue_ = clamp(localValue_ - step, value_.minLimit, value_.maxLimit); - tree->model()->rowChanged(this); - return true; - } - if (ev->key() == Qt::Key_Right) - { - tree->model()->rowAboutToBeChanged(this); - localValue_ = clamp(localValue_ + step, value_.minLimit, value_.maxLimit); - tree->model()->rowChanged(this); - return true; - } - return PropertyRowNumberField::onKeyDown(tree, ev); -} - -bool PropertyRowSliderI::onMouseDown(QPropertyTree* tree, QPoint point, [[maybe_unused]] bool& changed) -{ - if (floorRect(tree).contains(point) && !userReadOnly()) - { - tree->model()->rowAboutToBeChanged(this); - if (handleMouse(tree, point)) - { - tree->update(); - } - captured_ = true; - return true; - } - captured_ = false; - return true; -} - -void PropertyRowSliderI::onMouseDrag(const PropertyDragEvent& e) -{ - if (!captured_) - { - return; - } - if (userReadOnly()) - { - return; - } - if (handleMouse(e.tree, e.pos)) - { - e.tree->update(); - } -} - -void PropertyRowSliderI::onMouseUp(QPropertyTree* tree, QPoint point) -{ - if (!captured_) - { - return; - } - handleMouse(tree, point); - tree->model()->rowChanged(this); -} - -void PropertyRowSliderI::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - value_ = *(SSliderI*)ser.pointer(); - localValue_ = *value_.valuePointer; - value_.valuePointer = 0; -} - -void PropertyRowSliderI::redraw(const PropertyDrawContext& context) -{ - PropertyRowNumberField::redraw(context); - int val = localValue_; - int valRange = value_.maxLimit - value_.minLimit; - if (valRange == 0) - { - valRange = 1; - } - float relativeVal = clamp(float(val - value_.minLimit) / valRange, 0.0f, 1.0f); - - drawSlider(context, relativeVal, userReadOnly(), selected()); -} - -PropertyRowSliderI::PropertyRowSliderI() - : captured_(false) - , localValue_() - , incrementStartValue_() -{ -} - -DECLARE_SEGMENT(PropertyRowSliderI) -REGISTER_PROPERTY_ROW(SSliderI, PropertyRowSliderI) diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.cpp deleted file mode 100644 index 3a0afc103c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.cpp +++ /dev/null @@ -1,299 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" -#include "QPropertyTree.h" -#include "PropertyRowField.h" -#include "PropertyRowSprite.h" -#include "PropertyDrawContext.h" -#include "PropertyTreeModel.h" -#include -#include -#include -#include - -extern QString AssetRelativePathFromAbsolutePath(const QString& absPath); - -bool PropertyRowSprite::onActivateButton(int buttonIndex, const PropertyActivationEvent& ev) -{ - Show show = FromButtonIndexToShow( buttonIndex ); - - if( show == Show::kFilePicker ) - { - return showFilePicker( ev ); - } - - if( show == Show::kSpriteBorderEditor ) - { - return showSpriteBorderEditor( ev ); - } - - // This is to avoid a compiler warning. - // We should NEVER get here. - CRY_ASSERT( 0 ); - return false; -} - -bool PropertyRowSprite::onActivate(const PropertyActivationEvent& ev) -{ - if( PropertyRowField::onActivate( ev ) ) - { - // PropertyRowSprite::onActivateButton() has handled this event. - // Nothing else to do. - return true; - } - - return showFilePicker( ev ); -} - -void PropertyRowSprite::setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) -{ - Serialization::Sprite* value = (Serialization::Sprite *)ser.pointer(); - - m_path = value->m_path->c_str(); -} - -bool PropertyRowSprite::assignTo(const Serialization::SStruct& ser) const -{ - if( ser.size() != sizeof(Serialization::Sprite) ) - { - return false; - } - - Serialization::Sprite* s = (Serialization::Sprite *)ser.pointer(); - - *s->m_path = m_path.c_str(); - - return true; -} - -void PropertyRowSprite::serializeValue(Serialization::IArchive& ar) -{ - ar(m_path, "path"); - ar(m_filter, "filter"); - ar(m_startFolder, "startFolder"); -} - -int PropertyRowSprite::buttonCount() const -{ - return ( CanBeEdited() ? 2 : 1 ); -} - -const QIcon& PropertyRowSprite::buttonIcon(const QPropertyTree* tree, int index) const -{ - Show show = FromButtonIndexToShow( index ); - - if( show == Show::kFilePicker ) - { - #include "file_open.xpm" - static QIcon icon = QIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(file_open_xpm)))); - return icon; - } - - if( show == Show::kSpriteBorderEditor ) - { - #include "gear.xpm" - static QIcon icon = QIcon(QPixmap::fromImage(*tree->_iconCache()->getImageForIcon(Serialization::IconXPM(gear_xpm)))); - return icon; - } - - // This is to avoid a compiler warning. - // We should NEVER get here. - CRY_ASSERT( 0 ); - - #include "gear.xpm" - static QIcon icon; - return icon; -} - -string PropertyRowSprite::valueAsString() const -{ - return m_path; -} - -void PropertyRowSprite::clear() -{ - m_path.clear(); -} - -bool PropertyRowSprite::onContextMenu(QMenu &menu, QPropertyTree* tree) -{ - QAction* action = nullptr; - - action = menu.addAction("Clear"); - QObject::connect( action, - &QAction::triggered, - tree, - [ this, tree ] - { - Clear( tree ); - } ); - - int buttonIndex = ( buttonCount() - 1 ); - - action = menu.addAction(buttonIcon(tree, buttonIndex--), "Pick Resource..."); - QObject::connect( action, - &QAction::triggered, - tree, - [ this, tree ] - { - PropertyActivationEvent ev; - ev.tree = tree; - showFilePicker( ev ); - } ); - - if( buttonIndex >= 0 ) - { - action = menu.addAction(buttonIcon(tree, buttonIndex), "Edit"); - QObject::connect( action, - &QAction::triggered, - tree, - [ this, tree ] - { - PropertyActivationEvent ev; - ev.tree = tree; - showSpriteBorderEditor( ev ); - } ); - } - - return true; -} - -bool PropertyRowSprite::processesKey(QPropertyTree* tree, const QKeyEvent* ev) -{ - if (ev->key() == Qt::Key_Delete) - { - return true; - } - - return PropertyRowField::processesKey(tree, ev); -} - -bool PropertyRowSprite::onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) -{ - if( ev->key() == Qt::Key_Delete ) - { - Clear( tree ); - return true; - } - return PropertyRowField::onKeyDown(tree, ev); -} - -void PropertyRowSprite::Clear(QPropertyTree* tree) -{ - tree->model()->rowAboutToBeChanged(this); - clear(); - tree->model()->rowChanged(this); -} - -bool PropertyRowSprite::showFilePicker(const PropertyActivationEvent& ev) -{ - if (ev.reason == ev.REASON_RELEASE) - return false; - - // Open the file picker and get the filename the user selects - // (QFileDialog can traverse symlinks and shortcuts) - QString filename = QFileDialog::getOpenFileName(ev.tree, - "Choose file", - QString(), - "*.tif;;*.sprite" ); - - // Early out. - { - if (filename.isEmpty()) - { - // Nothing selected. - return true; - } - - QFileInfo fileInfo( filename ); - if( ! ( ( fileInfo.suffix() == "tif" ) || - ( fileInfo.suffix() == "sprite" ) ) ) - { - // Incompatible files selected. - return true; - } - } - - ev.tree->model()->rowAboutToBeChanged(this); - m_path = AssetRelativePathFromAbsolutePath(filename).toStdString().c_str();; - ev.tree->model()->rowChanged(this); - - return true; -} - -bool PropertyRowSprite::showSpriteBorderEditor(const PropertyActivationEvent& ev) -{ - SpriteBorderEditor sbe( m_path.c_str(), ev.tree ); - if (sbe.GetHasBeenInitializedProperly()) - { - sbe.exec(); - return true; - } - - return false; -} - -bool PropertyRowSprite::CanBeEdited() const -{ - return ( ! m_path.empty() ); -} - -PropertyRowSprite::Show PropertyRowSprite::FromButtonIndexToShow(int index) const -{ - bool showFile = false; - bool showGear = false; - - if( index ) - { - // Second icon from the right. - - showFile = true; - } - else - { - // First icon from the right (right-most icon). - - if( CanBeEdited() ) - { - showGear = true; - } - else - { - showFile = true; - } - } - - if( showFile ) - { - return Show::kFilePicker; - } - - if( showGear ) - { - return Show::kSpriteBorderEditor; - } - - // This is to avoid a compiler warning. - // We should NEVER get here. - CRY_ASSERT( 0 ); - return (Show)0; -} - -DECLARE_SEGMENT(PropertyRowSprite) -REGISTER_PROPERTY_ROW(Serialization::Sprite, PropertyRowSprite); - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.h deleted file mode 100644 index e6f278023d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowSprite.h +++ /dev/null @@ -1,70 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSPRITE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSPRITE_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyRowField.h" -#endif - -class PropertyRowSprite -: public PropertyRowField -{ -public: - void clear(); - - bool isLeaf() const override{ return true; } - bool isStatic() const override{ return false; } - - void setValueAndContext(const Serialization::SStruct& ser, Serialization::IArchive& ar) override; - bool assignTo(const Serialization::SStruct& ser) const override; - bool onActivateButton(int buttonIndex, const PropertyActivationEvent& ev) override; - bool onActivate(const PropertyActivationEvent& ev) override; - - int buttonCount() const override; - virtual const QIcon& buttonIcon(const QPropertyTree* tree, int index) const override; - virtual bool usePathEllipsis() const override { return true; } - string valueAsString() const override; - void serializeValue(Serialization::IArchive& ar); - - bool onContextMenu(QMenu& menu, QPropertyTree* tree); - - bool processesKey(QPropertyTree* tree, const QKeyEvent* ev) override; - bool onKeyDown(QPropertyTree* tree, const QKeyEvent* ev) override; - -private: - - enum class Show - { - kFilePicker, - kSpriteBorderEditor - }; - - void Clear(QPropertyTree* tree); - bool showFilePicker(const PropertyActivationEvent& ev); - bool showSpriteBorderEditor(const PropertyActivationEvent& ev); - bool CanBeEdited() const; - Show FromButtonIndexToShow(int index) const; - - string m_path; - string m_filter; - string m_startFolder; - int m_flags; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSPRITE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.cpp deleted file mode 100644 index 200c75d09e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include - -#include "PropertyRowString.h" -#include "PropertyTreeModel.h" -#include "PropertyDrawContext.h" -#include "QPropertyTree.h" - -#include "Serialization/IArchive.h" -#include "Serialization/ClassFactory.h" -#include -#include "Unicode.h" - -// --------------------------------------------------------------------------- -SERIALIZATION_CLASS_NAME(PropertyRow, PropertyRowString, "PropertyRowString", "string"); - -bool PropertyRowString::assignTo(string& str) const -{ - str = fromWideChar(value_.c_str()); - return true; -} - -bool PropertyRowString::assignTo(wstring& str) const -{ - str = value_; - return true; -} - -PropertyRowWidget* PropertyRowString::createWidget(QPropertyTree* tree) -{ - return new PropertyRowWidgetString(this, tree); -} - -bool PropertyRowString::assignToByPointer(void* instance, const Serialization::TypeID& type) const -{ - if (type == Serialization::TypeID::get()) - { - assignTo(*(string*)instance); - return true; - } - else if (type == Serialization::TypeID::get()) - { - assignTo(*(wstring*)instance); - return true; - } - return false; -} - -string PropertyRowString::valueAsString() const -{ - return fromWideChar(value_.c_str()); -} - -void PropertyRowString::setValue(const wchar_t* str, const void* handle, const Serialization::TypeID& type) -{ - value_ = str; - serializer_.setPointer((void*)handle); - serializer_.setType(type); -} - -void PropertyRowString::setValue(const char* str, const void* handle, const Serialization::TypeID& type) -{ - value_ = toWideChar(str); - serializer_.setPointer((void*)handle); - serializer_.setType(type); -} - -void PropertyRowString::serializeValue(Serialization::IArchive& ar) -{ - ar(value_, "value", "Value"); -} - -#include -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.h deleted file mode 100644 index 4a85466463..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowString.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRING_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRING_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyRowField.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Unicode.h" -#include "MathUtils.h" - -#include -#endif - -class PropertyRowString - : public PropertyRowField -{ -public: - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - using PropertyRowField::assignTo; - bool assignTo(string& str) const; - bool assignTo(wstring& str) const; - void setValue(const char* str, const void* handle, const Serialization::TypeID& typeId); - void setValue(const wchar_t* str, const void* handle, const Serialization::TypeID& typeId); - PropertyRowWidget* createWidget(QPropertyTree* tree); - string valueAsString() const; - wstring valueAsWString() const { return value_; } - WidgetPlacement widgetPlacement() const override { return WIDGET_VALUE; } - void serializeValue(Serialization::IArchive& ar) override; - const wstring& value() const{ return value_; } - bool assignToByPointer(void* instance, const Serialization::TypeID& type) const; -protected: - wstring value_; -}; - -class PropertyRowWidgetString - : public PropertyRowWidget -{ - Q_OBJECT -public: - PropertyRowWidgetString(PropertyRowString* row, QPropertyTree* tree) - : PropertyRowWidget(row, tree) - , entry_(new QLineEdit()) - , tree_(tree) - { - initialValue_ = QString(fromWideChar(row->value().c_str()).c_str()); - entry_->setText(initialValue_); - entry_->selectAll(); - connect(entry_.data(), SIGNAL(editingFinished()), this, SLOT(onEditingFinished())); - connect(entry_.data(), &QLineEdit::textChanged, this, [this, tree] { - QFontMetrics fm(entry_->font()); - int contentWidth = min((int)fm.horizontalAdvance(entry_->text()) + 8, tree->width() - entry_->x()); - if (contentWidth > entry_->width()) - { - entry_->resize(contentWidth, entry_->height()); - } - }); - } - ~PropertyRowWidgetString() - { - entry_->hide(); - entry_->setParent(0); - entry_.take()->deleteLater(); - } - - void commit() - { - onEditingFinished(); - } - QWidget* actualWidget() { return entry_.data(); } - -public slots: - void onEditingFinished() - { - PropertyRowString* row = static_cast(this->row()); - if (initialValue_ != entry_->text() || row_->multiValue()) - { - model()->rowAboutToBeChanged(row); - vector str; - QString text = entry_->text(); - str.resize(text.size() + 1, L'\0'); - if (!text.isEmpty()) - { - text.toWCharArray(&str[0]); - } - row->setValue(&str[0], row->searchHandle(), row->typeId()); - model()->rowChanged(row); - } - else - { - tree_->_cancelWidget(); - } - } -protected: - QPropertyTree* tree_; - QScopedPointer entry_; - QString initialValue_; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRING_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.cpp deleted file mode 100644 index 35d4589388..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.cpp +++ /dev/null @@ -1,42 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "Factory.h" -#include "PropertyRowStringListValue.h" - -#include "Serialization/IArchive.h" -#include "Serialization/ClassFactory.h" - -using Serialization::StringList; -using Serialization::StringListValue; - -REGISTER_PROPERTY_ROW(StringListValue, PropertyRowStringListValue) - -PropertyRowWidget * PropertyRowStringListValue::createWidget(QPropertyTree * tree) -{ - return new PropertyRowWidgetStringListValue(this, tree); -} - -// --------------------------------------------------------------------------- -REGISTER_PROPERTY_ROW(StringListStaticValue, PropertyRowStringListStaticValue) - -PropertyRowWidget * PropertyRowStringListStaticValue::createWidget(QPropertyTree * tree) -{ - return new PropertyRowWidgetStringListValue(this, tree); -} - -DECLARE_SEGMENT(PropertyRowStringList) - -#include -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.h deleted file mode 100644 index f8d31ac45b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowStringListValue.h +++ /dev/null @@ -1,303 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRINGLISTVALUE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRINGLISTVALUE_H -#pragma once -#if !defined(Q_MOC_RUN) -#include "PropertyRowImpl.h" -#include "PropertyTreeModel.h" -#include "PropertyDrawContext.h" -#include "QPropertyTree.h" -#include -#include -#include -#include -#include -#endif - -using Serialization::StringListValue; -class PropertyRowStringListValue - : public PropertyRow -{ -public: - PropertyRowStringListValue() - : handle_() {} - PropertyRowWidget* createWidget(QPropertyTree* tree) override; - string valueAsString() const override { return value_.c_str(); } - bool assignTo(const Serialization::SStruct& ser) const override - { - *((StringListValue*)ser.pointer()) = value_.c_str(); - return true; - } - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - YASLI_ESCAPE(ser.size() == sizeof(StringListValue), return ); - const StringListValue& stringListValue = *((StringListValue*)(ser.pointer())); - stringList_ = stringListValue.stringList(); - value_ = stringListValue.c_str(); - handle_ = stringListValue.handle(); - type_ = stringListValue.type(); - } - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - int widgetSizeMin(const QPropertyTree* tree) const override - { - if (userWidgetToContent()) - { - return widthCache_.getOrUpdate(tree, this, tree->_defaultRowHeight()); - } - else - { - return 80; - } - } - WidgetPlacement widgetPlacement() const override { return WIDGET_VALUE; } - const void* searchHandle() const override { return handle_; } - Serialization::TypeID typeId() const override { return type_; } - - void redraw(const PropertyDrawContext& context) override - { - if (multiValue()) - { - context.drawEntry(L" ... ", false, true, 0); - } - else if (userReadOnly()) - { - context.drawValueText(pulledSelected(), valueAsWString().c_str()); - } - else - { - QStyleOptionComboBox option; - option.editable = false; - option.frame = true; - option.currentText = QString(valueAsString().c_str()); - option.state |= QStyle::State_Enabled; - option.rect = QRect(0, 0, context.widgetRect.width(), context.widgetRect.height()); - // we have to translate painter here to work around bug in some themes - context.painter->translate(context.widgetRect.left(), context.widgetRect.top()); - - // create a real instance of a combo so that it has the style sheet applied. - QComboBox widgetForContext; - context.tree->style()->drawComplexControl(QStyle::CC_ComboBox, &option, context.painter, &widgetForContext); - context.painter->setPen(QPen(context.tree->palette().color(QPalette::WindowText))); - QRect textRect = context.tree->style()->subControlRect(QStyle::CC_ComboBox, &option, QStyle::SC_ComboBoxEditField, &widgetForContext); - - textRect.adjust(1, 0, -1, 0); - context.tree->_drawRowValue(*context.painter, valueAsWString().c_str(), &context.tree->font(), textRect, context.tree->palette().color(QPalette::WindowText), false, false); - context.painter->translate(-context.widgetRect.left(), -context.widgetRect.top()); - } - } - - - void serializeValue(Serialization::IArchive& ar) - { - ar(value_, "value", "Value"); - ar(stringList_, "stringList", "String List"); - } -private: - Serialization::StringList stringList_; - string value_; - const void* handle_; - Serialization::TypeID type_; - friend class PropertyRowWidgetStringListValue; - mutable RowWidthCache widthCache_; -}; - -using Serialization::StringListStaticValue; -class PropertyRowStringListStaticValue - : public PropertyRowImpl -{ -public: - PropertyRowStringListStaticValue() - : handle_() {} - PropertyRowWidget* createWidget(QPropertyTree* tree) override; - string valueAsString() const override { return value_.c_str(); } - bool assignTo(const Serialization::SStruct& ser) const override - { - *((StringListStaticValue*)ser.pointer()) = value_.c_str(); - return true; - } - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - YASLI_ESCAPE(ser.size() == sizeof(StringListStaticValue), return ); - const StringListStaticValue& stringListValue = *((StringListStaticValue*)(ser.pointer())); - stringList_.resize(stringListValue.stringList().size()); - for (size_t i = 0; i < stringList_.size(); ++i) - { - stringList_[i] = stringListValue.stringList()[i]; - } - value_ = stringListValue.c_str(); - handle_ = stringListValue.handle(); - type_ = stringListValue.type(); - } - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - int widgetSizeMin(const QPropertyTree* tree) const override - { - if (userWidgetToContent()) - { - return widthCache_.getOrUpdate(tree, this, tree->_defaultRowHeight()); - } - else - { - return 80; - } - } - WidgetPlacement widgetPlacement() const override { return WIDGET_VALUE; } - const void* searchHandle() const override { return handle_; } - Serialization::TypeID typeId() const override { return type_; } - void redraw(const PropertyDrawContext& context) override - { - if (multiValue()) - { - context.drawEntry(L" ... ", false, true, 0); - } - else if (userReadOnly()) - { - context.drawValueText(pulledSelected(), valueAsWString().c_str()); - } - else - { - QStyleOptionComboBox option; - option.currentText = QString(valueAsString().c_str()); - option.state |= QStyle::State_Enabled; - option.rect = context.widgetRect; - - // create a real instance of a combo so that it has the style sheet applied. - QComboBox widgetForContext; - context.tree->style()->drawComplexControl(QStyle::CC_ComboBox, &option, context.painter, &widgetForContext); - context.painter->setPen(QPen(context.tree->palette().color(QPalette::WindowText))); - QRect textRect = context.tree->style()->subControlRect(QStyle::CC_ComboBox, &option, QStyle::SC_ComboBoxEditField, &widgetForContext); - - textRect.adjust(1, 0, -1, 0); - context.tree->_drawRowValue(*context.painter, valueAsWString().c_str(), &context.tree->font(), textRect, context.tree->palette().color(QPalette::WindowText), false, false); - } - } - - - void serializeValue(Serialization::IArchive& ar) - { - ar(value_, "value", "Value"); - ar(stringList_, "stringList", "String List"); - } -private: - Serialization::StringList stringList_; - string value_; - const void* handle_; - Serialization::TypeID type_; - friend class PropertyRowWidgetStringListValue; - mutable RowWidthCache widthCache_; -}; - - -// --------------------------------------------------------------------------- - - -class PropertyRowWidgetStringListValue - : public PropertyRowWidget -{ - Q_OBJECT -public: - PropertyRowWidgetStringListValue(PropertyRowStringListValue* row, QPropertyTree* tree) - : PropertyRowWidget(row, tree) - , comboBox_(new QComboBox()) - { - const Serialization::StringList& stringList = row->stringList_; - for (size_t i = 0; i < stringList.size(); ++i) - { - comboBox_->addItem(stringList[i].c_str()); - } - comboBox_->setCurrentIndex(stringList.find(row->value_.c_str())); - connect(comboBox_, SIGNAL(activated(int)), this, SLOT(onChange(int))); - } - - PropertyRowWidgetStringListValue(PropertyRowStringListStaticValue* row, QPropertyTree* tree) - : PropertyRowWidget(row, tree) - , comboBox_(new QComboBox()) - { - const Serialization::StringList& stringList = row->stringList_; - for (size_t i = 0; i < stringList.size(); ++i) - { - comboBox_->addItem(stringList[i].c_str()); - } - comboBox_->setCurrentIndex(stringList.find(row->value_.c_str())); - connect(comboBox_, SIGNAL(currentIndexChanged(int)), this, SLOT(onChange(int))); - } - - void showPopup() override - { - // Here comboBox_->showPopup() should be sufficient, but sadly with Fusion - // theme ComboBox, when clicked, it fires a mouseReleseTimer, which doesn't - // happen with showPopup. It is used to distinguish click-and-hold from - // simple click. If timer is not fired following mouse release hides combo - // box. That's why the user click is emulated here. - QSize size = comboBox_->size(); - QPoint localPoint = QPoint(aznumeric_cast(size.width() * 0.5f), aznumeric_cast(size.height() * 0.5f)); - QMouseEvent ev(QMouseEvent::MouseButtonPress, localPoint, comboBox_->mapToGlobal(localPoint), Qt::LeftButton, Qt::LeftButton, Qt::KeyboardModifiers()); - QApplication::sendEvent(comboBox_, &ev); - } - - ~PropertyRowWidgetStringListValue() - { - comboBox_->hide(); - comboBox_->setParent(0); - comboBox_->deleteLater(); - comboBox_ = 0; - } - - - void commit(){} - QWidget* actualWidget() { return comboBox_; } -public slots: - void onChange(int) - { - if (strcmp(this->row()->typeName(), Serialization::TypeID::get().name()) == 0) - { - PropertyRowStringListValue* r = static_cast(this->row()); - QByteArray newValue = comboBox_->currentText().toUtf8(); - if (r->value_ != newValue.data()) - { - model()->rowAboutToBeChanged(r); - r->value_ = newValue.data(); - model()->rowChanged(r); - } - else - { - tree_->_cancelWidget(); - } - } - else if (strcmp(this->row()->typeName(), Serialization::TypeID::get().name()) == 0) - { - PropertyRowStringListStaticValue* r = static_cast(this->row()); - QByteArray newValue = comboBox_->currentText().toUtf8(); - if (r->value_ != newValue.data()) - { - model()->rowAboutToBeChanged(r); - r->value_ = newValue.data(); - model()->rowChanged(r); - } - else - { - tree_->_cancelWidget(); - } - } - } -protected: - QComboBox* comboBox_; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWSTRINGLISTVALUE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.cpp deleted file mode 100644 index 832357bfc7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.cpp +++ /dev/null @@ -1,132 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "PropertyRowTagList.h" -#include "PropertyRowString.h" -#include "QPropertyTree.h" -#include "Serialization/Decorators/TagList.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/IArchive.h" -#include "Serialization/Decorators/TagListImpl.h" -#include - -PropertyRowTagList::PropertyRowTagList() - : source_(0) -{ -} - -PropertyRowTagList::~PropertyRowTagList() -{ - if (source_) - { - source_->Release(); - } -} - -void PropertyRowTagList::generateMenu(QMenu& item, QPropertyTree* tree, [[maybe_unused]] bool addActions) -{ - if (userReadOnly() || isFixedSize()) - { - return; - } - - if (!source_) - { - return; - } - - TagListMenuHandler* handler = new TagListMenuHandler(); - handler->tree = tree; - handler->row = this; - tree->addMenuHandler(handler); - - unsigned int numGroups = source_->GroupCount(); - for (unsigned int group = 0; group < numGroups; ++group) - { - unsigned int tagCount = source_->TagCount(group); - if (tagCount == 0) - { - continue; - } - const char* groupName = source_->GroupName(group); - QString title = QString("From ") + groupName; - QMenu* menu = item.addMenu(title); - for (unsigned int tagIndex = 0; tagIndex < tagCount; ++tagIndex) - { - QString str; - str = source_->TagValue(group, tagIndex); - const char* desc = source_->TagDescription(group, tagIndex); - if (desc && desc[0] != '\0') - { - str += "\t"; - str += desc; - } - QAction* action = menu->addAction(str); - QString tag = QString::fromLocal8Bit(source_->TagValue(group, tagIndex)); - action->setData(QVariant(tag)); - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuAddTag())); - } - } - - - QAction* action = item.addAction("Add"); - action->setData(QVariant(QString())); - QObject::connect(action, SIGNAL(triggered()), handler, SLOT(onMenuAddTag())); - - PropertyRowContainer::generateMenu(item, tree, false); -} - -void PropertyRowTagList::addTag(const char* tag, QPropertyTree* tree) -{ - Serialization::SharedPtr ref(this); - - PropertyRow* child = addElement(tree, false); - if (child && strcmp(child->typeName(), "string") == 0) - { - PropertyRowString* stringRow = static_cast(child); - tree->model()->rowAboutToBeChanged(stringRow); - stringRow->setValue(tag, stringRow->searchHandle(), stringRow->typeId()); - tree->model()->rowChanged(stringRow); - } -} - -void TagListMenuHandler::onMenuAddTag() -{ - if (QAction* action = qobject_cast(sender())) - { - QString str = action->data().toString(); - row->addTag(str.toLocal8Bit().data(), tree); - } -} - -void PropertyRowTagList::setValueAndContext(const Serialization::IContainer& value, Serialization::IArchive& ar) -{ - if (source_) - { - source_->Release(); - } - source_ = ar.FindContext(); - if (source_) - { - source_->AddRef(); - } - - PropertyRowContainer::setValueAndContext(value, ar); -} - - -REGISTER_PROPERTY_ROW(TagList, PropertyRowTagList) -DECLARE_SEGMENT(PropertyRowTagList) - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.h deleted file mode 100644 index 4ea032efa9..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowTagList.h +++ /dev/null @@ -1,51 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWTAGLIST_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWTAGLIST_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "PropertyRowContainer.h" -#endif - -struct ITagSource; - -class PropertyRowTagList - : public PropertyRowContainer -{ -public: - PropertyRowTagList(); - ~PropertyRowTagList(); - void setValueAndContext(const Serialization::IContainer& value, Serialization::IArchive& ar) override; - void generateMenu(QMenu& item, QPropertyTree* tree, bool addActions) override; - void addTag(const char* tag, QPropertyTree* tree); - -private: - using PropertyRow::setValueAndContext; - ITagSource* source_; -}; - -struct TagListMenuHandler - : public PropertyRowMenuHandler -{ - Q_OBJECT -public: - - PropertyRowTagList * row; - QPropertyTree* tree; -public slots: - void onMenuAddTag(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYROWTAGLIST_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowToggleButton.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowToggleButton.cpp deleted file mode 100644 index 7ae3231673..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyRowToggleButton.cpp +++ /dev/null @@ -1,205 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - - -#include "EditorCommon_precompiled.h" -#include - -#include "Serialization/ClassFactory.h" -#include "PropertyDrawContext.h" -#include "PropertyRowImpl.h" -#include "QPropertyTree.h" -#include "PropertyTreeModel.h" -#include "Serialization.h" -#include "Color.h" -#include "Unicode.h" -#include "Serialization/Decorators/ToggleButton.h" -using Serialization::ToggleButton; -using Serialization::RadioButton; - -class PropertyRowToggleButton - : public PropertyRow -{ -public: - PropertyRowToggleButton() - : underMouse_(false) - , value_(false) - { - } - - bool isLeaf() const{ return true; } - bool isStatic() const{ return false; } - bool isSelectable() const{ return true; } - - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - ToggleButton* value = (ToggleButton*)(ser.pointer()); - value_ = *value->value; - } - - bool assignTo(const Serialization::SStruct& ser) const override - { - ToggleButton* value = (ToggleButton*)(ser.pointer()); - *value->value = value_; - return true; - } - wstring valueAsWString() const override { return L""; } - WidgetPlacement widgetPlacement() const override { return WIDGET_INSTEAD_OF_TEXT; } - void serializeValue([[maybe_unused]] Serialization::IArchive& ar) {} - int widgetSizeMin([[maybe_unused]] const QPropertyTree* tree) const override { return 36; } - - bool onActivate(const PropertyActivationEvent& e) override - { - if (e.reason == PropertyActivationEvent::REASON_KEYBOARD) - { - value_; - } - return true; - } - - bool onMouseDown(QPropertyTree* tree, QPoint point, [[maybe_unused]] bool& changed) override - { - if (widgetRect(tree).contains(point)) - { - underMouse_ = true; - pressed_ = true; - tree->update(); - return true; - } - return false; - } - - void onMouseDrag(const PropertyDragEvent& e) override - { - bool underMouse = widgetRect(e.tree).contains(e.pos); - if (underMouse != underMouse_) - { - underMouse_ = underMouse; - e.tree->update(); - } - } - - void onMouseUp(QPropertyTree* tree, QPoint point) override - { - if (widgetRect(tree).contains(point)) - { - tree->model()->rowAboutToBeChanged(this); - pressed_ = false; - value_ = !value_; - tree->model()->rowChanged(this); - } - } - - void redraw(const PropertyDrawContext& context) override - { - QRect rect = context.widgetRect; - - wstring text = toWideChar(labelUndecorated()); - int buttonFlags = BUTTON_CENTER; - if ((value_ || pressed_) && underMouse_) - { - buttonFlags |= BUTTON_PRESSED; - } - if (selected() || pressed_) - { - buttonFlags |= BUTTON_FOCUSED; - } - if (userReadOnly()) - { - buttonFlags |= BUTTON_DISABLED; - } - context.drawButton(rect, text.c_str(), buttonFlags, &context.tree->font()); - } -protected: - bool pressed_ : 1; - bool underMouse_ : 1; - bool value_ : 1; -}; - -class PropertyRowRadioButton - : public PropertyRow -{ -public: - - bool isLeaf() const override { return true; } - bool isStatic() const override { return false; } - bool isSelectable() const override { return false; } - - bool onActivate(const PropertyActivationEvent& e) override - { - if (!m_justSet) - { - e.tree->model()->rowAboutToBeChanged(this); - m_justSet = true; - e.tree->model()->rowChanged(this); - } - return true; - } - void setValueAndContext(const Serialization::SStruct& ser, [[maybe_unused]] Serialization::IArchive& ar) override - { - RadioButton* value = (RadioButton*)(ser.pointer()); - m_value = value->buttonValue; - m_toggled = m_value == *value->value; - m_justSet = false; - } - bool assignTo(const Serialization::SStruct& ser) const override - { - if (m_justSet) - { - *((RadioButton*)ser.pointer())->value = m_value; - } - return true; - } - wstring valueAsWString() const override { return L""; } - WidgetPlacement widgetPlacement() const override { return WIDGET_INSTEAD_OF_TEXT; } - void serializeValue(Serialization::IArchive& ar) override - { - bool oldToggled = m_toggled; - ar(m_toggled, "toggled"); - if (m_toggled && !oldToggled) - { - m_justSet = true; - } - ar(m_value, "value"); - } - int widgetSizeMin([[maybe_unused]] const QPropertyTree* tree) const override { return 40; } - - void redraw(const PropertyDrawContext& context) - { - QRect rect = context.widgetRect; - bool pressed = context.m_pressed || m_toggled || m_justSet; - - wstring text = toWideChar(labelUndecorated()); - int buttonFlags = BUTTON_CENTER; - if (pressed) - { - buttonFlags |= BUTTON_PRESSED; - } - if (selected()) - { - buttonFlags |= BUTTON_FOCUSED; - } - if (userReadOnly()) - { - buttonFlags |= BUTTON_DISABLED; - } - context.drawButton(rect, text.c_str(), buttonFlags, &context.tree->font()); - } -protected: - bool m_toggled; - bool m_justSet; - int m_value; -}; - -REGISTER_PROPERTY_ROW(ToggleButton, PropertyRowToggleButton); -REGISTER_PROPERTY_ROW(RadioButton, PropertyRowRadioButton); diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeMenuHandler.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeMenuHandler.h deleted file mode 100644 index 2d821266da..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeMenuHandler.h +++ /dev/null @@ -1,45 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMENUHANDLER_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMENUHANDLER_H -#pragma once - -#include "PropertyRow.h" - -struct PropertyTreeMenuHandler - : PropertyRowMenuHandler -{ - Q_OBJECT -public: - PropertyRow * row; - QPropertyTree* tree; - - string filterName; - string filterValue; - string filterType; - -public slots: - void onMenuFilter(); - void onMenuFilterByName(); - void onMenuFilterByValue(); - void onMenuFilterByType(); - - void onMenuUndo(); - void onMenuRedo(); - - void onMenuCopy(); - void onMenuPaste(); -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMENUHANDLER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.cpp deleted file mode 100644 index 7192757ecc..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.cpp +++ /dev/null @@ -1,445 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyTreeModel.h" -#include "QPropertyTree.h" -#include "Serialization.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/Callback.h" - -PropertyTreeModel::PropertyTreeModel() -: expandLevels_(0) -, undoEnabled_(true) -, fullUndo_(false) -{ - clear(); -} - -PropertyTreeModel::~PropertyTreeModel() -{ - root_ = 0; - defaultTypes_.clear(); - defaultTypesPoly_.clear(); -} - -TreePath PropertyTreeModel::pathFromRow(PropertyRow* row) -{ - TreePath result; - if(row) - { - while(row->parent()){ - int childIndex = row->parent()->childIndex(row); - YASLI_ESCAPE(childIndex >= 0, return TreePath()); - result.insert(result.begin(), childIndex); - row = row->parent(); - } - } - return result; -} - -void PropertyTreeModel::selectRow(PropertyRow* row, bool select, bool exclusive) -{ - if(exclusive) - deselectAll(); - - row->setSelected(select); - - Selection::iterator it = std::find(selection_.begin(), selection_.end(), pathFromRow(row)); - if(select){ - if(it == selection_.end()) - selection_.push_back(pathFromRow(row)); - setFocusedRow(row); - } - else if(it != selection_.end()){ -#if !defined(NDEBUG) - PropertyRow* it_row = rowFromPath(*it); -#endif - YASLI_ASSERT(it_row->refCount() > 0 && it_row->refCount() < 0xFFFF); - selection_.erase(it); - } -} - -void PropertyTreeModel::deselectAll() -{ - Selection::iterator it; - for(it = selection_.begin(); it != selection_.end(); ++it){ - PropertyRow* row = rowFromPath(*it); - row->setSelected(false); - } - selection_.clear(); -} - -PropertyRow* PropertyTreeModel::rowFromPath(const TreePath& path) -{ - PropertyRow* row = root(); - if (!root()) - return 0; - TreePath::const_iterator it; - for(it = path.begin(); it != path.end(); ++it){ - int index = it->index; - if(index < int(row->count()) && index >= 0){ - PropertyRow* nextRow = row->childByIndex(index); - if(!nextRow) - return row; - else - row = nextRow; - } - else - return row; - } - return row; -} - -void PropertyTreeModel::setSelection(const Selection& selection) -{ - deselectAll(); - Selection::const_iterator it; - for(it = selection.begin(); it != selection.end(); ++it){ - const TreePath& path = *it; - PropertyRow* row = rowFromPath(path); - if(row) - selectRow(row, true, false); - } -} - -void PropertyTreeModel::clear() -{ - if(root_) - root_->clear(); - root_ = 0; - setRoot(new PropertyRow()); - root_->setNames("", "root", ""); - selection_.clear(); -} - -void PropertyTreeModel::onUpdated(const PropertyRows& rows, bool needApply) -{ - signalUpdated(rows, needApply); -} - -void PropertyTreeModel::applyOperator(PropertyTreeOperator* op) -{ - YASLI_ESCAPE(op, return); - PropertyRow *dest = rowFromPath(op->path_); - YASLI_ESCAPE(dest && "Unable to apply operator!", return); - if(op->type_ == PropertyTreeOperator::NONE) - return; - YASLI_ESCAPE(op->row_, return); - if(dest->parent()) - dest->parent()->replaceAndPreserveState(dest, op->row_, 0); - else{ - op->row_->assignRowProperties(root_); - root_ = op->row_; - } - PropertyRow* newRow = op->row_; - op->row_ = 0; - rowChanged(newRow); -} - -void PropertyTreeModel::undo() -{ - YASLI_ESCAPE(!undoOperators_.empty(), return); - - auto op = &undoOperators_.back(); - PropertyRow *dest = rowFromPath(op->path_); - PropertyTreeOperator redoOp = getCurrentStateTreeOperator(dest); - - applyOperator(op); - undoOperators_.pop_back(); - - pushRedo(redoOp); -} - -void PropertyTreeModel::redo() -{ - YASLI_ESCAPE(!redoOperators_.empty(), return); - - auto op = &redoOperators_.back(); - PropertyRow *dest = rowFromPath(op->path_); - PropertyTreeOperator undoOp = getCurrentStateTreeOperator(dest); - - applyOperator(op); - redoOperators_.pop_back(); - - pushUndo(undoOp); -} - -void PropertyTreeModel::clearUndo() -{ - undoOperators_.clear(); - redoOperators_.clear(); - - Q_EMIT signalUndoRedoStackChanged(false, false); -} - -PropertyTreeModel::UpdateLock PropertyTreeModel::lockUpdate() -{ - if(updateLock_) - return updateLock_; - else { - UpdateLock lock = new PropertyTreeModel::LockedUpdate(this);; - updateLock_ = lock; - lock->release(); - return lock; - } -} - -void PropertyTreeModel::dismissUpdate() -{ - if(updateLock_) - updateLock_->dismissUpdate(); -} - -void PropertyTreeModel::requestUpdate(const PropertyRows& rows, bool apply) -{ - if(updateLock_) - updateLock_->requestUpdate(rows, apply); - else - onUpdated(rows, apply); -} - -struct RowObtainer { - RowObtainer(std::vector& states) : states_(states) {} - ScanResult operator()(PropertyRow* row) - { - states_.push_back(row->expanded() ? 1 : 0); - return row->expanded() ? SCAN_CHILDREN_SIBLINGS : SCAN_SIBLINGS; - } -protected: - std::vector& states_; -}; - -struct RowExpander { - RowExpander(const std::vector& states) : states_(states), index_(0) {} - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, [[maybe_unused]] int index) - { - if(size_t(index_) >= states_.size()) - return SCAN_FINISHED; - - if(states_[index_++]){ - if(row->canBeToggled(tree)) - row->_setExpanded(true); - return SCAN_CHILDREN_SIBLINGS; - } - else{ - row->_setExpanded(false); - return SCAN_SIBLINGS; - } - } -protected: - int index_; - const std::vector& states_; -}; - -void PropertyTreeModel::Serialize(Serialization::IArchive& ar, QPropertyTree* tree) -{ - ar(focusedRow_, "focusedRow", 0); - ar(selection_, "selection", 0); - - if (root()) { - std::vector expanded; - if(ar.IsOutput()) { - RowObtainer op(expanded); - root()->scanChildren(op); - } - ar(expanded, "expanded", 0); - if(ar.IsInput()){ - Selection sel = selection_; - setSelection(sel); - RowExpander op(expanded); - root()->scanChildren(op, tree); - root()->setLayoutChanged(); - root()->setLayoutChangedToChildren(); - } - } -} - -void PropertyTreeModel::pushUndo(const PropertyTreeOperator& op) -{ - PropertyTreeOperator oper = op; - bool handled = false; - signalPushUndo(&oper, &handled); - if(!handled && oper.row_ != 0) - undoOperators_.push_back(oper); - - Q_EMIT signalUndoRedoStackChanged(!undoOperators_.empty(), !redoOperators_.empty()); -} - -void PropertyTreeModel::pushRedo(const PropertyTreeOperator& op) -{ - PropertyTreeOperator oper = op; - bool handled = false; - signalPushRedo(&oper, &handled); - if (!handled && oper.row_ != 0) - redoOperators_.push_back(oper); - - Q_EMIT signalUndoRedoStackChanged(!undoOperators_.empty(), !redoOperators_.empty()); -} - -PropertyTreeOperator PropertyTreeModel::getCurrentStateTreeOperator(PropertyRow* row) -{ - if (fullUndo_){ - if (undoEnabled_){ - SharedPtr clonedRow = root()->clone(constStrings()); - clonedRow->assignRowState(*root(), true); - return PropertyTreeOperator(TreePath(), clonedRow); - } - else{ - return PropertyTreeOperator(TreePath(), 0); - } - } - else{ - if (undoEnabled_){ - SharedPtr clonedRow = row->clone(constStrings()); - clonedRow->assignRowState(*row, true); - return PropertyTreeOperator(pathFromRow(row), clonedRow); - } - else{ - return PropertyTreeOperator(pathFromRow(row), 0); - } - } -} - -void PropertyTreeModel::rowAboutToBeChanged(PropertyRow* row) -{ - YASLI_ESCAPE(row, return); - pushUndo(getCurrentStateTreeOperator(row)); - - // clear the redo stack now - redoOperators_.clear(); - Q_EMIT signalUndoRedoStackChanged(true, false); -} - -void PropertyTreeModel::callRowCallback(PropertyRow* row) -{ - PropertyRow* current = row; - while (true) { - Serialization::ICallback* callback = current->callback(); - if (callback) { - auto applyFunc = [=](void* arg, [[maybe_unused]] const TypeID& type) { - current->assignToByPointer(arg, callback->Type()); - }; - callback->Call(applyFunc); - return; - } - current = current->parent(); - if (current) - current->handleChildrenChange(); - else - break; - } -} - -void PropertyTreeModel::rowChanged(PropertyRow* row, bool apply) -{ - callRowCallback(row); - - YASLI_ESCAPE(row, return); - row->setLabelChanged(); - row->setLayoutChanged(); - - PropertyRow* parentObj = row; - while (parentObj->parent() && !parentObj->isObject()) - parentObj = parentObj->parent(); - - row->setMultiValue(false); - - PropertyRows rows; - rows.push_back(parentObj); - requestUpdate(rows, apply); -} - -bool PropertyTreeModel::defaultTypeRegistered(const char* typeName) const -{ - return defaultTypes_.find(typeName) != defaultTypes_.end(); -} - -void PropertyTreeModel::addDefaultType(PropertyRow* row, const char* typeName) -{ - YASLI_ESCAPE(typeName != 0, return); - defaultTypes_[typeName] = row; -} - -PropertyRow* PropertyTreeModel::defaultType(const char* typeName) const -{ - DefaultTypes::const_iterator it = defaultTypes_.find(typeName); - YASLI_ESCAPE(it != defaultTypes_.end(), return 0); - return it->second; -} - -void PropertyTreeModel::addDefaultType(const TypeID& type, const PropertyDefaultDerivedTypeValue& value) -{ - YASLI_ASSERT(type != TypeID()); - - BaseClass& base = defaultTypesPoly_[type]; - for (DerivedTypes::iterator it = base.types.begin(); it != base.types.end(); ++it){ - if (it->registeredName == value.registeredName) { - YASLI_ASSERT(it->root == 0); - *it = value; - return; - } - } - - base.types.push_back(value); - base.strings.push_back(value.label.c_str()); -} - -const PropertyDefaultDerivedTypeValue* PropertyTreeModel::defaultType(const TypeID& baseType, int derivedIndex) const -{ - DefaultTypesPoly::const_iterator it = defaultTypesPoly_.find(baseType); - YASLI_ESCAPE(it != defaultTypesPoly_.end(), return 0); - const BaseClass& base = it->second; - YASLI_ESCAPE(size_t(derivedIndex) < base.types.size(), return 0); - return &base.types[derivedIndex]; -} - -bool PropertyTreeModel::defaultTypeRegistered(const TypeID& baseType, const char* derivedRegisteredName) const -{ - if (!derivedRegisteredName) - derivedRegisteredName = ""; - DefaultTypesPoly::const_iterator it = defaultTypesPoly_.find(baseType); - - if (it == defaultTypesPoly_.end()) - return false; - - const BaseClass& base = it->second; - DerivedTypes::const_iterator dit; - for (dit = base.types.begin(); dit != base.types.end(); ++dit){ - if (dit->registeredName == derivedRegisteredName) - return true; - } - return false; -} - -const Serialization::StringList& PropertyTreeModel::typeStringList(const TypeID& baseType) const -{ - DefaultTypesPoly::const_iterator it = defaultTypesPoly_.find(baseType); - - static Serialization::StringList empty; - YASLI_ESCAPE(it != defaultTypesPoly_.end(), return empty); - const BaseClass& base = it->second; - return base.strings; -} - -// ---------------------------------------------------------------------------------- - -bool Serialize(Serialization::IArchive& ar, TreePathLeaf& value, const char* name, const char* label) -{ - return ar(value.index, name, label); -} - -bool Serialize(Serialization::IArchive& ar, TreeSelection& value, const char* name, const char* label) -{ - return ar(static_cast&>(value), name, label); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.h deleted file mode 100644 index 0b518f8171..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeModel.h +++ /dev/null @@ -1,208 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMODEL_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMODEL_H -#pragma once - - -#if !defined(Q_MOC_RUN) -#include -#include "PropertyRow.h" -#include "PropertyTreeOperator.h" -#include "Serialization/Pointers.h" -#endif - -using std::vector; -using std::map; - -struct TreeSelection : vector -{ - bool operator==(const TreeSelection& rhs){ - if(size() != rhs.size()) - return false; - for(int i = 0; i < int(size()); ++i) - if((*this)[i] != rhs[i]) - return false; - return true; - } -}; - -struct PropertyDefaultDerivedTypeValue -{ - string registeredName; - Serialization::SharedPtr root; - Serialization::IClassFactory* factory; - int factoryIndex; - std::string label; - - PropertyDefaultDerivedTypeValue() - : factoryIndex(-1) - , factory(0) - { - } -}; - -struct PropertyDefaultTypeValue -{ - Serialization::TypeID type; - string registedName; - Serialization::SharedPtr root; - Serialization::IClassFactory* factory; - int factoryIndex; - std::string label; - - PropertyDefaultTypeValue() - : factoryIndex(-1) - , factory(0) - { - } -}; - -// --------------------------------------------------------------------------- - -class PropertyTreeModel : public QObject -{ - Q_OBJECT -public: - class LockedUpdate : public Serialization::RefCounter{ - public: - LockedUpdate(PropertyTreeModel* model) - : model_(model) - , apply_(false) - {} - void requestUpdate(const PropertyRows& rows, bool apply) { - for (size_t i = 0; i < rows.size(); ++i) { - PropertyRow* row = rows[i]; - if (std::find(rows_.begin(), rows_.end(), row) == rows_.end()) - rows_.push_back(row); - } - if (apply) - apply_ = true; - } - void dismissUpdate(){ rows_.clear(); } - ~LockedUpdate(){ - model_->updateLock_ = 0; - if(!rows_.empty()) - model_->signalUpdated(rows_, apply_); - } - protected: - PropertyTreeModel* model_; - PropertyRows rows_; - bool apply_; - }; - typedef Serialization::SharedPtr UpdateLock; - - typedef TreeSelection Selection; - - PropertyTreeModel(); - ~PropertyTreeModel(); - - void clear(); - bool canUndo() const{ return !undoOperators_.empty(); } - void undo(); - bool canRedo() const{ return !redoOperators_.empty(); } - void redo(); - void clearUndo(); - - TreePath pathFromRow(PropertyRow* node); - PropertyRow* rowFromPath(const TreePath& path); - void setFocusedRow(PropertyRow* row) { focusedRow_ = pathFromRow(row); } - PropertyRow* focusedRow() { return rowFromPath(focusedRow_); } - - const Selection& selection() const{ return selection_; } - void setSelection(const Selection& selection); - - void setRoot(PropertyRow* root) { root_ = root; } - PropertyRow* root() { return root_; } - const PropertyRow* root() const { return root_; } - - void Serialize(Serialization::IArchive& ar, QPropertyTree* tree); - - UpdateLock lockUpdate(); - void requestUpdate(const PropertyRows& rows, bool needApply); - void dismissUpdate(); - - void selectRow(PropertyRow* row, bool selected, bool exclusive = true); - void deselectAll(); - - void rowAboutToBeChanged(PropertyRow* row); - void callRowCallback(PropertyRow* row); - void rowChanged(PropertyRow* row, bool apply = true); // be careful: it can destroy 'row' - - void setUndoEnabled(bool enabled) { undoEnabled_ = enabled; } - void setFullUndo(bool fullUndo) { fullUndo_ = fullUndo; } - void setExpandLevels(int levels) { expandLevels_ = levels; } - int expandLevels() const{ return expandLevels_; } - - void onUpdated(const PropertyRows& rows, bool needApply); - - // for defaultArchive - const Serialization::StringList& typeStringList(const Serialization::TypeID& baseType) const; - - bool defaultTypeRegistered(const char* typeName) const; - void addDefaultType(PropertyRow* propertyRow, const char* typeName); - PropertyRow* defaultType(const char* typeName) const; - - bool defaultTypeRegistered(const Serialization::TypeID& baseType, const char* derivedRegisteredName) const; - void addDefaultType(const Serialization::TypeID& baseType, const PropertyDefaultDerivedTypeValue& value); - const PropertyDefaultDerivedTypeValue* defaultType(const Serialization::TypeID& baseType, int index) const; - ConstStringList* constStrings() { return &constStrings_; } - -signals: - void signalUpdated(const PropertyRows& rows, bool needApply); - void signalPushUndo(PropertyTreeOperator* op, bool* result); - void signalPushRedo(PropertyTreeOperator* op, bool* result); - - void signalUndoRedoStackChanged(bool undosAvailable, bool redosAvailable); -private: - void applyOperator(PropertyTreeOperator* op); - void pushUndo(const PropertyTreeOperator& op); - void pushRedo(const PropertyTreeOperator& op); - - void clearObjectReferences(); - PropertyTreeOperator getCurrentStateTreeOperator(PropertyRow* row); - - TreePath focusedRow_; - Selection selection_; - - Serialization::SharedPtr root_; - UpdateLock updateLock_; - - typedef std::map > DefaultTypes; - DefaultTypes defaultTypes_; - - - typedef vector DerivedTypes; - struct BaseClass{ - Serialization::TypeID type; - std::string name; - Serialization::StringList strings; - DerivedTypes types; - }; - typedef map DefaultTypesPoly; - DefaultTypesPoly defaultTypesPoly_; - - int expandLevels_; - bool undoEnabled_; - bool fullUndo_; - - std::vector undoOperators_; - std::vector redoOperators_; - - ConstStringList constStrings_; - - friend class TreeImpl; -}; - -bool Serialize(Serialization::IArchive& ar, TreeSelection &selection, const char* name, const char* label); -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEMODEL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.cpp deleted file mode 100644 index 1c70b6d73c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ - -// Modifications copyright Amazon.com, Inc. or its affiliates. - -#include "EditorCommon_precompiled.h" -#include "PropertyTreeOperator.h" -#include "PropertyRow.h" -#include "Serialization/Enum.h" -#include "Serialization/STL.h" -#include "Serialization/Pointers.h" -#include "Serialization/IArchive.h" -#include "Serialization/STLImpl.h" -#include "Serialization/PointersImpl.h" - -SERIALIZATION_ENUM_BEGIN_NESTED(PropertyTreeOperator, Type, "PropertyTreeOp") -SERIALIZATION_ENUM_VALUE_NESTED(PropertyTreeOperator, REPLACE, "Replace") -SERIALIZATION_ENUM_VALUE_NESTED(PropertyTreeOperator, ADD, "Add") -SERIALIZATION_ENUM_VALUE_NESTED(PropertyTreeOperator, REMOVE, "Remove") -SERIALIZATION_ENUM_END() - -PropertyTreeOperator::PropertyTreeOperator(const TreePath& path, PropertyRow* row) -: type_(REPLACE) -, path_(path) -, index_(-1) -, row_(row) -{ -} - -PropertyTreeOperator::PropertyTreeOperator() -: type_(NONE) -, index_(-1) -{ -} - -PropertyTreeOperator::~PropertyTreeOperator() -{ -} - -void PropertyTreeOperator::Serialize(Serialization::IArchive& ar) -{ - ar(type_, "type", "Type"); - ar(path_, "path", "Path"); - ar(row_, "row", "Row"); - ar(index_, "index", "Index"); -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.h deleted file mode 100644 index 0316cfe7cd..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/PropertyTreeOperator.h +++ /dev/null @@ -1,65 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEOPERATOR_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEOPERATOR_H -#pragma once - -#include -#include "Serialization/Pointers.h" - -namespace Serialization{ class IArchive; } - -class PropertyRow; - -struct TreePathLeaf -{ - int index; - - TreePathLeaf(int _index = -1) - : index(_index) - { - } - bool operator==(const TreePathLeaf& rhs) const{ - return index == rhs.index; - } - bool operator!=(const TreePathLeaf& rhs) const{ - return index != rhs.index; - } -}; -bool Serialize(Serialization::IArchive& ar, TreePathLeaf& value, const char* name, const char* label); - -typedef std::vector TreePath; -typedef std::vector TreePathes; - -class PropertyTreeOperator -{ -public: - enum Type{ - NONE, - REPLACE, - ADD, - REMOVE - }; - - PropertyTreeOperator(); - ~PropertyTreeOperator(); - PropertyTreeOperator(const TreePath& path, PropertyRow* row); - void Serialize(Serialization::IArchive& ar); -private: - Type type_; - TreePath path_; - Serialization::SharedPtr row_; - int index_; - friend class PropertyTreeModel; -}; - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_PROPERTYTREEOPERATOR_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.cpp deleted file mode 100644 index 87db4de1b0..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.cpp +++ /dev/null @@ -1,227 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "QPropertyDialog.h" -#include "QPropertyTree.h" -#include "Serialization/IArchive.h" -#include "Serialization/BinArchive.h" -#include "Serialization/JSONIArchive.h" -#include "Serialization/JSONOArchive.h" -#include -#include -#include - -#include - -#ifndef SERIALIZATION_STANDALONE -#include -#include -#else -namespace PathUtil -{ - string GetParentDirectory(const char* path) - { - const char* end = strrchr(path, '/'); - if (!end) - { - end = strrchr(path, '\\'); - } - if (end) - { - return string(path, end); - } - else - { - return string(); - } - } -}; -#endif - -#ifndef SERIALIZATION_STANDALONE -#include -#endif - -static string getFullStateFilename(const char* filename) -{ -#ifdef SERIALIZATION_STANDALONE - // use current folder - return filename; -#else - string path = GetIEditor()->GetResolvedUserFolder().toUtf8().data(); - if (!path.empty() && path[path.size() - 1] != '\\' && path[path.size() - 1] != '/') - { - path.push_back('\\'); - } - path += filename; - return path; -#endif -} - -bool QPropertyDialog::edit(Serialization::SStruct& ser, const char* title, const char* windowStateFilename, QWidget* parent) -{ - QPropertyDialog dialog(parent); - dialog.setSerializer(ser); - dialog.setWindowTitle(QString::fromLocal8Bit(title)); - dialog.setWindowStateFilename(windowStateFilename); - - return dialog.exec() == QDialog::Accepted; -} - -QPropertyDialog::QPropertyDialog(QWidget* parent) - : QDialog(parent) - , m_sizeHint(440, 500) - , m_layout(0) - , m_storeContent(false) -{ - connect(this, SIGNAL(accepted()), this, SLOT(onAccepted())); - connect(this, SIGNAL(rejected()), this, SLOT(onRejected())); - setModal(true); - setWindowModality(Qt::ApplicationModal); - - m_propertyTree = new QPropertyTree(this); - m_propertyTree->setExpandLevels(1); - - m_layout = new QBoxLayout(QBoxLayout::TopToBottom, this); - - m_layout->addWidget(m_propertyTree, 1); - QDialogButtonBox* buttons = new QDialogButtonBox(this); - buttons->setStandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); - connect(buttons, SIGNAL(accepted()), this, SLOT(accept())); - connect(buttons, SIGNAL(rejected()), this, SLOT(reject())); - m_layout->addWidget(buttons, 0); -} - -QPropertyDialog::~QPropertyDialog() -{ -} - -void QPropertyDialog::revert() -{ - if (m_propertyTree) - { - m_propertyTree->revert(); - } -} - -void QPropertyDialog::setSerializer(const Serialization::SStruct& ser) -{ - if (!m_serializer) - { - m_serializer.reset(new Serialization::SStruct()); - } - *m_serializer = ser; -} - -void QPropertyDialog::setWindowStateFilename(const char* windowStateFilename) -{ - m_windowStateFilename = windowStateFilename; -} - -void QPropertyDialog::setSizeHint(const QSize& size) -{ - m_sizeHint = size; -} - -void QPropertyDialog::setStoreContent(bool storeContent) -{ - m_storeContent = storeContent; -} - -QSize QPropertyDialog::sizeHint() const -{ - return m_sizeHint; -} - -void QPropertyDialog::setVisible(bool visible) -{ - QDialog::setVisible(visible); - - if (visible) - { - string fullStateFilename = getFullStateFilename(m_windowStateFilename.c_str()); - if (!fullStateFilename.empty()) - { - Serialization::JSONIArchive ia; - if (ia.load(fullStateFilename.c_str())) - { - ia(*this); - } - } - - m_backup.reset(new Serialization::BinOArchive()); - if (m_serializer && *m_serializer) - { - const Serialization::SStruct& ser = *m_serializer; - (*m_backup)(ser, "backup"); - m_propertyTree->attach(*m_serializer); - } - } -} - -void QPropertyDialog::onAccepted() -{ - string fullStateFilename = getFullStateFilename(m_windowStateFilename.c_str()); - if (!fullStateFilename.empty()) - { - Serialization::JSONOArchive oa; - oa(*this); - - QDir().mkdir(QString::fromLocal8Bit(PathUtil::GetParentDirectory(fullStateFilename.c_str()).c_str())); - oa.save(fullStateFilename.c_str()); - } -} - -void QPropertyDialog::onRejected() -{ - if (m_backup.get() && m_serializer.get() && *m_serializer) - { - // restore previous object state - Serialization::BinIArchive ia; - if (ia.open(m_backup->buffer(), m_backup->length())) - { - const Serialization::SStruct& ser = *m_serializer; - ia(ser, "backup"); - } - } -} - -void QPropertyDialog::setArchiveContext(Serialization::SContextLink* context) -{ - m_propertyTree->setArchiveContext(context); -} - -void QPropertyDialog::Serialize(Serialization::IArchive& ar) -{ - if (m_storeContent && m_serializer.get()) - { - ar(*m_serializer, "content"); - } - - QByteArray geometry; - if (ar.IsOutput()) - { - geometry = saveGeometry(); - } - std::vector geometryVec(geometry.begin(), geometry.end()); - ar(geometryVec, "geometry"); - if (ar.IsInput() && !geometryVec.empty()) - { - restoreGeometry(QByteArray(geometryVec.data(), (int)geometryVec.size())); - } - - ar(*m_propertyTree, "propertyTree"); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.h deleted file mode 100644 index a295ec188f..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyDialog.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYDIALOG_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYDIALOG_H -#pragma once - -#if !defined(Q_MOC_RUN) -#include "../EditorCommonAPI.h" -#include "Strings.h" -#include - -#include -#endif - -namespace Serialization -{ - struct SStruct; - struct SContextLink; - class BinOArchive; - class IArchive; -} - -class QPropertyTree; -class QBoxLayout; - -class EDITOR_COMMON_API QPropertyDialog - : public QDialog -{ - Q_OBJECT -public: - static bool edit(Serialization::SStruct& ser, const char* title, const char* windowStateFilename, QWidget* parent); - - QPropertyDialog(QWidget* parent); - ~QPropertyDialog(); - - void setSerializer(const Serialization::SStruct& ser); - void setArchiveContext(Serialization::SContextLink* context); - void setWindowStateFilename(const char* windowStateFilename); - void setSizeHint(const QSize& sizeHint); - void setStoreContent(bool storeContent); - - void revert(); - QBoxLayout* layout() { return m_layout; } - - void Serialize(Serialization::IArchive& ar); -protected slots: - void onAccepted(); - void onRejected(); - -protected: - QSize sizeHint() const override; - void setVisible(bool visible) override; -private: - QPropertyTree* m_propertyTree; - QBoxLayout* m_layout; - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::unique_ptr m_serializer; - std::unique_ptr m_backup; - string m_windowStateFilename; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - QSize m_sizeHint; - bool m_storeContent; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYDIALOG_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.cpp deleted file mode 100644 index 0af0b8368a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.cpp +++ /dev/null @@ -1,3083 +0,0 @@ -// Modifications copyright Amazon.com, Inc. or its affiliates. - -/** -* wWidgets - Lightweight UI Toolkit. -* Copyright (C) 2009-2011 Evgeny Andreeshchev -* Alexander Kotliar -* -* This code is distributed under the MIT License: -* http://www.opensource.org/licenses/MIT -*/ - - -#include "EditorCommon_precompiled.h" -#include "QPropertyTree.h" -#include "PropertyDrawContext.h" -#include "Serialization.h" -#include "Serialization/Decorators/Range.h" -using Serialization::Range; -#include "PropertyTreeModel.h" -#include "QPropertyTreeStyle.h" - -#include "PropertyOArchive.h" -#include "PropertyIArchive.h" -#include "Unicode.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include "PropertyTreeMenuHandler.h" - -#include "MathUtils.h" - -#include -// only for clipboard: -#include -#include -#include "PropertyRowPointer.h" -#include "PropertyRowContainer.h" -// ^^^ -#include "PropertyRowObject.h" -#include - -using Serialization::SStructs; - -void PropertyTreeMenuHandler::onMenuFilter() -{ - tree->startFilter(""); -} - -void PropertyTreeMenuHandler::onMenuFilterByName() -{ - tree->startFilter(filterName.c_str()); -} - -void PropertyTreeMenuHandler::onMenuFilterByValue() -{ - tree->startFilter(filterValue.c_str()); -} - -void PropertyTreeMenuHandler::onMenuFilterByType() -{ - tree->startFilter(filterType.c_str()); -} - -void PropertyTreeMenuHandler::onMenuUndo() -{ - tree->model()->undo(); -} - -void PropertyTreeMenuHandler::onMenuRedo() -{ - tree->model()->redo(); -} - -static PropertyRow* findFirstLeafPulledRow(PropertyRow* row) -{ - if (row->isLeaf() && - row->widgetPlacement() != PropertyRow::WIDGET_ICON && - row->widgetPlacement() != PropertyRow::WIDGET_NONE) - return row; - - for (int i = 0; i < row->count(); ++i) - { - PropertyRow* child = row->childByIndex(i); - if (!child) - continue; - if (!child->pulledUp()) - continue; - PropertyRow* leaf = findFirstLeafPulledRow(child); - if (leaf) - return leaf; - } - - return 0; -} - -static QMimeData* propertyRowToMimeData(PropertyRow* row, ConstStringList* constStrings) -{ - PropertyRow::setConstStrings(constStrings); - SharedPtr clonedRow(row->clone(constStrings)); - Serialization::BinOArchive oa; - PropertyRow::setConstStrings(constStrings); - if (!oa(clonedRow, "row", "Row")) { - PropertyRow::setConstStrings(0); - return 0; - } - PropertyRow::setConstStrings(0); - - QByteArray byteArray(oa.buffer(), (int)oa.length()); - QMimeData* mime = new QMimeData; - mime->setData("binary/crypropertytree", byteArray); - if (clonedRow) - { - PropertyRow* textRow = findFirstLeafPulledRow(row); - if (textRow) - mime->setText(QString::fromWCharArray(textRow->valueAsWString().c_str())); - } - return mime; -} - -static bool smartPaste(PropertyRow* dest, SharedPtr& source, PropertyTreeModel* model, bool onlyCheck) -{ - bool result = false; - // content of the pulled container has a priority over the node itself - PropertyRowContainer* destPulledContainer = static_cast(dest->pulledContainer()); - if ((destPulledContainer && strcmp(destPulledContainer->elementTypeName(), source->typeName()) == 0)) { - PropertyRow* elementRow = model->defaultType(destPulledContainer->elementTypeName()); - YASLI_ESCAPE(elementRow, return false); - if (strcmp(elementRow->typeName(), source->typeName()) == 0){ - result = true; - if (!onlyCheck){ - PropertyRow* dest = elementRow; - if (dest->isPointer() && !source->isPointer()){ - PropertyRowPointer* d = static_cast(dest); - SharedPtr newSourceRoot = static_cast(d->clone(model->constStrings()).get()); - source->swapChildren(newSourceRoot, model); - source = newSourceRoot; - } - destPulledContainer->add(source.get()); - } - } - } - else if ((source->isContainer() && dest->isContainer() && - strcmp(static_cast(source.get())->elementTypeName(), - static_cast(dest)->elementTypeName()) == 0) || - (!source->isContainer() && !dest->isContainer() && strcmp(source->typeName(), dest->typeName()) == 0)){ - result = true; - if (!onlyCheck){ - if (dest->isPointer() && !source->isPointer()){ - PropertyRowPointer* d = static_cast(dest); - SharedPtr newSourceRoot = static_cast(d->clone(model->constStrings()).get()); - source->swapChildren(newSourceRoot, model); - source = newSourceRoot; - } - const char* name = dest->name(); - const char* nameAlt = dest->label(); - source->setName(name); - source->setLabel(nameAlt); - if (dest->parent()) - dest->parent()->replaceAndPreserveState(dest, source, model); - else{ - dest->swapChildren(source, model); - source->clear(); - } - source->setLabelChanged(); - } - } - else if (dest->isContainer()){ - if (model){ - PropertyRowContainer* container = static_cast(dest); - PropertyRow* elementRow = model->defaultType(container->elementTypeName()); - YASLI_ESCAPE(elementRow, return false); - if (strcmp(elementRow->typeName(), source->typeName()) == 0){ - result = true; - if (!onlyCheck){ - PropertyRow* dest = elementRow; - if (dest->isPointer() && !source->isPointer()){ - PropertyRowPointer* d = static_cast(dest); - SharedPtr newSourceRoot = static_cast(d->clone(model->constStrings()).get()); - source->swapChildren(newSourceRoot, model); - source = newSourceRoot; - } - - container->add(source.get()); - } - } - container->setLabelChanged(); - } - } - - return result; -} - -static bool propertyRowFromMimeData(SharedPtr& row, const QMimeData* mimeData, ConstStringList* constStrings) -{ - PropertyRow::setConstStrings(constStrings); - QStringList formats = mimeData->formats(); - QByteArray array = mimeData->data("binary/crypropertytree"); - if (array.isEmpty()) - return 0; - Serialization::BinIArchive ia; - if (!ia.open(array.data(), array.size())) - return 0; - - if (!ia(row, "row", "Row")) - return false; - - PropertyRow::setConstStrings(0); - return true; - -} - -bool propertyRowFromClipboard(SharedPtr& row, ConstStringList* constStrings) -{ - const QMimeData* mime = QApplication::clipboard()->mimeData(); - if (!mime) - return false; - return propertyRowFromMimeData(row, mime, constStrings); -} - -void PropertyTreeMenuHandler::onMenuCopy() -{ - QMimeData* mime = propertyRowToMimeData(row, tree->model()->constStrings()); - if (mime) - QApplication::clipboard()->setMimeData(mime); -} - -void PropertyTreeMenuHandler::onMenuPaste() -{ - if (!tree->canBePasted(row)) - return; - PropertyRow* parent = row->parent(); - - tree->model()->rowAboutToBeChanged(row); - - SharedPtr source; - if (!propertyRowFromClipboard(source, tree->model()->constStrings())) - return; - - if (!smartPaste(row, source, tree->model(), false)) - return; - - tree->model()->rowChanged(parent ? parent : tree->model()->root()); -} - -class FilterEntry : public QLineEdit -{ -public: - FilterEntry(QPropertyTree* tree) - : QLineEdit(tree) - , tree_(tree) - { - } -protected: - - void keyPressEvent(QKeyEvent * ev) - { - if (ev->key() == Qt::Key_Escape || ev->key() == Qt::Key_Return) - { - ev->accept(); - tree_->setFocus(); - tree_->keyPressEvent(ev); - } - - if (ev->key() == Qt::Key_Backspace && text().isEmpty()) - { - tree_->setFilterMode(false); - } - QLineEdit::keyPressEvent(ev); - } -private: - QPropertyTree* tree_; -}; - -// --------------------------------------------------------------------------- - -DragWindow::DragWindow(QPropertyTree* tree) - : tree_(tree) - , offset_(0, 0) -{ - QWidget::setWindowFlags(Qt::ToolTip); - QWidget::setWindowOpacity(192.0f / 256.0f); -} - -void DragWindow::set(QPropertyTree* tree, PropertyRow* row, const QRect& rowRect) -{ - QRect rect = tree->rect(); - rect.setTopLeft(tree->mapToGlobal(rect.topLeft())); - - offset_ = rect.topLeft(); - - row_ = row; - rect_ = rowRect; -} - -void DragWindow::setWindowPos([[maybe_unused]] bool visible) -{ - QWidget::move(rect_.left() + offset_.x() - 3, rect_.top() + offset_.y() - 3 + tree_->area_.top()); - QWidget::resize(rect_.width() + 5, rect_.height() + 5); -} - -void DragWindow::show() -{ - setWindowPos(true); - QWidget::show(); -} - -void DragWindow::move(int deltaX, int deltaY) -{ - offset_ += QPoint(deltaX, deltaY); - setWindowPos(isVisible()); -} - -void DragWindow::hide() -{ - setWindowPos(false); - QWidget::hide(); -} - -struct DrawRowVisitor -{ - DrawRowVisitor(QPainter& painter) : painter_(painter) {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, int index) - { - if (row->pulledUp() && row->visible(tree)) { - row->drawRow(painter_, tree, index, true); - row->drawRow(painter_, tree, index, false); - } - - return SCAN_CHILDREN_SIBLINGS; - } - -protected: - QPainter& painter_; -}; - -void DragWindow::drawRow(QPainter& p) -{ - QRect entireRowRect(0, 0, rect_.width() + 4, rect_.height() + 4); - - p.setBrush(tree_->palette().button()); - p.setPen(QPen(tree_->palette().color(QPalette::WindowText))); - p.drawRect(entireRowRect); - - QPoint leftTop = row_->rect().topLeft(); - int offsetX = aznumeric_cast(-leftTop.x() - tree_->treeStyle().firstLevelIndent * tree_->_defaultRowHeight() + 3); - int offsetY = -leftTop.y() + 3; - p.translate(offsetX, offsetY); - int rowIndex = 0; - if (row_->parent()) - rowIndex = row_->parent()->childIndex(row_); - row_->drawRow(p, tree_, 0, true); - row_->drawRow(p, tree_, 0, false); - DrawRowVisitor visitor(p); - row_->scanChildren(visitor, tree_); - p.translate(-offsetX, -offsetY); -} - -void DragWindow::paintEvent([[maybe_unused]] QPaintEvent* ev) -{ - QPainter p(this); - - drawRow(p); -} - -// --------------------------------------------------------------------------- - -class QPropertyTree::DragController -{ -public: - DragController(QPropertyTree* tree) - : tree_(tree) - , captured_(false) - , dragging_(false) - , before_(false) - , row_(0) - , clickedRow_(0) - , window_(tree) - , hoveredRow_(0) - , destinationRow_(0) - { - } - - void beginDrag(PropertyRow* clickedRow, PropertyRow* draggedRow, QPoint pt) - { - row_ = draggedRow; - clickedRow_ = clickedRow; - startPoint_ = pt; - lastPoint_ = pt; - captured_ = true; - dragging_ = false; - } - - bool dragOn(QPoint screenPoint) - { - if (dragging_) - window_.move(screenPoint.x() - lastPoint_.x(), screenPoint.y() - lastPoint_.y()); - - bool needCapture = false; - if (!dragging_ && (startPoint_ - screenPoint).manhattanLength() >= 5) - if (row_->canBeDragged()){ - needCapture = true; - QRect rect = row_->rect(); - rect = QRect(rect.topLeft() - tree_->offset_ + QPoint(aznumeric_cast(tree_->treeStyle().firstLevelIndent * tree_->_defaultRowHeight()), 0), - rect.bottomRight() - tree_->offset_); - - window_.set(tree_, row_, rect); - window_.move(screenPoint.x() - startPoint_.x(), screenPoint.y() - startPoint_.y()); - window_.show(); - dragging_ = true; - } - - if (dragging_){ - QPoint point = tree_->mapFromGlobal(screenPoint); - trackRow(point); - } - lastPoint_ = screenPoint; - return needCapture; - } - - void interrupt() - { - captured_ = false; - dragging_ = false; - row_ = 0; - window_.hide(); - } - - void trackRow(QPoint pt) - { - hoveredRow_ = 0; - destinationRow_ = 0; - - QPoint point = pt; - PropertyRow* row = tree_->rowByPoint(point); - if (!row || !row_) - return; - - row = row->nonPulledParent(); - if (!row->parent() || row->isChildOf(row_) || row == row_) - return; - - float pos = (point.y() - row->rect().top()) / float(row->rect().height()); - if (row_->canBeDroppedOn(row->parent(), row, tree_)){ - if (pos < 0.25f){ - destinationRow_ = row->parent(); - hoveredRow_ = row; - before_ = true; - return; - } - if (pos > 0.75f){ - destinationRow_ = row->parent(); - hoveredRow_ = row; - before_ = false; - return; - } - } - if (row_->canBeDroppedOn(row, 0, tree_)) - hoveredRow_ = destinationRow_ = row; - } - - void drawUnder(QPainter& painter) - { - if (dragging_ && destinationRow_ == hoveredRow_ && hoveredRow_){ - QRect rowRect = hoveredRow_->rect(); - rowRect.setLeft(aznumeric_cast(rowRect.left() + tree_->treeStyle().firstLevelIndent * tree_->_defaultRowHeight())); - QBrush brush(true ? tree_->palette().highlight() : tree_->palette().shadow()); - QColor brushColor = brush.color(); - QColor borderColor(brushColor.alpha() / 4, brushColor.red(), brushColor.green(), brushColor.blue()); - fillRoundRectangle(painter, brush, rowRect, borderColor, 6); - } - } - - void drawOver(QPainter& painter) - { - if (!dragging_) - return; - - QRect rowRect = row_->rect(); - - if (destinationRow_ != hoveredRow_ && hoveredRow_){ - const int tickSize = 4; - QRect hoveredRect = hoveredRow_->rect(); - hoveredRect.setLeft(aznumeric_cast(hoveredRect.left() + tree_->treeStyle().firstLevelIndent * tree_->_defaultRowHeight())); - - if (!before_){ // previous - QRect rect(hoveredRect.left() - 1, hoveredRect.bottom() - 1, hoveredRect.width(), 2); - QRect rectLeft(hoveredRect.left() - 1, hoveredRect.bottom() - tickSize, 2, tickSize * 2); - QRect rectRight(hoveredRect.right() - 1, hoveredRect.bottom() - tickSize, 2, tickSize * 2); - painter.fillRect(rect, tree_->palette().highlight()); - painter.fillRect(rectLeft, tree_->palette().highlight()); - painter.fillRect(rectRight, tree_->palette().highlight()); - } - else{ // next - QRect rect(hoveredRect.left() - 1, hoveredRect.top() - 1, hoveredRect.width(), 2); - QRect rectLeft(hoveredRect.left() - 1, hoveredRect.top() - tickSize, 2, tickSize * 2); - QRect rectRight(hoveredRect.right() - 1, hoveredRect.top() - tickSize, 2, tickSize * 2); - painter.fillRect(rect, tree_->palette().highlight()); - painter.fillRect(rectLeft, tree_->palette().highlight()); - painter.fillRect(rectRight, tree_->palette().highlight()); - } - } - } - - bool drop([[maybe_unused]] QPoint screenPoint) - { - bool rowLayoutChanged = false; - if (row_ && hoveredRow_){ - YASLI_ASSERT(destinationRow_); - clickedRow_->setSelected(false); - row_->dropInto(destinationRow_, destinationRow_ == hoveredRow_ ? 0 : hoveredRow_, tree_, before_); - rowLayoutChanged = true; - } - - captured_ = false; - dragging_ = false; - row_ = 0; - window_.hide(); - hoveredRow_ = 0; - destinationRow_ = 0; - return rowLayoutChanged; - } - - bool captured() const{ return captured_; } - bool dragging() const{ return dragging_; } - PropertyRow* draggedRow() { return row_; } -protected: - DragWindow window_; - QPropertyTree* tree_; - PropertyRow* row_; - PropertyRow* clickedRow_; - PropertyRow* hoveredRow_; - PropertyRow* destinationRow_; - QPoint startPoint_; - QPoint lastPoint_; - bool captured_; - bool dragging_; - bool before_; -}; - -// --------------------------------------------------------------------------- - -AZ_PUSH_DISABLE_WARNING(4335, "-Wunknown-warning-option") -QPropertyTree::QPropertyTree(QWidget* parent) - : QWidget(parent) - , sizeHint_(180, 180) - , model_(0) - , cursorX_(0) - , attachedPropertyTree_(0) - , autoHideAttachedPropertyTree_(false) - , autoRevert_(true) - , dragController_(new DragController(this)) - , leftBorder_(0) - , rightBorder_(0) - , filterMode_(false) - - , applyTime_(0) - , revertTime_(0) - , updateHeightsTime_(0) - , paintTime_(0) - , pressPoint_(-1, -1) - , pressDelta_(0, 0) - , pointerMovedSincePress_(false) - , lastStillPosition_(-1, -1) - , pressedRow_(0) - , capturedRow_(0) - , iconCache_(new IconXPMCache()) - , dragCheckMode_(false) - , dragCheckValue_(false) - , archiveContext_(0) - , outlineMode_(false) - , sizeToContent_(false) - , hideSelection_(false) - , zoomLevel_(10) - , validatorBlock_(new ValidatorBlock) - , style_(new QPropertyTreeStyle()) - - , aggregateMouseEvents_(false) - , aggregatedMouseEventCount_(0) -{ - setFocusPolicy(Qt::WheelFocus); - setMouseTracking(true); // need to receive mouseMoveEvent to update mouse cursor and tooltip - - scrollBar_ = new QScrollBar(Qt::Vertical, this); - connect(scrollBar_, SIGNAL(valueChanged(int)), this, SLOT(onScroll(int))); - - model_.reset(new PropertyTreeModel()); - model_->setExpandLevels(config_.expandLevels); - model_->setUndoEnabled(config_.undoEnabled); - model_->setFullUndo(config_.fullUndo); - - connect(model_.data(), SIGNAL(signalUpdated(const PropertyRows&, bool)), this, SLOT(onModelUpdated(const PropertyRows&, bool))); - connect(model_.data(), SIGNAL(signalPushUndo(PropertyTreeOperator*, bool*)), this, SLOT(onModelPushUndo(PropertyTreeOperator*, bool*))); - connect(model_.data(), SIGNAL(signalPushRedo(PropertyTreeOperator*, bool*)), this, SLOT(onModelPushRedo(PropertyTreeOperator*, bool*))); - //model_->signalPushUndo().connect(this, &QPropertyTree::onModelPushUndo); - - filterEntry_.reset(new FilterEntry(this)); - QObject::connect(filterEntry_.data(), SIGNAL(textChanged(const QString&)), this, SLOT(onFilterChanged(const QString&))); - filterEntry_->hide(); - - mouseStillTimer_ = new QTimer(this); - mouseStillTimer_->setSingleShot(true); - connect(mouseStillTimer_, SIGNAL(timeout()), this, SLOT(onMouseStillTimeout())); - - boldFont_.setBold(true); - backgroundColor_ = palette().color(QPalette::Window); -} -AZ_POP_DISABLE_WARNING - -QPropertyTree::~QPropertyTree() -{ - clearMenuHandlers(); -} - -bool QPropertyTree::onRowKeyDown(PropertyRow* row, const QKeyEvent* ev) -{ - PropertyTreeMenuHandler handler; - handler.row = row; - handler.tree = this; - - if (row->onKeyDown(this, ev)) - return true; - if (row->pulledContainer() && static_cast(row->pulledContainer())->onKeyDownContainer(this, ev)) - return true; - - // NOTE: If you add a new key here, you also have to check for it in rowProcessesKey - - switch (ev->key()){ - case Qt::Key_C: - if (!row->userNonCopyable() && ev->modifiers() == Qt::CTRL) - handler.onMenuCopy(); - return true; - case Qt::Key_V: - if (!row->userNonCopyable() && ev->modifiers() == Qt::CTRL) - handler.onMenuPaste(); - return true; - case Qt::Key_Z: - if (config_.undoEnabled) - { - if (ev->modifiers() == (Qt::SHIFT | Qt::CTRL)) - { - if (model()->canRedo()) - { - handler.onMenuRedo(); - } - return true; - } - else if (ev->modifiers() == Qt::CTRL) - { - if (model()->canUndo()) - { - handler.onMenuUndo(); - } - return true; - } - } - else - { - if (ev->modifiers() == (Qt::SHIFT | Qt::CTRL)) - { - emit signalRedo(); - } - else if (ev->modifiers() == Qt::CTRL) - { - emit signalUndo(); - } - - return true; - } - break; - case Qt::Key_Y: - if (!config_.undoEnabled) - { - if (model()->canRedo()) - { - handler.onMenuRedo(); - } - } - else - { - if (ev->modifiers() == Qt::CTRL) - { - emit signalRedo(); - } - } - return true; - break; - - case Qt::Key_F2: - if (ev->modifiers() == Qt::NoModifier) { - if (selectedRow()) { - PropertyActivationEvent act; - act.tree = this; - act.force = true; - act.reason = PropertyActivationEvent::REASON_KEYBOARD; - selectedRow()->onActivate(act); - } - } - break; - case Qt::Key_Menu: - { - if (ev->modifiers() == Qt::NoModifier) { - QMenu menu(this); - - if (onContextMenu(row, menu)){ - QRect rect(row->rect()); - QPoint pt = _toScreen(QPoint(rect.left() + rect.height(), rect.bottom())); - menu.exec(pt); - } - return true; - } - break; - } - } - - PropertyRow* focusedRow = model()->focusedRow(); - if (!focusedRow) - return false; - PropertyRow* parentRow = focusedRow->nonPulledParent(); - int x = parentRow->horizontalIndex(this, focusedRow); - int y = model()->root()->verticalIndex(this, parentRow); - PropertyRow* selectedRow = 0; - switch (ev->key()){ - case Qt::Key_Up: - if (filterMode_ && y == 0) { - setFilterMode(true); - } - else { - selectedRow = model()->root()->rowByVerticalIndex(this, --y); - if (selectedRow) - selectedRow = selectedRow->rowByHorizontalIndex(this, cursorX_); - } - break; - case Qt::Key_Down: - if (filterMode_ && filterEntry_->hasFocus()) { - setFocus(); - } - else { - selectedRow = model()->root()->rowByVerticalIndex(this, ++y); - if (selectedRow) - selectedRow = selectedRow->rowByHorizontalIndex(this, cursorX_); - } - break; - case Qt::Key_Left: - selectedRow = parentRow->rowByHorizontalIndex(this, cursorX_ = --x); - if (selectedRow == focusedRow && parentRow->canBeToggled(this) && parentRow->expanded()){ - expandRow(parentRow, false); - selectedRow = model()->focusedRow(); - } - break; - case Qt::Key_Right: - selectedRow = parentRow->rowByHorizontalIndex(this, cursorX_ = ++x); - if (selectedRow == focusedRow && parentRow->canBeToggled(this) && !parentRow->expanded()){ - expandRow(parentRow, true); - selectedRow = model()->focusedRow(); - } - break; - case Qt::Key_Home: - if (ev->modifiers() == Qt::CTRL) { - selectedRow = parentRow->rowByHorizontalIndex(this, cursorX_ = INT_MIN); - } - else { - selectedRow = model()->root()->rowByVerticalIndex(this, 0); - if (selectedRow) - selectedRow = selectedRow->rowByHorizontalIndex(this, cursorX_); - } - break; - case Qt::Key_End: - if (ev->modifiers() == Qt::CTRL) { - selectedRow = parentRow->rowByHorizontalIndex(this, cursorX_ = INT_MAX); - } - else { - selectedRow = model()->root()->rowByVerticalIndex(this, INT_MAX); - if (selectedRow) - selectedRow = selectedRow->rowByHorizontalIndex(this, cursorX_); - } - break; - case Qt::Key_Space: - if (config_.filterWhenType) - break; - case Qt::Key_Return: - if (focusedRow->canBeToggled(this)) - expandRow(focusedRow, !focusedRow->expanded()); - else { - PropertyActivationEvent e; - e.tree = this; - e.reason = e.REASON_KEYBOARD; - e.force = false; - focusedRow->onActivate(e); - } - break; - } - if (selectedRow){ - onRowSelected(std::vector(1, selectedRow), false, false); - return true; - } - return false; -} - -bool QPropertyTree::rowProcessesKey(PropertyRow* row, const QKeyEvent* ev) -{ - if (row->processesKey(this, ev)) - { - return true; - } - - if (row->pulledContainer() && static_cast(row->pulledContainer())->processesKeyContainer(this, ev)) - { - return true; - } - - int modifiedKey = ev->key() | ev->modifiers(); - - switch (modifiedKey) - { - case (Qt::CTRL | Qt::Key_Z): - case (Qt::CTRL | Qt::SHIFT | Qt::Key_Z) : - case Qt::Key_Y: - case (Qt::CTRL | Qt::Key_V): - case (Qt::CTRL | Qt::Key_C): - case (Qt::CTRL | Qt::Key_F): - case Qt::Key_Menu: - case Qt::Key_F2: - return true; - break; - - default: - break; - } - - switch (ev->key()) - { - case Qt::Key_Up: - case Qt::Key_Down: - case Qt::Key_Left: - case Qt::Key_Right: - case Qt::Key_Home: - case Qt::Key_End: - case Qt::Key_Return: - return true; - break; - - default: - break; - } - - return false; -} - -struct FirstIssueVisitor -{ - ValidatorEntryType entryType_; - PropertyRow* startRow_; - PropertyRow* result; - - FirstIssueVisitor(ValidatorEntryType type, PropertyRow* startRow) - : entryType_(type) - , startRow_(startRow) - , result() - { - } - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, int) - { - if ((row->pulledUp() || row->pulledBefore()) && row->nonPulledParent() == startRow_) - return SCAN_SIBLINGS; - if (row->validatorCount()) { - if (const ValidatorEntry* validatorEntries = tree->_validatorBlock()->GetEntry(row->validatorIndex(), row->validatorCount())) { - for (int i = 0; i < row->validatorCount(); ++i) { - const ValidatorEntry* validatorEntry = validatorEntries + i; - if (validatorEntry->type == entryType_) { - result = row; - return SCAN_FINISHED; - } - } - } - } - return SCAN_CHILDREN_SIBLINGS; - } -}; - -void QPropertyTree::jumpToNextHiddenValidatorIssue(bool isError, PropertyRow* start) -{ - FirstIssueVisitor op(isError ? VALIDATOR_ENTRY_ERROR : VALIDATOR_ENTRY_WARNING, start); - start->scanChildren(op, this); - - PropertyRow* row = op.result; - - vector parents; - while (row && row->parent()) { - parents.push_back(row); - row = row->parent(); - } - for (int i = (int)parents.size() - 1; i >= 0; --i) { - if (!parents[i]->visible(this)) - break; - row = parents[i]; - } - if (row) - setSelectedRow(row); - - updateValidatorIcons(); - updateHeights(); -} - -static void rowsInBetween(vector* rows, PropertyRow* a, PropertyRow* b) -{ - if (!a) - return; - if (!b) - return; - vector pathA; - PropertyRow* rootA = a; - while (rootA->parent()) { - pathA.push_back(rootA); - rootA = rootA->parent(); - } - - vector pathB; - PropertyRow* rootB = b; - while (rootB->parent()) { - pathB.push_back(rootB); - rootB = rootB->parent(); - } - - if (rootA != rootB) - return; - - const PropertyRow* commonParent = rootA; - int maxDepth = min((int)pathA.size(), (int)pathB.size()); - for (int i = 0; i < maxDepth; ++i) { - PropertyRow* parentA = pathA[(int)pathA.size() - 1 - i]; - PropertyRow* parentB = pathB[(int)pathB.size() - 1 - i]; - if (parentA != parentB) { - int indexA = commonParent->childIndex(parentA); - int indexB = commonParent->childIndex(parentB); - int minIndex = min(indexA, indexB); - int maxIndex = max(indexA, indexB); - for (int j = minIndex; j <= maxIndex; ++j) - rows->push_back((PropertyRow*)commonParent->childByIndex(j)); - return; - } - commonParent = parentA; - } -} - -bool QPropertyTree::onRowLMBDown(PropertyRow* row, [[maybe_unused]] const QRect& rowRect, QPoint point, bool controlPressed, bool shiftPressed) -{ - pressPoint_ = point; - pressDelta_ = QPoint(0, 0); - pointerMovedSincePress_ = false; - row = model()->root()->hit(this, point); - if (row){ - if (!row->isRoot()) { - if (row->plusRect(this).contains(point) && toggleRow(row)) - return true; - if (row->validatorWarningIconRect(this).contains(point)) { - jumpToNextHiddenValidatorIssue(false, row); - return true; - } - if (row->validatorErrorIconRect(this).contains(point)) { - jumpToNextHiddenValidatorIssue(true, row); - return true; - } - } - - PropertyRow* rowToSelect = row; - while (rowToSelect && !rowToSelect->isSelectable()) - rowToSelect = rowToSelect->parent(); - - if (rowToSelect) { - if (!shiftPressed || !multiSelectable()) { - onRowSelected(std::vector(1, rowToSelect), multiSelectable() && controlPressed, true); - lastSelectedRow_ = rowToSelect; - } - else { - vector rowsToSelect; - - rowsInBetween(&rowsToSelect, lastSelectedRow_, rowToSelect); - onRowSelected(rowsToSelect, false, true); - } - } - } - - PropertyTreeModel::UpdateLock lock = model()->lockUpdate(); - row = model()->root()->hit(this, point); - if (row && !row->isRoot()){ - bool changed = false; - if (row->widgetRect(this).contains(point)) { - DragCheckBegin dragCheck = row->onMouseDragCheckBegin(); - if (dragCheck != DRAG_CHECK_IGNORE) { - dragCheckValue_ = dragCheck == DRAG_CHECK_SET; - dragCheckMode_ = true; - changed = row->onMouseDragCheck(this, dragCheckValue_); - } - } - - if (!dragCheckMode_) { - bool capture = row->onMouseDown(this, point, changed); - if (!changed){ - if (capture) - return true; - else if (row->widgetRect(this).contains(point)){ - if (row->widgetPlacement() != PropertyRow::WIDGET_ICON) - interruptDrag(); - PropertyActivationEvent e; - e.force = false; - e.tree = this; - e.clickPoint = point; - row->onActivate(e); - return false; - } - } - } - } - return false; -} - -void QPropertyTree::onRowLMBUp(PropertyRow* row, [[maybe_unused]] const QRect& rowRect, QPoint point) -{ - onMouseStill(point); - row->onMouseUp(this, point); - - if (!pointerMovedSincePress_ && (pressPoint_ - point).manhattanLength() < 1 && row->widgetRect(this).contains(point)) { - PropertyActivationEvent e; - e.tree = this; - e.clickPoint = point; - e.reason = e.REASON_RELEASE; - row->onActivate(e); - } -} - -void QPropertyTree::onRowRMBDown(PropertyRow* row, [[maybe_unused]] const QRect& rowRect, QPoint point) -{ - SharedPtr handle = row; - PropertyRow* menuRow = 0; - - if (row->isSelectable()){ - menuRow = row; - } - else{ - if (row->parent() && row->parent()->isSelectable()) - menuRow = row->parent(); - } - - if (menuRow) { - onRowSelected(std::vector(1, menuRow), false, true); - QMenu menu(this); - clearMenuHandlers(); - if (onContextMenu(menuRow, menu)) - menu.exec(point); - } -} - -void QPropertyTree::expandParents(PropertyRow* row) -{ - bool hasChanges = false; - typedef std::vector Parents; - Parents parents; - PropertyRow* p = row->nonPulledParent()->parent(); - while (p){ - parents.push_back(p); - p = p->parent(); - } - Parents::iterator it; - for (it = parents.begin(); it != parents.end(); ++it) { - PropertyRow* row = *it; - row->_setExpanded(true); - hasChanges = true; - } - if (hasChanges) { - updateValidatorIcons(); - updateHeights(); - } -} - - -void QPropertyTree::expandAll(PropertyRow* root) -{ - if (!root){ - root = model()->root(); - for (PropertyRows::iterator it = root->begin(); it != root->end(); ++it){ - PropertyRow* row = *it; - row->setExpandedRecursive(this, true); - } - root->setLayoutChanged(); - } - else - root->setExpandedRecursive(this, true); - - for (PropertyRow* r = root; r != 0; r = r->parent()) - r->setLayoutChanged(); - - updateHeights(); -} - -void QPropertyTree::collapseAll(PropertyRow* root) -{ - if (!root){ - root = model()->root(); - - for (PropertyRows::iterator it = root->begin(); it != root->end(); ++it){ - PropertyRow* row = *it; - row->setExpandedRecursive(this, false); - } - } - else{ - root->setExpandedRecursive(this, false); - PropertyRow* row = model()->focusedRow(); - while (row){ - if (root == row){ - model()->selectRow(row, true); - break; - } - row = row->parent(); - } - } - - for (PropertyRow* r = root; r != 0; r = r->parent()) - r->setLayoutChanged(); - - updateHeights(); -} - - -void QPropertyTree::expandRow(PropertyRow* row, bool expanded, bool updateHeights) -{ - bool hasChanges = false; - if (row->expanded() != expanded) { - row->_setExpanded(expanded); - hasChanges = true; - } - - for (PropertyRow* r = row; r != 0; r = r->parent()) - r->setLayoutChanged(); - - if (!row->expanded()){ - PropertyRow* f = model()->focusedRow(); - while (f){ - if (row == f){ - model()->selectRow(row, true); - break; - } - f = f->parent(); - } - } - - if (hasChanges) - updateValidatorIcons(); - if (hasChanges && updateHeights) - this->updateHeights(); -} - -void QPropertyTree::interruptDrag() -{ - dragController_->interrupt(); -} - -void QPropertyTree::updateHeights(bool recalculateTextSize) -{ - QFontMetrics fm(font()); - defaultRowHeight_ = max(16, int(fm.lineSpacing() * 1.666f)); // to fit at least 16x16 icons - - QElapsedTimer timer; - timer.start(); - - model()->root()->updateLabel(this, 0, false); - - QRect widgetRect = this->rect(); - - int scrollBarW = 16; - int lb = 1; - int rb = widgetRect.right() - lb - scrollBarW - 2; - int availableWidth = widgetRect.width() - 4 - scrollBarW; - bool force = recalculateTextSize || lb != leftBorder_ || rb != rightBorder_; - leftBorder_ = lb; - rightBorder_ = rb; - model()->root()->calculateMinimalSize(this, leftBorder_, availableWidth, force, 0, 0, 0); - - updateValidatorIcons(); - - int totalHeight = 0; - model()->root()->adjustVerticalPosition(this, totalHeight); - totalHeight += 4; - QPoint oldSize = size_; - size_.setY(totalHeight); - - updateScrollBar(); - - area_.setLeft(widgetRect.left() + 2); - area_.setRight(widgetRect.right() - 2 - scrollBarW); - area_.setTop(widgetRect.top() + 2); - area_.setBottom(widgetRect.bottom() - 2); - size_.setX(area_.width()); - - int filterAreaHeight = 0; - if (filterMode_) - { - filterAreaHeight = filterEntry_ ? filterEntry_->height() : 0; - area_.setTop(area_.top() + filterAreaHeight + 2 + 2); - } - - _arrangeChildren(); - - int contentHeight = totalHeight + filterAreaHeight + 4; - if (sizeToContent_) - { - setMaximumHeight(contentHeight); - setMinimumHeight(contentHeight); - } - else - { - setMaximumHeight(QWIDGETSIZE_MAX); - setMinimumHeight(0); - } - - update(); - updateHeightsTime_ = aznumeric_cast(timer.elapsed()); - - QSize contentSize = QSize(area_.width(), contentHeight); - if (contentSize_.height() != contentSize.height()) - { - contentSize_ = contentSize; - signalSizeChanged(); - } - else - { - contentSize_ = contentSize; - } -} - -void QPropertyTree::setSizeToContent(bool sizeToContent) -{ - if (sizeToContent != sizeToContent_) - { - sizeToContent_ = sizeToContent; - updateHeights(); - } -} - - -bool QPropertyTree::updateScrollBar() -{ - int pageSize = rect().height(); - offset_.setX(max(0, min(offset_.x(), max(0, size_.x() - area_.right() - 1)))); - offset_.setY(max(0, min(offset_.y(), max(0, size_.y() - pageSize)))); - - if (pageSize < size_.y()) - { - scrollBar_->setRange(0, size_.y() - pageSize); - scrollBar_->setSliderPosition(offset_.y()); - scrollBar_->setPageStep(pageSize); - scrollBar_->show(); - scrollBar_->move(rect().right() - scrollBar_->width(), 0); - scrollBar_->resize(scrollBar_->width(), height()); - return true; - } - else - { - scrollBar_->hide(); - return false; - } -} - -QPoint QPropertyTree::treeSize() const -{ - return size_ + (compact() ? QPoint(0, 0) : QPoint(8, 8)); -} - -void QPropertyTree::onScroll([[maybe_unused]] int pos) -{ - offset_.setY(scrollBar_->sliderPosition()); - _arrangeChildren(); - repaint(); -} - -void QPropertyTree::Serialize(IArchive& ar) -{ - model()->Serialize(ar, this); - - if (ar.IsInput()){ - ensureVisible(model()->focusedRow()); - updateAttachedPropertyTree(false); - updateHeights(); - signalSelected(); - } -} - -void QPropertyTree::ensureVisible(PropertyRow* row, bool update, bool considerChildren) -{ - if (row == 0) - return; - if (row->isRoot()) - return; - - expandParents(row); - - QRect rect = considerChildren ? row->rectIncludingChildren(this) : row->rect(); - if (rect.bottom() > area_.bottom() + offset_.y()){ - offset_.setY(max(0, rect.bottom() - area_.bottom())); - } - if (rect.top() < area_.top() + offset_.y()){ - offset_.setY(max(0, rect.top() - area_.top())); - } - updateScrollBar(); - if (update) - this->update(); -} - -void QPropertyTree::onRowSelected(const std::vector& rows, bool addSelection, bool adjustCursorPos) -{ - for (size_t i = 0; i < rows.size(); ++i) { - PropertyRow* row = rows[i]; - if (!row->isRoot()) { - bool addRowToSelection = !(addSelection && row->selected() && model()->selection().size() > 1) || i > 0; - bool exclusiveSelection = !addSelection && i == 0; - model()->selectRow(row, addRowToSelection, exclusiveSelection); - } - } - if (!rows.empty()) { - ensureVisible(rows.back(), true, false); - if (adjustCursorPos) - cursorX_ = rows.back()->nonPulledParent()->horizontalIndex(this, rows.back()); - } - updateAttachedPropertyTree(false); - signalSelected(); -} - -bool QPropertyTree::attach(const Serialization::SStructs& serializers) -{ - bool changed = false; - if (attached_.size() != serializers.size()) - changed = true; - else { - for (size_t i = 0; i < serializers.size(); ++i) { - if (attached_[i].serializer() != serializers[i]) { - changed = true; - break; - } - } - } - - // We can't perform plain copying here, as it was before: - // attached_ = serializers; - // ...as move forwarder calls copying constructor with non-const argument - // which invokes second templated constructor of Serializer, which is not what we need. - if (changed) { - attached_.assign(serializers.begin(), serializers.end()); - model_->clearUndo(); - } - - revertNoninterrupting(); - - return changed; -} - -void QPropertyTree::attach(const Serialization::SStruct& serializer) -{ - if (attached_.size() != 1 || attached_[0].serializer() != serializer) { - attached_.clear(); - attached_.push_back(Serialization::Object(serializer)); - model_->clearUndo(); - } - revert(); -} - -void QPropertyTree::attach(const Serialization::Object& object) -{ - attached_.clear(); - attached_.push_back(object); - - revert(); -} - -void QPropertyTree::detach() -{ - if (widget_) - widget_.reset(); - attached_.clear(); - model()->root()->clear(); - update(); -} - -int QPropertyTree::revertObjects(vector objectAddresses) -{ - int result = 0; - for (size_t i = 0; i < objectAddresses.size(); ++i) { - if (revertObject(objectAddresses[i])) - ++result; - } - return result; -} - -bool QPropertyTree::revertObject(void* objectAddress) -{ - PropertyRow* row = model()->root()->findByAddress(objectAddress); - if (row && row->isObject()) { - // TODO: - // revertObjectRow(row); - return true; - } - return false; -} - - -void QPropertyTree::revert() -{ - interruptDrag(); - widget_.reset(); - capturedRow_ = 0; - - if (!attached_.empty()) { - validatorBlock_->Clear(); - - QElapsedTimer timer; - timer.start(); - - PropertyOArchive oa(model_.data(), model_->root(), validatorBlock_.data()); - oa.SetOutlineMode(outlineMode_); - if (archiveContext_) - oa.SetInnerContext(archiveContext_); - oa.SetFilter(config_.filter); - - Objects::iterator it = attached_.begin(); - signalAboutToSerialize(oa); - (*it)(oa); - signalSerialized(oa); - - PropertyTreeModel model2; - if (it != attached_.end()) { - while (++it != attached_.end()){ - PropertyOArchive oa2(&model2, model2.root(), validatorBlock_.data()); - oa2.SetOutlineMode(outlineMode_); - Serialization::SContext treeContext(oa2, this); - if (archiveContext_) - oa2.SetInnerContext(archiveContext_); - oa2.SetFilter(config_.filter); - signalAboutToSerialize(oa2); - (*it)(oa2); - signalSerialized(oa2); - model_->root()->intersect(model2.root()); - } - } - revertTime_ = int(timer.elapsed()); - - if (attached_.size() != 1) - validatorBlock_->Clear(); - applyValidation(); - } - else - model_->clear(); - - if (filterMode_) { - if (model_->root()) - model_->root()->updateLabel(this, 0, false); - onFilterChanged(QString()); - } - else { - updateHeights(); - } - - update(); - updateAttachedPropertyTree(true); - - signalReverted(); -} - -struct ValidatorVisitor -{ - ValidatorVisitor(ValidatorBlock* validator) - : validator_(validator) - { - } - - ScanResult operator()(PropertyRow* row, [[maybe_unused]] QPropertyTree* tree, int) - { - const void* rowHandle = row->searchHandle(); - int index = 0; - int count = 0; - Serialization::TypeID typeID = row->typeId(); - if (validator_->FindHandleEntries(&index, &count, rowHandle, typeID)) - { - validator_->MarkAsUsed(index, count); - if (row->setValidatorEntry(index, count)) - row->setLabelChanged(); - } - else - { - if (row->setValidatorEntry(0, 0)) - row->setLabelChanged(); - } - - return SCAN_CHILDREN_SIBLINGS; - } - -protected: - ValidatorBlock* validator_; -}; - -void QPropertyTree::applyValidation() -{ - if (!validatorBlock_->IsEnabled()) - return; - - ValidatorVisitor visitor(validatorBlock_.data()); - model()->root()->scanChildren(visitor, this); - - int rootFirst = 0; - int rootCount = 0; - Serialization::TypeID typeID = model()->root()->typeId(); - // Gather all the items with unknown handle/type pair at root level. - validatorBlock_->MergeUnusedItemsWithRootItems(&rootFirst, &rootCount, model()->root()->searchHandle(), typeID); - model()->root()->setValidatorEntry(rootFirst, rootCount); - model()->root()->setLabelChanged(); -} - -void QPropertyTree::revertNoninterrupting() -{ - if (!capturedRow_) - revert(); -} - -void QPropertyTree::apply(bool continuousUpdate) -{ - QElapsedTimer timer; - timer.start(); - - if (!attached_.empty()) { - Objects::iterator it; - for (it = attached_.begin(); it != attached_.end(); ++it) { - PropertyIArchive ia(model_.data(), model_->root()); - Serialization::SContext treeContext(ia, this); - ia.SetFilter(config_.filter); - if (archiveContext_) - ia.SetInnerContext(archiveContext_); - signalAboutToSerialize(ia); - (*it)(ia); - signalSerialized(ia); - } - } - - if (!continuousUpdate) - signalChanged(); - else - signalContinuousChange(); - applyTime_ = aznumeric_cast(timer.elapsed()); -} - -void QPropertyTree::applyInplaceEditor() -{ - if (widget_) - widget_->commit(); -} - -bool QPropertyTree::spawnWidget(PropertyRow* row, bool ignoreReadOnly) -{ - if (!widget_ || widget_->row() != row || !widget_->actualWidget()->isVisible()){ - interruptDrag(); - setWidget(0); - PropertyRowWidget* newWidget = 0; - if ((ignoreReadOnly && row->userReadOnlyRecurse()) || !row->userReadOnly()) - newWidget = row->createWidget(this); - setWidget(newWidget); - return newWidget != 0; - } - return false; -} - -void QPropertyTree::addMenuHandler(PropertyRowMenuHandler* handler) -{ - menuHandlers_.push_back(handler); -} - -void QPropertyTree::clearMenuHandlers() -{ - for (size_t i = 0; i < menuHandlers_.size(); ++i) - { - PropertyRowMenuHandler* handler = menuHandlers_[i]; - delete handler; - } - menuHandlers_.clear(); -} - -static string quoteIfNeeded(const char* str) -{ - if (!str) - return string(); - if (strchr(str, ' ') != 0) { - string result; - result = "\""; - result += str; - result += "\""; - return result; - } - else { - return string(str); - } -} - -bool QPropertyTree::onContextMenu(PropertyRow* r, QMenu& menu) -{ - SharedPtr row(r); - PropertyTreeMenuHandler* handler = new PropertyTreeMenuHandler(); - addMenuHandler(handler); - handler->tree = this; - handler->row = row; - - PropertyRow::iterator it; - for (it = row->begin(); it != row->end(); ++it){ - PropertyRow* child = *it; - if (child->isContainer() && child->pulledUp()) - child->onContextMenu(menu, this); - } - row->onContextMenu(menu, this); - if (config_.undoEnabled){ - if (!menu.isEmpty()) - menu.addSeparator(); - QAction* undo = menu.addAction("Undo", handler, SLOT(onMenuUndo())); - undo->setEnabled(model()->canUndo()); - undo->setShortcut(QKeySequence("Ctrl+Z")); - - QAction* redo = menu.addAction("Redo", handler, SLOT(onMenuRedo())); - redo->setEnabled(model()->canRedo()); - redo->setShortcut(QKeySequence("Ctrl+Shift+Z")); - } - if (!menu.isEmpty()) - menu.addSeparator(); - - if (!row->userNonCopyable()){ - menu.addAction("Copy", handler, SLOT(onMenuCopy()), QKeySequence("Ctrl+C")); - - if(!row->userReadOnly()){ - QAction* paste = menu.addAction("Paste", handler, SLOT(onMenuPaste()), QKeySequence("Ctrl+V")); - paste->setEnabled(canBePasted(row)); - } - - menu.addSeparator(); - } - - menu.addAction("Filter...", handler, SLOT(onMenuFilter()), QKeySequence("Ctrl+F")); - QMenu* filter = menu.addMenu("Filter by"); - { - string nameFilter = "#"; - nameFilter += quoteIfNeeded(row->labelUndecorated()); - handler->filterName = nameFilter; - filter->addAction((string("Name:\t") + nameFilter).c_str(), handler, SLOT(onMenuFilterByName())); - - string valueFilter = "="; - valueFilter += quoteIfNeeded(row->valueAsString().c_str()); - handler->filterValue = valueFilter; - filter->addAction((string("Value:\t") + valueFilter).c_str(), handler, SLOT(onMenuFilterByValue())); - - string typeFilter = ":"; - typeFilter += quoteIfNeeded(row->typeNameForFilter(this)); - handler->filterType = typeFilter; - filter->addAction((string("Type:\t") + typeFilter).c_str(), handler, SLOT(onMenuFilterByType())); - } - -#if 0 - menu.addSeparator(); - menu.addAction(TRANSLATE("Decompose"), row).connect(this, &QPropertyTree::onRowMenuDecompose); -#endif - return true; -} - -void QPropertyTree::onRowMouseMove(PropertyRow* row, [[maybe_unused]] const QRect& rowRect, QPoint point) -{ - PropertyDragEvent e; - e.tree = this; - e.pos = point; - e.start = pressPoint_; - e.totalDelta = pressDelta_; - row->onMouseDrag(e); - update(); -} - - -bool QPropertyTree::canBePasted(PropertyRow* destination) -{ - SharedPtr source; - if (!propertyRowFromClipboard(source, model_->constStrings())) - return false; - - if (!smartPaste(destination, source, model(), true)) - return false; - return true; -} - -bool QPropertyTree::canBePasted(const char* destinationType) -{ - SharedPtr source; - if (!propertyRowFromClipboard(source, model()->constStrings())) - return false; - - bool result = strcmp(source->typeName(), destinationType) == 0; - return result; -} - -struct DecomposeProxy -{ - DecomposeProxy(SharedPtr& row) : row(row) {} - - void Serialize(IArchive& ar) - { - ar(row, "row", "Row"); - } - - SharedPtr& row; -}; - -void QPropertyTree::onRowMenuDecompose([[maybe_unused]] PropertyRow* row) -{ - // SharedPtr clonedRow = row->clone(); - // DecomposeProxy proxy(clonedRow); - // edit(SStruct(proxy), 0, IMMEDIATE_UPDATE, this); -} - -void QPropertyTree::onModelUpdated([[maybe_unused]] const PropertyRows& rows, bool needApply) -{ - if (widget_) - widget_.reset(); - - if (config_.immediateUpdate){ - if (needApply) - apply(false); - - if (autoRevert_) - revert(); - else { - updateHeights(); - updateAttachedPropertyTree(true); - if (!config_.immediateUpdate) - onSignalChanged(); - } - } - else { - update(); - } -} - -void QPropertyTree::onModelPushUndo([[maybe_unused]] PropertyTreeOperator* op, [[maybe_unused]] bool* handled) -{ - signalPushUndo(); -} - -void QPropertyTree::onModelPushRedo([[maybe_unused]] PropertyTreeOperator* op, [[maybe_unused]] bool* handled) -{ - signalPushRedo(); -} - -void QPropertyTree::setWidget(PropertyRowWidget* widget) -{ - if (widget_){ - widget_->setParent(0); - } - widget_.reset(); - model()->dismissUpdate(); - - if (widget) - { - QWidget* actualWidget = widget->actualWidget(); - if (actualWidget) - { - actualWidget->setParent(this); - actualWidget->setFocus(); - } - - widget_.reset(widget); - _arrangeChildren(); - - if (widget_) - { - widget_->showPopup(); - } - } -} - -bool QPropertyTree::hasFocusOrInplaceHasFocus() const -{ - if (hasFocus()) - return true; - - if (widget_ && widget_->actualWidget() && widget_->actualWidget()->hasFocus()) - return true; - - return false; -} - -void QPropertyTree::setFilterMode(bool inFilterMode) -{ - bool changed = filterMode_ != inFilterMode; - filterMode_ = inFilterMode; - - if (filterMode_) - { - filterEntry_->show(); - filterEntry_->setFocus(); - filterEntry_->selectAll(); - } - else - filterEntry_->hide(); - - if (changed) - { - onFilterChanged(QString()); - } -} - -void QPropertyTree::startFilter(const char* filter) -{ - setFilterMode(true); - filterEntry_->setText(filter); - onFilterChanged(filter); -} - -void QPropertyTree::_arrangeChildren() -{ - if (widget_){ - PropertyRow* row = widget_->row(); - if (row->visible(this)){ - QWidget* w = widget_->actualWidget(); - YASLI_ASSERT(w); - if (w){ - QRect rect = row->widgetRect(this); - rect = QRect(rect.topLeft() - offset_ + area_.topLeft(), - rect.bottomRight() - offset_ + area_.topLeft()); - w->move(rect.topLeft()); - w->resize(rect.size()); - if (!w->isVisible()){ - w->show(); - w->setFocus(); - } - } - else{ - //YASLI_ASSERT(w); - } - } - else{ - widget_.reset(); - } - } - - if (filterEntry_) { - QSize size = rect().size(); - const int padding = 2; - QRect pos(padding, padding, size.width() - padding * 2, filterEntry_->height()); - filterEntry_->move(pos.topLeft()); - filterEntry_->resize(pos.size() - QSize(scrollBar_ ? scrollBar_->width() : 0, 0)); - } -} - - - -void QPropertyTree::setExpandLevels(int levels) -{ - config_.expandLevels = levels; - model()->setExpandLevels(levels); -} - -PropertyRow* QPropertyTree::selectedRow() -{ - const PropertyTreeModel::Selection &sel = model()->selection(); - if (sel.empty()) - return 0; - return model()->rowFromPath(sel.front()); -} - -int QPropertyTree::selectedRowCount() const -{ - return (int)model()->selection().size(); -} - -PropertyRow* QPropertyTree::selectedRowByIndex(int index) -{ - std::vector result; - const PropertyTreeModel::Selection &sel = model()->selection(); - if (size_t(index) >= sel.size()) - return 0; - - return model()->rowFromPath(sel[index]); -} - -bool QPropertyTree::getSelectedObject(Serialization::Object* object) -{ - const PropertyTreeModel::Selection &sel = model()->selection(); - if (sel.empty()) - return 0; - PropertyRow* row = model()->rowFromPath(sel.front()); - while (row && !row->isObject()) - row = row->parent(); - if (!row) - return false; - - if (row->isObject()) { - PropertyRowObject* obj = static_cast(row); - *object = obj->object(); - return true; - } - else { - return false; - } -} - -QPoint QPropertyTree::_toScreen(QPoint point) const -{ - QPoint pt(point.x() - offset_.x() + area_.left(), - point.y() - offset_.y() + area_.top()); - - return mapToGlobal(pt); -} - -bool QPropertyTree::setSelectedRow(PropertyRow* row) -{ - TreeSelection sel; - if (row) - sel.push_back(model()->pathFromRow(row)); - if (model()->selection() != sel) { - model()->setSelection(sel); - if (row) - ensureVisible(row); - updateAttachedPropertyTree(false); - repaint(); - return true; - } - return false; -} - -bool QPropertyTree::selectByAddress(const void* addr, bool keepSelectionIfChildSelected) -{ - if (model()->root()) { - PropertyRow* row = model()->root()->findByAddress(addr); - - bool keepSelection = false; - if (keepSelectionIfChildSelected && row && !model()->selection().empty()) { - keepSelection = true; - TreeSelection::const_iterator it; - for (it = model()->selection().begin(); it != model()->selection().end(); ++it){ - PropertyRow* selectedRow = model()->rowFromPath(*it); - if (!selectedRow) - continue; - if (!selectedRow->isChildOf(row)){ - keepSelection = false; - break; - } - } - } - - if (!keepSelection) - return setSelectedRow(row); - } - return false; -} - -bool QPropertyTree::selectByAddresses(const void* const* addresses, size_t addressCount, bool keepSelectionIfChildSelected) -{ - bool result = false; - if (model()->root()) { - bool keepSelection = false; - vector rows; - for (size_t i = 0; i < addressCount; ++i) { - const void* addr = addresses[i]; - PropertyRow* row = model()->root()->findByAddress(addr); - - if (keepSelectionIfChildSelected && row && !model()->selection().empty()) { - keepSelection = true; - TreeSelection::const_iterator it; - for (it = model()->selection().begin(); it != model()->selection().end(); ++it){ - PropertyRow* selectedRow = model()->rowFromPath(*it); - if (!selectedRow) - continue; - if (!selectedRow->isChildOf(row)){ - keepSelection = false; - break; - } - } - } - - if (row) - rows.push_back(row); - } - - if (!keepSelection) { - TreeSelection sel; - for (size_t j = 0; j < rows.size(); ++j) { - PropertyRow* row = rows[j]; - if (row) - sel.push_back(model()->pathFromRow(row)); - } - if (model()->selection() != sel) { - model()->setSelection(sel); - if (!rows.empty()) - ensureVisible(rows.back()); - update(); - result = true; - if (attachedPropertyTree_) - updateAttachedPropertyTree(false); - } - } - } - return result; -} - -void QPropertyTree::setUndoEnabled(bool enabled, bool full) -{ - config_.undoEnabled = enabled; - config_.fullUndo = full; - model()->setUndoEnabled(enabled); - model()->setFullUndo(full); -} - -void QPropertyTree::attachPropertyTree(QPropertyTree* propertyTree) -{ - if (attachedPropertyTree_) - disconnect(attachedPropertyTree_, SIGNAL(signalChanged()), this, SLOT(onAttachedTreeChanged())); - attachedPropertyTree_ = propertyTree; - if (attachedPropertyTree_) - connect(attachedPropertyTree_, SIGNAL(signalChanged()), this, SLOT(onAttachedTreeChanged())); - updateAttachedPropertyTree(true); -} - -void QPropertyTree::detachPropertyTree() -{ - attachPropertyTree(0); -} - -void QPropertyTree::setAutoHideAttachedPropertyTree(bool autoHide) -{ - autoHideAttachedPropertyTree_ = autoHide; -} - -void QPropertyTree::getSelectionSerializers(Serialization::SStructs* serializers) -{ - TreeSelection::const_iterator i; - for (i = model()->selection().begin(); i != model()->selection().end(); ++i){ - PropertyRow* row = model()->rowFromPath(*i); - if (!row) - continue; - - - while (row && ((row->pulledUp() || row->pulledBefore()) || row->isLeaf())) { - row = row->parent(); - } - if (outlineMode_) { - PropertyRow* topmostContainerElement = 0; - PropertyRow* r = row; - while (r && r->parent()) { - if (r->parent()->isContainer()) - topmostContainerElement = r; - r = r->parent(); - } - if (topmostContainerElement != 0) - row = topmostContainerElement; - } - Serialization::SStruct ser = row->serializer(); - - if (ser) - serializers->push_back(ser); - } -} - -void QPropertyTree::updateAttachedPropertyTree(bool revert) -{ - if (attachedPropertyTree_) { - Serialization::SStructs serializers; - getSelectionSerializers(&serializers); - if (!attachedPropertyTree_->attach(serializers) && revert) - attachedPropertyTree_->revertNoninterrupting(); - if (autoHideAttachedPropertyTree_) - attachedPropertyTree_->setVisible(!serializers.empty()); - } -} - -struct FilterVisitor -{ - const QPropertyTree::RowFilter& filter_; - - FilterVisitor(const QPropertyTree::RowFilter& filter) - : filter_(filter) - { - } - - static void markChildrenAsBelonging(PropertyRow* row, bool belongs) - { - int count = int(row->count()); - for (int i = 0; i < count; ++i) - { - PropertyRow* child = row->childByIndex(i); - child->setBelongsToFilteredRow(belongs); - - markChildrenAsBelonging(child, belongs); - } - } - - static bool hasMatchingChildren(PropertyRow* row) - { - int numChildren = (int)row->count(); - for (int i = 0; i < numChildren; ++i) - { - PropertyRow* child = row->childByIndex(i); - if (!child) - continue; - if (child->matchFilter()) - return true; - if (hasMatchingChildren(child)) - return true; - } - return false; - } - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree) - { - const char* label = row->labelUndecorated(); - Serialization::string value = row->valueAsString(); - - bool matchFilter = filter_.match(label, filter_.NAME_VALUE, 0, 0) || filter_.match(value.c_str(), filter_.NAME_VALUE, 0, 0); - if (matchFilter && filter_.typeRelevant(filter_.NAME)) - filter_.match(label, filter_.NAME, 0, 0); - if (matchFilter && filter_.typeRelevant(filter_.VALUE)) - matchFilter = filter_.match(value.c_str(), filter_.VALUE, 0, 0); - if (matchFilter && filter_.typeRelevant(filter_.TYPE)) - matchFilter = filter_.match(row->typeNameForFilter(tree), filter_.TYPE, 0, 0); - - int numChildren = int(row->count()); - if (matchFilter) { - if (row->pulledBefore() || row->pulledUp()) { - // treat pulled rows as part of parent - PropertyRow* parent = row->parent(); - parent->setMatchFilter(true); - markChildrenAsBelonging(parent, true); - parent->setBelongsToFilteredRow(false); - } - else { - markChildrenAsBelonging(row, true); - row->setBelongsToFilteredRow(false); - row->setLayoutChanged(); - row->setLabelChanged(); - } - } - else { - bool belongs = hasMatchingChildren(row); - row->setBelongsToFilteredRow(belongs); - if (belongs) { - tree->expandRow(row, true, false); - for (int i = 0; i < numChildren; ++i) { - PropertyRow* child = row->childByIndex(i); - if (child->pulledUp()) - child->setBelongsToFilteredRow(true); - } - } - else { - row->_setExpanded(false); - row->setLayoutChanged(); - } - } - - row->setMatchFilter(matchFilter); - return SCAN_CHILDREN_SIBLINGS; - } - -protected: - string labelStart_; -}; - - - -void QPropertyTree::RowFilter::parse(const char* filter) -{ - for (int i = 0; i < NUM_TYPES; ++i) { - start[i].clear(); - substrings[i].clear(); - tillEnd[i] = false; - } - - YASLI_ESCAPE(filter != 0, return); - - vector filterBuf(filter, filter + strlen(filter) + 1); - for (size_t i = 0; i < filterBuf.size(); ++i) - filterBuf[i] = tolower(filterBuf[i]); - - const char* str = &filterBuf[0]; - - Type type = NAME_VALUE; - while (true) - { - bool fromStart = false; - while (*str == '^') { - fromStart = true; - ++str; - } - - const char* tokenStart = str; - - if (*str == '\"') - { - ++str; - while (*str != '\0' && *str != '\"') - ++str; - } - else - { - while (*str != '\0' && *str != ' ' && *str != '=' && *str != ':' && *str != '#') - ++str; - } - if (str != tokenStart) { - if (*tokenStart == '\"' && *str == '\"') { - start[type].assign(tokenStart + 1, str); - tillEnd[type] = true; - ++str; - } - else - { - if (fromStart) - start[type].assign(tokenStart, str); - else - substrings[type].push_back(string(tokenStart, str)); - } - } - while (*str == ' ') - ++str; - if (*str == '#') { - type = NAME; - ++str; - } - else if (*str == '=') { - type = VALUE; - ++str; - } - else if (*str == ':') { - type = TYPE; - ++str; - } - else if (*str == '\0') - break; - } -} - -bool QPropertyTree::RowFilter::match(const char* textOriginal, Type type, size_t* matchStart, size_t* matchEnd) const -{ - YASLI_ESCAPE(textOriginal, return false); - - char* text; - { - size_t textLen = strlen(textOriginal); - text = (char*)alloca((textLen + 1)); - memcpy(text, textOriginal, (textLen + 1)); - for (char* p = text; *p; ++p) - *p = tolower(*p); - } - - const string &startForType = this->start[type]; - if (tillEnd[type]){ - if (startForType == text) { - if (matchStart) - *matchStart = 0; - if (matchEnd) - *matchEnd = startForType.size(); - return true; - } - else - return false; - } - - const vector &substringsForType = this->substrings[type]; - - const char* startPos = text; - - if (matchStart) - *matchStart = 0; - if (matchEnd) - *matchEnd = 0; - if (!startForType.empty()) { - if (strncmp(text, startForType.c_str(), startForType.size()) != 0){ - //_freea(text); - return false; - } - if (matchEnd) - *matchEnd = startForType.size(); - startPos += startForType.size(); - } - - size_t numSubstrings = substringsForType.size(); - for (size_t i = 0; i < numSubstrings; ++i) { - const char* substr = strstr(startPos, substringsForType[i].c_str()); - if (!substr){ - return false; - } - startPos += substringsForType[i].size(); - if (matchStart && i == 0 && startForType.empty()) { - *matchStart = substr - text; - } - if (matchEnd) - *matchEnd = substr - text + substringsForType[i].size(); - } - return true; -} - -void QPropertyTree::onFilterChanged([[maybe_unused]] const QString& text) -{ - QByteArray arr = filterEntry_->text().toLocal8Bit(); - const char* filterStr = filterMode_ ? arr.data() : ""; - rowFilter_.parse(filterStr); - FilterVisitor visitor(rowFilter_); - model()->root()->scanChildrenBottomUp(visitor, this); - updateHeights(); -} - -void QPropertyTree::drawFilteredString(QPainter& p, const wchar_t* text, RowFilter::Type type, const QFont* font, const QRect& rect, const QColor& textColor, bool pathEllipsis, bool center) const -{ - int textLen = (int)wcslen(text); - - if (textLen == 0) - return; - - string textStr(fromWideChar(text)); - QString str(textStr.c_str()); - QFontMetrics fm(*font); - QRect textRect = rect; - int alignment; - if (center) - alignment = Qt::AlignHCenter | Qt::AlignVCenter; - else { - if (pathEllipsis && textRect.width() < fm.horizontalAdvance(str)) - alignment = Qt::AlignRight | Qt::AlignVCenter; - else - alignment = Qt::AlignLeft | Qt::AlignVCenter; - } - - if (filterMode_) { - size_t hiStart = 0; - size_t hiEnd = 0; - bool matched = rowFilter_.match(textStr.c_str(), type, &hiStart, &hiEnd) && hiStart != hiEnd; - if (!matched && (type == RowFilter::NAME || type == RowFilter::VALUE)) - matched = rowFilter_.match(textStr.c_str(), RowFilter::NAME_VALUE, &hiStart, &hiEnd); - if (matched && hiStart != hiEnd) { - QRectF boxFull; - QRectF boxStart; - QRectF boxEnd; - - boxFull = fm.boundingRect(textRect, alignment, str); - - if (hiStart > 0) - boxStart = fm.boundingRect(textRect, alignment, str.left(hiStart)); - else { - boxStart = fm.boundingRect(textRect, alignment, str); - boxStart.setWidth(0.0f); - } - boxEnd = fm.boundingRect(textRect, alignment, str.left(hiEnd)); - - QColor highlightColor, highlightBorderColor; - { - highlightColor = palette().color(QPalette::Highlight); - int h, s, v; - highlightColor.getHsv(&h, &s, &v); - h -= 175; - if (h < 0) - h += 360; - highlightColor.setHsv(h, min(255, int(s * 1.33f)), v, 255); - highlightBorderColor.setHsv(h, aznumeric_cast(s * 0.5f), v, 255); - } - - int left = int(boxFull.left() + boxStart.width()) - 1; - int top = int(boxFull.top()); - int right = int(boxFull.left() + boxEnd.width()); - int bottom = int(boxFull.top() + boxEnd.height()); - QRect highlightRect(left, top, right - left, bottom - top); - QBrush br(highlightColor); - p.setBrush(br); - p.setPen(highlightBorderColor); - bool oldAntialiasing = p.renderHints().testFlag(QPainter::Antialiasing); - p.setRenderHint(QPainter::Antialiasing, true); - - QRect intersectedHighlightRect = rect.intersected(highlightRect); - p.drawRoundedRect(intersectedHighlightRect, 4.0, 4.0); - p.setRenderHint(QPainter::Antialiasing, oldAntialiasing); - } - } - - QBrush textBrush(textColor); - p.setBrush(textBrush); - p.setPen(textColor); - QFont previousFont = p.font(); - p.setFont(*font); - p.drawText(textRect, alignment, str, 0); - p.setFont(previousFont); -} - -void QPropertyTree::_drawRowLabel(QPainter& p, const wchar_t* text, const QFont* font, const QRect& rect, const QColor& textColor) const -{ - drawFilteredString(p, text, RowFilter::NAME, font, rect, textColor, false, false); -} - -void QPropertyTree::_drawRowValue(QPainter& p, const wchar_t* text, const QFont* font, const QRect& rect, const QColor& textColor, bool pathEllipsis, bool center) const -{ - drawFilteredString(p, text, RowFilter::VALUE, font, rect, textColor, pathEllipsis, center); -} - -struct DrawVisitor -{ - DrawVisitor(QPainter& painter, const QRect& area, int scrollOffset, bool selectionPass) - : area_(area) - , painter_(painter) - , offset_(0) - , scrollOffset_(scrollOffset) - , lastParent_(0) - , selectionPass_(selectionPass) - {} - - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, int index) - { - if (row->visible(tree) && ((!row->parent() || (row->parent()->expanded() && !lastParent_)) || row->pulledUp())){ - QRect rect = row->rect(); - if (rect.top() > scrollOffset_ + area_.height()) - lastParent_ = row->parent(); - - int height = row->heightIncludingChildren(); - if ((height == USHRT_MAX || rect.top() + height > scrollOffset_) && rect.width() > 0) - row->drawRow(painter_, tree, index, selectionPass_); - - return SCAN_CHILDREN_SIBLINGS; - } - else - return SCAN_SIBLINGS; - } - -protected: - QPainter& painter_; - QRect area_; - int offset_; - int scrollOffset_; - PropertyRow* lastParent_; - bool selectionPass_; -}; - -QSize QPropertyTree::sizeHint() const -{ - if (sizeToContent_) - return minimumSize(); - else - return sizeHint_; -} - -bool QPropertyTree::event(QEvent* ev) -{ - if (ev->type() == QEvent::ShortcutOverride) - { - if (!widget_) - { - PropertyRow* row = model()->focusedRow(); - if (row) - { - QKeyEvent* keyEvent = static_cast(ev); - bool keyWillBeProcessed = false; - - int modifiedKey = keyEvent->key() | keyEvent->modifiers(); - switch (modifiedKey) - { - case (Qt::Key_F | Qt::CTRL): - case Qt::Key_Escape: - keyWillBeProcessed = true; - break; - - default: - keyWillBeProcessed = rowProcessesKey(row, keyEvent); - break; - } - - if (keyWillBeProcessed) - { - ev->accept(); - return true; - } - } - } - } - - return QWidget::event(ev); -} - -void QPropertyTree::paintEvent([[maybe_unused]] QPaintEvent* ev) -{ - QElapsedTimer timer; - timer.start(); - QPainter painter(this); - QRect clientRect = this->rect(); - - int clientHeight = clientRect.height(); - backgroundColor_ = palette().color(QPalette::Window); - painter.fillRect(clientRect, QBrush(backgroundColor_)); - - painter.translate(-offset_.x(), -offset_.y()); - - if (dragController_->captured()) - dragController_->drawUnder(painter); - - painter.translate(area_.left(), area_.top()); - - if (model()->root()) { - DrawVisitor selectionOp(painter, area_, offset_.y(), true); - model()->root()->scanChildren(selectionOp, this); - - DrawVisitor op(painter, area_, offset_.y(), false); - op(model()->root(), this, 0); - model()->root()->scanChildren(op, this); - } - - painter.translate(-area_.left(), -area_.top()); - painter.translate(offset_.x(), offset_.y()); - - //painter.setClipRect(rect()); - - if (size_.y() > clientHeight) - { - const int shadowHeight = int(_defaultRowHeight() * 0.3f); - QColor color1(0, 0, 0, 0); - QColor color2(0, 0, 0, 96); - - int visibleAreaWidth = area_.width() + 5; - - QRect upperRect(rect().left() + 1, rect().top(), visibleAreaWidth - 2, shadowHeight); - QLinearGradient upperGradient(upperRect.left(), upperRect.top(), upperRect.left(), upperRect.bottom()); - upperGradient.setColorAt(0.0f, color2); - upperGradient.setColorAt(1.0f, color1); - painter.fillRect(upperRect, QBrush(upperGradient)); - - QLinearGradient upperEdgeGradient(upperRect.left(), upperRect.top(), upperRect.left(), upperRect.bottom() + shadowHeight); - upperEdgeGradient.setColorAt(0.0f, color2); - upperEdgeGradient.setColorAt(1.0f, color1); - painter.fillRect(QRect(rect().left(), rect().top(), 1, shadowHeight * 2 + 1), QBrush(upperEdgeGradient)); - painter.fillRect(QRect(visibleAreaWidth - 1, rect().top(), 1, shadowHeight * 2 + 1), QBrush(upperEdgeGradient)); - - QRect lowerRect(rect().left() + 1, rect().bottom() - shadowHeight / 2, visibleAreaWidth - 2, shadowHeight / 2 + 1); - QLinearGradient lowerGradient(lowerRect.left(), lowerRect.top(), lowerRect.left(), lowerRect.bottom()); - lowerGradient.setColorAt(0.0f, color1); - lowerGradient.setColorAt(1.0f, color2); - QBrush lowerBrush(lowerGradient); - painter.fillRect(lowerRect, lowerGradient); - - QLinearGradient lowerEdgeGradient(lowerRect.left(), lowerRect.top() - shadowHeight, lowerRect.left(), lowerRect.bottom()); - lowerEdgeGradient.setColorAt(0.0f, color1); - lowerEdgeGradient.setColorAt(1.0f, color2); - painter.fillRect(QRect(rect().left(), rect().bottom() - shadowHeight * 2, 1, shadowHeight * 2 + 1), QBrush(lowerEdgeGradient)); - painter.fillRect(QRect(visibleAreaWidth - 1, rect().bottom() - shadowHeight * 2, 1, shadowHeight * 2 + 1), QBrush(lowerEdgeGradient)); - } - - if (dragController_->captured()) { - painter.translate(-offset_); - dragController_->drawOver(painter); - painter.translate(offset_); - } - else{ - // if(model()->focusedRow() != 0 && model()->focusedRow()->isRoot() && tree_->hasFocus()){ - // clientRect.left += 2; clientRect.top += 2; - // clientRect.right -= 2; clientRect.bottom -= 2; - // DrawFocusRect(dc, &clientRect); - // } - } - paintTime_ = aznumeric_cast(timer.elapsed()); -} - -QPropertyTree::HitTest QPropertyTree::hitTest(PropertyRow* row, const QPoint& pointInWindowSpace, const QRect& rowRect) -{ - QPoint point = pointToRootSpace(pointInWindowSpace); - - if (!row->hasVisibleChildren(this) && row->plusRect(this).contains(point)) - return TREE_HIT_PLUS; - - if (row->textRect(this).contains(point)) - return TREE_HIT_TEXT; - - if (rowRect.contains(point)) - return TREE_HIT_ROW; - - return TREE_HIT_NONE; - -} - -PropertyRow* QPropertyTree::rowByPoint(const QPoint& pt) -{ - if (!model_->root()) - return 0; - if (!area_.contains(pt)) - return 0; - return model_->root()->hit(this, pointToRootSpace(pt)); -} - -QPoint QPropertyTree::pointToRootSpace(const QPoint& point) const -{ - return QPoint(point.x() + offset_.x() - area_.left(), point.y() + offset_.y() - area_.top()); -} - -QPoint QPropertyTree::pointFromRootSpace(const QPoint& point) const -{ - return QPoint(point.x() - offset_.x() + area_.left(), point.y() - offset_.y() + area_.top()); -} - - -void QPropertyTree::moveEvent(QMoveEvent* ev) -{ - QWidget::moveEvent(ev); -} - -void QPropertyTree::resizeEvent(QResizeEvent* ev) -{ - QWidget::resizeEvent(ev); - - updateHeights(); -} - -void QPropertyTree::mousePressEvent(QMouseEvent* ev) -{ - //QWidget::mousePressEvent(ev); - setFocus(Qt::MouseFocusReason); - - if (ev->button() == Qt::LeftButton) - { - PropertyRow* row = rowByPoint(ev->pos()); - if (row && !row->isSelectable()) - row = row->parent(); - if (row){ - if (onRowLMBDown(row, row->rect(), pointToRootSpace(ev->pos()), ev->modifiers().testFlag(Qt::ControlModifier), ev->modifiers().testFlag(Qt::ShiftModifier))) { - capturedRow_ = row; - lastStillPosition_ = pointToRootSpace(ev->pos()); - } - else if (!dragCheckMode_){ - row = rowByPoint(ev->pos()); - PropertyRow* draggedRow = row; - while (draggedRow && (!draggedRow->isSelectable() || draggedRow->pulledUp() || draggedRow->pulledBefore())) - draggedRow = draggedRow->parent(); - if (draggedRow && !draggedRow->userReadOnly() && !widget_){ - dragController_->beginDrag(row, draggedRow, ev->globalPos()); - } - } - } - update(); - } - else if (ev->button() == Qt::RightButton) - { - QPoint point = ev->pos(); - PropertyRow* row = rowByPoint(point); - if (row){ - model()->setFocusedRow(row); - update(); - - onRowRMBDown(row, row->rect(), _toScreen(pointToRootSpace(point))); - } - else{ - QRect rect = this->rect(); - onRowRMBDown(model()->root(), rect, _toScreen(pointToRootSpace(point))); - } - } - else if (ev->button() == Qt::MiddleButton) - { - QPoint point = ev->pos(); - PropertyRow* row = rowByPoint(point); - if (row){ - switch (hitTest(row, point, row->rect())){ - case TREE_HIT_PLUS: - break; - case TREE_HIT_NONE: - default: - model()->setFocusedRow(row); - update(); - break; - } - - } - } -} - -void QPropertyTree::mouseReleaseEvent(QMouseEvent* ev) -{ - QWidget::mouseReleaseEvent(ev); - - if (ev->button() == Qt::LeftButton) - { - if (dragController_->captured()){ - if (dragController_->drop(QCursor::pos())) - updateHeights(); - else - update(); - } - if (dragCheckMode_) { - dragCheckMode_ = false; - } - else { - QPoint point = ev->pos(); - if (capturedRow_){ - QRect rowRect = capturedRow_->rect(); - onRowLMBUp(capturedRow_, rowRect, pointToRootSpace(ev->pos())); - mouseStillTimer_->stop(); - capturedRow_ = 0; - update(); - } - } - } - else if (ev->button() == Qt::RightButton) - { - - } - - unsetCursor(); -} - -void QPropertyTree::focusInEvent(QFocusEvent* ev) -{ - QWidget::focusInEvent(ev); - widget_.reset(); -} - -void QPropertyTree::keyPressEvent(QKeyEvent* ev) -{ - // NOTE: if you add any new key processing in here, make sure you update QPropertyTree::event() to handle - // it in the ShortcutOverride event. Otherwise, MainWindow/other shortcuts might take priority and eat it before - // it reaches this function. - - if (ev->key() == Qt::Key_F && ev->modifiers() == Qt::CTRL) { - setFilterMode(true); - } - - if (filterMode_) { - if (ev->key() == Qt::Key_Escape && ev->modifiers() == Qt::NoModifier) { - setFilterMode(false); - } - } - - bool result = false; - if (!widget_) { - PropertyRow* row = model()->focusedRow(); - if (row) - onRowKeyDown(row, ev); - } - update(); - if (!result) - QWidget::keyPressEvent(ev); -} - - -void QPropertyTree::mouseDoubleClickEvent(QMouseEvent* ev) -{ - QWidget::mouseDoubleClickEvent(ev); - - QPoint point = ev->pos(); - PropertyRow* row = rowByPoint(point); - if (row){ - PropertyActivationEvent e; - e.tree = this; - e.force = true; - e.reason = e.REASON_DOUBLECLICK; - PropertyRow* nonPulledParent = row; - while (nonPulledParent && nonPulledParent->pulledUp()) - nonPulledParent = nonPulledParent->parent(); - - if (row->widgetRect(this).contains(pointToRootSpace(point))){ - if (!row->onActivate(e)) - toggleRow(nonPulledParent); - } - else if (!toggleRow(row)) { - if (!row->onActivate(e)) - if (!toggleRow(nonPulledParent)) { - // activate first visible inline row - for (size_t i = 0; i < row->count(); ++i) { - PropertyRow* child = row->childByIndex(i); - if (child && child->pulledUp() && child->visible(this)) { - child->onActivate(e); - break; - } - } - } - } - } -} - -void QPropertyTree::onMouseStillTimeout() -{ - onMouseStill(mapFromGlobal(QCursor::pos())); -} - -void QPropertyTree::onMouseStill(QPoint point) -{ - if (capturedRow_) { - PropertyDragEvent e; - e.tree = this; - e.pos = point; - e.start = pressPoint_; - - capturedRow_->onMouseStill(e); - lastStillPosition_ = e.pos; - } -} - -void QPropertyTree::flushAggregatedMouseEvents() -{ - if (aggregatedMouseEventCount_ > 0) { - bool gotPendingEvent = aggregatedMouseEventCount_ > 1; - aggregatedMouseEventCount_ = 0; - if (gotPendingEvent && lastMouseMoveEvent_.data()) - mouseMoveEvent(lastMouseMoveEvent_.data()); - } -} - -void QPropertyTree::mouseMoveEvent(QMouseEvent* ev) -{ - if (ev->type() == QEvent::MouseMove && aggregateMouseEvents_) { - lastMouseMoveEvent_.reset(new QMouseEvent(QEvent::MouseMove, ev->localPos(), ev->windowPos(), ev->screenPos(), ev->button(), ev->buttons(), ev->modifiers())); - ev = lastMouseMoveEvent_.data(); - ++aggregatedMouseEventCount_; - if (aggregatedMouseEventCount_ > 1) - return; - } - - QCursor newCursor = QCursor(Qt::ArrowCursor); - QString newToolTip; - if (dragController_->captured() && !ev->buttons().testFlag(Qt::LeftButton)) - dragController_->interrupt(); - if (dragController_->captured()){ - QPoint pos = QCursor::pos(); - if (dragController_->dragOn(pos)) { - // SetCapture - } - update(); - } - else{ - QPoint point = ev->pos(); - PropertyRow* row = rowByPoint(point); - if (row && dragCheckMode_ && row->widgetRect(this).contains(pointToRootSpace(point))) { - row->onMouseDragCheck(this, dragCheckValue_); - } - else if (capturedRow_){ - onRowMouseMove(capturedRow_, QRect(), pointToRootSpace(point)); - if (config_.sliderUpdateDelay >= 0 && !mouseStillTimer_->isActive()) - mouseStillTimer_->start(config_.sliderUpdateDelay); - - if (cursor().shape() == Qt::BlankCursor) - { - pressDelta_ += pointToRootSpace(ev->pos()) - pressPoint_; - pointerMovedSincePress_ = true; - AzQtComponents::SetCursorPos(mapToGlobal(pointFromRootSpace(pressPoint_))); - } - else - { - pressDelta_ = pointToRootSpace(ev->pos()) - pressPoint_; - } - } - - PropertyRow* hoverRow = row; - if (capturedRow_) - hoverRow = capturedRow_; - PropertyHoverInfo hover; - if (hoverRow) { - QPoint pointInRootSpace = pointToRootSpace(point); - if (hoverRow->getHoverInfo(&hover, pointInRootSpace, this)) { - newCursor = hover.cursor; - newToolTip = hover.toolTip; - - PropertyRow* tooltipRow = hoverRow; - while (newToolTip.isEmpty() && tooltipRow->parent() && (tooltipRow->pulledUp() || tooltipRow->pulledBefore())) { - // check if parent of inlined property has a tooltip instead - tooltipRow = tooltipRow->parent(); - if (tooltipRow->getHoverInfo(&hover, pointInRootSpace, this)) - newToolTip = hover.toolTip; - } - } - - if (hoverRow->validatorWarningIconRect(this).contains(pointToRootSpace(point))) { - newCursor = QCursor(Qt::PointingHandCursor); - newToolTip = "Jump to next warning"; - } - if (hoverRow->validatorErrorIconRect(this).contains(pointToRootSpace(point))) { - newCursor = QCursor(Qt::PointingHandCursor); - newToolTip = "Jump to next error"; - } - } - } - setCursor(newCursor); - if (toolTip() != newToolTip) - setToolTip(newToolTip); - if (newToolTip.isEmpty()) - QToolTip::hideText(); -} - -void QPropertyTree::wheelEvent(QWheelEvent* ev) -{ - QWidget::wheelEvent(ev); - - float delta = ev->angleDelta().ry() / 360.0f; - if (ev->modifiers() & Qt::CTRL) { - if (delta > 0) - zoomLevel_ += 1; - else - zoomLevel_ -= 1; - if (zoomLevel_ < 8) - zoomLevel_ = 8; - if (zoomLevel_ > 30) - zoomLevel_ = 30; - float scale = zoomLevel_ * 0.1f; - QFont font; - font.setPointSizeF(font.pointSizeF() * scale); - setFont(font); - font.setBold(true); - boldFont_ = font; - - updateHeights(true); - } - else { - if (scrollBar_->isVisible() && scrollBar_->isEnabled()) - scrollBar_->setValue(scrollBar_->value() + -ev->angleDelta().y()); - } -} - -bool QPropertyTree::toggleRow(PropertyRow* row) -{ - if (!row->canBeToggled(this)) - return false; - expandRow(row, !row->expanded()); - updateHeights(); - return true; -} - -bool QPropertyTree::_isDragged(const PropertyRow* row) const -{ - if (!dragController_->dragging()) - return false; - if (dragController_->draggedRow() == row) - return true; - return false; -} - -bool QPropertyTree::_isCapturedRow(const PropertyRow* row) const -{ - return capturedRow_ == row; -} - -void QPropertyTree::setValueColumnWidth(float valueColumnWidth) -{ - if (style_->valueColumnWidth != valueColumnWidth) - { - style_->valueColumnWidth = valueColumnWidth; - updateHeights(); - update(); - } -} - -QPropertyTree::QPropertyTree(const QPropertyTree&) -{ -} - - -QPropertyTree& QPropertyTree::operator=(const QPropertyTree&) -{ - return *this; -} - -void QPropertyTree::onAttachedTreeChanged() -{ - revert(); -} - -struct ValidatorIconVisitor -{ - ScanResult operator()(PropertyRow* row, QPropertyTree* tree, int) - { - row->resetValidatorIcons(); - if (row->validatorCount()) { - bool hasErrors = false; - bool hasWarnings = false; - if (const ValidatorEntry* validatorEntries = tree->_validatorBlock()->GetEntry(row->validatorIndex(), row->validatorCount())) { - for (int i = 0; i < row->validatorCount(); ++i) { - const ValidatorEntry* validatorEntry = validatorEntries + i; - if (validatorEntry->type == VALIDATOR_ENTRY_ERROR) - hasErrors = true; - else if (validatorEntry->type == VALIDATOR_ENTRY_WARNING) - hasWarnings = true; - } - } - - if (hasErrors || hasWarnings) - { - PropertyRow* lastClosedParent = 0; - PropertyRow* current = row->parent(); - bool lastWasPulled = row->pulledUp() || row->pulledBefore(); - while (current && current->parent()) { - if (!current->expanded() && !lastWasPulled && current->visible(tree)) - lastClosedParent = current; - lastWasPulled = current->pulledUp() || current->pulledBefore(); - current = current->parent(); - } - if (lastClosedParent) - lastClosedParent->addValidatorIcons(hasWarnings, hasErrors); - } - } - return SCAN_CHILDREN_SIBLINGS; - } -}; - -void QPropertyTree::updateValidatorIcons() -{ - if (!validatorBlock_->IsEnabled()) - return; - ValidatorIconVisitor op; - model()->root()->scanChildren(op, this); - model()->root()->setLabelChangedToChildren(); -} - -void QPropertyTree::setTreeStyle(const QPropertyTreeStyle& style) -{ - *style_ = style; - updateHeights(true); -} - -void QPropertyTree::setPackCheckboxes(bool pack) -{ - style_->packCheckboxes = pack; - updateHeights(true); -} - -bool QPropertyTree::packCheckboxes() const -{ - return style_->packCheckboxes; -} - -void QPropertyTree::setCompact(bool compact) -{ - style_->compact = compact; - update(); -} - -bool QPropertyTree::compact() const -{ - return style_->compact; -} - -void QPropertyTree::setRowSpacing(float rowSpacing) -{ - style_->rowSpacing = rowSpacing; -} - -float QPropertyTree::rowSpacing() const -{ - return style_->rowSpacing; -} - -float QPropertyTree::valueColumnWidth() const -{ - return style_->valueColumnWidth; -} - -void QPropertyTree::setFullRowMode(bool fullRowMode) -{ - style_->fullRowMode = fullRowMode; - update(); -} - -bool QPropertyTree::fullRowMode() const -{ - return style_->fullRowMode; -} - -bool QPropertyTree::containsErrors() const -{ - return validatorBlock_->ContainsErrors(); -} - -void QPropertyTree::focusFirstError() -{ - jumpToNextHiddenValidatorIssue(true, model()->root()); -} - -void QPropertyTree::setBackgroundColor(const QColor& backgroundColor) -{ - backgroundColor_ = backgroundColor; -} - -#include -#include - -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.h deleted file mode 100644 index e5c6caec99..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTree.h +++ /dev/null @@ -1,528 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYTREE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYTREE_H -#pragma once - - - -#if !defined(Q_MOC_RUN) -#include "../EditorCommonAPI.h" -#include "ConstStringList.h" -#include "ValidatorBlock.h" -#include -#include "Serialization/Serializer.h" -#include "Serialization/IArchive.h" -#include "Serialization/Pointers.h" -#include "Serialization/Object.h" -#include "PropertyRow.h" -#include -#include -#endif - -namespace Serialization -{ - struct SContextLink; - class IClassFactory; -} - -class QMenu; -class QLineEdit; -class QScrollBar; - -struct Color; -class TreeImpl; -class PropertyTreeModel; -class PopupMenuItem; -class PropertyTreeModel; -class PropertyRow; -class PropertyRowWidget; -class PropertyTreeOperator; -class Entry; -struct IconXPMCache; - - -// --------------------------------------------------------------------------- -struct QPropertyTreeStyle; -struct PropertyTreeConfig -{ - bool immediateUpdate; - bool hideUntranslated; - bool showContainerIndices; - bool showContainerIndexLabels; - bool containerIndicesZeroBased; - bool filterWhenType; - int filter; - int sliderUpdateDelay; - int expandLevels; - bool undoEnabled; - bool fullUndo; - bool multiSelection; - bool copyPasteEnabled; - - PropertyTreeConfig() - : immediateUpdate(true) - , hideUntranslated(true) - , showContainerIndices(true) - , showContainerIndexLabels(false) - , containerIndicesZeroBased(true) - , filterWhenType(true) - , filter(0) - , sliderUpdateDelay(25) - , undoEnabled(true) - , fullUndo(true) - , multiSelection(true) - , copyPasteEnabled(true) - { - } -}; - -// --------------------------------------------------------------------------- - -struct PropertyRowMenuHandler; - -class DragWindow : public QWidget -{ - Q_OBJECT -public: - DragWindow(QPropertyTree* tree); - - void set(QPropertyTree* tree, PropertyRow* row, const QRect& rowRect); - void setWindowPos(bool visible); - void show(); - void move(int deltaX, int deltaY); - void hide(); - - void drawRow(QPainter& p); - void paintEvent(QPaintEvent* ev); - -protected: - bool useLayeredWindows_; - PropertyRow* row_; - QRect rect_; - QPropertyTree* tree_; - QPoint offset_; -}; - -class EDITOR_COMMON_API QPropertyTree : public QWidget -{ - Q_OBJECT -public: - explicit QPropertyTree(QWidget* parent = nullptr); - ~QPropertyTree(); - - // Used to attach an object to a PropertyTree widget. Attached object should implement - // Serialize method. Example of usage: - // - // struct MyType - // { - // void Serialize(Serialization::IArchive& ar); - // }; - // MyType object; - // - // propertyTree->attach(Serialization::SStruct(object)); - // - // Attached object will be serialized through PropertyOArchive to populate the tree. On - // every input made to the tree attached object will be deserialized through - // PropertyIArchive and serialized back again through PropertyOArchive to make sure that - // tree content is up-to-date. - // Property archives can be identified by calling ar.IsEdit(). - // SStruct stores a pointer to an actual object that should either outlive property tree - // or be detached on destruction. - void attach(const Serialization::SStruct& serializer); - // This form attaches an array of SStruct-s. This is used to edit multiple objects - // simultaneously. Only shared properties will be shown (i.e. intersection of all - // properties). Properties with different values will be shown as "..." or a gray - // checkbox. - bool attach(const Serialization::SStructs& serializers); - // Used for two-trees setup. In this case leader tree acts as an outliner, that shows - // top level of the data (either by using setOutlineMode or setting different filter). - // Attached, follower tree then shows properties ot the item selected in the main tree. - // Temporary structures (e.g. created on the stack) should not be used in this mode - // (except for decorators), as this may cause access to deallocated object when - // selecting it in the tree. - void attachPropertyTree(QPropertyTree* propertyTree); - void detachPropertyTree(); - void setAutoHideAttachedPropertyTree(bool autoHide); - // Effectively clears the tree. - void detach(); - bool attached() const { return !attached_.empty(); } - - // Forces serialization of attached object to update properties. Can be used to update - // property tree when attached object was changed for some reason. - void revert(); - // Same as revert(), except that it will but interrupt editing or mouse action in - // progress. - void revertNoninterrupting(); - // Forces deserialization of attached objects from property items. - void apply(bool continuousUpdate); - // Useful to apply edit boxes that are being edited at the moment. - // May be needed when click on toolbar button doesn't steal the focus, leaving input - // data effectively not saved. - void applyInplaceEditor(); - - // Reduces width of the tree by removing expansion arrow/plus on the first level of the - // tree (first level is always expanded). - void setCompact(bool compact); - bool compact() const; - // Puts checkboxes into two columns when possible. - void setPackCheckboxes(bool pack); - bool packCheckboxes() const; - // Changes distance between rows, multiplier of row height. - void setRowSpacing(float rowSpacing); - float rowSpacing() const; - // Sets default width of the value column, 0..1 (relative to widget width) - void setValueColumnWidth(float valueColumnWidth); - float valueColumnWidth() const; - // Allows to override background color, useful when placing on tabs or panels that have - // have different background. - void setBackgroundColor(const QColor& color); - const QColor& backgroundColor() const { return backgroundColor_; } - // Set number of levels to be expanded by default. Note that this function should be - // invoked before first call to attach attach() to have an effect. - void setExpandLevels(int levels); - // Can be used to control if container(array) elements have numbered labels. - void setShowContainerIndices(bool showContainerIndices) { config_.showContainerIndices = showContainerIndices; } - bool showContainerIndices() const{ return config_.showContainerIndices; } - // Can be used to control if container(array) elements should prepend the number to the existing label - void setShowContainerIndexLabels(bool showContainerIndexLabels) { config_.showContainerIndexLabels = showContainerIndexLabels; } - bool showContainerIndexLabels() const{ return config_.showContainerIndexLabels; } - // Can be used to control if container(array) elements should be zero- (default) or one-based - void setContainerIndicesZeroBased(bool containerIndicesZeroBased) { config_.containerIndicesZeroBased = containerIndicesZeroBased; } - bool containerIndicesZeroBased() const{ return config_.containerIndicesZeroBased; } - // Allows control of copy/paste functionality - void setCopyPasteEnabled(bool copyPasteEnabled) { config_.copyPasteEnabled = copyPasteEnabled; } - bool copyPasteEnabled() const{ return config_.copyPasteEnabled; } - - // Limits the rate at which sliders emit change signal. - void setSliderUpdateDelay(int delayMS) { config_.sliderUpdateDelay = delayMS; } - - // Limit number of mouse-movement updates per-frame. Used to prevent large tree updates - // from draining all the idle time. - void setAggregateMouseEvents(bool aggregate) { aggregateMouseEvents_ = aggregate; } - void flushAggregatedMouseEvents(); - - // Can be used to disable internal undo. - void setUndoEnabled(bool enabled, bool full = false); - // This can be used to disable automatic serialization after each deserialization call. - // May be useful to prevent double-revert when signalChange is connected to some - // external data model, which fires an event that reverts tree automatically. - void setAutoRevert(bool autoRevert) { autoRevert_ = autoRevert; } - // Default size. - void setSizeHint(const QSize& size) { sizeHint_ = size; } - // Sets minimal size of the widget to the size of the visible content of the tree. - void setSizeToContent(bool sizeToContent); - bool sizeToContent() const{ return sizeToContent_; } - // Retrieves size of the content, doesn't require sizeToContent to be set. - QSize contentSize() const{ return contentSize_; } - // When set filtering is started just by typing in the property tree - void setFilterWhenType(bool filterWhenType) { config_.filterWhenType = filterWhenType; } - - // Outline mode hides content of the elements of the container (excepted for - // inlined/pulled-up properties). Can be used together with second property - // tree through attachPropertyTree. - void setOutlineMode(bool outlineMode) { outlineMode_ = outlineMode; } - bool outlineMode() const{ return outlineMode_; } - // Hide selection when widget is out of focus. Disables selection for parent of inline items. - void setHideSelection(bool hideSelection) { hideSelection_ = hideSelection; } - bool hideSelection() const{ return hideSelection_; } - // Can be used to disable selection of multiple properties at the same time. - void setMultiSelection(bool multiSelection) { config_.multiSelection = multiSelection; } - bool multiSelection() const{ return config_.multiSelection; } - - // Sets head of the context-list. Can be used to pass additional data to nested decorators. - void setArchiveContext(Serialization::SContextLink* context) { archiveContext_ = context; } - // Sets archive filter. Filter is a bit mask stored within archive that can be used to - // affect behavior of serialization. For example one can have two trees that shows - // different portions of the same object. - void setFilter(int filter) { config_.filter = filter; } - - // This methods returns array of SStruct-s for all selected properties. - // This is useful for manual implementation of attachPropertyTree behavior - // with type filtering or special logic. - void getSelectionSerializers(Serialization::SStructs* serializers); - // Can be used to select once serialized object(s) in the tree. - bool selectByAddress(const void*, bool keepSelectionIfChildSelected = false); - bool selectByAddresses(const void* const* addresses, size_t addressCount, bool keepSelectionIfChildSelected); - // Can be used to query information about selection in the tree. - bool setSelectedRow(PropertyRow* row); - PropertyRow* selectedRow(); - int selectedRowCount() const; - PropertyRow* selectedRowByIndex(int index); - - // Reports if serialized data contains errors. Errors are reported - // through IArchive::Error() method. - bool containsErrors() const; - void focusFirstError(); - - void ensureVisible(PropertyRow* row, bool update = true, bool considerChildren = true); - void expandRow(PropertyRow* row, bool expanded = true, bool updateHeights = true); - - // PropertyTreeStyle used to customize visual appearance of the property tree - const QPropertyTreeStyle& treeStyle() const{ return *style_; } - void setTreeStyle(const QPropertyTreeStyle& style); - - // Config used to store behavioral settings - const PropertyTreeConfig& config() const{ return config_; } - - // Instance of PropertyTree can be serialized. In this case the expansion state - // of the rows and list of selected rows will be saved (not the property values). - void Serialize(Serialization::IArchive& ar); - - // OBSOLETE: Serialization::Object will be gone - void attach(const Serialization::Object& object); - int revertObjects(vector objectAddresses); - bool revertObject(void* objectAddress); -signals: - // Emited for every finished changed of the value. E.g. when you drag a slider, - // signalChanged will be invoked when you release a mouse button. - void signalChanged(); - // Used fast-pace changes, like movement of the slider before mouse gets released. - void signalContinuousChange(); - // Invoked whenever selection changed. - void signalSelected(); - // Invoked after each revert() call (can be caused by user intput). - void signalReverted(); - // Invoked before any change is going to occur and can be used to store current version - // of data for own undo stack. - void signalPushUndo(); - void signalPushRedo(); - - // Called before and after serialization is invoked. Can be used to update context list - // in archive. - void signalAboutToSerialize(Serialization::IArchive& ar); - void signalSerialized(Serialization::IArchive& ar); - - // OBSOLETE: do not use - void signalObjectChanged(const Serialization::Object& obj); - - // Called when visual size of the tree changes, i.e. when things are deserialized and - // and when rows are expanded/collapsed. - void signalSizeChanged(); - - // Called when undo/redo are triggered via keyboard shortcut - void signalUndo(); - void signalRedo(); -public slots: - void expandAll(PropertyRow* root = 0); - void collapseAll(PropertyRow* root = 0); - void onAttachedTreeChanged(); -public: - // internal methods: - void setFullRowMode(bool fullRowMode); - bool fullRowMode() const; - void setHideUntranslated(bool hideUntranslated) { config_.hideUntranslated = hideUntranslated; } - bool hideUntranslated() const{ return config_.hideUntranslated; } - void setImmediateUpdate(bool immediateUpdate) { config_.immediateUpdate = immediateUpdate; } - bool immediateUpdate() const{ return config_.immediateUpdate; } - int _defaultRowHeight() const { return defaultRowHeight_; } - PropertyTreeModel* model() { return model_.data(); } - const PropertyTreeModel* model() const { return model_.data(); } - - QPoint treeSize() const; - int leftBorder() const { return leftBorder_; } - int rightBorder() const { return rightBorder_; } - bool multiSelectable() const { return attachedPropertyTree_ != 0 || config_.multiSelection; } - void expandParents(PropertyRow* row); - bool spawnWidget(PropertyRow* row, bool ignoreReadOnly); - bool getSelectedObject(Serialization::Object* object); - void onSignalChanged() { signalChanged(); } - - void onRowSelected(const std::vector& row, bool addSelection, bool adjustCursorPos); - const ValidatorBlock* _validatorBlock() const { return validatorBlock_.data(); } - QPoint _toScreen(QPoint point) const; - void _cancelWidget(){ widget_.reset(); } - void _drawRowLabel(QPainter& p, const wchar_t* text, const QFont* font, const QRect& rect, const QColor& color) const; - void _drawRowValue(QPainter& p, const wchar_t* text, const QFont* font, const QRect& rect, const QColor& color, bool pathEllipsis, bool center) const; - QRect _visibleRect() const; - bool _isDragged(const PropertyRow* row) const; - bool _isCapturedRow(const PropertyRow* row) const; - PropertyRow* _pressedRow() const { return pressedRow_; } - void _setPressedRow(PropertyRow* row) { pressedRow_ = row; } - int _applyTime() const{ return applyTime_; } - int _revertTime() const{ return revertTime_; } - int _updateHeightsTime() const{ return updateHeightsTime_; } - int _paintTime() const{ return paintTime_; } - const QFont& _boldFont() const{ return boldFont_; } - bool hasFocusOrInplaceHasFocus() const; - void addMenuHandler(PropertyRowMenuHandler* handler); - IconXPMCache* _iconCache() const{ return iconCache_.data(); } -public slots: - void onFilterChanged(const QString& str); -protected slots: - void onScroll(int pos); - void onModelUpdated(const PropertyRows& rows, bool apply); - void onModelPushUndo(PropertyTreeOperator* op, bool* handled); - void onModelPushRedo(PropertyTreeOperator* op, bool* handled); - void onMouseStillTimeout(); - -private: - QPropertyTree(const QPropertyTree&); - QPropertyTree& operator=(const QPropertyTree&); -protected: - class DragController; - enum HitTest{ - TREE_HIT_PLUS, - TREE_HIT_TEXT, - TREE_HIT_ROW, - TREE_HIT_NONE - }; - PropertyRow* rowByPoint(const QPoint& point); - HitTest hitTest(PropertyRow* row, const QPoint& pointInWindowSpace, const QRect& rowRect); - void onRowMenuDecompose(PropertyRow* row); - void onMouseStill(QPoint point); - - QSize sizeHint() const override; - bool event(QEvent* ev) override; - void paintEvent(QPaintEvent* ev) override; - void moveEvent(QMoveEvent* ev) override; - void resizeEvent(QResizeEvent* ev) override; - void mousePressEvent(QMouseEvent* ev) override; - void mouseReleaseEvent(QMouseEvent* ev) override; - void mouseDoubleClickEvent(QMouseEvent* ev) override; - void mouseMoveEvent(QMouseEvent* ev) override; - void wheelEvent(QWheelEvent* ev) override; - void keyPressEvent(QKeyEvent* ev) override; - void focusInEvent(QFocusEvent* ev) override; - - void updateArea(); - bool toggleRow(PropertyRow* row); - - struct RowFilter { - enum Type { - NAME_VALUE, - NAME, - VALUE, - TYPE, - NUM_TYPES - }; - - string start[NUM_TYPES]; - bool tillEnd[NUM_TYPES]; - std::vector substrings[NUM_TYPES]; - - void parse(const char* filter); - bool match(const char* text, Type type, size_t* matchStart, size_t* matchEnd) const; - bool typeRelevant(Type type) const{ - return !start[type].empty() || !substrings[type].empty(); - } - - RowFilter() - { - for (int i = 0; i < NUM_TYPES; ++i) - tillEnd[i] = false; - } - }; - - QPoint pointToRootSpace(const QPoint& pointInWindowSpace) const; - QPoint pointFromRootSpace(const QPoint& point) const; - - void interruptDrag(); - void updateHeights(bool recalculateTextSize=false); - void updateValidatorIcons(); - bool updateScrollBar(); - void applyValidation(); - void jumpToNextHiddenValidatorIssue(bool isError, PropertyRow* start); - - bool onContextMenu(PropertyRow* row, QMenu& menu); - void clearMenuHandlers(); - bool onRowKeyDown(PropertyRow* row, const QKeyEvent* ev); - bool rowProcessesKey(PropertyRow* row, const QKeyEvent* ev); - // points here are specified in root-row space - bool onRowLMBDown(PropertyRow* row, const QRect& rowRect, QPoint point, bool controlPressed, bool shiftPressed); - void onRowLMBUp(PropertyRow* row, const QRect& rowRect, QPoint point); - void onRowRMBDown(PropertyRow* row, const QRect& rowRect, QPoint point); - void onRowMouseMove(PropertyRow* row, const QRect& rowRect, QPoint point); - - bool canBePasted(PropertyRow* destination); - bool canBePasted(const char* destinationType); - - void setFilterMode(bool inFilterMode); - void startFilter(const char* filter); - void setWidget(PropertyRowWidget* widget); - void _arrangeChildren(); - - void updateAttachedPropertyTree(bool revert); - void drawFilteredString(QPainter& p, const wchar_t* text, RowFilter::Type type, const QFont* font, const QRect& rect, const QColor& color, bool pathEllipsis, bool center) const; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - QScopedPointer model_; - int cursorX_; - - QScopedPointer widget_; // in-place widget - vector menuHandlers_; - - typedef vector Objects; - Objects attached_; - QPropertyTree* attachedPropertyTree_; - bool autoHideAttachedPropertyTree_; - - bool filterMode_; - RowFilter rowFilter_; - QScopedPointer filterEntry_; - QScopedPointer iconCache_; - Serialization::SContextLink* archiveContext_; - QScopedPointer validatorBlock_; - bool outlineMode_; - bool sizeToContent_; - bool hideSelection_; - - bool autoRevert_; - bool needUpdate_; - - QScrollBar* scrollBar_; - QFont boldFont_; - QColor backgroundColor_; - QRect area_; - int leftBorder_; - int rightBorder_; - QPoint size_; - QPoint offset_; - QSize sizeHint_; - QSize contentSize_; - DragController* dragController_; - Serialization::SharedPtr lastSelectedRow_; - QPoint pressPoint_; - QPoint pressDelta_; - bool pointerMovedSincePress_; - QPoint lastStillPosition_; - PropertyRow* capturedRow_; - PropertyRow* pressedRow_; - QTimer* mouseStillTimer_; - - bool aggregateMouseEvents_; - int aggregatedMouseEventCount_; - QScopedPointer lastMouseMoveEvent_; - - PropertyTreeConfig config_; - QScopedPointer style_; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - int defaultRowHeight_; - - int applyTime_; - int revertTime_; - int updateHeightsTime_; - int paintTime_; - int zoomLevel_; - bool dragCheckMode_; - bool dragCheckValue_; - - friend class TreeImpl; - friend class FilterEntry; - friend class DragWindow; - friend struct FilterVisitor; - friend struct PropertyTreeMenuHandler; -}; - -wstring generateDigest(Serialization::SStruct& ser); -// vim: tw=90: - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_QPROPERTYTREE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTreeStyle.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTreeStyle.h deleted file mode 100644 index 82577c1b90..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/QPropertyTreeStyle.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "Serialization.h" -#include "Serialization/Decorators/Range.h" - -struct QPropertyTreeStyle -{ - bool compact; - bool packCheckboxes; - bool fullRowMode; - bool showHorizontalLines; - bool doNotIndentSecondLevel; - bool groupShadows; - bool groupRectangle; - bool alignLabelsToRight; - float valueColumnWidth; - float rowSpacing; - unsigned char levelShadowOpacity; - float levelIndent; - float firstLevelIndent; - float groupShade; - float sliderSaturation; - - QPropertyTreeStyle() - : compact(false) - , packCheckboxes(true) - , fullRowMode(false) - , valueColumnWidth(.59f) - , rowSpacing(1.1f) - , showHorizontalLines(false) - , firstLevelIndent(0.75f) - , levelIndent(0.75f) - , levelShadowOpacity(36) - , doNotIndentSecondLevel(false) - , groupShadows(false) - , sliderSaturation(0.0f) - , groupShade(0.15f) - , groupRectangle(false) - , alignLabelsToRight(false) - { - } - - void Serialize(Serialization::IArchive& ar) - { - ar.Doc("Here you can define appearance of QPropertyTree control."); - - ar(valueColumnWidth, "valueColumnWidth", "Value Column Width"); - ar.Doc("Defines a ratio of the value / name columns. Normalized."); - ar(Serialization::Range(rowSpacing, 0.5f, 3.0f), "rowSpacing", "Row Spacing"); - ar.Doc("Height of one row (line) in text-height units."); - ar(alignLabelsToRight, "alignLabelsToRight", "Right Alignment"); - ar(Serialization::Range(levelIndent, 0.0f, 3.0f), "levelIndent", "Level Indent"); - ar.Doc("Indentation of a every next level in text-height units."); - - ar(Serialization::Range(firstLevelIndent, 0.0f, 3.0f), "firstLevelIndent", "First Level Indent"); - ar.Doc("Indentation of a very first level in text-height units."); - ar(Serialization::Range(sliderSaturation, 0.0f, 1.0f), "sliderSaturation", "Slider Saturation"); - ar(levelShadowOpacity, "levelShadowOpacity", "Level Shadow Opacity"); - ar.Doc("Amount of background darkening that gets added to each next nested level."); - - ar(compact, "compact", "Compact"); - ar.Doc("Compact mode removes expansion pluses from the level and reduces inner padding. Useful for narrowing the widget."); - ar(packCheckboxes, "packCheckboxes", "Pack Checkboxes"); - ar.Doc("Arranges checkboxes in two columns, when possible."); - - ar(showHorizontalLines, "showHorizontalLines", "Horizontal Lines"); - ar.Doc("Show thin line that connects row name with its value."); - - ar(doNotIndentSecondLevel, "doNotIndentSecondLevel", "Do not indent second level"); - ar(groupShadows, "groupShadows", "Group Shadows"); - ar(groupRectangle, "groupRectangle", "Group Rectangle"); - - ar(Serialization::Range(groupShade, -1.0f, 1.0f), "groupShade", "Group Shade"); - ar.Doc("Shade of the group."); - } -}; - diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Serialization.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Serialization.h deleted file mode 100644 index 3ce0c2c8f2..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Serialization.h +++ /dev/null @@ -1,29 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_SERIALIZATION_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_SERIALIZATION_H -#pragma once - - -#include "Serialization/STL.h" -#include "Serialization/Pointers.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/StringList.h" - -#include "Serialization/IArchive.h" -#include "Serialization/BinArchive.h" - -using Serialization::IArchive; -using Serialization::SStruct; -using Serialization::TypeID; -using Serialization::SharedPtr; - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_SERIALIZATION_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.cpp deleted file mode 100644 index 640197ca45..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.cpp +++ /dev/null @@ -1,56 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" - -SlicerEdit::SlicerEdit( SpriteBorder border, - QSize& unscaledPixmapSize, - ISprite* sprite ) -: QLineEdit() -, m_manipulator( nullptr ) -{ - bool isVertical = IsBorderVertical( border ); - - float totalUnscaledSizeInPixels = aznumeric_cast( isVertical ? unscaledPixmapSize.width() : unscaledPixmapSize.height() ); - - setPixelPosition( GetBorderValueInPixels( sprite, border, totalUnscaledSizeInPixels ) ); - - setValidator( new QDoubleValidator( 0.0f, totalUnscaledSizeInPixels, 1 ) ); - - QObject::connect( this, - &SlicerEdit::editingFinished, this, - [ this, border, sprite, totalUnscaledSizeInPixels ]() - { - float p = text().toFloat(); - - m_manipulator->setPixelPosition( p ); - - SetBorderValue( sprite, border, p, totalUnscaledSizeInPixels ); - } ); -} - -void SlicerEdit::SetManipulator(SlicerManipulator* manipulator) -{ - m_manipulator = manipulator; -} - -void SlicerEdit::setPixelPosition(float p) -{ - setText( QString::number( p ) ); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.h deleted file mode 100644 index 88d47d3817..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerEdit.h +++ /dev/null @@ -1,46 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SLICEREDIT_H -#define CRYINCLUDE_EDITORCOMMON_SLICEREDIT_H - -#if !defined(Q_MOC_RUN) -#include - -#include "SpriteBorderEditorCommon.h" -#endif - -class SlicerEdit -: public QLineEdit -{ - Q_OBJECT - -public: - - SlicerEdit( SpriteBorder border, - QSize& unscaledPixmapSize, - ISprite* sprite ); - - void SetManipulator(SlicerManipulator* manipulator); - - void setPixelPosition(float p); - -private: - - SlicerManipulator* m_manipulator; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_SLICEREDIT_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.cpp deleted file mode 100644 index d516f30e7d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.cpp +++ /dev/null @@ -1,143 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" - -#define CRYINCLUDE_EDITORCOMMON_DRAW_SELECTABLE_AREA_OF_SLICERMANIPULATOR ( 0 ) -#define CRYINCLUDE_EDITORCOMMON_ARBITRARILY_LARGE_NUMBER ( 10000.0f ) -#define CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH ( 2.0f ) - -SlicerManipulator::SlicerManipulator( SpriteBorder border, - QSize& unscaledPixmapSize, - QSize& scaledPixmapSize, - float thicknessInPixels, - ISprite* sprite, - QGraphicsScene* scene ) -: QGraphicsRectItem() -, m_border( border ) -, m_isVertical( IsBorderVertical( m_border ) ) -, m_unscaledPixmapSize( unscaledPixmapSize ) -, m_scaledPixmapSize( scaledPixmapSize ) -, m_sprite( sprite ) -, m_unscaledOverScaledFactor( ( (float)m_unscaledPixmapSize.width() / (float)m_scaledPixmapSize.width() ), - ( (float)m_unscaledPixmapSize.height() / (float)m_scaledPixmapSize.height() ) ) -, m_scaledOverUnscaledFactor( ( 1.0f / m_unscaledOverScaledFactor.x() ), - ( 1.0f / m_unscaledOverScaledFactor.y() ) ) -, m_color( Qt::white ) -, m_edit( nullptr ) -{ - setAcceptHoverEvents( true ); - - scene->addItem( this ); - - setRect( ( m_isVertical ? - ( thicknessInPixels * 0.5f ) : - CRYINCLUDE_EDITORCOMMON_ARBITRARILY_LARGE_NUMBER ), - ( m_isVertical ? - CRYINCLUDE_EDITORCOMMON_ARBITRARILY_LARGE_NUMBER : - ( thicknessInPixels * 0.5f ) ), - ( m_isVertical ? thicknessInPixels : ( 3.0f * CRYINCLUDE_EDITORCOMMON_ARBITRARILY_LARGE_NUMBER ) ), - ( m_isVertical ? ( 3.0f * CRYINCLUDE_EDITORCOMMON_ARBITRARILY_LARGE_NUMBER ) : thicknessInPixels ) ); - - setPixelPosition( GetBorderValueInPixels( m_sprite, m_border, aznumeric_cast( m_isVertical ? m_unscaledPixmapSize.width() : m_unscaledPixmapSize.height() ) ) ); - - setFlag( QGraphicsItem::ItemIsMovable, true ); - setFlag( QGraphicsItem::ItemIsSelectable, true ); // This allows using the CTRL key to select multiple manipulators and move them simultaneously. - setFlag( QGraphicsItem::ItemSendsScenePositionChanges, true ); -} - -void SlicerManipulator::SetEdit( SlicerEdit *edit ) -{ - m_edit = edit; -} - -void SlicerManipulator::paint(QPainter* painter, [[maybe_unused]] const QStyleOptionGraphicsItem* option, [[maybe_unused]] QWidget* widget) -{ -#if CRYINCLUDE_EDITORCOMMON_DRAW_SELECTABLE_AREA_OF_SLICERMANIPULATOR - QGraphicsRectItem::paint( painter, option, widget ); -#endif // CRYINCLUDE_EDITORCOMMON_DRAW_SELECTABLE_AREA_OF_SLICERMANIPULATOR - - QPen pen; - pen.setStyle( isSelected() ? Qt::DashLine : Qt::DotLine ); - pen.setWidthF( CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH ); - - // Draw a thin line in the middle of the selectable area. - if( m_isVertical ) - { - float x = aznumeric_cast( ( ( rect().left() + rect().right() ) * 0.5f ) - CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH ); - - pen.setColor( m_color ); - painter->setPen( pen ); - painter->drawLine(aznumeric_cast(x), aznumeric_cast(rect().top()), aznumeric_cast(x), aznumeric_cast(rect().bottom()) ); - - x += CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH; - pen.setColor( Qt::black ); - painter->setPen( pen ); - painter->drawLine(aznumeric_cast(x), aznumeric_cast(rect().top()), aznumeric_cast(x), aznumeric_cast(rect().bottom()) ); - } - else - { - float y = aznumeric_cast( ( ( rect().top() + rect().bottom() ) * 0.5f ) - CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH ); - - pen.setColor( m_color ); - painter->setPen( pen ); - painter->drawLine(aznumeric_cast(rect().left()), aznumeric_cast(y), aznumeric_cast(rect().right()), aznumeric_cast(y) ); - - y += CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_WIDTH; - pen.setColor( Qt::black ); - painter->setPen( pen ); - painter->drawLine(aznumeric_cast(rect().left()), aznumeric_cast(y), aznumeric_cast(rect().right()), aznumeric_cast(y) ); - } -} - -void SlicerManipulator::setPixelPosition(float p) -{ - setPos( ( m_isVertical ? ( p * m_scaledOverUnscaledFactor.x() ) : 0.0f ), - ( m_isVertical ? 0.0f : ( p * m_scaledOverUnscaledFactor.y() ) ) ); -} - -QVariant SlicerManipulator::itemChange(GraphicsItemChange change, const QVariant& value) -{ - if( ( change == ItemPositionChange ) && - scene() ) - { - float totalScaledSizeInPixels = aznumeric_cast( m_isVertical ? m_scaledPixmapSize.width() : m_scaledPixmapSize.height() ); - - float p = clamp_tpl(aznumeric_cast( m_isVertical ? value.toPointF().x() : value.toPointF().y() ), - 0.0f, - totalScaledSizeInPixels ); - - m_edit->setPixelPosition( m_isVertical ? aznumeric_cast( p * m_unscaledOverScaledFactor.x() ) : aznumeric_cast( p * m_unscaledOverScaledFactor.y() ) ); - - SetBorderValue( m_sprite, m_border, p, totalScaledSizeInPixels ); - - return QPointF( ( m_isVertical ? p : 0.0f ), - ( m_isVertical ? 0.0f : p ) ); - } - - return QGraphicsItem::itemChange( change, value ); -} - -void SlicerManipulator::hoverEnterEvent([[maybe_unused]] QGraphicsSceneHoverEvent* event) -{ - setCursor( m_isVertical ? Qt::SizeHorCursor : Qt::SizeVerCursor ); - m_color = Qt::yellow; - update(); -} - -void SlicerManipulator::hoverLeaveEvent([[maybe_unused]] QGraphicsSceneHoverEvent* event) -{ - setCursor(Qt::ArrowCursor); - m_color = Qt::white; - update(); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.h deleted file mode 100644 index 7f4f21506e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerManipulator.h +++ /dev/null @@ -1,58 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_H -#define CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_H - -class SlicerManipulator -: public QGraphicsRectItem -{ -public: - - SlicerManipulator( SpriteBorder border, - QSize& unscaledPixmapSize, - QSize& scaledPixmapSize, - float thicknessInPixels, - ISprite* sprite, - QGraphicsScene* scene ); - - void SetEdit(SlicerEdit* edit); - - void setPixelPosition(float p); - -protected: - - QVariant itemChange(GraphicsItemChange change, const QVariant& value) override; - void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override; - void hoverEnterEvent(QGraphicsSceneHoverEvent* event) override; - void hoverLeaveEvent(QGraphicsSceneHoverEvent* event) override; - -private: - - SpriteBorder m_border; - bool m_isVertical; - QSize m_unscaledPixmapSize; - QSize m_scaledPixmapSize; - ISprite* m_sprite; - QPointF m_unscaledOverScaledFactor; - QPointF m_scaledOverUnscaledFactor; - QColor m_color; - - SlicerEdit* m_edit; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_SLICERMANIPULATOR_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.cpp deleted file mode 100644 index 7ec2ec4c8c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.cpp +++ /dev/null @@ -1,25 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" - -SlicerView::SlicerView(QGraphicsScene* scene, QWidget* parent) -: QGraphicsView( scene, parent ) -{ - setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); - setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff ); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.h deleted file mode 100644 index f2644123ce..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SlicerView.h +++ /dev/null @@ -1,34 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SLICERVIEW_H -#define CRYINCLUDE_EDITORCOMMON_SLICERVIEW_H - -class SlicerView -: public QGraphicsView -{ -public: - - SlicerView(QGraphicsScene* scene, QWidget* parent = nullptr); - -protected: - - // This is intentionally empty. - void scrollContentsBy([[maybe_unused]] int dx, [[maybe_unused]] int dy) override {}; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_SLICERVIEW_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.cpp deleted file mode 100644 index d67936de3f..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.cpp +++ /dev/null @@ -1,175 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" -#include // for Getting the game folder - -//------------------------------------------------------------------------------- - -#define VIEW_WIDTH ( 200 ) -#define VIEW_HEIGHT ( 200 ) -#define MANIPULATOR_THICKNESS_IN_PIXELS ( 24 ) - -//------------------------------------------------------------------------------- - -SpriteBorderEditor::SpriteBorderEditor(const char* path, QWidget* parent) -: QDialog( parent ) -, hasBeenInitializedProperly( true ) -{ - ISprite* sprite = gEnv->pLyShine->LoadSprite( path ); - CRY_ASSERT( sprite ); - - // The layout. - QGridLayout* outerGrid = new QGridLayout(this); - - QGridLayout* innerGrid = new QGridLayout(); - outerGrid->addLayout( innerGrid, 0, 0, 1, 2 ); - - // The scene. - QGraphicsScene* scene( new QGraphicsScene( 0.0f, 0.0f, VIEW_WIDTH, VIEW_HEIGHT, this ) ); - - // The view. - innerGrid->addWidget( new SlicerView( scene, this ), 0, 0, 6, 1 ); - - // The image. - QGraphicsPixmapItem* pixmapItem = nullptr; - QSize unscaledPixmapSize; - QSize scaledPixmapSize; - { - // assets can be in gems as well as in the current project. Qpixmap requires a path to - // the asset and doesn't know about such concepts. So adjust the pathname to something - // that Qpixmap can open. - QString fullPath = Path::GamePathToFullPath(sprite->GetTexturePathname().c_str()); - QPixmap unscaledPixmap(fullPath); - - bool isVertical = ( unscaledPixmap.size().height() > unscaledPixmap.size().width() ); - - // Scale-to-fit, while preserving aspect ratio. - pixmapItem = scene->addPixmap( isVertical ? unscaledPixmap.scaledToHeight( VIEW_HEIGHT ) : unscaledPixmap.scaledToWidth( VIEW_WIDTH ) ); - - unscaledPixmapSize = unscaledPixmap.size(); - scaledPixmapSize = pixmapItem->pixmap().size(); - } - - // Add text fields and manipulators. - { - int row = 0; - - innerGrid->addWidget( new QLabel( QString( "Texture is %1 x %2" ).arg( QString::number( unscaledPixmapSize.width() ), - QString::number( unscaledPixmapSize.height() ) ), - this ), - row++, - 1 ); - - for( SpriteBorder b : SpriteBorder() ) - { - SlicerEdit* edit = new SlicerEdit( b, - unscaledPixmapSize, - sprite ); - - SlicerManipulator* manipulator = new SlicerManipulator( b, - unscaledPixmapSize, - scaledPixmapSize, - MANIPULATOR_THICKNESS_IN_PIXELS, - sprite, - scene ); - - edit->SetManipulator( manipulator ); - manipulator->SetEdit( edit ); - - innerGrid->addWidget( new QLabel( SpriteBorderToString( b ), this ), row, 1 ); - innerGrid->addWidget( edit, row, 2 ); - innerGrid->addWidget( new QLabel( "pixels", this ), row, 3 ); - ++row; - } - } - - // Add buttons. - { - // Save button. - QPushButton* saveButton = new QPushButton( "Save", this ); - QObject::connect( saveButton, - &QPushButton::clicked, this, - [ this, sprite ]([[maybe_unused]] bool checked ) - { - // Sanitize values. - // - // This is the simplest way to sanitize the - // border values. Otherwise, we need to prevent - // flipping the manipulators in the UI. - { - ISprite::Borders b = sprite->GetBorders(); - - if( b.m_top > b.m_bottom ) - { - std::swap( b.m_top, b.m_bottom ); - } - - if( b.m_left > b.m_right ) - { - std::swap( b.m_left, b.m_right ); - } - - sprite->SetBorders( b ); - } - - QString fullPath = Path::GamePathToFullPath(sprite->GetPathname().c_str()); - bool result = sprite->SaveToXml(fullPath.toUtf8().data()); - - if (result) - { - close(); - } - else - { - QMessageBox box(QMessageBox::Critical, - "Error", - "Unable to save file", - QMessageBox::Ok); - box.exec(); - } - } ); - outerGrid->addWidget( saveButton, 1, 0 ); - - // Cancel button. - ISprite::Borders originalBorders = sprite->GetBorders(); - QPushButton* cancelButton = new QPushButton( "Cancel", this ); - QObject::connect( cancelButton, - &QPushButton::clicked, this, - [ this, sprite, originalBorders ]([[maybe_unused]] bool checked ) - { - // Restore original borders. - sprite->SetBorders( originalBorders ); - - close(); - } ); - outerGrid->addWidget( cancelButton, 1, 1 ); - } - - setWindowTitle( "SpriteBorderEditor" ); - setModal( true ); - setWindowModality( Qt::ApplicationModal ); - - layout()->setSizeConstraint( QLayout::SetFixedSize ); -} - -bool SpriteBorderEditor::GetHasBeenInitializedProperly() -{ - return hasBeenInitializedProperly; -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.h deleted file mode 100644 index b670d75af8..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditor.h +++ /dev/null @@ -1,41 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITOR_H -#define CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITOR_H - -#if !defined(Q_MOC_RUN) -#include -#endif - -class SpriteBorderEditor -: public QDialog -{ - Q_OBJECT - -public: - - SpriteBorderEditor(const char* path, QWidget* parent = nullptr); - - bool GetHasBeenInitializedProperly(); - -private: - - bool hasBeenInitializedProperly; -}; - -#endif // CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITOR_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.cpp b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.cpp deleted file mode 100644 index 305f9dafa7..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.cpp +++ /dev/null @@ -1,120 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "SpriteBorderEditorCommon.h" - -bool IsBorderVertical(SpriteBorder border) -{ - return ( ( border == SpriteBorder::Left ) || - ( border == SpriteBorder::Right ) ); -} - -float GetBorderValueInPixels(ISprite* sprite, SpriteBorder b, float totalSizeInPixels) -{ - // IMPORTANT: We CAN'T replace totalSizeInPixels with - // sprite->GetTexture()->GetWidth()/GetHeight() because - // it DOESN'T return the original texture file's size. - - ISprite::Borders sb = sprite->GetBorders(); - - float *f = nullptr; - - if( b == SpriteBorder::Top ) - { - f = &sb.m_top; - } - else if( b == SpriteBorder::Bottom ) - { - f = &sb.m_bottom; - } - else if( b == SpriteBorder::Left ) - { - f = &sb.m_left; - } - else if( b == SpriteBorder::Right ) - { - f = &sb.m_right; - } - else - { - CRY_ASSERT( 0 ); - f = nullptr; - } - - return ( *f * totalSizeInPixels ); -} - -void SetBorderValue(ISprite* sprite, SpriteBorder b, float pixelPosition, float totalSizeInPixels) -{ - // IMPORTANT: We CAN'T replace totalSizeInPixels with - // sprite->GetTexture()->GetWidth()/GetHeight() because - // it DOESN'T return the original texture file's size. - - ISprite::Borders sb = sprite->GetBorders(); - - float *f = nullptr; - - if( b == SpriteBorder::Top ) - { - f = &sb.m_top; - } - else if( b == SpriteBorder::Bottom ) - { - f = &sb.m_bottom; - } - else if( b == SpriteBorder::Left ) - { - f = &sb.m_left; - } - else if( b == SpriteBorder::Right ) - { - f = &sb.m_right; - } - else - { - CRY_ASSERT( 0 ); - f = nullptr; - } - - *f = ( pixelPosition / totalSizeInPixels ); - sprite->SetBorders( sb ); -} - -const char* SpriteBorderToString(SpriteBorder b) -{ - if( b == SpriteBorder::Top ) - { - return "Top"; - } - else if( b == SpriteBorder::Bottom ) - { - return "Bottom"; - } - else if( b == SpriteBorder::Left ) - { - return "Left"; - } - else if( b == SpriteBorder::Right ) - { - return "Right"; - } - else - { - CRY_ASSERT( 0 ); - return "UNKNOWN"; - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.h deleted file mode 100644 index de85c71e5a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/SpriteBorderEditorCommon.h +++ /dev/null @@ -1,78 +0,0 @@ -//------------------------------------------------------------------------------- -// Copyright (C) Amazon.com, Inc. or its affiliates. -// All Rights Reserved. -// -// Licensed under the terms set out in the LICENSE.HTML file included at the -// root of the distribution; you may not use this file except in compliance -// with the License. -// -// Do not remove or modify this notice or the LICENSE.HTML file. This file -// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, -// either express or implied. See the License for the specific language -// governing permissions and limitations under the License. -//------------------------------------------------------------------------------- - -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITORCOMMON_H -#define CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITORCOMMON_H - -#include // required to be included before platform.h -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class SlicerEdit; -class SlicerManipulator; -class SlicerView; -class SpriteBorderEditor; - -enum class SpriteBorder -{ - Top, - Bottom, - Left, - Right -}; - -// This allows iterating over an enum class. -#define ADD_ENUM_CLASS_ITERATION_OPERATORS( CLASS_NAME, FIRST_VALUE, LAST_VALUE ) \ - \ - inline CLASS_NAME operator++(CLASS_NAME &m){ return m = (CLASS_NAME)(std::underlying_type::type(m) + 1); } \ - inline CLASS_NAME operator*(CLASS_NAME m){ return m; } \ - inline CLASS_NAME begin([[maybe_unused]] CLASS_NAME m){ return FIRST_VALUE; } \ - inline CLASS_NAME end([[maybe_unused]] CLASS_NAME m){ return (CLASS_NAME)(std::underlying_type::type(LAST_VALUE) + 1); } - -ADD_ENUM_CLASS_ITERATION_OPERATORS( SpriteBorder, - SpriteBorder::Top, - SpriteBorder::Right ); - -#include "SlicerEdit.h" -#include "SlicerManipulator.h" -#include "SlicerView.h" -#include "SpriteBorderEditor.h" - -bool IsBorderVertical(SpriteBorder border); -float GetBorderValueInPixels(ISprite* sprite, SpriteBorder b, float totalSizeInPixels); -void SetBorderValue(ISprite* sprite, SpriteBorder b, float pixelPosition, float totalSizeInPixels); -const char* SpriteBorderToString(SpriteBorder b); - -#endif // CRYINCLUDE_EDITORCOMMON_SPRITEBORDEREDITORCOMMON_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Strings.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Strings.h deleted file mode 100644 index 5f52145f41..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Strings.h +++ /dev/null @@ -1,29 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_STRINGS_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_STRINGS_H -#pragma once - -#ifndef SERIALIZATION_STANDALONE -#include - -typedef CryStringT string; -typedef CryStringT wstring; -#else -#include -using std::string; -using std::wstring; -#endif - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_STRINGS_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Unicode.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Unicode.h deleted file mode 100644 index 71f9830d0e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/Unicode.h +++ /dev/null @@ -1,24 +0,0 @@ -/** - * wWidgets - Lightweight UI Toolkit. - * Copyright (C) 2009-2011 Evgeny Andreeshchev - * Alexander Kotliar - * - * This code is distributed under the MIT License: - * http://www.opensource.org/licenses/MIT - */ -// Modifications copyright Amazon.com, Inc. or its affiliates - -#ifndef CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_UNICODE_H -#define CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_UNICODE_H -#pragma once - -#include "Strings.h" -#include - -string fromWideChar(const wchar_t* wideCharString); -wstring toWideChar(const char* multiByteString); -wstring fromANSIToWide(const char* ansiString); -string toANSIFromWide(const wchar_t* wstr); - - -#endif // CRYINCLUDE_EDITORCOMMON_QPROPERTYTREE_UNICODE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ValidatorBlock.h b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ValidatorBlock.h deleted file mode 100644 index db1480225c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/ValidatorBlock.h +++ /dev/null @@ -1,172 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include "Strings.h" -#include -#include -#include - -enum ValidatorEntryType -{ - VALIDATOR_ENTRY_WARNING, - VALIDATOR_ENTRY_ERROR -}; - -struct ValidatorEntry -{ - const void* handle; - Serialization::TypeID typeId; - - ValidatorEntryType type; - string message; - - bool operator<(const ValidatorEntry& rhs) const - { - if (handle != rhs.handle) - { - return handle < rhs.handle; - } - return typeId < rhs.typeId; - } - - ValidatorEntry(ValidatorEntryType type, const void* handle, const Serialization::TypeID& typeId, const char* message) - : type(type) - , handle(handle) - , message(message) - , typeId(typeId) - { - } - - ValidatorEntry() - : handle() - , type(VALIDATOR_ENTRY_WARNING) - { - } -}; -typedef std::vector ValidatorEntries; - -class ValidatorBlock -{ -public: - ValidatorBlock() - : m_enabled(false) - { - } - - void Clear() - { - m_entries.clear(); - m_used.clear(); - } - - void AddEntry(const ValidatorEntry& entry) - { - ValidatorEntries::iterator it = std::upper_bound(m_entries.begin(), m_entries.end(), entry); - m_used.insert(m_used.begin() + (it - m_entries.begin()), false); - m_entries.insert(it, entry); - m_enabled = true; - } - - bool IsEnabled() const { return m_enabled; } - - const ValidatorEntry* GetEntry(int index, int count) const - { - if (size_t(index) >= m_entries.size()) - { - return 0; - } - if (size_t(index + count) > m_entries.size()) - { - return 0; - } - return &m_entries[index]; - } - - bool FindHandleEntries(int* outIndex, int* outCount, const void* handle, Serialization::TypeID& typeId) - { - if (handle == 0) - { - return false; - } - ValidatorEntry e; - e.handle = handle; - e.typeId = typeId; - ValidatorEntries::iterator begin = std::lower_bound(m_entries.begin(), m_entries.end(), e); - ValidatorEntries::iterator end = std::upper_bound(m_entries.begin(), m_entries.end(), e); - if (begin != end) - { - *outIndex = int(begin - m_entries.begin()); - *outCount = int(end - begin); - return true; - } - return false; - } - - void MarkAsUsed(int start, int count) - { - if (start < 0) - { - return; - } - if (start + count > m_entries.size()) - { - return; - } - for (int i = start; i < start + count; ++i) - { - m_used[i] = true; - } - } - - void MergeUnusedItemsWithRootItems(int* firstUnusedItem, int* count, const void* newHandle, Serialization::TypeID& typeId) - { - size_t numItems = m_used.size(); - for (size_t i = 0; i < numItems; ++i) - { - if (m_entries[i].handle == newHandle) - { - m_entries.push_back(m_entries[i]); - m_used.push_back(true); - m_entries[i].typeId = Serialization::TypeID(); - } - if (!m_used[i]) - { - m_entries.push_back(m_entries[i]); - m_used.push_back(true); - m_entries.back().handle = newHandle; - m_entries.back().typeId = typeId; - } - } - *firstUnusedItem = (int)numItems; - *count = int(m_entries.size() - numItems); - } - - bool ContainsErrors() const - { - for (size_t i = 0; i < m_entries.size(); ++i) - { - if (m_entries[i].type == VALIDATOR_ENTRY_ERROR) - { - return true; - } - } - return false; - } - -private: - ValidatorEntries m_entries; - std::vector m_used; - bool m_enabled; -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/error.xpm b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/error.xpm deleted file mode 100644 index c26942bda9..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/error.xpm +++ /dev/null @@ -1,126 +0,0 @@ -/* XPM */ -static const char * error_xpm[] = { -"16 16 107 2", -" c None", -". c #F98267", -"+ c #F78065", -"@ c #F57E63", -"# c #F37C61", -"$ c #F98268", -"% c #EE836E", -"& c #F4A692", -"* c #F8B4A0", -"= c #F3A691", -"- c #E97D68", -"; c #EB7359", -"> c #F88166", -", c #F19784", -"' c #FBBDA9", -") c #F8A38A", -"! c #F6896B", -"~ c #F8A289", -"{ c #FABCA8", -"] c #EC927F", -"^ c #E46C52", -"/ c #F67F65", -"( c #F09783", -"_ c #F58263", -": c #FFFFFF", -"< c #F37E61", -"[ c #F37C60", -"} c #F9B9A6", -"| c #EA8D7B", -"1 c #DE644A", -"2 c #EC816C", -"3 c #F58162", -"4 c #F48062", -"5 c #F17A5F", -"6 c #F0785F", -"7 c #EF765D", -"8 c #F8B5A5", -"9 c #DD705D", -"0 c #F8A188", -"a c #EE735C", -"b c #EC705B", -"c c #F19382", -"d c #EC9889", -"e c #D2583E", -"f c #ED765B", -"g c #F8B6A1", -"h c #F48467", -"i c #EB6E5A", -"j c #EA6C59", -"k c #E96F5F", -"l c #F1A89B", -"m c #CE533A", -"n c #E97157", -"o c #F7B3A0", -"p c #F28065", -"q c #FAD9D3", -"r c #E86958", -"s c #E76757", -"t c #E76C5D", -"u c #F1A599", -"v c #CA4F35", -"w c #E56D52", -"x c #F09F8E", -"y c #F49984", -"z c #F19D90", -"A c #F3AFA6", -"B c #E66556", -"C c #E56255", -"D c #EB897D", -"E c #E79185", -"F c #C64A31", -"G c #E07360", -"H c #F7B3A4", -"I c #E36154", -"J c #E25F53", -"K c #F2A99F", -"L c #D16150", -"M c #DA6046", -"N c #E68878", -"O c #F5B0A3", -"P c #ED9289", -"Q c #EC9288", -"R c #E15D52", -"S c #DD7D6F", -"T c #C0442B", -"U c #D3593F", -"V c #E38475", -"W c #F4ACA1", -"X c #EC8B7F", -"Y c #E4675C", -"Z c #E3665B", -"` c #EA877D", -" . c #F1A89F", -".. c #DD7C6F", -"+. c #BF4329", -"@. c #CC5238", -"#. c #D46452", -"$. c #E79084", -"%. c #EEA095", -"&. c #ED9F95", -"*. c #E58E83", -"=. c #CE5D4C", -"-. c #BD4128", -";. c #C4482F", -">. c #C2462C", -",. c #C0442A", -"'. c #BE4228", -" ", -" . + @ # ", -" $ % & * * = - ; ", -" > , ' ) ! ! ~ { ] ^ ", -" / ( ' _ _ : : < [ } | 1 ", -" 2 ' _ 3 4 : : 5 6 7 8 9 ", -" 5 = 0 4 < [ : : 7 a b c d e ", -" f g h [ 5 6 : : b i j k l m ", -" n o p 6 7 a q : j r s t u v ", -" w x y a b i z A s B C D E F ", -" G H i j r : : C I J K L ", -" M N O s B P Q J R K S T ", -" U V W X Y Z ` ...+. ", -" @.#.$.%.&.*.=.-. ", -" ;.>.,.'. ", -" "}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_open.xpm b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_open.xpm deleted file mode 100644 index cd355e8dd4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_open.xpm +++ /dev/null @@ -1,142 +0,0 @@ -/* XPM */ -static const char * file_open_xpm[] = { -"16 16 123 2", -" c None", -". c #E0C259", -"+ c #E2C361", -"@ c #E3C463", -"# c #E3C462", -"$ c #E0C056", -"% c #DBB53C", -"& c #FEFEFD", -"* c #FFFFFE", -"= c #FFFEFE", -"- c #FFFEFD", -"; c #FBF7EA", -"> c #E5C86E", -", c #E4C96F", -"' c #E7CF7D", -") c #E8D084", -"! c #DCB441", -"~ c #FEFCF7", -"{ c #F8E48E", -"] c #F5DE91", -"^ c #F5E09F", -"/ c #F6E1AC", -"( c #FEFBEF", -"_ c #FEFDF4", -": c #FEFCF3", -"< c #FEFCF1", -"[ c #FEFBEE", -"} c #FFFDFA", -"| c #E0BC58", -"1 c #DCAE40", -"2 c #FDFAF1", -"3 c #F5DE94", -"4 c #F4DC93", -"5 c #F2D581", -"6 c #EDCA6A", -"7 c #EACB6C", -"8 c #EFD385", -"9 c #EFD280", -"0 c #EFD07A", -"a c #EECF76", -"b c #EECF72", -"c c #FBF7E9", -"d c #DCB23E", -"e c #DBAD39", -"f c #FBF6E8", -"g c #EFD494", -"h c #EECE88", -"i c #E9C173", -"j c #F6E9C9", -"k c #FEFCF2", -"l c #FEFCF0", -"m c #DBAE3C", -"n c #DBA83B", -"o c #FFFDF8", -"p c #FFFDF6", -"q c #FFFCF5", -"r c #FCF6D8", -"s c #F8E694", -"t c #F7E385", -"u c #F6DF76", -"v c #F5DB68", -"w c #F4D85C", -"x c #FCF4D7", -"y c #DBA73B", -"z c #DBA33B", -"A c #FEFCF6", -"B c #FCF2C8", -"C c #FBEFB9", -"D c #FAECAC", -"E c #F9E89C", -"F c #F7E38B", -"G c #F6E07C", -"H c #F6DC6C", -"I c #F5D95D", -"J c #F4D64F", -"K c #F3D344", -"L c #FCF3D0", -"M c #DBA23B", -"N c #DB9D3C", -"O c #FDFAF2", -"P c #FAEDB3", -"Q c #F9E9A4", -"R c #F8E695", -"S c #F7E285", -"T c #F6DE76", -"U c #F5DB65", -"V c #F4D757", -"W c #F3D449", -"X c #F2D13B", -"Y c #F1CE30", -"Z c #FBF2CC", -"` c #DB9B3B", -" . c #DB973B", -".. c #FEFAEF", -"+. c #F9E9A1", -"@. c #F8E591", -"#. c #F7E181", -"$. c #F6DE72", -"%. c #F5DA63", -"&. c #F4D754", -"*. c #F3D347", -"=. c #F2D039", -"-. c #F1CD2E", -";. c #F0CB26", -">. c #FBF2CA", -",. c #DD9947", -"'. c #FAF1DE", -"). c #F4DDA8", -"!. c #F4DB9E", -"~. c #F3DA96", -"{. c #F3D88E", -"]. c #F3D786", -"^. c #F2D47F", -"/. c #F2D379", -"(. c #F1D272", -"_. c #F1D06C", -":. c #F1CF69", -"<. c #F8EAC2", -"[. c #DB953F", -"}. c #DB913E", -"|. c #D98C34", -"1. c #D98B34", -"2. c #DA8F39", -" ", -" ", -" . + @ @ @ # $ ", -" % & * = - * ; > , , , ' ) ", -" ! ~ { ] ^ / ( _ : < ( [ } | ", -" 1 2 3 4 5 6 7 8 9 0 a b c d ", -" e f g h i j k : k l ( [ * m ", -" n * o p q : r s t u v w x y ", -" z A B C D E F G H I J K L M ", -" N O P Q R S T U V W X Y Z ` ", -" N O P Q R S T U V W X Y Z ` ", -" ...+.@.#.$.%.&.*.=.-.;.>. . ", -" ,.'.).!.~.{.].^./.(._.:.<.[. ", -" ,.}.|.|.|.|.|.|.|.|.1.2. ", -" ", -" "}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_save.xpm b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_save.xpm deleted file mode 100644 index 0f44467069..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/file_save.xpm +++ /dev/null @@ -1,168 +0,0 @@ -/* XPM */ -static const char * file_save_xpm[] = { -"16 16 149 2", -" c None", -". c #8DABD9", -"+ c #5E89C9", -"@ c #4375C0", -"# c #3A6EBD", -"$ c #376CBB", -"% c #366BBB", -"& c #366ABB", -"* c #396CBC", -"= c #3B6EBD", -"- c #3A6DBB", -"; c #4474BF", -"> c #658DC9", -", c #85A5D6", -"' c #D1E0F6", -") c #D1E0F7", -"! c #F8FBFE", -"~ c #F7FBFE", -"{ c #F6F9FD", -"] c #F0F5FC", -"^ c #EDF2FB", -"/ c #F7FAFD", -"( c #EBF1FB", -"_ c #DFE9F8", -": c #BED1EC", -"< c #6A92CD", -"[ c #5582C6", -"} c #D1DFF6", -"| c #80AAE9", -"1 c #F6FAFE", -"2 c #F6FAFD", -"3 c #648CC8", -"4 c #EEF3FB", -"5 c #F2F6FC", -"6 c #F1F6FC", -"7 c #E2ECF9", -"8 c #DBE7F8", -"9 c #BAD0EE", -"0 c #BDD0EC", -"a c #4374BD", -"b c #4274C0", -"c c #D0DFF6", -"d c #7EA8E8", -"e c #E9F1FA", -"f c #E8F0FA", -"g c #DDE8F8", -"h c #DBE6F7", -"i c #7AA3E1", -"j c #C3D5EF", -"k c #366AB7", -"l c #CCDDF5", -"m c #7EA8E7", -"n c #668DC9", -"o c #E9F0FA", -"p c #F8FAFE", -"q c #EFF4FC", -"r c #DFE9F9", -"s c #DBE7F7", -"t c #D9E5F7", -"u c #78A2E0", -"v c #A9C2E7", -"w c #3568B6", -"x c #C9DCF4", -"y c #7DA7E7", -"z c #E1ECF9", -"A c #E3EDF9", -"B c #EEF4FC", -"C c #F3F7FD", -"D c #E5EDFA", -"E c #D8E5F6", -"F c #77A0DE", -"G c #A4BEE4", -"H c #3467B4", -"I c #C7D9F4", -"J c #7DA6E6", -"K c #678EC9", -"L c #6C92CB", -"M c #6990CA", -"N c #658CC8", -"O c #749CDA", -"P c #9FBAE1", -"Q c #3466B3", -"R c #C5D8F2", -"S c #7BA4E3", -"T c #7AA3E3", -"U c #7AA4E3", -"V c #7BA4E2", -"W c #7BA3E2", -"X c #79A2E1", -"Y c #77A0DF", -"Z c #769FDE", -"` c #749EDD", -" . c #729CDB", -".. c #749DDC", -"+. c #9AB5DD", -"@. c #3465B1", -"#. c #BED2F0", -"$. c #7AA3E2", -"%. c #7BA3E1", -"&. c #779FDE", -"*. c #769FDD", -"=. c #729BD9", -"-. c #7199D8", -";. c #7099D6", -">. c #8EABD5", -",. c #3363AD", -"'. c #366ABA", -"). c #BBD0EF", -"!. c #7AA2E2", -"~. c #6D96D3", -"{. c #8AA7D2", -"]. c #3262AB", -"^. c #386BBB", -"/. c #B8CEEF", -"(. c #F7FAFE", -"_. c #88C062", -":. c #6A93CF", -"<. c #84A3CE", -"[. c #3261AA", -"}. c #386CBB", -"|. c #B6CCEE", -"1. c #7AA2E1", -"2. c #C2DCBF", -"3. c #6890CD", -"4. c #819ECC", -"5. c #3261A8", -"6. c #386CBA", -"7. c #B3CAED", -"8. c #7AA2E0", -"9. c #658DCA", -"0. c #7C9BC9", -"a. c #3261A7", -"b. c #4F7DC3", -"c. c #ADC6EB", -"d. c #ADC5EA", -"e. c #7C9AC8", -"f. c #7998C7", -"g. c #406BAD", -"h. c #7095CD", -"i. c #4273BD", -"j. c #3568B7", -"k. c #3568B5", -"l. c #3466B2", -"m. c #3364AE", -"n. c #3263AC", -"o. c #3262AA", -"p. c #3261A9", -"q. c #3160A8", -"r. c #3C69AB", -" . + @ # $ % & * = - ; > ", -" , ' ) ! ~ { ] ^ { / ( _ : < ", -" [ } | 1 2 3 4 5 ! 6 7 8 9 0 a ", -" b c d 6 6 3 e / { f g h i j k ", -" # l m f f n o p q r s t u v w ", -" $ x y z z A B C D s t E F G H ", -" % I J 3 > K L M N 3 3 3 O P Q ", -" & R S T U V W X Y Z ` ...+.@.", -" & #.$.$.i W %.&.*...=.-.;.>.,.", -" '.).!.! ! ! ! ! ! ! ! ! ~.{.].", -" ^./.X (._._._._._._._.{ :.<.[.", -" }.|.1.(.2.2.2.2.2.2.2.{ 3.4.5.", -" 6.7.8.(._._._._._._._.{ 9.0.a.", -" b.c.d.! ! ! ! ! ! ! ! ! e.f.g.", -" h.i.j.k.H l.m.n.o.p.q.a.r. ", -" "}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/gear.xpm b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/gear.xpm deleted file mode 100644 index edebbc4367..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/gear.xpm +++ /dev/null @@ -1,24 +0,0 @@ -/* XPM */ -static const char * gear_xpm[] = { -/* columns rows colors chars-per-pixel */ -"16 16 2 1", -" c #000000", -". c None", -/* pixels */ -"....... .......", -"....... .......", -".. .. .. ..", -".. ..", -"... .... ...", -"... ...... ...", -".. ........ ..", -" ........ ", -" ........ ", -".. ........ ..", -"... ...... ...", -"... .... ...", -".. ..", -".. .. .. ..", -"....... .......", -"....... ......." -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/wWidgets_NOTICES.txt b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/wWidgets_NOTICES.txt deleted file mode 100644 index 5e8ea4b43e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/wWidgets_NOTICES.txt +++ /dev/null @@ -1,49 +0,0 @@ -Portions based on WWidgets and Yasli Serialization Library - -wWidgets - Lightweight UI Toolkit. -Copyright (C) 2009-2011 Evgeny Andreeshchev - Alexander Kotliar - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - - -Yasli Serialization Library -Copyright (c) 2007 Eugene Andreeshchev - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/warning.xpm b/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/warning.xpm deleted file mode 100644 index 84626cbd9c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QPropertyTree/warning.xpm +++ /dev/null @@ -1,134 +0,0 @@ -/* XPM */ -static const char * warning_xpm[] = { -"16 16 115 2", -" c None", -". c #EBBC3C", -"+ c #EABA3A", -"@ c #F1D485", -"# c #F0D182", -"$ c #E7B537", -"% c #E9BA3A", -"& c #FDFAF1", -"* c #FAEFD5", -"= c #E6B235", -"- c #E9B93A", -"; c #F2D894", -"> c #FEFCF3", -", c #FEFAE7", -"' c #F0D38F", -") c #E3AC31", -"! c #E8B738", -"~ c #FFFDF9", -"{ c #F9E994", -"] c #FAEB9E", -"^ c #FEFAEC", -"/ c #E1A92F", -"( c #F4DFA9", -"_ c #FDF9ED", -": c #D6A33E", -"< c #FCF5D4", -"[ c #F1D7A2", -"} c #DEA32B", -"| c #E6B436", -"1 c #EDC871", -"2 c #FFFEF9", -"3 c #F4DC5E", -"4 c #D5A23E", -"5 c #F4D95C", -"6 c #FEFBED", -"7 c #E5BB68", -"8 c #D99924", -"9 c #F7EAC8", -"0 c #FDFAE6", -"a c #F4DA5D", -"b c #D5A13D", -"c c #F2D757", -"d c #FCF3C7", -"e c #F4E3C0", -"f c #E6B336", -"g c #F0D28C", -"h c #FEFBEA", -"i c #F8E694", -"j c #F4DA5C", -"k c #DDB147", -"l c #F2D756", -"m c #F5DB5C", -"n c #FDF8DE", -"o c #E7C07D", -"p c #D48E1D", -"q c #E5B134", -"r c #FEFBF3", -"s c #FBF2C3", -"t c #F6DC5C", -"u c #F6DF64", -"v c #EBCB57", -"w c #F2D655", -"x c #F5D954", -"y c #F8E794", -"z c #FBF4E3", -"A c #D08717", -"B c #E5B034", -"C c #F1D79D", -"D c #FDF9E7", -"E c #F8E58B", -"F c #F6DB5A", -"G c #F4DA5B", -"H c #F2D654", -"I c #F5D852", -"J c #F4D650", -"K c #FCF6D8", -"L c #E5BF88", -"M c #C9790E", -"N c #E3AD31", -"O c #E8BF62", -"P c #FEFCF4", -"Q c #FAEFB5", -"R c #F5DA58", -"S c #F3D857", -"T c #F2D758", -"U c #F2D658", -"V c #F4D957", -"W c #F5D851", -"X c #F4D74E", -"Y c #F6DA62", -"Z c #D29344", -"` c #C36D06", -" . c #F5E3BE", -".. c #FEFBEF", -"+. c #FEFBEE", -"@. c #FEFCEF", -"#. c #FEFBEC", -"$. c #FEFCF2", -"%. c #EBCEAB", -"&. c #C16803", -"*. c #E2AA2F", -"=. c #E0A72D", -"-. c #DFA42B", -";. c #DDA129", -">. c #DC9E27", -",. c #DA9B25", -"'. c #D99823", -"). c #D69320", -"!. c #D38C1B", -"~. c #CF8516", -"{. c #CC7E11", -"]. c #C9770D", -"^. c #C67109", -"/. c #C36C06", -"(. c #BF6400", -" ", -" . + ", -" . @ # $ ", -" % & * = ", -" - ; > , ' ) ", -" ! ~ { ] ^ / ", -" ! ( _ : : < [ } ", -" | 1 2 3 4 4 5 6 7 8 ", -" | 9 0 a b b c d e 8 ", -" f g h i j k b l m n o p ", -" q r s t j u v w x y z A ", -" B C D E F G b b H I J K L M ", -"N O P Q R R S T U V W X Y h Z ` ", -"N .P ..+.+.@.@...+.6 6 #.$.%.&.", -"*.=.-.;.>.,.'.).!.~.{.].^./.&.(.", -" "}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp b/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp deleted file mode 100644 index 36f9511e60..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.cpp +++ /dev/null @@ -1,913 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include "QViewport.h" -#include "QViewportEvents.h" -#include "QViewportConsumer.h" -#include "QViewportSettings.h" -#include "Serialization.h" - -#include -#include -#include - -#include - -// Class to implement the WindowRequestBus::Handler instead of the QViewport class. -// This is to bypass a link warning that occurs in unity builds if EditorCommon dll -// is linked along with a gem that also implements WindowRequestBus::Handler. The -// issue is that QViewport has a dllexport so it causes duplicate code to be linked -// in and a warning that there will be two of the same symbol in memory -class QViewportRequests - : public AzFramework::WindowRequestBus::Handler -{ -public: - QViewportRequests(QViewport& viewport) - : m_viewport(viewport) - { - } - - ~QViewportRequests() override - { - AzFramework::WindowRequestBus::Handler::BusDisconnect(); - } - - // WindowRequestBus::Handler... - void SetWindowTitle(const AZStd::string& title) override - { - m_viewport.SetWindowTitle(title); - } - - AzFramework::WindowSize GetClientAreaSize() const override - { - return m_viewport.GetClientAreaSize(); - } - - void ResizeClientArea(AzFramework::WindowSize clientAreaSize) override - { - m_viewport.ResizeClientArea(clientAreaSize); - } - - bool GetFullScreenState() const override - { - return m_viewport.GetFullScreenState(); - } - - void SetFullScreenState(bool fullScreenState) override - { - m_viewport.SetFullScreenState(fullScreenState); - } - - bool CanToggleFullScreenState() const override - { - return m_viewport.CanToggleFullScreenState(); - } - - void ToggleFullScreenState() override - { - m_viewport.ToggleFullScreenState(); - } - -private: - QViewport& m_viewport; -}; - -struct QViewport::SPreviousContext -{ - CCamera renderCamera; - CCamera systemCamera; - int width; - int height; - HWND window; - bool isMainViewport; -}; - -struct QViewport::SPrivate -{ - CDLight m_VPLight0; - CDLight m_sun; -}; - -QViewport::QViewport(QWidget* parent, StartupMode startupMode) - : QWidget(parent) - , m_renderContextCreated(false) - , m_updating(false) - , m_width(0) - , m_height(0) - , m_fastMode(false) - , m_slowMode(false) - , m_lastTime(0) - , m_lastFrameTime(0.0f) - , m_averageFrameTime(0.0f) - , m_sceneDimensions(1.0f, 1.0f, 1.0f) - , m_creatingRenderContext(false) - , m_timer(0) - , m_cameraSmoothPosRate(0) - , m_cameraSmoothRotRate(0) - , m_settings(new SViewportSettings()) - , m_state(new SViewportState()) - , m_useArrowsForNavigation(true) - , m_mouseMovementsSinceLastFrame(0) - , m_private(new SPrivate()) - , m_cameraControlMode(CameraControlMode::NONE) -{ - m_viewportRequests = AZStd::make_unique(*this); - - if (startupMode & StartupMode_Immediate) - Startup(); -} - -void QViewport::Startup() -{ - m_frameTimer = new QElapsedTimer(); - - m_camera.reset(new CCamera()); - ResetCamera(); - - m_mousePressPos = QCursor::pos(); - - UpdateBackgroundColor(); - - setUpdatesEnabled(false); - setMouseTracking(true); - m_LightRotationRadian = 0; - m_frameTimer->start(); -} - -QViewport::~QViewport() -{ - m_viewportRequests.reset(); -} - -void QViewport::UpdateBackgroundColor() -{ - QPalette pal(palette()); - pal.setColor(QPalette::Window, QColor(m_settings->background.topColor.r, - m_settings->background.topColor.g, - m_settings->background.topColor.b, - m_settings->background.topColor.a)); - setPalette(pal); - setAutoFillBackground(true); -} - -bool QViewport::ScreenToWorldRay(Ray* ray, int x, int y) -{ - AZ_UNUSED(ray); - AZ_UNUSED(x); - AZ_UNUSED(y); - return false; -} - -QPoint QViewport::ProjectToScreen(const Vec3&) -{ - return QPoint(0, 0); -} - -void QViewport::LookAt(const Vec3& target, float radius, bool snap) -{ - QuatT cameraTarget = m_state->cameraTarget; - CreateLookAt(target, radius, cameraTarget); - CameraMoved(cameraTarget, snap); -} - -int QViewport::Width() const -{ - return rect().width(); -} - -int QViewport::Height() const -{ - return rect().height(); -} - -void QViewport::Serialize(IArchive& ar) -{ - if (!ar.IsEdit()) - { - ar(m_state->cameraTarget, "cameraTarget", "Camera Target"); - } -} - -struct AutoBool -{ - AutoBool(bool* value) - : m_value(value) - { - * m_value = true; - } - - ~AutoBool() - { - * m_value = false; - } - - bool* m_value; -}; - -void QViewport::Update() -{ - int64 time = m_frameTimer->elapsed(); - if (m_lastTime == 0) - { - m_lastTime = time; - } - m_lastFrameTime = (time - m_lastTime) * 0.001f; - m_lastTime = time; - if (m_averageFrameTime == 0.0f) - { - m_averageFrameTime = m_lastFrameTime; - } - else - { - m_averageFrameTime = 0.01f * m_lastFrameTime + 0.99f * m_averageFrameTime; - } -} - -void QViewport::CaptureMouse() -{ - grabMouse(); -} - -void QViewport::ReleaseMouse() -{ - releaseMouse(); -} - -void QViewport::SetForegroundUpdateMode([[maybe_unused]] bool foregroundUpdate) -{ - //m_timer->setInterval(foregroundUpdate ? 2 : 50); -} - -CCamera* QViewport::Camera() const -{ - return m_camera.get(); -} - -void QViewport::SetSceneDimensions(const Vec3& size) -{ - m_sceneDimensions = size; -} - -const SViewportSettings& QViewport::GetSettings() const -{ - return *m_settings; -} - -const SViewportState& QViewport::GetState() const -{ - return *m_state; -} - -void QViewport::SetSize(const QSize& size) -{ - m_width = size.width(); - m_height = size.height(); -} - -float QViewport::GetLastFrameTime() -{ - return m_lastFrameTime; -} - - -void QViewport::ProcessMouse() -{ - QPoint point = mapFromGlobal(QCursor::pos()); - - if (point == m_mousePressPos) - { - return; - } - - if (m_cameraControlMode == CameraControlMode::ZOOM) - { - if (!(m_settings->camera.transformRestraint & eCameraTransformRestraint_Zoom)) - { - float speedScale = CalculateMoveSpeed(m_fastMode, m_slowMode, true); - - // Zoom. - QuatT qt = m_state->cameraTarget; - Vec3 ydir = qt.GetColumn1().GetNormalized(); - Vec3 pos = qt.t; - pos = pos - 0.2f * ydir * aznumeric_cast(m_mousePressPos.y() - point.y()) * speedScale; - qt.t = pos; - CameraMoved(qt, false); - - // Check to see if the orbit target is behind the camera's view - // position - Vec3 target = m_state->orbitTarget; - Vec3 at = target - pos; - float isAlmostBehind = at * ydir; - if (isAlmostBehind < 0.01f) - { - // Force the orbit target to be slightly in front of the view - // position - m_state->orbitRadius = 0.01f; - m_state->orbitTarget = qt.t + ydir * 0.01f; - } - else - { - m_state->orbitRadius = at.GetLength(); - } - - AzQtComponents::SetCursorPos(mapToGlobal(m_mousePressPos)); - } - } - else if (m_cameraControlMode == CameraControlMode::ROTATE) - { - if (!(m_settings->camera.transformRestraint & eCameraTransformRestraint_Rotation)) - { - Ang3 angles(aznumeric_cast(-point.y() + m_mousePressPos.y()), 0, aznumeric_cast(-point.x() + m_mousePressPos.x())); - angles = angles * 0.001f * m_settings->camera.rotationSpeed; - - QuatT qt = m_state->cameraTarget; - Ang3 ypr = CCamera::CreateAnglesYPR(Matrix33(qt.q)); - ypr.x += angles.z; - ypr.y += angles.x; - ypr.y = clamp_tpl(ypr.y, -1.5f, 1.5f); - - qt.q = Quat(CCamera::CreateOrientationYPR(ypr)); - - // Move the orbit target with the rotate operation. - float distanceFromTarget = (qt.t - m_state->orbitTarget).GetLength(); - Vec3 ydir = qt.GetColumn1().GetNormalized(); - m_state->orbitTarget = qt.t + ydir * distanceFromTarget; - - CameraMoved(qt, false); - - AzQtComponents::SetCursorPos(mapToGlobal(m_mousePressPos)); - } - } - else if (m_cameraControlMode == CameraControlMode::PAN) - { - if (!(m_settings->camera.transformRestraint & eCameraTransformRestraint_Panning)) - { - float speedScale = CalculateMoveSpeed(m_fastMode, m_slowMode, true) * 3; - speedScale = max(0.1f, speedScale); - - // Slide. - QuatT qt = m_state->cameraTarget; - Vec3 xdir = qt.GetColumn0().GetNormalized(); - Vec3 zdir = qt.GetColumn2().GetNormalized(); - - Vec3 delta = 0.0025f * xdir * aznumeric_cast(point.x() - m_mousePressPos.x()) * speedScale + 0.0025f * zdir * aznumeric_cast(m_mousePressPos.y() - point.y()) * speedScale; - qt.t += delta; - - // Move the orbit target with the pan operation. This ensures the - // center of the orbit moves with the camera as it pans. - m_state->orbitTarget += delta; - - CameraMoved(qt, false); - - AzQtComponents::SetCursorPos(mapToGlobal(m_mousePressPos)); - } - } - else if (m_cameraControlMode == CameraControlMode::ORBIT) - { - // Rotate around orbit target. - QuatT cameraTarget = m_state->cameraTarget; - Vec3 at = cameraTarget.t - m_state->orbitTarget; - float distanceFromTarget = at.GetLength(); - if (distanceFromTarget > 0.001f) - { - at /= distanceFromTarget; - } - else - { - at = Vec3(0.0f, m_state->orbitRadius, 0.0f); - distanceFromTarget = m_state->orbitRadius; - } - - Vec3 up = Vec3(0.0f, 0.0f, 1.0f); - const Vec3 right = at.Cross(up).GetNormalized(); - up = right.Cross(at).GetNormalized(); - - Ang3 angles = CCamera::CreateAnglesYPR(Matrix33::CreateFromVectors(right, at, up)); - const Ang3 delta = Ang3(aznumeric_cast(-point.y() + m_mousePressPos.y()), 0.0f, aznumeric_cast(-point.x() + m_mousePressPos.x())) * 0.002f * m_settings->camera.rotationSpeed; - angles.x += delta.z; - angles.y -= delta.x; - angles.y = clamp_tpl(angles.y, -1.5f, 1.5f); - - cameraTarget.t = m_state->orbitTarget + CCamera::CreateOrientationYPR(angles).TransformVector(Vec3(0.0f, distanceFromTarget, 0.0f)); - m_state->orbitRadius = distanceFromTarget; - - CameraMoved(cameraTarget, true); - - AzQtComponents::SetCursorPos(mapToGlobal(m_mousePressPos)); - } -} - -void QViewport::ProcessKeys() -{ - if (!m_renderContextCreated) - { - return; - } - - float deltaTime = m_lastFrameTime; - - if (deltaTime > 0.1f) - { - deltaTime = 0.1f; - } - - QuatT qt = m_state->cameraTarget; - Vec3 ydir = qt.GetColumn1().GetNormalized(); - Vec3 xdir = qt.GetColumn0().GetNormalized(); - Vec3 pos = qt.t; - - float moveSpeed = CalculateMoveSpeed(m_fastMode, m_slowMode); - bool hasPressedKey = false; - - if ((m_useArrowsForNavigation && CheckVirtualKey(Qt::Key_Up)) || CheckVirtualKey(Qt::Key_W)) - { - hasPressedKey = true; - Vec3 delta = deltaTime * moveSpeed * ydir; - qt.t += delta; - m_state->orbitTarget += delta; - CameraMoved(qt, false); - } - - if ((m_useArrowsForNavigation && CheckVirtualKey(Qt::Key_Down)) || CheckVirtualKey(Qt::Key_S)) - { - hasPressedKey = true; - Vec3 delta = deltaTime * moveSpeed * ydir; - qt.t -= delta; - m_state->orbitTarget -= delta; - CameraMoved(qt, false); - } - - if (m_cameraControlMode != CameraControlMode::ORBIT && ((m_useArrowsForNavigation && CheckVirtualKey(Qt::Key_Left)) || CheckVirtualKey(Qt::Key_A))) - { - hasPressedKey = true; - Vec3 delta = deltaTime * moveSpeed * xdir; - qt.t -= delta; - m_state->orbitTarget -= delta; - CameraMoved(qt, false); - } - - if (m_cameraControlMode != CameraControlMode::ORBIT && ((m_useArrowsForNavigation && CheckVirtualKey(Qt::Key_Right)) || CheckVirtualKey(Qt::Key_D))) - { - hasPressedKey = true; - Vec3 delta = deltaTime * moveSpeed * xdir; - qt.t += delta; - m_state->orbitTarget += delta; - CameraMoved(qt, false); - } - - if (CheckVirtualKey(Qt::RightButton) | CheckVirtualKey(Qt::MiddleButton)) - { - hasPressedKey = true; - } -} - -void QViewport::CameraMoved(QuatT qt, bool snap) -{ - if (m_cameraControlMode == CameraControlMode::ORBIT) - { - CreateLookAt(m_state->orbitTarget, m_state->orbitRadius, qt); - } - m_state->cameraTarget = qt; - if (snap) - { - m_state->lastCameraTarget = qt; - } - SignalCameraMoved(qt); -} - -void QViewport::OnKeyEvent(const SKeyEvent& ev) -{ - for (size_t i = 0; i < m_consumers.size(); ++i) - { - m_consumers[i]->OnViewportKey(ev); - } - SignalKey(ev); -} - -void QViewport::OnMouseEvent(const SMouseEvent& ev) -{ - if (ev.type == SMouseEvent::EType::TYPE_MOVE) - { - // Make sure we don't process more than one mouse event per frame, so we don't - // end up consuming all the "idle" time - ++m_mouseMovementsSinceLastFrame; - - if (m_mouseMovementsSinceLastFrame > 1) - { - // we can't discard all movement events, the last one should be delivered. - m_pendingMouseMoveEvent = ev; - return; - } - } - - for (size_t i = 0; i < m_consumers.size(); ++i) - { - m_consumers[i]->OnViewportMouse(ev); - } - SignalMouse(ev); -} - -void QViewport::PreRender() -{ - SRenderContext rc; - rc.camera = m_camera.get(); - rc.viewport = this; - - SignalPreRender(rc); - - - const float fov = DEG2RAD(m_settings->camera.fov); - const float fTime = m_lastFrameTime; - float lastRotWeight = 0.0f; - - QuatT targetTM = m_state->cameraTarget; - QuatT currentTM = m_state->lastCameraTarget; - - if ((targetTM.t - currentTM.t).len() > 0.0001f) - { - SmoothCD(currentTM.t, m_cameraSmoothPosRate, fTime, targetTM.t, m_settings->camera.smoothPos); - } - else - { - m_cameraSmoothPosRate = Vec3(0); - } - - SmoothCD(lastRotWeight, m_cameraSmoothRotRate, fTime, 1.0f, m_settings->camera.smoothRot); - - if (lastRotWeight >= 1.0f) - { - m_cameraSmoothRotRate = 0.0f; - } - - currentTM = QuatT(Quat::CreateNlerp(currentTM.q, targetTM.q, lastRotWeight), currentTM.t); - - m_state->lastCameraParentFrame = m_state->cameraParentFrame; - m_state->lastCameraTarget = currentTM; - - m_camera->SetFrustum(m_width, m_height, fov, m_settings->camera.nearClip); - m_camera->SetMatrix(Matrix34(m_state->cameraParentFrame * currentTM)); -} - -void QViewport::Render() -{ -} - -void QViewport::RenderInternal() -{ -} - -void QViewport::SetWindowTitle(const AZStd::string& title) -{ - // Do not support the WindowRequestBus changing the editor window title - AZ_UNUSED(title); -} - -AzFramework::WindowSize QViewport::GetClientAreaSize() const -{ - const QWidget* window = this->window(); - QSize windowSize = window->size(); - return AzFramework::WindowSize(windowSize.width(), windowSize.height()); -} - -void QViewport::ResizeClientArea(AzFramework::WindowSize clientAreaSize) -{ - QWidget* window = this->window(); - window->resize(aznumeric_cast(clientAreaSize.m_width), aznumeric_cast(clientAreaSize.m_height)); -} - -bool QViewport::GetFullScreenState() const -{ - // QViewport does not currently support full screen. - return false; -} - -void QViewport::SetFullScreenState([[maybe_unused]]bool fullScreenState) -{ - // QViewport does not currently support full screen. -} - -bool QViewport::CanToggleFullScreenState() const -{ - // QViewport does not currently support full screen. - return false; -} - -void QViewport::ToggleFullScreenState() -{ - // QViewport does not currently support full screen. -} - -void QViewport::ResetCamera() -{ - *m_state = SViewportState(); - m_camera->SetMatrix(Matrix34(m_state->cameraTarget)); -} - -void QViewport::SetSettings(const SViewportSettings& settings) -{ - *m_settings = settings; -} - -void QViewport::SetState(const SViewportState& state) -{ - *m_state = state; -} - -float QViewport::CalculateMoveSpeed(bool shiftPressed, bool ctrlPressed, bool scaleWithOrbitDistance) const -{ - // The value used to caculate speedScale respects the value used in RenderViewPort. - // Please refer to the function: CRenderViewport::ProcessKeys().-- Vera, Confetti - float speedScale = 20; - - speedScale *= m_settings->camera.moveSpeed; - - float moveSpeed = speedScale; - - if (shiftPressed) - { - moveSpeed *= m_settings->camera.fastMoveMultiplier; - } - if (ctrlPressed) - { - moveSpeed *= m_settings->camera.slowMoveMultiplier; - } - if (scaleWithOrbitDistance) - { - // Slow the movement down as we get closer to the orbit target - QuatT qt = m_state->cameraTarget; - float distanceFromTarget = (qt.t - m_state->orbitTarget).GetLength(); - moveSpeed *= distanceFromTarget * 0.01f; - // Prevent the speed from going too close to 0, which would prevent movement - moveSpeed = max(0.001f, moveSpeed); - } - - return moveSpeed; -} - -void QViewport::CreateLookAt(const Vec3& target, float radius, QuatT& cameraTarget) const -{ - Vec3 at = target - cameraTarget.t; - float distanceFromTarget = at.GetLength(); - if (distanceFromTarget > 0.001f) - { - at /= distanceFromTarget; - } - else - { - at = Vec3(0.0f, radius, 0.0f); - distanceFromTarget = radius; - } - if (distanceFromTarget < radius) - { - distanceFromTarget = radius; - cameraTarget.t = target - (at * radius); - } - Vec3 up = Vec3(0.0f, 0.0f, 1.0f); - const Vec3 right = at.Cross(up).GetNormalized(); - up = right.Cross(at).GetNormalized(); - cameraTarget.q = Quat(Matrix33::CreateFromVectors(right, at, up)); -} - -void QViewport::UpdateCameraControlMode(QMouseEvent* ev) -{ - Qt::MouseButton mouseButton = ev->button(); - Qt::KeyboardModifiers modifiers = ev->modifiers(); - if (mouseButton & Qt::RightButton && mouseButton & Qt::MiddleButton) - { - m_cameraControlMode = CameraControlMode::ZOOM; - } - else if (mouseButton == Qt::MiddleButton) - { - if (modifiers & Qt::ALT) - { - m_cameraControlMode = CameraControlMode::ORBIT; - } - else - { - if (m_cameraControlMode == CameraControlMode::ROTATE) - { - m_cameraControlMode = CameraControlMode::ZOOM; - } - else - { - m_cameraControlMode = CameraControlMode::PAN; - } - } - } - else if (mouseButton == Qt::RightButton) - { - if (m_cameraControlMode == CameraControlMode::PAN || (modifiers & Qt::ALT)) - { - m_cameraControlMode = CameraControlMode::ZOOM; - } - else - { - m_cameraControlMode = CameraControlMode::ROTATE; - } - } - else - { - m_cameraControlMode = CameraControlMode::NONE; - } -} - -void QViewport::mousePressEvent(QMouseEvent* ev) -{ - SMouseEvent me; - me.type = SMouseEvent::TYPE_PRESS; - me.button = SMouseEvent::EButton(ev->button()); - me.x = ev->x(); - me.y = ev->y(); - me.viewport = this; - me.shift = (ev->modifiers() & Qt::SHIFT) != 0; - me.control = (ev->modifiers() & Qt::CTRL) != 0; - OnMouseEvent(me); - - QWidget::mousePressEvent(ev); - setFocus(); - - m_mousePressPos = ev->pos(); - - UpdateCameraControlMode(ev); - if (m_cameraControlMode != CameraControlMode::NONE) - { - QApplication::setOverrideCursor(Qt::BlankCursor); - } -} - -void QViewport::mouseReleaseEvent(QMouseEvent* ev) -{ - SMouseEvent me; - me.type = SMouseEvent::TYPE_RELEASE; - me.button = SMouseEvent::EButton(ev->button()); - me.x = ev->x(); - me.y = ev->y(); - me.viewport = this; - OnMouseEvent(me); - - m_cameraControlMode = CameraControlMode::NONE; - QWidget::mouseReleaseEvent(ev); - QApplication::restoreOverrideCursor(); -} - -void QViewport::wheelEvent(QWheelEvent* ev) -{ - QuatT qt = m_state->cameraTarget; - Vec3 ydir = qt.GetColumn1().GetNormalized(); - Vec3 pos = qt.t; - const float wheelSpeed = m_settings->camera.zoomSpeed * (m_fastMode ? m_settings->camera.fastMoveMultiplier : 1.0f) * (m_slowMode ? m_settings->camera.slowMoveMultiplier : 1.0f); - pos += 0.01f * ydir * aznumeric_cast(ev->angleDelta().y()) * wheelSpeed; - qt.t = pos; - CameraMoved(qt, false); -} - -void QViewport::mouseMoveEvent(QMouseEvent* ev) -{ - SMouseEvent me; - me.type = SMouseEvent::TYPE_MOVE; - me.button = SMouseEvent::EButton(ev->button()); - me.x = ev->x(); - me.y = ev->y(); - me.viewport = this; - m_fastMode = (ev->modifiers() & Qt::SHIFT) != 0; - m_slowMode = (ev->modifiers() & Qt::CTRL) != 0; - OnMouseEvent(me); - - QWidget::mouseMoveEvent(ev); -} - -void QViewport::keyPressEvent(QKeyEvent* ev) -{ - SKeyEvent event; - event.type = SKeyEvent::TYPE_PRESS; - event.key = ev->key() | ev->modifiers(); - m_fastMode = (ev->modifiers() & Qt::SHIFT) != 0; - m_slowMode = (ev->modifiers() & Qt::CTRL) != 0; - OnKeyEvent(event); - - QWidget::keyPressEvent(ev); -} - -void QViewport::keyReleaseEvent(QKeyEvent* ev) -{ - SKeyEvent event; - event.type = SKeyEvent::TYPE_RELEASE; - event.key = ev->key() | ev->modifiers(); - m_fastMode = (ev->modifiers() & Qt::SHIFT) != 0; - m_slowMode = (ev->modifiers() & Qt::CTRL) != 0; - OnKeyEvent(event); - QWidget::keyReleaseEvent(ev); -} - -void QViewport::resizeEvent(QResizeEvent* ev) -{ - QWidget::resizeEvent(ev); - -#if defined(AZ_PLATFORM_WINDOWS) - // Needed for high DPI mode on windows - const qreal ratio = devicePixelRatioF(); -#else - const qreal ratio = 1.0f; -#endif - int cx = aznumeric_cast(ev->size().width() * ratio); - int cy = aznumeric_cast(ev->size().height() * ratio); - if (cx == 0 || cy == 0) - { - return; - } - - m_width = cx; - m_height = cy; - - GetIEditor()->GetEnv()->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_RESIZE, cx, cy); - SignalUpdate(); - Update(); -} - -void QViewport::showEvent(QShowEvent* ev) -{ - QWidget::showEvent(ev); -} - -void QViewport::moveEvent(QMoveEvent* ev) -{ - QWidget::moveEvent(ev); - - GetIEditor()->GetEnv()->pSystem->GetISystemEventDispatcher()->OnSystemEvent(ESYSTEM_EVENT_MOVE, ev->pos().x(), ev->pos().y()); -} - -bool QViewport::event(QEvent* ev) -{ - bool result = QWidget::event(ev); - - if (ev->type() == QEvent::ShortcutOverride) - { - // When a shortcut is matched, Qt's event processing sends out a shortcut override event - // to allow other systems to override it. If it's not overridden, then the key events - // get processed as a shortcut, even if the widget that's the target has a keyPress event - // handler. So, we need to communicate that we've processed the shortcut override - // which will tell Qt not to process it as a shortcut and instead pass along the - // keyPressEvent. - - QKeyEvent* keyEvent = static_cast(ev); - QKeySequence key(keyEvent->key() | keyEvent->modifiers()); - - for (size_t i = 0; i < m_consumers.size(); ++i) - { - if (m_consumers[i]->ProcessesViewportKey(key)) - { - ev->accept(); - return true; - } - } - } - - return result; -} - -void QViewport::paintEvent(QPaintEvent* ev) -{ - QWidget::paintEvent(ev); -} - -void QViewport::AddConsumer(QViewportConsumer* consumer) -{ - RemoveConsumer(consumer); - m_consumers.push_back(consumer); -} - -void QViewport::RemoveConsumer(QViewportConsumer* consumer) -{ - m_consumers.erase(std::remove(m_consumers.begin(), m_consumers.end(), consumer), m_consumers.end()); -} - -void QViewport::SetUseArrowsForNavigation(bool useArrowsForNavigation) -{ - m_useArrowsForNavigation = useArrowsForNavigation; -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewport.h b/Code/Sandbox/Plugins/EditorCommon/QViewport.h deleted file mode 100644 index 5566edc126..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewport.h +++ /dev/null @@ -1,193 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#include - -#include -#include -#include "EditorCommonAPI.h" -#include "QViewportEvents.h" - -#include - -class CImageEx; -struct DisplayContext; -class CCamera; -struct SRenderingPassInfo; -struct SRendParams; -struct Ray; -struct IRenderer; -struct SSystemGlobalEnvironment; -namespace Serialization { - class IArchive; -} -using Serialization::IArchive; -using std::unique_ptr; - -struct SKeyEvent; -struct SMouseEvent; -struct SViewportSettings; -struct SViewportState; -class QElapsedTimer; -class QViewportRequests; - -class EDITOR_COMMON_API QViewport; -struct SRenderContext -{ - CCamera* camera; - QViewport* viewport; - SRendParams* renderParams; - SRenderingPassInfo* passInfo; -}; - -enum class CameraControlMode -{ - NONE, - PAN, - ROTATE, - ZOOM, - ORBIT -}; - - -class QViewportConsumer; -AZ_PUSH_DISABLE_DLL_EXPORT_BASECLASS_WARNING -AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING -class EDITOR_COMMON_API QViewport - : public QWidget -{ - Q_OBJECT -AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -AZ_POP_DISABLE_DLL_EXPORT_BASECLASS_WARNING -public: - - enum StartupMode { - StartupMode_Immediate = 1, // Startup() will be called by QViewport's CTOR - StartupMode_Manual // Startup() will be called by the derived class - }; - - explicit QViewport(QWidget* parent, StartupMode startupMode = StartupMode_Immediate); - virtual ~QViewport(); - void Startup(); - - void AddConsumer(QViewportConsumer* consumer); - void RemoveConsumer(QViewportConsumer* consumer); - - void CaptureMouse(); - void ReleaseMouse(); - void SetForegroundUpdateMode(bool foregroundUpdate); - CCamera* Camera() const; - void ResetCamera(); - void Serialize(IArchive& ar); - - void SetUseArrowsForNavigation(bool useArrowsForNavigation); - void SetSceneDimensions(const Vec3& size); - void SetSettings(const SViewportSettings& settings); - const SViewportSettings& GetSettings() const; - void SetState(const SViewportState& state); - const SViewportState& GetState() const; - bool ScreenToWorldRay(Ray* ray, int x, int y); - QPoint ProjectToScreen(const Vec3& point); - void LookAt(const Vec3& target, float radius, bool snap); - - int Width() const; - int Height() const; - void SetSize(const QSize& size); - - // WindowRequestBus::Handler... (handler moved to cpp to resolve link issues in unity builds) - void SetWindowTitle(const AZStd::string& title); - AzFramework::WindowSize GetClientAreaSize() const; - void ResizeClientArea(AzFramework::WindowSize clientAreaSize); - bool GetFullScreenState() const; - void SetFullScreenState(bool fullScreenState); - bool CanToggleFullScreenState() const; - void ToggleFullScreenState(); - -public slots: - void Update(); -protected slots: - void RenderInternal(); -signals: - void SignalPreRender(const SRenderContext&); - void SignalRender(const SRenderContext&); - void SignalKey(const SKeyEvent&); - void SignalMouse(const SMouseEvent&); - void SignalUpdate(); - void SignalCameraMoved(const QuatT& qt); -protected: - void mousePressEvent(QMouseEvent* ev) override; - void mouseReleaseEvent(QMouseEvent* ev) override; - void wheelEvent(QWheelEvent* ev) override; - void mouseMoveEvent(QMouseEvent* ev) override; - void keyPressEvent(QKeyEvent* ev) override; - void keyReleaseEvent(QKeyEvent* ev) override; - void resizeEvent(QResizeEvent* ev) override; - void showEvent(QShowEvent* ev) override; - void moveEvent(QMoveEvent* ev) override; - void paintEvent(QPaintEvent* ev) override; - bool event(QEvent* ev) override; - - void CameraMoved(QuatT qt, bool snap); //Confetti: Jurecka ... making this protected so can adjust camera to focus on items in derived class. - - float GetLastFrameTime(); -private: - struct SPrivate; - -private: - void UpdateBackgroundColor(); - - void ProcessMouse(); - void ProcessKeys(); - void PreRender(); - void Render(); - void OnMouseEvent(const SMouseEvent& ev); - void OnKeyEvent(const SKeyEvent& ev); - float CalculateMoveSpeed(bool shiftPressed, bool ctrlPressed, bool scaleWithOrbitDistance = false) const; - void CreateLookAt(const Vec3& target, float radius, QuatT& cameraTarget) const; - void UpdateCameraControlMode(QMouseEvent* ev); - - struct SPreviousContext; - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - std::vector m_previousContexts; - std::unique_ptr m_camera; - QElapsedTimer* m_frameTimer; - QTimer* m_timer; - int m_width; - int m_height; - QPoint m_mousePressPos; - int64 m_lastTime; - float m_lastFrameTime; - float m_averageFrameTime; - bool m_useArrowsForNavigation; - bool m_renderContextCreated; - bool m_creatingRenderContext; - bool m_updating; - bool m_fastMode; - bool m_slowMode; - CameraControlMode m_cameraControlMode; - - Vec3 m_cameraSmoothPosRate; - float m_cameraSmoothRotRate; - int m_mouseMovementsSinceLastFrame; - f32 m_LightRotationRadian; - SMouseEvent m_pendingMouseMoveEvent; - - Vec3 m_sceneDimensions; - std::unique_ptr m_private; - std::unique_ptr m_settings; - std::unique_ptr m_state; - std::vector m_consumers; - AZStd::unique_ptr m_viewportRequests; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING -}; diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewportConsumer.h b/Code/Sandbox/Plugins/EditorCommon/QViewportConsumer.h deleted file mode 100644 index 61d81b8dbf..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewportConsumer.h +++ /dev/null @@ -1,37 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_QVIEWPORTCONSUMER_H -#define CRYINCLUDE_EDITORCOMMON_QVIEWPORTCONSUMER_H - -struct SRenderContext; -struct SKeyEvent; -struct SMouseEvent; -class QKeySequence; - -class QViewportConsumer -{ -public: - virtual ~QViewportConsumer() = default; - virtual void OnViewportRender([[maybe_unused]] const SRenderContext& rc) {} - - // If you're overriding OnViewportKey, you should also override ProcessesViewportKey and return true if you're interested in a particular key. - // If you don't, then registered shortcuts get keyPressed events first, and in many cases will never get passed to OnViewportKey - virtual void OnViewportKey([[maybe_unused]] const SKeyEvent& ev) {} - virtual bool ProcessesViewportKey([[maybe_unused]] const QKeySequence& key) { return false; } - - virtual void OnViewportMouse([[maybe_unused]] const SMouseEvent& ev) {} -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QVIEWPORTCONSUMER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewportEvents.h b/Code/Sandbox/Plugins/EditorCommon/QViewportEvents.h deleted file mode 100644 index 8e6e96c62d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewportEvents.h +++ /dev/null @@ -1,96 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QVIEWPORTEVENTS_H -#define CRYINCLUDE_EDITORCOMMON_QVIEWPORTEVENTS_H -#pragma once - -#include "EditorCommonAPI.h" -class EDITOR_COMMON_API QViewport; - -struct SMouseEvent -{ - enum EType - { - TYPE_NONE, - TYPE_PRESS, - TYPE_RELEASE, - TYPE_MOVE - }; - - enum EButton - { - BUTTON_NONE, - BUTTON_LEFT, - BUTTON_RIGHT, - BUTTON_MIDDLE - }; - - EType type; - int x; - int y; - EButton button; - bool shift; - bool control; - QViewport* viewport; - - SMouseEvent() - : type(TYPE_NONE) - , x(INT_MIN) - , y(INT_MIN) - , button(BUTTON_NONE) - , viewport(0) - , shift(false) - , control(false) - { - } -}; - -struct SSelectionID -{ -}; - -struct SInteractionEvent -{ - enum EType - { - TYPE_NONE, - TYPE_ENTER, - TYPE_LEAVE, - TYPE_DRAG - }; - - SSelectionID selection; - Vec3 start; - Vec3 end; -}; - -struct SKeyEvent -{ - enum EType - { - TYPE_NONE, - TYPE_PRESS, - TYPE_RELEASE - }; - - EType type; - int key; - - SKeyEvent() - : type(TYPE_NONE) - { - } -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QVIEWPORTEVENTS_H diff --git a/Code/Sandbox/Plugins/EditorCommon/QViewportSettings.h b/Code/Sandbox/Plugins/EditorCommon/QViewportSettings.h deleted file mode 100644 index 2a2111144e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/QViewportSettings.h +++ /dev/null @@ -1,269 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_QVIEWPORTSETTINGS_H -#define CRYINCLUDE_EDITORCOMMON_QVIEWPORTSETTINGS_H -#pragma once - -#include -#include -#include "EditorCommonAPI.h" -#include "Serialization.h" -#include - -namespace Serialization -{ - class IArchive; -}; - -enum ECameraTransformRestraint -{ - eCameraTransformRestraint_Rotation = 0x01, - eCameraTransformRestraint_Panning = 0x02, - eCameraTransformRestraint_Zoom = 0x04 -}; - -struct SViewportState -{ - QuatT cameraTarget; - QuatT cameraParentFrame; - QuatT gridOrigin; - Vec3 gridCellOffset; - QuatT lastCameraTarget; - QuatT lastCameraParentFrame; - - Vec3 orbitTarget; - float orbitRadius; - - - SViewportState() - : cameraParentFrame(IDENTITY) - , gridOrigin(IDENTITY) - , gridCellOffset(0) - , lastCameraTarget(IDENTITY) - , lastCameraParentFrame(IDENTITY) - , orbitTarget(ZERO) - { - // This eye position is similar to Maya's initial camera position - AZ::Transform transform = AZ::Transform::CreateLookAt( - AZ::Vector3(-3.5f, 3.625f, 2.635f), // Eye position - AZ::Vector3(LYVec3ToAZVec3(orbitTarget)) - ); - cameraTarget = AZTransformToLYQuatT(transform); - orbitRadius = cameraTarget.t.GetLength(); - - lastCameraTarget = cameraTarget; - } -}; - -struct SViewportRenderingSettings -{ - bool wireframe; - bool sunlight; // Add setting for time of day feature - Vera, Confetti - bool fps; - - SViewportRenderingSettings() - : wireframe(false) - , fps(true) - , sunlight(false) - { - } - - void Serialize(Serialization::IArchive& ar) - { - ar(wireframe, "wireframe", "Wireframe"); - ar(fps, "fps", "Framerate"); - ar(sunlight, "sunlight", "Sunlight"); - } -}; - -struct SViewportCameraSettings -{ - bool showViewportOrientation; - - float fov; - float nearClip; - float smoothPos; - float smoothRot; - - float moveSpeed; - float rotationSpeed; - float zoomSpeed; - float fastMoveMultiplier; - float slowMoveMultiplier; - - int transformRestraint; - - SViewportCameraSettings() - : showViewportOrientation(true) - , fov(60) - , nearClip(0.01f) - , smoothPos(0.07f) - , smoothRot(0.05f) - , moveSpeed(0.7f) - , rotationSpeed(2.0f) - , zoomSpeed(0.1f) - , fastMoveMultiplier(3.0f) - , slowMoveMultiplier(0.1f) - , transformRestraint(0) - { - } - - void Serialize(Serialization::IArchive& ar) - { - ar(showViewportOrientation, "showViewportOrientation", "Show Viewport Orientation"); - ar(Serialization::Range(fov, 20.0f, 120.0f), "fov", "FOV"); - ar(Serialization::Range(nearClip, 0.01f, 0.5f), "nearClip", "Near Clip"); - ar(Serialization::Range(moveSpeed, 0.1f, 3.0f), "moveSpeed", "Move Speed"); - ar(transformRestraint, "TransformRestraint", "Transform Restraint"); - ar.Doc("Relative to the scene size"); - ar(Serialization::Range(rotationSpeed, 0.1f, 4.0f), "rotationSpeed", "Rotation Speed"); - ar.Doc("Degrees per 1000 px"); - if (ar.OpenBlock("movementSmoothing", "+Movement Smoothing")) - { - ar(smoothPos, "smoothPos", "Position"); - ar(smoothRot, "smoothRot", "Rotation"); - ar.CloseBlock(); - } - } -}; - - -struct SViewportGridSettings -{ - bool showGrid; - bool circular; - ColorB mainColor; - ColorB middleColor; - int alphaFalloff; - float spacing; - uint16 count; - uint16 interCount; - bool origin; - ColorB originColor; - - SViewportGridSettings() - : showGrid(true) - , circular(true) - , mainColor(255, 255, 255, 50) - , middleColor(255, 255, 255, 10) - , alphaFalloff(100) - , spacing(1.0f) - , count(10) - , interCount(10) - , origin(false) - , originColor(10, 10, 10, 255) - { - } - - void Serialize(Serialization::IArchive& ar) - { - ar(showGrid, "showGrid", "Show Grid"); - if (showGrid) - { - ar(circular, "circular", 0); - } - ar(mainColor, "mainColor", "Main Color"); - ar(middleColor, "middleColor", "Middle Color"); - ar(Serialization::Range(alphaFalloff, 0, 100), "alphaFalloff", 0); - ar(spacing, "spacing", "Spacing"); - ar(count, "count", "Main Lines"); - ar(interCount, "interCount", "Middle Lines"); - ar(origin, "origin", "Origin"); - ar(originColor, "originColor", origin ? "Origin Color" : 0); - } -}; - -struct SViewportLightingSettings -{ - f32 m_brightness; - ColorB m_ambientColor; - - bool m_useLightRotation; - f32 m_lightMultiplier; - f32 m_lightSpecMultiplier; - - ColorB m_directionalLightColor; - - SViewportLightingSettings() - { - m_brightness = 1.0f; - m_ambientColor = ColorB(128, 128, 128, 255); - - m_useLightRotation = 0; - m_lightMultiplier = 3.0; - m_lightSpecMultiplier = 2.0f; - - m_directionalLightColor = ColorB(255, 255, 255, 255); - } - - void Serialize(Serialization::IArchive& ar) - { - ar(Serialization::Range(m_brightness, 0.0f, 200.0f), "brightness", "Brightness"); - ar(m_ambientColor, "ambientColor", "Ambient Color"); - - ar(m_useLightRotation, "rotatelight", "Rotate Light"); - ar(m_lightMultiplier, "lightMultiplier", "Light Multiplier"); - ar(m_lightSpecMultiplier, "lightSpecMultiplier", "Light Spec Multiplier"); - - ar(m_directionalLightColor, "directionalLightColor", "Directional Light Color"); - } -}; - -struct SViewportBackgroundSettings -{ - bool useGradient; - ColorB topColor; - ColorB bottomColor; - - SViewportBackgroundSettings() - : useGradient(true) - , topColor(128, 128, 128, 255) - , bottomColor(32, 32, 32, 255) - { - } - - void Serialize(Serialization::IArchive& ar) - { - ar(useGradient, "useGradient", "Use Gradient"); - if (useGradient) - { - ar(topColor, "topColor", "Top Color"); - ar(bottomColor, "bottomColor", "Bottom Color"); - } - else - { - ar(topColor, "topColor", "Color"); - } - } -}; - -struct SViewportSettings -{ - SViewportRenderingSettings rendering; - SViewportCameraSettings camera; - SViewportGridSettings grid; - SViewportLightingSettings lighting; - SViewportBackgroundSettings background; - - void Serialize(Serialization::IArchive& ar) - { - ar(rendering, "debug", "Debug"); - ar(camera, "camera", "Camera"); - ar(grid, "grid", "Grid"); - ar(lighting, "lighting", "Lighting"); - ar(background, "background", "Background"); - } -}; - -#endif // CRYINCLUDE_EDITORCOMMON_QVIEWPORTSETTINGS_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization.cpp deleted file mode 100644 index 6d3db713c5..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization.cpp +++ /dev/null @@ -1,15 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "Serialization.h" diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization.h b/Code/Sandbox/Plugins/EditorCommon/Serialization.h deleted file mode 100644 index b017376355..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_H - -#include -#include - -namespace Serialization { - class IArchive; -} - -struct SkeletonAlias; -bool Serialize(Serialization::IArchive& ar, SkeletonAlias& value, const char* name, const char* label); - -#include -#include -#include -#include -using Serialization::BitFlags; -#include -#include -#include "Serialization/Decorators/ToggleButton.h" -#include "Serialization/Qt.h" -#include -#include - -#include - -using Serialization::IArchive; - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.cpp deleted file mode 100644 index 9ee929ec55..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.cpp +++ /dev/null @@ -1,839 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "BinArchive.h" -#include -#include "Serialization/ClassFactory.h" - -namespace Serialization { - static const unsigned char SIZE16 = 254; - static const unsigned char SIZE32 = 255; - - static const unsigned int BIN_MAGIC = 0xb1a4c17f; - - //#ifdef _DEBUG - //typedef std::map HashMap; - //static HashMap hashMap; - //#endif - - BinOArchive::BinOArchive() - : IArchive(OUTPUT | BINARY) - { - clear(); - } - - void BinOArchive::clear() - { - stream_.clear(); - stream_.write((const char*)&BIN_MAGIC, sizeof(BIN_MAGIC)); - } - - size_t BinOArchive::length() const - { - return stream_.position(); - } - - bool BinOArchive::save(const char* filename) - { - FILE* f = nullptr; - azfopen(&f, filename, "wb"); - if (!f) - { - return false; - } - - if (fwrite(buffer(), 1, length(), f) != length()) - { - fclose(f); - return false; - } - - fclose(f); - return true; - } - - inline void BinOArchive::openNode(const char* name, bool size8) - { - if (!strlen(name)) - { - return; - } - - unsigned short hash = calcHash(name); - stream_.write(hash); - - blockSizeOffsets_.push_back(int(stream_.position())); - stream_.write((unsigned char)0); - if (!size8) - { - stream_.write((unsigned short)0); - } - -#ifdef _DEBUG - // HashMap::iterator i = hashMap.find(hash); - // if(i != hashMap.end() && i->second != name) - // ASSERT_STR(0, name); - // hashMap[hash] = name; -#endif - } - - inline void BinOArchive::closeNode(const char* name, bool size8) - { - if (!strlen(name)) - { - return; - } - - unsigned int offset = blockSizeOffsets_.back(); - unsigned int size = (unsigned int)(stream_.position() - offset - sizeof(unsigned char) - (size8 ? 0 : sizeof(unsigned short))); - blockSizeOffsets_.pop_back(); - unsigned char* sizePtr = (unsigned char*)(stream_.buffer() + offset); - - if (size < SIZE16) - { - *sizePtr = size; - if (!size8) - { - unsigned char* buffer = sizePtr + 3; - memmove(buffer - 2, buffer, size); - stream_.setPosition(stream_.position() - 2); - } - } - else - { - YASLI_ASSERT(!size8); - if (size < 0x10000) - { - *sizePtr = SIZE16; - *((unsigned short*)(sizePtr + 1)) = size; - } - else - { - unsigned char* buffer = sizePtr + 3; - stream_.write((unsigned short)0); - *sizePtr = SIZE32; - memmove(buffer + 2, buffer, size); - *((unsigned int*)(sizePtr + 1)) = size; - } - } - } - - bool BinOArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - bool size8 = strlen(value.get()) + 1 < SIZE16; - openNode(name, size8); - stream_ << value.get(); - stream_.write(char(0)); - closeNode(name, size8); - return true; - } - - bool BinOArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - bool size8 = (wcslen(value.get()) + 1) * 2 < SIZE16; - openNode(name, size8); - stream_ << value.get(); - stream_.write(short(0)); - closeNode(name, size8); - return true; - } - - bool BinOArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - openNode(name); - stream_.write(value); - closeNode(name); - return true; - } - - bool BinOArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - ser(*this); - closeNode(name, false); - return true; - } - - bool BinOArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - - unsigned int size = (unsigned int)ser.size(); - if (size < SIZE16) - { - stream_.write((unsigned char)size); - } - else if (size < 0x10000) - { - stream_.write(SIZE16); - stream_.write((unsigned short)size); - } - else - { - stream_.write(SIZE32); - stream_.write(size); - } - - if (strlen(name)) - { - if (size > 0) - { - int i = 0; - do - { - char elementName[16]; - azitoa(i++, elementName, AZ_ARRAY_SIZE(elementName), 10); - ser(*this, elementName, ""); - } while (ser.next()); - } - - closeNode(name, false); - } - else - { - if (size > 0) - { - do - { - ser(*this, "", ""); - } - while (ser.next()); - } - } - - return true; - } - - bool BinOArchive::operator()(IPointer& ptr, const char* name, [[maybe_unused]] const char* label) - { - openNode(name, false); - - const char* typeName = ptr.registeredTypeName(); - if (!typeName) - { - typeName = ""; - } - if (ptr.get() && typeName[0] == '\0') - { - CRY_ASSERT_MESSAGE(0, "Writing unregistered class. Use SERIALIZATION_CLASS_NAME macro for registration."); - } - - TypeID baseType = ptr.baseType(); - - if (ptr.get()) - { - stream_ << typeName; - stream_.write(char(0)); - ptr.serializer()(*this); - } - else - { - stream_.write(char(0)); - } - - closeNode(name, false); - return true; - } - - - ////////////////////////////////////////////////////////////////////////// - - BinIArchive::BinIArchive() - : IArchive(INPUT | BINARY) - , loadedData_(0) - { - } - - BinIArchive::~BinIArchive() - { - close(); - } - - bool BinIArchive::load(const char* filename) - { - close(); - - FILE* f = nullptr; - azfopen(&f, filename, "rb"); - if (!f) - { - return false; - } - fseek(f, 0, SEEK_END); - size_t length = ftell(f); - fseek(f, 0, SEEK_SET); - if (length == 0) - { - fclose(f); - return false; - } - loadedData_ = new char[length]; - if (fread((void*)loadedData_, 1, length, f) != length || !open(loadedData_, length)) - { - close(); - fclose(f); - return false; - } - fclose(f); - return true; - } - - bool BinIArchive::open(const char* buffer, size_t size) - { - if (size < sizeof(int)) - { - return false; - } - if (*(unsigned*)(buffer) != BIN_MAGIC) - { - return false; - } - buffer += sizeof(unsigned int); - size -= sizeof(unsigned int); - - blocks_.push_back(Block(buffer, (unsigned int)size)); - return true; - } - - void BinIArchive::close() - { - if (loadedData_) - { - delete [] loadedData_; - } - loadedData_ = 0; - } - - bool BinIArchive::openNode(const char* name) - { - Block block(0, 0); - if (currentBlock().get(name, block)) - { - blocks_.push_back(block); - return true; - } - return false; - } - - void BinIArchive::closeNode([[maybe_unused]] const char* name, [[maybe_unused]] bool check) - { - YASLI_ASSERT(!check || currentBlock().validToClose()); - blocks_.pop_back(); - } - - bool BinIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - string str; - read(str); - value.set(str.c_str()); - return true; - } - - if (!openNode(name)) - { - return false; - } - - string str; - read(str); - value.set(str.c_str()); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - wstring str; - read(str); - value.set(str.c_str()); - return true; - } - - if (!openNode(name)) - { - return false; - } - - wstring str; - read(str); - value.set(str.c_str()); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - - bool BinIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - read(value); - return true; - } - - if (!openNode(name)) - { - return false; - } - - read(value); - closeNode(name); - return true; - } - - bool BinIArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - if (!strlen(name)) - { - ser(*this); - return true; - } - - if (!openNode(name)) - { - return false; - } - - ser(*this); - closeNode(name, false); - return true; - } - - bool BinIArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (strlen(name)) - { - if (!openNode(name)) - { - return false; - } - - size_t size = currentBlock().readPackedSize(); - ser.resize(size); - - if (size > 0) - { - int i = 0; - do - { - char elementName[16]; - azitoa(i++, elementName, AZ_ARRAY_SIZE(elementName), 10); - ser(*this, elementName, ""); - } - while (ser.next()); - } - closeNode(name); - return true; - } - else - { - size_t size = currentBlock().readPackedSize(); - ser.resize(size); - if (size > 0) - { - do - { - ser(*this, "", ""); - } - while (ser.next()); - } - return true; - } - } - - bool BinIArchive::operator()(IPointer& ptr, const char* name, [[maybe_unused]] const char* label) - { - if (strlen(name) && !openNode(name)) - { - return false; - } - - string typeName; - read(typeName); - if (ptr.get() && (typeName.empty() || (typeName != ptr.registeredTypeName()))) - { - ptr.create(""); // 0 - } - if (!typeName.empty() && !ptr.get()) - { - ptr.create(typeName.c_str()); - } - - if (SStruct ser = ptr.serializer()) - { - ser(*this); - } - - if (strlen(name)) - { - closeNode(name); - } - return true; - } - - unsigned int BinIArchive::Block::readPackedSize() - { - unsigned char size8; - read(size8); - if (size8 < SIZE16) - { - return size8; - } - if (size8 == SIZE16) - { - unsigned short size16; - read(size16); - return size16; - } - unsigned int size32; - read(size32); - return size32; - } - - bool BinIArchive::Block::get(const char* name, Block& block) - { - if (begin_ == end_) - { - return false; - } - complex_ = true; - unsigned short hashName = calcHash(name); - const char* currInitial = curr_; - bool restarted = false; - for (;; ) - { - if (curr_ >= end_) - { - return false; - } - - unsigned short hash; - read(hash); - unsigned int size = readPackedSize(); - - const char* currPrev = curr_; - if ((curr_ += size) == end_) - { - if (restarted) - { - return false; - } - curr_ = begin_; - restarted = true; - } - - //ASSERT(curr_ < end_); - - if (hash == hashName) - { - block = Block(currPrev, size); - return true; - } - - if (curr_ == currInitial) - { - return false; - } - } - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.h deleted file mode 100644 index 09285bf2fc..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/BinArchive.h +++ /dev/null @@ -1,183 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -// For tags 16-bit xor-hash is used, with check for uniquness in debug -// Block size is automatic: 8, 16 or 32 bits - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_BINARCHIVE_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_BINARCHIVE_H -#pragma once - -#include "Serialization/IArchive.h" -#include "MemoryWriter.h" -#include "EditorCommonAPI.h" - -namespace Serialization { - inline unsigned short calcHash(const char* str) - { - unsigned short hash = 0; - const unsigned short* p = (const unsigned short*)(str); - for (;; ) - { - unsigned short w = *p++; - if (!(w & 0xff)) - { - break; - } - hash ^= w; - if (!(w & 0xff00)) - { - break; - } - } - return hash; - } - - class BinOArchive - : public IArchive - { - public: - BinOArchive(); - ~BinOArchive() {} - - void clear(); - size_t length() const; - const char* buffer() const { return stream_.buffer(); } - bool save(const char* fileName); - - bool operator()(bool& value, const char* name, const char* label); - bool operator()(IString& value, const char* name, const char* label); - bool operator()(IWString& value, const char* name, const char* label); - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(int8& value, const char* name, const char* label); - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - bool operator()(const SStruct& ser, const char* name, const char* label); - bool operator()(IContainer& ser, const char* name, const char* label); - bool operator()(IPointer& ptr, const char* name, const char* label); - - using IArchive::operator(); - - private: - void openContainer(const char* name, int size, const char* typeName); - void openNode(const char* name, bool size8 = true); - void closeNode(const char* name, bool size8 = true); - - std::vector blockSizeOffsets_; - MemoryWriter stream_; - }; - - ////////////////////////////////////////////////////////////////////////// - - class BinIArchive - : public IArchive - { - public: - BinIArchive(); - ~BinIArchive(); - - bool load(const char* fileName); - bool open(const char* buffer, size_t length); // doesn't copy the buffer - bool open(const BinOArchive& ar) { return open(ar.buffer(), ar.length()); } - void close(); - - bool operator()(bool& value, const char* name, const char* label); - bool operator()(IString& value, const char* name, const char* label); - bool operator()(IWString& value, const char* name, const char* label); - bool operator()(float& value, const char* name, const char* label); - bool operator()(double& value, const char* name, const char* label); - bool operator()(int16& value, const char* name, const char* label); - bool operator()(uint16& value, const char* name, const char* label); - bool operator()(int32& value, const char* name, const char* label); - bool operator()(uint32& value, const char* name, const char* label); - bool operator()(int64& value, const char* name, const char* label); - bool operator()(uint64& value, const char* name, const char* label); - - bool operator()(int8& value, const char* name, const char* label); - bool operator()(uint8& value, const char* name, const char* label); - bool operator()(char& value, const char* name, const char* label); - - bool operator()(const SStruct& ser, const char* name, const char* label); - bool operator()(IContainer& ser, const char* name, const char* label); - bool operator()(IPointer& ptr, const char* name, const char* label); - - using IArchive::operator(); - - private: - class Block - { - public: - Block(const char* data, int size) - : begin_(data) - , curr_(data) - , end_(data + size) - , complex_(false) {} - - bool get(const char* name, Block& block); - - void read(void* data, int size) - { - YASLI_ASSERT(curr_ + size <= end_); - memcpy(data, curr_, size); - curr_ += size; - } - - template - void read(T& x){ read(&x, sizeof(x)); } - - void read(string& s) - { - YASLI_ASSERT(curr_ + strlen(curr_) < end_); - s = curr_; - curr_ += strlen(curr_) + 1; - } - void read(wstring& s) - { - YASLI_ASSERT(curr_ + sizeof(wchar_t) * wcslen((wchar_t*)curr_) < end_); - s = (wchar_t*)curr_; - curr_ += (wcslen((wchar_t*)curr_) + 1) * sizeof(wchar_t); - } - - unsigned int readPackedSize(); - - bool validToClose() const { return complex_ || curr_ == end_; } - - private: - const char* begin_; - const char* end_; - const char* curr_; - bool complex_; - }; - - typedef std::vector Blocks; - Blocks blocks_; - const char* loadedData_; - - bool openNode(const char* name); - void closeNode(const char* name, bool check = true); - Block& currentBlock() { return blocks_.back(); } - template - void read(T& t) { currentBlock().read(t); } - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_BINARCHIVE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/EditorActionButton.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/EditorActionButton.h deleted file mode 100644 index 77d064203b..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/EditorActionButton.h +++ /dev/null @@ -1,76 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#include -#include -#include - -namespace Serialization -{ - typedef AZStd::function StdFunctionActionButtonCalback; - - struct StdFunctionActionButton - : public IActionButton - { - StdFunctionActionButtonCalback callback; - string icon; - - explicit StdFunctionActionButton(const StdFunctionActionButtonCalback& callback, const char* icon = "") - : callback(callback) - , icon(icon) - { - } - - // IActionButton - - virtual void Callback() const override - { - if (callback) - { - callback(); - } - } - - virtual const char* Icon() const override - { - return icon.c_str(); - } - - virtual IActionButtonPtr Clone() const override - { - return IActionButtonPtr(new StdFunctionActionButton(callback, icon.c_str())); - } - - // ~IActionButton - }; - - inline bool Serialize(Serialization::IArchive& ar, StdFunctionActionButton& button, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(static_cast(button)), name, label); - } - else - { - return false; - } - } - - inline StdFunctionActionButton ActionButton(const StdFunctionActionButtonCalback& callback, const char* icon = "") - { - return StdFunctionActionButton(callback, icon); - } -} - diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IGizmoSink.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IGizmoSink.h deleted file mode 100644 index c0d402e484..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IGizmoSink.h +++ /dev/null @@ -1,49 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_IGIZMOSINK_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_IGIZMOSINK_H -#pragma once - - -namespace Serialization { - struct LocalPosition; - struct LocalFrame; - struct LocalOrientation; - - struct GizmoFlags - { - bool visible; - bool selected; - - GizmoFlags() - : visible(true) - , selected(false) {} - }; - - struct IGizmoSink - { - virtual ~IGizmoSink() = default; - virtual int CurrentGizmoIndex() const = 0; - virtual int Write(const LocalPosition&, const GizmoFlags& flags, const void* handle) = 0; - virtual int Write(const LocalOrientation&, const GizmoFlags& flags, const void* handle) = 0; - virtual int Write(const LocalFrame&, const GizmoFlags& flags, const void* handle) = 0; - virtual void SkipRead() = 0; - virtual bool Read(LocalPosition* position, GizmoFlags* flags, const void* handle) = 0; - virtual bool Read(LocalOrientation* position, GizmoFlags* flags, const void* handle) = 0; - virtual bool Read(LocalFrame* position, GizmoFlags* flags, const void* handle) = 0; - virtual void Reset(const void* handle) = 0; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_IGIZMOSINK_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/INavigationProvider.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/INavigationProvider.h deleted file mode 100644 index 8efe913c03..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/INavigationProvider.h +++ /dev/null @@ -1,43 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_INAVIGATIONPROVIDER_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_INAVIGATIONPROVIDER_H -#pragma once - -namespace Serialization -{ - struct SNavigationContext - { - string path; - }; - - struct INavigationProvider - { - virtual ~INavigationProvider() = default; - virtual const char* GetIcon(const char* type, const char* path) const = 0; - virtual const char* GetFileSelectorMaskForType(const char* type) const = 0; - virtual const char* GetEngineTypeForInputType(const char* extension) const { return extension; } - virtual bool IsSelected(const char* type, const char* path, int index) const = 0; - virtual bool IsActive(const char* type, const char* path, int index) const = 0; - virtual bool IsModified(const char* type, const char* path, int index) const = 0; - virtual bool Select(const char* type, const char* path, int index) const = 0; - virtual bool CanSelect([[maybe_unused]] const char* type, [[maybe_unused]] const char* path, [[maybe_unused]] int index) const { return false; } - virtual bool CanPickFile([[maybe_unused]] const char* type, [[maybe_unused]] int index) const { return true; } - virtual bool CanCreate([[maybe_unused]] const char* type, [[maybe_unused]] int index) const { return false; } - virtual bool Create([[maybe_unused]] const char* type, [[maybe_unused]] const char* path, [[maybe_unused]] int index) const { return false; } - virtual bool IsRegistered([[maybe_unused]] const char* type) const { return false; } - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_INAVIGATIONPROVIDER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IconXPM.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IconXPM.h deleted file mode 100644 index 17154e3c6f..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/IconXPM.h +++ /dev/null @@ -1,100 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_ICONXPM_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_ICONXPM_H -#pragma once - -namespace Serialization { - class IArchive; - - // Icon, stored in XPM format - struct IconXPM - { - const char* const* source; - int lineCount; - - IconXPM() - : source(0) - , lineCount(0) - { - } - template - explicit IconXPM(const char* (&xpm)[Size]) - { - source = xpm; - lineCount = Size; - } - - void Serialize([[maybe_unused]] Serialization::IArchive& ar) {} - bool operator<(const IconXPM& rhs) const { return source < rhs.source; } - }; - - struct IconXPMToggle - { - bool* variable_; - bool value_; - IconXPM iconTrue_; - IconXPM iconFalse_; - - template - IconXPMToggle(bool& variable, char* (&xpmTrue)[Size1], char* (&xpmFalse)[Size2]) - : iconTrue_(xpmTrue) - , iconFalse_(xpmFalse) - , variable_(&variable) - , value_(variable) - { - } - - IconXPMToggle(bool& variable, const IconXPM& iconTrue, const IconXPM& iconFalse) - : iconTrue_(iconTrue) - , iconFalse_(iconFalse) - , variable_(&variable) - , value_(variable) - { - } - - IconXPMToggle(const IconXPMToggle& orig) - : variable_(0) - , value_(orig.value_) - , iconTrue_(orig.iconTrue_) - , iconFalse_(orig.iconFalse_) - { - } - - IconXPMToggle() - : variable_(0) - { - } - IconXPMToggle& operator=(const IconXPMToggle& rhs) - { - value_ = rhs.value_; - return *this; - } - ~IconXPMToggle() - { - if (variable_) - { - * variable_ = value_; - } - } - - template - void Serialize(TArchive& ar) - { - ar(value_, "value", "Value"); - } - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_ICONXPM_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButton.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButton.h deleted file mode 100644 index dfbc210f87..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButton.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTON_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTON_H -#pragma once - -namespace Serialization -{ - class IArchive; - - struct ToggleButton - { - bool* value; - - ToggleButton(bool& value) - : value(&value) - { - } - }; - - struct RadioButton - { - int* value; - int buttonValue; - - RadioButton(int& value, int buttonValue) - : value(&value) - , buttonValue(buttonValue) - { - } - }; - - bool Serialize(Serialization::IArchive& ar, Serialization::ToggleButton& button, const char* name, const char* label); - bool Serialize(Serialization::IArchive& ar, Serialization::RadioButton& button, const char* name, const char* label); -} - -#include "ToggleButtonImpl.h" - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTON_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButtonImpl.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButtonImpl.h deleted file mode 100644 index a691d1a33a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Decorators/ToggleButtonImpl.h +++ /dev/null @@ -1,44 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTONIMPL_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTONIMPL_H -#pragma once - -namespace Serialization -{ - inline bool Serialize(Serialization::IArchive& ar, Serialization::ToggleButton& button, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(button), name, label); - } - else - { - return ar(*button.value, name, label); - } - } - - inline bool Serialize(Serialization::IArchive& ar, Serialization::RadioButton& button, const char* name, const char* label) - { - if (ar.IsEdit()) - { - return ar(Serialization::SStruct::ForEdit(button), name, label); - } - else - { - return false; - } - } -} -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_DECORATORS_TOGGLEBUTTONIMPL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.cpp deleted file mode 100644 index 874f70f581..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.cpp +++ /dev/null @@ -1,1522 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include -#include -#include -#include "Serialization/ClassFactory.h" -#include "Serialization/STL.h" -#include "JSONIArchive.h" -#include "Serialization/BlackBox.h" -#include "MemoryReader.h" -#include "MemoryWriter.h" - -#if 0 -# define DEBUG_TRACE(fmt, ...) printf(fmt "\n", __VA_ARGS__) -# define DEBUG_TRACE_TOKENIZER(fmt, ...) printf(fmt "\n", __VA_ARGS__) -#else -# define DEBUG_TRACE(...) -# define DEBUG_TRACE_TOKENIZER(...) -#endif - -namespace Serialization { - static char hexValueTable[256] = { - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0, - - 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 10, 11, 12, 13, 14, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 - }; - - static void unescapeString(std::vector& buf, string& out, const char* begin, const char* end) - { - if (begin >= end) - { - out.clear(); - return; - } - // TODO: use stack string - buf.resize(end - begin); - char* ptr = &buf[0]; - while (begin != end) - { - if (*begin != '\\') - { - *ptr = *begin; - ++ptr; - } - else - { - ++begin; - if (begin == end) - { - break; - } - - switch (*begin) - { - case '0': - *ptr = '\0'; - ++ptr; - break; - case 't': - *ptr = '\t'; - ++ptr; - break; - case 'n': - *ptr = '\n'; - ++ptr; - break; - case 'r': - *ptr = '\r'; - ++ptr; - break; - case '\\': - *ptr = '\\'; - ++ptr; - break; - case '\"': - *ptr = '\"'; - ++ptr; - break; - case '\'': - *ptr = '\''; - ++ptr; - break; - case 'x': - if (begin + 2 < end) - { - *ptr = (hexValueTable[int(begin[1])] << 4) + hexValueTable[int(begin[2])]; - ++ptr; - begin += 2; - break; - } - default: - *ptr = *begin; - ++ptr; - break; - } - } - ++begin; - } - buf.resize(ptr - &buf[0]); - if (!buf.empty()) - { - out.assign(&buf[0], &buf[0] + buf.size()); - } - else - { - out.clear(); - } - } - - // --------------------------------------------------------------------------- - - class JSONTokenizer - { - public: - JSONTokenizer(); - - Token operator()(const char* text) const; - private: - inline bool isSpace(char c) const; - inline bool isWordPart(unsigned char c) const; - inline bool isComment(char c) const; - inline bool isQuoteOpen(int& quoteIndex, char c) const; - inline bool isQuoteClose(int quoteIndex, char c) const; - inline bool isQuote(char c) const; - }; - - JSONTokenizer::JSONTokenizer() - { - } - - inline bool JSONTokenizer::isSpace(char c) const - { - return c == ' ' || c == '\t' || c == '\n' || c == '\r'; - } - - inline bool JSONTokenizer::isComment(char c) const - { - return c == '#'; - } - - - inline bool JSONTokenizer::isQuote(char c) const - { - return c == '\"'; - } - - static const char charTypes[256] = { - 0 /* 0x00: */, - 0 /* 0x01: */, - 0 /* 0x02: */, - 0 /* 0x03: */, - 0 /* 0x04: */, - 0 /* 0x05: */, - 0 /* 0x06: */, - 0 /* 0x07: */, - 0 /* 0x08: */, - 0 /* 0x09: \t */, - 0 /* 0x0A: \n */, - 0 /* 0x0B: */, - 0 /* 0x0C: */, - 0 /* 0x0D: */, - 0 /* 0x0E: */, - 0 /* 0x0F: */, - - - 0 /* 0x10: */, - 0 /* 0x11: */, - 0 /* 0x12: */, - 0 /* 0x13: */, - 0 /* 0x14: */, - 0 /* 0x15: */, - 0 /* 0x16: */, - 0 /* 0x17: */, - 0 /* 0x18: */, - 0 /* 0x19: */, - 0 /* 0x1A: */, - 0 /* 0x1B: */, - 0 /* 0x1C: */, - 0 /* 0x1D: */, - 0 /* 0x1E: */, - 0 /* 0x1F: */, - - - 0 /* 0x20: */, - 0 /* 0x21: ! */, - 0 /* 0x22: " */, - 0 /* 0x23: # */, - 0 /* 0x24: $ */, - 0 /* 0x25: % */, - 0 /* 0x26: & */, - 0 /* 0x27: ' */, - 0 /* 0x28: ( */, - 0 /* 0x29: ) */, - 0 /* 0x2A: * */, - 0 /* 0x2B: + */, - 0 /* 0x2C: , */, - 1 /* 0x2D: - */, - 1 /* 0x2E: . */, - 0 /* 0x2F: / */, - - - 1 /* 0x30: 0 */, - 1 /* 0x31: 1 */, - 1 /* 0x32: 2 */, - 1 /* 0x33: 3 */, - 1 /* 0x34: 4 */, - 1 /* 0x35: 5 */, - 1 /* 0x36: 6 */, - 1 /* 0x37: 7 */, - 1 /* 0x38: 8 */, - 1 /* 0x39: 9 */, - 0 /* 0x3A: : */, - 0 /* 0x3B: ; */, - 0 /* 0x3C: < */, - 0 /* 0x3D: = */, - 0 /* 0x3E: > */, - 0 /* 0x3F: ? */, - - - 0 /* 0x40: @ */, - 1 /* 0x41: A */, - 1 /* 0x42: B */, - 1 /* 0x43: C */, - 1 /* 0x44: D */, - 1 /* 0x45: E */, - 1 /* 0x46: F */, - 1 /* 0x47: G */, - 1 /* 0x48: H */, - 1 /* 0x49: I */, - 1 /* 0x4A: J */, - 1 /* 0x4B: K */, - 1 /* 0x4C: L */, - 1 /* 0x4D: M */, - 1 /* 0x4E: N */, - 1 /* 0x4F: O */, - - - 1 /* 0x50: P */, - 1 /* 0x51: Q */, - 1 /* 0x52: R */, - 1 /* 0x53: S */, - 1 /* 0x54: T */, - 1 /* 0x55: U */, - 1 /* 0x56: V */, - 1 /* 0x57: W */, - 1 /* 0x58: X */, - 1 /* 0x59: Y */, - 1 /* 0x5A: Z */, - 0 /* 0x5B: [ */, - 0 /* 0x5C: \ */, - 0 /* 0x5D: ] */, - 0 /* 0x5E: ^ */, - 1 /* 0x5F: _ */, - - - 0 /* 0x60: ` */, - 1 /* 0x61: a */, - 1 /* 0x62: b */, - 1 /* 0x63: c */, - 1 /* 0x64: d */, - 1 /* 0x65: e */, - 1 /* 0x66: f */, - 1 /* 0x67: g */, - 1 /* 0x68: h */, - 1 /* 0x69: i */, - 1 /* 0x6A: j */, - 1 /* 0x6B: k */, - 1 /* 0x6C: l */, - 1 /* 0x6D: m */, - 1 /* 0x6E: n */, - 1 /* 0x6F: o */, - - - 1 /* 0x70: p */, - 1 /* 0x71: q */, - 1 /* 0x72: r */, - 1 /* 0x73: s */, - 1 /* 0x74: t */, - 1 /* 0x75: u */, - 1 /* 0x76: v */, - 1 /* 0x77: w */, - 1 /* 0x78: x */, - 1 /* 0x79: y */, - 1 /* 0x7A: z */, - 0 /* 0x7B: { */, - 0 /* 0x7C: | */, - 0 /* 0x7D: } */, - 0 /* 0x7E: ~ */, - 0 /* 0x7F: */, - - - 0 /* 0x80: */, - 0 /* 0x81: */, - 0 /* 0x82: */, - 0 /* 0x83: */, - 0 /* 0x84: */, - 0 /* 0x85: */, - 0 /* 0x86: */, - 0 /* 0x87: */, - 0 /* 0x88: */, - 0 /* 0x89: */, - 0 /* 0x8A: */, - 0 /* 0x8B: */, - 0 /* 0x8C: */, - 0 /* 0x8D: */, - 0 /* 0x8E: */, - 0 /* 0x8F: */, - - - 0 /* 0x90: */, - 0 /* 0x91: */, - 0 /* 0x92: */, - 0 /* 0x93: */, - 0 /* 0x94: */, - 0 /* 0x95: */, - 0 /* 0x96: */, - 0 /* 0x97: */, - 0 /* 0x98: */, - 0 /* 0x99: */, - 0 /* 0x9A: */, - 0 /* 0x9B: */, - 0 /* 0x9C: */, - 0 /* 0x9D: */, - 0 /* 0x9E: */, - 0 /* 0x9F: */, - - - 0 /* 0xA0: */, - 0 /* 0xA1: */, - 0 /* 0xA2: */, - 0 /* 0xA3: */, - 0 /* 0xA4: */, - 0 /* 0xA5: */, - 0 /* 0xA6: */, - 0 /* 0xA7: */, - 0 /* 0xA8: */, - 0 /* 0xA9: */, - 0 /* 0xAA: */, - 0 /* 0xAB: */, - 0 /* 0xAC: */, - 0 /* 0xAD: */, - 0 /* 0xAE: */, - 0 /* 0xAF: */, - - - 0 /* 0xB0: */, - 0 /* 0xB1: */, - 0 /* 0xB2: */, - 0 /* 0xB3: */, - 0 /* 0xB4: */, - 0 /* 0xB5: */, - 0 /* 0xB6: */, - 0 /* 0xB7: */, - 0 /* 0xB8: */, - 0 /* 0xB9: */, - 0 /* 0xBA: */, - 0 /* 0xBB: */, - 0 /* 0xBC: */, - 0 /* 0xBD: */, - 0 /* 0xBE: */, - 0 /* 0xBF: */, - - - 0 /* 0xC0: */, - 0 /* 0xC1: */, - 0 /* 0xC2: */, - 0 /* 0xC3: */, - 0 /* 0xC4: */, - 0 /* 0xC5: */, - 0 /* 0xC6: */, - 0 /* 0xC7: */, - 0 /* 0xC8: */, - 0 /* 0xC9: */, - 0 /* 0xCA: */, - 0 /* 0xCB: */, - 0 /* 0xCC: */, - 0 /* 0xCD: */, - 0 /* 0xCE: */, - 0 /* 0xCF: */, - - - 0 /* 0xD0: */, - 0 /* 0xD1: */, - 0 /* 0xD2: */, - 0 /* 0xD3: */, - 0 /* 0xD4: */, - 0 /* 0xD5: */, - 0 /* 0xD6: */, - 0 /* 0xD7: */, - 0 /* 0xD8: */, - 0 /* 0xD9: */, - 0 /* 0xDA: */, - 0 /* 0xDB: */, - 0 /* 0xDC: */, - 0 /* 0xDD: */, - 0 /* 0xDE: */, - 0 /* 0xDF: */, - - - 0 /* 0xE0: */, - 0 /* 0xE1: */, - 0 /* 0xE2: */, - 0 /* 0xE3: */, - 0 /* 0xE4: */, - 0 /* 0xE5: */, - 0 /* 0xE6: */, - 0 /* 0xE7: */, - 0 /* 0xE8: */, - 0 /* 0xE9: */, - 0 /* 0xEA: */, - 0 /* 0xEB: */, - 0 /* 0xEC: */, - 0 /* 0xED: */, - 0 /* 0xEE: */, - 0 /* 0xEF: */, - - - 0 /* 0xF0: */, - 0 /* 0xF1: */, - 0 /* 0xF2: */, - 0 /* 0xF3: */, - 0 /* 0xF4: */, - 0 /* 0xF5: */, - 0 /* 0xF6: */, - 0 /* 0xF7: */, - 0 /* 0xF8: */, - 0 /* 0xF9: */, - 0 /* 0xFA: */, - 0 /* 0xFB: */, - 0 /* 0xFC: */, - 0 /* 0xFD: */, - 0 /* 0xFE: */, - 0 /* 0xFF: */ - }; - - inline bool JSONTokenizer::isWordPart(unsigned char c) const - { - return charTypes[c] != 0; - } - - Token JSONTokenizer::operator()(const char* ptr) const - { - while (isSpace(*ptr)) - { - ++ptr; - } - Token cur(ptr, ptr); - while (!cur && *ptr != '\0') - { - while (isComment(*cur.end)) - { - while (*cur.end && *cur.end != '\n') - { - ++cur.end; - } - while (isSpace(*cur.end)) - { - ++cur.end; - } - DEBUG_TRACE_TOKENIZER("Got comment: '%s'", string(commentStart, cur.end).c_str()); - cur.start = cur.end; - } - CRY_ASSERT(!isSpace(*cur.end)); - if (isQuote(*cur.end)) - { - ++cur.end; - while (*cur.end) - { - if (*cur.end == '\\') - { - ++cur.end; - if (*cur.end) - { - if (*cur.end != 'x' && *cur.end != 'X') - { - ++cur.end; - } - else - { - ++cur.end; - if (*cur.end) - { - ++cur.end; - } - } - continue; - } - } - if (isQuote(*cur.end)) - { - ++cur.end; - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - else - { - ++cur.end; - } - } - } - else - { - if (!*cur.end) - { - return cur; - } - - DEBUG_TRACE_TOKENIZER("%c", *cur.end); - if (isWordPart(*cur.end)) - { - do - { - ++cur.end; - } while (isWordPart(*cur.end) != 0); - } - else - { - ++cur.end; - return cur; - } - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - } - DEBUG_TRACE_TOKENIZER("Tokenizer result: '%s'", cur.str().c_str()); - return cur; - } - - - // --------------------------------------------------------------------------- - - JSONIArchive::JSONIArchive() - : IArchive(INPUT | TEXT) - , buffer_(0) - { - } - - JSONIArchive::~JSONIArchive() - { - if (buffer_) - { - free(buffer_); - buffer_ = 0; - } - stack_.clear(); - reader_.reset(); - } - - bool JSONIArchive::open(const char* buffer, size_t length, bool free) - { - if (!length) - { - return false; - } - - if (buffer) - { - reader_.reset(new MemoryReader(buffer, length, free)); - } - buffer_ = 0; - - token_ = Token(reader_->begin(), reader_->begin()); - stack_.clear(); - - stack_.push_back(Level()); - readToken(); - putToken(); - stack_.back().start = token_.end; - return true; - } - - - bool JSONIArchive::load(const char* filename) - { - FILE* file = nullptr; - azfopen(&file, filename, "rb"); - if (file) - { - fseek(file, 0, SEEK_END); - long fileSize = ftell(file); - fseek(file, 0, SEEK_SET); - - void* buffer = 0; - if (fileSize > 0) - { - buffer = malloc(fileSize + 1); - CRY_ASSERT(buffer != 0); - memset(buffer, 0, fileSize + 1); - size_t elementsRead = fread(buffer, fileSize, 1, file); - CRY_ASSERT(((char*)(buffer))[fileSize] == '\0'); - if (elementsRead != 1) - { - free(buffer); - return false; - } - } - fclose(file); - - filename_ = filename; - buffer_ = buffer; - if (fileSize > 0) - { - return open((char*)buffer, fileSize, false); - } - else - { - return false; - } - } - else - { - return false; - } - } - - void JSONIArchive::readToken() - { - JSONTokenizer tokenizer; - token_ = tokenizer(token_.end); - DEBUG_TRACE(" ~ read token '%s' at %i", token_.str().c_str(), token_.start - reader_->begin()); - } - - void JSONIArchive::putToken() - { - DEBUG_TRACE(" putToken: '%s'", token_.str().c_str()); - token_ = Token(token_.start, token_.start); - } - - int JSONIArchive::line(const char* position) const - { - return int(std::count(reader_->begin(), position, '\n') + 1); - } - - bool JSONIArchive::isName(Token token) const - { - if (!token) - { - return false; - } - char firstChar = token.start[0]; - if (firstChar == '"') - { - return true; - } - return false; - } - - - bool JSONIArchive::expect(char token) - { - if (token_ != token) - { - const char* lineEnd = token_.start; - while (lineEnd && *lineEnd != '\0' && *lineEnd != '\r' && *lineEnd != '\n') - { - ++lineEnd; - } - - MemoryWriter msg; - msg << "Error parsing file, expected ':' at line " << line(token_.start) << ":\n" - << string(token_.start, lineEnd).c_str(); - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - return true; - } - - void JSONIArchive::skipBlock() - { - DEBUG_TRACE("Skipping block from %i ...", token_.end - reader_->begin()); - if (openBracket() || openContainerBracket()) - { - closeBracket(); // Skipping entire block - } - else - { - readToken(); // Skipping value - } - readToken(); - if (token_ != ',') - { - putToken(); - } - DEBUG_TRACE(" ...till %i", token_.end - reader_->begin()); - } - - bool JSONIArchive::findName(const char* name, Token* outName) - { - DEBUG_TRACE(" * finding name '%s'", name); - DEBUG_TRACE(" started at byte %i", int(token_.start - reader_->begin())); - if (stack_.empty()) - { - // TODO: diagnose - return false; - } - if (stack_.back().isKeyValue) - { - return true; - } - const char* start = 0; - const char* blockBegin = stack_.back().start; - if (*blockBegin == '\0') - { - return false; - } - - readToken(); - if (token_ == ',') - { - readToken(); - } - if (!token_) - { - start = blockBegin; - token_.set(blockBegin, blockBegin); - readToken(); - } - - if (stack_.size() == 1 || stack_.back().isContainer || outName != 0) - { - if (token_ == ']' || token_ == '}') - { - DEBUG_TRACE("Got close bracket..."); - putToken(); - return false; - } - else - { - DEBUG_TRACE("Got unnamed value: '%s'", token_.str().c_str()); - putToken(); - return true; - } - } - else - { - if (isName(token_)) - { - DEBUG_TRACE("Seems to be a name '%s'", token_.str().c_str()); - Token nameContent(token_.start + 1, token_.end - 1); - if (nameContent == name) - { - readToken(); - expect(':'); - DEBUG_TRACE("Got one"); - return true; - } - else - { - start = token_.start; - - readToken(); - expect(':'); - skipBlock(); - } - } - else - { - start = token_.start; - if (token_ == ']' || token_ == '}') - { - token_ = Token(blockBegin, blockBegin); - } - else - { - putToken(); - skipBlock(); - } - } - } - - while (true) - { - readToken(); - if (!token_) - { - token_.set(blockBegin, blockBegin); - continue; - } - //return false; // Reached end of file while searching for name - DEBUG_TRACE("'%s'", token_.str().c_str()); - DEBUG_TRACE("Checking for loop: %i and %i", token_.start - reader_->begin(), start - reader_->begin()); - CRY_ASSERT(start != 0); - if (token_.start == start) - { - putToken(); - DEBUG_TRACE("unable to find..."); - return false; // Reached a full circle: unable to find name - } - - if (token_ == '}' || token_ == ']') // CONVERSION - { - DEBUG_TRACE("Going to begin of block, from %i", token_.start - reader_->begin()); - token_ = Token(blockBegin, blockBegin); - DEBUG_TRACE(" to %i", token_.start - reader_->begin()); - continue; // Reached '}' or ']' while searching for name, continue from begin of block - } - - if (name[0] == '\0') - { - if (isName(token_)) - { - readToken(); - if (!token_) - { - return false; // Reached end of file while searching for name - } - expect(':'); - skipBlock(); - } - else - { - putToken(); // Not a name - put it back - return true; - } - } - else - { - if (isName(token_)) - { - Token nameContent(token_.start + 1, token_.end - 1); - readToken(); - expect(':'); - if (nameContent == name) - { - return true; - } - else - { - skipBlock(); - } - } - else - { - putToken(); - skipBlock(); - } - } - } - - return false; - } - - bool JSONIArchive::openBracket() - { - readToken(); - if (token_ == '{') - { - return true; - } - putToken(); - return false; - } - - bool JSONIArchive::closeBracket() - { - int relativeLevel = 0; - while (true) - { - readToken(); - if (token_ == ',') - { - readToken(); - } - if (!token_) - { - MemoryWriter msg; - CRY_ASSERT(!stack_.empty()); - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while no matching bracket found"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - else if (token_ == '}' || token_ == ']') // CONVERSION - { - if (relativeLevel == 0) - { - return true; - } - else - { - --relativeLevel; - } - } - else if (token_ == '{' || token_ == '[') // CONVERSION - { - ++relativeLevel; - } - } - return false; - } - - bool JSONIArchive::openContainerBracket() - { - readToken(); - if (token_ == '[') - { - return true; - } - putToken(); - return false; - } - - bool JSONIArchive::closeContainerBracket() - { - readToken(); - if (token_ == ']') - { - DEBUG_TRACE("closeContainerBracket(): ok"); - return true; - } - else - { - DEBUG_TRACE("closeContainerBracket(): failed ('%s')", token_.str().c_str()); - putToken(); - return false; - } - } - - bool JSONIArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - } - else if (openContainerBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - stack_.back().isContainer = true; - } - else - { - return false; - } - - ser(*this); - CRY_ASSERT(!stack_.empty()); - stack_.pop_back(); -#if !defined(NDEBUG) - bool closed = -#endif - closeBracket(); - CRY_ASSERT(closed); - return true; - } - return false; - } - - bool JSONIArchive::operator()(const SBlackBox& box, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket() || openContainerBracket()) - { - const char* start = token_.start; - putToken(); - skipBlock(); - const char* end = token_.start; - if (end < start) - { - CRY_ASSERT(0); - return false; - } - while (end > start && - (*(end - 1) == ' ' - || *(end - 1) == '\r' - || *(end - 1) == '\n' - || *(end - 1) == '\t')) - { - --end; - } - // box has to be const in the interface so we can serialize - // temporary variables (i.e. function call result or structures - // constructed on the stack) - const_cast(box).set("json", (void*)start, end - start); - return true; - } - } - return false; - } - - bool JSONIArchive::operator()(IKeyValue& keyValue, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) - { - Token nextName; - if (!stack_.empty() && stack_.back().isContainer) - { - readToken(); - if (isName(token_) && checkStringValueToken()) - { - string key; - unescapeString(unescapeBuffer_, key, token_.start + 1, token_.end - 1); - keyValue.set(key.c_str()); - readToken(); - if (!expect(':')) - { - return false; - } - if (!keyValue.serializeValue(*this, "", 0)) - { - return false; - } - return true; - } - else - { - putToken(); - return false; - } - } - else if (findName("", &nextName)) - { - string key; - unescapeString(unescapeBuffer_, key, nextName.start + 1, nextName.end - 1); - keyValue.set(key.c_str()); - stack_.push_back(Level()); - stack_.back().isKeyValue = true; - - bool result = keyValue.serializeValue(*this, "", 0); - if (stack_.empty()) - { - // TODO: diagnose - return false; - } - stack_.pop_back(); - return result; - } - return false; - } - - - bool JSONIArchive::operator()(IPointer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - if (openBracket()) - { - stack_.push_back(Level()); - stack_.back().start = token_.end; - stack_.back().isKeyValue = true; - - readToken(); - if (isName(token_)) - { - if (checkStringValueToken()) - { - string typeName; - unescapeString(unescapeBuffer_, typeName, token_.start + 1, token_.end - 1); - if (strcmp(ser.registeredTypeName(), typeName.c_str()) != 0) - { - ser.create(typeName.c_str()); - } - readToken(); - expect(':'); - operator()(ser.serializer(), "", 0); - } - } - else - { - putToken(); - - ser.create(""); - } - closeBracket(); - stack_.pop_back(); - return true; - } - } - return false; - } - - - bool JSONIArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - bool containerBracket = openContainerBracket(); - bool dictionaryBracket = false; - if (!containerBracket) - { - dictionaryBracket = openBracket(); - } - if (containerBracket || dictionaryBracket) - { - stack_.push_back(Level()); - stack_.back().isContainer = true; - stack_.back().start = token_.end; - - std::size_t size = ser.size(); - std::size_t index = 0; - - while (true) - { - readToken(); - if (token_ == ',') - { - readToken(); - } - if (token_ == '}' || token_ == ']') - { - break; - } - else if (!token_) - { - CRY_ASSERT(0 && "Reached end of file while reading container!"); - return false; - } - putToken(); - if (index == size) - { - size = index + 1; - } - if (index < size) - { - if (!ser(*this, "", "")) - { - // We've got a named item within a container, - // i.e. looks like a dictionary but not a container. - // Bail out, it is nothing we can do here. - closeBracket(); - break; - } - } - else - { - skipBlock(); - } - ser.next(); - ++index; - } - if (size > index) - { - ser.resize(index); - } - - CRY_ASSERT(!stack_.empty()); - stack_.pop_back(); - return true; - } - } - return false; - } - - void JSONIArchive::checkValueToken() - { - if (!token_) - { - CRY_ASSERT(!stack_.empty()); - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while reading element's value"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - } - } - - bool JSONIArchive::checkStringValueToken() - { - if (!token_) - { - return false; - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": End of file while reading element's value"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - if (token_.start[0] != '"' || token_.end[-1] != '"') - { - return false; - MemoryWriter msg; - const char* start = stack_.back().start; - msg << filename_.c_str() << ": " << line(start) << " line"; - msg << ": Expected string"; - CRY_ASSERT_MESSAGE(0, msg.c_str()); - return false; - } - return true; - } - - bool JSONIArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = strtoul(token_.start, 0, 10); - return true; - } - return false; - } - - - bool JSONIArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (int16)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (uint16)strtoul(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = _strtoi64(token_.start, 0, 10); -#else - value = strtoll(token_.start, 0, 10); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = _strtoui64(token_.start, 0, 10); -#else - value = strtoull(token_.start, 0, 10); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = float(std::atof(token_.str().c_str())); -#else - value = strtof(token_.start, 0); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); -#ifdef _MSC_VER - value = std::atof(token_.str().c_str()); -#else - value = strtod(token_.start, 0); -#endif - return true; - } - return false; - } - - bool JSONIArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - if (checkStringValueToken()) - { - string buf; - unescapeString(unescapeBuffer_, buf, token_.start + 1, token_.end - 1); - value.set(buf.c_str()); - } - else - { - return false; - } - return true; - } - return false; - } - - - inline size_t utf8InUtf16Len(const char* p) - { - size_t result = 0; - - for (; *p; ++p) - { - unsigned char ch = (unsigned char)(*p); - - if (ch < 0x80 || (ch >= 0xC0 && ch < 0xFC)) - { - ++result; - } - } - - return result; - } - - inline const char* readUtf16FromUtf8(unsigned int* ch, const char* s) - { - const unsigned char byteMark = 0x80; - const unsigned char byteMaskRead = 0x3F; - - const unsigned char* str = (const unsigned char*)s; - - size_t len; - if (*str < byteMark) - { - *ch = *str; - return s + 1; - } - else if (*str < 0xC0) - { - *ch = ' '; - return s + 1; - } - else if (*str < 0xE0) - { - len = 2; - } - else if (*str < 0xF0) - { - len = 3; - } - else if (*str < 0xF8) - { - len = 4; - } - else if (*str < 0xFC) - { - len = 5; - } - else - { - *ch = ' '; - return s + 1; - } - - const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - *ch = (*str++ & ~firstByteMark[len]); - - switch (len) - { - case 5: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 4: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 3: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - case 2: - (*ch) <<= 6; - (*ch) += (*str++ & byteMaskRead); - } - - return (const char*)str; - } - - - inline void utf8ToUtf16(wstring* out, const char* in) - { - out->clear(); - out->reserve(utf8InUtf16Len(in)); - - for (; *in; ) - { - unsigned int character; - in = readUtf16FromUtf8(&character, in); - (*out) += (wchar_t)character; - } - } - - - bool JSONIArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - if (checkStringValueToken()) - { - string buf; - unescapeString(unescapeBuffer_, buf, token_.start + 1, token_.end - 1); - wstring wbuf; - utf8ToUtf16(&wbuf, buf.c_str()); - value.set(wbuf.c_str()); - } - else - { - return false; - } - return true; - } - return false; - } - - bool JSONIArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - if (token_ == "true") - { - value = true; - } - else if (token_ == "false") - { - value = false; - } - else - { - CRY_ASSERT(0 && "Invalid boolean value"); - } - return true; - } - return false; - } - - bool JSONIArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (int8)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (uint8)strtol(token_.start, 0, 10); - return true; - } - return false; - } - - bool JSONIArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - if (findName(name)) - { - readToken(); - checkValueToken(); - value = (char)strtol(token_.start, 0, 10); - return true; - } - return false; - } -} -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.h deleted file mode 100644 index 60ce90672c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONIArchive.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONIARCHIVE_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONIARCHIVE_H -#pragma once - -#include "Pointers.h" -#include "Serialization/IArchive.h" -#include "Serialization/MemoryReader.h" -#include "Token.h" -#include "EditorCommonAPI.h" -#include -#include - -namespace Serialization { - class MemoryReader; - - class JSONIArchive - : public IArchive - { - public: - JSONIArchive(); - ~JSONIArchive(); - - bool load(const char* filename); - bool open(const char* buffer, size_t length, bool free = false); - - // virtuals: - bool operator()(bool& value, const char* name = "", const char* label = 0); - bool operator()(IString& value, const char* name = "", const char* label = 0); - bool operator()(IWString& value, const char* name = "", const char* label = 0); - bool operator()(float& value, const char* name = "", const char* label = 0); - bool operator()(double& value, const char* name = "", const char* label = 0); - bool operator()(int16& value, const char* name = "", const char* label = 0); - bool operator()(uint16& value, const char* name = "", const char* label = 0); - bool operator()(int32& value, const char* name = "", const char* label = 0); - bool operator()(uint32& value, const char* name = "", const char* label = 0); - bool operator()(int64& value, const char* name = "", const char* label = 0); - bool operator()(uint64& value, const char* name = "", const char* label = 0); - - bool operator()(int8& value, const char* name = "", const char* label = 0); - bool operator()(uint8& value, const char* name = "", const char* label = 0); - bool operator()(char& value, const char* name = "", const char* label = 0); - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0); - bool operator()(const SBlackBox& ser, const char* name = "", const char* label = 0); - bool operator()(IContainer& ser, const char* name = "", const char* label = 0); - bool operator()(IKeyValue& ser, const char* name = "", const char* label = 0); - bool operator()(IPointer& ser, const char* name = "", const char* label = 0); - - using IArchive::operator(); - - private: - bool findName(const char* name, Token* outName = 0); - bool openBracket(); - bool closeBracket(); - - bool openContainerBracket(); - bool closeContainerBracket(); - - void checkValueToken(); - bool checkStringValueToken(); - void readToken(); - void putToken(); - int line(const char* position) const; - bool isName(Token token) const; - - bool expect(char token); - void skipBlock(); - - struct Level - { - const char* start; - const char* firstToken; - bool isContainer; - bool isKeyValue; - Level() - : isContainer(false) - , isKeyValue(false) {} - }; - typedef std::vector Stack; - Stack stack_; - - std::unique_ptr reader_; - Token token_; - std::vector unescapeBuffer_; - AZStd::string filename_; - void* buffer_; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONIARCHIVE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.cpp deleted file mode 100644 index fa71eee245..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.cpp +++ /dev/null @@ -1,828 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "JSONOArchive.h" -#include "MemoryWriter.h" -#include "Serialization/KeyValue.h" -#include "Serialization/ClassFactory.h" -#include "Serialization/BlackBox.h" -#include - -namespace Serialization { - // Some of non-latin1 characters here are not escaped to - // keep compatibility with 8-bit local encoding (e.g. windows-1251) - static const char* escapeTable[256] = { - "\\0" /* 0x00: */, - "\\x01" /* 0x01: */, - "\\x02" /* 0x02: */, - "\\x03" /* 0x03: */, - "\\x04" /* 0x04: */, - "\\x05" /* 0x05: */, - "\\x06" /* 0x06: */, - "\\x07" /* 0x07: */, - "\\x08" /* 0x08: */, - "\\t" /* 0x09: \t */, - "\\n" /* 0x0A: \n */, - "\\x0B" /* 0x0B: */, - "\\x0C" /* 0x0C: */, - "\\r" /* 0x0D: */, - "\\x0E" /* 0x0E: */, - "\\x0F" /* 0x0F: */, - - - "\\x10" /* 0x10: */, - "\\x11" /* 0x11: */, - "\\x12" /* 0x12: */, - "\\x13" /* 0x13: */, - "\\x14" /* 0x14: */, - "\\x15" /* 0x15: */, - "\\x16" /* 0x16: */, - "\\x17" /* 0x17: */, - "\\x18" /* 0x18: */, - "\\x19" /* 0x19: */, - "\\x1A" /* 0x1A: */, - "\\x1B" /* 0x1B: */, - "\\x1C" /* 0x1C: */, - "\\x1D" /* 0x1D: */, - "\\x1E" /* 0x1E: */, - "\\x1F" /* 0x1F: */, - - - " " /* 0x20: */, - "!" /* 0x21: ! */, - "\\\"" /* 0x22: " */, - "#" /* 0x23: # */, - "$" /* 0x24: $ */, - "%" /* 0x25: % */, - "&" /* 0x26: & */, - "'" /* 0x27: ' */, - "(" /* 0x28: ( */, - ")" /* 0x29: ) */, - "*" /* 0x2A: * */, - "+" /* 0x2B: + */, - "," /* 0x2C: , */, - "-" /* 0x2D: - */, - "." /* 0x2E: . */, - "/" /* 0x2F: / */, - - - "0" /* 0x30: 0 */, - "1" /* 0x31: 1 */, - "2" /* 0x32: 2 */, - "3" /* 0x33: 3 */, - "4" /* 0x34: 4 */, - "5" /* 0x35: 5 */, - "6" /* 0x36: 6 */, - "7" /* 0x37: 7 */, - "8" /* 0x38: 8 */, - "9" /* 0x39: 9 */, - ":" /* 0x3A: : */, - ";" /* 0x3B: ; */, - "<" /* 0x3C: < */, - "=" /* 0x3D: = */, - ">" /* 0x3E: > */, - "?" /* 0x3F: ? */, - - - "@" /* 0x40: @ */, - "A" /* 0x41: A */, - "B" /* 0x42: B */, - "C" /* 0x43: C */, - "D" /* 0x44: D */, - "E" /* 0x45: E */, - "F" /* 0x46: F */, - "G" /* 0x47: G */, - "H" /* 0x48: H */, - "I" /* 0x49: I */, - "J" /* 0x4A: J */, - "K" /* 0x4B: K */, - "L" /* 0x4C: L */, - "M" /* 0x4D: M */, - "N" /* 0x4E: N */, - "O" /* 0x4F: O */, - - - "P" /* 0x50: P */, - "Q" /* 0x51: Q */, - "R" /* 0x52: R */, - "S" /* 0x53: S */, - "T" /* 0x54: T */, - "U" /* 0x55: U */, - "V" /* 0x56: V */, - "W" /* 0x57: W */, - "X" /* 0x58: X */, - "Y" /* 0x59: Y */, - "Z" /* 0x5A: Z */, - "[" /* 0x5B: [ */, - "\\\\" /* 0x5C: \ */, - "]" /* 0x5D: ] */, - "^" /* 0x5E: ^ */, - "_" /* 0x5F: _ */, - - - "`" /* 0x60: ` */, - "a" /* 0x61: a */, - "b" /* 0x62: b */, - "c" /* 0x63: c */, - "d" /* 0x64: d */, - "e" /* 0x65: e */, - "f" /* 0x66: f */, - "g" /* 0x67: g */, - "h" /* 0x68: h */, - "i" /* 0x69: i */, - "j" /* 0x6A: j */, - "k" /* 0x6B: k */, - "l" /* 0x6C: l */, - "m" /* 0x6D: m */, - "n" /* 0x6E: n */, - "o" /* 0x6F: o */, - - - "p" /* 0x70: p */, - "q" /* 0x71: q */, - "r" /* 0x72: r */, - "s" /* 0x73: s */, - "t" /* 0x74: t */, - "u" /* 0x75: u */, - "v" /* 0x76: v */, - "w" /* 0x77: w */, - "x" /* 0x78: x */, - "y" /* 0x79: y */, - "z" /* 0x7A: z */, - "{" /* 0x7B: { */, - "|" /* 0x7C: | */, - "}" /* 0x7D: } */, - "~" /* 0x7E: ~ */, - "\x7F" /* 0x7F: */, // for utf-8 - - - "\x80" /* 0x80: */, - "\x81" /* 0x81: */, - "\x82" /* 0x82: */, - "\x83" /* 0x83: */, - "\x84" /* 0x84: */, - "\x85" /* 0x85: */, - "\x86" /* 0x86: */, - "\x87" /* 0x87: */, - "\x88" /* 0x88: */, - "\x89" /* 0x89: */, - "\x8A" /* 0x8A: */, - "\x8B" /* 0x8B: */, - "\x8C" /* 0x8C: */, - "\x8D" /* 0x8D: */, - "\x8E" /* 0x8E: */, - "\x8F" /* 0x8F: */, - - - "\x90" /* 0x90: */, - "\x91" /* 0x91: */, - "\x92" /* 0x92: */, - "\x93" /* 0x93: */, - "\x94" /* 0x94: */, - "\x95" /* 0x95: */, - "\x96" /* 0x96: */, - "\x97" /* 0x97: */, - "\x98" /* 0x98: */, - "\x99" /* 0x99: */, - "\x9A" /* 0x9A: */, - "\x9B" /* 0x9B: */, - "\x9C" /* 0x9C: */, - "\x9D" /* 0x9D: */, - "\x9E" /* 0x9E: */, - "\x9F" /* 0x9F: */, - - - "\xA0" /* 0xA0: */, - "\xA1" /* 0xA1: */, - "\xA2" /* 0xA2: */, - "\xA3" /* 0xA3: */, - "\xA4" /* 0xA4: */, - "\xA5" /* 0xA5: */, - "\xA6" /* 0xA6: */, - "\xA7" /* 0xA7: */, - "\xA8" /* 0xA8: */, - "\xA9" /* 0xA9: */, - "\xAA" /* 0xAA: */, - "\xAB" /* 0xAB: */, - "\xAC" /* 0xAC: */, - "\xAD" /* 0xAD: */, - "\xAE" /* 0xAE: */, - "\xAF" /* 0xAF: */, - - - "\xB0" /* 0xB0: */, - "\xB1" /* 0xB1: */, - "\xB2" /* 0xB2: */, - "\xB3" /* 0xB3: */, - "\xB4" /* 0xB4: */, - "\xB5" /* 0xB5: */, - "\xB6" /* 0xB6: */, - "\xB7" /* 0xB7: */, - "\xB8" /* 0xB8: */, - "\xB9" /* 0xB9: */, - "\xBA" /* 0xBA: */, - "\xBB" /* 0xBB: */, - "\xBC" /* 0xBC: */, - "\xBD" /* 0xBD: */, - "\xBE" /* 0xBE: */, - "\xBF" /* 0xBF: */, - - - "\xC0" /* 0xC0: */, - "\xC1" /* 0xC1: */, - "\xC2" /* 0xC2: */, - "\xC3" /* 0xC3: */, - "\xC4" /* 0xC4: */, - "\xC5" /* 0xC5: */, - "\xC6" /* 0xC6: */, - "\xC7" /* 0xC7: */, - "\xC8" /* 0xC8: */, - "\xC9" /* 0xC9: */, - "\xCA" /* 0xCA: */, - "\xCB" /* 0xCB: */, - "\xCC" /* 0xCC: */, - "\xCD" /* 0xCD: */, - "\xCE" /* 0xCE: */, - "\xCF" /* 0xCF: */, - - - "\xD0" /* 0xD0: */, - "\xD1" /* 0xD1: */, - "\xD2" /* 0xD2: */, - "\xD3" /* 0xD3: */, - "\xD4" /* 0xD4: */, - "\xD5" /* 0xD5: */, - "\xD6" /* 0xD6: */, - "\xD7" /* 0xD7: */, - "\xD8" /* 0xD8: */, - "\xD9" /* 0xD9: */, - "\xDA" /* 0xDA: */, - "\xDB" /* 0xDB: */, - "\xDC" /* 0xDC: */, - "\xDD" /* 0xDD: */, - "\xDE" /* 0xDE: */, - "\xDF" /* 0xDF: */, - - - "\xE0" /* 0xE0: */, - "\xE1" /* 0xE1: */, - "\xE2" /* 0xE2: */, - "\xE3" /* 0xE3: */, - "\xE4" /* 0xE4: */, - "\xE5" /* 0xE5: */, - "\xE6" /* 0xE6: */, - "\xE7" /* 0xE7: */, - "\xE8" /* 0xE8: */, - "\xE9" /* 0xE9: */, - "\xEA" /* 0xEA: */, - "\xEB" /* 0xEB: */, - "\xEC" /* 0xEC: */, - "\xED" /* 0xED: */, - "\xEE" /* 0xEE: */, - "\xEF" /* 0xEF: */, - - - "\xF0" /* 0xF0: */, - "\xF1" /* 0xF1: */, - "\xF2" /* 0xF2: */, - "\xF3" /* 0xF3: */, - "\xF4" /* 0xF4: */, - "\xF5" /* 0xF5: */, - "\xF6" /* 0xF6: */, - "\xF7" /* 0xF7: */, - "\xF8" /* 0xF8: */, - "\xF9" /* 0xF9: */, - "\xFA" /* 0xFA: */, - "\xFB" /* 0xFB: */, - "\xFC" /* 0xFC: */, - "\xFD" /* 0xFD: */, - "\xFE" /* 0xFE: */, - "\xFF" /* 0xFF: */ - }; - - static void escapeString(MemoryWriter& dest, const char* begin, const char* end) - { - while (begin != end) - { - const char* str = escapeTable[(unsigned char)(*begin)]; - dest.write(str); - ++begin; - } - } - - // --------------------------------------------------------------------------- - - static const int TAB_WIDTH = 2; - - JSONOArchive::JSONOArchive(int textWidth, const char* header) - : IArchive(OUTPUT | TEXT) - , header_(header) - , textWidth_(textWidth) - , compactOffset_(0) - { - buffer_.reset(new MemoryWriter(1024, true)); - if (header_) - { - (*buffer_) << header_; - } - - YASLI_ASSERT(stack_.empty()); - stack_.push_back(Level(false, 0, 0)); - } - - JSONOArchive::~JSONOArchive() - { - } - - bool JSONOArchive::save(const char* fileName) - { - YASLI_ESCAPE(fileName && strlen(fileName) > 0, return false); - YASLI_ESCAPE(stack_.size() == 1, return false); - YASLI_ESCAPE(buffer_.get() != 0, return false); - YASLI_ESCAPE(buffer_->position() <= buffer_->size(), return false); - stack_.pop_back(); - FILE* file = nullptr; - azfopen(&file, fileName, "wb"); - if (file) - { - if (fwrite(buffer_->c_str(), 1, buffer_->position(), file) != buffer_->position()) - { - fclose(file); - return false; - } - fclose(file); - return true; - } - else - { - return false; - } - } - - const char* JSONOArchive::c_str() const - { - return buffer_->c_str(); - } - - size_t JSONOArchive::length() const - { - return buffer_->position(); - } - - void JSONOArchive::openBracket() - { - *buffer_ << "{"; - } - - void JSONOArchive::closeBracket() - { - *buffer_ << "}"; - } - - void JSONOArchive::openContainerBracket() - { - *buffer_ << "["; - } - - void JSONOArchive::closeContainerBracket() - { - *buffer_ << "]"; - } - - void JSONOArchive::placeName(const char* name) - { - if (stack_.back().isKeyValue) - { - return; - } - if ((name[0] != '\0' || !stack_.back().isContainer) && stack_.size() > 1) - { - *buffer_ << "\""; - *buffer_ << name; - *buffer_ << "\": "; - stack_.back().nameIndex += 1; - } - } - - void JSONOArchive::placeIndent(bool putComma) - { - if (stack_.back().isKeyValue) - { - return; - } - if (putComma && stack_.back().elementIndex > 0) - { - *buffer_ << ","; - } - if (buffer_->position() > 0) - { - *buffer_ << "\n"; - } - int count = int(stack_.size() - 1); - stack_.back().indentCount += count; - stack_.back().elementIndex += 1; - for (int i = 0; i < count; ++i) - { - *buffer_ << "\t"; - } - compactOffset_ = 0; - } - - void JSONOArchive::placeIndentCompact(bool putComma) - { - if (stack_.back().isKeyValue) - { - return; - } - if (putComma && stack_.back().elementIndex > 0) - { - *buffer_ << ","; - } - if ((compactOffset_ % 32) != 0 && stack_.back().isContainer) - { - *buffer_ << " "; - compactOffset_ += 1; - stack_.back().elementIndex += 1; - } - else if (buffer_->size()) - { - *buffer_ << "\n"; - int count = int(stack_.size() - 1); - stack_.back().indentCount += count /* * TAB_WIDTH*/; - stack_.back().elementIndex += 1; - for (int i = 0; i < count; ++i) - { - *buffer_ << "\t"; - } - compactOffset_ = 1; - } - } - - bool JSONOArchive::operator()(bool& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - *buffer_ << (value ? "true" : "false"); - return true; - } - - - bool JSONOArchive::operator()(IString& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - (*buffer_) << "\""; - const char* str = value.get(); - escapeString(*buffer_, str, str + strlen(value.get())); - (*buffer_) << "\""; - return true; - } - - inline char* writeUtf16ToUtf8(char* s, unsigned int ch) - { - const unsigned char byteMark = 0x80; - const unsigned char byteMask = 0xBF; - - size_t len; - - if (ch < 0x80) - { - len = 1; - } - else if (ch < 0x800) - { - len = 2; - } - else if (ch < 0x10000) - { - len = 3; - } - else if (ch < 0x200000) - { - len = 4; - } - else - { - return s; - } - - s += len; - - const unsigned char firstByteMark[7] = { 0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC }; - switch (len) - { - case 4: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 3: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 2: - *--s = (char)((ch | byteMark) & byteMask); - ch >>= 6; - case 1: - *--s = (char)(ch | firstByteMark[len]); - } - - return s + len; - } - - bool JSONOArchive::operator()(IWString& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - (*buffer_) << "\""; - - const wchar_t* in = value.get(); - for (; *in; ++in) - { - char buf[6]; - escapeString(*buffer_, buf, writeUtf16ToUtf8(buf, *in)); - } - - (*buffer_) << "\""; - return true; - } - - bool JSONOArchive::operator()(float& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(double& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int32& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint32& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int16& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint16& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int64& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint64& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(uint8& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(int8& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(char& value, const char* name, [[maybe_unused]] const char* label) - { - placeIndentCompact(); - placeName(name); - (*buffer_) << value; - return true; - } - - bool JSONOArchive::operator()(const SStruct& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - std::size_t position = buffer_->position(); - openBracket(); - stack_.push_back(Level(false, position, int(strlen(name) + 2 * (name[0] & 1) + (stack_.size() - 1) * TAB_WIDTH + 2))); - - YASLI_ASSERT(ser); - ser(*this); - - bool joined = joinLinesIfPossible(); - bool noNames = stack_.back().nameIndex == 0; - if (noNames) - { - if (stack_.size() != 2) - { - buffer_->buffer()[stack_.back().startPosition] = '['; - } - } - stack_.pop_back(); - if (!joined) - { - placeIndent(false); - } - else - { - *buffer_ << " "; - } - if (noNames) - { - closeContainerBracket(); - } - else - { - closeBracket(); - } - return true; - } - - bool JSONOArchive::operator()(const SBlackBox& box, const char* name, [[maybe_unused]] const char* label) - { - if (strcmp(box.format, "json") != 0) - { - return false; - } - if (box.size == 0) - { - return false; - } - - placeIndent(); - placeName(name); - return buffer_->write(box.data, box.size); - } - - bool JSONOArchive::operator()(IKeyValue& keyValue, [[maybe_unused]] const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - - *buffer_ << "\""; - *buffer_ << keyValue.get(); - *buffer_ << "\": "; - stack_.back().nameIndex += 1; - - stack_.back().isKeyValue = true; - keyValue.serializeValue(*this, "", 0); - stack_.back().isKeyValue = false; - if (stack_.back().isContainer) - { - stack_.back().isDictionary = true; - } - return true; - } - - bool JSONOArchive::operator()(IPointer& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - openBracket(); - const char* registeredTypeName = ser.registeredTypeName(); - if (registeredTypeName && registeredTypeName[0] != '\0') - { - *buffer_ << " "; - placeName(registeredTypeName); - stack_.back().isKeyValue = true; - operator()(ser.serializer(), ""); - stack_.back().isKeyValue = false; - *buffer_ << " "; - } - closeBracket(); - return true; - } - - bool JSONOArchive::operator()(IContainer& ser, const char* name, [[maybe_unused]] const char* label) - { - placeIndent(); - placeName(name); - std::size_t position = buffer_->position(); - openContainerBracket(); - stack_.push_back(Level(true, position, int(strlen(name) + 2 * (name[0] & 1) + stack_.size() - 1 * TAB_WIDTH + 2))); - - std::size_t size = ser.size(); - if (size > 0) - { - do - { - ser(*this, "", ""); - } while (ser.next()); - } - - bool joined = joinLinesIfPossible(); - bool isDictionary = stack_.back().isDictionary; - if (isDictionary) - { - buffer_->buffer()[stack_.back().startPosition] = '{'; - } - stack_.pop_back(); - if (!joined) - { - placeIndent(false); - } - else - { - *buffer_ << " "; - } - - if (isDictionary) - { - closeBracket(); - } - else - { - closeContainerBracket(); - } - return true; - } - - static char* joinLines(char* start, char* end) - { - YASLI_ASSERT(start <= end); - char* next = start; - while (next != end) - { - if (*next != '\t' && *next != '\r') - { - if (*next != '\n') - { - *start = *next; - } - else - { - *start = ' '; - } - ++start; - } - ++next; - } - return start; - } - - bool JSONOArchive::joinLinesIfPossible() - { - YASLI_ASSERT(!stack_.empty()); - std::size_t startPosition = stack_.back().startPosition; - YASLI_ASSERT(startPosition < buffer_->size()); - int indentCount = stack_.back().indentCount; - //YASLI_ASSERT(startPosition >= indentCount); - if (buffer_->position() - startPosition - indentCount < std::size_t(textWidth_)) - { - char* buffer = buffer_->buffer(); - char* start = buffer + startPosition; - char* end = buffer + buffer_->position(); - end = joinLines(start, end); - std::size_t newPosition = end - buffer; - YASLI_ASSERT(newPosition <= buffer_->position()); - buffer_->setPosition(newPosition); - return true; - } - return false; - } -} -// vim:ts=4 sw=4: diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.h deleted file mode 100644 index 085e1abf16..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/JSONOArchive.h +++ /dev/null @@ -1,108 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONOARCHIVE_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONOARCHIVE_H -#pragma once - -#include "Serialization/IArchive.h" -#include "Serialization/MemoryWriter.h" -#include "EditorCommonAPI.h" -#include - -namespace Serialization { - class MemoryWriter; - - class JSONOArchive - : public IArchive - { - public: - // header = 0 - default header, use "" to omit - JSONOArchive(int textWidth = 80, const char* header = 0); - ~JSONOArchive(); - - bool save(const char* fileName); - - const char* c_str() const; - const char* buffer() const { return c_str(); } - size_t length() const; - - // from Archive: - bool operator()(bool& value, const char* name = "", const char* label = 0); - bool operator()(IString& value, const char* name = "", const char* label = 0); - bool operator()(IWString& value, const char* name = "", const char* label = 0); - bool operator()(float& value, const char* name = "", const char* label = 0); - bool operator()(double& value, const char* name = "", const char* label = 0); - bool operator()(int16& value, const char* name = "", const char* label = 0); - bool operator()(uint16& value, const char* name = "", const char* label = 0); - bool operator()(int32& value, const char* name = "", const char* label = 0); - bool operator()(uint32& value, const char* name = "", const char* label = 0); - bool operator()(int64& value, const char* name = "", const char* label = 0); - bool operator()(uint64& value, const char* name = "", const char* label = 0); - - bool operator()(char& value, const char* name = "", const char* label = 0); - bool operator()(int8& value, const char* name = "", const char* label = 0); - bool operator()(uint8& value, const char* name = "", const char* label = 0); - - bool operator()(const SStruct& ser, const char* name = "", const char* label = 0); - bool operator()(const SBlackBox& box, const char* name = "", const char* label = 0); - bool operator()(IContainer& ser, const char* name = "", const char* label = 0); - bool operator()(IKeyValue& keyValue, const char* name = "", const char* label = 0); - bool operator()(IPointer& ser, const char* name = "", const char* label = 0); - // ^^^ - - using IArchive::operator(); - - private: - void openBracket(); - void closeBracket(); - void openContainerBracket(); - void closeContainerBracket(); - void placeName(const char* name); - void placeIndent(bool putComma = true); - void placeIndentCompact(bool putComma = true); - - bool joinLinesIfPossible(); - - struct Level - { - Level(bool _isContainer, std::size_t position, int column) - : isContainer(_isContainer) - , isKeyValue(false) - , isDictionary(false) - , startPosition(position) - , indentCount(-column) - , elementIndex(0) - , nameIndex(0) - {} - bool isKeyValue; - bool isContainer; - bool isDictionary; - std::size_t startPosition; - int nameIndex; - int elementIndex; - int indentCount; - }; - - typedef std::vector Stack; - Stack stack_; - std::unique_ptr buffer_; - const char* header_; - int textWidth_; - string fileName_; - int compactOffset_; - bool isKeyValue_; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_JSONOARCHIVE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.cpp deleted file mode 100644 index 995064a57a..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include -#include "Serialization/Assert.h" -#include "MemoryReader.h" -#include -#include - -namespace Serialization { - MemoryReader::MemoryReader() - : size_(0) - , position_(0) - , memory_(0) - , ownedMemory_(false) - { - } - - - MemoryReader::MemoryReader(const void* memory, std::size_t size, bool ownAndFree) - : size_(size) - , position_((const char*)(memory)) - , memory_((const char*)(memory)) - , ownedMemory_(ownAndFree) - { - } - - MemoryReader::~MemoryReader() - { - if (ownedMemory_) - { - free(const_cast(memory_)); - memory_ = 0; - size_ = 0; - } - } - - void MemoryReader::setPosition(const char* position) - { - position_ = position; - } - - void MemoryReader::read(void* data, std::size_t size) - { - YASLI_ASSERT(memory_ && position_); - YASLI_ASSERT(position_ - memory_ + size <= size_); - memcpy(data, position_, size); - position_ += size; - } - - bool MemoryReader::checkedRead(void* data, std::size_t size) - { - if (!memory_ || !position_) - { - return false; - } - if (position_ - memory_ + size > size_) - { - return false; - } - - memcpy(data, position_, size); - position_ += size; - return true; - } - - bool MemoryReader::checkedSkip(std::size_t size) - { - if (!memory_ || !position_) - { - return false; - } - if (position_ - memory_ + size > size_) - { - return false; - } - - position_ += size; - return true; - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.h deleted file mode 100644 index 1785574285..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryReader.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_MEMORYREADER_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_MEMORYREADER_H -#pragma once - - -#include - -namespace Serialization { - class MemoryReader - { - public: - MemoryReader(); - MemoryReader(const void* memory, size_t size, bool ownAndFree = false); - ~MemoryReader(); - - void setPosition(const char* position); - const char* position() { return position_; } - - template - void read(T& value) - { - read(reinterpret_cast(&value), sizoef(value)); - } - void read(void* data, size_t size); - bool checkedSkip(size_t size); - bool checkedRead(void* data, size_t size); - template - bool checkedRead(T& t) - { - return checkedRead((void*)&t, sizeof(t)); - } - - const char* buffer() const { return memory_; } - size_t size() const { return size_; } - - const char* begin() const { return memory_; } - const char* end() const { return memory_ + size_; } - - - private: - size_t size_; - const char* position_; - const char* memory_; - bool ownedMemory_; - }; -} -// vim:ts=4 sw=4: - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_MEMORYREADER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.cpp deleted file mode 100644 index 7cb515bb10..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.cpp +++ /dev/null @@ -1,275 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include -#include "Serialization/Assert.h" -#include -#include -#include -#include -#ifdef _MSC_VER -# include -# define isnan _isnan -#endif - -#include "MemoryWriter.h" - -#undef YASLI_ASSERT -#define YASLI_ASSERT(x) - -namespace Serialization { - MemoryWriter::MemoryWriter(std::size_t size, bool reallocate) - : size_(size) - , reallocate_(reallocate) - , digits_(5) - { - allocate(size); - } - - MemoryWriter::~MemoryWriter() - { - position_ = 0; - free(memory_); - } - - void MemoryWriter::allocate(std::size_t initialSize) - { - memory_ = (char*)malloc(initialSize + 1); - position_ = memory_; - } - - void MemoryWriter::reallocate(std::size_t newSize) - { - YASLI_ASSERT(newSize > size_); - std::size_t pos = position(); - memory_ = (char*)realloc(memory_, newSize + 1); - YASLI_ASSERT(memory_ != 0); - position_ = memory_ + pos; - size_ = newSize; - } - - MemoryWriter& MemoryWriter::operator<<(int value) - { - // TODO: optimize - char buffer[12]; - sprintf_s(buffer, "%i", value); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(long value) - { - // TODO: optimize - char buffer[12]; -#ifdef _MSC_VER - sprintf_s(buffer, "%i", value); -#else - sprintf_s(buffer, "%li", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned long value) - { - // TODO: optimize - char buffer[12]; -#ifdef _MSC_VER - sprintf_s(buffer, "%u", value); -#else - sprintf_s(buffer, "%lu", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(long long value) - { - // TODO: optimize - char buffer[24]; -#ifdef _MSC_VER - sprintf_s(buffer, "%I64i", value); -#else - sprintf_s(buffer, "%lli", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned long long value) - { - // TODO: optimize - char buffer[24]; -#ifdef _MSC_VER - sprintf_s(buffer, "%I64u", value); -#else - sprintf_s(buffer, "%llu", value); -#endif - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned int value) - { - // TODO: optimize - char buffer[12]; - sprintf_s(buffer, "%u", value); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(unsigned char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - MemoryWriter& MemoryWriter::operator<<(signed char value) - { - char buffer[12]; - sprintf_s(buffer, "%i", int(value)); - return operator<<((const char*)buffer); - } - - inline void cutRightZeros(const char* str) - { - for (char* p = (char*)str + strlen(str) - 1; p >= str; --p) - { - if (*p == '0') - { - *p = 0; - } - else - { - return; - } - } - } - - MemoryWriter& MemoryWriter::operator<<(double value) - { - // YASLI_ASSERT(!isnan(value)); disabled, because physics data is not always initialized - - int point = 0; - int sign = 0; - -#ifdef _MSC_VER - char buf[_CVTBUFSIZE]; - _fcvt_s(buf, value, digits_, &point, &sign); -#else - const char* buf = fcvt(value, digits_, &point, &sign); -#endif - - if (sign != 0) - { - write("-"); - } - if (point <= 0) - { - cutRightZeros(buf); - if (strlen(buf)) - { - write("0."); - while (point < 0) - { - write("0"); - ++point; - } - write(buf); - } - else - { - write("0"); - } - *position_ = '\0'; - } - else - { - write(buf, point); - write("."); - cutRightZeros(buf + point); - operator<<(buf + point); - } - return *this; - } - - MemoryWriter& MemoryWriter::operator<<(const char* value) - { - write((void*)value, strlen(value)); - YASLI_ASSERT(position() < size()); - *position_ = '\0'; - return *this; - } - - MemoryWriter& MemoryWriter::operator<<(const wchar_t* value) - { - write((void*)value, wcslen(value) * sizeof(wchar_t)); - YASLI_ASSERT(position() < size()); - *position_ = '\0'; - return *this; - } - - void MemoryWriter::setPosition(std::size_t pos) - { - YASLI_ASSERT(pos < size_); - YASLI_ASSERT(memory_ + pos <= position_); - position_ = memory_ + pos; - } - - void MemoryWriter::write(const char* value) - { - write((void*)value, strlen(value)); - } - - bool MemoryWriter::write(const void* data, std::size_t size) - { - YASLI_ASSERT(memory_ <= position_); - YASLI_ASSERT(position() < this->size()); - if (size_ - position() > size) - { - memcpy(position_, data, size); - position_ += size; - } - else - { - if (!reallocate_) - { - return false; - } - - reallocate(size_ * 2); - write(data, size); - } - YASLI_ASSERT(position() < this->size()); - return true; - } - - void MemoryWriter::write(char c) - { - if (size_ - position() > 1) - { - *(char*)(position_) = c; - ++position_; - } - else - { - YASLI_ESCAPE(reallocate_, return ); - reallocate(size_ * 2); - write(c); - } - YASLI_ASSERT(position() < this->size()); - } -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.h deleted file mode 100644 index acd852cb62..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/MemoryWriter.h +++ /dev/null @@ -1,80 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_MEMORYWRITER_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_MEMORYWRITER_H -#pragma once - - -#include -#include "Pointers.h" -#include "EditorCommonAPI.h" - -namespace Serialization { - class MemoryWriter - : public RefCounter - { - public: - MemoryWriter(std::size_t size = 128, bool reallocate = true); - ~MemoryWriter(); - - const char* c_str() { return memory_; }; - const wchar_t* w_str() { return (wchar_t*)memory_; }; - char* buffer() { return memory_; } - const char* buffer() const { return memory_; } - std::size_t size() const{ return size_; } - void clear() { position_ = memory_; } - - // String interface (after this calls '\0' is always written) - MemoryWriter& operator<<(int value); - MemoryWriter& operator<<(long value); - MemoryWriter& operator<<(unsigned long value); - MemoryWriter& operator<<(unsigned int value); - MemoryWriter& operator<<(long long value); - MemoryWriter& operator<<(unsigned long long value); - MemoryWriter& operator<<(float value) { return (*this) << double(value); } - MemoryWriter& operator<<(double value); - MemoryWriter& operator<<(signed char value); - MemoryWriter& operator<<(unsigned char value); - MemoryWriter& operator<<(char value); - MemoryWriter& operator<<(const char* value); - MemoryWriter& operator<<(const wchar_t* value); - - // Binary interface (does not writes trailing '\0') - template - void write(const T& value) - { - write(reinterpret_cast(&value), sizeof(value)); - } - void write(char c); - void write(const char* str); - bool write(const void* data, std::size_t size); - - std::size_t position() const { return position_ - memory_; } - void setPosition(std::size_t pos); - - MemoryWriter& setDigits(int digits) { digits_ = (unsigned char)digits; return *this; } - - private: - void allocate(std::size_t initialSize); - void reallocate(std::size_t newSize); - - std::size_t size_; - char* position_; - char* memory_; - bool reallocate_; - unsigned char digits_; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_MEMORYWRITER_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Pointers.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Pointers.h deleted file mode 100644 index db674701d4..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Pointers.h +++ /dev/null @@ -1,265 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_POINTERS_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_POINTERS_H -#pragma once - -#include "Serialization/Assert.h" - -namespace Serialization { - class RefCounter - { - public: - RefCounter() - : refCounter_(0) - {} - ~RefCounter() {}; - - int refCount() const { return refCounter_; } - - void acquire() { ++refCounter_; } - int release() { return --refCounter_; } - private: - int refCounter_; - }; - - class PolyRefCounter - : public RefCounter - { - public: - virtual ~PolyRefCounter() {} - }; - - class PolyPtrBase - { - public: - PolyPtrBase() - : ptr_(0) - { - } - void release() - { - if (ptr_) - { - if (!ptr_->release()) - { - delete ptr_; - } - ptr_ = 0; - } - } - void set(PolyRefCounter* const ptr) - { - if (ptr_ != ptr) - { - release(); - ptr_ = ptr; - if (ptr_) - { - ptr_->acquire(); - } - } - } - protected: - PolyRefCounter* ptr_; - }; - - template - class PolyPtr - : public PolyPtrBase - { - public: - PolyPtr() - : PolyPtrBase() - { - } - - PolyPtr(PolyRefCounter* ptr) - { - set(ptr); - } - - template - PolyPtr(U* ptr) - { - // TODO: replace with static_assert - YASLI_ASSERT("PolyRefCounter must be a first base when used with multiple inheritance." && - static_cast(ptr) == reinterpret_cast(ptr)); - set(static_cast(ptr)); - } - - PolyPtr(const PolyPtr& ptr) - : PolyPtrBase() - { - set(ptr.ptr_); - } - ~PolyPtr() - { - release(); - } - operator T*() const { - return get(); - } - template - operator PolyPtr() const { - return PolyPtr(get()); - } - operator bool() const { - return ptr_ != 0; - } - - PolyPtr& operator=(const PolyPtr& ptr) - { - set(ptr.ptr_); - return *this; - } - T* get() const { return reinterpret_cast(ptr_); } - T& operator*() const - { - return *get(); - } - T* operator->() const { return get(); } - }; - - class IArchive; - template - class SharedPtr - { - public: - SharedPtr() - : ptr_(0) {} - SharedPtr(T* const ptr) - : ptr_(0) - { - set(ptr); - } - SharedPtr(const SharedPtr& ptr) - : ptr_(0) - { - set(ptr.ptr_); - } - ~SharedPtr() - { - release(); - } - operator T*() const { - return get(); - } - template - operator SharedPtr() const { - return SharedPtr(get()); - } - SharedPtr& operator=(const SharedPtr& ptr) - { - set(ptr.ptr_); - return *this; - } - T* get() { return ptr_; } - T* get() const { return ptr_; } - T& operator*() - { - return *get(); - } - T* operator->() const { return get(); } - void release() - { - if (ptr_) - { - if (!ptr_->release()) - { - delete ptr_; - } - ptr_ = 0; - } - } - template - void set(_T* const ptr) { reset(ptr); } - template - void reset(_T* const ptr) - { - if (ptr_ != ptr) - { - release(); - ptr_ = ptr; - if (ptr_) - { - ptr_->acquire(); - } - } - } - protected: - T* ptr_; - }; - - - template - class AutoPtr - { - public: - AutoPtr() - : ptr_(0) - { - } - AutoPtr(T* ptr) - : ptr_(0) - { - set(ptr); - } - ~AutoPtr() - { - release(); - } - AutoPtr& operator=(T* ptr) - { - set(ptr); - return *this; - } - void set(T* ptr) - { - if (ptr_ && ptr_ != ptr) - { - release(); - } - ptr_ = ptr; - } - T* get() const { return ptr_; } - operator T*() const { - return get(); - } - void detach() - { - ptr_ = 0; - } - void release() - { - delete ptr_; - ptr_ = 0; - } - T& operator*() const { return *get(); } - T* operator->() const { return get(); } - private: - T* ptr_; - }; - - class IArchive; -} - -template -bool Serialize(Serialization::IArchive& ar, Serialization::SharedPtr& ptr, const char* name, const char* label); - -template -bool Serialize(Serialization::IArchive& ar, Serialization::PolyPtr& ptr, const char* name, const char* label); - -#include -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_POINTERS_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/PointersImpl.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/PointersImpl.h deleted file mode 100644 index 3d5d5d0c72..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/PointersImpl.h +++ /dev/null @@ -1,140 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_POINTERSIMPL_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_POINTERSIMPL_H -#pragma once - - -#include "Pointers.h" -#include "Serialization/IClassFactory.h" -#include "Serialization/ClassFactory.h" - -namespace Serialization { - template - class SharedPtrSerializer - : public IPointer - { - public: - SharedPtrSerializer(SharedPtr& ptr) - : ptr_(ptr) - {} - - const char* registeredTypeName() const - { - if (ptr_) - { - return ClassFactory::the().getRegisteredTypeName(ptr_.get()); - } - else - { - return ""; - } - } - void create(const char* typeName) const - { - YASLI_ASSERT(!ptr_ || ptr_->refCount() == 1); - if (typeName && typeName[0] != '\0') - { - ptr_.set(factory()->create(typeName)); - } - else - { - ptr_.set((T*)0); - } - } - TypeID baseType() const { return TypeID::get(); } - virtual SStruct serializer() const - { - return SStruct(*ptr_); - } - void* get() const - { - return reinterpret_cast(ptr_.get()); - } - const void* handle() const - { - return &ptr_; - } - TypeID pointerType() const - { - return TypeID::get >(); - } - virtual ClassFactory* factory() const{ return &ClassFactory::the(); } - - protected: - SharedPtr& ptr_; - }; - - template - class PolyPtrSerializer - : public IPointer - { - public: - PolyPtrSerializer(PolyPtr& ptr) - : ptr_(ptr) - {} - - TypeID type() const - { - if (ptr_) - { - return TypeID::get(ptr_.get()); - } - else - { - return TypeID(); - } - } - void create(TypeID type) const - { - // YASLI_ASSERT(!ptr_ || ptr_->refCount() == 1); not necessary to be true - if (type) - { - ptr_.set(ClassFactory::the().create(type)); - } - else - { - ptr_.set((T*)0); - } - } - TypeID baseType() const { return TypeID::get(); } - virtual SStruct serializer() const - { - return SStruct(*ptr_); - } - void* get() const - { - return reinterpret_cast(ptr_.get()); - } - IClassFactory* factory() const { return &ClassFactory::the(); } - - protected: - PolyPtr& ptr_; - }; -} - -template -bool Serialize(Serialization::IArchive& ar, Serialization::SharedPtr& ptr, const char* name, const char* label) -{ - return ar(static_cast(Serialization::SharedPtrSerializer(ptr)), name, label); -} - -template -bool Serialize(Serialization::IArchive& ar, Serialization::PolyPtr& ptr, const char* name, const char* label) -{ - return ar(static_cast(Serialization::PolyPtrSerializer(ptr)), name, label); -} -// vim:sw=4 ts=4: - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_POINTERSIMPL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.cpp b/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.cpp deleted file mode 100644 index f3001b95da..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.cpp +++ /dev/null @@ -1,393 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "EditorCommonAPI.h" -#include "Serialization/Serializer.h" -#include "Serialization/Qt.h" -#include "Serialization/STL.h" -#include "Serialization/IArchive.h" -#include -#include -#include -#include -#include - -class StringQt - : public Serialization::IWString -{ -public: - StringQt(QString& str) - : str_(str) {} - - void set(const wchar_t* value) { str_.setUnicode((const QChar*)value, (int)wcslen(value)); } - const wchar_t* get() const { return (wchar_t*)str_.data(); } - const void* handle() const { return &str_; } - Serialization::TypeID type() const{ return Serialization::TypeID::get(); } -private: - QString& str_; -}; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QString& value, const char* name, const char* label) -{ - StringQt str(value); - return ar(static_cast(str), name, label); -} - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QByteArray& byteArray, const char* name, const char* label) -{ - std::vector temp(byteArray.begin(), byteArray.end()); - if (!ar(temp, name, label)) - { - return false; - } - if (ar.IsInput()) - { - byteArray = QByteArray(temp.empty() ? (char*)0 : (char*)&temp[0], (int)temp.size()); - } - return true; -} - -QString GetIndexPath(QAbstractItemModel* model, const QModelIndex& index) -{ - QString path; - - QModelIndex cur = index; - while (cur.isValid() && cur != QModelIndex()) - { - if (!path.isEmpty()) - { - path = QString("|") + path; - } - path = model->data(cur).toString() + path; - cur = model->parent(cur); - } - return path; -} - -QModelIndex FindIndexChildByText(QAbstractItemModel* model, const QModelIndex& parent, const QString& text) -{ - int rowCount = model->rowCount(parent); - for (int i = 0; i < rowCount; ++i) - { - QModelIndex child = model->index(i, 0, parent); - QString childText = model->data(child).toString(); - if (childText == text) - { - return child; - } - } - return QModelIndex(); -} - -QModelIndex GetIndexByPath(QAbstractItemModel* model, const QString& path) -{ - QStringList items = path.split('|'); - QModelIndex cur = QModelIndex(); - for (int i = 0; i < items.size(); ++i) - { - cur = FindIndexChildByText(model, cur, items[i]); - if (!cur.isValid()) - { - return QModelIndex(); - } - } - return cur; -} - -std::vector GetIndexPaths(QAbstractItemModel* model, const QModelIndexList& indices) -{ - std::vector result; - for (int i = 0; i < indices.size(); ++i) - { - QString path = GetIndexPath(model, indices[i]); - if (!path.isEmpty()) - { - result.push_back(path); - } - } - return result; -} - -QModelIndexList GetIndicesByPath(QAbstractItemModel* model, const std::vector& paths) -{ - QModelIndexList result; - for (int i = 0; i < paths.size(); ++i) - { - QModelIndex index = GetIndexByPath(model, paths[i]); - if (index.isValid()) - { - result.push_back(index); - } - } - return result; -} - -struct QTreeViewStateSerializer -{ - QTreeView* treeView; - QTreeViewStateSerializer(QTreeView* treeView) - : treeView(treeView) {} - - void Serialize(Serialization::IArchive& ar) - { - QAbstractItemModel* model = treeView->model(); - - std::vector expandedItems; - if (ar.IsOutput()) - { - std::vector stack; - stack.push_back(QModelIndex()); - while (!stack.empty()) - { - QModelIndex index = stack.back(); - stack.pop_back(); - - int rowCount = model->rowCount(index); - for (int i = 0; i < rowCount; ++i) - { - QModelIndex child = model->index(i, 0, index); - if (treeView->isExpanded(child)) - { - stack.push_back(child); - expandedItems.push_back(GetIndexPath(model, child)); - } - } - } - } - ar(expandedItems, "expandedItems"); - if (ar.IsInput()) - { - treeView->collapseAll(); - for (size_t i = 0; i < expandedItems.size(); ++i) - { - QModelIndex index = GetIndexByPath(model, expandedItems[i]); - if (index.isValid()) - { - treeView->expand(index); - } - } - } - - std::vector selectedItems; - if (ar.IsOutput()) - { - selectedItems = GetIndexPaths(model, treeView->selectionModel()->selectedIndexes()); - } - ar(selectedItems, "selectedItems"); - if (ar.IsInput()) - { - QModelIndexList indices = GetIndicesByPath(model, selectedItems); - if (!indices.empty()) - { - treeView->selectionModel()->select(QModelIndex(), QItemSelectionModel::ClearAndSelect); - for (int i = 0; i < indices.size(); ++i) - { - treeView->selectionModel()->select(indices[i], QItemSelectionModel::Select); - } - } - } - - QString currentItem; - if (ar.IsOutput()) - { - currentItem = GetIndexPath(model, treeView->selectionModel()->currentIndex()); - } - ar(currentItem, "currentItem"); - if (ar.IsInput()) - { - QModelIndex currentIndex = GetIndexByPath(model, currentItem); - treeView->scrollTo(currentIndex, QAbstractItemView::PositionAtCenter); - treeView->selectionModel()->setCurrentIndex(currentIndex, QItemSelectionModel::Current); - } - - std::vector sectionsHidden; - std::vector sectionsVisible; - if (ar.IsOutput()) - { - for (int i = 0; i < treeView->model()->columnCount(); ++i) - { - if (treeView->header()->isSectionHidden(i)) - { - sectionsHidden.push_back(i); - } - else - { - sectionsVisible.push_back(i); - } - } - } - ar(sectionsHidden, "sectionsHidden"); - ar(sectionsVisible, "sectionsVisible"); - if (ar.IsInput()) - { - int columnCount = treeView->model()->columnCount(); - for (int i = 0; i < sectionsHidden.size(); ++i) - { - int section = sectionsHidden[i]; - if (section >= 0 && section < columnCount) - { - treeView->header()->hideSection(section); - } - } - for (int i = 0; i < sectionsVisible.size(); ++i) - { - int section = sectionsVisible[i]; - if (section >= 0 && section < columnCount) - { - treeView->header()->showSection(section); - } - } - } - } -}; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QTreeView* treeView, const char* name, const char* label) -{ - return ar(QTreeViewStateSerializer(treeView), name, label); -} - - -static const char* g_paletteColorGroupNames[QPalette::NColorGroups] = { - "Active", "Disabled", "Inactive" -}; - -static const char* g_paletteColorRoleNames[QPalette::NColorRoles] = { - "WindowText", "Button", "Light", "Midlight", "Dark", "Mid", - "Text", "BrightText", "ButtonText", "Base", "Window", "Shadow", - "Highlight", "HighlightedText", - "Link", "LinkVisited", - "AlternateBase", - "NoRole", - "ToolTipBase", "ToolTipText", -#if !defined(AZ_PLATFORM_LINUX) - "PlaceholderText", -#endif // !defined(AZ_PLATFORM_LINUX) -}; - -struct QPaletteSerializable -{ - QPalette& palette; - QPaletteSerializable(QPalette& palette) - : palette(palette) - { - } - - struct SRole - { - int role; - QPalette& palette; - - SRole(QPalette& palette, int role) - : palette(palette) - , role(role) - { - } - - void Serialize(Serialization::IArchive& ar) - { - for (int group = 0; group < QPalette::NColorGroups; ++group) - { - QColor color = palette.color(QPalette::ColorGroup(group), QPalette::ColorRole(role)); - ar(color, g_paletteColorGroupNames[group], g_paletteColorGroupNames[group]); - if (ar.IsInput()) - { - palette.setColor(QPalette::ColorGroup(group), QPalette::ColorRole(role), color); - } - } - } - }; - - void Serialize(Serialization::IArchive& ar) - { - for (int roleIndex = 0; roleIndex < QPalette::NColorRoles; ++roleIndex) - { - SRole role(palette, roleIndex); - ar(role, g_paletteColorRoleNames[roleIndex], g_paletteColorRoleNames[roleIndex]); - } - } -}; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QPalette& palette, const char* name, const char* label) -{ - QPaletteSerializable serializer(palette); - return ar(serializer, name, label); -} - -struct QColorSerializable -{ - QColor& color; - QColorSerializable(QColor& color) - : color(color) {} - - void Serialize(Serialization::IArchive& ar) - { - // this is not comprehensive, as QColor can store color components - // in diffrent models, depending on the way they were specified - unsigned char r = color.red(); - unsigned char g = color.green(); - unsigned char b = color.blue(); - unsigned char a = color.alpha(); - ar(r, "r", "^R"); - ar(g, "g", "^G"); - ar(b, "b", "^B"); - ar(a, "a", "^A"); - if (ar.IsInput()) - { - color.setRed(r); - color.setGreen(g); - color.setBlue(b); - color.setAlpha(a); - } - } -}; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QColor& color, const char* name, const char* label) -{ - QColorSerializable serializer(color); - return ar(serializer, name, label); -} - -struct QSplitterSerializer -{ - QSplitter& splitter; - - QSplitterSerializer(QSplitter& splitter) - : splitter(splitter) {} - - void Serialize(Serialization::IArchive& ar) - { - QList qsizes = splitter.sizes(); - std::vector sizes(qsizes.begin(), qsizes.end()); - ar(sizes, "sizes", "Sizes"); - if (ar.IsInput()) - { - qsizes.clear(); - for (int i = 0; i < sizes.size(); ++i) - { - qsizes.push_back(sizes[i]); - } - splitter.setSizes(qsizes); - } - } -}; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QSplitter* splitter, const char* name, const char* label) -{ - if (!splitter) - { - return false; - } - QSplitterSerializer serializer(*splitter); - return ar(serializer, name, label); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.h deleted file mode 100644 index c315567bb0..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Qt.h +++ /dev/null @@ -1,33 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QT_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QT_H -#pragma once - -#include "EditorCommonAPI.h" - -class QByteArray; -class QColor; -class QPalette; -class QSplitter; -class QString; -class QTreeView; - -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QSplitter* splitter, const char* name, const char* label); -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QByteArray& value, const char* name, const char* label); -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QString& value, const char* name, const char* label); -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QTreeView* treeViewState, const char* name, const char* label); -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QPalette& palette, const char* name, const char* label); -bool EDITOR_COMMON_API Serialize(Serialization::IArchive& ar, QColor& color, const char* name, const char* label); -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QT_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/QtImpl.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/QtImpl.h deleted file mode 100644 index 299e9be568..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/QtImpl.h +++ /dev/null @@ -1,24 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QTIMPL_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QTIMPL_H -#pragma once - -#include "Serialization/Serializer.h" - -namespace Serialization { -} - - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_QTIMPL_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/Token.h b/Code/Sandbox/Plugins/EditorCommon/Serialization/Token.h deleted file mode 100644 index 1c9f803e55..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/Token.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_SERIALIZATION_TOKEN_H -#define CRYINCLUDE_EDITORCOMMON_SERIALIZATION_TOKEN_H -#pragma once - -#include - -#include "Serialization/Strings.h" - -namespace Serialization { - struct Token - { - Token(const char* _str = 0) - : start(_str) - , end(_str ? _str + strlen(_str) : 0) - { - } - - Token(const char* _str, size_t _len) - : start(_str) - , end(_str + _len) {} - Token(const char* _start, const char* _end) - : start(_start) - , end(_end) {} - - void set(const char* _start, const char* _end) { start = _start; end = _end; } - std::size_t length() const{ return end - start; } - - bool operator==(const Token& rhs) const - { - if (length() != rhs.length()) - { - return false; - } - return memcmp(start, rhs.start, length()) == 0; - } - bool operator==(const string& rhs) const - { - if (length() != rhs.size()) - { - return false; - } - return memcmp(start, rhs.c_str(), length()) == 0; - } - - bool operator==(const char* text) const - { - if (strncmp(text, start, length()) == 0) - { - return text[length()] == '\0'; - } - return false; - } - bool operator!=(const char* text) const - { - if (strncmp(text, start, length()) == 0) - { - return text[length()] != '\0'; - } - return true; - } - bool operator==(char c) const - { - return length() == 1 && *start == c; - } - bool operator!=(char c) const - { - return length() != 1 || *start != c; - } - - operator bool() const{ - return start != end; - } - string str() const{ return string(start, end); } - - const char* start; - const char* end; - }; -} - -#endif // CRYINCLUDE_EDITORCOMMON_SERIALIZATION_TOKEN_H diff --git a/Code/Sandbox/Plugins/EditorCommon/Serialization/yasli_NOTICES.txt b/Code/Sandbox/Plugins/EditorCommon/Serialization/yasli_NOTICES.txt deleted file mode 100644 index 5e8ea4b43e..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Serialization/yasli_NOTICES.txt +++ /dev/null @@ -1,49 +0,0 @@ -Portions based on WWidgets and Yasli Serialization Library - -wWidgets - Lightweight UI Toolkit. -Copyright (C) 2009-2011 Evgeny Andreeshchev - Alexander Kotliar - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - - - -Yasli Serialization Library -Copyright (c) 2007 Eugene Andreeshchev - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without -restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the -Software is furnished to do so, subject to the following -conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT -HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR -OTHER DEALINGS IN THE SOFTWARE. diff --git a/Code/Sandbox/Plugins/EditorCommon/Timeline.cpp b/Code/Sandbox/Plugins/EditorCommon/Timeline.cpp deleted file mode 100644 index 49a3a07f35..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Timeline.cpp +++ /dev/null @@ -1,2728 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "Timeline.h" -#include "QtUtil.h" -#include "DrawingPrimitives/TimeSlider.h" -#include "DrawingPrimitives/Ruler.h" - -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#ifdef min -#undef min -#endif - -#ifdef max -#undef max -#endif - -int STimelineViewState::ScrollOffset(float origin) const -{ - return int((origin / visibleDistance + 0.5f) * widthPixels); -} - -int STimelineViewState::TimeToLayout(float time) const -{ - return int((time / visibleDistance) * widthPixels + 0.5f); -} - -int STimelineViewState::TimeToLocal(float time) const -{ - return TimeToLayout(time) + treeWidth + scrollPixels.x(); -} - -float STimelineViewState::LayoutToTime(int x) const -{ - return (float(x) - 0.5f) / widthPixels * visibleDistance; -} - -float STimelineViewState::LocalToTime(int x) const -{ - return LayoutToTime(x - treeWidth - scrollPixels.x()); -} - -QPoint STimelineViewState::LocalToLayout(const QPoint& p) const -{ - return p - scrollPixels - QPoint(treeWidth, 0); -} - -QPoint STimelineViewState::LayoutToLocal(const QPoint& p) const -{ - return p + scrollPixels + QPoint(treeWidth, 0); -} - -enum -{ - THUMB_WIDTH = 12, - THUMB_HEIGHT = 24, - - RULER_HEIGHT = 16, - RULER_SHADOW_HEIGHT = 6, - RULER_MARK_HEIGHT = 8, - - TRACK_MARK_HEIGHT = 6, - - DEFAULT_KEY_WIDTH = 8, - VERTICAL_PADDING = 4, - TRACK_DESCRIPTION_INDENT = 8, - - SELECTION_WIDTH = 4, - SCROLL_SHADOW_WIDTH = 8, - - MAX_PUSH_OUT = VERTICAL_PADDING * 2, - PUSH_OUT_DISTANCE = 3, - - SPLITTER_WIDTH = 10, - - DEFAULT_TREE_WIDTH = 200, - TREE_LEFT_MARGIN = 6, - TREE_INDENT_MULTIPLIER = 12, - TREE_BRANCH_INDICATOR_SIZE = 8 -}; - -namespace -{ - const float DEFAULT_KEY_RADIUS = 0.1f; - const int TIMELINE_PADDING = 20; -} - -struct STimelineContentElementRef -{ - STimelineContentElementRef() - : pTrack(nullptr) - , index(0) - {} - - STimelineContentElementRef(STimelineTrack* pTrack, size_t index) - : pTrack(pTrack) - , index(index) - {} - - STimelineElement& GetElement() const - { - return pTrack->elements[index]; - } - - bool IsValid() const { return pTrack != 0 && index < pTrack->elements.size(); } - - bool operator<(const STimelineContentElementRef& rhs) const - { - if (pTrack == rhs.pTrack) - { - return index < rhs.index; - } - else - { - if (!pTrack && rhs.pTrack) - { - return true; - } - else if (pTrack && !rhs.pTrack) - { - return false; - } - else if (pTrack && rhs.pTrack) - { - return pTrack->name < rhs.pTrack->name; - } - return false; - } - } - - STimelineTrack* pTrack; - size_t index; -}; - -struct SElementLayout -{ - STimelineElement::EType type; - int caps; - float pushOutDistance; - QRect rect; - ColorB color; - string description; - - STimelineContentElementRef elementRef; - std::vector subElements; - - bool IsSelected() const - { - if ((elementRef.pTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) == 0) - { - return elementRef.GetElement().selected; - } - else - { - bool bSelected = false; - const size_t numSubElements = subElements.size(); - - for (size_t i = 0; i < numSubElements; ++i) - { - bSelected = bSelected || subElements[i].GetElement().selected; - } - - return bSelected; - } - } - - void SetSelected(const bool bSelected) const - { - if ((elementRef.pTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) == 0) - { - elementRef.GetElement().selected = bSelected; - } - else - { - const size_t numSubElements = subElements.size(); - for (size_t i = 0; i < numSubElements; ++i) - { - subElements[i].GetElement().selected = bSelected; - } - } - } - - SElementLayout() - : pushOutDistance(0.0f) - , caps(0) - , type(STimelineElement::KEY) - {} -}; - -struct STrackLayout; -typedef std::vector STrackLayouts; - -struct STrackLayout -{ - QRect rect; - int indent; - - STimelineTrack* pTimelineTrack; - - std::vector elements; - STrackLayouts tracks; - - STrackLayout() - : indent(0) - , pTimelineTrack(0) - { - } -}; - -struct STimelineLayout -{ - int thumbPositionX; - STrackLayouts tracks; - SAnimTime minStartTime; - SAnimTime maxEndTime; - QSize size; - - STimelineLayout() - : thumbPositionX(0) - , minStartTime(0.0f) - , maxEndTime(1.0f) - , size(1, 1) - { - } -}; - -namespace -{ - QColor InterpolateColor(const QColor& a, const QColor& b, float k) - { - float mk = 1.0f - k; - return QColor(aznumeric_cast(a.red() * mk + b.red() * k), - aznumeric_cast(a.green() * mk + b.green() * k), - aznumeric_cast(a.blue() * mk + b.blue() * k), - aznumeric_cast(a.alpha() * mk + b.alpha() * k)); - } - - void ClampViewOrigin(STimelineViewState* viewState, const STimelineLayout& layout) - { - float zoomOffset = viewState->visibleDistance * 0.5f; - - const float padding = viewState->LayoutToTime(TIMELINE_PADDING); - float maxViewOrigin = layout.minStartTime.ToFloat() - zoomOffset + padding; - float minViewOrigin = std::min(viewState->visibleDistance - layout.maxEndTime.ToFloat() - zoomOffset - padding, maxViewOrigin); - - viewState->viewOrigin = clamp_tpl(viewState->viewOrigin, minViewOrigin, maxViewOrigin); - } - - SElementLayout& AddElementToTrackLayout(STimelineTrack& track, STrackLayout& trackLayout, const STimelineElement& element, - const STimelineViewState& viewState, uint keyWidth, [[maybe_unused]] int treeWidth, int& currentTop, size_t elementIndex) - { - trackLayout.elements.push_back(SElementLayout()); - SElementLayout& elementl = trackLayout.elements.back(); - elementl.color = element.color; - elementl.type = element.type; - elementl.caps = element.caps; - elementl.description = element.description; - elementl.elementRef.pTrack = &track; - elementl.elementRef.index = elementIndex; - - if (element.type == STimelineElement::KEY) - { - int left = (viewState.TimeToLayout(element.start.ToFloat()) - keyWidth / 2); - int right = left + keyWidth; - elementl.rect = QRect(left, currentTop + VERTICAL_PADDING, right - left, track.height - VERTICAL_PADDING * 2); - } - else - { - int left = viewState.TimeToLayout(element.start.ToFloat()); - int right = viewState.TimeToLayout(element.end.ToFloat()); - elementl.rect = QRect(left, currentTop + VERTICAL_PADDING, right - left, track.height - VERTICAL_PADDING * 2); - } - - return elementl; - } - - void AddCompoundElementsToTrackLayout(STimelineTrack& track, STimelineLayout* layout, const STimelineViewState& viewState, int trackId, uint keyWidth, int treeWidth, int& currentTop) - { - const size_t numSubTracks = track.tracks.size(); - SAnimTime currentElementTime = SAnimTime::Min(); - size_t* pCurrentSubTrackIndices = static_cast(alloca(sizeof(size_t) * numSubTracks)); - memset(pCurrentSubTrackIndices, 0, sizeof(size_t) * numSubTracks); - - while (true) - { - bool bElementFound = false; - SAnimTime minElementTime = SAnimTime::Max(); - - // First search for minimum element time for current track positions - for (size_t i = 0; i < numSubTracks; ++i) - { - const STimelineTrack& subTrack = *track.tracks[i]; - const STimelineElements& elements = subTrack.elements; - const size_t numTrackElements = elements.size(); - const size_t index = pCurrentSubTrackIndices[i]; - - if (index < numTrackElements) - { - const SAnimTime elementTime = elements[index].start; - minElementTime = min(elementTime, minElementTime); - bElementFound = true; - } - } - - if (!bElementFound) - { - break; - } - - STimelineElement compoundElement; - compoundElement.start = minElementTime; - compoundElement.end = minElementTime; - - // If elements were found create a compound element - STrackLayout& trackLayout = layout->tracks[trackId]; - SElementLayout& compoundElementLayout = AddElementToTrackLayout(track, trackLayout, compoundElement, viewState, keyWidth, treeWidth, currentTop, 0); - currentElementTime = minElementTime; - - compoundElementLayout.description = "("; - - // Advance track positions and add elements IDs to compound element if times match - for (size_t i = 0; i < numSubTracks; ++i) - { - STimelineTrack* pSubTrack = track.tracks[i]; - const STimelineElements& elements = pSubTrack->elements; - const size_t numTrackElements = elements.size(); - size_t& index = pCurrentSubTrackIndices[i]; - - if (index < numTrackElements) - { - const SAnimTime elementTime = elements[index].start; - - if (elementTime == minElementTime) - { - STimelineContentElementRef ref; - ref.pTrack = pSubTrack; - ref.index = index; - compoundElementLayout.subElements.push_back(ref); - compoundElementLayout.description += elements[index].description; - ++index; - } - else - { - compoundElementLayout.description += "-"; - } - - if ((i + 1) < numSubTracks) - { - compoundElementLayout.description += ", "; - } - } - } - - compoundElementLayout.description += ")"; - } - } - - bool FilterTracks(const STimelineTrack& track, std::unordered_set& invisibleTracks, const char* filterString) - { - bool bAnyChildVisible = false; - const bool bNameMatchesFilter = CryStringUtils::stristr(track.name, filterString) != nullptr; - - if (!bNameMatchesFilter) - { - const size_t numChildTracks = track.tracks.size(); - for (size_t i = 0; i < numChildTracks; ++i) - { - bAnyChildVisible = FilterTracks(*track.tracks[i], invisibleTracks, filterString) || bAnyChildVisible; - } - } - - if (!bNameMatchesFilter && !bAnyChildVisible) - { - invisibleTracks.insert(&track); - } - - return bNameMatchesFilter || bAnyChildVisible; - } - - void CalculateMinMaxTime(STimelineLayout* layout, STimelineTrack& parentTrack) - { - layout->minStartTime = min(layout->minStartTime, parentTrack.startTime); - layout->maxEndTime = max(layout->maxEndTime, parentTrack.endTime); - - const size_t numTracks = parentTrack.tracks.size(); - for (size_t i = 0; i < numTracks; ++i) - { - STimelineTrack& track = *parentTrack.tracks[i]; - CalculateMinMaxTime(layout, track); - } - } - - void CalculateTrackLayout(STimelineLayout* layout, int& currentTop, int currentIndent, STimelineTrack& parentTrack, const STimelineViewState& viewState, - float thumbTime, uint keyWidth, int treeWidth, const std::unordered_set& invisibleTracks) - { - const size_t numTracks = parentTrack.tracks.size(); - for (size_t i = 0; i < numTracks; ++i) - { - STimelineTrack& track = *parentTrack.tracks[i]; - - if (stl::find(invisibleTracks, &track)) - { - continue; - } - - layout->tracks.push_back(STrackLayout()); - STrackLayout& trackLayout = layout->tracks.back(); - trackLayout.elements.reserve(track.elements.size()); - trackLayout.indent = currentIndent; - trackLayout.pTimelineTrack = &track; - - const bool bIsCompositeTrack = (track.caps & STimelineTrack::CAP_COMPOUND_TRACK) != 0; - - if (bIsCompositeTrack) - { - const int trackLayoutId = layout->tracks.size() - 1; - AddCompoundElementsToTrackLayout(track, layout, viewState, trackLayoutId, keyWidth, treeWidth, currentTop); - } - else - { - for (size_t i2 = 0; i2 < track.elements.size(); ++i2) - { - const STimelineElement& element = track.elements[i2]; - AddElementToTrackLayout(track, trackLayout, element, viewState, keyWidth, treeWidth, currentTop, i2); - } - } - - int left = viewState.TimeToLayout(track.startTime.ToFloat()); - int right = viewState.TimeToLayout(track.endTime.ToFloat()); - trackLayout.rect = QRect(left, currentTop, right - left, track.height); - currentTop += track.height; - - if (track.expanded) - { - CalculateTrackLayout(layout, currentTop, currentIndent + 1, track, viewState, thumbTime, keyWidth, treeWidth, invisibleTracks); - } - } - } - - void ApplyPushOut(STimelineLayout* layout, uint keyWidth) - { - float maxPushOut = 0.0f; - - const size_t numLayoutTracks = layout->tracks.size(); - for (size_t i = 0; i < numLayoutTracks; ++i) - { - STrackLayout& track = layout->tracks[i]; - - const size_t numElements = track.elements.size(); - for (size_t i2 = 0; i2 < numElements; ++i2) - { - if (track.elements[i2].type != STimelineElement::KEY) - { - continue; - } - - for (size_t j = 0; j < numElements; ++j) - { - if ((track.elements[j].type != STimelineElement::KEY) || (j == i2)) - { - continue; - } - - float distance = aznumeric_cast(track.elements[j].rect.left() - track.elements[i2].rect.left()); - float delta = clamp_tpl(1.0f - fabsf(distance) / keyWidth, 0.0f, 1.0f); - - if (delta == 0.0f) - { - continue; - } - - float& pushOutDistance = track.elements[i2].pushOutDistance; - pushOutDistance += (i2 < j) ? -delta : delta; - - if (fabsf(pushOutDistance) > maxPushOut) - { - maxPushOut = fabsf(pushOutDistance); - } - } - } - } - - float maxPushOutNormalized = float(MAX_PUSH_OUT) / PUSH_OUT_DISTANCE; - float pushOutScale = 1.0f; - - if (maxPushOut > maxPushOutNormalized && maxPushOut > 0.0f) - { - pushOutScale = maxPushOutNormalized / maxPushOut; - } - - for (size_t i = 0; i < numLayoutTracks; ++i) - { - STrackLayout& track = layout->tracks[i]; - - for (size_t j = 0; j < track.elements.size(); ++j) - { - track.elements[j].rect.translate(QPoint(0, int(pushOutScale * track.elements[j].pushOutDistance * PUSH_OUT_DISTANCE))); - } - } - } - - void CalculateLayout(STimelineLayout* layout, STimelineContent& content, const STimelineViewState& viewState, const QLineEdit* pFilterLineEdit, float thumbTime, uint keyWidth, bool treeVisible) - { - layout->thumbPositionX = viewState.TimeToLayout(thumbTime); - - if (!content.track.tracks.empty()) - { - layout->minStartTime = SAnimTime::Max(); - layout->maxEndTime = SAnimTime::Min(); - } - else - { - layout->minStartTime = SAnimTime(0.0f); - layout->maxEndTime = SAnimTime(1.0f); - } - - int currentTop = RULER_HEIGHT + VERTICAL_PADDING; - const int treeWidth = treeVisible ? viewState.treeWidth : 0; - - std::unordered_set invisibleTracks; - if (pFilterLineEdit && !pFilterLineEdit->text().isEmpty()) - { - FilterTracks(content.track, invisibleTracks, QtUtil::ToString(pFilterLineEdit->text())); - } - - CalculateMinMaxTime(layout, content.track); - CalculateTrackLayout(layout, currentTop, 0, content.track, viewState, thumbTime, keyWidth, treeWidth, invisibleTracks); - - layout->size = QSize(viewState.TimeToLayout(layout->maxEndTime.ToFloat()), currentTop + VERTICAL_PADDING); - } - - STrackLayout* HitTestTrack(STrackLayouts& tracks, const QPoint& point) - { - auto findIter = std::upper_bound(tracks.begin(), tracks.end(), point.y(), [&](int y, const STrackLayout& track) - { - return y < track.rect.bottom(); - }); - - if (findIter != tracks.end() && findIter->rect.contains(point)) - { - return &(*findIter); - } - - return nullptr; - } - - void ForEachTrack(STimelineTrack& track, AZStd::function fun) - { - fun(track); - - for (size_t i = 0; i < track.tracks.size(); ++i) - { - STimelineTrack& subTrack = *track.tracks[i]; - ForEachTrack(subTrack, fun); - } - } - - void ForEachElement(STimelineTrack& track, AZStd::function fun) - { - ForEachTrack(track, [&](STimelineTrack& subTrack) - { - for (size_t i = 0; i < subTrack.elements.size(); ++i) - { - fun(subTrack, subTrack.elements[i]); - } - }); - } - - void ForEachElementWithIndex(STimelineTrack& track, AZStd::function fun) - { - ForEachTrack(track, [&](STimelineTrack& subTrack) - { - for (size_t i = 0; i < subTrack.elements.size(); ++i) - { - fun(subTrack, subTrack.elements[i], i); - } - }); - } - - void ClearTrackSelection(STimelineTrack& track) - { - ForEachTrack(track, [](STimelineTrack& track) - { - track.selected = false; - }); - } - - void GetSelectedTracks(STimelineTrack& track, std::vector& tracks) - { - ForEachTrack(track, [&](STimelineTrack& track) - { - if (track.selected) - { - tracks.push_back(&track); - } - }); - } - - void ClearElementSelection(STimelineTrack& track) - { - ForEachElement(track, [](STimelineTrack& track, STimelineElement& element) - { - track.keySelectionChanged = track.keySelectionChanged || element.selected; - element.selected = false; - }); - } - - void SetSelectedElementTimes(STimelineTrack& track, const std::vector& times) - { - auto iter = times.begin(); - ForEachElement(track, [&](STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - track.modified = true; - element.start = *(iter++); - } - }); - } - - std::vector GetSelectedElementTimes(STimelineTrack& track) - { - std::vector times; - ForEachElement(track, [&]([[maybe_unused]] STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - times.push_back(element.start); - } - }); - return times; - } - - VectorSet GetSelectedElementsTimeSet(STimelineTrack& track) - { - VectorSet timeSet; - ForEachElement(track, [&]([[maybe_unused]] STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - timeSet.insert(element.start); - } - }); - return timeSet; - } - - typedef std::vector > TSelectedElements; - TSelectedElements GetSelectedElements(STimelineTrack& track) - { - TSelectedElements elements; - - ForEachElement(track, [&](STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - elements.push_back(std::make_pair(&track, &element)); - } - }); - - return elements; - } - - void MoveSelectedElements(STimelineTrack& track, SAnimTime delta) - { - ForEachElement(track, [&](STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - track.modified = true; - element.start += delta; - } - }); - } - - void DeletedMarkedElements(STimelineTrack& track) - { - ForEachTrack(track, [&](STimelineTrack& track) - { - for (auto iter = track.elements.begin(); iter != track.elements.end(); ) - { - if (iter->deleted) - { - iter = track.elements.erase(iter); - } - else - { - ++iter; - } - } - }); - } - - void SelectElementsInRect(const STrackLayouts& tracks, const QRect& rect) - { - for (size_t j = 0; j < tracks.size(); ++j) - { - const STrackLayout& track = tracks[j]; - - for (size_t i = 0; i < track.elements.size(); ++i) - { - const SElementLayout& element = track.elements[i]; - - if ((element.caps & STimelineElement::CAP_SELECT) == 0) - { - continue; - } - - STimelineTrack* pTimelineTrack = element.elementRef.pTrack; - const bool bIsCompoundTrack = (pTimelineTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) != 0; - - if (element.rect.intersects(rect)) - { - if (!bIsCompoundTrack) - { - if (!element.elementRef.GetElement().selected) - { - element.elementRef.GetElement().selected = true; - element.elementRef.pTrack->keySelectionChanged = true; - } - } - else - { - const size_t numSubElements = element.subElements.size(); - - for (size_t k = 0; k < numSubElements; ++k) - { - if (!element.subElements[k].GetElement().selected) - { - element.subElements[k].GetElement().selected = true; - element.subElements[k].pTrack->keySelectionChanged = true; - } - } - } - } - } - - SelectElementsInRect(track.tracks, rect); - } - } - - typedef std::vector SElementLayoutPtrs; - bool HitTestElements(STrackLayouts& tracks, const QRect& rect, SElementLayoutPtrs& out) - { - bool bHit = false; - - for (size_t j = 0; j < tracks.size(); ++j) - { - STrackLayout& track = tracks[j]; - - for (size_t i = 0; i < track.elements.size(); ++i) - { - SElementLayout& element = track.elements[i]; - - if (element.rect.intersects(rect)) - { - out.push_back(&element); - bHit = true; - } - } - - bHit = bHit || HitTestElements(track.tracks, rect, out); - } - - return bHit; - } - - enum EPass - { - PASS_BACKGROUND, - PASS_SELECTION, - PASS_SHADOW, - PASS_MAIN, - NUM_PASSES - }; - - QBrush PickTrackBrush(const QPalette& palette, const STrackLayout& track) - { - const QColor trackColor = InterpolateColor(palette.color(QPalette::Mid), palette.color(QPalette::Window), 0.96f); - const QColor descriptionTrackColor = InterpolateColor(palette.color(QPalette::Mid), palette.color(QPalette::Window), 0.9f); - const QColor compositeTrackColor = InterpolateColor(palette.color(QPalette::Mid), palette.color(QPalette::Window), 0.85f); - const QColor selectionColor = InterpolateColor(palette.color(QPalette::Highlight), palette.color(QPalette::Window), 0.5f); - - const bool bIsDescriptionTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_DESCRIPTION_TRACK) != 0; - const bool bIsCompositeTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) != 0; - - const QColor color = bIsDescriptionTrack ? descriptionTrackColor : (bIsCompositeTrack ? compositeTrackColor : trackColor); - return QBrush(track.pTimelineTrack->selected ? InterpolateColor(color, selectionColor, 0.3f) : color); - } - - struct SElementLayoutIntCompareLeft - { - const bool operator()(const SElementLayout& a, int b) { return a.rect.left() < b; } - const bool operator()(int a, const SElementLayout& b) { return a < b.rect.left(); } - }; - - struct SElementLayoutIntCompareRight - { - const bool operator()(const SElementLayout& a, int b) { return a.rect.right() < b; } - const bool operator()(int a, const SElementLayout& b) { return a < b.rect.right(); } - }; - - void DrawTracks(QPainter& painter, const uint startPass, const uint endPass, const STimelineLayout& layout, const STimelineViewState& viewState, - const QPalette& palette, [[maybe_unused]] const QPoint& mousePos, bool hasFocus, int width, float keyRadius, float timeUnitScale, bool drawMarkers) - { - const STrackLayouts& tracks = layout.tracks; - - const int trackAreaLeft = viewState.LocalToLayout(QPoint(viewState.treeWidth, 0)).x(); - const int trackAreaRight = trackAreaLeft + width; - - const QColor textColor = palette.buttonText().color(); - QPen descriptionTextPen = QPen(InterpolateColor(textColor, palette.color(QPalette::Window), 0.5f)); - - DrawingPrimitives::STickOptions markOptions; - markOptions.m_rect = QRect(-viewState.scrollPixels.x(), 0, width - viewState.treeWidth, 0); - markOptions.m_visibleRange = Range(viewState.LocalToTime(viewState.treeWidth) * timeUnitScale, viewState.LocalToTime(width) * timeUnitScale); - markOptions.m_rulerRange = Range(layout.minStartTime.ToFloat() * timeUnitScale, layout.maxEndTime.ToFloat() * timeUnitScale); - markOptions.m_markHeight = TRACK_MARK_HEIGHT; - - // Precalculate ticks because they are the same for all tracks - std::vector ticks = DrawingPrimitives::CalculateTicks(markOptions.m_rect.width(), markOptions.m_visibleRange, markOptions.m_rulerRange, nullptr, nullptr); - - for (int i = startPass; i <= endPass; ++i) - { - EPass pass = (EPass)i; - - for (size_t j = 0; j < tracks.size(); ++j) - { - const STrackLayout& track = tracks[j]; - - const bool bIsDescriptionTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_DESCRIPTION_TRACK) != 0; - const bool bIsCompositeTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) != 0; - const bool bIsToggleTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_TOGGLE_TRACK) != 0; - - std::vector sortedElements = track.elements; - std::sort(sortedElements.begin(), sortedElements.end(), [](const SElementLayout& a, const SElementLayout& b) { return a.rect.left() < b.rect.left(); }); - const uint numElements = sortedElements.size(); - - if (pass == PASS_BACKGROUND) - { - painter.setPen(Qt::NoPen); - painter.setBrush(PickTrackBrush(palette, track)); - QRect backgroundRect = track.rect; - backgroundRect.setLeft(-viewState.scrollPixels.x()); - backgroundRect.setWidth(width); - painter.drawRect(backgroundRect); - - if (bIsDescriptionTrack) - { - painter.setPen(descriptionTextPen); - QRect textRect = track.rect; - textRect.moveLeft(textRect.left() - viewState.scrollPixels.x() + TRACK_DESCRIPTION_INDENT); - textRect.setWidth(width); - textRect.moveTop(textRect.top() + 1); - painter.drawText(textRect, QString(track.pTimelineTrack->name)); - } - - const int lineY = track.rect.bottom() + 1; - painter.setPen(QPen(InterpolateColor(palette.color(QPalette::Mid), palette.color(QPalette::Window), 0.75f))); - painter.drawLine(QPoint(trackAreaLeft, lineY), QPoint(trackAreaRight, lineY)); - - if (drawMarkers && !bIsDescriptionTrack) - { - markOptions.m_rect.setTop(track.rect.top()); - markOptions.m_rect.setBottom(track.rect.bottom()); - DrawingPrimitives::DrawTicks(ticks, painter, palette, markOptions); - } - - if (bIsToggleTrack) - { - const QColor toggleColor = InterpolateColor(QColor(255, 255, 255), palette.color(QPalette::Mid), 0.5f); - - const uint drawStart = track.pTimelineTrack->toggleDefaultState ? 0 : 1; - - painter.setBrush(QBrush(toggleColor)); - QRect toggleRect = track.rect; - toggleRect.setTop(toggleRect.top() + 2); - toggleRect.setBottom(toggleRect.bottom() - 2); - - for (uint i2 = drawStart; i2 <= numElements; i2 += 2) - { - const int left = (i2 == 0) ? (-viewState.scrollPixels.x()) : sortedElements[i2 - 1].rect.right(); - const int right = (i2 == numElements) ? (-viewState.scrollPixels.x() + width) : sortedElements[i2].rect.left(); - - toggleRect.setLeft(left); - toggleRect.setRight(right); - painter.drawRect(toggleRect); - } - } - - continue; - } - - auto begin = std::lower_bound(sortedElements.begin(), sortedElements.end(), -viewState.scrollPixels.x(), SElementLayoutIntCompareRight()); - auto end = std::upper_bound(sortedElements.begin(), sortedElements.end(), width - viewState.scrollPixels.x(), SElementLayoutIntCompareLeft()); - - if (begin != sortedElements.begin()) - { - --begin; - } - if (end != sortedElements.end()) - { - ++end; - } - - for (auto iter = begin; iter != end; ++iter) - { - const SElementLayout& element = *iter; - QRectF rect = QRectF(element.rect); - float ratio = 1.0f; - - if (rect.width() != 0) - { - ratio = rect.height() != 0 ? aznumeric_cast(rect.width() / float(rect.height())) : 1.0f; - } - - const bool bSelected = element.IsSelected(); - - if (element.type == STimelineElement::KEY) - { - float rx = keyRadius * 200.0f / ratio; - float ry = keyRadius * 200.0f; - - if (pass == PASS_SELECTION) - { - if (bSelected) - { - QRectF selectionRect = rect.adjusted(-SELECTION_WIDTH * 0.5f + 0.5f, -SELECTION_WIDTH * 0.5f + 0.5f, SELECTION_WIDTH * 0.5f - 0.5f, SELECTION_WIDTH * 0.5f - 0.5f); - painter.setPen(QPen(palette.color(hasFocus ? QPalette::Highlight : QPalette::Shadow), SELECTION_WIDTH)); - painter.setBrush(QBrush(Qt::NoBrush)); - painter.drawRoundedRect(selectionRect, rx, ry, Qt::RelativeSize); - } - } - else if (pass != PASS_SHADOW) - { - QRectF shadowRect = rect.adjusted(-1.0f, -0.5f, 1.0f, 1.5f); - painter.setPen(QPen(QColor(0, 0, 0, 128), 2.0f)); - painter.setBrush(QBrush(Qt::NoBrush)); - painter.drawRoundedRect(shadowRect, rx, ry, Qt::RelativeSize); - - painter.setPen(QPen(QColor(element.color.r, element.color.g, element.color.b, 255))); - painter.setBrush(QBrush(QColor(element.color.r, element.color.g, element.color.b, 255))); - painter.drawRoundedRect(rect, rx, ry, Qt::RelativeSize); - - QRect textRect = track.rect; - textRect.moveLeft(aznumeric_cast(rect.right() + TRACK_DESCRIPTION_INDENT)); - textRect.setTop(textRect.top() + 1); - - if ((iter + 1) != sortedElements.end()) - { - textRect.setRight((iter + 1)->rect.left() - 6); - } - - painter.setPen(descriptionTextPen); - const QString elidedText = painter.fontMetrics().elidedText(element.description.c_str(), Qt::ElideRight, textRect.width()); - painter.drawText(textRect, Qt::TextSingleLine, elidedText); - } - } - else - { - float radius = 0.2f; - float rx = radius * 200.0f / ratio; - float ry = radius * 200.0f; - - if (pass == PASS_SELECTION) - { - if (bSelected) - { - QRectF selectionRect = rect.adjusted(-SELECTION_WIDTH * 0.5f + 0.5f, -SELECTION_WIDTH * 0.5f + 0.5f, SELECTION_WIDTH * 0.5f - 0.5f, SELECTION_WIDTH * 0.5f - 0.5f); - painter.setPen(QPen(palette.color(hasFocus ? QPalette::Highlight : QPalette::Shadow), SELECTION_WIDTH)); - painter.setBrush(QBrush(Qt::NoBrush)); - painter.drawRoundedRect(selectionRect, rx, ry, Qt::RelativeSize); - } - } - else if (pass == PASS_SHADOW) - { - QRectF shadowRect = rect.adjusted(0.0f, 0.0f, 0.0f, 1.0f); - painter.setPen(QPen(QColor(0, 0, 0, 128), 2.0f)); - painter.setBrush(QBrush(Qt::NoBrush)); - painter.drawRoundedRect(shadowRect, radius * 200.0f / ratio, radius * 200.0f, Qt::RelativeSize); - } - else - { - painter.setPen(QPen(QColor(element.color.r, element.color.g, element.color.b, 255))); - painter.setBrush(QBrush(QColor(element.color.r, element.color.g, element.color.b, 128))); - painter.drawRoundedRect(rect, radius * 200.0f / ratio, radius * 200.0f, Qt::RelativeSize); - } - } - } - } - } - } - - void DrawSelectionLines(QPainter& painter, const QPalette& palette, const STimelineViewState& viewState, STimelineContent& content, [[maybe_unused]] int rulerPrecision, [[maybe_unused]] int width, int height, [[maybe_unused]] float time, [[maybe_unused]] float timeUnitScale, bool hasFocus) - { - const VectorSet times = GetSelectedElementsTimeSet(content.track); - - QColor indicatorColor = palette.color(hasFocus ? QPalette::Highlight : QPalette::Shadow); - indicatorColor.setAlpha(70); - - for (auto iter = times.begin(); iter != times.end(); ++iter) - { - const float indicatorX = viewState.TimeToLocal(iter->ToFloat()) + 0.5f; - painter.setPen(indicatorColor); - painter.drawLine(QPointF(indicatorX, 0), QPointF(indicatorX, height)); - } - } - - void DrawTree(QPainter& painter, const QRect& treeRect, const QPalette& palette, QWidget* timeline, [[maybe_unused]] const STimelineContent& content, const STrackLayouts& tracks, const STimelineViewState& viewState, int scroll) - { - painter.save(); - - painter.setClipRect(treeRect); - painter.setClipping(true); - - painter.translate(0, -scroll); - - QTextOption textOption; - textOption.setWrapMode(QTextOption::NoWrap); - - const QColor textColor = palette.buttonText().color(); - - QStyleOptionFrame opt; - opt.palette = palette; - opt.state = QStyle::State_Enabled; - opt.rect = QRect(treeRect.left(), treeRect.top() - 1, treeRect.width(), treeRect.height() + 2); - - // Draw frame around tree - timeline->style()->drawPrimitive(QStyle::PE_Frame, &opt, &painter, timeline); - - for (size_t i = 0; i < tracks.size(); ++i) - { - const STrackLayout& track = tracks[i]; - - const QRect backgroundRect(1, track.rect.top() + 1, viewState.treeWidth - SPLITTER_WIDTH - 1, track.rect.height() - 1); - - const bool bIsDescriptionTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_DESCRIPTION_TRACK) != 0; - const bool bIsCompositeTrack = (track.pTimelineTrack->caps & STimelineTrack::CAP_COMPOUND_TRACK) != 0; - - painter.setPen(Qt::NoPen); - painter.setBrush(PickTrackBrush(palette, track)); - painter.drawRect(backgroundRect); - - const int branchLeft = TREE_LEFT_MARGIN + track.indent * TREE_INDENT_MULTIPLIER; - - if (track.pTimelineTrack->tracks.size() > 0) - { - QStyleOptionViewItem opt2; - opt2.rect = QRect(branchLeft, track.rect.top() + 1, TREE_BRANCH_INDICATOR_SIZE, track.rect.height() - 2); - opt2.state = QStyle::State_Enabled | QStyle::State_Children; - opt2.state |= track.pTimelineTrack->expanded ? QStyle::State_Open : QStyle::State_None; - - timeline->style()->drawPrimitive(QStyle::PE_IndicatorBranch, &opt2, &painter, timeline); - } - - const int textLeft = branchLeft + TREE_BRANCH_INDICATOR_SIZE + 4; - const int textWidth = std::max(treeRect.width() - textLeft - 4, 0); - const QRect textRect(textLeft, track.rect.top() + 1, textWidth, track.rect.height() - 2); - painter.setPen(QPen(textColor)); - painter.drawText(textRect, QString(track.pTimelineTrack->name), textOption); - } - - for (size_t i = 0; i < tracks.size(); ++i) - { - const STrackLayout& track = tracks[i]; - - const int lineY = track.rect.bottom() + 1; - painter.setPen(QPen(InterpolateColor(palette.color(QPalette::Mid), palette.color(QPalette::Window), 0.75f))); - painter.drawLine(QPoint(0, lineY), QPoint(treeRect.width(), lineY)); - } - - painter.restore(); - } - - void DrawSplitter(QPainter& painter, const QRect& splitterRect, const QPalette& palette, QWidget* timeline) - { - painter.fillRect(splitterRect, palette.color(QPalette::Window)); - - // Draw frame around splitter - QStyleOptionFrame frameOpt; - frameOpt.palette = palette; - frameOpt.state = QStyle::State_Enabled; - frameOpt.rect = QRect(splitterRect.left(), splitterRect.top(), splitterRect.width(), splitterRect.height() + 2); - timeline->style()->drawPrimitive(QStyle::PE_Frame, &frameOpt, &painter, timeline); - - // Draw resize handle dots - QStyleOption option; - option.palette = palette; - option.rect = QRect(splitterRect.left(), splitterRect.top() - 1, splitterRect.width() - 2, splitterRect.height() + 2); - timeline->style()->drawPrimitive(QStyle::PE_IndicatorDockWidgetResizeHandle, &option, &painter, timeline); - } -} - -struct CTimeline::SMouseHandler -{ - virtual ~SMouseHandler() = default; - virtual void mousePressEvent([[maybe_unused]] QMouseEvent* ev) {} - virtual void mouseDoubleClickEvent([[maybe_unused]] QMouseEvent* ev) {} - virtual void mouseMoveEvent([[maybe_unused]] QMouseEvent* ev) {} - virtual void mouseReleaseEvent([[maybe_unused]] QMouseEvent* ev) {} - virtual void focusOutEvent([[maybe_unused]] QFocusEvent* ev) {} - virtual void paintOver([[maybe_unused]] QPainter& painter) {} -}; - -struct CTimeline::SSelectionHandler - : SMouseHandler -{ - CTimeline* m_timeline; - QPoint m_startPoint; - QRect m_rect; - bool m_add; - TSelectedElements m_oldSelectedElements; - - SSelectionHandler(CTimeline* timeline, bool add) - : m_timeline(timeline) - , m_add(add) - { - if (m_timeline->m_pContent) - { - m_oldSelectedElements = GetSelectedElements(m_timeline->m_pContent->track); - } - } - - void mousePressEvent(QMouseEvent* ev) override - { - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint pos(ev->pos().x(), ev->pos().y() + scroll); - m_startPoint = m_timeline->m_viewState.LocalToLayout(pos); - m_rect = QRect(m_startPoint, m_startPoint + QPoint(1, 1)); - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint pos(ev->pos().x(), ev->pos().y() + scroll); - m_rect = QRect(m_startPoint, m_timeline->m_viewState.LocalToLayout(pos) + QPoint(1, 1)); - Apply(true); - } - - void Apply(bool continuous) - { - if (m_timeline->m_pContent) - { - const TSelectedElements selectedElements = GetSelectedElements(m_timeline->m_pContent->track); - - ClearElementSelection(m_timeline->m_pContent->track); - SelectElementsInRect(m_timeline->m_layout->tracks, m_rect); - - const TSelectedElements newSelectedElements = GetSelectedElements(m_timeline->m_pContent->track); - if ((continuous && selectedElements != newSelectedElements) - || (!continuous && m_oldSelectedElements != newSelectedElements)) - { - m_timeline->SignalSelectionChanged(continuous); - } - } - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* ev) override - { - Apply(false); - } - - void paintOver(QPainter& painter) override - { - painter.save(); - QColor highlightColor = m_timeline->palette().color(QPalette::Highlight); - QColor highlightColorA = QColor(highlightColor.red(), highlightColor.green(), highlightColor.blue(), 128); - painter.setPen(QPen(highlightColor)); - painter.setBrush(QBrush(highlightColorA)); - painter.drawRect(QRectF(m_rect)); - painter.restore(); - } -}; - -static STimelineElement* NextSelectedElement(const SElementLayoutPtrs& array, STimelineElement* nextToValue, STimelineElement* defaultValue) -{ - for (size_t i = 0; i < array.size(); ++i) - { - if (&array[i]->elementRef.GetElement() == nextToValue) - { - return &array[(i + 1) % array.size()]->elementRef.GetElement(); - } - } - return defaultValue; -} - -struct CTimeline::SMoveHandler - : SMouseHandler -{ - CTimeline* m_timeline; - QPoint m_startPoint; - bool m_cycleSelection; - SAnimTime m_startTime; - SAnimTime m_newTime; - std::vector m_elementTimes; - - SMoveHandler(CTimeline* timeline, bool cycleSelection) - : m_timeline(timeline) - , m_cycleSelection(cycleSelection) {} - - void mousePressEvent(QMouseEvent* ev) override - { - m_startTime = m_timeline->m_time; - m_newTime = m_startTime; - - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint currentPos(ev->pos().x(), ev->pos().y() + scroll); - - m_startPoint = m_timeline->m_viewState.LocalToLayout(QPoint(currentPos)); - m_elementTimes = GetSelectedElementTimes(m_timeline->m_pContent->track); - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - if (m_timeline->m_viewState.widthPixels == 0) - { - return; - } - - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint currentPos(ev->pos().x(), ev->pos().y() + scroll); - - int delta = m_timeline->m_viewState.LocalToLayout(currentPos).x() - m_startPoint.x(); - - const TSelectedElements selectedElements = GetSelectedElements(m_timeline->m_pContent->track); - - SetSelectedElementTimes(m_timeline->m_pContent->track, m_elementTimes); - - SAnimTime minDeltaTime = SAnimTime::Min(); - SAnimTime maxDeltaTime = SAnimTime::Max(); - SAnimTime minKeyTime = SAnimTime::Min(); - - for (size_t i = 0; i < selectedElements.size(); ++i) - { - const STimelineTrack& track = *selectedElements[i].first; - const STimelineElement& element = *selectedElements[i].second; - - SAnimTime minStartDelta = track.startTime - element.start; - minDeltaTime = max(minStartDelta, minDeltaTime); - SAnimTime maxEndDelta = track.endTime - (element.type == element.CLIP ? element.end : element.start); - maxDeltaTime = min(maxEndDelta, maxDeltaTime); - - minKeyTime = min(element.start, minKeyTime); - } - - SAnimTime deltaTime = SAnimTime(float(delta) / m_timeline->m_viewState.widthPixels * m_timeline->m_viewState.visibleDistance); - if (m_timeline->m_snapKeys) - { - SAnimTime newMinKeyTime = minKeyTime + deltaTime; - newMinKeyTime = newMinKeyTime.SnapToNearest(m_timeline->m_frameRate); - deltaTime = newMinKeyTime - minKeyTime; - } - - deltaTime = clamp_tpl(deltaTime, minDeltaTime, maxDeltaTime); - - m_newTime = m_startTime + deltaTime; - - MoveSelectedElements(m_timeline->m_pContent->track, deltaTime); - - m_timeline->ContentChanged(true); - - m_timeline->setCursor(Qt::SizeHorCursor); - m_cycleSelection = false; - } - - void focusOutEvent([[maybe_unused]] QFocusEvent* ev) - { - SetSelectedElementTimes(m_timeline->m_pContent->track, m_elementTimes); - m_timeline->UpdateLayout(); - } - - void mouseReleaseEvent(QMouseEvent* ev) - { - if (m_cycleSelection) - { - SElementLayoutPtrs hitElements; - - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint currentPos(ev->pos().x(), ev->pos().y() + scroll); - - QPoint posInLayoutSpace = m_timeline->m_viewState.LocalToLayout(currentPos); - HitTestElements(m_timeline->m_layout->tracks, QRect(posInLayoutSpace - QPoint(2, 2), posInLayoutSpace + QPoint(2, 2)), hitElements); - - if (!hitElements.empty()) - { - TSelectedElements selectedElements = GetSelectedElements(m_timeline->m_pContent->track); - if (selectedElements.size() == 1) - { - STimelineElement* lastSelection = selectedElements[0].second; - - ClearElementSelection(m_timeline->m_pContent->track); - NextSelectedElement(hitElements, lastSelection, &hitElements.back()->elementRef.GetElement())->selected = true; - m_timeline->SignalSelectionChanged(false); - } - else - { - ClearElementSelection(m_timeline->m_pContent->track); - hitElements.back()->elementRef.GetElement().selected = true; - m_timeline->SignalSelectionChanged(false); - } - } - } - - m_timeline->ContentChanged(false); - } -}; - -struct CTimeline::SPanHandler - : SMouseHandler -{ - CTimeline* m_timeline; - QPoint m_startPoint; - float m_startOrigin; - - SPanHandler(CTimeline* timeline) - : m_timeline(timeline) - { - } - - void mousePressEvent(QMouseEvent* ev) override - { - m_startPoint = QPoint(int(ev->x()), int(ev->y())); - m_startOrigin = m_timeline->m_viewState.viewOrigin; - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - QPoint pos(int(ev->x()), int(ev->y())); - float delta = 0.0f; - - if (m_timeline->m_viewState.widthPixels != 0) - { - delta = (pos - m_startPoint).x() * m_timeline->m_viewState.visibleDistance / m_timeline->m_viewState.widthPixels; - } - - m_timeline->m_viewState.viewOrigin = m_startOrigin + delta; - ClampViewOrigin(&m_timeline->m_viewState, *m_timeline->m_layout); - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* ev) override - { - } -}; - -struct CTimeline::SScrubHandler - : SMouseHandler -{ - CTimeline* m_timeline; - SScrubHandler(CTimeline* timeline) - : m_timeline(timeline) {} - SAnimTime m_startThumbPosition; - QPoint m_startPoint; - - void SetThumbPositionX(int positionX) - { - SAnimTime time = SAnimTime(m_timeline->m_viewState.LayoutToTime(positionX)); - - m_timeline->ClampAndSetTime(time, false); - } - - void mousePressEvent(QMouseEvent* ev) override - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - QPoint posInLayout = m_timeline->m_viewState.LocalToLayout(point); - - int thumbPositionX = m_timeline->m_viewState.TimeToLayout(m_timeline->m_time.ToFloat()); - QRect thumbRect(thumbPositionX - THUMB_WIDTH / 2, 0, THUMB_WIDTH, THUMB_HEIGHT); - - if (!thumbRect.contains(posInLayout)) - { - SetThumbPositionX(m_timeline->m_viewState.LocalToLayout(point).x()); - } - - m_startThumbPosition = m_timeline->m_time; - m_startPoint = point; - } - - void Apply(QMouseEvent* ev, [[maybe_unused]] bool continuous) - { - QPoint point = QPoint(ev->pos().x(), ev->pos().y()); - - bool shift = ev->modifiers().testFlag(Qt::ShiftModifier); - bool control = ev->modifiers().testFlag(Qt::ControlModifier); - - float delta = 0.0f; - - if (m_timeline->m_viewState.widthPixels != 0) - { - delta = (point.x() - m_startPoint.x()) * m_timeline->m_viewState.visibleDistance / m_timeline->m_viewState.widthPixels; - } - - if (shift) - { - delta *= 0.01f; - } - - if (control) - { - delta *= 0.1f; - } - - m_timeline->ClampAndSetTime(m_startThumbPosition + SAnimTime(delta), true); - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - Apply(ev, true); - } - - void mouseReleaseEvent(QMouseEvent* ev) override - { - Apply(ev, false); - } -}; - -struct CTimeline::SSplitterHandler - : SMouseHandler -{ - CTimeline* m_timeline; - int m_offset; - bool m_movedSlider; - - SSplitterHandler(CTimeline* timeline) - : m_timeline(timeline) - , m_offset(0) - , m_movedSlider(false) {} - - void mousePressEvent(QMouseEvent* ev) override - { - m_offset = m_timeline->m_viewState.treeWidth - ev->pos().x(); - } - - void mouseReleaseEvent([[maybe_unused]] QMouseEvent* ev) override - { - if (!m_movedSlider) - { - STimelineViewState& viewState = m_timeline->m_viewState; - - if (viewState.treeWidth == SPLITTER_WIDTH) - { - viewState.treeWidth = viewState.treeLastOpenedWidth; - } - else - { - viewState.treeLastOpenedWidth = viewState.treeWidth; - viewState.treeWidth = SPLITTER_WIDTH; - } - - m_timeline->UpdateLayout(); - m_timeline->update(); - } - } - - void mouseMoveEvent(QMouseEvent* ev) override - { - m_timeline->setCursor(QCursor(Qt::SplitHCursor)); - uint treeWidth = clamp_tpl(ev->pos().x(), SPLITTER_WIDTH, m_timeline->width()) + m_offset; - m_timeline->m_viewState.treeWidth = treeWidth; - m_timeline->m_viewState.treeLastOpenedWidth = treeWidth; - m_timeline->UpdateLayout(); - m_timeline->update(); - m_movedSlider = true; - } -}; - -struct CTimeline::STreeMouseHandler - : SMouseHandler -{ - CTimeline* m_timeline; - STreeMouseHandler(CTimeline* timeline) - : m_timeline(timeline) {} - - void mousePressEvent(QMouseEvent* ev) override - { - const bool bCtrlPressed = (ev->modifiers() & Qt::CTRL) != 0; - const bool bShiftPressed = (ev->modifiers() & Qt::SHIFT) != 0; - - const int scroll = m_timeline->m_scrollBar ? m_timeline->m_scrollBar->value() : 0; - const QPoint pos(ev->pos().x(), ev->pos().y() + scroll); - - STrackLayout* pTrackLayout = m_timeline->GetTrackLayoutFromPos(pos); - - if (!pTrackLayout) - { - if (!bShiftPressed && !bCtrlPressed) - { - ClearTrackSelection(m_timeline->m_pContent->track); - } - } - else - { - const int left = TREE_LEFT_MARGIN + pTrackLayout->indent * TREE_INDENT_MULTIPLIER; - const int right = left + TREE_BRANCH_INDICATOR_SIZE; - - const int x = pos.x(); - - if (x >= left && x <= right) - { - ToggleTrackExpansion(pTrackLayout); - } - else - { - const bool bPreviousState = pTrackLayout->pTimelineTrack->selected; - - if (!bCtrlPressed) - { - ClearTrackSelection(m_timeline->m_pContent->track); - } - - if (bCtrlPressed) - { - pTrackLayout->pTimelineTrack->selected = !bPreviousState; - } - else if (bShiftPressed) - { - STrackLayouts& tracks = m_timeline->m_layout->tracks; - - auto startFindIter = std::find_if(tracks.begin(), tracks.end(), [=](const STrackLayout& track) { return (pTrackLayout == &track); }); - auto endFindIter = std::find_if(tracks.begin(), tracks.end(), [=](const STrackLayout& track) { return (m_timeline->m_pLastSelectedTrack == &track); }); - - if (startFindIter != tracks.end() && endFindIter != tracks.end()) - { - if (startFindIter > endFindIter) - { - std::swap(startFindIter, endFindIter); - } - - for (auto iter = startFindIter; iter <= endFindIter; ++iter) - { - iter->pTimelineTrack->selected = true; - } - } - } - else - { - pTrackLayout->pTimelineTrack->selected = true; - } - - if (!bShiftPressed && pTrackLayout->pTimelineTrack->selected) - { - m_timeline->m_pLastSelectedTrack = pTrackLayout; - } - - m_timeline->SignalTrackSelectionChanged(); - } - } - } - - void mouseDoubleClickEvent(QMouseEvent* ev) override - { - if (ev->modifiers() == 0) - { - STrackLayout* pTrackLayout = m_timeline->GetTrackLayoutFromPos(ev->pos()); - ToggleTrackExpansion(pTrackLayout); - } - } - -private: - void ToggleTrackExpansion(STrackLayout* pTrackLayout) - { - if (pTrackLayout && pTrackLayout->pTimelineTrack) - { - pTrackLayout->pTimelineTrack->expanded = !pTrackLayout->pTimelineTrack->expanded; - m_timeline->UpdateLayout(); - m_timeline->update(); - } - } -}; - -// --------------------------------------------------------------------------- - -CTimeline::CTimeline(QWidget* parent) - : QWidget(parent) - , m_cycled(true) - , m_sizeToContent(false) - , m_snapTime(false) - , m_snapKeys(false) - , m_treeVisible(false) - , m_selIndicators(false) - , m_verticalScrollbarVisible(false) - , m_drawMarkers(false) - , m_layout(new STimelineLayout) - , m_keyWidth(DEFAULT_KEY_WIDTH) - , m_keyRadius(DEFAULT_KEY_RADIUS) - , m_cornerWidget(nullptr) - , m_scrollBar(nullptr) - , m_cornerWidgetWidth(0) - , m_pContent(nullptr) - , m_timeUnitScale(1.0f) - , m_timeStepNum(1) - , m_timeStepIndex(0) - , m_frameRate(SAnimTime::eFrameRate_30fps) - , m_time(0.0f) - , m_pFilterLineEdit(nullptr) - , m_pLastSelectedTrack(nullptr) -{ - setMinimumWidth(THUMB_WIDTH * 3); - setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Maximum); - setFocusPolicy(Qt::WheelFocus); - setMouseTracking(true); - - m_viewState.visibleDistance = 1.0f; -} - -CTimeline::~CTimeline() -{ -} - -void CTimeline::paintEvent([[maybe_unused]] QPaintEvent* ev) -{ - const QPoint mousePos = mapFromGlobal(QCursor::pos()); - - QPainter painter(this); - painter.save(); - painter.translate(0.5f, 0.5f); - - if (m_viewState.visibleDistance != 0) - { - SAnimTime totalDuration = m_layout->maxEndTime - m_layout->minStartTime; - m_viewState.scrollPixels = QPoint(m_viewState.ScrollOffset(m_viewState.viewOrigin), 0); - m_viewState.maxScrollX = int(m_viewState.widthPixels * totalDuration.ToFloat() / m_viewState.visibleDistance) - m_viewState.widthPixels; - } - else - { - m_viewState.scrollPixels = QPoint(0, 0); - m_viewState.maxScrollX = 0; - } - - const int scroll = m_scrollBar ? m_scrollBar->value() : 0; - const QPoint localToLayoutTranslate = m_viewState.LayoutToLocal(QPoint(0, -scroll)); - - int rulerPrecision = 0; - - painter.translate(localToLayoutTranslate); - painter.setRenderHint(QPainter::Antialiasing); - - DrawTracks(painter, PASS_BACKGROUND, PASS_BACKGROUND, *m_layout, m_viewState, - palette(), mousePos, hasFocus(), width(), m_keyRadius, m_timeUnitScale, m_drawMarkers); - - DrawTracks(painter, PASS_SELECTION, PASS_MAIN, *m_layout, m_viewState, - palette(), mousePos, hasFocus(), width(), m_keyRadius, m_timeUnitScale, m_drawMarkers); - - painter.translate(-localToLayoutTranslate); - - DrawingPrimitives::SRulerOptions rulerOptions; - rulerOptions.m_rect = QRect(m_viewState.treeWidth, -1, size().width() - m_viewState.treeWidth, RULER_HEIGHT + 2); - rulerOptions.m_visibleRange = Range(m_viewState.LocalToTime(m_viewState.treeWidth) * m_timeUnitScale, m_viewState.LocalToTime(size().width()) * m_timeUnitScale); - rulerOptions.m_rulerRange = Range(m_layout->minStartTime.ToFloat() * m_timeUnitScale, m_layout->maxEndTime.ToFloat() * m_timeUnitScale); - rulerOptions.m_markHeight = RULER_MARK_HEIGHT; - rulerOptions.m_shadowSize = RULER_SHADOW_HEIGHT; - DrawingPrimitives::DrawRuler(painter, palette(), rulerOptions, &rulerPrecision); - - if (m_pContent && isEnabled()) - { - DrawingPrimitives::STimeSliderOptions timeSliderOptions; - timeSliderOptions.m_rect = rect(); - timeSliderOptions.m_precision = rulerPrecision; - timeSliderOptions.m_position = m_viewState.TimeToLocal(m_time.ToFloat()); - timeSliderOptions.m_time = m_time.ToFloat() * m_timeUnitScale; - timeSliderOptions.m_bHasFocus = hasFocus(); - DrawingPrimitives::DrawTimeSlider(painter, palette(), timeSliderOptions); - - DrawSelectionLines(painter, palette(), m_viewState, *m_pContent, rulerPrecision, width(), height(), m_time.ToFloat(), m_timeUnitScale, hasFocus()); - } - - painter.translate(localToLayoutTranslate); - - if (m_mouseHandler) - { - m_mouseHandler->paintOver(painter); - } - - painter.translate(-localToLayoutTranslate); - - if (m_viewState.scrollPixels.x() < 0) - { - QRect rect(m_viewState.treeWidth, 0, SCROLL_SHADOW_WIDTH, height()); - QLinearGradient grad(rect.left(), rect.top(), rect.right(), rect.top()); - grad.setColorAt(0.0f, QColor(0, 0, 0, 96)); - grad.setColorAt(1.0f, QColor(0, 0, 0, 0)); - painter.fillRect(rect, QBrush(grad)); - } - - SAnimTime totalDuration = m_layout->maxEndTime - m_layout->minStartTime; - - if (m_viewState.scrollPixels.x() > -m_viewState.maxScrollX) - { - QRect rect(width() - SCROLL_SHADOW_WIDTH, 0, SCROLL_SHADOW_WIDTH, height()); - QLinearGradient grad(rect.left(), rect.top(), rect.right(), rect.top()); - grad.setColorAt(0.0f, QColor(0, 0, 0, 0)); - grad.setColorAt(1.0f, QColor(0, 0, 0, 96)); - painter.fillRect(rect, QBrush(grad)); - } - - { - QColor color = palette().color(QPalette::Dark); - color.setAlpha(128); - painter.setPen(QPen(color)); - painter.drawLine(QPoint(0, 0), QPoint(0, height())); - painter.drawLine(QPoint(width() - 1, 0), QPoint(width() - 1, height())); - painter.drawLine(QPoint(1, 0), QPoint(width() - 1, 0)); - painter.drawLine(QPoint(0, height()), QPoint(width() - 1, height())); - } - - painter.restore(); - - if (m_treeVisible) - { - if (m_pContent) - { - QRect treeRect(0, 0, m_viewState.treeWidth - SPLITTER_WIDTH + 1, height()); - DrawTree(painter, treeRect, palette(), this, *m_pContent, m_layout->tracks, m_viewState, scroll); - } - - QRect splitterRect(m_viewState.treeWidth - SPLITTER_WIDTH, 0, SPLITTER_WIDTH, height()); - DrawSplitter(painter, splitterRect, palette(), this); - } - - if (!isEnabled()) - { - QColor disabledOverlayColor = palette().color(QPalette::Disabled, QPalette::Button); - disabledOverlayColor.setAlpha(128); - painter.fillRect(0, 0, width(), height(), QBrush(disabledOverlayColor)); - } -} - -void CTimeline::keyPressEvent(QKeyEvent* ev) -{ - const QPoint mousePos = mapFromGlobal(QCursor::pos()); - QMouseEvent mouseEvent(QEvent::MouseMove, mousePos, Qt::NoButton, Qt::NoButton, ev->modifiers()); - mouseMoveEvent(&mouseEvent); - int rawKey = ev->key() | ev->modifiers(); - QKeySequence key(rawKey); - - if (key == QKeySequence(Qt::Key_Z | Qt::CTRL)) - { - SignalUndo(); - } - else if (key == QKeySequence(Qt::Key_Y | Qt::CTRL) || (key == QKeySequence(Qt::Key_Z | Qt::CTRL | Qt::SHIFT))) - { - SignalRedo(); - } - else - { - HandleKeyEvent(rawKey); - } -} - -void CTimeline::keyReleaseEvent(QKeyEvent* ev) -{ - const QPoint mousePos = mapFromGlobal(QCursor::pos()); - QMouseEvent mouseEvent(QEvent::MouseMove, mousePos, Qt::NoButton, Qt::NoButton, ev->modifiers()); - mouseMoveEvent(&mouseEvent); -} - -bool CTimeline::HandleKeyEvent(int k) -{ - QKeySequence key(k); - - if (key == QKeySequence(Qt::Key_Delete)) - { - OnMenuDelete(); - return true; - } - - if (key == QKeySequence(Qt::Key_D)) - { - OnMenuDuplicate(); - return true; - } - - if (key == QKeySequence(Qt::Key_Home)) - { - m_time = SAnimTime(0); - update(); - SignalScrub(false); - return true; - } - if (key == QKeySequence(Qt::Key_End)) - { - SAnimTime endTime = SAnimTime(0); - for (size_t i = 0; i < m_pContent->track.tracks.size(); ++i) - { - endTime = std::max(endTime, m_pContent->track.tracks[i]->endTime); - } - m_time = endTime; - update(); - SignalScrub(false); - return true; - } - if (key == QKeySequence(Qt::Key_X) || key == QKeySequence(Qt::Key_PageUp)) - { - OnMenuPreviousKey(); - return true; - } - if (key == QKeySequence(Qt::Key_C) || key == QKeySequence(Qt::Key_PageDown)) - { - OnMenuNextKey(); - return true; - } - - if (k == Qt::Key_Comma || k == Qt::Key_Left) - { - OnMenuPreviousFrame(); - return true; - } - - if (k == Qt::Key_Period || k == Qt::Key_Right) - { - OnMenuNextFrame(); - return true; - } - - if (key == QKeySequence(Qt::Key_Space)) - { - OnMenuPlay(); - return true; - } - - // shortcut is Ctrl+# - int maskedKey = ((~Qt::KeyboardModifierMask) & k); - if (((k & Qt::CTRL) != 0) && (maskedKey >= Qt::Key_0 && maskedKey <= Qt::Key_9)) - { - int number = maskedKey - int(Qt::Key_0); - SignalNumberHotkey(number); - return true; - } - - return false; -} - -bool CTimeline::ProcessesKey(const QKeySequence& key) -{ - static QSet customShortcuts = { - QKeySequence(Qt::Key_Delete), - QKeySequence(Qt::Key_D), - QKeySequence(Qt::Key_Home), - QKeySequence(Qt::Key_End), - QKeySequence(Qt::Key_PageUp), - QKeySequence(Qt::Key_X), - QKeySequence(Qt::Key_PageDown), - QKeySequence(Qt::Key_C), - QKeySequence(Qt::Key_Comma), - QKeySequence(Qt::Key_Left), - QKeySequence(Qt::Key_Period), - QKeySequence(Qt::Key_Right), - QKeySequence(Qt::Key_Space), - QKeySequence(Qt::CTRL | Qt::Key_0), - QKeySequence(Qt::CTRL | Qt::Key_1), - QKeySequence(Qt::CTRL | Qt::Key_2), - QKeySequence(Qt::CTRL | Qt::Key_3), - QKeySequence(Qt::CTRL | Qt::Key_4), - QKeySequence(Qt::CTRL | Qt::Key_5), - QKeySequence(Qt::CTRL | Qt::Key_6), - QKeySequence(Qt::CTRL | Qt::Key_7), - QKeySequence(Qt::CTRL | Qt::Key_8), - QKeySequence(Qt::CTRL | Qt::Key_9) - }; - - return customShortcuts.contains(key); -} - -void CTimeline::mousePressEvent(QMouseEvent* ev) -{ - setFocus(); - - const bool bInTreeArea = m_treeVisible && (ev->x() <= m_viewState.treeWidth); - - if (ev->button() == Qt::LeftButton) - { - QPoint posInLayout = m_viewState.LocalToLayout(ev->pos()); - - if (bInTreeArea) - { - const bool bOverSplitter = ev->x() >= (m_viewState.treeWidth - SPLITTER_WIDTH); - - if (bOverSplitter) - { - m_mouseHandler.reset(new SSplitterHandler(this)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - else - { - m_mouseHandler.reset(new STreeMouseHandler(this)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - } - else if (ev->y() < RULER_HEIGHT) - { - m_mouseHandler.reset(new SScrubHandler(this)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - else - { - QPoint posInLayoutSpace = m_viewState.LocalToLayout(ev->pos()); - - SElementLayoutPtrs hitElements; - bool bHit = HitTestElements(m_layout->tracks, QRect(posInLayoutSpace - QPoint(2, 2), posInLayoutSpace + QPoint(2, 2)), hitElements); - - if (ev->modifiers() & Qt::SHIFT || ev->modifiers() & Qt::CTRL) - { - if (bHit) - { - hitElements.back()->SetSelected(hitElements.back()->IsSelected()); - mouseMoveEvent(ev); - update(); - } - else - { - m_mouseHandler.reset(new SSelectionHandler(this, true)); - m_mouseHandler->mousePressEvent(ev); - } - } - else - { - if (bHit) - { - bool useExistingSelection = std::any_of(hitElements.begin(), hitElements.end(), [](const SElementLayout* element) { return element->IsSelected(); }); - - if (!useExistingSelection) - { - const TSelectedElements selectedElements = GetSelectedElements(m_pContent->track); - - ClearElementSelection(m_pContent->track); - hitElements.back()->SetSelected(true); - - if (selectedElements != GetSelectedElements(m_pContent->track)) - { - SignalSelectionChanged(false); - } - } - - bool cycleSelection = useExistingSelection; - m_mouseHandler.reset(new SMoveHandler(this, cycleSelection)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - else - { - m_mouseHandler.reset(new SSelectionHandler(this, false)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - } - } - } - else if (ev->button() == Qt::MiddleButton) - { - if (!bInTreeArea) - { - m_mouseHandler.reset(new SPanHandler(this)); - m_mouseHandler->mousePressEvent(ev); - update(); - } - } - else if (ev->button() == Qt::RightButton) - { - if (bInTreeArea) - { - std::vector selectedTracks; - GetSelectedTracks(m_pContent->track, selectedTracks); - - STrackLayout* pLayout = GetTrackLayoutFromPos(ev->pos()); - if (pLayout) - { - if (!stl::find(selectedTracks, pLayout->pTimelineTrack)) - { - ClearTrackSelection(m_pContent->track); - pLayout->pTimelineTrack->selected = true; - } - - SignalTreeContextMenu(mapToGlobal(ev->pos())); - } - } - else - { - QMenu menu; - bool hasSelection = false; - ForEachElement(m_pContent->track, [&]([[maybe_unused]] STimelineTrack& t, STimelineElement& e) - { - if (e.selected) - { - hasSelection = true; - } - }); - - menu.addAction("Selection to Cursor", this, SLOT(OnMenuSelectionToCursor()))->setEnabled(hasSelection); - QAction* duplicateAction = menu.addAction("Duplicate", this, SLOT(OnMenuDuplicate()), QKeySequence("D")); - duplicateAction->setEnabled(hasSelection); - menu.addSeparator(); - menu.addAction("Delete Event(s)", this, SLOT(OnMenuDelete()), QKeySequence("Delete"))->setEnabled(hasSelection); - menu.addSeparator(); - menu.addAction("Play / Pause", this, SLOT(OnMenuPlay()), QKeySequence("Space")); - menu.addAction("Previous Frame", this, SLOT(OnMenuPreviousFrame()), QKeySequence(",")); - menu.addAction("Next Frame", this, SLOT(OnMenuNextFrame()), QKeySequence(".")); - menu.addAction("Jump to Previous Event", this, SLOT(OnMenuPreviousKey()), QKeySequence("X")); - menu.addAction("Jump to Next Event", this, SLOT(OnMenuNextKey()), QKeySequence("C")); - menu.exec(QCursor::pos(), duplicateAction); - } - } -} - -void CTimeline::AddKeyToTrack(STimelineTrack& track, SAnimTime time) -{ - if (m_snapKeys) - { - time = time.SnapToNearest(m_frameRate); - } - - track.modified = true; - track.elements.push_back(track.defaultElement); - track.elements.back().added = true; - SAnimTime length = track.defaultElement.end - track.defaultElement.start; - track.elements.back().start = time; - track.elements.back().end = length; - track.elements.back().selected = true; -} - -void CTimeline::mouseDoubleClickEvent(QMouseEvent* ev) -{ - if (ev->button() == Qt::LeftButton) - { - QPoint posInLayout = m_viewState.LocalToLayout(ev->pos()); - - const bool bInTreeArea = m_treeVisible && (ev->x() <= m_viewState.treeWidth); - - if (bInTreeArea) - { - const bool bOverSplitter = ev->x() >= (m_viewState.treeWidth - SPLITTER_WIDTH); - - if (!bOverSplitter) - { - m_mouseHandler.reset(new STreeMouseHandler(this)); - m_mouseHandler->mouseDoubleClickEvent(ev); - update(); - } - } - - QPoint layoutPoint = m_viewState.LocalToLayout(ev->pos()); - STrackLayout* track = HitTestTrack(m_layout->tracks, layoutPoint); - - if (track) - { - SElementLayoutPtrs hitElements; - const bool bHit = HitTestElements(m_layout->tracks, QRect(layoutPoint - QPoint(2, 2), layoutPoint + QPoint(2, 2)), hitElements); - - if (!bHit) - { - float time = m_viewState.LayoutToTime(layoutPoint.x()); - STimelineTrack& timelineTrack = *track->pTimelineTrack; - - if ((timelineTrack.caps & STimelineTrack::CAP_COMPOUND_TRACK) == 0) - { - AddKeyToTrack(timelineTrack, SAnimTime(time)); - } - else - { - const size_t numSubTracks = timelineTrack.tracks.size(); - for (size_t i = 0; i < numSubTracks; ++i) - { - STimelineTrack& subTrack = *timelineTrack.tracks[i]; - AddKeyToTrack(subTrack, SAnimTime(time)); - } - } - - ContentChanged(false); - m_mouseHandler.reset(); - mouseMoveEvent(ev); - } - } - } -} - -void CTimeline::UpdateCursor(QMouseEvent* ev) -{ - const int scroll = m_scrollBar ? m_scrollBar->value() : 0; - const QPoint pos(ev->pos().x(), ev->pos().y() + scroll); - - QPoint posInLayoutSpace = m_viewState.LocalToLayout(pos); - - SElementLayoutPtrs hitElements; - HitTestElements(m_layout->tracks, QRect(posInLayoutSpace - QPoint(2, 2), posInLayoutSpace + QPoint(2, 2)), hitElements); - const bool bOverSelected = !hitElements.empty() && hitElements.back()->IsSelected(); - const bool bInTreeArea = m_treeVisible && (ev->x() <= m_viewState.treeWidth); - - bool shift = ev->modifiers().testFlag(Qt::ShiftModifier); - bool control = ev->modifiers().testFlag(Qt::ControlModifier); - - if (m_mouseHandler) - { - m_mouseHandler->mouseMoveEvent(ev); - update(); - } - else if (m_treeVisible && (ev->x() <= m_viewState.treeWidth) && (ev->x() >= (m_viewState.treeWidth - SPLITTER_WIDTH))) - { - setCursor(QCursor(Qt::SplitHCursor)); - } - else if (!bInTreeArea && bOverSelected && !(shift || control)) - { - setCursor(QCursor(Qt::SizeHorCursor)); - } - else - { - setCursor(QCursor()); - } -} - -void CTimeline::mouseMoveEvent(QMouseEvent* ev) -{ - UpdateCursor(ev); -} - -void CTimeline::mouseReleaseEvent(QMouseEvent* ev) -{ - if (ev->button() == Qt::LeftButton || ev->button() == Qt::MiddleButton) - { - if (m_mouseHandler.get()) - { - m_mouseHandler->mouseReleaseEvent(ev); - m_mouseHandler.reset(); - update(); - } - } - UpdateCursor(ev); -} - -void CTimeline::focusOutEvent(QFocusEvent* ev) -{ - if (m_mouseHandler.get()) - { - m_mouseHandler->focusOutEvent(ev); - m_mouseHandler.reset(); - } - - update(); -} - -void CTimeline::wheelEvent(QWheelEvent* ev) -{ - int pixelDelta = ev->pixelDelta().manhattanLength(); - - if (pixelDelta == 0) - { - pixelDelta = ev->angleDelta().y(); - } - - const float fractionOfView = std::min(m_viewState.widthPixels != 0 ? float(pixelDelta) / m_viewState.widthPixels : 0.0f, 0.5f); - - SetVisibleDistance(m_viewState.visibleDistance - m_viewState.visibleDistance * fractionOfView); -} - -QSize CTimeline::sizeHint() const -{ - return QSize(m_layout->size); -} - -void CTimeline::resizeEvent([[maybe_unused]] QResizeEvent* ev) -{ - UpdateLayout(); -} - -SAnimTime CTimeline::ClampAndSnapTime(SAnimTime time, bool snapToFrames) const -{ - SAnimTime minTime = m_layout->minStartTime; - SAnimTime maxTime = m_layout->maxEndTime; - SAnimTime unclampedTime = time; - SAnimTime deltaTime = maxTime - minTime; - - if (m_cycled) - { - while (unclampedTime < minTime) - { - unclampedTime += deltaTime; - } - - unclampedTime = ((unclampedTime - minTime) % deltaTime) + minTime; - } - - SAnimTime clampedTime = clamp_tpl(unclampedTime, minTime, maxTime); - - if (!snapToFrames) - { - return clampedTime; - } - else - { - int timeStepIndex = static_cast(floor(clampedTime.ToFloat() * static_cast(m_timeStepNum) + 0.05f)); - float normalizedTime = static_cast(timeStepIndex) / static_cast(m_timeStepNum); - return SAnimTime(normalizedTime); - } -} - -void CTimeline::ClampAndSetTime(SAnimTime time, bool scrubThrough) -{ - SAnimTime newTime = ClampAndSnapTime(time, m_snapTime); - - if (newTime != m_time) - { - m_time = newTime; - UpdateLayout(); - update(); - SignalScrub(scrubThrough); - } -} - -void CTimeline::SetTimeUnitScale(float scale, float step) -{ - m_timeUnitScale = scale; - m_timeStepNum = static_cast(scale / step); - update(); -} - -void CTimeline::SetTime(SAnimTime time) -{ - m_time = time; - update(); -} - -void CTimeline::SetCycled(bool cycled) -{ - m_cycled = cycled; -} - -void CTimeline::SetContent(STimelineContent* pContent) -{ - m_pContent = pContent; - - UpdateLayout(); - update(); -} - -void CTimeline::UpdateLayout() -{ - m_layout->tracks.clear(); - - m_viewState.widthPixels = width(); - - if (m_treeVisible) - { - m_viewState.widthPixels -= m_viewState.treeWidth; - m_viewState.widthPixels = std::max(m_viewState.widthPixels, 0); - } - - if (m_verticalScrollbarVisible) - { - if (!m_scrollBar) - { - m_scrollBar = new QScrollBar(Qt::Vertical, this); - connect(m_scrollBar, SIGNAL(valueChanged(int)), this, SLOT(OnVerticalScroll(int))); - } - - const uint scrollbarWidth = style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, this); - m_scrollBar->setGeometry(width() - scrollbarWidth, 0, scrollbarWidth, height()); - - m_viewState.widthPixels -= scrollbarWidth; - m_viewState.widthPixels = std::max(m_viewState.widthPixels, 0); - } - else if (!m_verticalScrollbarVisible && m_scrollBar) - { - SAFE_DELETE(m_scrollBar); - } - - ClampViewOrigin(&m_viewState, *m_layout); - - if (m_pContent) - { - CalculateLayout(m_layout.get(), *m_pContent, m_viewState, m_pFilterLineEdit, m_time.ToFloat(), m_keyWidth, m_treeVisible); - ApplyPushOut(m_layout.get(), m_keyWidth); - } - - if (m_scrollBar) - { - const int timelineHeight = rect().height(); - const int scrollBarRange = m_layout->size.height() - timelineHeight; - - if (scrollBarRange > 0) - { - m_scrollBar->setRange(0, scrollBarRange); - m_scrollBar->show(); - } - else - { - m_scrollBar->setValue(0); - m_scrollBar->hide(); - } - } - - if (m_sizeToContent) - { - setMaximumHeight(m_layout->size.height()); - setMinimumHeight(m_layout->size.height()); - } - else - { - setMinimumHeight(RULER_HEIGHT + 1); - setMaximumHeight(QWIDGETSIZE_MAX); - } - - if (m_treeVisible) - { - if (!m_pFilterLineEdit) - { - m_pFilterLineEdit = new QLineEdit(this); - connect(m_pFilterLineEdit, SIGNAL(textChanged(const QString&)), this, SLOT(OnFilterChanged())); - } - - const uint cornerWidgetWidth = m_cornerWidget ? m_cornerWidgetWidth : 0; - m_pFilterLineEdit->resize(m_viewState.treeWidth - SPLITTER_WIDTH - cornerWidgetWidth, RULER_HEIGHT + VERTICAL_PADDING); - - if (m_cornerWidget) - { - m_cornerWidget->setGeometry(m_viewState.treeWidth - SPLITTER_WIDTH - cornerWidgetWidth, 0, cornerWidgetWidth, RULER_HEIGHT + VERTICAL_PADDING); - } - } - else if (!m_treeVisible && m_pFilterLineEdit) - { - SAFE_DELETE(m_pFilterLineEdit); - } -} - -void CTimeline::SetSizeToContent(bool sizeToContent) -{ - m_sizeToContent = sizeToContent; - - UpdateLayout(); -} - -void CTimeline::ContentChanged(bool continuous) -{ - SignalContentChanged(continuous); - - DeletedMarkedElements(m_pContent->track); - - if (!continuous) - { - ForEachElement(m_pContent->track, [](STimelineTrack& track, STimelineElement& element) - { - track.modified = false; - element.added = false; - }); - } - - UpdateLayout(); - update(); -} - -void CTimeline::OnMenuSelectionToCursor() -{ - TSelectedElements elements = GetSelectedElements(m_pContent->track); - - for (size_t i = 0; i < elements.size(); ++i) - { - STimelineTrack& track = *elements[i].first; - STimelineElement& element = *elements[i].second; - SAnimTime length = element.end - element.start; - element.start = m_time; - element.end = element.start + length; - if (element.type == element.CLIP) - { - if (length > track.endTime) - { - element.start = track.endTime - length; - } - } - if (element.start < track.startTime) - { - element.start = track.startTime; - } - } - - ContentChanged(false); -} - -void CTimeline::OnMenuDuplicate() -{ - TSelectedElements selectedElements = GetSelectedElements(m_pContent->track); - if (selectedElements.empty()) - { - return; - } - - typedef std::vector > TTrackElements; - - TTrackElements elements; - - ForEachElement(m_pContent->track, [&](STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - elements.push_back(std::make_pair(&track, element)); - element.selected = false; - } - }); - - for (size_t i = 0; i < elements.size(); ++i) - { - STimelineTrack* track = elements[i].first; - const STimelineElement& element = elements[i].second; - track->elements.push_back(element); - STimelineElement& e = track->elements.back(); - e.userId = 0; - e.added = true; - e.sideLoadChanged = true; - e.selected = true; - } - - ContentChanged(false); - SignalSelectionChanged(false); -} - -void CTimeline::OnMenuCopy() -{ -} - -void CTimeline::OnMenuPaste() -{ -} - -void CTimeline::OnMenuDelete() -{ - ForEachElement(m_pContent->track, [](STimelineTrack& track, STimelineElement& element) - { - if (element.selected) - { - track.modified = true; - element.deleted = true; - } - }); - - ContentChanged(false); -} - -void CTimeline::OnMenuPlay() -{ - SignalPlay(); -} - -typedef std::vector > TimeToId; -static void GetAllTimes(TimeToId* times, const STimelineTrack& track) -{ - for (size_t i = 0; i < track.tracks.size(); ++i) - { - GetAllTimes(times, *track.tracks[i]); - } -} - -static void GetAllTimes(TimeToId* times, STimelineContent& content) -{ - ForEachTrack(content.track, [&](STimelineTrack& track) - { - times->push_back(std::make_pair(track.startTime, STimelineContentElementRef())); - times->push_back(std::make_pair(track.endTime, STimelineContentElementRef())); - }); - - ForEachElementWithIndex(content.track, [=](STimelineTrack& track, STimelineElement& element, size_t i) - { - STimelineContentElementRef ref(&track, i); - times->push_back(std::make_pair(element.start, ref)); - if (element.type == STimelineElement::CLIP) - { - times->push_back(std::make_pair(element.end, ref)); - } - }); - - std::sort(times->begin(), times->end()); -} - -static STimelineContentElementRef SelectedIdAtTime(const std::vector& selection, [[maybe_unused]] const STimelineContent& content, SAnimTime time) -{ - for (size_t i = 0; i < selection.size(); ++i) - { - const STimelineContentElementRef& id = selection[i]; - const STimelineElement& element = id.GetElement(); - if (element.start == time || element.end == time) - { - return id; - } - } - return STimelineContentElementRef(); -} - -void CTimeline::OnMenuPreviousKey() -{ - if (!m_pContent) - { - return; - } - TimeToId times; - GetAllTimes(×, *m_pContent); - - std::vector selection; - ForEachElementWithIndex(m_pContent->track, [&](STimelineTrack& t, STimelineElement& e, size_t i) - { - if (e.selected) - { - selection.push_back(STimelineContentElementRef(&t, i)); - } - }); - - STimelineContentElementRef selectedId = SelectedIdAtTime(selection, *m_pContent, m_time); - - TimeToId::iterator it = std::lower_bound(times.begin(), times.end(), std::make_pair(m_time, selectedId)); - if (it != times.end()) - { - if (it != times.begin()) - { - --it; - } - - ClearElementSelection(m_pContent->track); - if (it->second.IsValid()) - { - it->second.GetElement().selected = true; - } - - m_time = it->first; - - SignalSelectionChanged(false); - SignalScrub(false); - update(); - } -} - -void CTimeline::OnMenuNextKey() -{ - if (!m_pContent) - { - return; - } - TimeToId times; - GetAllTimes(×, *m_pContent); - - std::vector selection; - ForEachElementWithIndex(m_pContent->track, [&](STimelineTrack& t, STimelineElement& e, size_t i) - { - if (e.selected) - { - selection.push_back(STimelineContentElementRef(&t, i)); - } - }); - - STimelineContentElementRef selectedId = SelectedIdAtTime(selection, *m_pContent, m_time); - - TimeToId::iterator it = std::upper_bound(times.begin(), times.end(), std::make_pair(m_time, selectedId)); - if (it != times.end()) - { - ClearElementSelection(m_pContent->track); - if (it->second.IsValid()) - { - it->second.GetElement().selected = true; - } - - m_time = it->first; - - SignalSelectionChanged(false); - SignalScrub(false); - update(); - } -} - -void CTimeline::OnMenuPreviousFrame() -{ - m_timeStepIndex = static_cast(floor(m_time.ToFloat() * static_cast(m_timeStepNum) + 0.05f)) - 1; - if (m_timeStepIndex < 0) - { - m_timeStepIndex = m_timeStepNum; - } - float normalizedTime = static_cast(m_timeStepIndex) / static_cast(m_timeStepNum); - m_time = SAnimTime(normalizedTime); - SignalScrub(false); - update(); -} - -void CTimeline::OnMenuNextFrame() -{ - m_timeStepIndex = static_cast(floor(m_time.ToFloat() * static_cast(m_timeStepNum) + 0.05f)) + 1; - if (m_timeStepIndex > m_timeStepNum) - { - m_timeStepIndex = 0; - } - float normalizedTime = static_cast(m_timeStepIndex) / static_cast(m_timeStepNum); - m_time = SAnimTime(normalizedTime); - SignalScrub(false); - update(); -} - -void CTimeline::OnFilterChanged() -{ - UpdateLayout(); - update(); -} - -void CTimeline::OnVerticalScroll([[maybe_unused]] int value) -{ - update(); -} - -bool CTimeline::event(QEvent* e) -{ - switch (e->type()) - { - case QEvent::ShortcutOverride: - { - // When a shortcut is matched, Qt's event processing sends out a shortcut override event - // to allow other systems to override it. If it's not overridden, then the key events - // get processed as a shortcut, even if the widget that's the target has a keyPress event - // handler. So, we need to communicate that we've processed the shortcut override - // which will tell Qt not to process it as a shortcut and instead pass along the - // keyPressEvent. - - QKeyEvent* keyEvent = static_cast(e); - QKeySequence keySequence = keyEvent->key() | keyEvent->modifiers(); - - // special case undo/redo, because they're only handled in CTimeline::keyPressEvent() - // and not in HandleKeyEvent: - static QSet customShortcuts = { - QKeySequence(Qt::CTRL | Qt::Key_Z), - QKeySequence(Qt::CTRL | Qt::Key_Y), - QKeySequence(Qt::Key_Z | Qt::CTRL | Qt::SHIFT) - }; - - if (ProcessesKey(keySequence) || customShortcuts.contains(keySequence)) - { - e->accept(); - return true; - } - } - break; - } - - return QWidget::event(e); -} - -void CTimeline::SetTreeVisible(bool visible) -{ - m_treeVisible = visible; - m_viewState.treeWidth = visible ? DEFAULT_TREE_WIDTH : 0; - - UpdateLayout(); - update(); -} - -STrackLayout* CTimeline::GetTrackLayoutFromPos(const QPoint& pos) const -{ - if (pos.y() < RULER_HEIGHT) - { - return nullptr; - } - - STrackLayouts& tracks = m_layout->tracks; - - auto findIter = std::upper_bound(tracks.begin(), tracks.end(), pos.y(), [&](int y, const STrackLayout& track) - { - return y < track.rect.bottom(); - }); - - if (findIter != tracks.end() && pos.y() <= findIter->rect.bottom()) - { - return &(*findIter); - } - - return nullptr; -} - -void CTimeline::SetCustomTreeCornerWidget(QWidget* pWidget, uint width) -{ - SAFE_DELETE(m_cornerWidget); - - m_cornerWidget = pWidget; - m_cornerWidgetWidth = width; - - if (m_cornerWidget) - { - m_cornerWidget->setCursor(QCursor()); - } - - UpdateLayout(); - update(); -} - -void CTimeline::SetVerticalScrollbarVisible(bool bVisible) -{ - m_verticalScrollbarVisible = bVisible; - UpdateLayout(); - update(); -} - -void CTimeline::SetDrawTrackTimeMarkers(bool bDrawMarkers) -{ - m_drawMarkers = bDrawMarkers; - update(); -} - -void CTimeline::SetVisibleDistance(float distance) -{ - const float totalDuration = (m_layout->maxEndTime - m_layout->minStartTime).ToFloat(); - const float padding = (float(TIMELINE_PADDING) - 0.5f) / m_viewState.widthPixels * totalDuration; - m_viewState.visibleDistance = clamp_tpl(distance, 0.01f, totalDuration + 2.0f * padding); - - UpdateLayout(); - update(); -} diff --git a/Code/Sandbox/Plugins/EditorCommon/Timeline.h b/Code/Sandbox/Plugins/EditorCommon/Timeline.h deleted file mode 100644 index 7449841695..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/Timeline.h +++ /dev/null @@ -1,216 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once -#ifndef CRYINCLUDE_EDITORCOMMON_TIMELINE_H -#define CRYINCLUDE_EDITORCOMMON_TIMELINE_H - -#include -#include - -#include "TimelineContent.h" - -class QPainter; -class QPaintEvent; -class QLineEdit; -class QScrollBar; - -struct STimelineLayout; - -struct STimelineViewState -{ - float viewOrigin; - float visibleDistance; - float clampedViewOrigin; - int widthPixels; - QPoint scrollPixels; - int maxScrollX; - int treeWidth; - int treeLastOpenedWidth; - - STimelineViewState() - : viewOrigin(0.0f) - , clampedViewOrigin(0.0f) - , visibleDistance(1.0f) - , scrollPixels(0, 0) - , maxScrollX(0) - , treeWidth(0) - , widthPixels(1) - { - } - - QPoint LocalToLayout(const QPoint& p) const; - QPoint LayoutToLocal(const QPoint& p) const; - - int ScrollOffset(float origin) const; - int TimeToLayout(float time) const; - float LocalToTime(int x) const; - int TimeToLocal(float time) const; - float LayoutToTime(int x) const; -}; - -struct STrackLayout; - -class EDITOR_COMMON_API CTimeline - : public QWidget -{ - Q_OBJECT -public: - CTimeline(QWidget* parent); - ~CTimeline(); - - void SetContent(STimelineContent* pContent); - STimelineContent* Content() const { return m_pContent; } - - void ContentUpdated() { UpdateLayout(); update(); } - - bool IsDragged() const { return m_mouseHandler.get() != 0; } - - // make it possible to have actual time in normalized units, but different display units - void SetTimeUnitScale(float timeUnitScale, float step); - void SetTime(SAnimTime time); - void SetCycled(bool cycled); - void SetSizeToContent(bool sizeToContent); - void SetFrameRate(SAnimTime::EFrameRate frameRate) { m_frameRate = frameRate; } - void SetTimeSnapping(bool snapTime) { m_snapTime = snapTime; } - void SetKeySnapping(bool snapKeys) { m_snapKeys = snapKeys; } - void SetKeyWidth(uint width) { m_keyWidth = width; UpdateLayout(); update(); } - void SetKeyRadius(float radius) { m_keyRadius = radius; UpdateLayout(); update(); } - void SetTreeVisible(bool visible); - void SetDrawSelectionIndicators(bool visible) { m_selIndicators = visible; update(); } - void SetCustomTreeCornerWidget(QWidget* pWidget, uint width); - void SetVerticalScrollbarVisible(bool bVisible); - void SetDrawTrackTimeMarkers(bool bDrawMarkers); - void SetVisibleDistance(float distance); - - SAnimTime Time() const { return m_time; } - - bool HandleKeyEvent(int key); - bool ProcessesKey(const QKeySequence& key); - - void paintEvent(QPaintEvent* ev) override; - void mousePressEvent(QMouseEvent* ev) override; - void mouseMoveEvent(QMouseEvent* ev) override; - void mouseReleaseEvent(QMouseEvent* ev) override; - void focusOutEvent(QFocusEvent* ev) override; - void mouseDoubleClickEvent(QMouseEvent* ev) override; - - void AddKeyToTrack(STimelineTrack& subTrack, SAnimTime time); - - void keyPressEvent(QKeyEvent* ev) override; - void keyReleaseEvent(QKeyEvent* ev) override; - void resizeEvent(QResizeEvent* ev) override; - void wheelEvent(QWheelEvent* ev) override; - QSize sizeHint() const override; - -signals: - void SignalScrub(bool scrubThrough); - void SignalContentChanged(bool continuous); - void SignalSelectionChanged(bool continuous); - void SignalTrackSelectionChanged(); - void SignalPlay(); - void SignalNumberHotkey(int number); - void SignalTreeContextMenu(const QPoint& point); - - void SignalUndo(); - void SignalRedo(); - -protected slots: - void OnMenuSelectionToCursor(); - void OnMenuDuplicate(); - void OnMenuCopy(); - void OnMenuPaste(); - void OnMenuDelete(); - void OnMenuPlay(); - void OnMenuNextKey(); - void OnMenuPreviousKey(); - void OnMenuNextFrame(); - void OnMenuPreviousFrame(); - void OnFilterChanged(); - void OnVerticalScroll(int value); - -protected: - - bool event(QEvent* e) override; - -private: - struct SMouseHandler; - struct SSelectionHandler; - struct SMoveHandler; - struct SPanHandler; - struct SScrubHandler; - struct SSplitterHandler; - struct STreeMouseHandler; - - void ContentChanged(bool continuous); - void UpdateLayout(); - void UpdateCursor(QMouseEvent* ev); - void DrawMarkers(QPainter& painter, int offsetY); - SAnimTime ClampAndSnapTime(SAnimTime time, bool snapToFrames) const; - void ClampAndSetTime(SAnimTime time, bool scrubThrough); - STrackLayout* GetTrackLayoutFromPos(const QPoint& pos) const; - - // Exposed parameters - float m_timeUnitScale; - int m_timeStepNum; - int m_timeStepIndex; - SAnimTime::EFrameRate m_frameRate; - bool m_cycled : 1; - bool m_sizeToContent : 1; - bool m_snapTime : 1; - bool m_snapKeys : 1; - bool m_treeVisible : 1; - bool m_selIndicators : 1; - bool m_verticalScrollbarVisible : 1; - bool m_drawMarkers : 1; - uint m_keyWidth; - float m_keyRadius; - uint m_cornerWidgetWidth; - - // Widgets - QScrollBar* m_scrollBar; - QWidget* m_cornerWidget; - - AZ_PUSH_DISABLE_DLL_EXPORT_MEMBER_WARNING - STimelineViewState m_viewState; - STimelineContent* m_pContent; - SAnimTime m_time; - std::unique_ptr m_layout; - std::unique_ptr m_mouseHandler; - AZ_POP_DISABLE_DLL_EXPORT_MEMBER_WARNING - - // Filtering - QLineEdit* m_pFilterLineEdit; - - // Track selection - STrackLayout* m_pLastSelectedTrack; - - friend class CTimelineTracks; -}; - -class CTimelineTracks - : public QWidget -{ - Q_OBJECT -public: - CTimelineTracks(QWidget* widget) - : QWidget(widget) {} - void ConnectToTimeline(CTimeline* timeline) { m_timeline = timeline; } - -private: - CTimeline* m_timeline; -}; - - - -#endif // CRYINCLUDE_EDITORCOMMON_TIMELINE_H diff --git a/Code/Sandbox/Plugins/EditorCommon/TimelineContent.cpp b/Code/Sandbox/Plugins/EditorCommon/TimelineContent.cpp deleted file mode 100644 index 8ee8c3acf6..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/TimelineContent.cpp +++ /dev/null @@ -1,20 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -#include "TimelineContent.h" -#include "Serialization.h" - -SERIALIZATION_ENUM_BEGIN_NESTED(STimelineElement, ECaps, "Capabilities") -SERIALIZATION_ENUM_VALUE_NESTED(STimelineElement, CAP_SELECT, "Select") -SERIALIZATION_ENUM_VALUE_NESTED(STimelineElement, CAP_MOVE, "Move") -SERIALIZATION_ENUM_VALUE_NESTED(STimelineElement, CAP_DELETE, "Delete") -SERIALIZATION_ENUM_VALUE_NESTED(STimelineElement, CAP_CHANGE_DURATION, "Change Duration") -SERIALIZATION_ENUM_END() diff --git a/Code/Sandbox/Plugins/EditorCommon/TimelineContent.h b/Code/Sandbox/Plugins/EditorCommon/TimelineContent.h deleted file mode 100644 index a2d89f9c7d..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/TimelineContent.h +++ /dev/null @@ -1,154 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#ifndef CRYINCLUDE_EDITORCOMMON_TIMELINECONTENT_H -#define CRYINCLUDE_EDITORCOMMON_TIMELINECONTENT_H -#pragma once - -#include "QPropertyTree/Color.h" -#include "Serialization/Strings.h" -#include "Serialization/SmartPtr.h" -#include "Serialization.h" - -#include -#include - -using Serialization::string; - -struct STimelineElement -{ - enum EType - { - KEY, - CLIP - }; - - enum ECaps - { - CAP_SELECT = BIT(0), - CAP_DELETE = BIT(1), - - // not implemented: - CAP_MOVE = BIT(2), - CAP_CHANGE_DURATION = BIT(3) - }; - - EType type; - int caps; - SAnimTime start; - SAnimTime end; - ColorB color; - float baseWeight; - uint64 userId; - string description; - DynArray userSideLoad; - // state flags - bool selected : 1; - bool added : 1; - bool deleted : 1; - bool sideLoadChanged : 1; - - STimelineElement() - : type(KEY) - , start(0.0f) - , end(0.1f) - , color(212, 212, 212, 255) - , caps(CAP_SELECT | CAP_MOVE | CAP_CHANGE_DURATION) - , selected(false) - , added(false) - , deleted(false) - , sideLoadChanged(false) - , userId(0) - { - } - - void Serialize(IArchive& ar) - { - ar(type, "type", "^>80>"); - ar(start, "start", "^"); - if (type == CLIP) - { - ar(end, "end", "^"); - } - ar(BitFlags(caps), "caps", "Capabilities"); - ar(color, "color", "Color"); - } -}; -typedef std::vector STimelineElements; - -struct STimelineTrack; -typedef std::vector<_smart_ptr > STimelineTracks; - -struct STimelineTrack - : public _i_reference_target_t -{ - enum ECaps - { - CAP_ADD_ELEMENTS = BIT(0), - CAP_DESCRIPTION_TRACK = BIT(1), // No keys - CAP_COMPOUND_TRACK = BIT(2), // No own keys, but will show combined keys for child tracks - CAP_TOGGLE_TRACK = BIT(3), // For boolean tracks that are either on or off between keys. Used to key visibility etc. - }; - bool expanded : 1; - bool modified : 1; - bool selected : 1; - bool deleted : 1; - bool keySelectionChanged : 1; - bool toggleDefaultState : 1; // Default state for toggle tracks (on or off) - int height; - int caps; - SAnimTime startTime; - SAnimTime endTime; - string type; - string name; - DynArray userSideLoad; - STimelineElements elements; - STimelineElement defaultElement; - STimelineTracks tracks; - - STimelineTrack() - : expanded(true) - , modified(false) - , selected(false) - , deleted(false) - , keySelectionChanged(false) - , height(64) - , startTime(0.0f) - , endTime(1.0f) - , caps(CAP_ADD_ELEMENTS) - {} - - void Serialize(IArchive& ar) - { - ar(name, "name", "^"); - ar(type, "type", "^"); - ar(height, "height", "Height"); - ar(startTime, "startTime", "Start Time"); - ar(endTime, "endTime", "End Time"); - ar(elements, "elements", "Elements"); - ar(tracks, "tracks", "+Tracks"); - } -}; - -struct STimelineContent -{ - STimelineTrack track; - DynArray userSideLoad; - - void Serialize(IArchive& ar) - { - ar(track, "track", "Track"); - } -}; - -#endif // CRYINCLUDE_EDITORCOMMON_TIMELINECONTENT_H diff --git a/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.cpp b/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.cpp deleted file mode 100644 index 71acb24c3c..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.cpp +++ /dev/null @@ -1,117 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include "UnsavedChangesDialog.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -CUnsavedChangedDialog::CUnsavedChangedDialog(QWidget* parent) - : QDialog(parent) -{ - setWindowTitle("Unsaved Changes"); - setModal(true); - - auto layout = new QBoxLayout(QBoxLayout::TopToBottom); - auto label = new QLabel("The following files were modified.\n\nWould you like to save them before closing?"); - layout->addWidget(label, 0); - - m_list = new QListWidget(); - layout->addWidget(m_list, 1); - - auto buttonBox = new QDialogButtonBox(QDialogButtonBox::Yes | QDialogButtonBox::No | QDialogButtonBox::Cancel, Qt::Horizontal); - layout->addWidget(buttonBox, 0); - - connect(buttonBox, &QDialogButtonBox::clicked, this, [this, buttonBox](QAbstractButton* button) - { - done(buttonBox->buttonRole(button)); - }); - - setLayout(layout); - resize(500, 350); - - if (parent) - { - QPoint center = parent->mapToGlobal(parent->geometry().center()); - const QRect screenDimensions = QApplication::screenAt(center)->geometry(); - if (screenDimensions.contains(center)) - { - QPoint dialogPosition = center - QPoint(width() / 2, height() / 2); - if (screenDimensions.contains(dialogPosition)) - { - move(dialogPosition); - } - else - { - move(center); - } - } - else - { - move((screenDimensions.width() - width()) / 2, (screenDimensions.height() - height()) / 2); - } - } -} - -bool CUnsavedChangedDialog::Exec(DynArray* selectedFiles, const DynArray& files) -{ - m_list->clear(); - - std::vector items(files.size(), nullptr); - - for (size_t i = 0; i < files.size(); ++i) - { - auto item = new QListWidgetItem(files[i].c_str(), m_list); - item->setFlags(item->flags() | Qt::ItemIsUserCheckable); - item->setCheckState(Qt::Checked); - items[i] = item; - } - - selectedFiles->clear(); - - int result = exec(); - if (result == QDialogButtonBox::YesRole) - { - for (size_t i = 0; i < items.size(); ++i) - { - if (items[i]->checkState() == Qt::Checked) - { - selectedFiles->push_back(files[i].c_str()); - } - } - return true; - } - else if (result == QDialogButtonBox::NoRole) - { - return true; - } - else - { - return false; - } -} - -bool EDITOR_COMMON_API UnsavedChangesDialog(QWidget* parent, DynArray* selectedFiles, const DynArray& files) -{ - CUnsavedChangedDialog dialog(parent); - return dialog.Exec(selectedFiles, files); -} - -#include diff --git a/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.h b/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.h deleted file mode 100644 index 999b226845..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/UnsavedChangesDialog.h +++ /dev/null @@ -1,42 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#pragma once - -#if !defined(Q_MOC_RUN) -#include "EditorCommonAPI.h" -#include "Serialization/Strings.h" -#include "Serialization/DynArray.h" - -#include -#endif -class QListWidget; - -// Supposed to be used through -// ConfirmSaveDialog function. -class CUnsavedChangedDialog - : public QDialog -{ - Q_OBJECT -public: - CUnsavedChangedDialog(QWidget* parent); - - bool Exec(DynArray* selectedFiles, const DynArray& files); -private: - QListWidget* m_list; - int m_result; -}; - -// Returns true if window should be closed (Yes/No). False for Cancel. -// selectedFiles contains list of files that should be saved (empty in No case). -bool EDITOR_COMMON_API UnsavedChangesDialog(QWidget* parent, DynArray* selectedFiles, const DynArray& files); diff --git a/Code/Sandbox/Plugins/EditorCommon/editorcommon_files.cmake b/Code/Sandbox/Plugins/EditorCommon/editorcommon_files.cmake index 5551c07be1..a7b3860905 100644 --- a/Code/Sandbox/Plugins/EditorCommon/editorcommon_files.cmake +++ b/Code/Sandbox/Plugins/EditorCommon/editorcommon_files.cmake @@ -13,16 +13,8 @@ set(FILES EditorCommon.h EditorCommon.cpp EditorCommon.rc - EditorCommon.qrc EditorCommonAPI.h - moc.cpp - QViewportConsumer.h - TimelineContent.h EditorCommon_precompiled.h - CurveEditorControl.cpp - CurveEditorControl.h - DisplayViewportAdapter.cpp - DisplayViewportAdapter.h ActionOutput.h ActionOutput.cpp UiEditorDLLBus.h @@ -30,140 +22,16 @@ set(FILES DockTitleBarWidget.h SaveUtilities/AsyncSaveRunner.h SaveUtilities/AsyncSaveRunner.cpp - Events/EventManager.cpp - Events/EventManager.h AxisHelper.cpp DisplayContext.cpp - QPropertyTree/PropertyRowSlider.cpp - BatchFileDialog.cpp - BatchFileDialog.h DeepFilterProxyModel.cpp DeepFilterProxyModel.h - QAbstractQVariantTreeDataModel.h - QAbstractQVariantTreeDataModel.cpp - UnsavedChangesDialog.h - UnsavedChangesDialog.cpp Resource.h DrawingPrimitives/Ruler.cpp DrawingPrimitives/Ruler.h DrawingPrimitives/TimeSlider.cpp DrawingPrimitives/TimeSlider.h - Timeline.cpp - Timeline.h - CurveEditor.cpp - CurveEditor.h - CurveEditorContent.h WinWidget/WinWidget.h WinWidget/WinWidgetManager.h WinWidget/WinWidgetManager.cpp - QPropertyTree/Color.cpp - QPropertyTree/Color.h - QPropertyTree/ConstStringList.cpp - QPropertyTree/ConstStringList.h - QPropertyTree/Factory.h - QPropertyTree/MathUtils.h - QPropertyTree/PropertyDrawContext.cpp - QPropertyTree/PropertyDrawContext.h - QPropertyTree/PropertyIArchive.cpp - QPropertyTree/PropertyIArchive.h - QPropertyTree/PropertyOArchive.cpp - QPropertyTree/PropertyOArchive.h - QPropertyTree/PropertyRow.cpp - QPropertyTree/PropertyRow.h - QPropertyTree/PropertyRowActionButton.cpp - QPropertyTree/PropertyRowBool.cpp - QPropertyTree/PropertyRowBool.h - QPropertyTree/PropertyRowColor.cpp - QPropertyTree/PropertyRowColor.h - QPropertyTree/PropertyRowColorPicker.cpp - QPropertyTree/PropertyRowColorPicker.h - QPropertyTree/PropertyRowContainer.cpp - QPropertyTree/PropertyRowContainer.h - QPropertyTree/PropertyRowField.cpp - QPropertyTree/PropertyRowField.h - QPropertyTree/PropertyRowIconXPM.cpp - QPropertyTree/PropertyRowImpl.h - QPropertyTree/PropertyRowLocalFrame.cpp - QPropertyTree/PropertyRowLocalFrame.h - QPropertyTree/PropertyRowNumber.cpp - QPropertyTree/PropertyRowNumber.h - QPropertyTree/PropertyRowNumberField.cpp - QPropertyTree/PropertyRowNumberField.h - QPropertyTree/PropertyRowObject.cpp - QPropertyTree/PropertyRowObject.h - QPropertyTree/PropertyRowPointer.cpp - QPropertyTree/PropertyRowPointer.h - QPropertyTree/PropertyRowSprite.cpp - QPropertyTree/PropertyRowSprite.h - QPropertyTree/PropertyRowString.h - QPropertyTree/PropertyRowString.cpp - QPropertyTree/PropertyRowStringListValue.cpp - QPropertyTree/PropertyRowStringListValue.h - QPropertyTree/PropertyRowTagList.cpp - QPropertyTree/PropertyRowTagList.h - QPropertyTree/PropertyRowToggleButton.cpp - QPropertyTree/PropertyTreeMenuHandler.h - QPropertyTree/PropertyTreeModel.cpp - QPropertyTree/PropertyTreeModel.h - QPropertyTree/PropertyTreeOperator.cpp - QPropertyTree/PropertyTreeOperator.h - QPropertyTree/QPropertyTree.cpp - QPropertyTree/QPropertyTree.h - QPropertyTree/QPropertyTreeStyle.h - QPropertyTree/Serialization.h - QPropertyTree/Strings.h - QPropertyTree/Unicode.h - QPropertyTree/ContextList.h - QPropertyTree/file_open.xpm - QPropertyTree/file_save.xpm - QPropertyTree/SlicerEdit.cpp - QPropertyTree/SlicerEdit.h - QPropertyTree/SlicerManipulator.cpp - QPropertyTree/SlicerManipulator.h - QPropertyTree/SlicerView.cpp - QPropertyTree/SlicerView.h - QPropertyTree/SpriteBorderEditor.cpp - QPropertyTree/SpriteBorderEditor.h - QPropertyTree/SpriteBorderEditorCommon.cpp - QPropertyTree/SpriteBorderEditorCommon.h - QPropertyTree/ValidatorBlock.h - ListSelectionDialog.cpp - ListSelectionDialog.h - QViewport.cpp - QViewport.h - QViewportEvents.h - QViewportSettings.h - QPropertyTree/PropertyRowResourceFilePath.cpp - QPropertyTree/PropertyRowResourceFilePath.h - QPropertyTree/PropertyRowResourceFolderPath.cpp - QPropertyTree/PropertyRowResourceFolderPath.h - QPropertyTree/PropertyRowResourceSelector.cpp - QPropertyTree/PropertyRowResourceSelector.h - QPropertyTree/PropertyRowOutputFilePath.cpp - QPropertyTree/PropertyRowOutputFilePath.h - QPropertyTree/QPropertyDialog.cpp - QPropertyTree/QPropertyDialog.h - Serialization.cpp - Serialization.h - Serialization/BinArchive.cpp - Serialization/BinArchive.h - Serialization/JSONIArchive.cpp - Serialization/JSONIArchive.h - Serialization/JSONOArchive.cpp - Serialization/JSONOArchive.h - Serialization/MemoryReader.cpp - Serialization/MemoryReader.h - Serialization/MemoryWriter.cpp - Serialization/MemoryWriter.h - Serialization/Pointers.h - Serialization/PointersImpl.h - Serialization/Qt.cpp - Serialization/Qt.h - Serialization/QtImpl.h - Serialization/Token.h - Serialization/Decorators/ToggleButton.h - Serialization/Decorators/ToggleButtonImpl.h - Serialization/Decorators/IGizmoSink.h - Serialization/Decorators/IconXPM.h - Serialization/Decorators/INavigationProvider.h ) diff --git a/Code/Sandbox/Plugins/EditorCommon/moc.cpp b/Code/Sandbox/Plugins/EditorCommon/moc.cpp deleted file mode 100644 index ce9570b673..0000000000 --- a/Code/Sandbox/Plugins/EditorCommon/moc.cpp +++ /dev/null @@ -1,21 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "EditorCommon_precompiled.h" -#include -#include -#include - -#include -#include -#include diff --git a/Gems/AudioEngineWwise/Code/Platform/Android/AudioEngineWwise_Traits_Android.h b/Gems/AudioEngineWwise/Code/Platform/Android/AudioEngineWwise_Traits_Android.h index 336d6e78c0..b753d321da 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Android/AudioEngineWwise_Traits_Android.h +++ b/Gems/AudioEngineWwise/Code/Platform/Android/AudioEngineWwise_Traits_Android.h @@ -22,7 +22,6 @@ #endif #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE 32 << 10 /* 32 MiB */ #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE_DEFAULT_TEXT "32768 (32 MiB)" -#define AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE_DEFAULT_TEXT "0 (0 MiB)" #define AZ_TRAIT_AUDIOENGINEWWISE_STREAMER_DEVICE_MEMORY_POOL_SIZE 2 << 10 /* 2 MiB */ diff --git a/Gems/AudioEngineWwise/Code/Platform/Linux/AudioEngineWwise_Traits_Linux.h b/Gems/AudioEngineWwise/Code/Platform/Linux/AudioEngineWwise_Traits_Linux.h index 6df576637b..a7900484e3 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Linux/AudioEngineWwise_Traits_Linux.h +++ b/Gems/AudioEngineWwise/Code/Platform/Linux/AudioEngineWwise_Traits_Linux.h @@ -26,7 +26,6 @@ #endif #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE 128 << 10 /* 128 MiB */ #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE_DEFAULT_TEXT "131072 (128 MiB)" -#define AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE_DEFAULT_TEXT "0 (0 MiB)" #define AZ_TRAIT_AUDIOENGINEWWISE_STREAMER_DEVICE_MEMORY_POOL_SIZE 2 << 10 /* 2 MiB */ diff --git a/Gems/AudioEngineWwise/Code/Platform/Mac/AudioEngineWwise_Traits_Mac.h b/Gems/AudioEngineWwise/Code/Platform/Mac/AudioEngineWwise_Traits_Mac.h index 6df576637b..a7900484e3 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Mac/AudioEngineWwise_Traits_Mac.h +++ b/Gems/AudioEngineWwise/Code/Platform/Mac/AudioEngineWwise_Traits_Mac.h @@ -26,7 +26,6 @@ #endif #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE 128 << 10 /* 128 MiB */ #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE_DEFAULT_TEXT "131072 (128 MiB)" -#define AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE_DEFAULT_TEXT "0 (0 MiB)" #define AZ_TRAIT_AUDIOENGINEWWISE_STREAMER_DEVICE_MEMORY_POOL_SIZE 2 << 10 /* 2 MiB */ diff --git a/Gems/AudioEngineWwise/Code/Platform/Windows/AudioEngineWwise_Traits_Windows.h b/Gems/AudioEngineWwise/Code/Platform/Windows/AudioEngineWwise_Traits_Windows.h index c1c51482fb..b71f0b7d0d 100644 --- a/Gems/AudioEngineWwise/Code/Platform/Windows/AudioEngineWwise_Traits_Windows.h +++ b/Gems/AudioEngineWwise/Code/Platform/Windows/AudioEngineWwise_Traits_Windows.h @@ -26,7 +26,6 @@ #endif #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE 128 << 10 /* 128 MiB */ #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE_DEFAULT_TEXT "131072 (128 MiB)" -#define AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE_DEFAULT_TEXT "0 (0 MiB)" #define AZ_TRAIT_AUDIOENGINEWWISE_STREAMER_DEVICE_MEMORY_POOL_SIZE 2 << 10 /* 2 MiB */ diff --git a/Gems/AudioEngineWwise/Code/Platform/iOS/AudioEngineWwise_Traits_iOS.h b/Gems/AudioEngineWwise/Code/Platform/iOS/AudioEngineWwise_Traits_iOS.h index 336d6e78c0..b753d321da 100644 --- a/Gems/AudioEngineWwise/Code/Platform/iOS/AudioEngineWwise_Traits_iOS.h +++ b/Gems/AudioEngineWwise/Code/Platform/iOS/AudioEngineWwise_Traits_iOS.h @@ -22,7 +22,6 @@ #endif #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE 32 << 10 /* 32 MiB */ #define AZ_TRAIT_AUDIOENGINEWWISE_PRIMARY_POOL_SIZE_DEFAULT_TEXT "32768 (32 MiB)" -#define AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE 0 #define AZ_TRAIT_AUDIOENGINEWWISE_SECONDARY_POOL_SIZE_DEFAULT_TEXT "0 (0 MiB)" #define AZ_TRAIT_AUDIOENGINEWWISE_STREAMER_DEVICE_MEMORY_POOL_SIZE 2 << 10 /* 2 MiB */ diff --git a/Gems/AudioEngineWwise/Code/Source/AudioEngineWwiseGemSystemComponent.cpp b/Gems/AudioEngineWwise/Code/Source/AudioEngineWwiseGemSystemComponent.cpp index faaf4d5c75..c5dae7de75 100644 --- a/Gems/AudioEngineWwise/Code/Source/AudioEngineWwiseGemSystemComponent.cpp +++ b/Gems/AudioEngineWwise/Code/Source/AudioEngineWwiseGemSystemComponent.cpp @@ -36,10 +36,6 @@ namespace Audio { CAudioLogger g_audioImplLogger_wwise; -#if AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - TMemoryPoolReferenced g_audioImplMemoryPoolSecondary_wwise; -#endif // AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - namespace Platform { void* InitializeSecondaryMemoryPool(size_t& secondarySize); @@ -154,13 +150,6 @@ namespace AudioEngineWwiseGem m_engineWwise = AZStd::make_unique(assetPlatform.c_str()); if (m_engineWwise) { - #if AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - size_t secondarySize = 0; - void* secondaryMemoryPtr = Audio::Platform::InitializeSecondaryMemoryPool(secondarySize); - - Audio::g_audioImplMemoryPoolSecondary_wwise.InitMem(secondarySize, static_cast(secondaryMemoryPtr)); - #endif // AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - Audio::g_audioImplLogger_wwise.Log(Audio::eALT_ALWAYS, "AudioEngineWwise created!"); Audio::SAudioRequest oAudioRequestData; diff --git a/Gems/AudioEngineWwise/Code/Source/Editor/AudioSystemEditor_wwise.h b/Gems/AudioEngineWwise/Code/Source/Editor/AudioSystemEditor_wwise.h index e35b225fc6..ee7b54217d 100644 --- a/Gems/AudioEngineWwise/Code/Source/Editor/AudioSystemEditor_wwise.h +++ b/Gems/AudioEngineWwise/Code/Source/Editor/AudioSystemEditor_wwise.h @@ -35,12 +35,6 @@ namespace AudioControls bool HasProperties() override { return true; } - void Serialize(Serialization::IArchive& ar) override - { - ar(m_mult, "mult", "Multiply"); - ar(m_shift, "shift", "Shift"); - } - float m_mult; float m_shift; }; @@ -61,11 +55,6 @@ namespace AudioControls bool HasProperties() override { return true; } - void Serialize(Serialization::IArchive& ar) override - { - ar(m_value, "value", "Value"); - } - float m_value; }; diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp index 89afb0bf33..2e11c7a810 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp +++ b/Gems/AudioEngineWwise/Code/Source/Engine/AudioSystemImpl_wwise.cpp @@ -1757,16 +1757,9 @@ namespace Audio memoryInfo.nPrimaryPoolSize = AZ::AllocatorInstance::Get().Capacity(); memoryInfo.nPrimaryPoolUsedSize = memoryInfo.nPrimaryPoolSize - AZ::AllocatorInstance::Get().GetUnAllocatedMemory(); memoryInfo.nPrimaryPoolAllocations = 0; - - #if AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - memoryInfo.nSecondaryPoolSize = g_audioImplMemoryPoolSecondary_wwise.MemSize(); - memoryInfo.nSecondaryPoolUsedSize = memoryInfo.nSecondaryPoolSize - g_audioImplMemoryPoolSecondary_wwise.MemFree(); - memoryInfo.nSecondaryPoolAllocations = g_audioImplMemoryPoolSecondary_wwise.FragmentCount(); - #else memoryInfo.nSecondaryPoolSize = 0; memoryInfo.nSecondaryPoolUsedSize = 0; memoryInfo.nSecondaryPoolAllocations = 0; - #endif // AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL } /////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h b/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h index 7f67196dc6..2e806a80e9 100644 --- a/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h +++ b/Gems/AudioEngineWwise/Code/Source/Engine/Common_wwise.h @@ -19,20 +19,6 @@ #include #include - -#if AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - #include - #include - - using TMemoryPoolReferenced = NCryPoolAlloc::CThreadSafe, NCryPoolAlloc::CListItemReference>>; - - namespace Audio - { - extern TMemoryPoolReferenced g_audioImplMemoryPoolSecondary_wwise; - } -#endif // AZ_TRAIT_AUDIOENGINEWWISE_PROVIDE_IMPL_SECONDARY_POOL - - #define WWISE_IMPL_VERSION_STRING "Wwise " AK_WWISESDK_VERSIONNAME #define ASSERT_WWISE_OK(x) (AKASSERT((x) == AK_Success)) diff --git a/Gems/AudioSystem/Code/Include/Editor/IAudioConnection.h b/Gems/AudioSystem/Code/Include/Editor/IAudioConnection.h index 5191f211b8..084b14bd18 100644 --- a/Gems/AudioSystem/Code/Include/Editor/IAudioConnection.h +++ b/Gems/AudioSystem/Code/Include/Editor/IAudioConnection.h @@ -14,8 +14,6 @@ #pragma once #include -#include -#include namespace AudioControls { @@ -40,10 +38,6 @@ namespace AudioControls return false; } - virtual void Serialize([[maybe_unused]] Serialization::IArchive& ar) - { - } - private: CID m_id; }; diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioControl.h b/Gems/AudioSystem/Code/Source/Editor/AudioControl.h index 878cf269c6..a974c5f556 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioControl.h +++ b/Gems/AudioSystem/Code/Source/Editor/AudioControl.h @@ -19,6 +19,7 @@ #include #include +#include #include namespace AudioControls diff --git a/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp b/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp index 6edf80e3fe..101454db58 100644 --- a/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/AudioResourceSelectors.cpp @@ -13,7 +13,6 @@ #include #include -#include #include #include #include diff --git a/Gems/AudioSystem/Code/Source/Editor/ConnectionsWidget.ui b/Gems/AudioSystem/Code/Source/Editor/ConnectionsWidget.ui index e2043df679..120df694bc 100644 --- a/Gems/AudioSystem/Code/Source/Editor/ConnectionsWidget.ui +++ b/Gems/AudioSystem/Code/Source/Editor/ConnectionsWidget.ui @@ -120,28 +120,6 @@ 6 - - - - - 0 - 0 - - - - - 0 - 0 - - - - - 16777215 - 16777215 - - - - @@ -153,12 +131,6 @@ QListWidget
QConnectionListWidget.h
- - QPropertyTree - QWidget -
QPropertyTree/QPropertyTree.h
- 1 -
diff --git a/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp b/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp index 27e810202d..ab025d5b2d 100644 --- a/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp +++ b/Gems/AudioSystem/Code/Source/Editor/QConnectionsWidget.cpp @@ -26,8 +26,6 @@ #include #include #include -#include -#include namespace AudioControls { @@ -40,10 +38,6 @@ namespace AudioControls { setupUi(this); - m_connectionProperties->setSizeToContent(true); - m_connectionPropertiesFrame->setHidden(true); - connect(m_connectionProperties, SIGNAL(signalChanged()), this, SLOT(CurrentConnectionModified())); - m_connectionList->viewport()->installEventFilter(this); m_connectionList->installEventFilter(this); @@ -131,17 +125,6 @@ namespace AudioControls } } } - - if (connection && connection->HasProperties()) - { - m_connectionProperties->attach(Serialization::SStruct(*connection.get())); - m_connectionPropertiesFrame->setHidden(false); - } - else - { - m_connectionProperties->detach(); - m_connectionPropertiesFrame->setHidden(true); - } } //-------------------------------------------------------------------------------------------// diff --git a/Gems/GameEffectSystem/preview.png b/Gems/GameEffectSystem/preview.png deleted file mode 100644 index b3a5a5880e..0000000000 --- a/Gems/GameEffectSystem/preview.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:fed875535032ff47526dd94870fc171028f3126a5c1d98f773f7da8083d495e4 -size 40620 diff --git a/Gems/LyShine/Code/Editor/ViewportWidget.cpp b/Gems/LyShine/Code/Editor/ViewportWidget.cpp index 753e207288..89c5a0bb50 100644 --- a/Gems/LyShine/Code/Editor/ViewportWidget.cpp +++ b/Gems/LyShine/Code/Editor/ViewportWidget.cpp @@ -18,7 +18,6 @@ #include #include #include -#include #include #include diff --git a/Gems/Maestro/Code/Source/Cinematics/CryMovie.cpp b/Gems/Maestro/Code/Source/Cinematics/CryMovie.cpp deleted file mode 100644 index cec0fd5f01..0000000000 --- a/Gems/Maestro/Code/Source/Cinematics/CryMovie.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - -#include "Maestro_precompiled.h" -#include "CryMovie.h" -#include "Movie.h" -#include - -#include -#include -#include - -#undef GetClassName - -////////////////////////////////////////////////////////////////////////// -struct CSystemEventListner_Movie - : public ISystemEventListener -{ -public: - virtual void OnSystemEvent(ESystemEvent event, UINT_PTR wparam, UINT_PTR lparam) - { - switch (event) - { - case ESYSTEM_EVENT_LEVEL_POST_UNLOAD: - { - STLALLOCATOR_CLEANUP; - CLightAnimWrapper::ReconstructCache(); - break; - } - } - } -}; - -static CSystemEventListner_Movie g_system_event_listener_movie; - -////////////////////////////////////////////////////////////////////////// -class CEngineModule_CryMovie - : public IEngineModule -{ - CRYINTERFACE_SIMPLE(IEngineModule) - CRYGENERATE_SINGLETONCLASS(CEngineModule_CryMovie, "EngineModule_CryMovie", 0xdce26beebdc6400f, 0xa0e9b42839f2dd5b) - - ////////////////////////////////////////////////////////////////////////// - virtual const char* GetName() const { - return "CryMovie"; - }; - virtual const char* GetCategory() const { return "CryEngine"; }; - - ////////////////////////////////////////////////////////////////////////// - virtual bool Initialize(SSystemGlobalEnvironment& env, const SSystemInitParams& initParams) - { - ISystem* pSystem = env.pSystem; - - pSystem->GetISystemEventDispatcher()->RegisterListener(&g_system_event_listener_movie); - - env.pMovieSystem = aznew CMovieSystem(pSystem); - return true; - } -}; - -CRYREGISTER_SINGLETON_CLASS(CEngineModule_CryMovie) - -CEngineModule_CryMovie::CEngineModule_CryMovie() -{ -}; - -CEngineModule_CryMovie::~CEngineModule_CryMovie() -{ -}; diff --git a/Gems/Maestro/Code/Source/Cinematics/CryMovie.def b/Gems/Maestro/Code/Source/Cinematics/CryMovie.def deleted file mode 100644 index fc5c3c91cd..0000000000 --- a/Gems/Maestro/Code/Source/Cinematics/CryMovie.def +++ /dev/null @@ -1,3 +0,0 @@ -EXPORTS - ModuleInitISystem @2 - CryModuleGetMemoryInfo @8 diff --git a/Gems/Maestro/Code/Source/Cinematics/CryMovie.h b/Gems/Maestro/Code/Source/Cinematics/CryMovie.h deleted file mode 100644 index 6936f4e1fb..0000000000 --- a/Gems/Maestro/Code/Source/Cinematics/CryMovie.h +++ /dev/null @@ -1,40 +0,0 @@ -/* -* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -* its licensors. -* -* For complete copyright and license terms please see the LICENSE at the root of this -* distribution (the "License"). All use of this software is governed by the License, -* or, if provided, by the license below or the license accompanying this file. Do not -* remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* -*/ -// Original file Copyright Crytek GMBH or its affiliates, used under license. - - -// The following ifdef block is the standard way of creating macros which make exporting -// from a DLL simpler. All files within this DLL are compiled with the CRYMOVIE_EXPORTS -// symbol defined on the command line. this symbol should not be defined on any project -// that uses this DLL. This way any other project whose source files include this file see -// CRYMOVIE_API functions as being imported from a DLL, wheras this DLL sees symbols -// defined with this macro as being exported. - -#ifndef CRYINCLUDE_CRYMOVIE_CRYMOVIE_H -#define CRYINCLUDE_CRYMOVIE_CRYMOVIE_H -#pragma once - -#ifdef CRYMOVIE_EXPORTS - #define CRYMOVIE_API DLL_EXPORT -#else - #define CRYMOVIE_API DLL_IMPORT -#endif - -struct ISystem; -struct IMovieSystem; - -extern "C" -{ -CRYMOVIE_API IMovieSystem* CreateMovieSystem(ISystem* pSystem); -CRYMOVIE_API void DeleteMovieSystem(IMovieSystem* pMM); -} -#endif // CRYINCLUDE_CRYMOVIE_CRYMOVIE_H diff --git a/Gems/Maestro/Code/Source/Cinematics/CryMovie.rc b/Gems/Maestro/Code/Source/Cinematics/CryMovie.rc deleted file mode 100644 index 5730d0a537..0000000000 --- a/Gems/Maestro/Code/Source/Cinematics/CryMovie.rc +++ /dev/null @@ -1,111 +0,0 @@ -// Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "winres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - -///////////////////////////////////////////////////////////////////////////// -// Russian resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_RUS) -#ifdef _WIN32 -LANGUAGE LANG_RUSSIAN, SUBLANG_DEFAULT -#pragma code_page(1251) -#endif //_WIN32 - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE -BEGIN - "#include ""winres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE -BEGIN - "\r\n" - "\0" -END - -#endif // APSTUDIO_INVOKED - -#endif // Russian resources -///////////////////////////////////////////////////////////////////////////// - - -///////////////////////////////////////////////////////////////////////////// -// German (Germany) resources - -#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_DEU) -#ifdef _WIN32 -LANGUAGE LANG_GERMAN, SUBLANG_GERMAN -#pragma code_page(1252) -#endif //_WIN32 - -///////////////////////////////////////////////////////////////////////////// -// -// Version -// - -VS_VERSION_INFO VERSIONINFO - FILEVERSION 1,0,0,1 - PRODUCTVERSION 1,0,0,1 - FILEFLAGSMASK 0x17L -#ifdef _DEBUG - FILEFLAGS 0x1L -#else - FILEFLAGS 0x0L -#endif - FILEOS 0x4L - FILETYPE 0x2L - FILESUBTYPE 0x0L -BEGIN - BLOCK "StringFileInfo" - BEGIN - BLOCK "000904b0" - BEGIN - VALUE "CompanyName", "Amazon.com, Inc." - VALUE "FileVersion", "1, 0, 0, 1" - VALUE "LegalCopyright", "Portions of this file Copyright (c) Amazon.com, Inc. or its affiliates. All Rights Reserved. Original file Copyright (c) Crytek GMBH. Used under license by Amazon.com, Inc. and its affiliates." - VALUE "ProductName", "Lumberyard" - VALUE "ProductVersion", "1, 0, 0, 1" - END - END - BLOCK "VarFileInfo" - BEGIN - VALUE "Translation", 0x9, 1200 - END -END - -#endif // German (Germany) resources -///////////////////////////////////////////////////////////////////////////// - - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/Gems/SVOGI/preview.png b/Gems/SVOGI/preview.png deleted file mode 100644 index 2f1ed47754..0000000000 --- a/Gems/SVOGI/preview.png +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:6d6204c6730e5675791765ca194e9b1cbec282208e280507de830afc2805e5fa -size 41127 diff --git a/cmake/TestImpactFramework/ConsoleFrontendConfig.in b/cmake/TestImpactFramework/ConsoleFrontendConfig.in index 5f3908671e..2371d7fb7f 100644 --- a/cmake/TestImpactFramework/ConsoleFrontendConfig.in +++ b/cmake/TestImpactFramework/ConsoleFrontendConfig.in @@ -50,7 +50,6 @@ include_filter = [ { target = "LmbrCentral.Editor.Tests", policy = "test_interleaved" }, { target = "EditorLib.Tests", policy = "test_interleaved" }, { target = "PhysX.Tests", policy = "test_interleaved" }, -{ target = "ImageProcessing.Tests", policy = "test_interleaved" }, { target = "Atom_RPI.Tests", policy = "test_interleaved" }, { target = "Atom_RHI.Tests", policy = "test_interleaved" }, { target = "AzManipulatorFramework.Tests", policy = "test_interleaved" }, diff --git a/scripts/build/package/Platform/Windows/package_filelists/atom.json b/scripts/build/package/Platform/Windows/package_filelists/atom.json index 885eff8504..f084173cb2 100644 --- a/scripts/build/package/Platform/Windows/package_filelists/atom.json +++ b/scripts/build/package/Platform/Windows/package_filelists/atom.json @@ -93,7 +93,6 @@ "GraphCanvas": "#include", "GraphModel": "#include", "HttpRequestor": "#include", - "ImageProcessing": "#include", "ImGui": "#include", "InAppPurchases": "#include", "LandscapeCanvas": "#include", diff --git a/scripts/commit_validation/commit_validation/pal_allowedlist.txt b/scripts/commit_validation/commit_validation/pal_allowedlist.txt index 278262d59c..e3bf4be52e 100644 --- a/scripts/commit_validation/commit_validation/pal_allowedlist.txt +++ b/scripts/commit_validation/commit_validation/pal_allowedlist.txt @@ -59,7 +59,6 @@ */Gems/EMotionFX/Code/EMotionFX/Tools/EMotionStudio/Plugins/StandardPlugins/Source/StandardPluginsConfig.h */Gems/EMotionFX/Code/MCore/Source/Config.h */Gems/GameStateSamples/Code/Include/GameStateSamples/GameStateLocalUserLobby.inl -*/Gems/ImageProcessing/Code/Tests/AtlasBuilderTest.cpp */Gems/PhysX/Code/Source/System/PhysXSystem.cpp */Gems/SaveData/Code/Tests/SaveDataTest.cpp */Gems/WhiteBox/Code/Source/Rendering/Legacy/WhiteBoxLegacyRenderMesh.cpp