From a51f3cffd8a398c93fa8e961c268644141378d9b Mon Sep 17 00:00:00 2001 From: HuYingzhuo Date: Tue, 30 Apr 2019 16:42:59 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E5=AE=8C=E6=95=B4=E7=9A=84?= =?UTF-8?q?=E5=B9=B3=E5=8F=B0=E5=92=8C=E5=BA=95=E5=B1=82=E6=94=AF=E6=8C=81?= =?UTF-8?q?=EF=BC=8C=E5=88=A0=E9=99=A4=E6=97=A7=E7=9A=84OpenGL=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CMakeLists.txt | 24 +- example/CMakeLists.txt | 9 +- example/DirectGLRender/CMakeLists.txt | 3 - example/DirectGLRender/main.cpp | 174 ----- example/DirectGLTexture/CMakeLists.txt | 4 - example/DirectGLTexture/TGATexture.cpp | 140 ---- example/DirectGLTexture/main.cpp | 192 ----- example/EnumRenderDevice/CMakeLists.txt | 3 - example/EnumRenderDevice/main.cpp | 71 -- example/NullWindow/CMakeLists.txt | 3 - example/NullWindow/main.cpp | 50 -- example/OutputGLInfo/CMakeLists.txt | 5 - example/OutputGLInfo/main.cpp | 110 --- example/TextureSampler/CMakeLists.txt | 4 - example/TextureSampler/TGATexture.cpp | 153 ---- example/TextureSampler/main.cpp | 200 ----- example/Vulkan/AssetsManage.cpp | 24 - example/Vulkan/AssetsManage.h | 6 - example/Vulkan/CMakeLists.txt | 71 +- example/Vulkan/Shader.cpp | 4 - example/Vulkan/Shader.h | 7 - example/Vulkan/VulkanAppFramework.h | 93 +++ example/Vulkan/main.cpp | 95 +-- inc/hgl/Logger.h | 133 ++++ inc/hgl/Time.h | 23 + inc/hgl/endian/Endian.h | 2 +- inc/hgl/filesystem/EnumFile.h | 75 ++ inc/hgl/filesystem/EnumVolume.h | 99 +++ inc/hgl/filesystem/FileSystem.h | 208 +++++ inc/hgl/graph/BlendMode.h | 21 - inc/hgl/graph/BufferData.h | 136 ---- inc/hgl/graph/BufferObject.h | 164 ---- inc/hgl/graph/Material.h | 105 --- inc/hgl/graph/PixelCompoment.h | 43 -- inc/hgl/graph/RenderDevice.h | 136 ---- inc/hgl/graph/RenderDriver.h | 14 - inc/hgl/graph/RenderPass.h | 20 - inc/hgl/graph/RenderState.h | 181 ----- inc/hgl/graph/RenderWindow.h | 51 -- inc/hgl/graph/Renderable.h | 40 - inc/hgl/graph/Shader.h | 198 ----- inc/hgl/graph/Texture.h | 53 -- inc/hgl/graph/Texture1D.h | 68 -- inc/hgl/graph/Texture2D.h | 61 -- inc/hgl/graph/TextureData.h | 184 ----- inc/hgl/graph/TextureFormat.h | 146 ---- inc/hgl/graph/TextureSourceFormat.h | 140 ---- inc/hgl/graph/VertexArray.h | 53 -- {example/Vulkan => inc/hgl/graph/vulkan}/VK.h | 0 .../hgl/graph/vulkan}/VKBuffer.h | 0 .../hgl/graph/vulkan}/VKBufferData.h | 0 .../hgl/graph/vulkan}/VKCommandBuffer.h | 0 .../hgl/graph/vulkan}/VKDescriptorSets.h | 0 .../hgl/graph/vulkan}/VKDevice.h | 8 +- .../hgl/graph/vulkan}/VKDeviceAttribute.h | 0 .../Vulkan => inc/hgl/graph/vulkan}/VKFence.h | 0 .../hgl/graph/vulkan}/VKFormat.h | 0 .../hgl/graph/vulkan}/VKFramebuffer.h | 0 .../hgl/graph/vulkan}/VKImageView.h | 0 .../hgl/graph/vulkan}/VKInstance.h | 4 +- .../hgl/graph/vulkan}/VKMaterial.h | 0 .../hgl/graph/vulkan}/VKPhysicalDevice.h | 0 .../hgl/graph/vulkan}/VKPipeline.h | 0 .../hgl/graph/vulkan}/VKPrimivate.h | 0 .../hgl/graph/vulkan}/VKRenderPass.h | 0 .../hgl/graph/vulkan}/VKRenderable.h | 0 .../hgl/graph/vulkan}/VKSemaphore.h | 0 .../hgl/graph/vulkan}/VKShaderModule.h | 0 .../hgl/graph/vulkan}/VKShaderModuleManage.h | 4 +- .../hgl/graph/vulkan}/VKShaderParse.h | 0 .../graph/vulkan}/VKSurfaceExtensionName.h | 0 .../graph/vulkan}/VKVertexAttributeBinding.h | 0 inc/hgl/io/DataInputStream.h | 231 ++++++ inc/hgl/io/DataOutputStream.h | 226 ++++++ inc/hgl/io/EndianDataInputStream.h | 100 +++ inc/hgl/io/EndianDataOutputStream.h | 103 +++ inc/hgl/io/FileAccess.h | 83 ++ inc/hgl/io/FileInputStream.h | 78 ++ inc/hgl/io/FileOutputStream.h | 93 +++ inc/hgl/io/IOType.h | 34 + inc/hgl/io/InputStream.h | 39 + inc/hgl/io/JavaInputStream.h | 71 ++ inc/hgl/io/JavaOutputStream.h | 62 ++ inc/hgl/io/MemoryInputStream.h | 163 ++++ inc/hgl/io/MemoryOutputStream.h | 236 ++++++ inc/hgl/io/OutputStream.h | 36 + inc/hgl/io/RandomAccessFile.h | 47 ++ inc/hgl/io/SeekAccess.h | 36 + inc/hgl/io/TextOutputStream.h | 176 +++++ inc/hgl/platform/ExternalModule.h | 36 + inc/hgl/platform/FuncLoad.h | 31 + inc/hgl/platform/SystemInfo.h | 69 ++ {example/Vulkan => inc/hgl/platform}/Window.h | 0 inc/hgl/platform/compiler/.directory | 5 - inc/hgl/platform/os/.directory | 5 - inc/hgl/proc/Fifo.h | 29 + inc/hgl/proc/FifoInputStream.h | 35 + inc/hgl/proc/Pipe.h | 24 + inc/hgl/proc/Proc.h | 41 + inc/hgl/proc/ProcMutex.h | 37 + inc/hgl/thread/CondVar.h | 2 +- inc/hgl/thread/RWLock.h | 2 +- inc/hgl/thread/Semaphore.h | 2 +- inc/hgl/thread/Thread.h | 2 +- inc/hgl/type/DateTime.h | 178 +++++ inc/hgl/type/StringList.h | 712 ++++++++++++++++++ {example/Vulkan => res/shader}/FlatColor.frag | 0 res/shader/FlatColor.frag.spv | Bin 0 -> 536 bytes res/shader/FlatColor.material | 32 + {example/Vulkan => res/shader}/FlatColor.vert | 0 res/shader/FlatColor.vert.spv | Bin 0 -> 1364 bytes .../Vulkan => res/shader}/shader_compile.bat | 0 src/Base/CMakeLists.txt | 56 +- src/Base/{ => DataType}/Color.cpp | 456 +++++------ src/Base/{ => DataType}/Color3f.cpp | 0 src/Base/{ => DataType}/Color4f.cpp | 0 src/Base/DataType/StringList.cpp | 182 +++++ src/Base/FileSystem/EnumFile.cpp | 42 ++ src/Base/FileSystem/FileSystem.cpp | 315 ++++++++ src/Base/IO/DataInputStream.cpp | 248 ++++++ src/Base/IO/DataOutputStream.cpp | 185 +++++ src/Base/IO/FileAccess.cpp | 174 +++++ src/Base/IO/FileInputStream.cpp | 65 ++ src/Base/IO/FileOutputStream.cpp | 60 ++ src/Base/IO/IOType.cpp | 37 + src/Base/IO/RandomAccessFile.cpp | 60 ++ src/Base/IO/TextOutputStream.cpp | 47 ++ src/Base/{ => Other}/CodePage.cpp | 534 ++++++------- src/Base/Other/DateTime.cpp | 348 +++++++++ src/Base/Other/ExpendString.cpp | 120 +++ src/Base/Other/ThreadFunc.cpp | 44 ++ src/Base/Other/TimeCount.cpp | 57 ++ src/Base/Other/TimeVal.cpp | 14 + src/Base/PlugIn/ExternalModule.cpp | 93 +++ src/Base/SystemInfo.cpp | 136 ++++ src/CMakeLists.txt | 1 - src/Platform/Android/AndroidMain.cpp | 344 +++++++++ src/Platform/Android/JNISupport.cpp | 25 + src/Platform/Android/LogConsole.cpp | 146 ++++ .../Android/NativeActivitySupport.cpp | 15 + src/Platform/Android/ProgramPath.cpp | 75 ++ src/Platform/Apple/ProgramPath.mm | 42 ++ src/Platform/Apple/Semaphore.cpp | 78 ++ src/Platform/CMakeLists.txt | 124 ++- src/Platform/UNIX/CondVar.cpp | 47 ++ src/Platform/UNIX/DateTime.cpp | 125 +++ src/Platform/UNIX/EnumFile.cpp | 141 ++++ src/Platform/UNIX/ExternalModule.cpp | 43 ++ src/Platform/UNIX/Fifo.cpp | 24 + src/Platform/UNIX/File.cpp | 220 ++++++ src/Platform/UNIX/FileAccess.cpp | 69 ++ src/Platform/UNIX/Pipe.cpp | 13 + src/Platform/UNIX/ProcMutex.cpp | 62 ++ src/Platform/UNIX/Process.cpp | 85 +++ src/Platform/UNIX/ProgramPath.cpp | 78 ++ src/Platform/UNIX/RWLock.cpp | 51 ++ src/Platform/UNIX/Semaphore.cpp | 87 +++ src/Platform/UNIX/SystemInfo.cpp | 121 +++ src/Platform/UNIX/Thread.cpp | 97 +++ src/Platform/UNIX/ThreadMutex.cpp | 67 ++ src/Platform/UNIX/Time.cpp | 102 +++ .../Platform/UNIX}/XCBWindow.cpp | 0 src/Platform/Win/Clipboard.cpp | 43 ++ src/Platform/Win/CondVar.cpp | 38 + src/Platform/Win/DateTime.cpp | 154 ++++ src/Platform/Win/Desktop.cpp | 141 ++++ src/Platform/Win/EnumFile.cpp | 131 ++++ src/Platform/Win/EnumVolume.cpp | 89 +++ src/Platform/Win/ExternalModule.cpp | 54 ++ src/Platform/Win/Fifo.cpp | 0 src/Platform/Win/File.cpp | 217 ++++++ src/Platform/Win/FileAccess.cpp | 68 ++ src/Platform/Win/KeyConvert.cpp | 171 +++++ src/Platform/Win/LogConsole.cpp | 66 ++ src/Platform/Win/LogDialog.cpp | 53 ++ src/Platform/Win/Pipe.cpp | 16 + src/Platform/Win/ProcMutex.cpp | 65 ++ src/Platform/Win/ProgramPath.cpp | 49 ++ src/Platform/Win/RWLock.cpp | 25 + src/Platform/Win/Semaphore.cpp | 54 ++ src/Platform/Win/SystemInfo.cpp | 99 +++ src/Platform/Win/Thread.cpp | 63 ++ src/Platform/Win/ThreadMutex.cpp | 55 ++ src/Platform/Win/Time.cpp | 90 +++ .../Vulkan => src/Platform/Win}/WinWindow.cpp | 4 +- src/RenderDevice/CMakeLists.txt | 3 +- src/RenderDevice/GLFW/RenderDeviceGLFW.cpp | 248 ------ src/RenderDevice/GLFW/RenderWindowGLFW.cpp | 65 -- src/RenderDevice/Vulkan/CMakeLists.txt | 21 + .../RenderDevice}/Vulkan/VKBuffer.cpp | 2 +- .../RenderDevice}/Vulkan/VKCommandBuffer.cpp | 16 +- .../RenderDevice}/Vulkan/VKDescriptorSets.cpp | 4 +- .../RenderDevice}/Vulkan/VKDevice.cpp | 20 +- .../Vulkan/VKDeviceAttribute.cpp | 6 +- .../RenderDevice}/Vulkan/VKDeviceBuffer.cpp | 4 +- .../RenderDevice}/Vulkan/VKDeviceCreater.cpp | 8 +- .../RenderDevice}/Vulkan/VKFence.cpp | 2 +- .../RenderDevice}/Vulkan/VKFormat.cpp | 2 +- .../RenderDevice}/Vulkan/VKFramebuffer.cpp | 8 +- .../RenderDevice}/Vulkan/VKInstance.cpp | 6 +- .../RenderDevice}/Vulkan/VKMaterial.cpp | 14 +- .../RenderDevice}/Vulkan/VKPhysicalDevice.cpp | 2 +- .../RenderDevice}/Vulkan/VKPipeline.cpp | 8 +- .../RenderDevice}/Vulkan/VKRenderPass.cpp | 2 +- .../RenderDevice}/Vulkan/VKRenderable.cpp | 6 +- .../RenderDevice}/Vulkan/VKSemaphore.cpp | 2 +- .../RenderDevice}/Vulkan/VKShaderModule.cpp | 6 +- .../Vulkan/VKShaderModuleManage.cpp | 17 +- .../Vulkan/VKVertexAttributeBinding.cpp | 4 +- .../RenderDevice}/Vulkan/VkImageView.cpp | 2 +- src/RenderDriver/BufferData.cpp | 85 --- src/RenderDriver/BufferObject.cpp | 183 ----- src/RenderDriver/CMakeLists.txt | 22 - src/RenderDriver/GLCore/CMakeLists.txt | 1 - .../GLCore/RenderDriverGLCore.cpp | 24 - src/RenderDriver/GLES/CMakeLists.txt | 1 - src/RenderDriver/GLSL.cpp | 397 ---------- src/RenderDriver/OpenGLDebug.cpp | 134 ---- src/RenderDriver/OpenGLExt.cpp | 17 - src/RenderDriver/RenderState.cpp | 46 -- src/RenderDriver/Renderable.cpp | 49 -- src/RenderDriver/Shader.cpp | 265 ------- src/RenderDriver/Texture1D.cpp | 103 --- src/RenderDriver/Texture1DDSA.cpp | 98 --- src/RenderDriver/Texture2D.cpp | 126 ---- src/RenderDriver/Texture2DDSA.cpp | 98 --- src/RenderDriver/TextureFormat.cpp | 137 ---- src/RenderDriver/VertexArray.cpp | 92 --- src/RenderDriver/VertexBufferObject.cpp | 47 -- 229 files changed, 10583 insertions(+), 5991 deletions(-) delete mode 100644 example/DirectGLRender/CMakeLists.txt delete mode 100644 example/DirectGLRender/main.cpp delete mode 100644 example/DirectGLTexture/CMakeLists.txt delete mode 100644 example/DirectGLTexture/TGATexture.cpp delete mode 100644 example/DirectGLTexture/main.cpp delete mode 100644 example/EnumRenderDevice/CMakeLists.txt delete mode 100644 example/EnumRenderDevice/main.cpp delete mode 100644 example/NullWindow/CMakeLists.txt delete mode 100644 example/NullWindow/main.cpp delete mode 100644 example/OutputGLInfo/CMakeLists.txt delete mode 100644 example/OutputGLInfo/main.cpp delete mode 100644 example/TextureSampler/CMakeLists.txt delete mode 100644 example/TextureSampler/TGATexture.cpp delete mode 100644 example/TextureSampler/main.cpp delete mode 100644 example/Vulkan/AssetsManage.cpp delete mode 100644 example/Vulkan/AssetsManage.h delete mode 100644 example/Vulkan/Shader.cpp delete mode 100644 example/Vulkan/Shader.h create mode 100644 example/Vulkan/VulkanAppFramework.h create mode 100644 inc/hgl/Logger.h create mode 100644 inc/hgl/Time.h create mode 100644 inc/hgl/filesystem/EnumFile.h create mode 100644 inc/hgl/filesystem/EnumVolume.h create mode 100644 inc/hgl/filesystem/FileSystem.h delete mode 100644 inc/hgl/graph/BlendMode.h delete mode 100644 inc/hgl/graph/BufferData.h delete mode 100644 inc/hgl/graph/BufferObject.h delete mode 100644 inc/hgl/graph/Material.h delete mode 100644 inc/hgl/graph/PixelCompoment.h delete mode 100644 inc/hgl/graph/RenderDevice.h delete mode 100644 inc/hgl/graph/RenderDriver.h delete mode 100644 inc/hgl/graph/RenderPass.h delete mode 100644 inc/hgl/graph/RenderState.h delete mode 100644 inc/hgl/graph/RenderWindow.h delete mode 100644 inc/hgl/graph/Renderable.h delete mode 100644 inc/hgl/graph/Shader.h delete mode 100644 inc/hgl/graph/Texture.h delete mode 100644 inc/hgl/graph/Texture1D.h delete mode 100644 inc/hgl/graph/Texture2D.h delete mode 100644 inc/hgl/graph/TextureData.h delete mode 100644 inc/hgl/graph/TextureFormat.h delete mode 100644 inc/hgl/graph/TextureSourceFormat.h delete mode 100644 inc/hgl/graph/VertexArray.h rename {example/Vulkan => inc/hgl/graph/vulkan}/VK.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKBuffer.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKBufferData.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKCommandBuffer.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKDescriptorSets.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKDevice.h (97%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKDeviceAttribute.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKFence.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKFormat.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKFramebuffer.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKImageView.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKInstance.h (96%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKMaterial.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKPhysicalDevice.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKPipeline.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKPrimivate.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKRenderPass.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKRenderable.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKSemaphore.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKShaderModule.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKShaderModuleManage.h (94%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKShaderParse.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKSurfaceExtensionName.h (100%) rename {example/Vulkan => inc/hgl/graph/vulkan}/VKVertexAttributeBinding.h (100%) create mode 100644 inc/hgl/io/DataInputStream.h create mode 100644 inc/hgl/io/DataOutputStream.h create mode 100644 inc/hgl/io/EndianDataInputStream.h create mode 100644 inc/hgl/io/EndianDataOutputStream.h create mode 100644 inc/hgl/io/FileAccess.h create mode 100644 inc/hgl/io/FileInputStream.h create mode 100644 inc/hgl/io/FileOutputStream.h create mode 100644 inc/hgl/io/IOType.h create mode 100644 inc/hgl/io/InputStream.h create mode 100644 inc/hgl/io/JavaInputStream.h create mode 100644 inc/hgl/io/JavaOutputStream.h create mode 100644 inc/hgl/io/MemoryInputStream.h create mode 100644 inc/hgl/io/MemoryOutputStream.h create mode 100644 inc/hgl/io/OutputStream.h create mode 100644 inc/hgl/io/RandomAccessFile.h create mode 100644 inc/hgl/io/SeekAccess.h create mode 100644 inc/hgl/io/TextOutputStream.h create mode 100644 inc/hgl/platform/ExternalModule.h create mode 100644 inc/hgl/platform/FuncLoad.h create mode 100644 inc/hgl/platform/SystemInfo.h rename {example/Vulkan => inc/hgl/platform}/Window.h (100%) delete mode 100644 inc/hgl/platform/compiler/.directory delete mode 100644 inc/hgl/platform/os/.directory create mode 100644 inc/hgl/proc/Fifo.h create mode 100644 inc/hgl/proc/FifoInputStream.h create mode 100644 inc/hgl/proc/Pipe.h create mode 100644 inc/hgl/proc/Proc.h create mode 100644 inc/hgl/proc/ProcMutex.h create mode 100644 inc/hgl/type/DateTime.h create mode 100644 inc/hgl/type/StringList.h rename {example/Vulkan => res/shader}/FlatColor.frag (100%) create mode 100644 res/shader/FlatColor.frag.spv create mode 100644 res/shader/FlatColor.material rename {example/Vulkan => res/shader}/FlatColor.vert (100%) create mode 100644 res/shader/FlatColor.vert.spv rename {example/Vulkan => res/shader}/shader_compile.bat (100%) rename src/Base/{ => DataType}/Color.cpp (98%) rename src/Base/{ => DataType}/Color3f.cpp (100%) rename src/Base/{ => DataType}/Color4f.cpp (100%) create mode 100644 src/Base/DataType/StringList.cpp create mode 100644 src/Base/FileSystem/EnumFile.cpp create mode 100644 src/Base/FileSystem/FileSystem.cpp create mode 100644 src/Base/IO/DataInputStream.cpp create mode 100644 src/Base/IO/DataOutputStream.cpp create mode 100644 src/Base/IO/FileAccess.cpp create mode 100644 src/Base/IO/FileInputStream.cpp create mode 100644 src/Base/IO/FileOutputStream.cpp create mode 100644 src/Base/IO/IOType.cpp create mode 100644 src/Base/IO/RandomAccessFile.cpp create mode 100644 src/Base/IO/TextOutputStream.cpp rename src/Base/{ => Other}/CodePage.cpp (96%) create mode 100644 src/Base/Other/DateTime.cpp create mode 100644 src/Base/Other/ExpendString.cpp create mode 100644 src/Base/Other/ThreadFunc.cpp create mode 100644 src/Base/Other/TimeCount.cpp create mode 100644 src/Base/Other/TimeVal.cpp create mode 100644 src/Base/PlugIn/ExternalModule.cpp create mode 100644 src/Base/SystemInfo.cpp create mode 100644 src/Platform/Android/AndroidMain.cpp create mode 100644 src/Platform/Android/JNISupport.cpp create mode 100644 src/Platform/Android/LogConsole.cpp create mode 100644 src/Platform/Android/NativeActivitySupport.cpp create mode 100644 src/Platform/Android/ProgramPath.cpp create mode 100644 src/Platform/Apple/ProgramPath.mm create mode 100644 src/Platform/Apple/Semaphore.cpp create mode 100644 src/Platform/UNIX/CondVar.cpp create mode 100644 src/Platform/UNIX/DateTime.cpp create mode 100644 src/Platform/UNIX/EnumFile.cpp create mode 100644 src/Platform/UNIX/ExternalModule.cpp create mode 100644 src/Platform/UNIX/Fifo.cpp create mode 100644 src/Platform/UNIX/File.cpp create mode 100644 src/Platform/UNIX/FileAccess.cpp create mode 100644 src/Platform/UNIX/Pipe.cpp create mode 100644 src/Platform/UNIX/ProcMutex.cpp create mode 100644 src/Platform/UNIX/Process.cpp create mode 100644 src/Platform/UNIX/ProgramPath.cpp create mode 100644 src/Platform/UNIX/RWLock.cpp create mode 100644 src/Platform/UNIX/Semaphore.cpp create mode 100644 src/Platform/UNIX/SystemInfo.cpp create mode 100644 src/Platform/UNIX/Thread.cpp create mode 100644 src/Platform/UNIX/ThreadMutex.cpp create mode 100644 src/Platform/UNIX/Time.cpp rename {example/Vulkan => src/Platform/UNIX}/XCBWindow.cpp (100%) create mode 100644 src/Platform/Win/Clipboard.cpp create mode 100644 src/Platform/Win/CondVar.cpp create mode 100644 src/Platform/Win/DateTime.cpp create mode 100644 src/Platform/Win/Desktop.cpp create mode 100644 src/Platform/Win/EnumFile.cpp create mode 100644 src/Platform/Win/EnumVolume.cpp create mode 100644 src/Platform/Win/ExternalModule.cpp create mode 100644 src/Platform/Win/Fifo.cpp create mode 100644 src/Platform/Win/File.cpp create mode 100644 src/Platform/Win/FileAccess.cpp create mode 100644 src/Platform/Win/KeyConvert.cpp create mode 100644 src/Platform/Win/LogConsole.cpp create mode 100644 src/Platform/Win/LogDialog.cpp create mode 100644 src/Platform/Win/Pipe.cpp create mode 100644 src/Platform/Win/ProcMutex.cpp create mode 100644 src/Platform/Win/ProgramPath.cpp create mode 100644 src/Platform/Win/RWLock.cpp create mode 100644 src/Platform/Win/Semaphore.cpp create mode 100644 src/Platform/Win/SystemInfo.cpp create mode 100644 src/Platform/Win/Thread.cpp create mode 100644 src/Platform/Win/ThreadMutex.cpp create mode 100644 src/Platform/Win/Time.cpp rename {example/Vulkan => src/Platform/Win}/WinWindow.cpp (98%) delete mode 100644 src/RenderDevice/GLFW/RenderDeviceGLFW.cpp delete mode 100644 src/RenderDevice/GLFW/RenderWindowGLFW.cpp create mode 100644 src/RenderDevice/Vulkan/CMakeLists.txt rename {example => src/RenderDevice}/Vulkan/VKBuffer.cpp (95%) rename {example => src/RenderDevice}/Vulkan/VKCommandBuffer.cpp (93%) rename {example => src/RenderDevice}/Vulkan/VKDescriptorSets.cpp (97%) rename {example => src/RenderDevice}/Vulkan/VKDevice.cpp (94%) rename {example => src/RenderDevice}/Vulkan/VKDeviceAttribute.cpp (97%) rename {example => src/RenderDevice}/Vulkan/VKDeviceBuffer.cpp (97%) rename {example => src/RenderDevice}/Vulkan/VKDeviceCreater.cpp (98%) rename {example => src/RenderDevice}/Vulkan/VKFence.cpp (72%) rename {example => src/RenderDevice}/Vulkan/VKFormat.cpp (99%) rename {example => src/RenderDevice}/Vulkan/VKFramebuffer.cpp (89%) rename {example => src/RenderDevice}/Vulkan/VKInstance.cpp (98%) rename {example => src/RenderDevice}/Vulkan/VKMaterial.cpp (93%) rename {example => src/RenderDevice}/Vulkan/VKPhysicalDevice.cpp (97%) rename {example => src/RenderDevice}/Vulkan/VKPipeline.cpp (97%) rename {example => src/RenderDevice}/Vulkan/VKRenderPass.cpp (73%) rename {example => src/RenderDevice}/Vulkan/VKRenderable.cpp (90%) rename {example => src/RenderDevice}/Vulkan/VKSemaphore.cpp (72%) rename {example => src/RenderDevice}/Vulkan/VKShaderModule.cpp (95%) rename {example => src/RenderDevice}/Vulkan/VKShaderModuleManage.cpp (88%) rename {example => src/RenderDevice}/Vulkan/VKVertexAttributeBinding.cpp (94%) rename {example => src/RenderDevice}/Vulkan/VkImageView.cpp (96%) delete mode 100644 src/RenderDriver/BufferData.cpp delete mode 100644 src/RenderDriver/BufferObject.cpp delete mode 100644 src/RenderDriver/CMakeLists.txt delete mode 100644 src/RenderDriver/GLCore/CMakeLists.txt delete mode 100644 src/RenderDriver/GLCore/RenderDriverGLCore.cpp delete mode 100644 src/RenderDriver/GLES/CMakeLists.txt delete mode 100644 src/RenderDriver/GLSL.cpp delete mode 100644 src/RenderDriver/OpenGLDebug.cpp delete mode 100644 src/RenderDriver/OpenGLExt.cpp delete mode 100644 src/RenderDriver/RenderState.cpp delete mode 100644 src/RenderDriver/Renderable.cpp delete mode 100644 src/RenderDriver/Shader.cpp delete mode 100644 src/RenderDriver/Texture1D.cpp delete mode 100644 src/RenderDriver/Texture1DDSA.cpp delete mode 100644 src/RenderDriver/Texture2D.cpp delete mode 100644 src/RenderDriver/Texture2DDSA.cpp delete mode 100644 src/RenderDriver/TextureFormat.cpp delete mode 100644 src/RenderDriver/VertexArray.cpp delete mode 100644 src/RenderDriver/VertexBufferObject.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 8e8988c5..bbf834fa 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.0) +cmake_minimum_required(VERSION 3.0) PROJECT(ULRE) @@ -14,20 +14,15 @@ check_system_bits() check_system_version() set_compiler_param() set_output_directory() - -IF(WIN32) - add_subdirectory(3rdpty/glfw) - include_directories(3rdpty/glfw/include) +IF(WIN32) include_directories(${Vulkan_INCLUDE_DIRS}) - + SET(SPIRV_CROSS_PATH 3rdpty/SPIRV-Cross) include_directories(${SPIRV_CROSS_PATH}) add_subdirectory(${SPIRV_CROSS_PATH}) - - SET(OPENGL_LIB opengl32) ELSE() - SET(OPENGL_LIB GL) + SET(RENDER_LIBRARY xcb) ENDIF() SET(VULKAN_LIB ${Vulkan_LIBRARIES}) @@ -38,24 +33,21 @@ add_definitions(-DMATH_AVX) add_definitions(-DGLFW_INCLUDE_VULKAN) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/3rdpty/MathGeoLib/src) -include_directories(${CMAKE_CURRENT_SOURCE_DIR}/3rdpty/GLEWCore/inc) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/3rdpty/NvTriStrip) include_directories(${CMAKE_CURRENT_SOURCE_DIR}/inc) SET(ROOT_INCLUDE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/inc) add_subdirectory(3rdpty/MathGeoLib) -add_subdirectory(3rdpty/GLEWCore) add_subdirectory(3rdpty/NvTriStrip) add_subdirectory(src) SET(ULRE ULRE.Base - ULRE.RenderDevice - ULRE.RenderDriver + ULRE.RenderDevice.Vulkan ULRE.Platform MathGeoLib - GLEWCore - glfw - ${OPENGL_LIB}) + ${RENDER_LIBRARY} + spirv-cross-core + ${Vulkan_LIBRARY}) add_subdirectory(example) diff --git a/example/CMakeLists.txt b/example/CMakeLists.txt index 5353b027..1f19bdb7 100644 --- a/example/CMakeLists.txt +++ b/example/CMakeLists.txt @@ -1,8 +1 @@ -add_subdirectory(EnumRenderDevice) -add_subdirectory(OutputGLInfo) -add_subdirectory(NullWindow) -add_subdirectory(DirectGLRender) -add_subdirectory(DirectGLTexture) -add_subdirectory(TextureSampler) - -add_subdirectory(Vulkan) +add_subdirectory(Vulkan) diff --git a/example/DirectGLRender/CMakeLists.txt b/example/DirectGLRender/CMakeLists.txt deleted file mode 100644 index 2b0330e1..00000000 --- a/example/DirectGLRender/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -add_executable(DirectGLRender main.cpp) - -target_link_libraries(DirectGLRender PRIVATE ${ULRE}) diff --git a/example/DirectGLRender/main.cpp b/example/DirectGLRender/main.cpp deleted file mode 100644 index 9fe46ece..00000000 --- a/example/DirectGLRender/main.cpp +++ /dev/null @@ -1,174 +0,0 @@ -#include -#include -#include -#include -#include -#include - -using namespace hgl; -using namespace hgl::graph; - -constexpr uint screen_width=1280; -constexpr uint screen_height=720; - -constexpr char vertex_shader[]=R"( -#version 330 core - -in vec2 Vertex; -in vec3 Color; - -out vec4 FragmentColor; - -void main() -{ - FragmentColor=vec4(Color,1.0); - - gl_Position=vec4(Vertex,0.0,1.0); -})"; - -constexpr char fragment_shader[]=R"( -#version 330 core - -in vec4 FragmentColor; -out vec4 FragColor; - -void main() -{ - FragColor=vec4(FragmentColor.rgb,1); -})"; - -Shader shader; - -bool InitShader() -{ - if(!shader.AddVertexShader(vertex_shader)) - return(false); - - if(!shader.AddFragmentShader(fragment_shader)) - return(false); - - if(!shader.Build()) - return(false); - - if(!shader.Use()) - return(false); - - return(true); -} - -ArrayBuffer *vb_vertex=nullptr; -ArrayBuffer *vb_color=nullptr; -VertexArray *va=nullptr; -Renderable *render_obj=nullptr; -RenderState render_state; - -constexpr float vertex_data[]={0.0f,0.5f, -0.5f,-0.5f, 0.5f,-0.5f }; -constexpr float color_data[]={1,0,0, 0,1,0, 0,0,1 }; - -constexpr GLfloat clear_color[4]= -{ - 77.f/255.f, - 78.f/255.f, - 83.f/255.f, - 1.f -}; - -void InitRenderState() -{ - DepthState *ds=new DepthState(); - - ds->clear_depth=true; //要求清除depth缓冲区 - ds->clear_depth_value=1.0f; //depth清除所用值 - - ds->depth_mask=false; //关闭depth mask - ds->depth_test=false; //关闭depth test - - render_state.Add(ds); - - ColorState *cs=new ColorState(); - - cs->clear_color=true; - memcpy(cs->clear_color_value,clear_color,sizeof(GLfloat)*4); - - render_state.Add(cs); -} - -void InitVertexBuffer() -{ - vb_vertex=CreateVBO(VB2f(3,vertex_data)); - vb_color=CreateVBO(VB3f(3,color_data)); - - va=new VertexArray(); ///<创建VAO - - const int vertex_location=shader.GetAttribLocation("Vertex"); ///<取得顶点数据输入流对应的shader地址 - const int color_location=shader.GetAttribLocation("Color"); ///<取得颜色数据输入流对应的shader地址 - - va->SetPosition(vertex_location,vb_vertex); - va->AddBuffer(color_location,vb_color); - - render_obj=new Renderable(GL_TRIANGLES,va); -} - -void draw() -{ - render_state.Apply(); - render_obj->Draw(); -} - -int main(void) -{ - RenderDevice *device=CreateRenderDeviceGLFW(); - - if(!device) - { - std::cerr<<"Create RenderDevice(GLFW) failed."<Init()) - { - std::cerr<<"Init RenderDevice(GLFW) failed."<Create(screen_width,screen_height,&ws,&rs); - - win->MakeToCurrent(); //切换当前窗口到前台 - - InitOpenGLDebug(); //初始化OpenGL调试输出 - - if(!InitShader()) - { - std::cerr<<"init shader failed."<Show(); - - while(win->IsOpen()) - { - draw(); - - win->SwapBuffer(); //交换前后台显示缓冲区 - win->PollEvent(); //处理窗口事件 - } - - delete render_obj; - delete va; - delete vb_color; - delete vb_vertex; - - delete win; - delete device; - - return 0; -} diff --git a/example/DirectGLTexture/CMakeLists.txt b/example/DirectGLTexture/CMakeLists.txt deleted file mode 100644 index 0a6fae4a..00000000 --- a/example/DirectGLTexture/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -add_executable(DirectGLTexture main.cpp TGATexture.cpp) - -target_link_libraries(DirectGLTexture PRIVATE ${ULRE}) - diff --git a/example/DirectGLTexture/TGATexture.cpp b/example/DirectGLTexture/TGATexture.cpp deleted file mode 100644 index cf3b0c50..00000000 --- a/example/DirectGLTexture/TGATexture.cpp +++ /dev/null @@ -1,140 +0,0 @@ -#include -#include -#include -#include - -namespace hgl -{ - namespace graph - { - namespace - { - #pragma pack(push,1) - struct TGAHeader - { - uint8 id; - uint8 color_map_type; - uint8 image_type; // 1 colormap image ,2 true-color,3 grayscale - - uint16 color_map_first; - uint16 color_map_length; - uint8 color_map_size; - - uint16 x_origin; - uint16 y_origin; - - uint16 width; - uint16 height; - uint8 bit; - - uint8 image_desc; - }; - - union TGAImageDesc - { - //不要把此union放到上面的struct中,否则Visual C++会将此union编译成4字节。GCC无此问题 - uint8 image_desc; - struct - { - uint alpha_depth:4; - uint reserved:1; - uint direction:1; //0 lower-left,1 upper left - }; - }; - #pragma pack(pop) - }//namespace - - bool LoadTGATexture(const std::string &filename,uint &tex_id) - { - std::ifstream file; - - file.open(filename,std::ifstream::in|std::ifstream::binary); - - if(!file.is_open()) - { - std::cerr<<"[ERROR] open file<"< failed."<image_type==2) - { - if(header->bit==24) - { - videomemory_format=GL_RGB8; - source_format=GL_BGR; - line_size=header->width*3; - } - else if(header->bit==32) - { - videomemory_format=GL_RGBA8; - source_format=GL_BGRA; - line_size=header->width*4; - } - } - else if(header->image_type==3&&header->bit==8) - { - videomemory_format=GL_R8; - source_format=GL_RED; - line_size=header->width; - } - else - { - std::cerr<<"[ERROR] Image format error,filename: "<width,header->height); - - TGAImageDesc img_desc; - - img_desc.image_desc=header->image_desc; - - if(img_desc.direction==1) - glTextureSubImage2D(tex_id,0,0,0,header->width,header->height,source_format,GL_UNSIGNED_BYTE,data+sizeof(TGAHeader)); - else - { - char *new_img=new char[line_size*header->height]; - char *sp=data+sizeof(TGAHeader)+line_size*(header->height-1); - char *tp=new_img; - - for(int i=0;iheight;i++) - { - memcpy(tp,sp,line_size); - tp+=line_size; - sp-=line_size; - } - - glTextureSubImage2D(tex_id,0,0,0,header->width,header->height,source_format,GL_UNSIGNED_BYTE,new_img); - delete[] new_img; - } - - glTextureParameteri(tex_id,GL_TEXTURE_MIN_FILTER,GL_LINEAR); - glTextureParameteri(tex_id,GL_TEXTURE_MAG_FILTER,GL_LINEAR); - glTextureParameteri(tex_id,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); - glTextureParameteri(tex_id,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); - - std::cout<<"load image file<"<:<"<width<<"x"<height<<"> to texture ok"< -#include -#include -#include -#include - -using namespace hgl; -using namespace hgl::graph; - -constexpr uint screen_width=720; -constexpr uint screen_height=720; - -uint texture_id=0; - -namespace hgl -{ - namespace graph - { - bool LoadTGATexture(const std::string &filename,uint &tex_id); - } -} - -constexpr char vertex_shader[]=R"( -#version 330 core - -in vec2 Vertex; -in vec2 TexCoord; - -out vec2 FragmentTexCoord; - -void main() -{ - FragmentTexCoord=TexCoord; - - gl_Position=vec4(Vertex,0.0,1.0); -})"; - -constexpr char fragment_shader[]=R"( -#version 330 core - -uniform sampler2D TextureLena; - -in vec2 FragmentTexCoord; -out vec4 FragColor; - -void main() -{ - FragColor=texture(TextureLena,FragmentTexCoord); -})"; - -Shader shader; - -bool InitShader() -{ - if(!shader.AddVertexShader(vertex_shader)) - return(false); - - if(!shader.AddFragmentShader(fragment_shader)) - return(false); - - if(!shader.Build()) - return(false); - - if(!shader.Use()) - return(false); - - return(true); -} - -ArrayBuffer *vb_vertex=nullptr; -ArrayBuffer *vb_texcoord=nullptr; -VertexArray *va=nullptr; -Renderable *render_obj=nullptr; - -constexpr float vertex_data[]={ -0.75f, 0.75f, - -0.75f,-0.75f, - 0.75f, 0.75f, - 0.75f,-0.75f -}; - -constexpr float texcoord_data[]={ 0,0, - 0,1, - 1,0, - 1,1 }; - -void InitVertexBuffer() -{ - vb_vertex=CreateVBO(VB2f(4,vertex_data)); - vb_texcoord=CreateVBO(VB2f(4,texcoord_data)); - - va=new VertexArray(); - - const int vertex_location=shader.GetAttribLocation("Vertex"); ///<取得顶点数据输入流对应的shader地址 - const int texcoord_location=shader.GetAttribLocation("TexCoord"); ///<取得纹理坐标数据输入流对应的shader地址 - - va->SetPosition(vertex_location,vb_vertex); - va->AddBuffer(texcoord_location,vb_texcoord); - - render_obj=new Renderable(GL_TRIANGLE_STRIP,va); -} - -bool InitTexture() -{ - if(!LoadTGATexture("lena.tga",texture_id)) - return(false); - - int texture_location=shader.GetUniformLocation("TextureLena"); - - glBindTextureUnit(0,texture_id); - - shader.SetUniform1i(texture_location,0); - - return(true); -} - -constexpr GLfloat clear_color[4]= -{ - 77.f/255.f, - 78.f/255.f, - 83.f/255.f, - 1.f -}; - -constexpr GLfloat clear_depth=1.0f; - -void draw() -{ - glClearBufferfv(GL_COLOR,0,clear_color); - glClearBufferfv(GL_DEPTH,0,&clear_depth); - - render_obj->Draw(); -} - -int main(void) -{ - RenderDevice *device=CreateRenderDeviceGLFW(); - - if(!device) - { - std::cerr<<"Create RenderDevice(GLFW) failed."<Init()) - { - std::cerr<<"Init RenderDevice(GLFW) failed."<Create(screen_width,screen_height,&ws,&rs); - - win->MakeToCurrent(); //切换当前窗口到前台 - - InitOpenGLDebug(); //初始化OpenGL调试输出 - - if(!InitShader()) - { - std::cerr<<"init shader failed."<Show(); - - while(win->IsOpen()) - { - draw(); - - win->SwapBuffer(); //交换前后台显示缓冲区 - win->PollEvent(); //处理窗口事件 - } - - delete render_obj; - delete va; - delete vb_texcoord; - delete vb_vertex; - - delete win; - delete device; - - return 0; -} diff --git a/example/EnumRenderDevice/CMakeLists.txt b/example/EnumRenderDevice/CMakeLists.txt deleted file mode 100644 index c3491a84..00000000 --- a/example/EnumRenderDevice/CMakeLists.txt +++ /dev/null @@ -1,3 +0,0 @@ -add_executable(EnumRenderDevice main.cpp) - -target_link_libraries(EnumRenderDevice PRIVATE ${ULRE}) diff --git a/example/EnumRenderDevice/main.cpp b/example/EnumRenderDevice/main.cpp deleted file mode 100644 index e4d3ad43..00000000 --- a/example/EnumRenderDevice/main.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include -#include -#include - -using namespace hgl; - -void put(const struct VideoMode *vm) -{ - std::cout<<"\t"<width<<"x"<height<<","<bit<<"bits,"<freq<<"hz"; -} - -void put(const struct Display *disp) -{ - const int inch=sqrt((disp->width*disp->width)+(disp->height*disp->height))*0.03937008; - - std::cout<<"["<name.c_str()<<"]["<width<<"x"<height<<" mm,"<x<<","<y<<"]"<GetCurVideoMode()); - std::cout< &vml=disp->GetVideoModeList(); - - for(int i=0;iInit()) - { - std::cerr<<"Init RenderDevice(GLFW) failed."<GetName(); - - std::cout<<"RenderDevice: "< disp_list; - - device->GetDisplayList(disp_list); - - const int count=disp_list.GetCount(); - - std::cout<<"Device have "< -#include -#include -#include - -using namespace hgl; - -int main(void) -{ - RenderDevice *device=CreateRenderDeviceGLFW(); - - if(!device) - { - std::cerr<<"Create RenderDevice(GLFW) failed."<Init()) - { - std::cerr<<"Init RenderDevice(GLFW) failed."<Create(1280,720,&ws,&rs); - - win->Show(); - - glClearColor(0,0,0,1); //设置清屏颜色 - - while(win->IsOpen()) - { - win->MakeToCurrent(); //切换当前窗口到前台 - - glClear(GL_COLOR_BUFFER_BIT); //清屏 - - win->SwapBuffer(); //交换前后台显示缓冲区 - win->PollEvent(); //处理窗口事件 - } - - delete win; - delete device; - - return 0; -} diff --git a/example/OutputGLInfo/CMakeLists.txt b/example/OutputGLInfo/CMakeLists.txt deleted file mode 100644 index fa8cc7bd..00000000 --- a/example/OutputGLInfo/CMakeLists.txt +++ /dev/null @@ -1,5 +0,0 @@ -add_executable(OutputGLInfo main.cpp) - -target_link_libraries(OutputGLInfo PRIVATE ${ULRE}) - - diff --git a/example/OutputGLInfo/main.cpp b/example/OutputGLInfo/main.cpp deleted file mode 100644 index 7dde2a31..00000000 --- a/example/OutputGLInfo/main.cpp +++ /dev/null @@ -1,110 +0,0 @@ -#include -#include -#include -#include -#include - -using namespace hgl; - -void draw() -{ - glClearColor(0,0,0,1); //设置清屏颜色 - glClear(GL_COLOR_BUFFER_BIT); //清屏 -} - -void output_ogl_info() -{ - std::cout<<"Vendor: "<Init()) - { - std::cerr<<"Init RenderDevice(GLFW) failed."<1) - { - if(stricmp(argv[1],"core")==0) - rs.opengl.core=true; - else - rs.opengl.core=false; - } - else - rs.opengl.core=false; - - RenderWindow *win=device->Create(1280,720,&ws,&rs); - - win->MakeToCurrent(); //切换当前窗口到前台 - - output_ogl_info(); - output_ogl_values(); - - delete win; - delete device; - - return 0; -} diff --git a/example/TextureSampler/CMakeLists.txt b/example/TextureSampler/CMakeLists.txt deleted file mode 100644 index 7d1c0fd9..00000000 --- a/example/TextureSampler/CMakeLists.txt +++ /dev/null @@ -1,4 +0,0 @@ -add_executable(TextureSampler main.cpp TGATexture.cpp) - -target_link_libraries(TextureSampler PRIVATE ${ULRE}) - diff --git a/example/TextureSampler/TGATexture.cpp b/example/TextureSampler/TGATexture.cpp deleted file mode 100644 index d91c0850..00000000 --- a/example/TextureSampler/TGATexture.cpp +++ /dev/null @@ -1,153 +0,0 @@ -#include -#include -#include -#include - -namespace hgl -{ - namespace graph - { - namespace - { - #pragma pack(push,1) - struct TGAHeader - { - uint8 id; - uint8 color_map_type; - uint8 image_type; // 1 colormap image ,2 true-color,3 grayscale - - uint16 color_map_first; - uint16 color_map_length; - uint8 color_map_size; - - uint16 x_origin; - uint16 y_origin; - - uint16 width; - uint16 height; - uint8 bit; - - uint8 image_desc; - }; - - union TGAImageDesc - { - //不要把此union放到上面的struct中,否则Visual C++会将此union编译成4字节。GCC无此问题 - uint8 image_desc; - struct - { - uint alpha_depth:4; - uint reserved:1; - uint direction:1; //0 lower-left,1 upper left - }; - }; - #pragma pack(pop) - }//namespace - - bool LoadTGATexture(const std::string &filename,GLuint &tex_id) - { - std::ifstream file; - - file.open(filename,std::ifstream::in|std::ifstream::binary); - - if(!file.is_open()) - { - std::cerr<<"[ERROR] open file<"< failed."<image_type==2) - { - if(header->bit==24) - { - videomemory_format=GL_RGB8; - source_format=GL_BGR; - line_size=header->width*3; - } - else if(header->bit==32) - { - videomemory_format=GL_RGBA8; - source_format=GL_BGRA; - line_size=header->width*4; - } - } - else if(header->image_type==3&&header->bit==8) - { - videomemory_format=GL_R8; - source_format=GL_RED; - line_size=header->width; - } - else - { - std::cerr<<"[ERROR] Image format error,filename: "<width,header->height); - - TGAImageDesc img_desc; - - img_desc.image_desc=header->image_desc; - - if(img_desc.direction==1) - glTextureSubImage2D(tex_id,0,0,0,header->width,header->height,source_format,GL_UNSIGNED_BYTE,data+sizeof(TGAHeader)); - else - { - char *new_img=new char[line_size*header->height]; - char *sp=data+sizeof(TGAHeader)+line_size*(header->height-1); - char *tp=new_img; - - for(int i=0;iheight;i++) - { - memcpy(tp,sp,line_size); - tp+=line_size; - sp-=line_size; - } - - glTextureSubImage2D(tex_id,0,0,0,header->width,header->height,source_format,GL_UNSIGNED_BYTE,new_img); - delete[] new_img; - } - - glGenerateTextureMipmap(tex_id); - - std::cout<<"load image file<"<:<"<width<<"x"<height<<"> to texture ok"< -#include -#include -#include -#include - -using namespace hgl; -using namespace hgl::graph; - -constexpr uint screen_width=640; -constexpr uint screen_height=640; - -GLuint texture_id=0; -GLuint sampler_id=0; - -namespace hgl -{ - namespace graph - { - bool LoadTGATexture(const std::string &filename,GLuint &tex_id); - GLuint CreateSamplerObject(GLint min_filter,GLint mag_filter,GLint clamp,const GLfloat *border_color); - } -} - -constexpr char vertex_shader[]=R"( -#version 330 core - -in vec2 Vertex; -in vec2 TexCoord; - -out vec2 FragmentTexCoord; - -void main() -{ - FragmentTexCoord=TexCoord; - - gl_Position=vec4(Vertex,0.0,1.0); -})"; - -constexpr char fragment_shader[]=R"( -#version 330 core - -uniform sampler2D TextureLena; - -in vec2 FragmentTexCoord; -out vec4 FragColor; - -void main() -{ - FragColor=texture(TextureLena,FragmentTexCoord); -})"; - -Shader shader; - -bool InitShader() -{ - if(!shader.AddVertexShader(vertex_shader)) - return(false); - - if(!shader.AddFragmentShader(fragment_shader)) - return(false); - - if(!shader.Build()) - return(false); - - if(!shader.Use()) - return(false); - - return(true); -} - -ArrayBuffer *vb_vertex=nullptr; -ArrayBuffer *vb_texcoord=nullptr; -VertexArray *va=nullptr; -Renderable *render_obj=nullptr; - -constexpr float vertex_data[]={ -0.75f, 0.75f, - -0.75f,-0.75f, - 0.75f, 0.75f, - 0.75f,-0.75f -}; - -constexpr float texcoord_data[]={ -0.25,-0.25, - -0.25, 1.25, - 1.25,-0.25, - 1.25, 1.25 -}; - -void InitVertexBuffer() -{ - vb_vertex=CreateVBO(VB2f(4,vertex_data)); - vb_texcoord=CreateVBO(VB2f(4,texcoord_data)); - - va=new VertexArray(); - - const int vertex_location=shader.GetAttribLocation("Vertex"); ///<取得顶点数据输入流对应的shader地址 - const int texcoord_location=shader.GetAttribLocation("TexCoord"); ///<取得纹理坐标数据输入流对应的shader地址 - - va->SetPosition(vertex_location,vb_vertex); - va->AddBuffer(texcoord_location,vb_texcoord); - - render_obj=new Renderable(GL_TRIANGLE_STRIP,va); -} - -bool InitTexture() -{ - if(!LoadTGATexture("lena.tga",texture_id)) - return(false); - - const GLfloat border_color[4]={1,1,0,1}; - - sampler_id=CreateSamplerObject(GL_NEAREST_MIPMAP_NEAREST, GL_NEAREST, GL_CLAMP_TO_BORDER,border_color); - - int texture_location=shader.GetUniformLocation("TextureLena"); - - glBindTextureUnit(0,texture_id); - glBindSampler(0,sampler_id); - - shader.SetUniform1i(texture_location,0); - - return(true); -} - -constexpr GLfloat clear_color[4]= -{ - 77.f/255.f, - 78.f/255.f, - 83.f/255.f, - 1.f -}; - -constexpr GLfloat clear_depth=1.0f; - -void draw() -{ - glClearBufferfv(GL_COLOR,0,clear_color); - glClearBufferfv(GL_DEPTH,0,&clear_depth); - - render_obj->Draw(); -} - -int main(void) -{ - RenderDevice *device=CreateRenderDeviceGLFW(); - - if(!device) - { - std::cerr<<"Create RenderDevice(GLFW) failed."<Init()) - { - std::cerr<<"Init RenderDevice(GLFW) failed."<Create(screen_width,screen_height,&ws,&rs); - - win->MakeToCurrent(); //切换当前窗口到前台 - - InitOpenGLDebug(); //初始化OpenGL调试输出 - - if(!InitShader()) - { - std::cerr<<"init shader failed."<Show(); - - while(win->IsOpen()) - { - draw(); - - win->SwapBuffer(); //交换前后台显示缓冲区 - win->PollEvent(); //处理窗口事件 - } - - delete render_obj; - delete va; - delete vb_texcoord; - delete vb_vertex; - - delete win; - delete device; - - return 0; -} diff --git a/example/Vulkan/AssetsManage.cpp b/example/Vulkan/AssetsManage.cpp deleted file mode 100644 index 4c6f1a2f..00000000 --- a/example/Vulkan/AssetsManage.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include -#ifndef WIN32 -#include -#endif// - -char *LoadFileToMemory(const char *filename,unsigned __int32 &file_length) -{ - std::ifstream fs; - - fs.open(filename,std::ios_base::binary); - - if(!fs.is_open()) - return(nullptr); - - fs.seekg(0,std::ios_base::end); - file_length=fs.tellg(); - char *data=new char[file_length]; - - fs.seekg(0,std::ios_base::beg); - fs.read(data,file_length); - - fs.close(); - return data; -} \ No newline at end of file diff --git a/example/Vulkan/AssetsManage.h b/example/Vulkan/AssetsManage.h deleted file mode 100644 index 013945f6..00000000 --- a/example/Vulkan/AssetsManage.h +++ /dev/null @@ -1,6 +0,0 @@ -#ifndef HGL_ASSETS_MANAGE_INCLUDE -#define HGL_ASSETS_MANAGE_INCLUDE - -char *LoadFileToMemory(const char *filename,unsigned __int32 &file_length); - -#endif//HGL_ASSETS_MANAGE_INCLUDE diff --git a/example/Vulkan/CMakeLists.txt b/example/Vulkan/CMakeLists.txt index 0bafc249..983ea1c3 100644 --- a/example/Vulkan/CMakeLists.txt +++ b/example/Vulkan/CMakeLists.txt @@ -1,69 +1,2 @@ -IF(UNIX) - SET(RENDER_WINDOW_SOURCE XCBWindow.cpp) - SET(RENDER_WINDOW_LIBRARY xcb) -ELSEIF(WIN32) - SET(RENDER_WINDOW_SOURCE WinWindow.cpp) -ENDIF() - -SET(VULKAN_TEST_SOURCE_FILES main.cpp - AssetsManage.cpp - ${RENDER_WINDOW_SOURCE} - VKFormat.cpp - VKInstance.cpp - VKPhysicalDevice.cpp - VKImageView.cpp - VKCommandBuffer.cpp - VKDeviceAttribute.cpp - VKDeviceCreater.cpp - VKDevice.cpp - VKDeviceBuffer.cpp - VKBuffer.cpp - VKDescriptorSets.cpp - VKRenderPass.cpp - VKShaderModule.cpp - VKShaderModuleManage.cpp - VKVertexAttributeBinding.cpp - VKPipeline.cpp - VKSemaphore.cpp - VKFramebuffer.cpp - VKFence.cpp - VKMaterial.cpp - VKRenderable.cpp - ) - -SET(VULKAN_TEST_HEADER_FILES AssetsManage.h - VK.h - VKFormat.h - VKPrimivate.h - VKInstance.h - VKPhysicalDevice.h - VKImageView.h - VKCommandBuffer.h - VKSurfaceExtensionName.h - VKDeviceAttribute.h - VKDevice.h - VKBuffer.h - VKDescriptorSets.h - VKRenderPass.h - VKShaderModule.h - VKShaderModuleManage.h - VKVertexAttributeBinding.h - VKSemaphore.h - VKPipeline.h - VKFramebuffer.h - VKFence.h - VKMaterial.h - VKRenderable.h - Window.h) - -SET(SHADER_FILES shader_compile.bat - FlatColor.vert - FlatColor.frag) - -SOURCE_GROUP("Header Files" FILES ${VULKAN_TEST_HEADER_FILES}) -SOURCE_GROUP("Source Files" FILES ${VULKAN_TEST_SOURCE_FILES}) -SOURCE_GROUP("Shader Files" FILES ${SHADER_FILES}) - -add_executable(VulkanTest ${VULKAN_TEST_HEADER_FILES} ${VULKAN_TEST_SOURCE_FILES} ${SHADER_FILES}) - -target_link_libraries(VulkanTest PRIVATE ${ULRE} ${VULKAN_LIB} ${RENDER_WINDOW_LIBRARY} spirv-cross-core) +add_executable(VulkanTest main.cpp ${SHADER_FILES}) +target_link_libraries(VulkanTest ${ULRE}) diff --git a/example/Vulkan/Shader.cpp b/example/Vulkan/Shader.cpp deleted file mode 100644 index 3938574e..00000000 --- a/example/Vulkan/Shader.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#include"Shader.h" - -VK_NAMESPACE_BEGIN -VK_NAMESPACE_END diff --git a/example/Vulkan/Shader.h b/example/Vulkan/Shader.h deleted file mode 100644 index 53be7f45..00000000 --- a/example/Vulkan/Shader.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef HGL_GRAPH_VULKAN_SHADER_INCLUDE -#define HGL_GRAPH_VULKAN_SHADER_INCLUDE - -#include"VK.h" -VK_NAMESPACE_BEGIN -VK_NAMESPACE_END -#endif//HGL_GRAPH_VULKAN_SHADER_INCLUDE diff --git a/example/Vulkan/VulkanAppFramework.h b/example/Vulkan/VulkanAppFramework.h new file mode 100644 index 00000000..694001b5 --- /dev/null +++ b/example/Vulkan/VulkanAppFramework.h @@ -0,0 +1,93 @@ +#pragma once +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace hgl; +using namespace hgl::graph; + +class VulkanApplicationFramework +{ +private: + + Window * win =nullptr; + vulkan::Instance * inst =nullptr; + +protected: + + vulkan::Device * device =nullptr; + vulkan::ShaderModuleManage *shader_manage =nullptr; + +public: + + virtual ~VulkanApplicationFramework() + { + SAFE_CLEAR(shader_manage); + SAFE_CLEAR(device); + SAFE_CLEAR(inst); + SAFE_CLEAR(win); + } + + virtual bool Init(int w,int h) + { + win=CreateRenderWindow(OS_TEXT("VulkanTest")); + if(!win) + return(false); + + if(!win->Create(w,h)) + return(false); + + inst=vulkan::CreateInstance(U8_TEXT("VulkanTest")); + + if(!inst) + return(false); + + device=inst->CreateRenderDevice(win); + + if(!device) + return(false); + + shader_manage=device->CreateShaderModuleManage(); + + const vulkan::PhysicalDevice *render_device=device->GetPhysicalDevice(); + + std::cout<<"auto select physical device: "<GetDeviceName()<AcquireNextImage(); + } + + void Submit(vulkan::CommandBuffer *cmd_buf) + { + device->QueueSubmit(cmd_buf); + device->Wait(); + device->QueuePresent(); + } + + void Wait(double seconds) + { + #ifdef WIN32 + Sleep(seconds * 1000.0f); + #elif defined(__ANDROID__) + sleep(seconds); + #else + sleep(seconds); + #endif + } +};//class VulkanApplicationFramework diff --git a/example/Vulkan/main.cpp b/example/Vulkan/main.cpp index 76021724..bf07d783 100644 --- a/example/Vulkan/main.cpp +++ b/example/Vulkan/main.cpp @@ -1,19 +1,4 @@ -#include"Window.h" -#include"VKInstance.h" -#include"VKPhysicalDevice.h" -#include"VKDevice.h" -#include"VKBuffer.h" -#include"VKShaderModule.h" -#include"VKShaderModuleManage.h" -#include"VKImageView.h" -#include"VKRenderable.h" -#include"VKDescriptorSets.h" -#include"VKRenderPass.h" -#include"VKPipeline.h" -#include"VKCommandBuffer.h" -#include"VKFormat.h" -#include"VKFramebuffer.h" -#include"VKMaterial.h" +#include"VulkanAppFramework.h" #include using namespace hgl; @@ -42,79 +27,6 @@ constexpr float color_data[VERTEX_COUNT][3]= {0,0,1} }; -void wait_seconds(double seconds) -{ -#ifdef WIN32 - Sleep(seconds * 1000.0f); -#elif defined(__ANDROID__) - sleep(seconds); -#else - sleep(seconds); -#endif -} - -class VulkanApplicationFramework -{ -private: - - Window * win =nullptr; - vulkan::Instance * inst =nullptr; - -protected: - - vulkan::Device * device =nullptr; - vulkan::ShaderModuleManage *shader_manage =nullptr; - -public: - - virtual ~VulkanApplicationFramework() - { - SAFE_CLEAR(shader_manage); - SAFE_CLEAR(device); - SAFE_CLEAR(inst); - SAFE_CLEAR(win); - } - - virtual bool Init(int w,int h) - { - win=CreateRenderWindow(OS_TEXT("VulkanTest")); - if(!win) - return(false); - - if(!win->Create(SCREEN_WIDTH,SCREEN_HEIGHT)) - return(false); - - inst=vulkan::CreateInstance(U8_TEXT("VulkanTest")); - - if(!inst) - return(false); - - device=inst->CreateRenderDevice(win); - - if(!device) - return(false); - - shader_manage=device->CreateShaderModuleManage(); - - const vulkan::PhysicalDevice *render_device=device->GetPhysicalDevice(); - - std::cout<<"auto select physical device: "<GetDeviceName()<AcquireNextImage(); - } - - void Submit(vulkan::CommandBuffer *cmd_buf) - { - device->QueueSubmit(cmd_buf); - device->Wait(); - device->QueuePresent(); - } -};//class VulkanApplicationFramework - class TestApp:public VulkanApplicationFramework { private: //需释放数据 @@ -148,7 +60,8 @@ private: bool InitMaterial() { - material=shader_manage->CreateMaterial("FlatColor.vert.spv","FlatColor.frag.spv"); + material=shader_manage->CreateMaterial(OS_TEXT("FlatColor.vert.spv"), + OS_TEXT("FlatColor.frag.spv")); if(!material) return(false); @@ -256,7 +169,7 @@ int main(int,char **) app.AcquireNextFrame(); app.Draw(); - wait_seconds(0.5); + app.Wait(0.5); return 0; } diff --git a/inc/hgl/Logger.h b/inc/hgl/Logger.h new file mode 100644 index 00000000..4897b7e2 --- /dev/null +++ b/inc/hgl/Logger.h @@ -0,0 +1,133 @@ +#ifndef HGL_LOGGER_INCLUDE +#define HGL_LOGGER_INCLUDE + +#include +namespace hgl +{ + namespace logger + { + enum LogLevel + { + llError=0, //错误,肯定出对话框 + llProblem, //问题,默认出对话框 + llHint, //提示,不重要,debug状态默认出对话框 + llLog //记录一下 + };//enum LogLevel + + /** + * 日志输出基类 + */ + class Logger + { + protected: + + LogLevel min_level; ///<最小输出级别 + UTF16String project_code; + + public: + + Logger(LogLevel l){min_level=l;} + virtual ~Logger()=default; + + const LogLevel GetLevel()const{return min_level;} ///<取得最小输出级别 + + virtual void Close()=0; ///<关闭日志 + + virtual void Write(const u16char *,int)=0; ///<输出一行u16char日志 + virtual void Write(const char *,int)=0; ///<输出一行char(utf8)日志 + };//class Logger + }//namespace logger + + namespace logger + { + /** + * 日志级别枚举 + */ + enum LOG_LEVEL + { + LL_START=0, ///<日志级别起始定义 + + LL_HOTPOT, ///<性能记录热点 + LL_CODE, ///<代码日志(引擎内部记录) + LL_USER, ///<用户日志(开发人员的日志) + LL_RUN, ///<运行日志(实际使用时的日志) + + LL_END ///<日志级别结束定义 + }; + + /** + * 影响级别 + */ + enum AFFECTOR_LEVEL + { + AL_START=0, + + AL_USER, ///<用户级(无关仅要,正常程序逻辑报错) + AL_FUNC, ///<函数级(当前函数报错) + AL_MODULE, ///<模块级 + AL_FULL, ///<整体级(很严重,只能退出) + + AL_MUST_FIXED, ///<必须修正的代码问题 + + AL_END + }; + + /** + * 日志输出基类 + */ + class LoggerBase + { + protected: + + LOG_LEVEL log_level; + AFFECTOR_LEVEL err_level; + + protected: + + uint32 source_file; ///<源代所在文件ID + uint32 source_line; ///<源代码所在行 + uint32 function; ///<函数ID + HGL_POINTER_UINT object_address; ///<对象地址 + HGL_POINTER_UINT thread_id; ///<线程ID + + public: + };//class AdvLogger + + /** + * 线程日志 + */ + class ThreadLogger + { + + public: + + + };//class ThreadLogger + + /** + * 对象日志 + */ + class ObjectLogger + { + }; + + /** + * 时间追踪日志 + * 针对同一数据记录每一次时间下的数值的日志输出模块 + */ + class TimeLogger + { + }; + + /** + * 图形日志
+ * 用于记录碰撞信息,寻路信息,路线跟踪等等 + */ + class GraphicsLogger + { + };// + }//namespace logger + + using namespace logger; +}//namespace hgl +#endif//HGL_LOGGER_INCLUDE diff --git a/inc/hgl/Time.h b/inc/hgl/Time.h new file mode 100644 index 00000000..a7983646 --- /dev/null +++ b/inc/hgl/Time.h @@ -0,0 +1,23 @@ +#ifndef HGL_TIME_INCLUDE +#define HGL_TIME_INCLUDE + +#include + +namespace hgl //ʱ +{ + int GetTimeZone(); ///<ʱʱ(λ) + + uint64 GetMilliStartTime(); ///<ȡúʱ(λ1/1000) + uint64 GetMicroStartTime(); ///<ȡ΢ʱ(λ1/1000000) + double GetDoubleStartTime(); ///<ȡʱ(λ) + + uint64 GetTime(); ///<ȡõǰʱ(λ1/1000) + uint64 GetMicroTime(); ///<ȡõǰʱ(λ1/1000000) + double GetDoubleTime(); ///<ȡõǰʱ(λ) + + double GetLocalDoubleTime(); ///<ȡñصǰʱ(λ) + + void WaitTime(double); ///<ȴһʱ(λ) +}//namespace hgl + +#endif//HGL_TIME_INCLUDE diff --git a/inc/hgl/endian/Endian.h b/inc/hgl/endian/Endian.h index 03b178c2..b65e9ae4 100644 --- a/inc/hgl/endian/Endian.h +++ b/inc/hgl/endian/Endian.h @@ -1,4 +1,4 @@ -#ifndef HGL_ENDIAN_INCLUDE +#ifndef HGL_ENDIAN_INCLUDE #define HGL_ENDIAN_INCLUDE #include // 平台定义 diff --git a/inc/hgl/filesystem/EnumFile.h b/inc/hgl/filesystem/EnumFile.h new file mode 100644 index 00000000..51089966 --- /dev/null +++ b/inc/hgl/filesystem/EnumFile.h @@ -0,0 +1,75 @@ +#include + +namespace hgl +{ + namespace filesystem + { + struct EnumFileConfig + { + OSString folder_name; ///<要枚举的目录名称 + +#if HGL_OS == HGL_OS_Windows ///<通配符过滤是Windows平台独有 + OSString find_name; ///<要枚举的文件名称 +#endif//HGL_OS == HGL_OS_Windows + + bool proc_folder; ///<是否处理目录 + bool proc_file; ///<是否处理文件 + bool sub_folder; ///<是否查找子目录 + + public: + + EnumFileConfig(const OSString &fn) + { + folder_name=fn; + +#if HGL_OS == HGL_OS_Windows + find_name=OS_TEXT("*.*"); +#endif//HGL_OS == HGL_OS_Windows + + proc_folder=true; + proc_file=true; + sub_folder=false; + } + + EnumFileConfig(const EnumFileConfig *efc,const OSString &sub_folder_name) + { + folder_name =sub_folder_name; + +#if HGL_OS == HGL_OS_Windows + find_name =efc->find_name; +#endif//HGL_OS == HGL_OS_Windows + + proc_folder =efc->proc_folder; + proc_file =efc->proc_file; + sub_folder =efc->sub_folder; + } + + virtual ~EnumFileConfig()=default; + };//struct EnumFileConfig + + /** + * 枚举文件系统内的文件 + */ + class EnumFile + { + protected: + + virtual void ProcFolder(struct EnumFileConfig *parent_efc,struct EnumFileConfig *cur_efc,FileInfo &fi){} + virtual void ProcFile(struct EnumFileConfig *,FileInfo &fi){} + + virtual EnumFileConfig *CreateSubConfig(struct EnumFileConfig *up_efc,const FileInfo &fi) + { + const OSString full_sub_folder_name=MergeFilename(up_efc->folder_name,fi.name); + + return(new EnumFileConfig(up_efc,full_sub_folder_name)); + } + + public: + + EnumFile()=default; + virtual ~EnumFile()=default; + + virtual int Enum(EnumFileConfig *); + };//class EnumFile + }//namespace filesystem +}//namespace hgl diff --git a/inc/hgl/filesystem/EnumVolume.h b/inc/hgl/filesystem/EnumVolume.h new file mode 100644 index 00000000..5cfd4c3b --- /dev/null +++ b/inc/hgl/filesystem/EnumVolume.h @@ -0,0 +1,99 @@ +#pragma once + +#include + +namespace hgl +{ + namespace filesystem + { + /** + * 卷信息数据结构 + */ + struct VolumeInfo + { + enum DriverType + { + dtNone=0, ///<未知类型 + + dtRemovable, ///<可移动设备 + dtFixed, ///<固定设备 + dtRemote, ///<远程设备 + dtCDROM, ///<光盘驱动器 + dtRamDisk, ///<内存虚拟设备 + + dtEnd ///<结束定义 + }; + + u16char name[HGL_MAX_PATH]; ///<卷名称 + + u16char path[HGL_MAX_PATH]; ///<卷所对应的路径名(注意:不是所有卷都有对应路径) + + DriverType driver_type; ///<驱动器类型(注意:不是所有的卷都对应驱动器) + + uint32 serial; ///<卷序列号 + + u16char volume_label[HGL_MAX_PATH]; ///<卷标名称 + + u16char file_system[HGL_MAX_PATH]; ///<文件系统名称 + + uint32 filename_max_length; ///<文件名最大长度 + + bool unicode; ///<文件名支持UNICODE + + uint64 available_space; ///<有效容量 + uint64 total_space; ///<总空量 + uint64 free_space; ///<自由容量 + };//struct VolumeInfo + +#if HGL_OS == HGL_OS_Windows + + /** + * 卷检测配置 + */ + struct VolumeCheckConfig + { + bool removable =false; + bool fixed =false; + bool remote =false; + bool cdrom =false; + bool ram_disk =false; + bool unknow =false; + + public: + + /** + * 设置为全部检测 + */ + void SetFullCheck() + { + memset(this,0xff,sizeof(VolumeCheckConfig)); + } + + /** + * 是否无效配置 + */ + bool isErrorConfig()const + { + if(removable)return(false); + if(fixed)return(false); + if(remote)return(false); + if(cdrom)return(false); + if(ram_disk)return(false); + if(unknow)return(false); + + return(true); + } + }; + + /** + * 枚举当前计算机所有卷 + * @param vi_list 储存卷信息的列表 + * @param check_removable 检测可移除设备 + * @param check_remote 检测远程驱动器 + * @param check_cd 检测光盘 + * @return 查找到的卷数量,-1表示失败 + */ + int EnumVolume(List &vi_list,const VolumeCheckConfig &); +#endif//HGL_OS == HGL_OS_Windows + }//namespace filesystem +}//namespace hgl \ No newline at end of file diff --git a/inc/hgl/filesystem/FileSystem.h b/inc/hgl/filesystem/FileSystem.h new file mode 100644 index 00000000..b41190ef --- /dev/null +++ b/inc/hgl/filesystem/FileSystem.h @@ -0,0 +1,208 @@ +#ifndef HGL_FILE_SYSTEM_INCLUDE +#define HGL_FILE_SYSTEM_INCLUDE + +#include +#include +namespace hgl +{ + namespace io + { + class InputStream; + }//namespace io + + namespace filesystem + { + template + inline BaseString MergeFilename(const BaseString &pathname,const BaseString &filename,const T directory_separator_char,const T *directory_separator_str) + { + BaseString fullname; + + if(pathname.GetEndChar()==directory_separator_char) //结尾有分隔符 + { + if(filename.GetBeginChar()==directory_separator_char) //开头有分隔符 + { + fullname.Set(pathname.c_str(),pathname.Length()-1); //少取一个字符 + } + else + { + fullname=pathname; + } + } + else //结尾没有分隔符 + { + fullname=pathname; + + if(filename.GetBeginChar()!=directory_separator_char) //开头没有分隔符 + { + fullname.Strcat(directory_separator_str); //添加分隔符 + } + } + + fullname.Strcat(filename); + return fullname; + } + + /** + * 截取完整路径中的文件名 + * @param filename 文件名 + * @param fullname 完整路径文件名 + */ + template + inline BaseString ClipFilename(const BaseString &fullname) + { + if(fullname.Length()<=1) + return(BaseString()); + + const T spear_char[] = { '/','\\' }; + + const int pos=fullname.FindRightChar(spear_char); + + if(pos==-1) + return BaseString(fullname); + + return fullname.SubString(pos+1); + } + + /** + * 截取完整文件名中的扩展名 + */ + template + inline BaseString ClipFileExtName(const BaseString &fullname) + { + int end=fullname.FindChar(T('?')); //url的文件名,以?为结束 + + if(end==-1) + end=fullname.Length(); + + int pos=fullname.FindRightChar(fullname.Length()-end,T('.')); + + if(pos==-1) + return BaseString(); + + return fullname.SubString(pos+1,end-(pos+1)); + } + + /** + * 截取路径最后一个名字 + */ + template + inline BaseString ClipLastPathname(const BaseString &fullname) + { + if(fullname.Length()<=1) + return(BaseString()); + + const T gap_char[2]={'\\','/'}; + + T *p=nullptr; + + T *s=fullname.c_str(); + T *e=fullname.c_str()+fullname.Length()-1; + + while(e>s) + { + if(!p) + { + if(*e==gap_char[0]||*e==gap_char[1]) + { + --e; + continue; + } + + p=e; + --e; + } + else + { + if(*e==gap_char[0]||*e==gap_char[1]) + { + return BaseString(e+1,p-e); + } + + --e; + } + } + + return(BaseString()); + } + + inline UTF8String MergeFilename(const UTF8String &pathname,const UTF8String &filename) ///<组合路径名与文件名 + {return MergeFilename(pathname,filename,HGL_DIRECTORY_SEPARATOR,HGL_DIRECTORY_SEPARATOR_U8STR);} + + inline WideString MergeFilename(const WideString &pathname,const WideString &filename) ///<组合路径名与文件名 + {return MergeFilename(pathname,filename,L'\\',L"\\");} + + bool FileCopy(const OSString &,const OSString &); ///<文件复制 + bool FileDelete(const OSString &); ///<文件删除 + bool FileMove(const OSString &,const OSString &); ///<文件移动 + bool FileRename(const OSString &,const OSString &); ///<文件改名 + bool FileExist(const OSString &); ///<文件确认是否存在 + bool FileComp(const OSString &,const OSString &); ///<文件比较 + + bool FileCanRead(const OSString &); ///<检测文件是否可读 + bool FileCanWrite(const OSString &); ///<检测文件是否可写 + bool FileCanExec(const OSString &); ///<检测文件是否可执行 + + int64 LoadFileToMemory(const OSString &,void **); ///<加载一个文件到内存 + int64 SaveMemoryToFile(const OSString &,const void *,const int64 &); ///<保存一块内存成文件 + int64 SaveMemoryToFile(const OSString &,void **,const int64 *,const int &); ///<保存多块内存成一个文件 + + void *LoadFileToMemory(const OSString &,int64,void *buf,int64); ///<加载一个文件的一部分到内存 + bool SaveMemoryToFile(const OSString &,int64,const void *,int64); ///<保存一块内存到一个文件 + + bool IsDirectory(const os_char *); + inline bool IsDirectory(const OSString &str){return IsDirectory(str.c_str());} ///<判断这个名称是否是目录 + +#if HGL_OS != HGL_OS_Windows + bool IsLink(const os_char *); ///<判断这个名称是否是链接 +#endif// + + bool MakePath(const OSString &); ///<创建一个路径 + bool DeletePath(const OSString &); ///<删除一个路径 + void DeleteTree(const OSString &); ///<删除一个路径(包含所有文件) + + bool GetCurrentPath(OSString &); ///<取得当前路径 + bool GetCurrentProgram(OSString &); ///<取得当前程序全路径名称 + bool GetCurrentProgramPath(OSString &); ///<取得当前程序所在路径 + void GetLocalAppdataPath(os_char fn[HGL_MAX_PATH]); ///<取得当前用户应用程序数据存放路径 + + //使用int64而不是__int64是因为不是所有编译器都支持__int64的写法,必须使用DataType.H中引入的定义 + + /** + * 文件信息数据结构 + */ + struct FileInfo ///文件信息 + { + os_char name[HGL_MAX_PATH]; ///<文件名(不包含路径) + os_char fullname[HGL_MAX_PATH]; ///<完整名称(包含路径) + + uint64 size; ///<文件长度 + + union + { + uint32 attrib; ///<文件属性 + + struct + { + bool is_file:1; ///<是文件 + bool is_directory:1; ///<是目录 + + bool is_hiddle:1; ///<是否隐藏文件 + +#if HGL_OS != HGL_OS_Windows + bool is_link:1; ///<是否是链接 +#endif//HGL_OS != HGL_OS_Windows + + bool can_read:1; ///<可以读 + bool can_write:1; ///<可以写 + }; + }; + + uint64 mtime; ///<最后修改日期(这个值在win/unix下不通用) + };//struct FileInfo + + bool GetFileInfo(const os_char *filename,struct FileInfo &); ///<取得文件信息 + + int GetFileInfoList(List &, const OSString &folder_name, bool proc_folder, bool proc_file, bool sub_folder); + }//namespace filesystem +}//namespace hgl +#endif//HGL_FILE_SYSTEM_INCLUDE diff --git a/inc/hgl/graph/BlendMode.h b/inc/hgl/graph/BlendMode.h deleted file mode 100644 index 58ade4e8..00000000 --- a/inc/hgl/graph/BlendMode.h +++ /dev/null @@ -1,21 +0,0 @@ -#ifndef HGL_GRAPH_BLEND_MODE_INCLUDE -#define HGL_GRAPH_BLEND_MODE_INCLUDE - -namespace hgl -{ - namespace graph - { - /** - * 混合模式数据结构 - */ - struct BlendMode ///混合模式 - { - struct - { - unsigned int src,dst; ///<混合因子 - unsigned int func; ///<混合方式 - }rgb,alpha; - };//struct BlendMode - //namespace graph -}//namespace hgl -#endif//HGL_GRAPH_BLEND_MODE_INCLUDE diff --git a/inc/hgl/graph/BufferData.h b/inc/hgl/graph/BufferData.h deleted file mode 100644 index e3eb3948..00000000 --- a/inc/hgl/graph/BufferData.h +++ /dev/null @@ -1,136 +0,0 @@ -#ifndef HGL_GRAPH_BUFFER_DATA_INCLUDE -#define HGL_GRAPH_BUFFER_DATA_INCLUDE - -#include -#include -namespace hgl -{ - namespace graph - { - /** - * 缓冲区数据管理类 - */ - class BufferData - { - protected: - - GLsizeiptr total_bytes; ///<数据总字节数 - - char * buffer_data; - - protected: - - friend BufferData *CreateBufferData(void *data,const GLsizeiptr &length); - - BufferData(char *data,const GLsizeiptr &length) - { - total_bytes =length; - buffer_data =data; - } - - public: - - virtual ~BufferData()=default; - - GLsizeiptr GetTotalBytes ()const {return total_bytes;} ///<取得数据总字节数 - void * GetData ()const {return buffer_data;} ///<取得数据指针 - };//class BufferData - - BufferData *CreateBufferData(const GLsizeiptr &length); - BufferData *CreateBufferData(void *data,const GLsizeiptr &length); - - class VertexBufferData:public BufferData - { - GLenum data_type; ///<单个数据类型 (GL_BYTE,GL_UNSIGNED_SHORT,GL_FLOAT等) - uint data_bytes; ///<单个数据字节数 (GL_BYTE为1,GL_UNSIGNED_SHORT为2,GL_FLOAT为4等) - uint data_comp; ///<数据成员数 (1/2/3/4,如2D纹理坐标用2,3D坐标/法线用3) - - uint data_stride; ///<每组数据字节数 - - GLsizeiptr data_count; ///<数据数量 - - protected: - - friend VertexBufferData *CreateVertexBufferData(void *data,const GLenum &dt,const uint &dbytes,const uint &dcm,const GLsizeiptr &count); - - VertexBufferData(const GLenum &dt,const uint &dbytes,const uint &dcm,const GLsizeiptr &count,char *data):BufferData(data,dbytes*dcm*count) - { - data_type=dt; - data_bytes=dbytes; - data_comp=dcm; - - data_stride=data_comp*data_bytes; - - data_count=count; - } - - public: - - virtual ~VertexBufferData()=default; - - GLenum GetDataType ()const{return data_type;} ///<取得数据类型 - uint GetComponent ()const{return data_comp;} ///<取数每一组数据中的数据数量 - uint GetStride ()const{return data_stride;} ///<取得每一组数据字节数 - - GLsizeiptr GetCount ()const{return data_count;} ///<取得数据数量 - GLsizeiptr GetTotalBytes ()const{return total_bytes;} ///<取得数据总字节数 - }; - - /** - * 创建一个顶点数据缓冲区
- * 这种方式创建的缓冲区,它会自行分配内存,最终释放 - * @param dt 单个数据类型 (GL_BYTE,GL_UNSIGNED_SHORT,GL_FLOAT等) - * @param dbytes 单个数据字节数 (GL_BYTE为1,GL_UNSIGNED_SHORT为2,GL_FLOAT为4等) - * @param dcm 数据成员数 (1/2/3/4,如2D纹理坐标用2,3D坐标/法线用3) - * @param count 数据数量 - */ - VertexBufferData *CreateVertexBufferData(const GLenum &dt,const uint &dbytes,const uint &dcm,const GLsizeiptr &count); - - /** - * 创建一个顶点数据缓冲区 - * @param data 数据指针 - * @param dt 单个数据类型 (GL_BYTE,GL_UNSIGNED_SHORT,GL_FLOAT等) - * @param dbytes 单个数据字节数 (GL_BYTE为1,GL_UNSIGNED_SHORT为2,GL_FLOAT为4等) - * @param dcm 数据成员数 (1/2/3/4,如2D纹理坐标用2,3D坐标/法线用3) - * @param count 数据数量 - */ - VertexBufferData *CreateVertexBufferData(void *data,const GLenum &dt,const uint &dbytes,const uint &dcm,const GLsizeiptr &count); - - #define VBDATA_CREATE_FUNC(type,gl_type,short_name) \ - inline VertexBufferData *VB1##short_name(const GLsizeiptr &count){return CreateVertexBufferData(gl_type,sizeof(type),1,count);} \ - inline VertexBufferData *VB2##short_name(const GLsizeiptr &count){return CreateVertexBufferData(gl_type,sizeof(type),2,count);} \ - inline VertexBufferData *VB3##short_name(const GLsizeiptr &count){return CreateVertexBufferData(gl_type,sizeof(type),3,count);} \ - inline VertexBufferData *VB4##short_name(const GLsizeiptr &count){return CreateVertexBufferData(gl_type,sizeof(type),4,count);} \ - \ - inline VertexBufferData *VB1##short_name(const GLsizeiptr &count,const type *data){return CreateVertexBufferData((void *)data,gl_type,sizeof(type),1,count);} \ - inline VertexBufferData *VB2##short_name(const GLsizeiptr &count,const type *data){return CreateVertexBufferData((void *)data,gl_type,sizeof(type),2,count);} \ - inline VertexBufferData *VB3##short_name(const GLsizeiptr &count,const type *data){return CreateVertexBufferData((void *)data,gl_type,sizeof(type),3,count);} \ - inline VertexBufferData *VB4##short_name(const GLsizeiptr &count,const type *data){return CreateVertexBufferData((void *)data,gl_type,sizeof(type),4,count);} - - VBDATA_CREATE_FUNC(int8, GL_BYTE, i8) - VBDATA_CREATE_FUNC(int8, GL_BYTE, b) - VBDATA_CREATE_FUNC(int16, GL_SHORT, i16) - VBDATA_CREATE_FUNC(int16, GL_SHORT, s) - VBDATA_CREATE_FUNC(int32, GL_INT, i32) - VBDATA_CREATE_FUNC(int32, GL_INT, i) - - VBDATA_CREATE_FUNC(uint8, GL_UNSIGNED_BYTE, u8) - VBDATA_CREATE_FUNC(uint8, GL_UNSIGNED_BYTE, ub) - VBDATA_CREATE_FUNC(uint16,GL_UNSIGNED_SHORT, u16) - VBDATA_CREATE_FUNC(uint16,GL_UNSIGNED_SHORT, us) - VBDATA_CREATE_FUNC(uint32,GL_UNSIGNED_INT, u32) - VBDATA_CREATE_FUNC(uint32,GL_UNSIGNED_INT, ui) - - VBDATA_CREATE_FUNC(uint16,GL_HALF_FLOAT, hf) - VBDATA_CREATE_FUNC(uint16,GL_HALF_FLOAT, f16) - VBDATA_CREATE_FUNC(float, GL_FLOAT, f) - VBDATA_CREATE_FUNC(float, GL_FLOAT, f32) - VBDATA_CREATE_FUNC(double,GL_DOUBLE, d) - VBDATA_CREATE_FUNC(double,GL_DOUBLE, f64) - #undef VBDATA_CREATE_FUNC - - inline VertexBufferData *EB16(const uint16 &count){return CreateVertexBufferData(GL_UNSIGNED_SHORT, 2,1,count);} - inline VertexBufferData *EB32(const uint32 &count){return CreateVertexBufferData(GL_UNSIGNED_INT, 4,1,count);} - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_BUFFER_DATA_INCLUDE diff --git a/inc/hgl/graph/BufferObject.h b/inc/hgl/graph/BufferObject.h deleted file mode 100644 index 4d8feb7b..00000000 --- a/inc/hgl/graph/BufferObject.h +++ /dev/null @@ -1,164 +0,0 @@ -#ifndef HGL_GRAPH_BUFFER_OBJECT_INCLUDE -#define HGL_GRAPH_BUFFER_OBJECT_INCLUDE - -#include -namespace hgl -{ - namespace graph - { - /** - * 显存数据缓冲区对象
- * 负责对象与API的交接 - */ - class BufferObject - { - protected: - - GLuint buffer_index; ///<缓冲区索引 - GLenum buffer_type; ///<缓冲区类型(GL_ARRAY_BUFFER,GL_ELEMENT_ARRAY_BUFFER等) - GLenum user_pattern; ///<数据存储区使用模式(GL_STATIC_DRAW,GL_DYNAMIC_DRAW等) - - GLsizeiptr buffer_bytes; - const BufferData *buffer_data; - - public: - - BufferObject(GLenum type); - virtual ~BufferObject(); - - public: - - GLuint GetBufferIndex ()const {return buffer_index;} ///<取得OpenGL缓冲区 - GLenum GetBufferType ()const {return buffer_type;} ///<取得缓冲区类型 - GLenum GetUserPattern ()const {return user_pattern;} ///<取得缓冲区使用方法 - - const BufferData *GetBufferData ()const {return buffer_data;} ///<取得缓冲数区(这里返回const是为了不想让只有BufferObject的模块可以修改数据) - const GLsizeiptr GetBufferSize ()const {return buffer_bytes;} ///<取得缓冲区总计字数 - - public: - - bool Create (GLsizeiptr); ///<创建数据区 - bool Submit (void *,GLsizeiptr,GLenum up=GL_STATIC_DRAW); ///<提交数据 - bool Submit (const BufferData *,GLenum up=GL_STATIC_DRAW); ///<提交数据 - bool Change (void *,GLsizeiptr,GLsizeiptr); ///<修改数据 - };//class BufferObject - - /** - * 显存顶点属性数据缓冲区对象 - */ - class VertexBufferObject:public BufferObject - { - public: - - using BufferObject::BufferObject; - ~VertexBufferObject()=default; - - const VertexBufferData *GetVertexBufferData()const{return (const VertexBufferData *)buffer_data;} - - #define VBD_FUNC_COPY(type,name) type Get##name()const{return buffer_data?((const VertexBufferData *)buffer_data)->Get##name():0;} - - VBD_FUNC_COPY(GLenum,DataType) - VBD_FUNC_COPY(uint,Component) - VBD_FUNC_COPY(uint,Stride) - VBD_FUNC_COPY(GLsizeiptr,Count) - - #undef VBD_FUNC_COPY - };//class VertexBufferObject:public BufferObject - - /** - * 创建一个缓冲区对象 - * @param buf_type 缓冲区类型(GL_ARRAY_BUFFER,GL_ELEMENT_ARRAY_BUFFER等) - * @param user_pattern 数据存储区使用模式(GL_STATIC_DRAW,GL_DYNAMIC_DRAW等) - * @param buf 数据缓冲区 - */ - template - inline BO *_CreateBufferObject(BD *buf=nullptr,const GLenum &user_pattern=GL_STATIC_DRAW) - { - BO *obj=new BO(); - - if(buf) - obj->Submit(buf,user_pattern); - - return(obj); - } - - ///** - // * 创建一个缓冲区对象 - // * @param buf_type 缓冲区类型(GL_ARRAY_BUFFER,GL_ELEMENT_ARRAY_BUFFER等) - // * @param user_pattern 数据存储区使用模式(GL_STATIC_DRAW,GL_DYNAMIC_DRAW等) - // * @param total_bytes 数据总字节数 - // */ - //template - //inline BO *_CreateBufferObject(const GLenum &buf_type,const GLenum &user_pattern,const GLsizeiptr &total_bytes) - //{ - // if(total_bytes<=0)return(nullptr); - - // BO *buf=new BO(buf_type); - - // //if(buf->Create(total_bytes,user_pattern)) - // // return buf; - - // delete buf; - // return(nullptr); - //} - - /** - * 创建一个缓冲区对象 - * @param buf_type 缓冲区类型(GL_ARRAY_BUFFER,GL_ELEMENT_ARRAY_BUFFER等) - * @param user_pattern 数据存储区使用模式(GL_STATIC_DRAW,GL_DYNAMIC_DRAW等) - * @param total_bytes 数据总字节数 - * @param data 数据指针 - */ - template - inline BO *_CreateBufferObject(void *data,const GLsizeiptr &total_bytes,const GLenum &user_pattern=GL_STATIC_DRAW) - { - if(total_bytes<=0)return(nullptr); - if(!data)return(nullptr); - - BO *buf=new BO(); - - //if(buf->Create(total_bytes,user_pattern)) - // return buf; - - if(buf->Submit(data,total_bytes,user_pattern)) - return buf; - - delete buf; - return(nullptr); - } - - #define VBCLASS_DEF(buffer_gl_type,buffer_class_name,BASE,data_name,short_name) \ - class buffer_class_name:public BASE \ - { \ - public: \ - \ - buffer_class_name():BASE(buffer_gl_type){} \ - ~buffer_class_name()=default; \ - }; \ - \ - inline buffer_class_name *Create##short_name() \ - { \ - return(new buffer_class_name()); \ - }; \ - \ - inline buffer_class_name *Create##short_name(data_name *buf=nullptr,const GLenum user_pattern=GL_STATIC_DRAW) \ - { \ - return _CreateBufferObject(buf,user_pattern); \ - }; \ - \ - inline buffer_class_name *Create##short_name(void *data,const GLsizeiptr &size,const GLenum &user_pattern=GL_STATIC_DRAW) \ - { \ - return _CreateBufferObject(data,size,user_pattern); \ - } - - //ps.在这里用宏了再用模板本是多此一举,但使用模板函数易于调试器中进行逐行调试,同时因为INLINE编译编译器也会自动展开代码,不用担心效率 - - VBCLASS_DEF(GL_ARRAY_BUFFER, ArrayBuffer, VertexBufferObject, VertexBufferData, VBO) - VBCLASS_DEF(GL_ELEMENT_ARRAY_BUFFER, ElementBuffer, VertexBufferObject, VertexBufferData, EBO) - VBCLASS_DEF(GL_UNIFORM_BUFFER, UniformBuffer, BufferObject, BufferData, UBO) - VBCLASS_DEF(GL_SHADER_STORAGE_BUFFER, ShaderStorageBuffer,BufferObject, BufferData, SSBO) - - #undef VBCLASS_DEF - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_BUFFER_OBJECT_INCLUDE diff --git a/inc/hgl/graph/Material.h b/inc/hgl/graph/Material.h deleted file mode 100644 index 9c911016..00000000 --- a/inc/hgl/graph/Material.h +++ /dev/null @@ -1,105 +0,0 @@ -#ifndef HGL_GRAPH_MATERIAL_INCLUDE -#define HGL_GRAPH_MATERIAL_INCLUDE - -#include -#include -#include -#include - -namespace hgl -{ - namespace graph - { - /** - * 假设 - * scene - * { - * mesh - * { - * Vertex - * TexCoordColor - * TexCoordNormal - * } - * - * texture - * { - * Color - * Normal - * } - * }; - * - * 有多种材质 - * - * material depth_render //只渲染深度,用于shadow maps或oq等 - * { - * in_vertex_attrib - * { - * Vertex - * } - * - * in_uniform - * { - * mvp - * } - * } - * - * material normal_render - * { - * in_vertex_attrib - * { - * Vertex, - * TexCoordColor, - * TexCoordNormal, - * } - * - * in_uniform - * { - * mvp - * light - * } - * } - */ - - - /** - * 渲染材质 - */ - class Material - { - protected: - - Shader *shader; - - protected: - -// Color4f Color; ///<颜色 -// -// -// float alpha_test; /// -namespace hgl -{ - namespace graph - { - /** - * 顶点象素成份枚举 - */ - enum PixelCompoment - { - HGL_PC_NONE=0, - - //单通道 - HGL_PC_ALPHA, - HGL_PC_DEPTH, - HGL_PC_LUMINANCE, - - //2通道 - HGL_PC_LUMINANCE_ALPHA, - - //3通道 - HGL_PC_RGB, - - //4通道 - HGL_PC_RGBA, - - //4通道 3+1模式 - HGL_PC_RGB_SPECULAR, - HGL_PC_RGB_DEPTH, - HGL_PC_NORMAL_HEIGHT, - - //4通道 2+2模式 - HGL_PC_RGB_NORMAL, - HGL_PC_NORMAL_TANGENT, - - HGL_PC_END - };//enum PixelCompoment - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_PIXEL_COMPENT_INCLUDE diff --git a/inc/hgl/graph/RenderDevice.h b/inc/hgl/graph/RenderDevice.h deleted file mode 100644 index f752dd74..00000000 --- a/inc/hgl/graph/RenderDevice.h +++ /dev/null @@ -1,136 +0,0 @@ -#ifndef HGL_RENDER_DEVICE_INCLUDE -#define HGL_RENDER_DEVICE_INCLUDE - -#include -#include -#include - -namespace hgl -{ - /** - * 显示模式数据结构 - */ - struct VideoMode - { - int width; ///<宽 - int height; ///<高 - int bit; ///<色彩位数 - int freq; ///<刷新率 - - int red; ///<红色位数 - int green; ///<绿色位数 - int blue; ///<蓝色位数 - };//struct VideoMode - - /** - * 显示屏数据结构 - */ - struct Display - { - UTF8String name; ///<显示屏名称 - int width,height; ///<显示屏尺寸(单位:毫米) - int x,y; ///<多显示屏时的排列位置 - - public: - - virtual const VideoMode *GetCurVideoMode()const=0; - virtual const ObjectList &GetVideoModeList()const=0; - }; - - struct WindowSetup - { - UTF8String Name; ///<窗口标题 - -// OSString IconFilename; ///<图标文件名称 -// OSString CursorFilename; ///<光标文件名称 - bool Edge =true; ///<是否显示边框 - - bool SysMenu =true; ///<是否显示系统菜单 - bool Right =false; ///<窗口是否使用靠右风格 - - bool Resize =false; ///<窗口大小是否可调整 - bool Minimize =false; ///<窗口是否可以最小化 - bool Maximize =false; ///<窗口是否可以最大化 - - bool TopMost =false; ///<永远在最上面 - bool AppTaskBar =true; ///<程序项在任务栏显示 - }; - - /** - * 渲染设备 - */ - struct RenderSetup - { - uint alpha; /// - * 该类是程序与操作系统或其它系统库的访问交接模块 - */ - class RenderDevice:public _Object - { - public: - - RenderDevice()=default; - virtual ~RenderDevice()=default; - - virtual const bool Init()=0; ///<初始化渲染设备 - virtual const void Close()=0; ///<关闭渲染设备 - - virtual const UTF8String GetName()=0; ///<取得设备名称 - - virtual const void GetDisplayList(List &)=0; ///<取得显示屏列表 - virtual const Display * GetDefaultDisplay()=0; ///<取得默认显示屏 - - public: - - virtual RenderWindow *Create(int,int,const WindowSetup *,const RenderSetup *)=0; ///<创建一个窗口渲染设备 - virtual RenderWindow *Create(const Display *,const VideoMode *,const RenderSetup *)=0; ///<创建一个全屏渲染设备 - };//class RenderDevice - - RenderDevice *CreateRenderDeviceGLFW(); ///<创建一个基于GLFW的渲染设备 -}//namespace hgl -#endif//HGL_RENDER_DEVICE_INCLUDE diff --git a/inc/hgl/graph/RenderDriver.h b/inc/hgl/graph/RenderDriver.h deleted file mode 100644 index e078c99b..00000000 --- a/inc/hgl/graph/RenderDriver.h +++ /dev/null @@ -1,14 +0,0 @@ -#ifndef HGL_RENDER_DRIVER_INCLUDE -#define HGL_RENDER_DRIVER_INCLUDE - -#include -namespace hgl -{ - namespace graph - { - void InitOpenGLDebug(); - - bool IsSupportDSA(); - }//namespace graph -}//namespace hgl -#endif//HGL_RENDER_DRIVER_INCLUDE diff --git a/inc/hgl/graph/RenderPass.h b/inc/hgl/graph/RenderPass.h deleted file mode 100644 index 24165371..00000000 --- a/inc/hgl/graph/RenderPass.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef HGL_GRAPH_RENDER_PASS_INCLUDE -#define HGL_GRAPH_RENDER_PASS_INCLUDE - -namespace hgl -{ - namespace graph - { - /** - * 单次渲染处理 - */ - class RenderPass - { - public: - - - };//class RenderPass - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_RENDER_PASS_INCLUDE - diff --git a/inc/hgl/graph/RenderState.h b/inc/hgl/graph/RenderState.h deleted file mode 100644 index 204143ac..00000000 --- a/inc/hgl/graph/RenderState.h +++ /dev/null @@ -1,181 +0,0 @@ -#ifndef HGL_RENDER_STATE_INCLUDE -#define HGL_RENDER_STATE_INCLUDE - -#include -//#include -#include -#include -namespace hgl -{ - namespace graph - { - struct RenderStateBlock - { - /** - * 应用当前状态 - */ - virtual void Apply()=0; - - /** - * 创建一个自身状态的复制品 - */ - virtual RenderStateBlock *CreateCopy()const=0; - };//struct RenderStateBlock - - #define RSB_OBJECT_BEGIN(rs_name) struct rs_name:public RenderStateBlock \ - { \ - rs_name()=default; \ - rs_name(const rs_name *obj){if(!obj)memcpy(this,obj,sizeof(rs_name));} \ - void Apply() override; \ - RenderStateBlock *CreateCopy()const override{return(new rs_name(this));} \ - \ - public: - - #define RSB_OBJECT_END }; - - RSB_OBJECT_BEGIN(ColorState) - bool red =true; - bool green =true; - bool blue =true; - bool alpha =true; - - bool clear_color=false; - GLfloat clear_color_value[4]={0,0,0,0}; - RSB_OBJECT_END - - enum class DEPTH_TEST - { - NEVER =GL_NEVER, - LESS =GL_LESS, - EQUAL =GL_EQUAL, - LEQUAL =GL_LEQUAL, - GREATER =GL_GREATER, - NOTEQUAL =GL_NOTEQUAL, - GEQUAL =GL_GEQUAL, - ALWAYS =GL_ALWAYS, - };//enum class DEPTH_TEST_FUNC - - RSB_OBJECT_BEGIN(DepthState) - GLfloat near_depth=0, - far_depth=1; - - bool depth_mask=true; - GLfloat clear_depth_value=far_depth; //清空深度时所用的值 - bool clear_depth; //是否要清空深度 - - DEPTH_TEST depth_func=DEPTH_TEST::LESS; - bool depth_test; - RSB_OBJECT_END - - enum class FACE - { - FRONT =GL_FRONT, - BACK =GL_BACK, - FRONT_AND_BACK =GL_FRONT_AND_BACK, - };//enum class CULL_FACE_MODE - - RSB_OBJECT_BEGIN(CullFaceState) - bool enabled =true; - FACE mode =FACE::BACK; - RSB_OBJECT_END - - enum class FILL_MODE - { - POINT =GL_POINT, - LINE =GL_LINE, - FACE =GL_FILL, - };//enum class FILL_MODE - - RSB_OBJECT_BEGIN(PolygonModeState) - FACE face=FACE::FRONT_AND_BACK; - FILL_MODE mode=FILL_MODE::FACE; - RSB_OBJECT_END - - /** - * 具体渲染状态数据 - */ - class RenderStateData:public RenderStateBlock - { - Set state_list; - - public: - - RenderStateData()=default; - RenderStateData(const RenderStateData *obj) - { - operator = (obj); - } - - RenderStateData(const RenderStateData &obj) - { - operator = (&obj); - } - - void Add(RenderStateBlock *rsb) - { - if(!rsb) - return; - - state_list.Add(rsb); - } - - void Apply() override - { - const int count=state_list.GetCount(); - - if(count<=0) - return; - - RenderStateBlock **rsb=state_list.GetData(); - - for(int i=0;iApply(); - ++rsb; - } - } - - RenderStateBlock *CreateCopy() const override - { - return(new RenderStateData(this)); - } - - void operator = (const RenderStateData *obj) - { - const int count=obj->state_list.GetCount(); - - if(count<=0)return; - - RenderStateBlock **rsb=obj->state_list.GetData(); - - for(int i=0;iCreateCopy()); - ++rsb; - } - } - };//class RenderStateData:public RenderStateBlock - - /** - * 渲染状态 - */ - class RenderState - { - RenderStateData state_data; - - public: - - RenderState()=default; - RenderState(const RenderStateData &rsd):state_data(rsd){} - virtual ~RenderState()=default; - - virtual void Add(RenderStateBlock *rsb) { state_data.Add(rsb); } - - virtual void Apply() - { - state_data.Apply(); - } - };//class RenderState - }//namespace graph -}//namespace hgl -#endif//HGL_RENDER_STATE_INCLUDE diff --git a/inc/hgl/graph/RenderWindow.h b/inc/hgl/graph/RenderWindow.h deleted file mode 100644 index 5917c8df..00000000 --- a/inc/hgl/graph/RenderWindow.h +++ /dev/null @@ -1,51 +0,0 @@ -#ifndef HGL_RENDER_WINDOW_INCLUDE -#define HGL_RENDER_WINDOW_INCLUDE - -#include -#include -namespace hgl -{ - /** - * 渲染窗口基类 - */ - class RenderWindow - { - protected: - - UTF8String caption; - bool full_screen; - - int width,height; - - public: - - const uint GetWidth()const{return width;} - const uint GetHeight()const{return height;} - const bool GetFullScreen()const{return full_screen;} - - public: //方法 - - RenderWindow()=default; ///<本类构造函数 - virtual ~RenderWindow()=default; ///<本类析构函数 - - virtual void ToMin()=0; ///<窗口最小化 - virtual void ToMax()=0; ///<窗口最大化 - - virtual void Show()=0; ///<显示窗口 - virtual void Hide()=0; ///<隐藏窗口 - - virtual const UTF8String &GetCaption()const{return caption;} - virtual void SetCaption(const UTF8String &)=0; - - public: //被实际操作系统接口层所调用的函数,在不了解的情况下请不要使用 - - virtual void SetSize(int w,int h)=0; ///<设置窗口大小 - - virtual void MakeToCurrent()=0; ///<切换到当前 - virtual void SwapBuffer()=0; ///<交换缓冲区 - virtual void WaitEvent(const double &time_out=0)=0; ///<等待下一个事件 - virtual void PollEvent()=0; ///<轮询事件 - virtual bool IsOpen()=0; ///<是否依然存在 - };//class RenderWindow -}//namespace hgl -#endif//HGL_RENDER_WINDOW_INCLUDE diff --git a/inc/hgl/graph/Renderable.h b/inc/hgl/graph/Renderable.h deleted file mode 100644 index f029b2dd..00000000 --- a/inc/hgl/graph/Renderable.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef HGL_GRAPH_RENDERABLE_INCLUDE -#define HGL_GRAPH_RENDERABLE_INCLUDE - -#include -#include - -namespace hgl -{ - namespace graph - { - /** - * 可渲染对象 - */ - class Renderable - { - protected: - - uint primitive; ///<绘制的图元类型 - VertexArray *vao; - -// Material *mtl; - - public: - - Renderable(uint prim,VertexArray *va=nullptr) - { - primitive=prim; - vao=va; - } - - const uint GetPrimitive()const { return primitive; } ///<取得要绘制的图元类型 - - public: - - uint GetDrawCount(); ///<取得可绘制的数据总数量 - bool Draw(); ///<绘制 - };//class Renderable - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_RENDERABLE_INCLUDE diff --git a/inc/hgl/graph/Shader.h b/inc/hgl/graph/Shader.h deleted file mode 100644 index f46aa1f6..00000000 --- a/inc/hgl/graph/Shader.h +++ /dev/null @@ -1,198 +0,0 @@ -#ifndef HGL_SHADER_INCLUDE -#define HGL_SHADER_INCLUDE - -#include -#include -#include -// #include -// #include -namespace hgl -{ - namespace graph - { - constexpr uint HGL_MAX_SHADER_NAME_LENGTH=128; ///<最大Shader名称长度 - - /** - * 着色程序类型枚举 - */ - enum ShaderType ///着色程序类型 - { - stVertex=0, ///<顶点着色程序 - stTessControl, ///<镶嵌控制着色程序(需OpenGL 4.0或ARB_tessellation_shader) - stTessEval, ///<镶嵌评估着色程序(需OpenGL 4.0或ARB_tessellation_shader) - stGeometry, ///<几何着色程序 - stFragment, ///<片断着色程序 - stCompute, ///<计算着色程序(需OpenGL 4.3或ARB_compute_shader) - - stEnd - };//enum ShaderType - - extern const char ShaderTypeName[ShaderType::stEnd][32]; ///<着色程序名称 - - /** - * 着色器程序 - */ - class Shader - { - uint program; - - uint shader_index[ShaderType::stEnd]; - - private: - - bool Link(); ///<连接使用当前着色程序 - - protected: - - Map attrib_location; - Map uniform_location; - - // Map uniform_block_index; - // MapObject uniform_block_object; - // - // Map ssbo_index; - // MapObject ssbo_object; - - int _GetAttribLocation(const char *); ///<取得指定属性地址 - int _GetUniformLocation(const char *); ///<取得一个变量的地址 - // int _GetUniformBlockIndex(const char *); ///<取得一个只读数据块的地址索引 - // int _GetShaderStorageIndex(const char *); ///<取得一个数据存储区的地址索引 - - public: - - Shader(){program=0;hgl_zero(shader_index,ShaderType::stEnd);} - ~Shader(){Clear();} - - void Clear(); ///<清除着色程序 - - bool AddShader (const int shader_type,const char *); ///<增加一个着色程序 - - bool AddVertexShader (const char *code){return AddShader(ShaderType::stVertex,code);} ///<增加一个顶点着色程序 - bool AddGeometryShader (const char *code){return AddShader(ShaderType::stGeometry,code);} ///<增加一个几何着色程序 - bool AddFragmentShader (const char *code){return AddShader(ShaderType::stFragment,code);} ///<增加一个片断着色程序 - bool AddComputeShader (const char *code){return AddShader(ShaderType::stFragment,code);} ///<增加一个计算着色程序 - - bool AddTessShader (const char *tess_control_shader,const char *tess_evaluation_shader) ///<增加一个镶嵌着色程序 - { - if(!AddShader(ShaderType::stTessControl,tess_control_shader ))return(false); - if(!AddShader(ShaderType::stTessEval, tess_evaluation_shader ))return(false); - return(true); - } - - bool Build(); ///<构建当前添加的着色程序 - - bool Use(); ///<使用当前着色程序 - - int GetAttribLocation(const char *); ///<取得指定属性地址 - int GetUniformLocation(const char *); ///<取得一个变量的地址 - // int GetUniformBlockIndex(const char *); ///<取得一个只读数据块索引 - // int GetShaderStorageIndex(const char *); ///<取得一个数据存储区索引 - - //bool SetAttrib1f(int,float); - //bool GetAttrib1f(int,float &); - - public: //设置一致变量用函数 - - bool SetUniform1f(int,float); - bool SetUniform2f(int,float,float); - bool SetUniform3f(int,float,float,float); - bool SetUniform4f(int,float,float,float,float); - - bool SetUniform1i(int,int); - bool SetUniform2i(int,int,int); - bool SetUniform3i(int,int,int,int); - bool SetUniform4i(int,int,int,int,int); - - bool SetUniform1ui(int,unsigned int); - bool SetUniform2ui(int,unsigned int,unsigned int); - bool SetUniform3ui(int,unsigned int,unsigned int,unsigned int); - bool SetUniform4ui(int,unsigned int,unsigned int,unsigned int,unsigned int); - - bool SetUniform1fv(int,int count,const float *); - bool SetUniform2fv(int,int count,const float *); - bool SetUniform3fv(int,int count,const float *); - bool SetUniform4fv(int,int count,const float *); - - bool SetUniform2fv(int index,const Vector2f &v){return SetUniform2fv(index,1,(const float *)&v);} - bool SetUniform3fv(int index,const Vector3f &v){return SetUniform3fv(index,1,(const float *)&v);} - bool SetUniform4fv(int index,const Vector4f &v){return SetUniform4fv(index,1,(const float *)&v);} - - bool SetUniform1iv(int,int count,const int *); - bool SetUniform2iv(int,int count,const int *); - bool SetUniform3iv(int,int count,const int *); - bool SetUniform4iv(int,int count,const int *); - - bool SetUniform1uiv(int,int count,const unsigned int *); - bool SetUniform2uiv(int,int count,const unsigned int *); - bool SetUniform3uiv(int,int count,const unsigned int *); - bool SetUniform4uiv(int,int count,const unsigned int *); - - bool SetUniformMatrix2fv(int,const float *); - bool SetUniformMatrix3fv(int,const float *); - bool SetUniformMatrix4fv(int,const float *); - - bool SetUniformMatrix2x3fv(int,const float *); - bool SetUniformMatrix3x2fv(int,const float *); - bool SetUniformMatrix2x4fv(int,const float *); - bool SetUniformMatrix4x2fv(int,const float *); - bool SetUniformMatrix3x4fv(int,const float *); - bool SetUniformMatrix4x3fv(int,const float *); - - public: - - bool SetUniform1f(const char *,float); - bool SetUniform2f(const char *,float,float); - bool SetUniform3f(const char *,float,float,float); - bool SetUniform4f(const char *,float,float,float,float); - - bool SetUniform1i(const char *,int); - bool SetUniform2i(const char *,int,int); - bool SetUniform3i(const char *,int,int,int); - bool SetUniform4i(const char *,int,int,int,int); - - bool SetUniform1ui(const char *,unsigned int); - bool SetUniform2ui(const char *,unsigned int,unsigned int); - bool SetUniform3ui(const char *,unsigned int,unsigned int,unsigned int); - bool SetUniform4ui(const char *,unsigned int,unsigned int,unsigned int,unsigned int); - - bool SetUniform1fv(const char *,int count,const float *); - bool SetUniform2fv(const char *,int count,const float *); - bool SetUniform3fv(const char *,int count,const float *); - bool SetUniform4fv(const char *,int count,const float *); - - bool SetUniform2fv(const char *name,const Vector2f &v){return SetUniform2fv(name,1,(const float *)&v);} - bool SetUniform3fv(const char *name,const Vector3f &v){return SetUniform3fv(name,1,(const float *)&v);} - bool SetUniform4fv(const char *name,const Vector4f &v){return SetUniform4fv(name,1,(const float *)&v);} - - bool SetUniform1iv(const char *,int count,const int *); - bool SetUniform2iv(const char *,int count,const int *); - bool SetUniform3iv(const char *,int count,const int *); - bool SetUniform4iv(const char *,int count,const int *); - - bool SetUniform1uiv(const char *,int count,const unsigned int *); - bool SetUniform2uiv(const char *,int count,const unsigned int *); - bool SetUniform3uiv(const char *,int count,const unsigned int *); - bool SetUniform4uiv(const char *,int count,const unsigned int *); - - bool SetUniformMatrix2fv(const char *,const float *); - bool SetUniformMatrix3fv(const char *,const float *); - bool SetUniformMatrix4fv(const char *,const float *); - - bool SetUniformMatrix3fv(const char *name,const Matrix3f &m){return SetUniformMatrix3fv(name,(const float *)&m);} - bool SetUniformMatrix4fv(const char *name,const Matrix4f &m){return SetUniformMatrix4fv(name,(const float *)&m);} - - bool SetUniformMatrix2x3fv(const char *,const float *); - bool SetUniformMatrix3x2fv(const char *,const float *); - bool SetUniformMatrix2x4fv(const char *,const float *); - bool SetUniformMatrix4x2fv(const char *,const float *); - bool SetUniformMatrix3x4fv(const char *,const float *); - bool SetUniformMatrix4x3fv(const char *,const float *); - - // public: //Uniform Block - // - // UBO *GetUniformBlock(const char *,uint=HGL_DYNAMIC_DRAW); - // SSBO *GetShaderStorage(const char *,uint=HGL_DYNAMIC_DRAW); - };//class Shader - }//namespace graph -}//namespace hgl -#endif//HGL_SHADER_INCLUDE diff --git a/inc/hgl/graph/Texture.h b/inc/hgl/graph/Texture.h deleted file mode 100644 index e858c409..00000000 --- a/inc/hgl/graph/Texture.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef HGL_GRAPH_TEXTURE_INCLUDE -#define HGL_GRAPH_TEXTURE_INCLUDE - -#include -#include -namespace hgl -{ - namespace graph - { - /** - * 贴图类 - */ - class Texture - { - protected: - - uint type; ///<纹理类型(如GL_TEXTURE_2D类) - - uint texture_id; ///<纹理ID - - uint pixel_format; ///<象素格式(如RED,RG,RGB,RGBA,SRGB,SRGBA之类) - uint video_format; ///<显存格式 - - public: - - Texture(uint t,uint tid) - { - type=t; - texture_id=tid; - - pixel_format=video_format=0; - } - - virtual ~Texture() - { - glDeleteTextures(1,&texture_id); - } - - public: - - uint GetID ()const{return texture_id;} ///<取得纹理ID - uint GetType ()const{return type;} ///<取得类型 - uint GetPixelFormat ()const{return pixel_format;} ///<取得象素格式 - uint GetVideoFormat ()const{return video_format;} ///<取得显存中的数据格式 - - public: - - virtual void GenMipmaps ()=0; ///<生成mipmaps - virtual void GetMipmapLevel (int &base_level,int &max_level)=0; ///<取得贴图mipmaps级别 - };//class Texture - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_TEXTURE_INCLUDE diff --git a/inc/hgl/graph/Texture1D.h b/inc/hgl/graph/Texture1D.h deleted file mode 100644 index 7844fec9..00000000 --- a/inc/hgl/graph/Texture1D.h +++ /dev/null @@ -1,68 +0,0 @@ -#ifndef HGL_GRAPH_TEXTURE_1D_INCLUDE -#define HGL_GRAPH_TEXTURE_1D_INCLUDE - -#include -namespace hgl -{ - namespace graph - { - struct Texture1DData; - - /** - * 1D贴图 - */ - class Texture1D:public Texture - { - protected: - - uint length; - - protected: - - virtual bool _SetImage (Texture1DData *)=0; - virtual int _GetImage (void *data_pointer, TSF fmt, int level)=0; - virtual bool _ChangeImage(uint s, uint l, void *data, uint bytes, TSF sf)=0; - - public: - - uint GetLength ()const{return length;} ///<取得纹理长度 - - public: - - Texture1D(uint tid):Texture(GL_TEXTURE_1D,tid) - { - length=0; - } - - bool SetImage (Texture1DData *); ///<创建1D贴图数据 - bool SetImage (uint l, TSF fmt) ///<创建1D贴图数据 - { - Texture1DData tex(l,fmt); - - return SetImage(&tex); - } - - bool SetImage (uint l, void *data, uint size, TSF sf, uint vf) - { - Texture1DData tex(l, data, size, sf, vf); - - return SetImage(&tex); - } - - bool ChangeImage (uint s,uint l,void *data,uint size,TSF sf); ///<更改1D贴图数据 - - int GetImage (void *data_pointer,TSF fmt,int level=0); ///<取得1D贴图数据 - - public: - - virtual void GenMipmaps ()=0; ///<生成mipmaps - virtual void GetMipmapLevel (int &base_level,int &max_level)=0; ///<取得贴图mipmaps级别 - };//class Texture1D - - Texture1D *CreateTexture1D(); - Texture1D *CreateTexture1D(Texture1DData *); - Texture1D *CreateTexture1D(uint length,TSF format); - Texture1D *CreateTexture1D(uint length,void *bitmap,uint bitmap_bytes,TSF source_format,uint video_format); - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_TEXTURE_1D_INCLUDE diff --git a/inc/hgl/graph/Texture2D.h b/inc/hgl/graph/Texture2D.h deleted file mode 100644 index b426ae75..00000000 --- a/inc/hgl/graph/Texture2D.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef HGL_GRAPH_TEXTURE_2D_INCLUDE -#define HGL_GRAPH_TEXTURE_2D_INCLUDE - -#include -namespace hgl -{ - namespace graph - { - /** - * 2D贴图 - */ - class Texture2D:public Texture - { - protected: - - uint width,height; ///<宽、高 - - virtual bool _SetImage (Texture2DData *tex)=0; - virtual int _GetImage (void *data_pointer, TSF fmt, int level,int width,int height)=0; - virtual bool _ChangeImage(uint l, uint t, uint w, uint h, void *data, uint bytes, TSF sf)=0; - - public: - - uint GetWidth ()const{return width;} ///<取得纹理宽度 - uint GetHeight ()const{return height;} ///<取得纹理高度 - - public: - - Texture2D(uint tid):Texture(GL_TEXTURE_2D,tid) - { - width=height=0; - } - - bool SetImage (Texture2DData *); ///<创建2D贴图数据 - bool SetImage (uint w, uint h, TSF fmt) - { - Texture2DData tex(w, h, fmt); - - return SetImage(&tex); - } - bool SetImage (uint w, uint h, void *data, uint size, TSF sf, uint vf) - { - Texture2DData tex(w,h,data,size,sf,vf); - - return SetImage(&tex); - } - - bool ChangeImage (uint l,uint t,uint w,uint h,void *,uint size, TSF sf); ///<更改贴图数据 - - int GetImage (void *data_pointer,TSF fmt,int level=0); ///<取得2D贴图数据 - };//class Texture2D - - Texture2D *CreateTexture2D(); - Texture2D *CreateTexture2D(Texture2DData *); - Texture2D *CreateTexture2D(uint width,uint height,TSF format); - Texture2D *CreateTexture2D(uint width,uint height,void *bitmap,uint bitmap_bytes,TSF source_format,uint video_format); - - Texture2D *CreateTexture2D(const OSString &,uint video_format=0); - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_TEXTURE_2D_INCLUDE diff --git a/inc/hgl/graph/TextureData.h b/inc/hgl/graph/TextureData.h deleted file mode 100644 index ba1d7d1f..00000000 --- a/inc/hgl/graph/TextureData.h +++ /dev/null @@ -1,184 +0,0 @@ -#ifndef HGL_GRAPH_TEXTURE_DATA_INCLUDE -#define HGL_GRAPH_TEXTURE_DATA_INCLUDE - -#include -namespace hgl -{ - namespace graph - { - /** - * 纹理数据 - */ - struct TextureData - { - const TextureFormat * source_format; ///<源始纹理格式 - - uint video_format; ///<显存格式 - - bool gen_mipmaps; ///<是否产生mipmaps - - void * bitmap; ///<位图数据 - - uint bitmap_bytes; ///<位图数据字节数 - - public: - - TextureData()=default; - virtual ~TextureData()=default; - - uint GetVideoFormat()const - { - return(video_format?video_format:source_format->video_format); - } - - uint GetPixelFormat()const - { - return(source_format?source_format->pixel_format:0); - } - - bool SetData(size_t this_size,TSF fmt) - { - if(!TextureSourceFormatCheck(fmt)) - { - hgl_zero(this,this_size); - return(false); - } - - gen_mipmaps=false; - bitmap = nullptr; - bitmap_bytes = 0; - - source_format = TextureFormatInfoList + fmt; //原始数据格式 - video_format = source_format->video_format; //显存格式 - - return(true); - } - - bool SetData(size_t this_size,void *data,uint size,TSF sf,uint vf) - { - if(data&&!TextureSourceFormatCheck(sf)) - { - hgl_zero(this,this_size); - return(false); - } - - gen_mipmaps = false; - bitmap = data; - bitmap_bytes = size; - - source_format = TextureFormatInfoList + sf; //原始数据格式 - video_format = vf ? vf : source_format->video_format; //显存格式 - return(true); - } - };//struct TextureData - - struct Texture1DData:public TextureData - { - uint length; - - public: - - Texture1DData() - { - hgl_zero(this, sizeof(Texture1DData)); - } - - Texture1DData(uint l, TSF fmt) - { - if(!SetData(sizeof(Texture1DData),fmt))return; - - length = l; - } - - Texture1DData(uint l, void *data, uint size, TSF sf, uint vf) - { - if(!SetData(sizeof(Texture1DData),data,size,sf,vf))return; - - length=l; - } - };//struct Texture1DData:public TextureData - - struct Texture2DData:public TextureData - { - uint width, height; - - public: - - Texture2DData() - { - hgl_zero(this, sizeof(Texture2DData)); - } - - Texture2DData(uint w, uint h, TSF fmt) - { - if(!SetData(sizeof(Texture2DData),fmt))return; - - width = w; - height = h; - } - - Texture2DData(uint w,uint h,void *data,uint size,TSF sf,uint vf) - { - if(!SetData(sizeof(Texture2DData),data,size,sf,vf))return; - - width=w; - height=h; - } - };//struct Texture2DData:public TextureData - - using TextureCubeMapData=Texture2DData; //cube map与2d参数一样,只是数据长6倍 - - struct Texture1DArrayData:public TextureData - { - uint length, count; - - public: - - Texture1DArrayData() - { - hgl_zero(this,sizeof(Texture1DArrayData)); - } - - Texture1DArrayData(uint l, uint c, TSF fmt) - { - if(!SetData(sizeof(Texture1DArrayData),fmt))return; - - length=l; - count=c; - } - - Texture1DArrayData(uint l,uint c,void *data,uint size,TSF sf,uint vf) - { - if(!SetData(sizeof(Texture1DArrayData),data,size,sf,vf))return; - - length=l; - count=c; - } - };//struct Texture1DArrayData:public TextureData - - struct Texture2DArrayData:public TextureData - { - uint width, height, count; - - public: - - Texture2DArrayData() - { - hgl_zero(this, sizeof(Texture2DArrayData)); - } - };//struct Texture2DArrayData:public TextureData - - struct Texture3DData:public TextureData - { - uint width, height, depth; - - public: - - Texture3DData() - { - hgl_zero(this, sizeof(Texture3DData)); - } - };//struct Texture3DData:public TextureData - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_TEXTURE_DATA_INCLUDE diff --git a/inc/hgl/graph/TextureFormat.h b/inc/hgl/graph/TextureFormat.h deleted file mode 100644 index aad8e764..00000000 --- a/inc/hgl/graph/TextureFormat.h +++ /dev/null @@ -1,146 +0,0 @@ -#ifndef HGL_GRAPH_TEXTURE_FORMAT_INCLUDE -#define HGL_GRAPH_TEXTURE_FORMAT_INCLUDE - -#include -#include -namespace hgl -{ - namespace graph - { - //贴图类型,核心模式,肯定支持array/cubemap - #define HGL_TEXTURE_1D GL_TEXTURE_1D - #define HGL_TEXTURE_2D GL_TEXTURE_2D - #define HGL_TEXTURE_3D GL_TEXTURE_3D - #define HGL_TEXTURE_RECTANGLE GL_TEXTURE_RECTANGLE //OpenGL 3.1 - #define HGL_TEXTURE_1D_ARRAY GL_TEXTURE_1D_ARRAY - #define HGL_TEXTURE_2D_ARRAY GL_TEXTURE_2D_ARRAY //OpenGL 3.0 - #define HGL_TEXTURE_CUBE_MAP GL_TEXTURE_CUBE_MAP - #define HGL_TEXTURE_CUBE_MAP_ARRAY GL_TEXTURE_CUBE_MAP_ARRAY //OpenGL 4.0 - #define HGL_TEXTURE_2D_MS GL_TEXTURE_2D_MULTISAMPLE - #define HGL_TEXTURE_2D_MS_ARRAY GL_TEXTURE_2D_MULTISAMPLE_ARRAY //OpenGL 3.2 - - #define HGL_TEXTURE_BUFFER GL_TEXTURE_BUFFER //TBO(OpenGL 3.1) - - // #define HGL_TEX_BIND_1D GL_TEXTURE_BINDING_1D - // #define HGL_TEX_BIND_2D GL_TEXTURE_BINDING_2D - // #define HGL_TEX_BIND_3D GL_TEXTURE_BINDING_3D - // #define HGL_TEX_BIND_RECTANGLE GL_TEXTURE_BINDING_RECTANGLE - // #define HGL_TEX_BIND_1D_ARRAY GL_TEXTURE_BINDING_1D_ARRAY - // #define HGL_TEX_BIND_2D_ARRAY GL_TEXTURE_BINDING_2D_ARRAY - // #define HGL_TEX_BIND_CUBE_MAP GL_TEXTURE_BINDING_CUBE_MAP - // #define HGL_TEX_BIND_CUBE_MAP_ARRAY GL_TEXTURE_BINDING_CUBE_MAP_ARRAY - // #define HGL_TEX_BIND_2D_MS GL_TEXTURE_BINDING_2D_MULTISAMPLE - // #define HGL_TEX_BIND_2D_MS_ARRAY GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY - // #define HGL_TEX_BIND_BUFFER GL_TEXTURE_BINDING_BUFFER - - //采样属性 - - //贴图寻址模式 - #define HGL_WRAP_CLAMP GL_CLAMP_TO_EDGE - #define HGL_WRAP_REPEAT GL_REPEAT - #define HGL_WRAP_MIRRORED_REPEAT GL_MIRRORED_REPEAT - - //贴图过滤模式 - #define HGL_FILTER_NEAREST GL_NEAREST - #define HGL_FILTER_LINEAR GL_LINEAR - #define HGL_FILTER_SMOOTH (GL_LINEAR+1) //(1.此功能为自行实现,使用GL_LINEAR+1只是为了区分。2.OpenGL 4.0以下使用性能较差) - - #define HGL_FILTER_NEAREST_MIPMAP_NEAREST GL_NEAREST_MIPMAP_NEAREST - #define HGL_FILTER_LINEAR_MIPMAP_NEAREST GL_LINEAR_MIPMAP_NEAREST - #define HGL_FILTER_NEAREST_MIPMAP_LINEAR GL_NEAREST_MIPMAP_LINEAR - #define HGL_FILTER_LINEAR_MIPMAP_LINEAR GL_LINEAR_MIPMAP_LINEAR - - //贴图象素格式 - #define HGL_DEPTH16 GL_DEPTH_COMPONENT16 - #define HGL_DEPTH24 GL_DEPTH_COMPONENT24 - #define HGL_DEPTH32 GL_DEPTH_COMPONENT32 - - #define HGL_R8 GL_R8 - #define HGL_R16 GL_R16 - #define HGL_RG8 GL_RG8 - #define HGL_RG16 GL_RG16 - - #define HGL_R3_G3_B2 GL_R3_G3_B2 - #define HGL_RGB4 GL_RGB4 - #define HGL_RGB5 GL_RGB5 - #define HGL_RGB8 GL_RGB8 - #define HGL_RGB10 GL_RGB10 - #define HGL_RGB12 GL_RGB12 - #define HGL_RGB16 GL_RGB16 - #define HGL_RGBA2 GL_RGBA2 - #define HGL_RGBA4 GL_RGBA4 - #define HGL_RGB5_A1 GL_RGB5_A1 - #define HGL_RGBA8 GL_RGBA8 - #define HGL_RGB10_A2 GL_RGB10_A2 - #define HGL_RGBA12 GL_RGBA12 - #define HGL_RGBA16 GL_RGBA16 - #define HGL_SRGB8 GL_SRGB8 - #define HGL_SRGB8_ALPHA8 GL_SRGB8_ALPHA8 - - #define HGL_R16F GL_R16F - #define HGL_RG16F GL_RG16F - #define HGL_RGB16F GL_RGB16F - #define HGL_RGBA16F GL_RGBA16F - - #define HGL_R32F GL_R32F - #define HGL_RG32F GL_RG32F - #define HGL_RGB32F GL_RGB32F - #define HGL_RGBA32F GL_RGBA32F - - #define HGL_RG11F_B10F GL_R11F_G11F_B10F - #define HGL_RGB9_E5 GL_RGB9_E5 - - //压缩贴图格式,核心模式无扩展,所以不用检测 - #define HGL_CR GL_COMPRESSED_RED - #define HGL_CRG GL_COMPRESSED_RG - #define HGL_CRGB GL_COMPRESSED_RGB - #define HGL_CRGBA GL_COMPRESSED_RGBA - - #define HGL_CSRGB GL_COMPRESSED_SRGB - #define HGL_CSRGBA GL_COMPRESSED_SRGB_ALPHA - - #define HGL_DXT1RGB GL_COMPRESSED_RGB_S3TC_DXT1_EXT - #define HGL_DXT1RGBA GL_COMPRESSED_RGBA_S3TC_DXT1_EXT - #define HGL_DXT3RGBA GL_COMPRESSED_RGBA_S3TC_DXT3_EXT - #define HGL_DXT5RGBA GL_COMPRESSED_RGBA_S3TC_DXT5_EXT - #define HGL_LATC1 GL_COMPRESSED_LUMINANCE_LATC1_EXT - #define HGL_LATC1s GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT - #define HGL_LATC2 GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT - #define HGL_LATC2s GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT - #define HGL_RGTC1 GL_COMPRESSED_RED_RGTC1 - #define HGL_RGTC1s GL_COMPRESSED_SIGNED_RED_RGTC1 - #define HGL_RGTC2 GL_COMPRESSED_RG_RGTC2 - #define HGL_RGTC2s GL_COMPRESSED_SIGNED_RG_RGTC2 - #define HGL_BPTC_RGBf GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB - #define HGL_BPTC_RGBuf GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB - #define HGL_BPTC_RGBA GL_COMPRESSED_RGBA_BPTC_UNORM_ARB - #define HGL_BPTC_SRGBA GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB - - inline const TextureFormat *GetTextureFormat(const TSF &tsf) - { - if(tsf<=HGL_SF_NONE||tsf>=HGL_SF_END) - return(nullptr); - - return TextureFormatInfoList+tsf; - } - - inline const uint GetVideoFormat(const TSF &tsf) - { - if (tsf <= HGL_SF_NONE || tsf >= HGL_SF_END) - return(0); - - return TextureFormatInfoList[tsf].video_format; - } - - inline const TextureFormat *GetTextureFormat(const char *format) - { - const TextureSourceFormat tsf= GetTextureFormatEnum(format); - - if(tsf<=HGL_SF_NONE||tsf>=HGL_SF_END) - return(nullptr); - - return TextureFormatInfoList+tsf; - } - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_TEXTURE_FORMAT_INCLUDE diff --git a/inc/hgl/graph/TextureSourceFormat.h b/inc/hgl/graph/TextureSourceFormat.h deleted file mode 100644 index 1f7dd4ba..00000000 --- a/inc/hgl/graph/TextureSourceFormat.h +++ /dev/null @@ -1,140 +0,0 @@ -#ifndef HGL_GRAPH_TEXTURE_SOURCE_FORMAT_INCLUDE -#define HGL_GRAPH_TEXTURE_SOURCE_FORMAT_INCLUDE - -#include -namespace hgl -{ - namespace graph - { - /** - * 贴图数据源格式 - */ - enum TextureSourceFormat:uint - { - HGL_SF_NONE=0, //无用,做为枚举起始 - - HGL_SF_R8, - HGL_SF_RG8, - HGL_SF_RGB8, - HGL_SF_RGBA8, - - HGL_SF_SRGB8, - HGL_SF_SRGBA8, - - HGL_SF_R16, - HGL_SF_RG16, - HGL_SF_RGB16, - HGL_SF_RGBA16, - - HGL_SF_R16F, - HGL_SF_RG16F, - HGL_SF_RGB16F, - HGL_SF_RGBA16F, - - HGL_SF_R32F, - HGL_SF_RG32F, - HGL_SF_RGB32F, - HGL_SF_RGBA32F, - - HGL_SF_UNCOMPRESSED, //无用,做为非压缩色分隔 - - HGL_SF_R3_G3_B2, - HGL_SF_RGB565, - - HGL_SF_RGBA4, - HGL_SF_RGB5_A1, - HGL_SF_RGB10_A2, - - HGL_SF_RG11F_B10F, - HGL_SF_RGB9_E5, - - HGL_SF_DEPTH, //无用,做为深度分隔 - - HGL_SF_DEPTH16, - HGL_SF_DEPTH24, - HGL_SF_DEPTH32, - - HGL_SF_DEPTH32F, - - HGL_SF_INDEX, //无用,做为索引色分隔 - - HGL_SF_INDEX_16_RGB, - HGL_SF_INDEX_16_RGBA, - HGL_SF_INDEX_256_RGB, - HGL_SF_INDEX_256_RGBA, - - HGL_SF_COMPRESSED, //无用,做为压缩格式分隔 - - //HGL_SF_CR, - //HGL_SF_CRG, - //HGL_SF_CRGB, - //HGL_SF_CRGBA, - - //HGL_SF_CSRGB, - //HGL_SF_CSRGBA, - - HGL_SF_DXT1RGB, - HGL_SF_DXT1RGBA, - HGL_SF_DXT3RGBA, - HGL_SF_DXT5RGBA, - - HGL_SF_LATC1, - HGL_SF_LATC1s, - HGL_SF_LATC2, - HGL_SF_LATC2s, - - HGL_SF_RGTC1, - HGL_SF_RGTC1s, - HGL_SF_RGTC2, - HGL_SF_RGTC2s, - - HGL_SF_BPTC_RGBf, - HGL_SF_BPTC_RGBuf, - HGL_SF_BPTC_RGBA, - HGL_SF_BPTC_SRGBA, - - HGL_SF_ETC2_RGB8, - HGL_SF_ETC2_SRGB8, - HGL_SF_ETC2_RGB8A1, - HGL_SF_ETC2_SRGB8A1, - HGL_SF_ETC2_RGBA8, - HGL_SF_ETC2_SRGBA8, - - HGL_SF_EAC_R11, - HGL_SF_EAC_R11s, - HGL_SF_EAC_RG11, - HGL_SF_EAC_RG11s, - - HGL_SF_END //无用,做为枚举结束 - };//enum TextureSourceFormat - - using TSF=TextureSourceFormat; - - bool TextureSourceFormatCheck(const TextureSourceFormat &); - bool TextureSourceFormatDepthCheck(const TextureSourceFormat &); - - struct TextureFormat - { - TextureSourceFormat tsf; //数据源格式枚举 - - char name[16]; //简写名称 - - bool compress; //是否压缩格式 - uint index; //索引色数量 - - uint video_format; //显存格式 - - uint pixel_format; //象素格式(指R/RG/RGB/RGBA/DEPTH这些) - uint data_type; //数据类型(指BYTE,SHORT,FLOAT这些) - - uint source_bytes; //原始格式字节数 - uint video_bytes; //显存格式字节数 - }; - - //贴图数据源格式信息 - extern const TextureFormat TextureFormatInfoList[HGL_SF_END]; - - TSF GetTextureFormatEnum(const char *); //根据简写名称取得对应的TextureSourceFormat - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_TEXTURE_SOURCE_FORMAT_INCLUDE diff --git a/inc/hgl/graph/VertexArray.h b/inc/hgl/graph/VertexArray.h deleted file mode 100644 index 75772c72..00000000 --- a/inc/hgl/graph/VertexArray.h +++ /dev/null @@ -1,53 +0,0 @@ -#ifndef HGL_GRAPH_VERTEX_ARRAY_INCLUDE -#define HGL_GRAPH_VERTEX_ARRAY_INCLUDE - -#include -#include -#include -namespace hgl -{ - namespace graph - { - /** - * 顶点阵列数据 - */ - class VertexArray - { - protected: - - GLuint vao; - - List vbo_list; ///<顶点数据缓冲区 - - ElementBuffer *element_buffer; - - ArrayBuffer *position_buffer; - int position_compoment; ///<位置属性格式 - - public: - - VertexArray(); - ~VertexArray(); - - static int GetMaxVertexAttrib(); - - const GLuint GetVAO ()const{return vao;} ///<取得VAO对象 - - public: //通用顶点缓冲区设置 - - int AddBuffer (int shader_location,ArrayBuffer *); ///<设置顶点缓冲区对象 - ArrayBuffer * GetBuffer (int index){return GetObject(vbo_list,index);} ///<取得顶点缓冲区对象 - bool ClearBuffer (int index){return vbo_list.Delete(index);} ///<清除顶点缓冲区对象 - void ClearBuffers(){ vbo_list.Clear();} ///<清除所有顶点缓冲区对象 - - public: //特殊缓冲区独立设置函数 - - bool SetElement (ElementBuffer *eb); ///<设置索引缓冲区对象 - bool SetPosition (int shader_location,ArrayBuffer *vb); ///<设置位置缓冲区对象 - - ElementBuffer * GetElement (){return element_buffer;} ///<获取索引缓冲区对象 - ArrayBuffer * GetPosition (){return position_buffer;} ///<获取位置缓冲区对象 - };//class VertexArray - }//namespace graph -}//namespace hgl -#endif//HGL_GRAPH_VERTEX_ARRAY_INCLUDE diff --git a/example/Vulkan/VK.h b/inc/hgl/graph/vulkan/VK.h similarity index 100% rename from example/Vulkan/VK.h rename to inc/hgl/graph/vulkan/VK.h diff --git a/example/Vulkan/VKBuffer.h b/inc/hgl/graph/vulkan/VKBuffer.h similarity index 100% rename from example/Vulkan/VKBuffer.h rename to inc/hgl/graph/vulkan/VKBuffer.h diff --git a/example/Vulkan/VKBufferData.h b/inc/hgl/graph/vulkan/VKBufferData.h similarity index 100% rename from example/Vulkan/VKBufferData.h rename to inc/hgl/graph/vulkan/VKBufferData.h diff --git a/example/Vulkan/VKCommandBuffer.h b/inc/hgl/graph/vulkan/VKCommandBuffer.h similarity index 100% rename from example/Vulkan/VKCommandBuffer.h rename to inc/hgl/graph/vulkan/VKCommandBuffer.h diff --git a/example/Vulkan/VKDescriptorSets.h b/inc/hgl/graph/vulkan/VKDescriptorSets.h similarity index 100% rename from example/Vulkan/VKDescriptorSets.h rename to inc/hgl/graph/vulkan/VKDescriptorSets.h diff --git a/example/Vulkan/VKDevice.h b/inc/hgl/graph/vulkan/VKDevice.h similarity index 97% rename from example/Vulkan/VKDevice.h rename to inc/hgl/graph/vulkan/VKDevice.h index 05b2182d..0426fea6 100644 --- a/example/Vulkan/VKDevice.h +++ b/inc/hgl/graph/vulkan/VKDevice.h @@ -4,10 +4,10 @@ #include #include #include -#include"VK.h" -#include"Window.h" -#include"VKDeviceAttribute.h" -#include"VKFramebuffer.h" +#include +#include +#include +#include VK_NAMESPACE_BEGIN struct PhysicalDevice; diff --git a/example/Vulkan/VKDeviceAttribute.h b/inc/hgl/graph/vulkan/VKDeviceAttribute.h similarity index 100% rename from example/Vulkan/VKDeviceAttribute.h rename to inc/hgl/graph/vulkan/VKDeviceAttribute.h diff --git a/example/Vulkan/VKFence.h b/inc/hgl/graph/vulkan/VKFence.h similarity index 100% rename from example/Vulkan/VKFence.h rename to inc/hgl/graph/vulkan/VKFence.h diff --git a/example/Vulkan/VKFormat.h b/inc/hgl/graph/vulkan/VKFormat.h similarity index 100% rename from example/Vulkan/VKFormat.h rename to inc/hgl/graph/vulkan/VKFormat.h diff --git a/example/Vulkan/VKFramebuffer.h b/inc/hgl/graph/vulkan/VKFramebuffer.h similarity index 100% rename from example/Vulkan/VKFramebuffer.h rename to inc/hgl/graph/vulkan/VKFramebuffer.h diff --git a/example/Vulkan/VKImageView.h b/inc/hgl/graph/vulkan/VKImageView.h similarity index 100% rename from example/Vulkan/VKImageView.h rename to inc/hgl/graph/vulkan/VKImageView.h diff --git a/example/Vulkan/VKInstance.h b/inc/hgl/graph/vulkan/VKInstance.h similarity index 96% rename from example/Vulkan/VKInstance.h rename to inc/hgl/graph/vulkan/VKInstance.h index 60cb2622..6d8725c9 100644 --- a/example/Vulkan/VKInstance.h +++ b/inc/hgl/graph/vulkan/VKInstance.h @@ -3,8 +3,8 @@ #include #include -#include"Window.h" -#include"VK.h" +#include +#include VK_NAMESPACE_BEGIN struct PhysicalDevice; diff --git a/example/Vulkan/VKMaterial.h b/inc/hgl/graph/vulkan/VKMaterial.h similarity index 100% rename from example/Vulkan/VKMaterial.h rename to inc/hgl/graph/vulkan/VKMaterial.h diff --git a/example/Vulkan/VKPhysicalDevice.h b/inc/hgl/graph/vulkan/VKPhysicalDevice.h similarity index 100% rename from example/Vulkan/VKPhysicalDevice.h rename to inc/hgl/graph/vulkan/VKPhysicalDevice.h diff --git a/example/Vulkan/VKPipeline.h b/inc/hgl/graph/vulkan/VKPipeline.h similarity index 100% rename from example/Vulkan/VKPipeline.h rename to inc/hgl/graph/vulkan/VKPipeline.h diff --git a/example/Vulkan/VKPrimivate.h b/inc/hgl/graph/vulkan/VKPrimivate.h similarity index 100% rename from example/Vulkan/VKPrimivate.h rename to inc/hgl/graph/vulkan/VKPrimivate.h diff --git a/example/Vulkan/VKRenderPass.h b/inc/hgl/graph/vulkan/VKRenderPass.h similarity index 100% rename from example/Vulkan/VKRenderPass.h rename to inc/hgl/graph/vulkan/VKRenderPass.h diff --git a/example/Vulkan/VKRenderable.h b/inc/hgl/graph/vulkan/VKRenderable.h similarity index 100% rename from example/Vulkan/VKRenderable.h rename to inc/hgl/graph/vulkan/VKRenderable.h diff --git a/example/Vulkan/VKSemaphore.h b/inc/hgl/graph/vulkan/VKSemaphore.h similarity index 100% rename from example/Vulkan/VKSemaphore.h rename to inc/hgl/graph/vulkan/VKSemaphore.h diff --git a/example/Vulkan/VKShaderModule.h b/inc/hgl/graph/vulkan/VKShaderModule.h similarity index 100% rename from example/Vulkan/VKShaderModule.h rename to inc/hgl/graph/vulkan/VKShaderModule.h diff --git a/example/Vulkan/VKShaderModuleManage.h b/inc/hgl/graph/vulkan/VKShaderModuleManage.h similarity index 94% rename from example/Vulkan/VKShaderModuleManage.h rename to inc/hgl/graph/vulkan/VKShaderModuleManage.h index 6813b016..62189523 100644 --- a/example/Vulkan/VKShaderModuleManage.h +++ b/inc/hgl/graph/vulkan/VKShaderModuleManage.h @@ -33,7 +33,7 @@ public: ~ShaderModuleManage(); const ShaderModule *CreateShader(const VkShaderStageFlagBits shader_stage_bit,const void *spv_data,const uint32_t spv_size); - const ShaderModule *CreateShader(const VkShaderStageFlagBits shader_stage_bit,const UTF8String &filename); + const ShaderModule *CreateShader(const VkShaderStageFlagBits shader_stage_bit,const OSString &filename); #define ADD_SHADER_FUNC(sn,vk_name) const ShaderModule *Create##sn##Shader(const void *spv_data,const uint32_t spv_size){return CreateShader(VK_SHADER_STAGE_##vk_name##_BIT,spv_data,spv_size);} ADD_SHADER_FUNC(Vertex, VERTEX) @@ -59,7 +59,7 @@ public: bool ReleaseShader (const ShaderModule *); Material * CreateMaterial(const VertexShaderModule *vertex_shader_module,const ShaderModule *fragment_shader_module)const; - Material * CreateMaterial(const UTF8String &vertex_shader_filename,const UTF8String &fragment_shader_filename) + Material * CreateMaterial(const OSString &vertex_shader_filename,const OSString &fragment_shader_filename) { const ShaderModule *vs=CreateShader(VK_SHADER_STAGE_VERTEX_BIT,vertex_shader_filename); diff --git a/example/Vulkan/VKShaderParse.h b/inc/hgl/graph/vulkan/VKShaderParse.h similarity index 100% rename from example/Vulkan/VKShaderParse.h rename to inc/hgl/graph/vulkan/VKShaderParse.h diff --git a/example/Vulkan/VKSurfaceExtensionName.h b/inc/hgl/graph/vulkan/VKSurfaceExtensionName.h similarity index 100% rename from example/Vulkan/VKSurfaceExtensionName.h rename to inc/hgl/graph/vulkan/VKSurfaceExtensionName.h diff --git a/example/Vulkan/VKVertexAttributeBinding.h b/inc/hgl/graph/vulkan/VKVertexAttributeBinding.h similarity index 100% rename from example/Vulkan/VKVertexAttributeBinding.h rename to inc/hgl/graph/vulkan/VKVertexAttributeBinding.h diff --git a/inc/hgl/io/DataInputStream.h b/inc/hgl/io/DataInputStream.h new file mode 100644 index 00000000..64b12ec1 --- /dev/null +++ b/inc/hgl/io/DataInputStream.h @@ -0,0 +1,231 @@ +#ifndef HGL_IO_DATA_INPUT_STREAM_INCLUDE +#define HGL_IO_DATA_INPUT_STREAM_INCLUDE + +#include +#include +#include +namespace hgl +{ + namespace io + { + class InputStream; + + /** + * 格式数据输入流基类 + */ + class DataInputStream ///格式数据输入流基类 + { + protected: + + InputStream *in; + + public: + + DataInputStream(InputStream *is) + { + in=is; + } + + virtual ~DataInputStream() + { + } + + virtual void Use(InputStream *is) + { + in=is; + } + + virtual int64 Read(void *buf,int64 size) + { + if(!buf||size<0)return(-1); + + return(in?in->Read(buf,size):-1); + } + + virtual int64 Peek(void *buf,int64 size) + { + if(!buf||size<0)return(-1); + + return(in?in->Peek(buf,size):-1); + } + + virtual int64 ReadFully(void *buf,int64 size) + { + if(!buf||size<0)return(-1); + + return(in?in->ReadFully(buf,size):-1); + } + + virtual int64 Seek(int64 offset,SeekOrigin so=soBegin) + { + return(in?in->Seek(offset,so):-1); + } + + virtual int64 Skip(int64 size) ///<跳过指定字节不访问 + { + return(in?in->Skip(size):-1); + } + + virtual bool CanRestart ()const{return in?in->CanRestart():false;} ///<是否可以复位 + virtual bool CanSeek ()const{return in?in->CanSeek ():false;} ///<是否可以定位 + virtual bool CanSize ()const{return in?in->CanSize ():false;} ///<是否可以取得尺寸 + virtual bool CanPeek ()const{return in?in->CanPeek ():false;} ///<是否可以预览数据 + + virtual bool Restart ()const{return in?in->Restart ():false;} ///<复位访问指针 + virtual int64 Tell ()const{return in?in->Tell ():-1;} ///<返回当前访问位置 + virtual int64 GetSize ()const{return in?in->GetSize ():-1;} ///<取得流长度 + virtual int64 Available ()const{return in?in->Available ():-1;} ///<剩下的可以不受阻塞读取的字节数 + + template bool ReadNumber(T &value); + + #define STREAM_READ(type,name) virtual bool Read##name(type &value) \ + { \ + return Read(value); \ + } \ + \ + virtual int64 Read##name(type *data,const int64 count) \ + { \ + if(count<=0)return(count); \ + if(!data)return(-1); \ + \ + return ReadArrays(data,count); \ + } + + STREAM_READ(char, Char ); + STREAM_READ(bool, Bool ); + STREAM_READ(int8, Int8 ); + STREAM_READ(uint8, Uint8 ); + + #undef STREAM_READ + + #define STREAM_READ(type,name) virtual bool Read##name(type &)=0; \ + virtual int64 Read##name(type *,const int64)=0; + + STREAM_READ(int16, Int16 ); + STREAM_READ(int32, Int32 ); + STREAM_READ(int64, Int64 ); + + STREAM_READ(uint16, Uint16 ); + STREAM_READ(uint32, Uint32 ); + STREAM_READ(uint64, Uint64 ); + + STREAM_READ(u16char, UTF16Char); + STREAM_READ(float, Float ); + STREAM_READ(double, Double ); + + #undef STREAM_READ + + bool Read(Vector2f &vec){return ReadFloat((float *)&vec,2)==2;} + bool Read(Vector3f &vec){return ReadFloat((float *)&vec,3)==3;} + bool Read(Vector4f &vec){return ReadFloat((float *)&vec,4)==4;} + + /** + * 自适应类型数据读取

+ * 请在多平台混用的情况下不要使用此函数,以免造成不同平台数据实质结构不一致的情况 + */ + template bool Read(T &data) + { + return(ReadFully(&data,sizeof(T))==sizeof(T)); + } + + /** + * 自适应类型数据阵列读取

+ * 请在多平台混用的情况下不要使用此函数,以免造成不同平台数据实质结构不一致的情况 + * @param data 数据存放区 + * @param count 数据个数 + * @return 实质读入的数据个数 + * @return <0 出错 + */ + template int64 ReadArrays(T *data,int64 count) + { + if(count<=0)return(count); + if(!data)return(-1); + + return ReadFully(data,count*sizeof(T))/sizeof(T); + } + + /** + * 自定义类型数据阵列读取

+ * 请在多平台混用的情况下不要使用此函数,以免造成不同平台数据实质结构不一致的情况 + * @param count 数据个数 + * @param alloc_count 分配数据个数(默认-1) + * @return 实质读入的数据指针,请使用delete[]释放 + * @return NULL 出错 + */ + template T *ReadArrays(int64 count) + { + if(count<=0)return(nullptr); + + T *data=new T[count]; + + if(data==0) + return(nullptr); + + if(ReadArrays(data,count)!=count) + { + delete[] data; + return(nullptr); + } + + return data; + } + + virtual bool ReadUTF16LEChars(u16char *,uint); ///<读取utf16-le格式字符阵列到u16char * + virtual bool ReadUTF16BEChars(u16char *,uint); ///<读取utf16-be格式字符阵列到u16char * + + //32bit str-length + virtual bool ReadUTF8String (char *, uint max_len=0); ///<读取utf8格式字符串(前缀四字节的字符串字节长度) + virtual bool ReadUTF8String (UTF8String &, uint max_len=0); ///<读取utf8格式字符串(前缀四字节的字符串字节长度) + virtual bool ReadUTF8String (UTF16String &, uint max_len=0); ///<读取utf8格式字符串(前缀四字节的字符串字节长度) + + virtual bool ReadUTF16LEString (u16char *, uint max_len=0); + virtual bool ReadUTF16BEString (u16char *, uint max_len=0); + + virtual bool ReadUTF16LEString (UTF16String &, uint max_len=0); ///<读取utf16-le格式字符串(前缀四字节的字符串字节长度) + virtual bool ReadUTF16BEString (UTF16String &, uint max_len=0); ///<读取utf16-be格式字符串(前缀四字节的字符串字节长度) + + //16bit str-length + virtual bool ReadUTF8ShortString (char *, uint max_len=0); + virtual bool ReadUTF8ShortString (UTF8String &, uint max_len=0); ///<读取utf8格式字符串(前缀四字节的字符串字节长度) + virtual bool ReadUTF8ShortString (UTF16String &, uint max_len=0); ///<读取utf8格式字符串(前缀四字节的字符串字节长度) + + virtual bool ReadUTF16LEShortString (u16char *, uint max_len=0); + virtual bool ReadUTF16BEShortString (u16char *, uint max_len=0); + + virtual bool ReadUTF16LEShortString (UTF16String &, uint max_len=0); ///<读取utf16-le格式字符串(前缀四字节的字符串字节长度) + virtual bool ReadUTF16BEShortString (UTF16String &, uint max_len=0); ///<读取utf16-be格式字符串(前缀四字节的字符串字节长度) + + //8bit str-length + virtual bool ReadUTF8TinyString (char *, uint max_len=0); + virtual bool ReadUTF8TinyString (UTF8String &, uint max_len=0); ///<读取utf8格式字符串(前缀四字节的字符串字节长度) + virtual bool ReadUTF8TinyString (UTF16String &, uint max_len=0); ///<读取utf8格式字符串(前缀四字节的字符串字节长度) + + virtual bool ReadUTF16LETinyString (u16char *, uint max_len=0); + virtual bool ReadUTF16BETinyString (u16char *, uint max_len=0); + + virtual bool ReadUTF16LETinyString (UTF16String &, uint max_len=0); ///<读取utf16-le格式字符串(前缀四字节的字符串字节长度) + virtual bool ReadUTF16BETinyString (UTF16String &, uint max_len=0); ///<读取utf16-be格式字符串(前缀四字节的字符串字节长度) + };//class DataInputStream + + template<> bool inline DataInputStream::ReadNumber(int8 &value){return ReadInt8(value);} + template<> bool inline DataInputStream::ReadNumber(uint8 &value){return ReadUint8(value);} + + #define DIS_READ_NUMBER(type,name) template<> bool inline DataInputStream::ReadNumber(type &value){return Read##name(value);} + + DIS_READ_NUMBER(int16, Int16 ); + DIS_READ_NUMBER(int32, Int32 ); + DIS_READ_NUMBER(int64, Int64 ); + + DIS_READ_NUMBER(uint16, Uint16 ); + DIS_READ_NUMBER(uint32, Uint32 ); + DIS_READ_NUMBER(uint64, Uint64 ); + + DIS_READ_NUMBER(u16char, UTF16Char); + DIS_READ_NUMBER(float, Float ); + DIS_READ_NUMBER(double, Double ); + + #undef DIS_READ_NUMBER + }//namespace io +}//namespace hgl +#include +#endif//HGL_IO_DATA_INPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/DataOutputStream.h b/inc/hgl/io/DataOutputStream.h new file mode 100644 index 00000000..ebccb501 --- /dev/null +++ b/inc/hgl/io/DataOutputStream.h @@ -0,0 +1,226 @@ +#ifndef HGL_IO_DATA_OUTPUT_STREAM_INCLUDE +#define HGL_IO_DATA_OUTPUT_STREAM_INCLUDE + +#include +#include +#include +#include +namespace hgl +{ + namespace io + { + class OutputStream; + + /** + * 格式数据输出流基类 + */ + class DataOutputStream ///格式数据输出流基类 + { + protected: + + OutputStream *out; + + public: + + DataOutputStream(OutputStream *os) + { + out=os; + } + + virtual ~DataOutputStream() + { + } + + virtual void Use(OutputStream *os) + { + out=os; + } + + virtual int64 Write(const void *buf,int64 size) + { + if(!buf||size<0)return(-1); + + return(out?out->Write(buf,size):-1); + } + + virtual int64 WriteFully(const void *buf,int64 size) + { + if(!buf||size<0)return(-1); + + return(out?out->WriteFully(buf,size):-1); + } + + virtual int64 Seek(int64 offset,SeekOrigin so=soBegin) + { + return(out?out->Seek(offset,so):-1); + } + + virtual bool CanRestart ()const{return out?out->CanRestart ():false;} ///<是否可以复位 + virtual bool CanSeek ()const{return out?out->CanSeek ():false;} ///<是否可以定位 + virtual bool CanSize ()const{return out?out->CanSize ():false;} ///<是否可以取得尺寸 + + virtual bool Restart ()const{return out?out->Restart ():false;} ///<复位访问指针 + virtual int64 Tell ()const{return out?out->Tell ():-1;} ///<返回当前访问位置 + virtual int64 GetSize ()const{return out?out->GetSize ():-1;} ///<取得流长度 + virtual int64 Available ()const{return out?out->Available ():-1;} ///<剩下的可以不受阻塞写入的字节数 + + template bool WriteNumber(const T &value); + + #define STREAM_WRITE(type,name) virtual bool Write##name(const type &value) \ + { \ + return Write(value); \ + } \ + \ + virtual int64 Write##name(const type *data,const int64 count) \ + { \ + if(count<=0)return(count); \ + if(!data)return(-1); \ + \ + return WriteArrays(data,count); \ + } + + STREAM_WRITE(char, Char ); + STREAM_WRITE(bool, Bool ); + STREAM_WRITE(int8, Int8 ); + STREAM_WRITE(uint8, Uint8 ); + + #undef STREAM_WRITE + + #define STREAM_WRITE(type,name) virtual bool Write##name(const type &)=0; \ + virtual int64 Write##name(const type *,const int64)=0; + + STREAM_WRITE(int16, Int16 ); + STREAM_WRITE(int32, Int32 ); + STREAM_WRITE(int64, Int64 ); + + STREAM_WRITE(uint16, Uint16 ); + STREAM_WRITE(uint32, Uint32 ); + STREAM_WRITE(uint64, Uint64 ); + + STREAM_WRITE(u16char, UTF16Char); + STREAM_WRITE(float, Float ); + STREAM_WRITE(double, Double ); + + #undef STREAM_WRITE + + bool Write(const Vector2f &vec){return WriteFloat((float *)&vec,2)==2;} + bool Write(const Vector3f &vec){return WriteFloat((float *)&vec,3)==3;} + bool Write(const Vector4f &vec){return WriteFloat((float *)&vec,4)==4;} + + /** + * 自适应类型数据写入

+ * 请在多平台混用的情况下不要使用此函数,以免造成不同平台数据实质结构不一致的情况 + */ + template bool Write(const T &data) + { + return WriteFully(&data,sizeof(T))==sizeof(T); + } + + /** + * 自适应类型数据阵列写入

+ * 请在多平台混用的情况下不要使用此函数,以免造成不同平台数据实质结构不一致的情况 + * @param data 数据 + * @param count 数据个数 + * @return 实质写入的数据个数 + * @return -1 出错 + */ + template int64 WriteArrays(const T *data,int64 count) + { + if(count<=0)return(count); + if(!data)return(-1); + + return WriteFully(data,count*sizeof(T))/sizeof(T); + } + + template bool WriteUTF8Chars (const T *str,uint count); ///<按utf8格式写入字符阵列 + template bool WriteUTF16LEChars (const T *str,uint count); ///<按utf16-le格式写入字符阵列 + template bool WriteUTF16BEChars (const T *str,uint count); ///<按utf16-be格式写入字符阵列 + + template bool WriteUTF8Chars (const BaseString &str){return WriteUTF8Chars (str.c_str(),str.Length());} + template bool WriteUTF16LEChars (const BaseString &str){return WriteUTF16LEChars (str.c_str(),str.Length());} + template bool WriteUTF16BEChars (const BaseString &str){return WriteUTF16BEChars (str.c_str(),str.Length());} + + template bool WriteUTF8StringWithLength (const char *str,const uint length); + template bool WriteUTF8StringWithLength (const UTF16String &str); + + template bool WriteUTF16StringWithLength(const u16char *str,const uint len); + + public: + + //32 bit length + bool WriteUTF8String (const char *str,uint length); ///<按utf16-le格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool WriteUTF8String (const char *str ); ///<按utf8格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool WriteUTF8String (const UTF8String &str ); ///<按utf8格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool WriteUTF8String (const UTF16String &str ); ///<按utf8格式写入字符串(前置4字节字符串长度,再写入字符阵列) + + bool WriteUTF16LEString (const u16char *str,uint len); ///<按utf16-le格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool WriteUTF16BEString (const u16char *str,uint len); ///<按utf16-be格式写入字符串(前置4字节字符串长度,再写入字符阵列) + + bool WriteUTF16LEString (const UTF16String &str ); ///<按utf16-le格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool WriteUTF16BEString (const UTF16String &str ); ///<按utf16-be格式写入字符串(前置4字节字符串长度,再写入字符阵列) + + bool WriteUTF16LEString (const u16char *str ); ///<按utf16-le格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool WriteUTF16BEString (const u16char *str ); ///<按utf16-be格式写入字符串(前置4字节字符串长度,再写入字符阵列) + + bool WriteUTF16LEString (const UTF8String &str ){return WriteUTF16LEString(to_u16(str));} ///<按utf16-le格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool WriteUTF16BEString (const UTF8String &str ){return WriteUTF16BEString(to_u16(str));} ///<按utf16-be格式写入字符串(前置4字节字符串长度,再写入字符阵列) + + //16 bit length + bool WriteUTF8ShortString (const char *str,uint length); ///<按utf16-le格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool WriteUTF8ShortString (const char *str ); ///<按utf8格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool WriteUTF8ShortString (const UTF8String &str ); ///<按utf8格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool WriteUTF8ShortString (const UTF16String &str ); ///<按utf8格式写入字符串(前置2字节字符串长度,再写入字符阵列) + + bool WriteUTF16LEShortString(const u16char *str,uint len); ///<按utf16-le格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool WriteUTF16BEShortString(const u16char *str,uint len); ///<按utf16-be格式写入字符串(前置2字节字符串长度,再写入字符阵列) + + bool WriteUTF16LEShortString(const UTF16String &str ); ///<按utf16-le格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool WriteUTF16BEShortString(const UTF16String &str ); ///<按utf16-be格式写入字符串(前置2字节字符串长度,再写入字符阵列) + + bool WriteUTF16LEShortString(const u16char *str ); ///<按utf16-le格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool WriteUTF16BEShortString(const u16char *str ); ///<按utf16-be格式写入字符串(前置2字节字符串长度,再写入字符阵列) + + bool WriteUTF16LEShortString(const UTF8String &str ){return WriteUTF16LEShortString(to_u16(str));} ///<按utf16-le格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool WriteUTF16BEShortString(const UTF8String &str ){return WriteUTF16BEShortString(to_u16(str));} ///<按utf16-be格式写入字符串(前置2字节字符串长度,再写入字符阵列) + + //8 bit length + bool WriteUTF8TinyString (const char *str,uint length); ///<按utf16-le格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool WriteUTF8TinyString (const char *str ); ///<按utf8格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool WriteUTF8TinyString (const UTF8String &str ); ///<按utf8格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool WriteUTF8TinyString (const UTF16String &str ); ///<按utf8格式写入字符串(前置1字节字符串长度,再写入字符阵列) + + bool WriteUTF16LETinyString (const u16char *str,uint len); ///<按utf16-le格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool WriteUTF16BETinyString (const u16char *str,uint len); ///<按utf16-be格式写入字符串(前置1字节字符串长度,再写入字符阵列) + + bool WriteUTF16LETinyString (const UTF16String &str ); ///<按utf16-le格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool WriteUTF16BETinyString (const UTF16String &str ); ///<按utf16-be格式写入字符串(前置1字节字符串长度,再写入字符阵列) + + bool WriteUTF16LETinyString (const u16char *str ); ///<按utf16-le格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool WriteUTF16BETinyString (const u16char *str ); ///<按utf16-be格式写入字符串(前置1字节字符串长度,再写入字符阵列) + + bool WriteUTF16LETinyString (const UTF8String &str ){return WriteUTF16LETinyString(to_u16(str));} ///<按utf16-le格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool WriteUTF16BETinyString (const UTF8String &str ){return WriteUTF16BETinyString(to_u16(str));} ///<按utf16-be格式写入字符串(前置1字节字符串长度,再写入字符阵列) + };//class DataOutputStream + + template<> bool inline DataOutputStream::WriteNumber(const int8 &value){return WriteInt8(value);} + template<> bool inline DataOutputStream::WriteNumber(const uint8 &value){return WriteUint8(value);} + + #define DOS_WRITE_NUMBER(type,name) template<> bool inline DataOutputStream::WriteNumber(const type &value){return Write##name(value);} + + DOS_WRITE_NUMBER(int16, Int16 ); + DOS_WRITE_NUMBER(int32, Int32 ); + DOS_WRITE_NUMBER(int64, Int64 ); + + DOS_WRITE_NUMBER(uint16, Uint16 ); + DOS_WRITE_NUMBER(uint32, Uint32 ); + DOS_WRITE_NUMBER(uint64, Uint64 ); + + DOS_WRITE_NUMBER(u16char, UTF16Char); + DOS_WRITE_NUMBER(float, Float ); + DOS_WRITE_NUMBER(double, Double ); + + #undef DOS_WRITE_NUMBER + }//namespace io +}//namespace hgl +#include +#endif//HGL_IO_DATA_OUTPUT_STREAM_INCLUDEs diff --git a/inc/hgl/io/EndianDataInputStream.h b/inc/hgl/io/EndianDataInputStream.h new file mode 100644 index 00000000..c313e066 --- /dev/null +++ b/inc/hgl/io/EndianDataInputStream.h @@ -0,0 +1,100 @@ +#ifndef HGL_IO_ENDIAN_DATA_INPUT_STREAM_INCLUDE +#define HGL_IO_ENDIAN_DATA_INPUT_STREAM_INCLUDE + +#include +#include +namespace hgl +{ + namespace io + { + class DirectDataInputStream:public DataInputStream + { + public: + + using DataInputStream::DataInputStream; + virtual ~DirectDataInputStream()=default; + + #define STREAM_DIRECT_READ(type,name) virtual bool Read##name(type &value) \ + { \ + return Read(value); \ + } \ + \ + virtual int64 Read##name(type *data,const int64 count) \ + { \ + if(count<=0)return(count); \ + if(!data)return(-1); \ + \ + return ReadArrays(data,count); \ + } + + STREAM_DIRECT_READ(int16, Int16 ); + STREAM_DIRECT_READ(int32, Int32 ); + STREAM_DIRECT_READ(int64, Int64 ); + + STREAM_DIRECT_READ(uint16, Uint16 ); + STREAM_DIRECT_READ(uint32, Uint32 ); + STREAM_DIRECT_READ(uint64, Uint64 ); + + STREAM_DIRECT_READ(u16char,UTF16Char); + STREAM_DIRECT_READ(float, Float ); + STREAM_DIRECT_READ(double, Double ); + + #undef STREAM_DIRECT_READ + };//class DirectDataInputStream + + class SwapDataInputStream:public DataInputStream + { + public: + + using DataInputStream::DataInputStream; + virtual ~SwapDataInputStream()=default; + + #define STREAM_SWAP_READ(type,name) virtual bool Read##name(type &value) \ + {\ + type swap_value; \ + \ + if(!Read(swap_value)) \ + return(false); \ + \ + value=EndianSwap(swap_value); \ + return(true); \ + } \ + \ + virtual int64 Read##name(type *data,const int64 count) \ + { \ + if(count<=0)return(count); \ + if(!data)return(-1); \ + \ + const int64 result=ReadArrays(data,count); \ + \ + if(result<=0)return(result); \ + \ + EndianSwap(data,result); \ + return(result); \ + } + + STREAM_SWAP_READ(int16, Int16 ); + STREAM_SWAP_READ(int32, Int32 ); + STREAM_SWAP_READ(int64, Int64 ); + + STREAM_SWAP_READ(uint16, Uint16 ); + STREAM_SWAP_READ(uint32, Uint32 ); + STREAM_SWAP_READ(uint64, Uint64 ); + + STREAM_SWAP_READ(u16char, UTF16Char); + STREAM_SWAP_READ(float, Float ); + STREAM_SWAP_READ(double, Double ); + + #undef STREAM_SWAP_READ + };//class SwapDataInputStream + +#if HGL_ENDIAN == HGL_LITTLE_ENDIAN + typedef DirectDataInputStream LEDataInputStream; + typedef SwapDataInputStream BEDataInputStream; +#else + typedef DirectDataInputStream BEDataInputStream; + typedef SwapDataInputStream LEDataInputStream; +#endif//HGL_ENDIAN == HGL_LITTLE_ENDIAN + }//namespace io +}//namespace hgl +#endif//HGL_IO_ENDIAN_DATA_INPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/EndianDataOutputStream.h b/inc/hgl/io/EndianDataOutputStream.h new file mode 100644 index 00000000..66fbfb8c --- /dev/null +++ b/inc/hgl/io/EndianDataOutputStream.h @@ -0,0 +1,103 @@ +#ifndef HGL_IO_ENDIAN_DATA_OUTPUT_STREAM_INCLUDE +#define HGL_IO_ENDIAN_DATA_OUTPUT_STREAM_INCLUDE + +#include +#include +namespace hgl +{ + namespace io + { + class DirectDataOutputStream:public DataOutputStream + { + public: + + DirectDataOutputStream(OutputStream *os):DataOutputStream(os) + { + } + + virtual ~DirectDataOutputStream() + { + } + + #define STREAM_DIRECT_WRITE(type,name) virtual bool Write##name(const type &value) \ + { \ + return Write(value); \ + } \ + \ + virtual int64 Write##name(const type *data,const int64 count) \ + { \ + if(count<=0)return(count); \ + if(!data)return(-1); \ + \ + return WriteArrays(data,count); \ + } + + STREAM_DIRECT_WRITE(int16, Int16 ); + STREAM_DIRECT_WRITE(int32, Int32 ); + STREAM_DIRECT_WRITE(int64, Int64 ); + + STREAM_DIRECT_WRITE(uint16, Uint16 ); + STREAM_DIRECT_WRITE(uint32, Uint32 ); + STREAM_DIRECT_WRITE(uint64, Uint64 ); + + STREAM_DIRECT_WRITE(u16char,UTF16Char); + STREAM_DIRECT_WRITE(float, Float ); + STREAM_DIRECT_WRITE(double, Double ); + + #undef STREAM_DIRECT_WRITE + };//class DirectDataOutputStream + + class SwapDataOutputStream:public DataOutputStream + { + public: + + SwapDataOutputStream(OutputStream *os):DataOutputStream(os) + { + } + + virtual ~SwapDataOutputStream() + { + } + + #define STREAM_SWAP_WRITE(type,name) virtual bool Write##name(const type &value) \ + {\ + return Write(EndianSwap(value)); \ + } \ + \ + virtual int64 Write##name(const type *data,const int64 count) \ + { \ + if(count<=0)return(count); \ + if(!data)return(-1); \ + \ + SharedArray swap_data=new type[count]; \ + \ + EndianSwap(swap_data,data,count); \ + \ + return WriteArrays(swap_data,count); \ + } + + STREAM_SWAP_WRITE(int16, Int16 ); + STREAM_SWAP_WRITE(int32, Int32 ); + STREAM_SWAP_WRITE(int64, Int64 ); + + STREAM_SWAP_WRITE(uint16, Uint16 ); + STREAM_SWAP_WRITE(uint32, Uint32 ); + STREAM_SWAP_WRITE(uint64, Uint64 ); + + STREAM_SWAP_WRITE(u16char, UTF16Char); + STREAM_SWAP_WRITE(float, Float ); + STREAM_SWAP_WRITE(double, Double ); + + #undef STREAM_SWAP_WRITE + };//class SwapDataOutputStream + +#if HGL_ENDIAN == HGL_LITTLE_ENDIAN + typedef DirectDataOutputStream LEDataOutputStream; + typedef SwapDataOutputStream BEDataOutputStream; +#else + typedef DirectDataOutputStream BEDataOutputStream; + typedef SwapDataOutputStream LEDataOutputStream; +#endif//HGL_ENDIAN == HGL_LITTLE_ENDIAN + }//namespace io +}//namespace hgl +#endif//HGL_IO_ENDIAN_DATA_OUTPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/FileAccess.h b/inc/hgl/io/FileAccess.h new file mode 100644 index 00000000..8d61fe2f --- /dev/null +++ b/inc/hgl/io/FileAccess.h @@ -0,0 +1,83 @@ +#ifndef HGL_IO_FILE_ACCESS_INCLUDE +#define HGL_IO_FILE_ACCESS_INCLUDE + +#include +#include +#include +namespace hgl +{ + namespace io + { + enum FileOpenMode ///文件访问模式枚举 + { + fomNone=0, + + fomCreate, ///<创建文件,如存在则失败 + fomCreateTrunc, ///<强制创建,如存在则抹掉 + fomCreateTemp, + fomOnlyRead, ///<只读方式 + fomOnlyWrite, ///<只写方式 + fomReadWrite, ///<可读可写 + fomAppend, ///<追加模式 + + fomEnd + };//enum FileOpenMode + + /** + * 文件访问实例管理类 + */ + class FileAccess ///文件访问实例管理类 + { + protected: + + OSString filename; + + int fp; + + struct_stat64 file_state; + + FileOpenMode mode; + + public: + + FileAccess(); + virtual ~FileAccess(); + + virtual bool Open(const OSString &,FileOpenMode fom); ///<以指定模式打开一个文件 + virtual bool Create(const OSString &fn){return Open(fn,fomCreate);} ///<创建一个新文件,如文件已存在则创建失败 + virtual bool CreateTrunc(const OSString &fn){return Open(fn,fomCreateTrunc);} ///<创建一个新文件,如文件已存在则抹消它 + virtual bool OpenRead(const OSString &fn){return Open(fn,fomOnlyRead);} ///<以只读模式打开一个文件 + virtual bool OpenWrite(const OSString &fn){return Open(fn,fomOnlyWrite);} ///<以只写模式打开一个文件 + virtual bool OpenReadWrite(const OSString &fn){return Open(fn,fomReadWrite);} ///<以读写模式打开一个文件 + virtual bool CreateTemp(); + + virtual void Close(); ///<关闭文件 + virtual void CloseRead(); ///<仅关闭读取 + virtual void CloseWrite(); ///<仅关闭写入 + + virtual int GetFileHandle()const{return fp;} + + virtual bool CanRead()const; ///<文件是否可读 + virtual bool CanPeek()const{return(CanRead()&&CanSeek());} ///<文件是否可预读 + virtual bool CanWrite()const; ///<文件是否可写 + virtual bool CanSeek()const; ///<文件是否可定位访问指针 + virtual bool CanRestart()const{return CanSeek();} ///<文件是否可复位访问 + virtual bool CanSize()const{return(true);} ///<文件是否可取得长度 + + virtual int64 Seek(int64,SeekOrigin=soBegin); ///<定位访问指针 + virtual int64 Tell()const; ///<取得访问指针位置 + virtual int64 GetSize(); ///<取得文件长度 + virtual bool Restart(); ///<复位访问指针 + + virtual int64 Read(void *,int64); ///<读取指定长度数据 + virtual int64 Peek(void *,int64); ///<预读指定长度数据 + virtual int64 Write(const void *,int64); ///<写入指定长度数据 + + virtual int64 AvailableRead(); ///<剩下的可读数据 + + virtual int64 Read(int64,void *,int64); ///<在指定位置读取指定长度的数据 + virtual int64 Write(int64,const void *,int64); ///<在指定位置写入指定长度的数据 + };//class FileAccess + }//namespace io +}//namespace hgl +#endif//HGL_IO_FILE_ACCESS_INCLUDE diff --git a/inc/hgl/io/FileInputStream.h b/inc/hgl/io/FileInputStream.h new file mode 100644 index 00000000..5490bf2a --- /dev/null +++ b/inc/hgl/io/FileInputStream.h @@ -0,0 +1,78 @@ +#ifndef HGL_IO_FILE_INPUT_STREAM_INCLUDE +#define HGL_IO_FILE_INPUT_STREAM_INCLUDE + +#include +#include +namespace hgl +{ + namespace io + { + /** + * 文件输入流类 + */ + class FileInputStream:public InputStream ///文件输入流类 + { + protected: + + SharedPtr file; ///<文件访问指针 + + public: + + FileInputStream(); + FileInputStream(SharedPtr &); + virtual ~FileInputStream(); + + virtual bool Open(const OSString &); ///<打开文件 + virtual void Close(); ///<关闭文件输入流 + + virtual int GetFileHandle()const{return file->GetFileHandle();} + + virtual int64 Read(void *,int64); ///<读取数据 + virtual int64 Peek(void *,int64); ///<预读数据 + + virtual bool CanSeek()const; ///<是否可移动访问指针 + virtual bool CanRestart()const; ///<是否可复位访问 + virtual bool CanSize()const; ///<是否可访问文件长度 + virtual bool CanPeek()const; ///<是否可预读数据 + + virtual int64 Skip(int64); ///<跳过指定字节 + virtual int64 Tell()const; ///<取当前位置 + virtual int64 GetSize()const; ///<取得文件长度 + virtual bool Restart(); ///<复位访问指针 + virtual int64 Seek(int64,SeekOrigin=soBegin); ///<移动访问指针 + + virtual int64 Available()const; ///<剩下的可以不受阻塞访问的字节数 + + virtual int64 Read(int64,void *,int64); ///<在指定位置读取指定长度的数据 + };//class FileInputStream + + class OpenFileInputStream + { + FileInputStream *fis; + + public: + + OpenFileInputStream(const OSString &filename) + { + fis=new FileInputStream(); + + if(!fis->Open(filename)) + { + delete fis; + fis=nullptr; + } + } + + ~OpenFileInputStream() + { + SAFE_CLEAR(fis); + } + + const bool operator !(){return !fis;} + operator FileInputStream *(){return fis;} + FileInputStream *operator &(){return fis;} + FileInputStream *operator ->(){return fis;} + };//class OpenFileInputStream + }//namespace io +}//namespace hgl +#endif//HGL_IO_FILE_INPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/FileOutputStream.h b/inc/hgl/io/FileOutputStream.h new file mode 100644 index 00000000..ca497a84 --- /dev/null +++ b/inc/hgl/io/FileOutputStream.h @@ -0,0 +1,93 @@ +#ifndef HGL_IO_FILE_OUTPUT_STREAM_INCLUDE +#define HGL_IO_FILE_OUTPUT_STREAM_INCLUDE + +#include +#include +namespace hgl +{ + namespace io + { + /** + * 文件输出流类 + */ + class FileOutputStream:public OutputStream ///文件输出流类 + { + protected: + + SharedPtr file; ///<文件访问指针 + + virtual bool OpenFile(const OSString &,FileOpenMode); + + public: + + FileOutputStream(); + FileOutputStream(SharedPtr &); + virtual ~FileOutputStream(); + + virtual bool Open(const OSString &fn,FileOpenMode mode){return OpenFile(fn,mode);} ///<打开文件,指定一个模式 + virtual bool Open(const OSString &fn){return OpenFile(fn,fomOnlyWrite);} ///<打开文件 + virtual bool Create(const OSString &fn){return OpenFile(fn,fomCreate);} ///<创建文件,如存在创建失败 + virtual bool CreateTrunc(const OSString &fn){return OpenFile(fn,fomCreateTrunc);} ///<创建文件,如存在则抹去 + virtual bool OpenAppend(const OSString &fn){return OpenFile(fn,fomAppend);} ///<打开文件,追加模式 + + virtual void Close(); ///<关闭文件 + + virtual int64 Write(const void *,int64); ///<写入数据 + + virtual bool CanSeek()const; ///<是否可移动访问指针 + virtual bool CanRestart()const; ///<是否可复位访问 + virtual bool CanSize()const; ///<是否可访问文件长度 + + virtual int64 Tell()const; ///<取当前位置 + virtual int64 GetSize()const; ///<取得文件长度 + virtual bool Restart(); ///<复位访问指针 + virtual int64 Seek(int64,SeekOrigin=soBegin); ///<移动访问指针 + virtual int64 Available()const{return -1;} ///<可不受影响写入的字节数 + + virtual int64 Write(int64,const void *,int64); ///<在指定位置写入指定长度的数据 + };//class FileOutputStream + + /** + * 打开一个文件输出流 + */ + class OpenFileOutputStream + { + FileOutputStream *fos; + + public: + + OpenFileOutputStream() + { + fos=nullptr; + } + + /** + * 打开一个文件输出流构造函数 + * @param filename 文件名 + * @param mode 打开模式,默认只写(必然可读) + * @see FileOpenMode + */ + OpenFileOutputStream(const OSString &filename,FileOpenMode mode=fomOnlyWrite) + { + fos=new FileOutputStream(); + + if(!fos->Open(filename)) + { + delete fos; + fos=nullptr; + } + } + + ~OpenFileOutputStream() + { + SAFE_CLEAR(fos); + } + + const bool operator !(){return !fos;} + operator FileOutputStream *(){return fos;} + FileOutputStream *operator &(){return fos;} + FileOutputStream *operator ->(){return fos;} + };//class OpenFileInputStream + }//namespace io +}//namespace hgl +#endif//HGL_IO_FILE_OUTPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/IOType.h b/inc/hgl/io/IOType.h new file mode 100644 index 00000000..5456d091 --- /dev/null +++ b/inc/hgl/io/IOType.h @@ -0,0 +1,34 @@ +#ifndef HGL_IO_TYPE_INCLUDE +#define HGL_IO_TYPE_INCLUDE + +#include +namespace hgl +{ + namespace io + { + class DataInputStream; + class DataOutputStream; + + template struct io_type + { + T value; + + public: + + io_type()=default; + io_type(const T &v){value=v;} + + bool Read(DataInputStream *); + bool Write(DataOutputStream *)const; + + void operator = (const T &v) + { + value=v; + } + + operator T (){return value;} + operator const T ()const{return value;} + };//template struct io_type + }//namespace io +}//namespace hgl +#endif//HGL_IO_TYPE_INCLUDE diff --git a/inc/hgl/io/InputStream.h b/inc/hgl/io/InputStream.h new file mode 100644 index 00000000..9f81e226 --- /dev/null +++ b/inc/hgl/io/InputStream.h @@ -0,0 +1,39 @@ +#ifndef HGL_IO_INPUT_STREAM_INCLUDE +#define HGL_IO_INPUT_STREAM_INCLUDE + +#include +#include +namespace hgl +{ + namespace io + { + /** + * 数据输入流基类 + */ + class InputStream:public SeekAccess ///数据输入流基类 + { + public: + + virtual ~InputStream()=default; + + virtual void Close()=0; ///<关闭输入流 + + virtual int64 Read(void *,int64)=0; ///<读取数据 + virtual int64 Peek(void *,int64)=0; ///<预览数据 + virtual int64 ReadFully(void *buf,int64 buf_size){return Read(buf,buf_size);} ///<充分读取,保证读取到指定长度的数据(不计算超时) + + virtual bool CanRestart()const=0; ///<是否可以复位 + virtual bool CanSeek()const=0; ///<是否可以定位 + virtual bool CanSize()const=0; ///<是否可以取得尺寸 + virtual bool CanPeek()const=0; ///<是否可以预览数据 + + virtual bool Restart()=0; ///<复位访问指针 + virtual int64 Skip(int64)=0; ///<跳过指定字节不访问 + virtual int64 Seek(int64,SeekOrigin=soBegin)=0; ///<移动访问指针 + virtual int64 Tell()const=0; ///<返回当前访问位置 + virtual int64 GetSize()const=0; ///<取得流长度 + virtual int64 Available()const=0; ///<剩下的可以不受阻塞访问的字节数 + };//class InputStream + }//namespace io +}//namespace hgl +#endif//HGL_IO_INPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/JavaInputStream.h b/inc/hgl/io/JavaInputStream.h new file mode 100644 index 00000000..7b17b5b3 --- /dev/null +++ b/inc/hgl/io/JavaInputStream.h @@ -0,0 +1,71 @@ +#ifndef HGL_IO_JAVA_INPUT_STREAM_INCLUDE +#define HGL_IO_JAVA_INPUT_STREAM_INCLUDE + +#include +namespace hgl +{ + namespace io + { + /** + * Java数据输入流
+ * 接口类似于java.io.DataInputStream,用于和Java程序进行交互 + */ + class JavaInputStream + { + protected: + + BEDataInputStream *in; + + public: + + JavaInputStream(InputStream *is) + { + in=new BEDataInputStream(is); + } + + virtual ~JavaInputStream() + { + delete in; + } + + int64 read (void *ptr,int size){return in?in->ReadFully(ptr,size):-1;} + int skipBytes (int size) {return in?in->Seek(size,soCurrent):-1;} + + bool readBoolean (bool &b) {return in?in->ReadBool (b):false;} + bool readByte (int8 &i) {return in?in->ReadInt8 (i):false;} + bool readUnsignedByte (uint8 &i) {return in?in->ReadUint8 (i):false;} + + bool readShort (int16 &i) {return in?in->ReadInt16 (i):false;} + bool readUnsignedShort (uint16 &i) {return in?in->ReadUint16 (i):false;} + bool readInt (int32 &i) {return in?in->ReadInt32 (i):false;} + bool readLong (int64 &i) {return in?in->ReadInt64 (i):false;} + bool readFloat (float &f) {return in?in->ReadFloat (f):false;} + bool readDouble (double &d) {return in?in->ReadDouble (d):false;} + + bool readChar (u16char &c) + { + if(!in) + return(false); + + uint16 c16; + + if(!in->Read(c16)) + return(false); + + c=BigToCurrentEndian(c16); + return(true); + } + + bool readChars (u16char *wstr,const int count) + { + return in?in->ReadUTF16BEChars(wstr,count):false; + } + + bool readUTF (UTF16String &str) + { + return in?in->ReadUTF8ShortString(str); + } + };//class JavaInputStream + }//namespace io +}//namespace hgl +#endif//HGL_IO_JAVA_INPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/JavaOutputStream.h b/inc/hgl/io/JavaOutputStream.h new file mode 100644 index 00000000..3d53000d --- /dev/null +++ b/inc/hgl/io/JavaOutputStream.h @@ -0,0 +1,62 @@ +#ifndef HGL_IO_JAVA_OUTPUT_STREAM_INCLUDE +#define HGL_IO_JAVA_OUTPUT_STREAM_INCLUDE + +#include +namespace hgl +{ + namespace io + { + /** + * Java数据输出流
+ * 接口类似于java.io.DataOutputStream,用于和Java程序进行交互 + */ + class JavaOutputStream + { + protected: + + BEDataOutputStream *out; + + public: + + JavaOutputStream(OutputStream *os) + { + out=new BEDataOutputStream(os); + } + + virtual ~JavaOutputStream() + { + delete out; + } + + int64 write (const void *ptr,int size) {return out?out->WriteFully(ptr,size):-1;} + + bool writeBoolean (const bool &b) {return out?out->WriteBool (b):false;} + bool writeByte (const int8 &i) {return out?out->WriteInt8 (i):false;} + bool writeUnsignedByte (const uint8 &i) {return out?out->WriteUint8 (i):false;} + + bool writeShort (const int16 &i) {return out?out->WriteInt16 (i):false;} + bool writeUnsignedShort (const uint16 &i) {return out?out->WriteUint16(i):false;} + bool writeInt (const int32 &i) {return out?out->WriteInt32 (i):false;} + bool writeLong (const int64 &i) {return out?out->WriteInt64 (i):false;} + bool writeFloat (const float &f) {return out?out->WriteFloat (f):false;} + bool writeDouble (const double &d) {return out?out->WriteDouble(d):false;} + + bool writeChar (const u16char &c) + { + if(!out) + return(false); + + return out->Write(ToBigEndian(c)); + } + + bool writeChars (const u16char *wstr,const int64 count) + { + return out?out->WriteUTF16BEChars(wstr,count):false; + } + + bool writeUTF (const UTF8String &str){return out?out->WriteUTF8ShortString(str);} + bool writeUTF (const UTF16String &str){return out?out->WriteUTF8ShortString(str);} + };//class JavaOutputStream + }//namespace io +}//namespace hgl +#endif//HGL_IO_JAVA_OUTPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/MemoryInputStream.h b/inc/hgl/io/MemoryInputStream.h new file mode 100644 index 00000000..78129cde --- /dev/null +++ b/inc/hgl/io/MemoryInputStream.h @@ -0,0 +1,163 @@ +#ifndef HGL_IO_MEMORY_INPUT_STREAM_INCLUDE +#define HGL_IO_MEMORY_INPUT_STREAM_INCLUDE + +#include +#include +namespace hgl +{ + namespace io + { + /** + * 内存数据输入流,从内存块中取得数据。 + */ + class MemoryInputStream:public InputStream ///内存数据输入流 + { + protected: + + const uint8 *buf; + size_t buf_size; + size_t cur_pos; + + public: + + MemoryInputStream() + { + buf=0; + + buf_size=0; + cur_pos=0; + } + + virtual ~MemoryInputStream() + { + } + + /** + * 关联一个数据区到当前输入流 + * @param data 数据指针 + * @param size 数据长度字节数 + * @return 是否成功 + */ + bool Link(const void *data,const size_t size) + { + if(!data) + return(false); + + buf=(uint8 *)data; + buf_size=size; + cur_pos=0; + + return(true); + } + + /** + * 更新关联的数据区长度,不复位cur_pos + * @param data 数据指针 + * @param size 数据长度字节数 + * @return 是否成功 + */ + bool Update(void *data,size_t size) + { + if(!data) + return(false); + + buf=(uint8 *)data; + buf_size=size; + + return(true); + } + + void Unlink() + { + buf=0; + } + + void Close() + { + Unlink(); + } + + int64 Read(void *data,int64 size) + { + const int result=Peek(data,size); + + if(result>0) + cur_pos+=result; + + return result; + } + + int64 Peek(void *data,int64 size) + { + if(!buf||!data||size<0) + return(-1); + + if(cur_pos+size>buf_size) + size=buf_size-cur_pos; + + if(size<=0) + return(0); + + memcpy(data,buf+cur_pos,size); + + return size; + } + + bool CanRestart()const{return true;} + bool CanSeek()const{return true;} + bool CanSize()const{return true;} + bool CanPeek()const{return true;} + + bool Restart() + { + cur_pos=0; + return(true); + } + + int64 Skip(int64 bytes) + { + return Seek(bytes,soCurrent); + } + + int64 Seek(int64 off,SeekOrigin so) + { + if(!CanSeek())return(-1); + + if(so==soCurrent) + { + off+=cur_pos; + } + else + if(so==soEnd) + { + off+=buf_size; + } + + if(off<0||off>=buf_size) + return(-1); + + cur_pos=off; + return cur_pos; + } + + int64 Tell()const + { + if(!buf)return(-1); + return cur_pos; + } + + int64 GetSize()const + { + if(!buf)return(-1); + return buf_size; + } + + int64 Available()const + { + if(!buf)return(-1); + return buf_size-cur_pos; + } + };//class MemoryInputStream + }//namespace io +}//namespace hgl +#endif//HGL_IO_MEMORY_INPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/MemoryOutputStream.h b/inc/hgl/io/MemoryOutputStream.h new file mode 100644 index 00000000..4b53205a --- /dev/null +++ b/inc/hgl/io/MemoryOutputStream.h @@ -0,0 +1,236 @@ +#ifndef HGL_IO_MEMORY_OUTPUT_STREAM_INCLUDE +#define HGL_IO_MEMORY_OUTPUT_STREAM_INCLUDE + +#include +#include +namespace hgl +{ + namespace io + { + /** + * 内存数据输出流,将数据输出到一个内存块中。 + */ + class MemoryOutputStream:public OutputStream ///内存数据输出流 + { + protected: + + uint8 *buf; + + size_t max_size; + size_t buf_size; + size_t cur_pos; + + bool one; + + public: + + MemoryOutputStream() + { + buf=0; + max_size=0; + buf_size=0; + cur_pos=0; + one=false; + } + + virtual ~MemoryOutputStream() + { + Close(); + } + + void *GetData()const{return buf;} + + /** + * 创建一个当前流数据的内存拷贝,此函数需用户自行delete[] + * @param len 存放数据长度的指针 + * @return 创建好的内存拷贝 + */ + void *CreateCopyData(int *len)const + { + if(buf_size<=0) + return(nullptr); + + uint8 *data=new uint8[buf_size+1]; + memcpy(data,buf,buf_size); + data[buf_size]=0; + + if(len) + *len=buf_size; + + return data; + } + + /** + * 关联一个数据区到当前输出流 + * @param ptr 数据指针 + * @param size 数据长度字节数 + * @param one_instance 是否仅此一份实例(如果是,将由MemoryOutputStream类负责释放) + * @return 是否成功 + */ + bool Link(void *ptr,size_t size,bool one_instance=false) + { + if(!ptr||!size) + return(false); + + buf=(uint8 *)ptr; + buf_size=size; + max_size=size; + cur_pos=0; + + one=one_instance; + + return(true); + } + + /** + * 更新关联的数据区长度,不复位cur_pos + * @param ptr 数据指针 + * @param size 数据长度字节数 + * @return 是否成功 + */ + bool Update(void *ptr,size_t size) + { + if(!ptr||!size) + return(false); + + buf=(uint8 *)ptr; + buf_size=size; + max_size=0; + + return(true); + } + + void Unlink() + { + buf=0; + buf_size=0; + max_size=0; + } + + bool Create(int64 size) + { + Close(); + + if(size<=0) + return(false); + + buf=(uint8 *)hgl_malloc(size); + + if(!buf) + return(false); + + one=true; + cur_pos=0; + buf_size=size; + max_size=size; + + return(true); + } + + void Close() override + { + if(buf) + { + if(one) + hgl_free(buf); + + buf=0; + } + + buf_size=0; + max_size=0; + } + + void ClearData() + { + cur_pos=0; + buf_size=0; + } + + int64 Write(const void *ptr,int64 size) override + { + if(!ptr||size<0) + return(-1); + + if(!buf) + { + if(!Create(size)) + return(-1); + } + + if(cur_pos+size>buf_size) + { + if(one) + { + buf_size=cur_pos+size; + + if(buf_size>max_size) + { + max_size=power_to_2(buf_size); + + buf=(uint8 *)hgl_realloc(buf,max_size); + } + } + else + size=buf_size-cur_pos; + } + + if(size<=0) + return(0); + + memcpy(buf+cur_pos,ptr,size); + + cur_pos+=size; + + return size; + } + + bool CanRestart()const override{return true;} + bool CanSeek()const override{return true;} + bool CanSize()const override{return true;} + + bool Restart() override + { + cur_pos=0; + return(true); + } + + int64 Seek(int64 off,SeekOrigin so=soBegin) override + { + if(!CanSeek())return(-1); + + if(so==soCurrent) + { + off+=cur_pos; + } + else + if(so==soEnd) + { + off+=buf_size; + } + + if(off<0||off>=buf_size) + return(-1); + + cur_pos=off; + return cur_pos; + } + + int64 Tell()const override + { + return cur_pos; + } + + int64 GetSize()const override + { + return buf_size; + } + + int64 Available()const override + { + return buf_size-cur_pos; + } + };//class MemoryOutputStream + }//namespace io +}//namespace hgl +#endif//HGL_IO_MEMORY_OUTPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/OutputStream.h b/inc/hgl/io/OutputStream.h new file mode 100644 index 00000000..b528851f --- /dev/null +++ b/inc/hgl/io/OutputStream.h @@ -0,0 +1,36 @@ +#ifndef HGL_IO_OUTPUT_STREAM_INCLUDE +#define HGL_IO_OUTPUT_STREAM_INCLUDE + +#include +#include +namespace hgl +{ + namespace io + { + /** + * 数据输出流基类 + */ + class OutputStream:public SeekAccess ///数据输出流基类 + { + public: + + virtual ~OutputStream()=default; + + virtual void Close()=0; ///<关闭输出流 + + virtual int64 Write(const void *,int64)=0; ///<写入数据 + virtual int64 WriteFully(const void *buf,int64 buf_size){return Write(buf,buf_size);} ///<充分写入,保证完整写入指定长度的数据 + + virtual bool CanRestart()const=0; ///<是否可以复位 + virtual bool CanSeek()const=0; ///<是否可以定位 + virtual bool CanSize()const=0; ///<是否可以取得尺寸 + + virtual bool Restart()=0; ///<复位访问指针 + virtual int64 Seek(int64,SeekOrigin=soBegin)=0; ///<移动访问指针 + virtual int64 Tell()const=0; ///<返回当前访问位置 + virtual int64 GetSize()const=0; ///<取得流长度 + virtual int64 Available()const=0; ///<剩下的可以不受阻塞写入的字节数 + };//class OutputStream + }//namespace io +}//namespace hgl +#endif//HGL_IO_OUTPUT_STREAM_INCLUDE diff --git a/inc/hgl/io/RandomAccessFile.h b/inc/hgl/io/RandomAccessFile.h new file mode 100644 index 00000000..e395cd67 --- /dev/null +++ b/inc/hgl/io/RandomAccessFile.h @@ -0,0 +1,47 @@ +#ifndef HGL_IO_RANDOM_ACCESS_FILE_INCLUDE +#define HGL_IO_RANDOM_ACCESS_FILE_INCLUDE + +#include +#include +#include +namespace hgl +{ + namespace io + { + /** + * 随机文件访问

+ * 可同时被DataInputStream/DataOutputStream包含引用,但需注意他们将共用一个访问指针 + */ + class RandomAccessFile:public InputStream,public OutputStream + { + protected: + + SharedPtr file; ///<文件访问指针 + + public: + + RandomAccessFile(); + RandomAccessFile(SharedPtr &); + ~RandomAccessFile(); + + virtual bool Open(const OSString &); ///<打开文件 + virtual void Close(); ///<关闭文件 + + virtual int64 Read(void *,int64); ///<读取数据 + virtual int64 Write(const void *,int64); ///<写入数据 + + virtual int64 Read(int64,void *,int64); ///<在指定位置读取指定长度的数据 + virtual int64 Write(int64,const void *,int64); ///<在指定位置写入指定长度的数据 + + virtual bool CanSeek()const; ///<是否可移动访问指针 + virtual bool CanRestart()const; ///<是否可复位访问 + virtual bool CanSize()const; ///<是否可访问文件长度 + + virtual int64 Tell()const; ///<取当前位置 + virtual int64 GetSize(); ///<取得文件长度 + virtual bool Restart(); ///<复位访问指针 + virtual int64 Seek(int64,SeekOrigin=soBegin); ///<移动访问指针 + };//class RandomAccessFile + }//namespace io +}//namespace hgl +#endif//HGL_IO_RANDOM_ACCESS_FILE_INCLUDE diff --git a/inc/hgl/io/SeekAccess.h b/inc/hgl/io/SeekAccess.h new file mode 100644 index 00000000..0f33ca86 --- /dev/null +++ b/inc/hgl/io/SeekAccess.h @@ -0,0 +1,36 @@ +#ifndef HGL_IO_SEEK_ACCESS_INCLUDE +#define HGL_IO_SEEK_ACCESS_INCLUDE + +#include +namespace hgl +{ + namespace io + { + enum_int(SeekOrigin) /// 资源偏移方向枚举 + { + soBegin=0, ///<从资源最开始处开始,offset必须大于0。移到资源的offset位置 + soCurrent, ///<从资源当前位置开始,移到资源的Position+offset位置 + soEnd ///<从资源的结束位置开始,offset必须小于0,表示结束前的字符数 + };//enum SeekOrigin + + /** + * 定位访问功能基类 + */ + class SeekAccess + { + public: + + virtual ~SeekAccess()=default; + + virtual bool CanRestart()const=0; ///<是否可以复位 + virtual bool CanSeek()const=0; ///<是否可以定位 + virtual bool CanSize()const=0; ///<是否可以取得尺寸 + + virtual bool Restart()=0; ///<复位访问指针 + virtual int64 Seek(int64,SeekOrigin=soBegin)=0; ///<移动访问指针 + virtual int64 Tell()const=0; ///<返回当前访问位置 + virtual int64 GetSize()const=0; ///<取得文件长度 + };//class SeekAccess + }//namespace io +}//namespace hgl +#endif//HGL_IO_SEEK_ACCESS_INCLUDE diff --git a/inc/hgl/io/TextOutputStream.h b/inc/hgl/io/TextOutputStream.h new file mode 100644 index 00000000..0d96beb7 --- /dev/null +++ b/inc/hgl/io/TextOutputStream.h @@ -0,0 +1,176 @@ +#ifndef HGL_IO_TEXT_OUTPUT_STREAM_INCLUDE +#define HGL_IO_TEXT_OUTPUT_STREAM_INCLUDE + +#include +#include +namespace hgl +{ + namespace io + { + /** + * 文本输出流
+ * 用于将数据输出成文件,用于日志、配置等文本信息处理。 + */ + class TextOutputStream + { + protected: + + ByteOrderMask bom; ///<文本编码 + DataOutputStream *out; ///<数据输出流 + + public: + + TextOutputStream(ByteOrderMask _bom,DataOutputStream *_out) + { + bom=_bom; + out=_out; + } + + virtual ~TextOutputStream() + { + delete out; + } + + const ByteOrderMask GetBOM()const + { + return bom; + } + + DataOutputStream *GetDataOutputStream() + { + return out; + } + + operator DataOutputStream *() + { + return out; + } + + bool WriteBOM() ///<写入文本文件bom头 + { + if(!out)return(false); + + const BOMFileHeader *bom_item=BOMData+bom; + + return(out->Write(bom_item->data,bom_item->size)==bom_item->size); + } + + virtual bool WriteChars(const char *,int64)=0; ///<写入一个字符串 + virtual bool WriteChars(const u16char *,int64)=0; ///<写入一个字符串 + + template + bool WriteString(const BaseString &str) ///<写入一个字符串 + { + return WriteChars(str.c_str(),str.Length()); + } + + bool WriteLineEnd() ///<写入一个换行符 + { + return WriteChars(HGL_LINE_END,HGL_LINE_END_SIZE); + } + + template + bool WriteLine(const N *str,int64 size) + { + if(!WriteChars(str,size)) + return(false); + + return WriteLineEnd(); + } + + template + bool WriteLine(const BaseString &str) + { + return WriteLine(str.c_str(),str.Length()); + } + + /** + * 向流中写入一个文本(注:整体按标准文本文件模式) + */ + template + bool WriteText(const StringList &sl) + { + const int count=sl.GetCount(); + + for(int i=0;i + bool Write(const StringList &sl) + { + const int count=sl.GetCount(); + + if(!out->WriteInt32(count)) //写入行数 + return(false); + + if(count<=0) + return(true); + + SharedArray line_length=new int32[count]; + SharedArray str_list=new T *[count]; + int32 *line_p=line_length; + T **str_p=str_list; + + int32 total=0; + + for(int i=0;i &str=sl[i]; + + const int len=str.Length(); + + total+=len; + + *line_p++=len; + + *str_list++=str.c_str(); + } + + if(out->WriteInt32(line_length,count)!=count) //写入每行长度 + return(false); + + line_p=line_length; + str_p=str_list; + + SharedArray text=new T[total]; + T *text_p=text; + + for(int i=0;i class EndianTextOutputStream:public TextOutputStream ///文本输出流 + { + public: + + EndianTextOutputStream(OutputStream *); + + bool WriteChars(const char *,int64); ///<写入一个字符串 + bool WriteChars(const u16char *,int64); ///<写入一个字符串 + };//template class EndianTextOutputStream + + typedef EndianTextOutputStream UTF8TextOutputStream; + typedef EndianTextOutputStream UTF16LETextOutputStream; + typedef EndianTextOutputStream UTF16BETextOutputStream; + + template TextOutputStream *CreateTextOutputStream(OutputStream *os); + }//namespace io +}//namespace hgl +#endif//HGL_IO_TEXT_OUTPUT_STREAM_INCLUDE diff --git a/inc/hgl/platform/ExternalModule.h b/inc/hgl/platform/ExternalModule.h new file mode 100644 index 00000000..bb3e85e0 --- /dev/null +++ b/inc/hgl/platform/ExternalModule.h @@ -0,0 +1,36 @@ +#ifndef HGL_EXTERNAL_MODULE_INCLUDE +#define HGL_EXTERNAL_MODULE_INCLUDE + +#include +#include +#include OS_EXTERNAL_H +namespace hgl +{ + /** + * 这个类用于对外部动态库的调用,支持Windows/Linux/BSD/MacOSX
+ * Windows 下动态库扩展名为.DLL
+ * FreeBSD/MacOSX 下动态库扩展名为.dylib
+ * Linux 下动态库扩展名为.so + */ + class ExternalModule ///外部模块调用类 + { + ExternalModulePointer fp; + + public: //方法 + + ExternalModule(); ///<本类构造函数 + ExternalModule(ExternalModulePointer); ///<本类构造函数 + virtual ~ExternalModule(); ///<本类析构函数 + + bool Load(const os_char *); ///<加载一个外部模块 + void Clear(); ///<清除当前模块 + + void *FindFunc(const char *); ///<查找函数 + void *GetFunc(const char *); ///<取得函数 + + int Get(FuncLoad *); ///<加载函数列表 + };//class ExternalModule + + ExternalModule *LoadExternalModule(const os_char *); ///<加载一个外部模块 +}//namespace hgl +#endif//HGL_EXTERNAL_MODULE_INCLUDE diff --git a/inc/hgl/platform/FuncLoad.h b/inc/hgl/platform/FuncLoad.h new file mode 100644 index 00000000..19777517 --- /dev/null +++ b/inc/hgl/platform/FuncLoad.h @@ -0,0 +1,31 @@ +#ifndef HGL_FUNC_LOAD_INCLUDE +#define HGL_FUNC_LOAD_INCLUDE + +namespace hgl +{ + /** + * 函数加载定义数据结构 + */ + struct FuncLoad + { + char func_name[64]; ///<函数名称 + void **func_pointer; ///<函数指针 + };//struct FuncLoad + + #define HGL_FUNC_LOAD_LIST_BEGIN(name) struct FuncLoad name[]={ + #define HGL_FUNC_LOAD(name) {#name,(void **)&name}, + #define HGL_FUNC_LOAD_LIST_END {"",(void **)0}}; + + inline void ClearFuncLoadPointer(struct FuncLoad *flp) + { + if(!flp)return; + + while(flp->func_pointer) + { + flp->func_pointer=(void **)0; + + ++flp; + } + } +}//namespace hgl +#endif//HGL_FUNC_LOAD_INCLUDE diff --git a/inc/hgl/platform/SystemInfo.h b/inc/hgl/platform/SystemInfo.h new file mode 100644 index 00000000..987efb99 --- /dev/null +++ b/inc/hgl/platform/SystemInfo.h @@ -0,0 +1,69 @@ +#ifndef HGL_SYSTEMINFO_INCLUDE +#define HGL_SYSTEMINFO_INCLUDE + +#include +#include +namespace hgl +{ + /** + * 内存信息结构体 + */ + struct MemInfo ///内存信息结构体 + { + uint64 AvailPhys; ///<有效物理内存 + uint64 TotalPhys; ///<总共物理内存 + + uint64 AvailPageFile; ///<有效页面文件 + uint64 TotalPageFile; ///<总共页面文件 + + uint64 AvailVirtual; ///<有效虚拟内存 + uint64 TotalVirtual; ///<总计虚拟内存 + + public: + + MemInfo(); + };//struct MemInfo + + /** + * 操作系统及引擎相关路径 + */ + struct SystemPath ///操作系统及引擎相关路径 + { + OSString start; ///<当前应用程序起始路径 + + OSString os; ///<操作系统路径 + OSString osfont; ///<操作系统字库路径 + OSString library; ///<操作系统辅助库路径 + + OSString common_data; ///<所有用户共用应用程序数据路径 + OSString local_data; ///<本地应用程序数据路径 + + OSString temp; ///<临时文件路径 + + OSString mydata; ///<当前用户应用程序数据保存路径 + OSString myprogram; ///<“我的程序”路径(Windows下为开始菜单程序路径,Mac下为应用程序路径) + OSString mydesktop; ///<“桌面”路径 + + OSString desktop; ///<所有用户桌面路径 + + OSString engine; ///<引擎所在路径 + OSString plug_ins; ///<引擎插件路径 + };//struct SystemPath + + /** + * 系统信息 + */ + struct SystemInfo ///系统信息结构 + { + MemInfo mem; ///<内存信息 + + u16char os_name[256]; ///<操作系统全名 + + SystemPath path; ///<系统相关路径 + + public: + + SystemInfo(); + };//struct SystemInfo +}//namespace hgl +#endif//HGL_SYSTEMINFO_INCLUDE diff --git a/example/Vulkan/Window.h b/inc/hgl/platform/Window.h similarity index 100% rename from example/Vulkan/Window.h rename to inc/hgl/platform/Window.h diff --git a/inc/hgl/platform/compiler/.directory b/inc/hgl/platform/compiler/.directory deleted file mode 100644 index fbddeed9..00000000 --- a/inc/hgl/platform/compiler/.directory +++ /dev/null @@ -1,5 +0,0 @@ -[Dolphin] -PreviewsShown=false -Timestamp=2018,11,27,14,37,5 -Version=4 -ViewMode=1 diff --git a/inc/hgl/platform/os/.directory b/inc/hgl/platform/os/.directory deleted file mode 100644 index 5dec1853..00000000 --- a/inc/hgl/platform/os/.directory +++ /dev/null @@ -1,5 +0,0 @@ -[Dolphin] -PreviewsShown=false -Timestamp=2018,11,27,14,37,9 -Version=4 -ViewMode=1 diff --git a/inc/hgl/proc/Fifo.h b/inc/hgl/proc/Fifo.h new file mode 100644 index 00000000..c5cb610e --- /dev/null +++ b/inc/hgl/proc/Fifo.h @@ -0,0 +1,29 @@ +#ifndef HGL_MULTI_PROC_FIFO_INCLUDE +#define HGL_MULTI_PROC_FIFO_INCLUDE + +#include +namespace hgl +{ + /** + * 命名管道通信 + */ + class Fifo ///命名管道通信 + { + public: + + char filename[HGL_MAX_PATH]; + + int fd; + + public: + + Fifo() + { + *filename=0; + fd=-1; + } + + bool Create(const char *); ///<创建一个管道通信文件(注:只需要文件名,不需要完整路径) + };//namespace hgl +}//namespace hgl +#endif//HGL_MULTI_PROC_FIFO_INCLUDE diff --git a/inc/hgl/proc/FifoInputStream.h b/inc/hgl/proc/FifoInputStream.h new file mode 100644 index 00000000..6ba5319d --- /dev/null +++ b/inc/hgl/proc/FifoInputStream.h @@ -0,0 +1,35 @@ +#ifndef HGL_MULTI_PROC_FIFO_INPUT_STREAM_INCLUDE +#define HGL_MULTI_PROC_FIFO_INPUT_STREAM_INCLUDE + +#include +#include + +namespace hgl +{ + namespace io + { + /** + * 命名管道输入流 + */ + class FifoInputStream:public InputStream + { + Fifo *f; + + public: + + FifoInputStream(Fifo *_f) + { + f=_f; + } + + virtual ~FifoInputStream() + { + if(f) + delete f; + } + + + };//class FifoInputStream + }//namespace io +}//namespace hgl +#endif//HGL_MULTI_PROC_FIFO_INPUT_STREAM_INCLUDE diff --git a/inc/hgl/proc/Pipe.h b/inc/hgl/proc/Pipe.h new file mode 100644 index 00000000..f4f957ee --- /dev/null +++ b/inc/hgl/proc/Pipe.h @@ -0,0 +1,24 @@ +#ifndef HGL_MULTI_PROC_PIPE_INCLUDE +#define HGL_MULTI_PROC_PIPE_INCLUDE + +#include + +#if HGL_OS==HGL_OS_Windows +#include +#endif// + +namespace hgl +{ + #if HGL_OS==HGL_OS_Windows + using pipe_ptr=HANDLE; + constexpr pipe_ptr PIPE_NULL=nullptr; + #else + using pipe_ptr=int; + constexpr pipe_ptr PIPE_NULL=-1; + #endif// + + using pipe_pair=pipe_ptr[2]; + + bool CreatePipe(pipe_pair &); ///<创建一对通信管道 +}//namespace hgl +#endif//HGL_MULTI_PROC_PIPE_INCLUDE diff --git a/inc/hgl/proc/Proc.h b/inc/hgl/proc/Proc.h new file mode 100644 index 00000000..01309ce2 --- /dev/null +++ b/inc/hgl/proc/Proc.h @@ -0,0 +1,41 @@ +#ifndef HGL_PROCESS_INCLUDE +#define HGL_PROCESS_INCLUDE + +#include +namespace hgl +{ + /** + * 进程管理类 + */ + class Process ///进程管理类 + { + OSString work_path; + OSString filename; + StringList args; + + int pid; + + public: + + Process() + { + pid=-1; + } + + virtual ~Process() + { + } + + bool SetWorkPath(const OSString &wp); ///<设置工作目录 + bool SetExecFile(const OSString &ef); ///<设置执行文件 + void AddArgv(const OSString &argv){if(!argv.IsEmpty())args.Add(argv);} ///<增加一个参数 + void ClearArgs(){args.Clear();} ///<清除所有参数 + + bool Execute(); ///<执行程序 + + bool Wait(); ///<等待子进程暂停或是终止 + bool Kill(); ///<杀掉子进程 + bool RequestTerminate(); ///<请求子进程终止 + };//class Process +}//namespace hgl +#endif//HGL_PROCESS_INCLUDE diff --git a/inc/hgl/proc/ProcMutex.h b/inc/hgl/proc/ProcMutex.h new file mode 100644 index 00000000..d2053691 --- /dev/null +++ b/inc/hgl/proc/ProcMutex.h @@ -0,0 +1,37 @@ +#ifndef HGL_PROCESS_MUTEX_INCLUDE +#define HGL_PROCESS_MUTEX_INCLUDE + +#include + +#if HGL_OS!=HGL_OS_Windows + #include +#endif//HGL_OS!=HGL_OS_Windows + +namespace hgl +{ + /** + * 进程排斥 + */ + class ProcMutex ///进程排斥 + { +#if HGL_OS==HGL_OS_Windows + void *lock; +#else + sem_t *lock; +#endif//HGL_OS==HGL_OS_Windows + + public: + + ProcMutex(); + ~ProcMutex(){Clear();} + + bool Create(const os_char *); ///<创建进程排斥 + void Clear(); ///<清除进程排斥 + + bool Lock(); ///<锁定 + bool TryLock(); ///<尝试锁定 + + bool Unlock(); ///<解锁 + };//class ProcMutex +}//namespace hgl +#endif//HGL_PROCESS_MUTEX_INCLUDE diff --git a/inc/hgl/thread/CondVar.h b/inc/hgl/thread/CondVar.h index 3103a9d9..1c94a0aa 100644 --- a/inc/hgl/thread/CondVar.h +++ b/inc/hgl/thread/CondVar.h @@ -1,4 +1,4 @@ -#ifndef HGL_MULTI_THREAD_CONDITION_VARIABLE_INCLUDE +#ifndef HGL_MULTI_THREAD_CONDITION_VARIABLE_INCLUDE #define HGL_MULTI_THREAD_CONDITION_VARIABLE_INCLUDE #include diff --git a/inc/hgl/thread/RWLock.h b/inc/hgl/thread/RWLock.h index 65ca68cb..953ed418 100644 --- a/inc/hgl/thread/RWLock.h +++ b/inc/hgl/thread/RWLock.h @@ -1,4 +1,4 @@ -#ifndef HGL_RWLOCK_INCLUDE +#ifndef HGL_RWLOCK_INCLUDE #define HGL_RWLOCK_INCLUDE #include diff --git a/inc/hgl/thread/Semaphore.h b/inc/hgl/thread/Semaphore.h index f9024446..75c9ccd0 100644 --- a/inc/hgl/thread/Semaphore.h +++ b/inc/hgl/thread/Semaphore.h @@ -1,4 +1,4 @@ -#ifndef HGL_SEMAPHORE_INCLUDE +#ifndef HGL_SEMAPHORE_INCLUDE #define HGL_SEMAPHORE_INCLUDE #ifdef __APPLE__ diff --git a/inc/hgl/thread/Thread.h b/inc/hgl/thread/Thread.h index 15002820..fcba970d 100644 --- a/inc/hgl/thread/Thread.h +++ b/inc/hgl/thread/Thread.h @@ -1,4 +1,4 @@ -#ifndef HGL_THREAD_INCLUDE +#ifndef HGL_THREAD_INCLUDE #define HGL_THREAD_INCLUDE #include diff --git a/inc/hgl/type/DateTime.h b/inc/hgl/type/DateTime.h new file mode 100644 index 00000000..1cf26d39 --- /dev/null +++ b/inc/hgl/type/DateTime.h @@ -0,0 +1,178 @@ +#ifndef HGL_DATETIME_INCLUDE +#define HGL_DATETIME_INCLUDE + +#include +#include + +namespace hgl +{ + namespace io + { + class DataInputStream; + class DataOutputStream; + }//namespace io + + /** + * 时间类,这个类用来保存和计算时间。 + * + * 当您对Hours,Minutes,Seconds中任何一个值进行加减时,其它值都会自动计算。如:11:30这个值,使用Minutes+=55。会自动计算出55分钟后的时间,值为12:25 + */ + class Time ///时间类 + { + int32 gmt_off; ///<当前时区与UTC时间的差值 + + int8 hours; + int8 minutes; + int8 seconds; + int32 micro_seconds; + int8 week_day; ///<为了取这个星期过了多少秒用的 + + public: + + int GetGMT ()const{return gmt_off;} ///<取得当前时间与UTC时间的时差 + + int GetHour ()const{return hours;} ///<时 + int GetMinute ()const{return minutes;} ///<分 + int GetSecond ()const{return seconds;} ///<秒 + int GetMicroSecond ()const{return micro_seconds;} ///<微秒(百万分之一秒) + + int GetDaySeconds ()const{return (hours*HGL_TIME_ONE_HOUR)+(minutes*HGL_TIME_ONE_MINUTE)+seconds;} ///<今天过了多少秒 + + int GetWeekSeconds ()const ///<这个星期过了多少秒 + { + int week = week_day; + if(week_day > 0) + --week; + + if(week_day == 0) + week=(HGL_DAY_ONE_WEEK-1); + + return ((week*HGL_HOUR_ONE_DAY+hours)*HGL_TIME_ONE_HOUR)+(minutes*HGL_TIME_ONE_MINUTE)+seconds; + } + +// int GetPastWeekSeconds()const{return int(GetDoubleTime()-GetWeekSeconds());} ///<过去那些年到这周一0点过了多少秒 + + void SetGMT(int go){gmt_off=go;} + void SetHour(int); + void SetMinute(int); + void SetSecond(int); + void SetMicroSecond(int); + + public: + + Time(); + Time(const double); + Time(int,int,int,int); + Time(const Time &); + + void Clear() + { + gmt_off=0; + hours=0; + minutes=0; + seconds=0; + micro_seconds=0; + week_day=0; + } + + void Set(int h,int m=0,int s=0,int ms=0,int wd=0); + + Time &operator = (const Time &); + + const int Comp(const Time &)const; + + CompOperator(const Time &,Comp); + + void Sync(const double=0); ///<和系统时间同步 + + bool SaveToStream(io::DataOutputStream *) const; + bool LoadFromStream(io::DataInputStream *); + };//class Time + + /** + * 日期类,这个类用来保存和计算日期。带有闰年的处理 + * + * 当您对Year,Month,Day中任意一个值进行修改时,其它值都会自动跟着计算。如1981-4-17,如果使用Day+=400,会自动计算出400天之后的日期,结果是1982-5-21 + */ + class Date ///日期类 + { + int32 year; + int8 month; + int8 day; + + int8 week_day; + int16 year_day; + + int8 max_days_per_month; + + public: + + int GetYear ()const{return year;} ///<年 + int GetMonth ()const{return month;} ///<月 + int GetDay ()const{return day;} ///<日 + int GetMaxDays ()const{return max_days_per_month;} ///<本月天数 + int GetWeekDay ()const{return week_day;} ///<星期,0为星期天 + int GetYearDay ()const{return year_day;} ///<今天为这一年的第几天 + + void SetYear (int y){year=y;} + void SetMonth (int); + void SetDay (int); + + public: + + Date(); + Date(const double); + Date(int,int,int); + Date(const Date &); + + void Clear() + { + year=0; + month=0; + day=0; + + week_day=0; + year_day=0; + + max_days_per_month=0; + } + + void Set(int y,int m,int d,int wd=0,int yd=0); + + Date &operator = (const Date &); + + const int Comp(const Date &)const; + + CompOperator(const Date &,Comp); + + void Sync(const double=0); ///<和系统日期同步 + + bool SaveToStream(io::DataOutputStream *) const; + bool LoadFromStream(io::DataInputStream *); + };//class Date + + /** + * 根据当前时间,转换出Date/Time两个结构 + */ + void ToDateTime(Date &,Time &,const double cur_time=0); + + /** + * 根据日期和时间,转换出以秒为单位的时间值 + * @param year 年 + * @param month 月 + * @param day 日 + * @param hour 小时 + * @param minute 分 + * @param second 秒 + * @param micro_second 微秒(1/1000秒) + * @return 转换出的值 + */ + double FromDateTime(const int year,const int month,const int day, + const int hour,const int minute=0,const int second=0,const int micro_second=0,const int gmt_off=0); + + /** + * 根据Date/Time转换出以秒为单位的时间值 + */ + double FromDateTime(const Date &,const Time &); +}//namespace hgl +#endif//HGL_DATETIME_INCLUDE diff --git a/inc/hgl/type/StringList.h b/inc/hgl/type/StringList.h new file mode 100644 index 00000000..8f0121aa --- /dev/null +++ b/inc/hgl/type/StringList.h @@ -0,0 +1,712 @@ +#ifndef HGL_STRINGLIST_INCLUDE +#define HGL_STRINGLIST_INCLUDE + +#include +#include +#include +#include +#include + +namespace hgl +{ + class HAC; + + /** + * 字符串列表处理类,用于保存字符串列表。 + */ + template class StringList ///字符串列表处理类 + { + static T NullString; + + protected: + + ObjectList Items; + + public: //属性 + + T **GetDataList()const{return Items.GetData();} ///<取得字符串列表指针数据 + const int GetCount()const{return Items.GetCount();} ///<字符串列表行数虚拟变量 + + public: //操作符重载 + + T &operator[](int n)const + { + if(n<0||n>=Items.GetCount()) + return NullString; + + T *result=Items[n]; + + if(result) + return(*result); + else + return NullString; + } + + StringList &operator = (const StringList &sl) + { + Clear(); + + const int n=sl.GetCount(); + T *str; + + for(int i=0;iAdd(*str); + } + + return(*this); + } + + public: //方法 + + StringList()=default; ///<本类构造函数 + //注:这里不要实现StringList(T &)或StringList(T *)之类 + virtual ~StringList(){Clear();} ///<本类析构函数 + + /** + * 增加一行字符串到当前列表中 + * @param str 要增加的字符串 + * @return 增加字符串成功后的索引 + */ + int Add(const T &str){return Items.Add(new T(str));} ///<添加字符串 + + /** + * 增加一个字符串列表到当前字符串列表中 + * @param sl 要增加的字符串列表 + */ + int Add(const StringList &sl) ///<添加字符串 + { + const int count=sl.GetCount(); + + for(int i=0;iComp(str)==0) + { + Items.Delete(count); + result++; + } + } + + return(result); + } + + /** + * 查找字符串 + * @param str 要查找的字符串 + * @return 查找到的字符串的索引,未找到返回-1 + */ + int Find(const T &str) const ///<查找字符串,未找到返回-1 + { + const int count=Items.GetCount(); + + for(int i=0;iComp(str)==0) + return(i); + + return(-1); + } + + /** + * 查找字符串,英文无视大小写 + * @param str 要指找的字符串 + * @return 查找到的字符串的索引,未找到返回-1 + */ + int CaseFind(const T &str) const ///<查找字符串,英文无视大小写,未找到返回-1 + { + const int count=Items.GetCount(); + + for(int i=0;iCaseComp(str)==0) + return(i); + + return(-1); + } + + /** + * 查找字符串,并指定最大比较长度 + * @param str 要查找的字符串 + * @param cn 限定的要查找字符串的最大长度 + * @return 查找到的字符串的索引,未找到返回-1 + */ + int Find(const T &str,const int cn) const ///<查找字符串,未找到返回-1 + { + const int count=Items.GetCount(); + + for(int i=0;iComp(str,cn)==0) + return(i); + + return(-1); + } + + /** + * 查找字符串,英文无视大小写,并指定最大比较长度 + * @param str 要指找的字符串 + * @param cn 限定的要查找字符串的最大长度 + * @return 查找到的字符串的索引,未找到返回-1 + */ + int CaseFind(const T &str,const int cn) const ///<查找字符串,英文无视大小写,未找到返回-1 + { + const int count=Items.GetCount(); + + for(int i=0;iCaseComp(str,cn)==0) + return(i); + + return(-1); + } + + /** + * 在指定位置插入一个字符串 + * @param index 要插入字符串的位置 + * @param str 要插入的字符串 + */ + void Insert(int index,const T &str) ///<在指定位置插入一个字符串 + { + if(index::Insert(index,new T(str)); + } + + /** + * 交换两个字符串的位置 + * @param index1 第一个字符串的位置 + * @param index2 第二个字符串的位置 + */ + void Exchange(int index1,int index2) ///<交换两行字符串 + { + Items.Exchange(index1,index2); + } + + T &GetString(int n)const{return *(Items[n]);} ///<取得指定行字符串 + };//template class StringList + + template T StringList::NullString; ///<空字符串实例 + + /** + * 以不可打印字符为分隔拆解一个字符串到一个字符串列表 + * @param sl 字符串列表处理类 + * @param str 字符串 + * @param size 字符串长度 + * @return 字符串行数 + */ + template int SplitToStringListBySpace(StringList > &sl,const T *str,int size) + { + if(!str||size<=0)return(-1); + + int count=0; + const T *p,*sp; + + sp=p=str; + + while(size>0) + { + if(!(*p)) + { + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + --size; + return count; + } + + if(isspace(*p)) + { + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + sp=p+1; ///<跳过分割符 + } + + ++p; + --size; + } + + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + return count; + }//int SplitToStringList + + /** + * 以指定字符为分隔拆解一个字符串到一个字符串列表 + * @param sl 字符串列表处理类 + * @param str 字符串 + * @param size 字符串长度 + * @param split_char 分隔字符 + * @return 字符串行数 + */ + template int SplitToStringList(StringList > &sl,const T *str,int size,const T &split_char) + { + if(!str||size<=0)return(-1); + + int count=0; + const T *p,*sp; + + sp=p=str; + + while(size>0) + { + if(!(*p)) + { + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + --size; + return count; + } + + if(*p==split_char) + { + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + sp=p+1; ///<跳过分割符 + } + + ++p; + --size; + } + + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + return count; + }//int SplitToStringList + + template int SplitToStringListFromString(StringList > &sl,const BaseString &str,const T &split_char) + { + return SplitToStringList(sl,str.c_str(),str.Length(),split_char); + } + + /** + * 以指定字符为分隔拆解一个字符串到一个字符串列表 + * @param sl 字符串列表处理类 + * @param str 字符串 + * @param size 字符串长度 + * @param split_char 分隔字符 + * @param maxSize 最多执行次数 + * @return 字符串行数 + */ + template int SplitToStringList(StringList > &sl,const T *str,int size,const T &split_char,int maxSize) + { + if(!str||size<=0)return(-1); + + int count=0; + const T *p,*sp; + + sp=p=str; + + while(size>0) + { + if(!(*p)) + { + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + --size; + return count; + } + + if(*p==split_char) + { + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + sp=p+1; ///<跳过分割符 + if(maxSize >0 && count >=maxSize-1) + { + ++p; + --size; + if(size > 0) + { + sl.Add(BaseString(sp,size)); + ++count; + } + + return count; + } + } + + ++p; + --size; + } + + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + return count; + }//int SplitToStringList + + template int SplitToStringList(StringList > &sl,const BaseString &str,const T &split_char,int maxSize) + { + return SplitToStringList(sl,str.c_str(),str.Length(),split_char,maxSize); + } + + /** + * 拆解一个多行字符串到一个字符串列表 + * @param sl 字符串列表处理类 + * @param str 字符串 + * @param size 字符串长度 + * @return 字符串行数 + */ + template int SplitToStringListByEnter(StringList > &sl,const T *str,int size) + { + if(!str||size<=0)return(-1); + + int count=0; + const T *p,*sp; + + sp=p=str; + + while(size>0) + { + if(!(*p)) + { + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + --size; + return count; + } + + if(*p==0x0D) // \r + { + sl.Add(BaseString(sp,p-sp)); + ++count; + + ++p; + --size; + + if(*p==0x0A) // \r\n,Windows下的断行是(\r\n)0x0D+0x0A,而其它系统是仅有一个 + { + ++p; + --size; + } + + sp=p; + } + else + if(*p==0x0A) // \n + { + sl.Add(BaseString(sp,p-sp)); + ++count; + + ++p; + --size; + + sp=p; + } + else + { + ++p; + --size; + } + } + + if(p>sp) + { + sl.Add(BaseString(sp,p-sp)); + ++count; + } + + return count; + }//int SplitToStringList + + template int SplitToStringList(StringList > &sl,const BaseString &str) + { + return SplitToStringList(sl,str.c_str(),str.Length()); + } + + /** + * 拆解一个多行字符串到多个字符串列表 + * @param sl 字符串列表处理类 + * @param slc 字符串列表处理类个数 + * @param str 字符串 + * @param size 字符串长度 + * @return 字符串行数 + */ + template int SplitToMultiStringList(StringList > **sl,int slc,const T *str,int size) + { + if(!str||size<=0)return(-1); + if(slc<=0)return(-1); + + int index=0; + int count=0; + const T *p,*sp; + + sp=p=str; + + while(size>0) + { + if(!(*p)) + { + if(p>sp) + { + sl[index]->Add(BaseString(sp,p-sp)); + if(++index==slc)index=0; + ++count; + } + + --size; + return count; + } + + if(*p==0x0D) // \r + { + sl[index]->Add(BaseString(sp,p-sp)); + if(++index==slc)index=0; + + ++count; + + ++p; + --size; + + if(*p==0x0A) // \r\n,Windows下的断行是(\r\n)0x0D+0x0A,而其它系统是仅有一个 + { + ++p; + --size; + } + + sp=p; + } + else + if(*p==0x0A) // \n + { + sl[index]->Add(BaseString(sp,p-sp)); + if(++index==slc)index=0; + + ++count; + + ++p; + --size; + + sp=p; + } + else + { + ++p; + --size; + } + } + + if(p>sp) + { + sl[index]->Add(BaseString(sp,p-sp)); + ++count; + } + + return count; + }//int SplitToStringList + + template int SplitToMultiStringList(StringList > **sl,int slc,const BaseString &str) + { + if(!sl||slc<=0)return(false); + + if(slc==1) + return SplitToStringList(**sl,str.c_str(),str.Length()); + else + return SplitToMultiStringList(sl,slc,str.c_str(),str.Length()); + } + + using UTF8StringList =StringList; + using UTF16StringList =StringList; + using UTF32StringList =StringList; + using AnsiStringList =StringList; + using WideStringList =StringList; + using OSStringList =StringList; + + template struct ReadStringFromDIS + { + bool ReadString(io::DataInputStream *dis,T &str); + }; + + template struct ReadStringFromDIS + { + bool ReadString(io::DataInputStream *dis,T &str) + { + return dis->ReadUTF8String(str); + } + }; + + template struct ReadStringFromDIS + { + bool ReadString(io::DataInputStream *dis,T &str) + { + return dis->ReadUTF16LEString(str); + } + }; + + template struct ReadStringFromDIS + { + bool ReadString(io::DataInputStream *dis,T &str) + { + return dis->ReadUTF16BEString(str); + } + }; + + /** + * 从DataInputStream流中读取一个字符串列表 + * @param sl 字符串列表处理类 + * @param dis 数据输入流 + * @return 字符串行数 + */ + template int LoadStringList(StringList > &sl,io::DataInputStream *dis) + { + if(!dis)return(-1); + + int count; + int result=0; + + if(!dis->ReadInt32(count)) + return(-2); + + ReadStringFromDIS,bom> rsfd; + + BaseString str; + + for(int i=0;i(sl,dis);} + inline int LoadUTF16LEStringList (UTF16StringList & sl,io::DataInputStream *dis){return LoadStringList(sl,dis);} + inline int LoadUTF16BEStringList (UTF16StringList & sl,io::DataInputStream *dis){return LoadStringList(sl,dis);} + + int LoadStringListFromText(UTF8StringList &sl,void *data,const int size,const CharSet &default_charset=UTF8CharSet); ///<从文件加载一个文本块到UTF8StringList + int LoadStringListFromText(UTF16StringList &sl,void *data,const int size,const CharSet &default_charset=UTF16LECharSet); ///<从文件加载一个文本块到UTF16StringList + + int LoadStringListFromTextFile(UTF8StringList &sl,const OSString &filename,const CharSet &default_charset=UTF8CharSet); ///<从文件加载一个文本文件到UTF8StringList + int LoadStringListFromTextFile(UTF16StringList &sl,const OSString &filename,const CharSet &default_charset=UTF16LECharSet); ///<从文件加载一个文本文件到UTF16StringList + + template struct WriteStringToDOS + { + bool WriteString(io::DataOutputStream *dos,const T &str); + }; + + template struct WriteStringToDOS + { + bool WriteString(io::DataOutputStream *dos,const T &str) + { + return dos->WriteUTF8String(str); + } + }; + + template struct WriteStringToDOS + { + bool WriteString(io::DataOutputStream *dos,const T &str) + { + return dos->WriteUTF16LEString(str); + } + }; + + template struct WriteStringToDOS + { + bool WriteString(io::DataOutputStream *dos,const T &str) + { + return dos->WriteUTF16BEString(str); + } + }; + + template int WriteStringList(io::DataOutputStream *dos,const StringList &sl) + { + WriteStringToDOS wtd; + + const int32 count=sl.GetCount(); + int result=0; + + if(!dos->WriteInt32(count)) + return(-2); + + for(int32 i=0;i int SaveUTF8StringList(io::DataOutputStream *dos,const StringList &sl) + { + return WriteStringList(dos,sl); + } + + template int SaveUTF16LEStringList(io::DataOutputStream *dos,const StringList &sl) + { + return WriteStringList(dos,sl); + } + + template int SaveUTF16BEStringList(io::DataOutputStream *dos,const StringList &sl) + { + return WriteStringList(dos,sl); + } +}//namespace hgl +#endif//HGL_STRINGLIST_INCLUDE diff --git a/example/Vulkan/FlatColor.frag b/res/shader/FlatColor.frag similarity index 100% rename from example/Vulkan/FlatColor.frag rename to res/shader/FlatColor.frag diff --git a/res/shader/FlatColor.frag.spv b/res/shader/FlatColor.frag.spv new file mode 100644 index 0000000000000000000000000000000000000000..69908edc099e8e7853d5536df7ee878bea304dc3 GIT binary patch literal 536 zcmYk2!Ae455QQgiS1n63qjq7m6r@Fk5Y-~cjZo1O2t@>`pgus))>E|!`o7t9}7$Y@5Eh;mv?ZWHy%_;YGw z2XEj9@Wc@y%h($6!%z;o$3 zXGt+qeoS5k>*6Qyy~o-cx_s+IUnG80)M|*?-z9SPx^JzfnEUpK?vvl6HgDk(-}l$N z#Cz1zVK2=DG8eEd>;_imSHl0|Ks8kOooTDoQ2%D!>kpG`+8GT-W3W1N zoZ(v70QUzUj*{`aWIRp20XaS6-5VQC(rG%%VC%Ww9&$&7 zUEoqY&0mscUh@zT9uHtKpm2CVKOV?YGJQB3`ZhvjTf( za_Z0H)r-}~JCRo}_D&bDJ+RtkEQB8~*THM-nnIRw@fA${Hh3NH8My{K?=SXfOtbDL z-X4rwSM0YUXPv9~CT3pih_7KT=eUlyj(1|dZM<4}^ND@0cwX&I%(X?ljkhoFtwB}a zM9y5d@#d8?mw30}jNd8t>YwoLYR%)a|KBiv6VGA2*Nd2U`WDtcRtgR`=lnL**>BXX z7M%Hy=+=HOW1d%U+_!l_Ro~c{HN6ABQ|FJlngxfObFG52X3W3CzKI$0zRdrMzMc6l n<~{fh)^YxOnEX#P_IDpMhrH+f9``Wc)^qkMR`-W#pJIOjnR-## literal 0 HcmV?d00001 diff --git a/example/Vulkan/shader_compile.bat b/res/shader/shader_compile.bat similarity index 100% rename from example/Vulkan/shader_compile.bat rename to res/shader/shader_compile.bat diff --git a/src/Base/CMakeLists.txt b/src/Base/CMakeLists.txt index 7e1dce6f..a85737a6 100644 --- a/src/Base/CMakeLists.txt +++ b/src/Base/CMakeLists.txt @@ -1,6 +1,54 @@ -add_library(ULRE.Base STATIC CodePage.cpp - Color.cpp - Color3f.cpp - Color4f.cpp) +SET(SYSTEM_INFO_SOURCE SystemInfo.cpp) +SET(BASE_TYPE_SOURCE +# DataType/Info.cpp +# DataType/BitArray.cpp + DataType/Color.cpp + DataType/Color3f.cpp + DataType/Color4f.cpp +# DataType/FontInfo.cpp + DataType/StringList.cpp) +SOURCE_GROUP("DataType" FILES ${BASE_TYPE_SOURCE}) + +SET(BASE_IO_SOURCE + IO/DataInputStream.cpp + IO/DataOutputStream.cpp + IO/FileAccess.cpp + IO/FileInputStream.cpp + IO/FileOutputStream.cpp + IO/IOType.cpp + IO/RandomAccessFile.cpp + IO/TextOutputStream.cpp) + +SOURCE_GROUP("IO" FILES ${BASE_IO_SOURCE}) + +SET(BASE_FILE_SYSTEM_SOURCE + FileSystem/FileSystem.cpp + FileSystem/EnumFile.cpp) + +SOURCE_GROUP("FileSystem" FILES ${BASE_FILE_SYSTEM_SOURCE}) + +SET(BASE_OTHER_SOURCE + Other/CodePage.cpp + Other/DateTime.cpp +# Other/ExpendString.cpp + Other/ThreadFunc.cpp + Other/TimeCount.cpp + Other/TimeVal.cpp) + +SOURCE_GROUP("Other" FILES ${BASE_OTHER_SOURCE}) + +SET(BASE_PLUG_IN_SOURCE + PlugIn/ExternalModule.cpp +# PlugIn/PlugIn.cpp +) + +SOURCE_GROUP("PlugIn" FILES ${BASE_PLUG_IN_SOURCE}) + +add_library(ULRE.Base STATIC #${SYSTEM_INFO_SOURCE} + ${BASE_TYPE_SOURCE} + ${BASE_IO_SOURCE} + ${BASE_FILE_SYSTEM_SOURCE} + ${BASE_OTHER_SOURCE} + ${BASE_PLUG_IN_SOURCE}) diff --git a/src/Base/Color.cpp b/src/Base/DataType/Color.cpp similarity index 98% rename from src/Base/Color.cpp rename to src/Base/DataType/Color.cpp index 1833e15d..707a3f2a 100644 --- a/src/Base/Color.cpp +++ b/src/Base/DataType/Color.cpp @@ -1,228 +1,228 @@ -#include - -namespace hgl -{ - #undef DEF_COLOR - #define DEF_COLOR(eng_name,red,green,blue,chs_name) { \ - red, \ - green, \ - blue, \ - int(double(red)*0.299+double(green)*0.587+double(blue)*0.114), \ - \ - float(double(red)/255.0f), \ - float(double(green)/255.0f), \ - float(double(blue)/255.0f), \ - float((double(red)*0.299+double(green)*0.587+double(blue)*0.114)/255.0f),\ - \ - #eng_name, \ - U16_TEXT(chs_name) \ - }, - - COLOR_DEF prv_color[ceEnd+1]= - { - DEF_COLOR(None, 0, 0, 0,"") - - DEF_COLOR(AliceBlue, 240,248,255,"艾利斯兰") - DEF_COLOR(AndroidGreen, 164,198, 57,"安卓绿") - DEF_COLOR(AntiqueWhite, 250,235,215,"古董白") - DEF_COLOR(AppleGreen, 141,182, 0,"苹果绿") - DEF_COLOR(Aqua, 0,255,255,"浅绿色") - DEF_COLOR(AquaMarine, 127,255,212,"碧绿色") - - DEF_COLOR(ArdenRed, 202, 23, 36,"雅顿红") //取自美国官网LOGO图片 - - DEF_COLOR(Azure, 240,255,255,"天蓝色") - DEF_COLOR(BananaMania, 250,231,181,"香蕉黄(芯)") - DEF_COLOR(BananaYellow, 255,225, 53,"香蕉黄(皮)") - DEF_COLOR(Beige, 245,245,220,"米色") - DEF_COLOR(Bisque, 255,228,196,"桔黄色") - DEF_COLOR(Black, 0, 0, 0,"黑色") - DEF_COLOR(BlanchedAlmond, 255,235,205,"白杏色") - DEF_COLOR(Blue, 0, 0,255,"蓝色") - DEF_COLOR(BlueViolet, 138, 43,226,"紫罗兰蓝") - DEF_COLOR(Brown, 165, 42, 42,"褐色") - DEF_COLOR(BurlyWood, 222,184,135,"实木色") - DEF_COLOR(CadetBlue, 95,158,160,"军兰色") - DEF_COLOR(CaribbeanGreen, 0,204,153,"加勒比海绿") - DEF_COLOR(Chartreuse, 127,255, 0,"黄绿色") - DEF_COLOR(CherryBlossomPink, 255,183,197,"樱桃花粉") - DEF_COLOR(Chocolate, 210,105, 30,"巧克力色") - DEF_COLOR(Coral, 255,127, 80,"珊瑚色") - DEF_COLOR(CornflowerBlue, 100,149,237,"菊花兰") - DEF_COLOR(Cornsilk, 255,248,220,"米绸色") - DEF_COLOR(Crimson, 220, 20, 60,"暗深红") - DEF_COLOR(Cyan, 0,255,255,"青色") - DEF_COLOR(DarkBlue, 0, 0,139,"暗蓝色") - DEF_COLOR(DarkCyan, 0,139,139,"暗青色") - DEF_COLOR(DarkGoldenrod, 184,134, 11,"暗金黄") - DEF_COLOR(DarkGray, 169,169,169,"暗灰色") - DEF_COLOR(DarkGreen, 0,100, 0,"暗绿色") - DEF_COLOR(DarkGrey, 169,169,169,"暗白色") - DEF_COLOR(DarkKhaki, 189,183,107,"暗黄褐色") - DEF_COLOR(DarkMagenta, 139, 0,139,"暗洋红") - DEF_COLOR(DarkOliveGreen, 85,107, 47,"暗橄榄绿") - DEF_COLOR(DarkOrange, 255,140, 0,"暗桔黄") - DEF_COLOR(DarkOrchid, 153, 50,204,"暗紫色") - DEF_COLOR(DarkRed, 139, 0, 0,"暗红色") - DEF_COLOR(DarkSalmon, 233,150,122,"暗肉色") - DEF_COLOR(DarkSeaGreen, 143,188,143,"暗海兰") - DEF_COLOR(DarkSlateBlue, 72, 61,139,"暗灰兰") - DEF_COLOR(DarkSlateGray, 47, 79, 79,"墨绿色") - DEF_COLOR(DarkSlateGrey, 47, 79, 79,"暗灰绿") - DEF_COLOR(DarkTurquoise, 0,206,209,"暗宝石绿") - DEF_COLOR(DarkViolet, 148, 0,211,"暗紫罗兰") - DEF_COLOR(DeepPink, 255, 20,147,"深粉红") - DEF_COLOR(DeepSkyBlue, 0,191,255,"深天蓝") - DEF_COLOR(DimGray, 105,105,105,"暗灰色") - DEF_COLOR(DimGrey, 105,105,105,"暗灰白") - DEF_COLOR(DodgerBlue, 30,144,255,"闪兰色") - DEF_COLOR(FireBrick, 178, 34, 34,"火砖色") - DEF_COLOR(FloralWhite, 255,250,240,"花白色") - DEF_COLOR(ForestGreen, 34,139, 34,"森林绿") - DEF_COLOR(FrenchBeige, 166,123, 91,"法国米色") - DEF_COLOR(FrenchBlue, 0,114,187,"法国兰") - DEF_COLOR(FrenchLilac, 134, 96,142,"法国丁香色") - DEF_COLOR(Fuchsia, 255, 0,255,"紫红色") - DEF_COLOR(Gainsboro, 220,220,220,"淡灰色") - DEF_COLOR(GhostWhite, 248,248,255,"幽灵白") - DEF_COLOR(Gold, 255,215, 0,"金色") - DEF_COLOR(Goldenrod, 218,165, 32,"金麒麟色") - DEF_COLOR(GoldenYellow, 255,223, 0,"金黄") - DEF_COLOR(Gray, 128,128,128,"灰色") - DEF_COLOR(Green, 0,128, 0,"绿色") - DEF_COLOR(GreenYellow, 173,255, 47,"蓝绿色") - DEF_COLOR(Grey, 128,128,128,"灰白色") - DEF_COLOR(HollywoodCerise, 244, 0,161,"好莱坞樱桃红") - DEF_COLOR(Honeydew, 240,255,240,"蜜色") - DEF_COLOR(HotPink, 255,105,180,"火热粉") - DEF_COLOR(HunterGreen, 53, 94, 59,"猎人绿") - DEF_COLOR(IndianGreen, 19,136, 8,"印度绿") - DEF_COLOR(IndianRed, 205, 92, 92,"印度红") - DEF_COLOR(IndianYellow, 227,168, 87,"印度黄") - DEF_COLOR(Indigo, 75, 0,130,"靛青色") - DEF_COLOR(Ivory, 255,255,240,"象牙白") - DEF_COLOR(Khaki, 240,230,140,"黄褐色") - DEF_COLOR(Lavender, 230,230,250,"淡紫色") - DEF_COLOR(LavenderBlush, 255,240,245,"淡紫红") - DEF_COLOR(LawnGreen, 124,252, 0,"草绿色") - DEF_COLOR(Lemon, 255,247, 0,"柠檬色") - DEF_COLOR(LemonYellow, 255,244, 79,"柠檬黄") - DEF_COLOR(LemonChiffon, 255,250,205,"柠檬绸") - DEF_COLOR(LightBlue, 173,216,230,"亮蓝色") - DEF_COLOR(LightCoral, 240,128,128,"亮珊瑚色") - DEF_COLOR(LightCyan, 224,255,255,"亮青色") - DEF_COLOR(LightGoldenrodYellow, 250,250,210,"亮金黄") - DEF_COLOR(LightGray, 211,211,211,"亮灰色") - DEF_COLOR(LightGreen, 144,238,144,"亮绿色") - DEF_COLOR(LightGrey, 211,211,211,"亮灰白") - DEF_COLOR(LightPink, 255,182,193,"亮粉红") - DEF_COLOR(LightSalmon, 255,160,122,"亮肉色") - DEF_COLOR(LightSeaGreen, 32,178,170,"亮海蓝") - DEF_COLOR(LightSkyBlue, 135,206,250,"亮天蓝") - DEF_COLOR(LightSlateGray, 119,136,153,"亮蓝灰") - DEF_COLOR(LightSlateGrey, 119,136,153,"亮蓝白") - DEF_COLOR(LightSteelBlue, 176,196,222,"亮钢兰") - DEF_COLOR(LightYellow, 255,255,224,"亮黄色") - DEF_COLOR(Lime, 0,255, 0,"酸橙色") - DEF_COLOR(LimeGreen, 50,205, 50,"橙绿色") - DEF_COLOR(Linen, 250,240,230,"亚麻色") - DEF_COLOR(Lion, 193,154,107,"獅子棕") - DEF_COLOR(Magenta, 255, 0,255,"红紫色") - DEF_COLOR(Maroon, 128, 0, 0,"粟色") - DEF_COLOR(MediumAquamarine, 102,205,170,"间绿色") - DEF_COLOR(MediumBlue, 0, 0,205,"间兰色") - DEF_COLOR(MediumOrchid, 186, 85,211,"间淡紫") - DEF_COLOR(MediumPurple, 147,112,219,"间紫色") - DEF_COLOR(MediumSeaGreen, 60,179,113,"间海蓝") - DEF_COLOR(MediumSlateBlue, 123,104,238,"间暗蓝") - DEF_COLOR(MediumSpringGreen, 0,250,154,"间春绿") - DEF_COLOR(MediumTurquoise, 72,209,204,"间绿宝石") - DEF_COLOR(MediumVioletRed, 199, 21,133,"间紫罗兰") - DEF_COLOR(MidNightBlue, 25, 25,112,"中灰蓝") - DEF_COLOR(Mint, 62,180,137,"薄荷色") - DEF_COLOR(MintCream, 245,255,250,"薄荷霜") - DEF_COLOR(MintGreen, 152,255,152,"薄荷绿") - DEF_COLOR(MistyRose, 255,228,225,"浅玫瑰") - DEF_COLOR(Moccasin, 255,228,181,"鹿皮色") - - DEF_COLOR(MozillaBlue, 0, 83,159,"火狐蓝") - DEF_COLOR(MozillaCharcoal, 77, 78, 83,"谋智炭") - DEF_COLOR(MozillaLightBlue, 0,150,221,"火狐亮蓝") - DEF_COLOR(MozillaLightOrange, 255,149, 0,"火狐亮橙") - DEF_COLOR(MoziilaNightBlue, 0, 33, 71,"谋智暗夜蓝") - DEF_COLOR(MozillaOrange, 230, 96, 0,"火狐橙") - DEF_COLOR(MozillaRed, 193, 56, 50,"谋智红") - DEF_COLOR(MozillaSand, 215,211,200,"谋智沙") - DEF_COLOR(MozillaYellow, 255,203, 0,"火狐黄") - - DEF_COLOR(NavajoWhite, 255,222,173,"纳瓦白") - DEF_COLOR(Navy, 0, 0,128,"海军色") - - DEF_COLOR(NiveaBlue, 0, 19,111,"妮维雅蓝") //取自妮维雅蓝国际官网 - - DEF_COLOR(NokiaBlue, 18, 65,145,"诺基亚蓝") //取自诺基亚官网 - - DEF_COLOR(OldLace, 253,245,230,"老花色") - DEF_COLOR(Olive, 128,128, 0,"橄榄色") - DEF_COLOR(Olivedrab, 107,142, 35,"深绿褐色") - DEF_COLOR(Orange, 255,165, 0,"橙色") - DEF_COLOR(OrangeRed, 255, 69, 0,"红橙色") - DEF_COLOR(Orchid, 218,112,214,"淡紫色") - DEF_COLOR(PaleGoldenrod, 238,232,170,"苍麒麟色") - DEF_COLOR(PaleGreen, 152,251,152,"苍绿色") - DEF_COLOR(PaleTurquoise, 175,238,238,"苍宝石绿") - DEF_COLOR(PaleVioletRed, 219,112,147,"苍紫罗兰色") - DEF_COLOR(Papayawhip, 255,239,213,"番木色") - DEF_COLOR(Peachpuff, 255,218,185,"桃色") - DEF_COLOR(Pear, 209,226, 49,"梨色") - DEF_COLOR(Peru, 205,133, 63,"秘鲁色") - DEF_COLOR(Pink, 255,192,203,"粉红色") - - DEF_COLOR(PlayStationBlue, 0, 55,145,"PlayStation蓝") - DEF_COLOR(PlayStationLightBlue, 0,120,200,"PlayStation亮蓝") - - DEF_COLOR(Plum, 221,160,221,"洋李色") - DEF_COLOR(PowderBlue, 176,224,230,"粉蓝色") - DEF_COLOR(Purple, 128, 0,128,"紫色") - DEF_COLOR(Red, 255, 0, 0,"红色") - DEF_COLOR(Rose, 255, 0,127,"玫瑰红") - DEF_COLOR(RosyBrown, 188,143,143,"褐玫瑰红") - DEF_COLOR(RoyalBlue, 65,105,225,"皇家蓝") - DEF_COLOR(Ruby, 224, 17, 95,"宝石红") - DEF_COLOR(SaddleBrown, 139, 69, 19,"重褐色") - DEF_COLOR(Salmon, 250,128,114,"鲜肉色") - - DEF_COLOR(SamsungBlue, 20, 40,160,"三星蓝") //取自三星官网 - - DEF_COLOR(SandyBrown, 244,164, 96,"沙褐色") - DEF_COLOR(SeaGreen, 46,139, 87,"海绿色") - DEF_COLOR(SeaShell, 255,245,238,"海贝色") - DEF_COLOR(Sienna, 160, 82, 45,"赭色") - DEF_COLOR(Silver, 192,192,192,"银色") - DEF_COLOR(SkyBlue, 135,206,235,"天蓝色") - DEF_COLOR(SlateBlue, 106, 90,205,"石蓝色") - DEF_COLOR(SlateGray, 112,128,144,"灰石色") - DEF_COLOR(SlateGrey, 112,128,144,"白灰石色") - DEF_COLOR(Snow, 255,250,250,"雪白色") - DEF_COLOR(SpringGreen, 0,255,127,"春绿色") - DEF_COLOR(SteelBlue, 70,130,180,"钢兰色") - DEF_COLOR(Tan, 210,180,140,"茶色") - DEF_COLOR(Teal, 0,128,128,"水鸭色") - DEF_COLOR(Thistle, 216,191,216,"蓟色") - - DEF_COLOR(TiffanyBlue, 129,216,208,"蒂芙尼蓝") //取自zh.wikipedia.org/zh-cn/蒂芙尼蓝 - - DEF_COLOR(Tomato, 255, 99, 71,"西红柿色") - DEF_COLOR(Turquoise, 64,224,208,"青绿色") - DEF_COLOR(Violet, 238,130,238,"紫罗兰色") - DEF_COLOR(Wheat, 245,222,179,"浅黄色") - DEF_COLOR(White, 255,255,255,"白色") - DEF_COLOR(WhiteSmoke, 245,245,245,"烟白色") - DEF_COLOR(Yellow, 255,255, 0,"黄色") - DEF_COLOR(YellowGreen, 154,205, 50,"黄绿色") - - DEF_COLOR(End, 0 ,0 ,0,"") - }; - - #undef DEF_COLOR -}//namespace hgl +#include + +namespace hgl +{ + #undef DEF_COLOR + #define DEF_COLOR(eng_name,red,green,blue,chs_name) { \ + red, \ + green, \ + blue, \ + int(double(red)*0.299+double(green)*0.587+double(blue)*0.114), \ + \ + float(double(red)/255.0f), \ + float(double(green)/255.0f), \ + float(double(blue)/255.0f), \ + float((double(red)*0.299+double(green)*0.587+double(blue)*0.114)/255.0f),\ + \ + #eng_name, \ + U16_TEXT(chs_name) \ + }, + + COLOR_DEF prv_color[ceEnd+1]= + { + DEF_COLOR(None, 0, 0, 0,"") + + DEF_COLOR(AliceBlue, 240,248,255,"艾利斯兰") + DEF_COLOR(AndroidGreen, 164,198, 57,"安卓绿") + DEF_COLOR(AntiqueWhite, 250,235,215,"古董白") + DEF_COLOR(AppleGreen, 141,182, 0,"苹果绿") + DEF_COLOR(Aqua, 0,255,255,"浅绿色") + DEF_COLOR(AquaMarine, 127,255,212,"碧绿色") + + DEF_COLOR(ArdenRed, 202, 23, 36,"雅顿红") //取自美国官网LOGO图片 + + DEF_COLOR(Azure, 240,255,255,"天蓝色") + DEF_COLOR(BananaMania, 250,231,181,"香蕉黄(芯)") + DEF_COLOR(BananaYellow, 255,225, 53,"香蕉黄(皮)") + DEF_COLOR(Beige, 245,245,220,"米色") + DEF_COLOR(Bisque, 255,228,196,"桔黄色") + DEF_COLOR(Black, 0, 0, 0,"黑色") + DEF_COLOR(BlanchedAlmond, 255,235,205,"白杏色") + DEF_COLOR(Blue, 0, 0,255,"蓝色") + DEF_COLOR(BlueViolet, 138, 43,226,"紫罗兰蓝") + DEF_COLOR(Brown, 165, 42, 42,"褐色") + DEF_COLOR(BurlyWood, 222,184,135,"实木色") + DEF_COLOR(CadetBlue, 95,158,160,"军兰色") + DEF_COLOR(CaribbeanGreen, 0,204,153,"加勒比海绿") + DEF_COLOR(Chartreuse, 127,255, 0,"黄绿色") + DEF_COLOR(CherryBlossomPink, 255,183,197,"樱桃花粉") + DEF_COLOR(Chocolate, 210,105, 30,"巧克力色") + DEF_COLOR(Coral, 255,127, 80,"珊瑚色") + DEF_COLOR(CornflowerBlue, 100,149,237,"菊花兰") + DEF_COLOR(Cornsilk, 255,248,220,"米绸色") + DEF_COLOR(Crimson, 220, 20, 60,"暗深红") + DEF_COLOR(Cyan, 0,255,255,"青色") + DEF_COLOR(DarkBlue, 0, 0,139,"暗蓝色") + DEF_COLOR(DarkCyan, 0,139,139,"暗青色") + DEF_COLOR(DarkGoldenrod, 184,134, 11,"暗金黄") + DEF_COLOR(DarkGray, 169,169,169,"暗灰色") + DEF_COLOR(DarkGreen, 0,100, 0,"暗绿色") + DEF_COLOR(DarkGrey, 169,169,169,"暗白色") + DEF_COLOR(DarkKhaki, 189,183,107,"暗黄褐色") + DEF_COLOR(DarkMagenta, 139, 0,139,"暗洋红") + DEF_COLOR(DarkOliveGreen, 85,107, 47,"暗橄榄绿") + DEF_COLOR(DarkOrange, 255,140, 0,"暗桔黄") + DEF_COLOR(DarkOrchid, 153, 50,204,"暗紫色") + DEF_COLOR(DarkRed, 139, 0, 0,"暗红色") + DEF_COLOR(DarkSalmon, 233,150,122,"暗肉色") + DEF_COLOR(DarkSeaGreen, 143,188,143,"暗海兰") + DEF_COLOR(DarkSlateBlue, 72, 61,139,"暗灰兰") + DEF_COLOR(DarkSlateGray, 47, 79, 79,"墨绿色") + DEF_COLOR(DarkSlateGrey, 47, 79, 79,"暗灰绿") + DEF_COLOR(DarkTurquoise, 0,206,209,"暗宝石绿") + DEF_COLOR(DarkViolet, 148, 0,211,"暗紫罗兰") + DEF_COLOR(DeepPink, 255, 20,147,"深粉红") + DEF_COLOR(DeepSkyBlue, 0,191,255,"深天蓝") + DEF_COLOR(DimGray, 105,105,105,"暗灰色") + DEF_COLOR(DimGrey, 105,105,105,"暗灰白") + DEF_COLOR(DodgerBlue, 30,144,255,"闪兰色") + DEF_COLOR(FireBrick, 178, 34, 34,"火砖色") + DEF_COLOR(FloralWhite, 255,250,240,"花白色") + DEF_COLOR(ForestGreen, 34,139, 34,"森林绿") + DEF_COLOR(FrenchBeige, 166,123, 91,"法国米色") + DEF_COLOR(FrenchBlue, 0,114,187,"法国兰") + DEF_COLOR(FrenchLilac, 134, 96,142,"法国丁香色") + DEF_COLOR(Fuchsia, 255, 0,255,"紫红色") + DEF_COLOR(Gainsboro, 220,220,220,"淡灰色") + DEF_COLOR(GhostWhite, 248,248,255,"幽灵白") + DEF_COLOR(Gold, 255,215, 0,"金色") + DEF_COLOR(Goldenrod, 218,165, 32,"金麒麟色") + DEF_COLOR(GoldenYellow, 255,223, 0,"金黄") + DEF_COLOR(Gray, 128,128,128,"灰色") + DEF_COLOR(Green, 0,128, 0,"绿色") + DEF_COLOR(GreenYellow, 173,255, 47,"蓝绿色") + DEF_COLOR(Grey, 128,128,128,"灰白色") + DEF_COLOR(HollywoodCerise, 244, 0,161,"好莱坞樱桃红") + DEF_COLOR(Honeydew, 240,255,240,"蜜色") + DEF_COLOR(HotPink, 255,105,180,"火热粉") + DEF_COLOR(HunterGreen, 53, 94, 59,"猎人绿") + DEF_COLOR(IndianGreen, 19,136, 8,"印度绿") + DEF_COLOR(IndianRed, 205, 92, 92,"印度红") + DEF_COLOR(IndianYellow, 227,168, 87,"印度黄") + DEF_COLOR(Indigo, 75, 0,130,"靛青色") + DEF_COLOR(Ivory, 255,255,240,"象牙白") + DEF_COLOR(Khaki, 240,230,140,"黄褐色") + DEF_COLOR(Lavender, 230,230,250,"淡紫色") + DEF_COLOR(LavenderBlush, 255,240,245,"淡紫红") + DEF_COLOR(LawnGreen, 124,252, 0,"草绿色") + DEF_COLOR(Lemon, 255,247, 0,"柠檬色") + DEF_COLOR(LemonYellow, 255,244, 79,"柠檬黄") + DEF_COLOR(LemonChiffon, 255,250,205,"柠檬绸") + DEF_COLOR(LightBlue, 173,216,230,"亮蓝色") + DEF_COLOR(LightCoral, 240,128,128,"亮珊瑚色") + DEF_COLOR(LightCyan, 224,255,255,"亮青色") + DEF_COLOR(LightGoldenrodYellow, 250,250,210,"亮金黄") + DEF_COLOR(LightGray, 211,211,211,"亮灰色") + DEF_COLOR(LightGreen, 144,238,144,"亮绿色") + DEF_COLOR(LightGrey, 211,211,211,"亮灰白") + DEF_COLOR(LightPink, 255,182,193,"亮粉红") + DEF_COLOR(LightSalmon, 255,160,122,"亮肉色") + DEF_COLOR(LightSeaGreen, 32,178,170,"亮海蓝") + DEF_COLOR(LightSkyBlue, 135,206,250,"亮天蓝") + DEF_COLOR(LightSlateGray, 119,136,153,"亮蓝灰") + DEF_COLOR(LightSlateGrey, 119,136,153,"亮蓝白") + DEF_COLOR(LightSteelBlue, 176,196,222,"亮钢兰") + DEF_COLOR(LightYellow, 255,255,224,"亮黄色") + DEF_COLOR(Lime, 0,255, 0,"酸橙色") + DEF_COLOR(LimeGreen, 50,205, 50,"橙绿色") + DEF_COLOR(Linen, 250,240,230,"亚麻色") + DEF_COLOR(Lion, 193,154,107,"獅子棕") + DEF_COLOR(Magenta, 255, 0,255,"红紫色") + DEF_COLOR(Maroon, 128, 0, 0,"粟色") + DEF_COLOR(MediumAquamarine, 102,205,170,"间绿色") + DEF_COLOR(MediumBlue, 0, 0,205,"间兰色") + DEF_COLOR(MediumOrchid, 186, 85,211,"间淡紫") + DEF_COLOR(MediumPurple, 147,112,219,"间紫色") + DEF_COLOR(MediumSeaGreen, 60,179,113,"间海蓝") + DEF_COLOR(MediumSlateBlue, 123,104,238,"间暗蓝") + DEF_COLOR(MediumSpringGreen, 0,250,154,"间春绿") + DEF_COLOR(MediumTurquoise, 72,209,204,"间绿宝石") + DEF_COLOR(MediumVioletRed, 199, 21,133,"间紫罗兰") + DEF_COLOR(MidNightBlue, 25, 25,112,"中灰蓝") + DEF_COLOR(Mint, 62,180,137,"薄荷色") + DEF_COLOR(MintCream, 245,255,250,"薄荷霜") + DEF_COLOR(MintGreen, 152,255,152,"薄荷绿") + DEF_COLOR(MistyRose, 255,228,225,"浅玫瑰") + DEF_COLOR(Moccasin, 255,228,181,"鹿皮色") + + DEF_COLOR(MozillaBlue, 0, 83,159,"火狐蓝") + DEF_COLOR(MozillaCharcoal, 77, 78, 83,"谋智炭") + DEF_COLOR(MozillaLightBlue, 0,150,221,"火狐亮蓝") + DEF_COLOR(MozillaLightOrange, 255,149, 0,"火狐亮橙") + DEF_COLOR(MoziilaNightBlue, 0, 33, 71,"谋智暗夜蓝") + DEF_COLOR(MozillaOrange, 230, 96, 0,"火狐橙") + DEF_COLOR(MozillaRed, 193, 56, 50,"谋智红") + DEF_COLOR(MozillaSand, 215,211,200,"谋智沙") + DEF_COLOR(MozillaYellow, 255,203, 0,"火狐黄") + + DEF_COLOR(NavajoWhite, 255,222,173,"纳瓦白") + DEF_COLOR(Navy, 0, 0,128,"海军色") + + DEF_COLOR(NiveaBlue, 0, 19,111,"妮维雅蓝") //取自妮维雅蓝国际官网 + + DEF_COLOR(NokiaBlue, 18, 65,145,"诺基亚蓝") //取自诺基亚官网 + + DEF_COLOR(OldLace, 253,245,230,"老花色") + DEF_COLOR(Olive, 128,128, 0,"橄榄色") + DEF_COLOR(Olivedrab, 107,142, 35,"深绿褐色") + DEF_COLOR(Orange, 255,165, 0,"橙色") + DEF_COLOR(OrangeRed, 255, 69, 0,"红橙色") + DEF_COLOR(Orchid, 218,112,214,"淡紫色") + DEF_COLOR(PaleGoldenrod, 238,232,170,"苍麒麟色") + DEF_COLOR(PaleGreen, 152,251,152,"苍绿色") + DEF_COLOR(PaleTurquoise, 175,238,238,"苍宝石绿") + DEF_COLOR(PaleVioletRed, 219,112,147,"苍紫罗兰色") + DEF_COLOR(Papayawhip, 255,239,213,"番木色") + DEF_COLOR(Peachpuff, 255,218,185,"桃色") + DEF_COLOR(Pear, 209,226, 49,"梨色") + DEF_COLOR(Peru, 205,133, 63,"秘鲁色") + DEF_COLOR(Pink, 255,192,203,"粉红色") + + DEF_COLOR(PlayStationBlue, 0, 55,145,"PlayStation蓝") + DEF_COLOR(PlayStationLightBlue, 0,120,200,"PlayStation亮蓝") + + DEF_COLOR(Plum, 221,160,221,"洋李色") + DEF_COLOR(PowderBlue, 176,224,230,"粉蓝色") + DEF_COLOR(Purple, 128, 0,128,"紫色") + DEF_COLOR(Red, 255, 0, 0,"红色") + DEF_COLOR(Rose, 255, 0,127,"玫瑰红") + DEF_COLOR(RosyBrown, 188,143,143,"褐玫瑰红") + DEF_COLOR(RoyalBlue, 65,105,225,"皇家蓝") + DEF_COLOR(Ruby, 224, 17, 95,"宝石红") + DEF_COLOR(SaddleBrown, 139, 69, 19,"重褐色") + DEF_COLOR(Salmon, 250,128,114,"鲜肉色") + + DEF_COLOR(SamsungBlue, 20, 40,160,"三星蓝") //取自三星官网 + + DEF_COLOR(SandyBrown, 244,164, 96,"沙褐色") + DEF_COLOR(SeaGreen, 46,139, 87,"海绿色") + DEF_COLOR(SeaShell, 255,245,238,"海贝色") + DEF_COLOR(Sienna, 160, 82, 45,"赭色") + DEF_COLOR(Silver, 192,192,192,"银色") + DEF_COLOR(SkyBlue, 135,206,235,"天蓝色") + DEF_COLOR(SlateBlue, 106, 90,205,"石蓝色") + DEF_COLOR(SlateGray, 112,128,144,"灰石色") + DEF_COLOR(SlateGrey, 112,128,144,"白灰石色") + DEF_COLOR(Snow, 255,250,250,"雪白色") + DEF_COLOR(SpringGreen, 0,255,127,"春绿色") + DEF_COLOR(SteelBlue, 70,130,180,"钢兰色") + DEF_COLOR(Tan, 210,180,140,"茶色") + DEF_COLOR(Teal, 0,128,128,"水鸭色") + DEF_COLOR(Thistle, 216,191,216,"蓟色") + + DEF_COLOR(TiffanyBlue, 129,216,208,"蒂芙尼蓝") //取自zh.wikipedia.org/zh-cn/蒂芙尼蓝 + + DEF_COLOR(Tomato, 255, 99, 71,"西红柿色") + DEF_COLOR(Turquoise, 64,224,208,"青绿色") + DEF_COLOR(Violet, 238,130,238,"紫罗兰色") + DEF_COLOR(Wheat, 245,222,179,"浅黄色") + DEF_COLOR(White, 255,255,255,"白色") + DEF_COLOR(WhiteSmoke, 245,245,245,"烟白色") + DEF_COLOR(Yellow, 255,255, 0,"黄色") + DEF_COLOR(YellowGreen, 154,205, 50,"黄绿色") + + DEF_COLOR(End, 0 ,0 ,0,"") + }; + + #undef DEF_COLOR +}//namespace hgl diff --git a/src/Base/Color3f.cpp b/src/Base/DataType/Color3f.cpp similarity index 100% rename from src/Base/Color3f.cpp rename to src/Base/DataType/Color3f.cpp diff --git a/src/Base/Color4f.cpp b/src/Base/DataType/Color4f.cpp similarity index 100% rename from src/Base/Color4f.cpp rename to src/Base/DataType/Color4f.cpp diff --git a/src/Base/DataType/StringList.cpp b/src/Base/DataType/StringList.cpp new file mode 100644 index 00000000..d65d9578 --- /dev/null +++ b/src/Base/DataType/StringList.cpp @@ -0,0 +1,182 @@ +#include +#include +namespace hgl +{ + /** + * 加载一个原始文本块到UTF8StringList + */ + int LoadStringListFromText(UTF8StringList &sl,uchar *data,const int size,const CharSet &cs) + { + char *str=nullptr; + + int line_count; + int char_count; + + if(size>=3&&data[0]==0xEF&&data[1]==0xBB&&data[2]==0xBF) //utf8 + line_count=SplitToStringListByEnter(sl,(char *)(data+3),size-3); + else + if(cs==UTF8CharSet) + line_count=SplitToStringListByEnter(sl,(char *)data,size); + else + { + if(size>=2) + { + int u16_count; + + if(data[0]==0xFF&&data[1]==0xFE) //LE + { + if(size>=4&&data[2]==0&&data[3]==0) //utf32-le + { + u16_count=(size-4)>>2; + u16char *u16str=new u16char[u16_count]; + + LittleToCurrentEndian(u16str,(uint32 *)(data+4),u16_count); + + str=u16_to_u8(u16str,u16_count,char_count); + delete[] u16str; + } + else //utf16-le + { + u16_count=(size-2)>>1; + LittleToCurrentEndian((u16char *)(data+2),u16_count); + str=u16_to_u8((u16char *)(data+2),u16_count,char_count); + } + } + else + if(data[0]==0&&data[1]==0&&data[2]==0xFE&&data[3]==0xFF) //utf32-be + { + u16_count=(size-4)>>2; + u16char *u16str=new u16char[u16_count]; + + BigToCurrentEndian(u16str,(uint32 *)(data+4),u16_count); + + str=u16_to_u8(u16str,u16_count,char_count); + delete[] u16str; + } + else + if(data[0]==0xFE&&data[1]==0xFF) //utf16-be + { + u16_count=(size-2)>>1; + BigToCurrentEndian((u16char *)(data+2),u16_count); + str=u16_to_u8((u16char *)(data+2),u16_count,char_count); + } + } + + if(!str) +#ifdef __ANDROID__ + return 0; +#else + char_count=to_utf8(cs,&str,(char *)data,size); +#endif// + + line_count=SplitToStringListByEnter(sl,str,char_count); + + delete[] str; + } + + delete[] data; + return line_count; + } + + /** + * 加载一个原始文本块到UTF16StringList + */ + int LoadStringListFromText(UTF16StringList &sl,uchar *data,const int size,const CharSet &cs) + { + u16char *str=nullptr; + + int char_count=0; + int line_count; + + if(size>=2) + { + if(data[0]==0xFF&&data[1]==0xFE) //LE + { + if(size>=4&&data[2]==0&&data[3]==0) //utf32-le + { + str=(u16char *)data; //32->16使用原缓冲区覆盖 + char_count=(size-4)>>2; + LittleToCurrentEndian(str,(uint32 *)(data+4),char_count); + } + else //utf16-le + { + str=(u16char *)(data+2); + char_count=(size-2)>>1; + LittleToCurrentEndian(str,char_count); + } + } + else + if(data[0]==0&&data[1]==0&&data[2]==0xFE&&data[3]==0xFF) //utf32-be + { + str=(u16char *)data; ////32->16使用原缓冲区覆盖 + char_count=(size-4)>>2; + BigToCurrentEndian(str,(uint32 *)(data+4),char_count); + } + else + if(data[0]==0xFE&&data[1]==0xFF) //utf16-be + { + str=(u16char *)(data+2); + char_count=(size-2)>>1; + BigToCurrentEndian(str,char_count); + } + } + + if((uchar *)str>=data&&(uchar *)str<=data+size) //如果str的地址在data的范围内 + { + line_count=SplitToStringListByEnter(sl,str,char_count); + } + else + { + if(size>=3&&data[0]==0xEF&&data[1]==0xBB&&data[2]==0xBF) //utf8 + str=u8_to_u16((char *)(data+3),size-3,char_count); + else + if(cs==UTF8CharSet) + str=u8_to_u16((char *)data,size,char_count); + else + { +#ifdef __ANDROID__ + return 0; +#else + char_count=to_utf16(cs,&str,(char *)data,size); +#endif// + } + + line_count=SplitToStringListByEnter(sl,str,char_count); + + delete[] str; + } + + delete[] data; + return line_count; + } + + /** + * 加载一个原始文本文件到UTF8StringList + */ + int LoadStringListFromTextFile(UTF8StringList &sl,const OSString &filename,const CharSet &cs) + { + uchar *data; + + const int size=filesystem::LoadFileToMemory(filename,(void **)&data); + + if(size<=0) + return size; + + return LoadStringListFromText(sl,data,size,cs); + } + + /** + * 加载一个原始文本文件到UTF16StringList + */ + int LoadStringListFromTextFile(UTF16StringList &sl,const OSString &filename,const CharSet &cs) + { + uchar *data; + + const int size=filesystem::LoadFileToMemory(filename,(void **)&data); + + if(size<=0) + return size; + + return LoadStringListFromText(sl,data,size,cs); + } +}//namespace hgl diff --git a/src/Base/FileSystem/EnumFile.cpp b/src/Base/FileSystem/EnumFile.cpp new file mode 100644 index 00000000..f483045b --- /dev/null +++ b/src/Base/FileSystem/EnumFile.cpp @@ -0,0 +1,42 @@ +#include + +namespace hgl +{ + namespace filesystem + { + namespace + { + class OnlyFileEnum:public EnumFile + { + protected: + + List *fi_list; + + public: + + OnlyFileEnum(List *lfi) + { + fi_list=lfi; + } + + void ProcFile(struct EnumFileConfig *efc,hgl::filesystem::FileInfo &fi) override + { + fi_list->Add(fi); + } + };//class OnlyFileEnum:public EnumFile + }//namespace + + int GetFileInfoList(List &fi_list,const OSString &folder_name,bool proc_folder,bool proc_file,bool sub_folder) + { + EnumFileConfig efc(folder_name); + + efc.proc_folder = proc_folder; + efc.proc_file = proc_file; + efc.sub_folder = sub_folder; + + OnlyFileEnum ofe(&fi_list); + + return ofe.Enum(&efc); + } + }//namespace filesystem +}//namespace hgl diff --git a/src/Base/FileSystem/FileSystem.cpp b/src/Base/FileSystem/FileSystem.cpp new file mode 100644 index 00000000..2e4c5e36 --- /dev/null +++ b/src/Base/FileSystem/FileSystem.cpp @@ -0,0 +1,315 @@ +#include +#include +#include +#include + +#include +#include +#include + +namespace hgl +{ + namespace filesystem + { + constexpr int FILE_PROC_BUF_SIZE=HGL_SIZE_1MB; + + /** + * 比较两个文件是否一样 + * @param filename1 第一个文件的名称 + * @param filename2 第二个文件的名称 + * @return 文件是否一样 + */ + bool FileComp(const OSString &filename1,const OSString &filename2) + { + io::FileInputStream fp1,fp2; + int64 fs1,fs2; + + if(!fp1.Open(filename1))return(false); + if(!fp2.Open(filename2))return(false); + + fs1=fp1.GetSize(); + fs2=fp2.GetSize(); + + if(fs1!=fs2) + return(false); + + int64 pos=0,size; + char *data1,*data2; + + data1=new char[FILE_PROC_BUF_SIZE]; + data2=new char[FILE_PROC_BUF_SIZE]; + + while(posfs1)size=fs1-pos; + + fp1.Read(data1,size); + fp2.Read(data2,size); + + if(memcmp(data1,data2,size)==0) + { + pos+=size; + continue; + } + else + { + delete[] data1; + delete[] data2; + return(false); + } + }; + + delete[] data1; + delete[] data2; + return(true); + } + + /** + * 加载一个文件到内存,文件数据请自己delete[]掉 + * @param filename 要载入的文件名称 + * @param buf 用来保存数据的内存指针的指针 + * @return 文件长度 + */ + int64 LoadFileToMemory(const OSString &filename,void **buf) + { + io::FileInputStream fs; + + if(!fs.Open(filename)) + return(-1); + + const int64 size=fs.GetSize(); + + char *fb=new char[size]; + + if(fs.Read(fb,size)==size) + { + *buf=fb; + return(size); + } + + delete[] fb; + return(-1); + } + + /** + * 保存一块内存成文件 + * @param filename 要保存的文件名称 + * @param buf 要保存的内存指针 + * @param size 要保存的内存数据长度 + * @return 成功写入的字节数 + * @return -1 失败 + */ + int64 SaveMemoryToFile(const OSString &filename,const void *buf,const int64 &size) + { + io::FileOutputStream fs; + + if(!fs.CreateTrunc(filename)) + return(-1); + + return fs.Write(buf,size); + } + + /** + * 保存多块内存成文件 + * @param filename 要保存的文件名称 + * @param buf_list 要保存的内存块指针列表 + * @param buf_size 要保存的内存块数据长度列表 + * @param buf_count 要保存的内存块数量 + * @return 成功写入的字节数 + * @return -1 失败 + */ + int64 SaveMemoryToFile(const OSString &filename,void **buf_list,const int64 *buf_size,const int &buf_count) + { + io::FileOutputStream fs; + + if(!fs.CreateTrunc(filename)) + return(-1); + + int64 total=0; + int64 result; + + for(int i=0;ifile_length) + { + LOG_PROBLEM(OS_TEXT("读取文件<")+filename+OS_TEXT("><")+OSString(offset)+OS_TEXT(",")+OSString(length)+OS_TEXT(">超出了范围,文件长度为<")+OSString(file_length)); + return(nullptr); + } + + char *fb; + + if(buf) + fb=(char *)buf; + else + fb=new char[length]; + + if(fs.Read(offset,fb,length)==length) + { + LOG_INFO(OS_TEXT("加载文件<")+filename+OS_TEXT("><")+OSString(offset)+OS_TEXT(",")+OSString(length)+OS_TEXT(">到缓冲区成功.")); + + return(buf); + } + else + { + if(fb!=buf) + delete[] fb; + + return(nullptr); + } + } + + /** + * 保存内存中的数据到文件中 + * @param filename 文件名 + * @param offset 起始地址 + * @param length 数据长度 + * @param data 数据长度 + * @return 是否成功 + */ + bool SaveMemoryToFile(const OSString &filename,int64 offset,const void *data,int64 length) + { + io::FileOutputStream fs; + + if(!fs.Open(filename)) + return(false); + + return fs.Write(offset,data,length); + } + + bool GetFileInfo(const os_char *filename,struct FileInfo &fi) + { + if(!filename||!*filename) + return(false); + + struct_stat64 file_state; + + memset(&file_state,0,sizeof(struct_stat64)); + + if(hgl_lstat64(filename,&file_state)==-1) + return(false); + + memset(&fi,0,sizeof(FileInfo)); + + if(file_state.st_mode&S_IFREG) + fi.is_file=true; + + if(file_state.st_mode&S_IFDIR) + fi.is_directory=true; + + if (file_state.st_mode&S_IREAD) + fi.can_read = true; + + if (file_state.st_mode&S_IWRITE) + fi.can_write = true; + +#if HGL_OS != HGL_OS_Windows + if(file_state.st_mode&S_IFLNK) + fi.is_link=true; +#endif//HGL_OS != HGL_OS_Windows + + fi.size=file_state.st_size; + + return(true); + } + }//namespace filesystem +}//namespace hgl diff --git a/src/Base/IO/DataInputStream.cpp b/src/Base/IO/DataInputStream.cpp new file mode 100644 index 00000000..03284959 --- /dev/null +++ b/src/Base/IO/DataInputStream.cpp @@ -0,0 +1,248 @@ +#include +#include + +namespace hgl +{ + namespace io + { + template + bool ReadUTF16Chars(u16char *str,DataInputStream *dis,uint count) + { + if(dis->ReadArrays(str,count)!=count) + return(false); + + EndianSwap(str,count); + str[count]=0; + + return(true); + } + + template<> + bool ReadUTF16Chars(u16char *str,DataInputStream *dis,uint count) + { + return(dis->ReadArrays(str,count)==count); + } + + bool DataInputStream::ReadUTF16LEChars(u16char *u16str,uint count) + { + if(!in||!u16str||!count)return(false); + + return ReadUTF16Chars(u16str,this,count); + } + + bool DataInputStream::ReadUTF16BEChars(u16char *u16str,uint count) + { + if(!in||!u16str||!count)return(false); + + return ReadUTF16Chars(u16str,this,count); + } + + template + bool ReadUTF8String(char *buf,uint max_len,DataInputStream *dis) + { + if(!buf||!max_len||!dis) + return(false); + + T str_len; + + if(!dis->ReadNumber(str_len)) + return(false); + + if(str_len<=0) + { + *buf=0; + return(true); + } + + if(max_len>=str_len) + { + if(dis->ReadArrays(buf,str_len)!=str_len) + return(false); + + if(max_len>str_len) + buf[str_len]=0; + + return(true); + } + + if(dis->ReadArrays(buf,max_len)!=max_len) + return(false); + + dis->Skip(str_len-max_len); + + return(true); + } + + bool DataInputStream::ReadUTF8String (char *u8str,uint max_len){return hgl::io::ReadUTF8String(u8str,max_len,this);} + bool DataInputStream::ReadUTF8ShortString (char *u8str,uint max_len){return hgl::io::ReadUTF8String(u8str,max_len,this);} + bool DataInputStream::ReadUTF8TinyString (char *u8str,uint max_len){return hgl::io::ReadUTF8String(u8str,max_len,this);} + + template + bool ReadUTF8String(UTF8String &u8str,uint max_len,DataInputStream *dis) + { + if(!max_len||!dis) + return(false); + + T str_len; + + if(!dis->ReadNumber(str_len)) + return(false); + + if(str_len==0) + { + u8str.Clear(); + return(true); + } + + const uint count=(max_len>str_len?str_len:max_len); + + char *utf8_str=dis->ReadArrays(count); + + if(!utf8_str) + return(false); + + if(countSkip(str_len-count); + + u8str.Set(utf8_str,count,true); + return(true); + } + + bool DataInputStream::ReadUTF8String (UTF8String &u8str,uint max_len){return hgl::io::ReadUTF8String(u8str,max_len,this);} + bool DataInputStream::ReadUTF8ShortString (UTF8String &u8str,uint max_len){return hgl::io::ReadUTF8String(u8str,max_len,this);} + bool DataInputStream::ReadUTF8TinyString (UTF8String &u8str,uint max_len){return hgl::io::ReadUTF8String(u8str,max_len,this);} + + template + bool ReadUTF8String(UTF16String &u16str,uint max_len,DataInputStream *dis) + { + if(!max_len||!dis) + return(false); + + T str_len; + + if(!dis->ReadNumber(str_len)) + return(false); + + if(str_len==0) + { + u16str.Clear(); + return(true); + } + + const uint count=(max_len>str_len?str_len:max_len); + + char *utf8_str=dis->ReadArrays(count); + + if(!utf8_str) + return(false); + + if(countSkip(str_len-count); + + int wide_count; + + u16char *wide_str=u8_to_u16(utf8_str,count,wide_count); + + u16str.Set(wide_str,wide_count,true); + + delete[] utf8_str; + return(true); + } + + bool DataInputStream::ReadUTF8String (UTF16String &u16str,uint max_len){return hgl::io::ReadUTF8String(u16str,max_len,this);} + bool DataInputStream::ReadUTF8ShortString (UTF16String &u16str,uint max_len){return hgl::io::ReadUTF8String(u16str,max_len,this);} + bool DataInputStream::ReadUTF8TinyString (UTF16String &u16str,uint max_len){return hgl::io::ReadUTF8String(u16str,max_len,this);} + + template + bool ReadUTF16String(u16char *str,uint max_len,DataInputStream *dis) + { + if(!dis)return(false); + if(!str||!max_len)return(false); + + T count; + + if(!dis->ReadNumber(count)) + return(false); + + if(count<=0) + { + *str=0; + return(true); + } + + if(max_len>=count) + { + if(dis->ReadArrays(str,count)!=count) + return(false); + + if(max_len>count) + str[count]=0; + } + else + { + if(dis->ReadArrays(str,max_len)!=max_len) + return(false); + + dis->Skip((count-max_len)*sizeof(u16char)); + + count=max_len; + } + + UTF16CharConvert::convert(str,count); + return(true); + } + + bool DataInputStream::ReadUTF16LEString (u16char *u16str,uint max_len){return ReadUTF16String(u16str,max_len,this);} + bool DataInputStream::ReadUTF16LEShortString(u16char *u16str,uint max_len){return ReadUTF16String(u16str,max_len,this);} + bool DataInputStream::ReadUTF16LETinyString (u16char *u16str,uint max_len){return ReadUTF16String(u16str,max_len,this);} + + bool DataInputStream::ReadUTF16BEString (u16char *u16str,uint max_len){return ReadUTF16String(u16str,max_len,this);} + bool DataInputStream::ReadUTF16BEShortString(u16char *u16str,uint max_len){return ReadUTF16String(u16str,max_len,this);} + bool DataInputStream::ReadUTF16BETinyString (u16char *u16str,uint max_len){return ReadUTF16String(u16str,max_len,this);} + + template + bool ReadUTF16String(UTF16String &str,DataInputStream *dis,uint max_len) + { + if(!dis||!max_len)return(false); + + T count; + + if(!dis->ReadNumber(count)) + return(false); + + if(count<0) + return(false); + + if(max_len>0) + { + if(count>max_len) + return(false); + } + + if(count==0) + { + str.Clear(); + return(true); + } + + u16char *utf16_str=dis->ReadArrays(count); + + if(!utf16_str) + return(false); + + UTF16CharConvert::convert(utf16_str,count); + + str.Set(utf16_str,count,true); + + return(true); + } + + bool DataInputStream::ReadUTF16LEString (UTF16String &u16str,uint max_len){return ReadUTF16String(u16str,this,max_len);} + bool DataInputStream::ReadUTF16LEShortString(UTF16String &u16str,uint max_len){return ReadUTF16String(u16str,this,max_len);} + bool DataInputStream::ReadUTF16LETinyString (UTF16String &u16str,uint max_len){return ReadUTF16String(u16str,this,max_len);} + + bool DataInputStream::ReadUTF16BEString (UTF16String &u16str,uint max_len){return ReadUTF16String(u16str,this,max_len);} + bool DataInputStream::ReadUTF16BEShortString(UTF16String &u16str,uint max_len){return ReadUTF16String(u16str,this,max_len);} + bool DataInputStream::ReadUTF16BETinyString (UTF16String &u16str,uint max_len){return ReadUTF16String(u16str,this,max_len);} + }//namespace io +}//namespace hgl diff --git a/src/Base/IO/DataOutputStream.cpp b/src/Base/IO/DataOutputStream.cpp new file mode 100644 index 00000000..5ed2702f --- /dev/null +++ b/src/Base/IO/DataOutputStream.cpp @@ -0,0 +1,185 @@ +#include + +namespace hgl +{ + namespace io // write utf8 chars + { + template<> bool DataOutputStream::WriteUTF8Chars (const char *str,uint size) + { + if(!out)return(false); + if(size==0)return(true); + + if(!str||!*str)return(false); + + return(WriteArrays(str,size)==size); + } + + template<> bool DataOutputStream::WriteUTF8Chars (const u16char *str,uint size) + { + if(!out)return(false); + if(size==0)return(true); + + if(!str||!*str)return(false); + + return WriteUTF8Chars(to_u8(str,size)); + } + } + + namespace io //write utf8 string + { + template bool DataOutputStream::WriteUTF8StringWithLength(const char *str,const uint length) + { + if(!out)return(false); + + if(length&&!str)return(false); + + if(!WriteNumber(length)) + return(false); + + if(!length) + return(true); + + return WriteUTF8Chars(str,length); + } + + template bool DataOutputStream::WriteUTF8StringWithLength(const UTF16String &str) + { + if(!out)return(false); + + int utf8_count; + char *utf8_str=u16_to_u8(str.c_str(),str.Length(),utf8_count); + + const bool result=WriteUTF8StringWithLength(utf8_str,utf8_count); + + delete[] utf8_str; + + return result; + } + } + + namespace io //write utf16 chars + { + template //非特例化版本,用于需要swap的 + bool WriteUTF16Chars(DataOutputStream *dos,const u16char *str,uint count) + { + SharedArray swap_str=new u16char[count]; + + EndianSwap(swap_str,str,count); + + return(dos->WriteArrays(swap_str,count)==count); + } + + template<> //特例化版本,用于直接写入的 + bool WriteUTF16Chars(DataOutputStream *dos,const u16char *str,uint count) + { + return(dos->WriteArrays(str,count)==count); + } + } + + namespace io //write utf16-le chars + { + template<> bool DataOutputStream::WriteUTF16LEChars(const char *str,uint length) + { + if(length==0)return(true); + if(!out||!str||!*str)return(false); + + UTF16String u16_str=to_u16(str); + + return WriteUTF16Chars(this,u16_str.c_str(),u16_str.Length()); + } + + template<> bool DataOutputStream::WriteUTF16LEChars(const u16char *str,uint length) + { + if(length==0)return(true); + if(!out||!str||!*str)return(false); + + return WriteUTF16Chars(this,str,length); + } + } + + namespace io //write utf16-be chars + { + template<> bool DataOutputStream::WriteUTF16BEChars(const char *str,uint length) + { + if(length==0)return(true); + if(!out||!str||!*str)return(false); + + UTF16String u16_str=to_u16(str,length); + + return WriteUTF16Chars(this,u16_str.c_str(),u16_str.Length()); + } + + template<> bool DataOutputStream::WriteUTF16BEChars(const u16char *str,uint length) + { + if(length==0)return(true); + if(!out||!str||!*str)return(false); + + return WriteUTF16Chars(this,str,length); + } + }//namespace io + + namespace io //write utf16 string + { + template bool DataOutputStream::WriteUTF16StringWithLength(const u16char *str,const uint len) + { + if(!out)return(false); + if(len&&!str)return(false); + + if(!WriteNumber(len)) + return(false); + + if(!len)return(true); + + return WriteUTF16Chars(this,str,len); + } + }//namespace io + + namespace io + { + bool DataOutputStream::WriteUTF8String (const char *str,uint length){return WriteUTF8StringWithLength(str, length);} ///<按utf16-le格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF8String (const char *str ){return WriteUTF8StringWithLength(str, hgl::strlen(str));} ///<按utf8格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF8String (const UTF8String &str ){return WriteUTF8StringWithLength(str.c_str(), str.Length());} ///<按utf8格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF8String (const UTF16String &str ){return WriteUTF8StringWithLength(str);} ///<按utf8格式写入字符串(前置4字节字符串长度,再写入字符阵列) + + bool DataOutputStream::WriteUTF16LEString (const u16char *str,uint len){return WriteUTF16StringWithLength(str, len);} ///<按utf16-le格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF16BEString (const u16char *str,uint len){return WriteUTF16StringWithLength(str, len);} ///<按utf16-be格式写入字符串(前置4字节字符串长度,再写入字符阵列) + + bool DataOutputStream::WriteUTF16LEString (const UTF16String &str ){return WriteUTF16StringWithLength(str.c_str(),str.Length());} ///<按utf16-le格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF16BEString (const UTF16String &str ){return WriteUTF16StringWithLength(str.c_str(),str.Length());} ///<按utf16-be格式写入字符串(前置4字节字符串长度,再写入字符阵列) + + bool DataOutputStream::WriteUTF16LEString (const u16char *str ){return WriteUTF16StringWithLength(str, hgl::strlen(str));} ///<按utf16-le格式写入字符串(前置4字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF16BEString (const u16char *str ){return WriteUTF16StringWithLength(str, hgl::strlen(str));} ///<按utf16-be格式写入字符串(前置4字节字符串长度,再写入字符阵列) + + + + bool DataOutputStream::WriteUTF8ShortString (const char *str,uint length){return WriteUTF8StringWithLength(str, length);} ///<按utf16-le格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF8ShortString (const char *str ){return WriteUTF8StringWithLength(str, hgl::strlen(str));} ///<按utf8格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF8ShortString (const UTF8String &str ){return WriteUTF8StringWithLength(str.c_str(), str.Length());} ///<按utf8格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF8ShortString (const UTF16String &str ){return WriteUTF8StringWithLength(str);} ///<按utf8格式写入字符串(前置2字节字符串长度,再写入字符阵列) + + bool DataOutputStream::WriteUTF16LEShortString(const u16char *str,uint len){return WriteUTF16StringWithLength(str, len);} ///<按utf16-le格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF16BEShortString(const u16char *str,uint len){return WriteUTF16StringWithLength(str, len);} ///<按utf16-be格式写入字符串(前置2字节字符串长度,再写入字符阵列) + + bool DataOutputStream::WriteUTF16LEShortString(const UTF16String &str ){return WriteUTF16StringWithLength(str.c_str(),str.Length());} ///<按utf16-le格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF16BEShortString(const UTF16String &str ){return WriteUTF16StringWithLength(str.c_str(),str.Length());} ///<按utf16-be格式写入字符串(前置2字节字符串长度,再写入字符阵列) + + bool DataOutputStream::WriteUTF16LEShortString(const u16char *str ){return WriteUTF16StringWithLength(str, hgl::strlen(str));} ///<按utf16-le格式写入字符串(前置2字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF16BEShortString(const u16char *str ){return WriteUTF16StringWithLength(str, hgl::strlen(str));} ///<按utf16-be格式写入字符串(前置2字节字符串长度,再写入字符阵列) + + + + bool DataOutputStream::WriteUTF8TinyString (const char *str,uint length){return WriteUTF8StringWithLength(str, length);} ///<按utf16-le格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF8TinyString (const char *str ){return WriteUTF8StringWithLength(str, hgl::strlen(str));} ///<按utf8格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF8TinyString (const UTF8String &str ){return WriteUTF8StringWithLength(str.c_str(), str.Length());} ///<按utf8格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF8TinyString (const UTF16String &str ){return WriteUTF8StringWithLength(str);} ///<按utf8格式写入字符串(前置1字节字符串长度,再写入字符阵列) + + bool DataOutputStream::WriteUTF16LETinyString (const u16char *str,uint len){return WriteUTF16StringWithLength(str, len);} ///<按utf16-le格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF16BETinyString (const u16char *str,uint len){return WriteUTF16StringWithLength(str, len);} ///<按utf16-be格式写入字符串(前置1字节字符串长度,再写入字符阵列) + + bool DataOutputStream::WriteUTF16LETinyString (const UTF16String &str ){return WriteUTF16StringWithLength(str.c_str(), str.Length());} ///<按utf16-le格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF16BETinyString (const UTF16String &str ){return WriteUTF16StringWithLength(str.c_str(), str.Length());} ///<按utf16-be格式写入字符串(前置1字节字符串长度,再写入字符阵列) + + bool DataOutputStream::WriteUTF16LETinyString (const u16char *str ){return WriteUTF16StringWithLength(str, hgl::strlen(str));} ///<按utf16-le格式写入字符串(前置1字节字符串长度,再写入字符阵列) + bool DataOutputStream::WriteUTF16BETinyString (const u16char *str ){return WriteUTF16StringWithLength(str, hgl::strlen(str));} ///<按utf16-be格式写入字符串(前置1字节字符串长度,再写入字符阵列) + }//namespace io +}//namespace hgl diff --git a/src/Base/IO/FileAccess.cpp b/src/Base/IO/FileAccess.cpp new file mode 100644 index 00000000..08475d56 --- /dev/null +++ b/src/Base/IO/FileAccess.cpp @@ -0,0 +1,174 @@ +#include +#include +#include + +#if HGL_OS != HGL_OS_Windows +#include +#else +#include +#endif//HGL_OS!=HGL_OS_Windows +namespace hgl +{ + namespace io + { + FileAccess::FileAccess() + { + fp=-1; + mode=fomNone; + } + + FileAccess::~FileAccess() + { + Close(); + } + + int OpenFile(const os_char *fn,FileOpenMode fom); + + bool FileAccess::Open(const OSString &fn,FileOpenMode fom) + { + Close(); + + if(fn.IsEmpty()) + { + LOG_ERROR(OS_TEXT("Error,filename is NULL")); + return(false); + } + + fp=OpenFile(fn.c_str(),fom); + + if(fp==-1) + { + LOG_ERROR(OS_TEXT("open file error,filename: ")+fn); + return(false); + } + + filename=fn; + mode=fom; + return(true); + } + + void CloseFile(int fp); + + void FileAccess::Close() + { + if(fp==-1)return; + + CloseFile(fp); + + fp=-1; + mode=fomNone; + } + + void FileAccess::CloseRead() + { + if(fp==-1)return; + + if(!CanWrite()) + Close(); + + mode=fomOnlyWrite; + } + + void FileAccess::CloseWrite() + { + if(fp==-1)return; + + if(!CanRead()) + Close(); + + mode=fomOnlyRead; + } + + bool FileAccess::CanRead() const + { + if(fp==-1)return(false); + + if(mode==fomOnlyWrite)return(false); + + return true; + } + + bool FileAccess::CanWrite() const + { + if(fp==-1)return(false); + + if(mode==fomOnlyRead)return(false); + + return(true); + } + + bool FileAccess::CanSeek() const + { + if(fp==-1)return(false); + if(mode=fomAppend)return(false); + + return(true); + } + + int64 FileAccess::Seek(int64 offset,SeekOrigin orign) + { + if(!CanSeek())return(-1); + + return hgl_lseek64(fp,offset,orign); + } + + int64 FileAccess::Tell()const + { + if(fp==-1)return(-1); + + return hgl_tell64(fp); + } + + int64 FileAccess::GetSize() + { + if(!CanSize())return(-1); + + hgl_fstat64(fp,&file_state); + return(file_state.st_size); + } + + int64 FileAccess::AvailableRead() + { + if(fp==-1)return(-1); + + if(mode!=fomOnlyRead + &&mode!=fomReadWrite) + return(-1); + + return GetSize()-Tell(); + } + + bool FileAccess::Restart() + { + if(!CanRestart())return(false); + + return(Seek(0,soBegin)==0); + } + + int64 FileAccess::Read(void *buf,int64 size) + { + if(!CanRead())return(-1); + + return hgl_read64(fp,buf,size); + } + + int64 FileAccess::Peek(void *buf,int64 size) + { + if(!CanPeek())return(-1); + + int result=hgl_read64(fp,buf,size); + + if(result>0) + hgl_lseek64(fp,-result,soCurrent); //回移这个长度 + + return result; + } + + int64 FileAccess::Write(const void *buf,int64 size) + { + if(!CanWrite())return(-1); + + return hgl_write64(fp,buf,size); + } + }//namespace io +}//namespace hgl diff --git a/src/Base/IO/FileInputStream.cpp b/src/Base/IO/FileInputStream.cpp new file mode 100644 index 00000000..f1d1077a --- /dev/null +++ b/src/Base/IO/FileInputStream.cpp @@ -0,0 +1,65 @@ +#include +namespace hgl +{ + namespace io + { + FileInputStream::FileInputStream() + { + } + + FileInputStream::FileInputStream(SharedPtr &fa) + { + file=fa; + } + + FileInputStream::~FileInputStream() + { + Close(); + } + + bool FileInputStream::Open(const OSString &filename) + { + Close(); + + if(filename.IsEmpty()) + return(false); + + file=new FileAccess(); + + if(!file->Open(filename,fomOnlyRead)) + { + file=nullptr; + return(false); + } + + return(true); + } + + void FileInputStream::Close() + { + if(file) + { + file->Close(); + file=nullptr; + } + } + + int64 FileInputStream::Read (void *buf,int64 size) {return file?file->Read(buf,size):-1;} + int64 FileInputStream::Peek (void *buf,int64 size) {return file?file->Peek(buf,size):-1;} + + bool FileInputStream::CanSeek ()const {return file?file->CanSeek():false;} + bool FileInputStream::CanRestart ()const {return file?file->CanRestart():false;} + bool FileInputStream::CanSize ()const {return file?file->CanSize():false;} + bool FileInputStream::CanPeek ()const {return file?file->CanPeek():false;} + + int64 FileInputStream::Skip (int64 bytes) {return file?file->Seek(bytes,soCurrent):-1;} + int64 FileInputStream::Tell ()const {return file?file->Tell():-1;} + int64 FileInputStream::GetSize ()const {return file?file->GetSize():-1;} + bool FileInputStream::Restart () {return file?file->Restart():false;} + int64 FileInputStream::Seek (int64 off,SeekOrigin so) {return file?file->Seek(off,so):-1;} + + int64 FileInputStream::Available ()const {return file?file->AvailableRead():-1;} + + int64 FileInputStream::Read (int64 off,void *buf,int64 size){return file?file->Read(off,buf,size):-1;} + }//namespace io +}//namespace hgl diff --git a/src/Base/IO/FileOutputStream.cpp b/src/Base/IO/FileOutputStream.cpp new file mode 100644 index 00000000..5bccd910 --- /dev/null +++ b/src/Base/IO/FileOutputStream.cpp @@ -0,0 +1,60 @@ +#include +namespace hgl +{ + namespace io + { + FileOutputStream::FileOutputStream() + { + } + + FileOutputStream::FileOutputStream(SharedPtr &fa) + { + file=fa; + } + + FileOutputStream::~FileOutputStream() + { + Close(); + } + + bool FileOutputStream::OpenFile(const OSString &filename,FileOpenMode mode) + { + Close(); + + if(filename.IsEmpty()) + return(false); + + file=new FileAccess(); + + if(!file->Open(filename,mode)) + { + file=nullptr; + return(false); + } + + return(true); + } + + void FileOutputStream::Close() + { + if(file) + { + file->CloseWrite(); + file=nullptr; + } + } + + int64 FileOutputStream::Write (const void *buf,int64 size) {return file?file->Write(buf,size):-1;} + + bool FileOutputStream::CanSeek ()const {return file?file->CanSeek():false;} + bool FileOutputStream::CanRestart()const {return file?file->CanRestart():false;} + bool FileOutputStream::CanSize ()const {return file?file->CanSize():false;} + + int64 FileOutputStream::Tell ()const {return file?file->Tell():-1;} + int64 FileOutputStream::GetSize ()const {return file?file->GetSize():-1;} + bool FileOutputStream::Restart () {return file?file->Restart():false;} + int64 FileOutputStream::Seek (int64 off,SeekOrigin so) {return file?file->Seek(off,so):-1;} + + int64 FileOutputStream::Write (int64 off,const void *buf,int64 size) {return file?file->Write(off,buf,size):-1;} + }//namespace io +}//namespace hgl diff --git a/src/Base/IO/IOType.cpp b/src/Base/IO/IOType.cpp new file mode 100644 index 00000000..b39d8766 --- /dev/null +++ b/src/Base/IO/IOType.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +namespace hgl +{ + namespace io + { +#define IO_TYPE_DEFINE(small,large) typedef io_type io##large; \ + \ + template<> bool io_type::Read(hgl::io::DataInputStream *dis) \ + { \ + if(!dis)return(false); \ + return dis->Read##large(value); \ + } \ + \ + template<> bool io_type::Write(hgl::io::DataOutputStream *dos)const \ + { \ + if(!dos)return(false); \ + return dos->Write##large(value); \ + } + + IO_TYPE_DEFINE(int8,Int8); + IO_TYPE_DEFINE(int16,Int16); + IO_TYPE_DEFINE(int32,Int32); + IO_TYPE_DEFINE(int64,Int64); + + IO_TYPE_DEFINE(uint8,Uint8); + IO_TYPE_DEFINE(uint16,Uint16); + IO_TYPE_DEFINE(uint32,Uint32); + IO_TYPE_DEFINE(uint64,Uint64); + + IO_TYPE_DEFINE(bool,Bool); + IO_TYPE_DEFINE(float,Float); + IO_TYPE_DEFINE(double,Double); +#undef IO_TYPE_DEFINE + }//namespace io +}//namespace hgl diff --git a/src/Base/IO/RandomAccessFile.cpp b/src/Base/IO/RandomAccessFile.cpp new file mode 100644 index 00000000..7feda481 --- /dev/null +++ b/src/Base/IO/RandomAccessFile.cpp @@ -0,0 +1,60 @@ +#include +#include +#include + +namespace hgl +{ + namespace io + { + RandomAccessFile::RandomAccessFile() + { + file=nullptr; + } + + RandomAccessFile::RandomAccessFile(SharedPtr &f) + { + file=f; + } + + RandomAccessFile::~RandomAccessFile() + { + Close(); + } + + bool RandomAccessFile::Open(const OSString &filename) + { + Close(); + + file=new FileAccess(); + + if(!file->Open(filename,fomReadWrite)) + { + file=nullptr; + return(false); + } + + return(true); + } + + void RandomAccessFile::Close() + { + if(file) + file=nullptr; + } + + int64 RandomAccessFile::Read (void *buf,int64 size) {return file?file->Read(buf,size):-1;} + int64 RandomAccessFile::Write (const void *buf,int64 size) {return file?file->Write(buf,size):-1;} + + bool RandomAccessFile::CanSeek ()const {return file?file->CanSeek():false;} + bool RandomAccessFile::CanRestart()const {return file?file->CanRestart():false;} + bool RandomAccessFile::CanSize ()const {return file?file->CanSize():false;} + + int64 RandomAccessFile::Tell ()const {return file?file->Tell():-1;} + int64 RandomAccessFile::GetSize () {return file?file->GetSize():-1;} + bool RandomAccessFile::Restart () {return file?file->Restart():false;} + int64 RandomAccessFile::Seek (int64 off,SeekOrigin so) {return file?file->Seek(off,so):-1;} + + int64 RandomAccessFile::Read (int64 off,void *buf,int64 size) {return file?file->Read(off,buf,size):-1;} + int64 RandomAccessFile::Write (int64 off,const void *buf,int64 size) {return file?file->Write(off,buf,size):-1;} + }//namespace io +}//namespace hgl diff --git a/src/Base/IO/TextOutputStream.cpp b/src/Base/IO/TextOutputStream.cpp new file mode 100644 index 00000000..65560e57 --- /dev/null +++ b/src/Base/IO/TextOutputStream.cpp @@ -0,0 +1,47 @@ +#include +#include +namespace hgl +{ + namespace io + { + template<> EndianTextOutputStream::EndianTextOutputStream(OutputStream *os):TextOutputStream(bomUTF8,new DirectDataOutputStream(os)){} + template<> EndianTextOutputStream::EndianTextOutputStream(OutputStream *os):TextOutputStream(bomUTF16LE,new LEDataOutputStream(os)){} + template<> EndianTextOutputStream::EndianTextOutputStream(OutputStream *os):TextOutputStream(bomUTF16BE,new BEDataOutputStream(os)){} + + template<> TextOutputStream *CreateTextOutputStream(OutputStream *os){return(new UTF8TextOutputStream(os));} + template<> TextOutputStream *CreateTextOutputStream(OutputStream *os){return(new UTF16LETextOutputStream(os));} + }//namespace io + + namespace io //WriteChars函数 + { + template<> bool EndianTextOutputStream::WriteChars(const char *str,int64 size) + { + return out?out->WriteUTF8Chars(str,size):false; + } + + template<> bool EndianTextOutputStream::WriteChars(const u16char *str,int64 size) + { + return out?out->WriteUTF8Chars(str,size):false; + } + + template<> bool EndianTextOutputStream::WriteChars(const char *str,int64 size) + { + return out?out->WriteUTF16LEChars(str,size):false; + } + + template<> bool EndianTextOutputStream::WriteChars(const u16char *str,int64 size) + { + return out?out->WriteUTF16LEChars(str,size):false; + } + + template<> bool EndianTextOutputStream::WriteChars(const char *str,int64 size) + { + return out?out->WriteUTF16BEChars(str,size):false; + } + + template<> bool EndianTextOutputStream::WriteChars(const u16char *str,int64 size) + { + return out?out->WriteUTF16BEChars(str,size):false; + } + }//namespace io +}//namespace hgl diff --git a/src/Base/CodePage.cpp b/src/Base/Other/CodePage.cpp similarity index 96% rename from src/Base/CodePage.cpp rename to src/Base/Other/CodePage.cpp index 5858e6a1..b104a24e 100644 --- a/src/Base/CodePage.cpp +++ b/src/Base/Other/CodePage.cpp @@ -1,267 +1,267 @@ -#include - -namespace hgl -{ - CharSet DefaultCharSet(); - - CharSet UTF8CharSet (ccpUTF8, utf8_charset ); - CharSet UTF16LECharSet (ccpUTF16LE,utf16le_charset ); - CharSet UTF16BECharSet (ccpUTF16BE,utf16be_charset ); - - int u16_to_u8(char *dst,int dst_size,const u16char *src,const int src_size) - { - if(src_size<=0||!src||!*src) - { - if(dst&&dst_size>0) - *dst=0; - - return(0); - } - - if(!dst||dst_size<=0) - return(-1); - - const u16char *sp=src; - uint8 *tp=(uint8 *)dst; - - while(*sp&&(int(tp-(uint8 *)dst)> 6)&0x1F); - *tp++=0x80|((*sp )&0x3F); - } - else // U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx - { - *tp++=0xE0|((*sp>>12)&0x0F); - *tp++=0x80|((*sp>> 6)&0x3F); - *tp++=0x80|((*sp )&0x3F); - } - - sp++; - } - -// *tp=0; - - return int(tp-(uint8 *)dst); - } - - int u8_to_u16(u16char *dst,int dst_size,const char *src,const int src_size) - { - if(src_size<=0||!src||!*src) - { - if(dst&&dst_size>0) - *dst=0; - - return(0); - } - - if(!dst||dst_size<=0) - return(-1); - - const uint8 *sp=(uint8 *)src; - u16char *tp=dst; - - while(*sp&&(int(tp-dst)=0xC0)&&(*sp<0xE0)) // U-00000080 - U-000007FF: 110xxxxx 10xxxxxx - { - *tp =((*sp++)&0x1F)<<6; - *tp|=((*sp++)&0x3F); - } - else if((*sp>=0xE0)&&(*sp<0xF0)) // U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx - { - *tp =((*sp++)&0x0F)<<12; - *tp|=((*sp++)&0x3F)<<6; - *tp|=((*sp++)&0x3F); - } - else if((*sp>=0xF0)&&(*sp<0xF8)) // U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - { - sp+=4; //不解析 - } - else if((*sp>=0xF8)&&(*sp<0xFC)) // U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - { - sp+=5; //不解析 - } - else if((*sp>=0xFC)) // U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - { - sp+=6; //不解析 - } - else - { - *tp=0; - break; - } - - tp++; - } - -// *tp=0; - - return int(tp-dst); - } - - /** - * 转换u16char *字符串到utf8格式char *字符串 - * @param src 源字符串 - * @param src_size 源字符串字符数 - * @param dst_size 结果字符串字符数 - * @return 转换结果,需自行delete[] - */ - char *u16_to_u8(const u16char *src,const int src_size,int &dst_size) - { - if(src_size<=0||!src||!*src) - { - dst_size=0; - return(nullptr); - } - - const u16char *sp=src; - dst_size=0; - - while(*sp&&(sp-src=0xC0)&&(*sp<0xE0)) // U-00000080 - U-000007FF: 110xxxxx 10xxxxxx - { - sp+=2; - dst_size++; - } - else if((*sp>=0xE0)&&(*sp<0xF0)) // U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx - { - sp+=3; - dst_size++; - } - else if((*sp>=0xF0)&&(*sp<0xF8)) // U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - { - sp+=4; //不解析 - } - else if((*sp>=0xF8)&&(*sp<0xFC)) // U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - { - sp+=5; //不解析 - } - else if((*sp>=0xFC)) // U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - { - sp+=6; //不解析 - } - else - { - break; - } - } - - if(dst_size<=0) - return(nullptr); - - u16char *dst=new u16char[dst_size+1]; - - dst[dst_size]=0; //为防止内存检测工具报错,所以提前赋0 - - u8_to_u16(dst,dst_size,src,src_size); - - return dst; - } - - /** - * 分析这个unicode文本文件的字节序 - * @param input 输入数据 - * @return 字节序 - */ - const BOMFileHeader *ParseBOM(const void *input) - { - if(!input)return(nullptr); - - const BOMFileHeader *bfh=BOMData+bomUTF8; - - for(uint i=bomUTF8;idata,bfh->size)==0) - return bfh; - - ++bfh; - } - - return nullptr; - } - - /** - * 转换BOM数据到CharSet结构 - * @param bom BOM数据 - * @param cs 字符集数据结构 - * @return 是否转换成功 - */ - bool BOM2CharSet(CharSet *cs,const BOMFileHeader *bom) - { - if(!cs)return(false); - if(!bom)return(false); - - if(bom->bom<=bomNone||bom->bom>=bomEnd)return(false); - - cs->codepage=bom->code_page; - memcpy(cs->charset,bom->char_set,sizeof(CharSetName)); - return(true); - } -}//namespace hgl +#include + +namespace hgl +{ + CharSet DefaultCharSet(); + + CharSet UTF8CharSet (ccpUTF8, utf8_charset ); + CharSet UTF16LECharSet (ccpUTF16LE,utf16le_charset ); + CharSet UTF16BECharSet (ccpUTF16BE,utf16be_charset ); + + int u16_to_u8(char *dst,int dst_size,const u16char *src,const int src_size) + { + if(src_size<=0||!src||!*src) + { + if(dst&&dst_size>0) + *dst=0; + + return(0); + } + + if(!dst||dst_size<=0) + return(-1); + + const u16char *sp=src; + uint8 *tp=(uint8 *)dst; + + while(*sp&&(int(tp-(uint8 *)dst)> 6)&0x1F); + *tp++=0x80|((*sp )&0x3F); + } + else // U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx + { + *tp++=0xE0|((*sp>>12)&0x0F); + *tp++=0x80|((*sp>> 6)&0x3F); + *tp++=0x80|((*sp )&0x3F); + } + + sp++; + } + +// *tp=0; + + return int(tp-(uint8 *)dst); + } + + int u8_to_u16(u16char *dst,int dst_size,const char *src,const int src_size) + { + if(src_size<=0||!src||!*src) + { + if(dst&&dst_size>0) + *dst=0; + + return(0); + } + + if(!dst||dst_size<=0) + return(-1); + + const uint8 *sp=(uint8 *)src; + u16char *tp=dst; + + while(*sp&&(int(tp-dst)=0xC0)&&(*sp<0xE0)) // U-00000080 - U-000007FF: 110xxxxx 10xxxxxx + { + *tp =((*sp++)&0x1F)<<6; + *tp|=((*sp++)&0x3F); + } + else if((*sp>=0xE0)&&(*sp<0xF0)) // U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx + { + *tp =((*sp++)&0x0F)<<12; + *tp|=((*sp++)&0x3F)<<6; + *tp|=((*sp++)&0x3F); + } + else if((*sp>=0xF0)&&(*sp<0xF8)) // U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + { + sp+=4; //不解析 + } + else if((*sp>=0xF8)&&(*sp<0xFC)) // U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + { + sp+=5; //不解析 + } + else if((*sp>=0xFC)) // U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + { + sp+=6; //不解析 + } + else + { + *tp=0; + break; + } + + tp++; + } + +// *tp=0; + + return int(tp-dst); + } + + /** + * 转换u16char *字符串到utf8格式char *字符串 + * @param src 源字符串 + * @param src_size 源字符串字符数 + * @param dst_size 结果字符串字符数 + * @return 转换结果,需自行delete[] + */ + char *u16_to_u8(const u16char *src,const int src_size,int &dst_size) + { + if(src_size<=0||!src||!*src) + { + dst_size=0; + return(nullptr); + } + + const u16char *sp=src; + dst_size=0; + + while(*sp&&(sp-src=0xC0)&&(*sp<0xE0)) // U-00000080 - U-000007FF: 110xxxxx 10xxxxxx + { + sp+=2; + dst_size++; + } + else if((*sp>=0xE0)&&(*sp<0xF0)) // U-00000800 - U-0000FFFF: 1110xxxx 10xxxxxx 10xxxxxx + { + sp+=3; + dst_size++; + } + else if((*sp>=0xF0)&&(*sp<0xF8)) // U-00010000 - U-001FFFFF: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx + { + sp+=4; //不解析 + } + else if((*sp>=0xF8)&&(*sp<0xFC)) // U-00200000 - U-03FFFFFF: 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + { + sp+=5; //不解析 + } + else if((*sp>=0xFC)) // U-04000000 - U-7FFFFFFF: 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx + { + sp+=6; //不解析 + } + else + { + break; + } + } + + if(dst_size<=0) + return(nullptr); + + u16char *dst=new u16char[dst_size+1]; + + dst[dst_size]=0; //为防止内存检测工具报错,所以提前赋0 + + u8_to_u16(dst,dst_size,src,src_size); + + return dst; + } + + /** + * 分析这个unicode文本文件的字节序 + * @param input 输入数据 + * @return 字节序 + */ + const BOMFileHeader *ParseBOM(const void *input) + { + if(!input)return(nullptr); + + const BOMFileHeader *bfh=BOMData+bomUTF8; + + for(uint i=bomUTF8;idata,bfh->size)==0) + return bfh; + + ++bfh; + } + + return nullptr; + } + + /** + * 转换BOM数据到CharSet结构 + * @param bom BOM数据 + * @param cs 字符集数据结构 + * @return 是否转换成功 + */ + bool BOM2CharSet(CharSet *cs,const BOMFileHeader *bom) + { + if(!cs)return(false); + if(!bom)return(false); + + if(bom->bom<=bomNone||bom->bom>=bomEnd)return(false); + + cs->codepage=bom->code_page; + memcpy(cs->charset,bom->char_set,sizeof(CharSetName)); + return(true); + } +}//namespace hgl diff --git a/src/Base/Other/DateTime.cpp b/src/Base/Other/DateTime.cpp new file mode 100644 index 00000000..f2782401 --- /dev/null +++ b/src/Base/Other/DateTime.cpp @@ -0,0 +1,348 @@ +#include +#include + +#include +#include + +#include + +#include + +namespace hgl +{ + bool Time::SaveToStream(io::DataOutputStream *str) const + { + if(!str)return(false); + + if(!str->WriteInt8(hours))return(false); + if(!str->WriteInt8(minutes))return(false); + if(!str->WriteInt8(seconds))return(false); + if(!str->WriteInt32(micro_seconds))return(false); + if(!str->WriteInt32(gmt_off))return(false); + + return(true); + } + + bool Time::LoadFromStream(io::DataInputStream *str) + { + if(!str)return(false); + + if(!str->ReadInt8(hours))return(false); + if(!str->ReadInt8(minutes))return(false); + if(!str->ReadInt8(seconds))return(false); + if(!str->ReadInt32(micro_seconds))return(false); + if(!str->ReadInt32(gmt_off))return(false); + + return(true); + } + + Time::Time() + { + hours=0; + minutes=0; + seconds=0; + micro_seconds=0; + } + + Time::Time(const double t) + { + Sync(t); + } + + Time::Time(int h,int m,int s,int ms) + { + hours=h; + minutes=m; + seconds=s; + micro_seconds=ms; + } + + Time::Time(const Time &t) + { + operator = (t); + } + + /** + * 设置时间 + * @param h 小时 + * @param m 分 + * @param s 秒 + * @param ms 微秒(百分分之一秒) + */ + void Time::Set(int h,int m,int s,int ms,int wd) + { + hours=h; + minutes=m; + seconds=s; + micro_seconds=ms; + week_day=wd; + } + + Time &Time::operator=(const Time &t) + { + hours =t.hours; + minutes =t.minutes; + seconds =t.seconds; + micro_seconds =t.micro_seconds; + + return(*this); + } + + const int Time::Comp(const Time &t)const + { + if(hours!=t.hours) + return hours-t.hours; + + if(minutes!=t.minutes) + return minutes-t.minutes; + + if(seconds!=t.seconds) + return seconds-t.seconds; + + return micro_seconds-t.micro_seconds; + } + + void Time::SetHour(int h) + { + if(h<0) + { + while(h<0) + h+=HGL_HOUR_ONE_DAY; + } + else if(h>0) + { + while(h>(HGL_HOUR_ONE_DAY-1)) + h-=HGL_HOUR_ONE_DAY; + } + + hours=h; + } + + void Time::SetMinute(int m) + { + int h=hours; + + if(m<0) + { + while(m<0) + { + m+=HGL_TIME_ONE_MINUTE; + h--; + } + } + else if(m>0) + { + while(m>(HGL_TIME_ONE_MINUTE-1)) + { + m-=HGL_TIME_ONE_MINUTE; + h++; + } + } + + minutes=m; + SetHour(h); + } + + void Time::SetSecond(int s) + { + int m=minutes; + + if(s<0) + { + while(s<0) + { + s+=HGL_TIME_ONE_MINUTE; + m--; + } + } + else if(s>0) + { + while(s>(HGL_TIME_ONE_MINUTE-1)) + { + s-=HGL_TIME_ONE_MINUTE; + m++; + } + } + + seconds=s; + SetMinute(m); + } + + void Time::SetMicroSecond(int ms) + { + int s=seconds; + + if(ms<0) + { + while(ms<0) + { + ms-=HGL_MICRO_SEC_PER_SEC; + s--; + } + } + else if(ms>0) + { + while(ms>(HGL_MICRO_SEC_PER_SEC-1)) + { + ms-=HGL_MICRO_SEC_PER_SEC; + s++; + } + } + + micro_seconds=ms; + SetSecond(s); + } +}//namespace hgl +//-------------------------------------------------------------------------------------------------- +namespace hgl +{ + Date::Date(const double t) + { + Sync(t); + } + + Date::Date(const Date &t) + { + operator = (t); + } + + Date &Date::operator=(const Date &t) + { + year =t.year; + month =t.month; + day =t.day; + max_days_per_month=t.max_days_per_month; + week_day=t.week_day; + year_day=t.year_day; + + return(*this); + } + + const int Date::Comp(const Date &t)const + { + if(year!=t.year) + return year-t.year; + + if(month!=t.month) + return month-t.month; + + return day-t.day; + } + + bool Date::SaveToStream(io::DataOutputStream *str) const + { + if(!str)return(false); + + if(!str->WriteInt32(year))return(false); + if(!str->WriteInt8(month))return(false); + if(!str->WriteInt8(day))return(false); + if(!str->WriteInt8(max_days_per_month))return(false); + if(!str->WriteInt8(week_day))return(false); + if(!str->WriteInt16(year_day))return(false); + + return(true); + } + + bool Date::LoadFromStream(io::DataInputStream *str) + { + if(!str)return(false); + + if(!str->ReadInt32(year))return(false); + if(!str->ReadInt8(month))return(false); + if(!str->ReadInt8(day))return(false); + if(!str->ReadInt8(max_days_per_month))return(false); + if(!str->ReadInt8(week_day))return(false); + if(!str->ReadInt16(year_day))return(false); + + return(true); + } + + Date::Date() + { + year=2000; + month=1; + day=1; + week_day=0; + year_day=0; + max_days_per_month=0; + } + + Date::Date(int y,int m,int d) + { + Set(y,m,d); + } + + void Date::Set(int y,int m,int d,int wd,int yd) + { + day=d; + month=m; + year=y; + week_day=wd; + year_day=yd; + max_days_per_month=0; + } + + void Date::SetMonth(int m) + { + if(m<1) + { + while(m<1) + { + m+=HGL_MONTH_ONE_YEAR; + year--; + } + } + else + { + while(m>HGL_MONTH_ONE_YEAR) + { + m-=HGL_MONTH_ONE_YEAR; + year++; + } + } + + month=m; + + const int md[HGL_MONTH_ONE_YEAR]={31,0,31,30,31,30,31,31,30,31,30,31}; + + if(month==2) + max_days_per_month=((year%4)?28:29); + else + max_days_per_month=md[month-1]; + } + + void Date::SetDay(int d) + { + int m=month; + + if(d<1) + { + while(d<1) + { + d+=max_days_per_month; + m--; + } + } + else + { + while(d>max_days_per_month) + { + d-=max_days_per_month; + m++; + } + } + + day=d; + SetMonth(m); + } +}//namespace hgl + +namespace hgl +{ + double FromDateTime(const Date &d,const Time &t) + { + return FromDateTime(d.GetYear(),d.GetMonth(),d.GetDay(), + t.GetHour(),t.GetMinute(),t.GetSecond(),t.GetMicroSecond(), + t.GetGMT()); + } +}//namespace hgl diff --git a/src/Base/Other/ExpendString.cpp b/src/Base/Other/ExpendString.cpp new file mode 100644 index 00000000..879df02d --- /dev/null +++ b/src/Base/Other/ExpendString.cpp @@ -0,0 +1,120 @@ +#include +#include +#include + +namespace hgl +{ + Map ExpendString; + + void SetExpendString(const OSString &flag,const OSString &str) + { + OSString flag_string=flag; + + flag_string.LowerCase(); + + ExpendString.Add(flag_string,str); + } + + void ClearExpendString(const OSString &flag) + { + OSString flag_string=flag; + + flag_string.LowerCase(); + + ExpendString.DeleteByKey(flag_string); + } + + bool GetExpendString(const OSString &flag,OSString &str) + { + struct + { + os_char flag[16]; + HGLFlagString index; + } + FlagStringIndex[]= + { + {OS_TEXT("CMGDK" ), hfsCMGDKPath }, + {OS_TEXT("PlugIn" ), hfsPlugInPath }, + {OS_TEXT("GUI" ), hfsGUIPath }, + {OS_TEXT("Start" ), hfsStartPath }, + + {OS_TEXT("OS" ), hfsOSPath }, + {OS_TEXT("Desktop" ), hfsUserDesktopPath }, + {OS_TEXT("CommonDesktop"), hfsCommonDesktopPath}, + {OS_TEXT("Temp" ), hfsTempPath }, + {OS_TEXT("Data" ), hfsUserDataPath }, + {OS_TEXT("Program" ), hfsUserProgramPath }, + + {OS_TEXT("" ), hfsEnd }, + }; + + HGLFlagString index=hfsNone; + + for(int i=0;;i++) + { + if(FlagStringIndex[i].index==hfsEnd) + break; + + if(flag==FlagStringIndex[i].flag) + { + index=FlagStringIndex[i].index; + break; + } + } + + if(index!=hfsNone) + { + str=GetString(index); + return(true); + } + + OSString flag_string=flag; + + flag_string.LowerCase(); + + return ExpendString.Get(flag_string,str); + } + + /** + * 转换特殊扩展字符串 + * @param source 原始字符串 + * @param target 转换后的字符串 + */ + bool ConvertExpendString(const OSString &source,OSString &target) + { + target=source; + + while(true) + { + const os_char *str=target.c_str(); + const os_char *start=hgl::strchr(str,'$'); + const os_char *end; + + if(!start)return(true); + + if(*(start+1)!='(')return(true); + + end=hgl::strchr(start+2,')'); + + if(!end)return(true); + + OSString flag(start+2,end-start-2); + OSString flag_string; + + if(!GetExpendString(flag,flag_string)) + { + LOG_ERROR(OS_TEXT("无法识别的标识串:")+flag); + + return(false); + } + + OSString new_str(str,start-str); + + new_str+=flag_string; + + new_str+=(end+1); + + target=new_str; + } + } +}//namespace hgl diff --git a/src/Base/Other/ThreadFunc.cpp b/src/Base/Other/ThreadFunc.cpp new file mode 100644 index 00000000..bede6325 --- /dev/null +++ b/src/Base/Other/ThreadFunc.cpp @@ -0,0 +1,44 @@ +#include +#include + +namespace hgl +{ + /** + * tips: PTHREAD_CREATE_DETACHED 方式创建的线程,在退出时,自动清除线程。无法使用pthread_join函数获取运行状态,pthread_join会返回22号错误 + * PTHREAD_CREATE_JOINABLE 方式创建的线程,在退出时,不会清除线程,必使使用pthread_join函数获取。或是在退出时使用pthread_detach(pthread_self())。 + */ + + /** + * 线程具体执行函数,会依操作系统的不同而有所差别 + */ + THREAD_FUNC ThreadFunc(Thread *tc) + { + tc->live_lock.Lock(); + + if(tc->ProcStartThread()) + { + while(tc->Execute()) + { + if(tc->exit_lock.TryLock()) + { + tc->exit_lock.Unlock(); + break; + } + } + + tc->ProcEndThread(); + } + + if(tc->IsExitDelete()) + { + tc->live_lock.Unlock(); + + HGL_THREAD_DETACH_SELF + delete tc; + } + else + tc->live_lock.Unlock(); + + return(0); + } +}//namespace hgl diff --git a/src/Base/Other/TimeCount.cpp b/src/Base/Other/TimeCount.cpp new file mode 100644 index 00000000..07f6695e --- /dev/null +++ b/src/Base/Other/TimeCount.cpp @@ -0,0 +1,57 @@ +#include + +namespace hgl +{ + long GetGMTOff(); + + namespace + { + uint64 program_start_time=0; + + long gmt_off=0; //windows下为long + + struct TimeInit + { + TimeInit() + { + program_start_time=GetMicroTime(); + + gmt_off=GetGMTOff(); + } + };//struct TimeInit + + static TimeInit time_init; + }//namespace + + /** + * 返回时区时差 + */ + int GetTimeZone() + { + return gmt_off; + } + + /** + * 取得本地当前时间(双精度) + * @return 当前时间(单位:秒) + */ + double GetLocalDoubleTime() + { + return GetDoubleTime()+GetTimeZone(); + } + + uint64 GetMilliStartTime() + { + return program_start_time/1000; + } + + uint64 GetMicroStartTime() + { + return program_start_time; + } + + double GetDoubleStartTime() + { + return double(program_start_time)/HGL_MICRO_SEC_PER_SEC; + } +}//namespace hgl diff --git a/src/Base/Other/TimeVal.cpp b/src/Base/Other/TimeVal.cpp new file mode 100644 index 00000000..8205769b --- /dev/null +++ b/src/Base/Other/TimeVal.cpp @@ -0,0 +1,14 @@ +#include + +#if HGL_OS_BSD +#include +#endif// + +namespace hgl +{ + void SetTimeVal(timeval &tv,const double t_sec) + { + tv.tv_sec=t_sec; + tv.tv_usec=(t_sec-(double)tv.tv_sec)*HGL_MICRO_SEC_PER_SEC; + } +}//namespace hgl diff --git a/src/Base/PlugIn/ExternalModule.cpp b/src/Base/PlugIn/ExternalModule.cpp new file mode 100644 index 00000000..7a5b350a --- /dev/null +++ b/src/Base/PlugIn/ExternalModule.cpp @@ -0,0 +1,93 @@ +#include +#include + +namespace hgl +{ + ExternalModule::ExternalModule() + { + fp=nullptr; + } + + ExternalModule::ExternalModule(ExternalModulePointer emp) + { + fp=emp; + } + + ExternalModule::~ExternalModule() + { + Clear(); + } + + void ExternalModule::Clear() + { + if(fp) + { + pi_close(fp); + + fp=nullptr; + } + } + + void *ExternalModule::GetFunc(const char *name) + { + if(fp) + { + void *func=pi_get(fp,name); + + if(!func) + LOG_ERROR("don't find "+UTF8String(name)); + + return(func); + } + else + { + LOG_ERROR("Get func <"+UTF8String(name)+"> error: no load module!"); + + return(nullptr); + } + } + + void *ExternalModule::FindFunc(const char *name) + { + if(fp) + { + void *func=pi_get(fp,name); + + if(func)return(func); + + char _name[HGL_MAX_PATH]; + + _name[0]='_'; + strcpy(_name+1,HGL_MAX_PATH-1,name); + + func=pi_get(fp,_name); + + if(func)return(func); + } + + return(nullptr); + } + + /** + * 读取函数列表 + * @return 成功加载的函数数量 + */ + int ExternalModule::Get(FuncLoad *flp) + { + if(!flp)return(-1); + + int count=0; + + while(flp->func_name[0]) + { + (*(flp->func_pointer))=GetFunc(flp->func_name); + + if(*(flp->func_pointer)) + ++count; + + ++flp; + } + + return(count); + } +}//namespace hgl diff --git a/src/Base/SystemInfo.cpp b/src/Base/SystemInfo.cpp new file mode 100644 index 00000000..0e52f696 --- /dev/null +++ b/src/Base/SystemInfo.cpp @@ -0,0 +1,136 @@ +#include +#include +#include +#include +#include + +namespace hgl +{ + using namespace filesystem; + + MemInfo::MemInfo() + { + memset(this,0,sizeof(MemInfo)); + } + + SystemInfo::SystemInfo() + { + memset(os_name,0,sizeof(os_name)); + } + + bool GetSystemPath(OSString &); + void GetOSPath(SystemPath &cp); + + bool CheckEnginePath(OSString &cur_path, + const OSString &work, + const OSString &start, + const OSString &cm, + const OSString &sub) + { + cur_path=MergeFilename(work,sub); + + if(IsDirectory(cur_path)) + return(true); + + if(work!=start) + { + cur_path=MergeFilename(start,sub); + + if(IsDirectory(cur_path)) + return(true); + } + + if(work!=cm) + { + cur_path=MergeFilename(cm,sub); + + if(IsDirectory(cur_path)) + return(true); + } + + OSString out_str=OS_TEXT("Don't find <")+sub+OS_TEXT("> folder from : \"")+work+OS_TEXT("\""); + + if(work!=start) out_str+=(OS_TEXT(",\"")+start +OS_TEXT("\"")); + if(work!=cm) out_str+=(OS_TEXT(",\"")+cm +OS_TEXT("\"")); + + LOG_INFO(out_str); + + return(false); + } + + void GetSystemPath(SystemPath &cp) + { + OSString cur_prog; + OSString cur_path; + + hgl::GetCurrentPath(cp.start); + + if(!GetSystemPath(cp.cm)) + cp.cm=cp.start; //如果没有找到CMGDK系统变量 + + hgl::GetCurrentProgram(cur_prog); + + cur_path=cur_prog; + + const int end_index=cur_path.FindRightChar(HGL_DIRECTORY_SEPARATOR); + + cur_path.ClipLeft(end_index); + + CheckEnginePath(cp.gui, cp.start,cur_path,cp.cm,OS_TEXT("gui")); + CheckEnginePath(cp.plug_ins, cp.start,cur_path,cp.cm,OS_TEXT("plug-in") + OSString(HGL_DIRECTORY_SEPARATOR_STR) + HGL_PLATFORM_STRING); //HGL_PLATFORM_STRING在CMAKE中定义 + + GetOSPath(cp); + + hgl::info::SetString(hfsCMGDKPath, cp.engine ); + hgl::info::SetString(hfsPlugInPath, cp.plug_ins ); + hgl::info::SetString(hfsStartPath, cp.start ); + hgl::info::SetString(hfsOSPath, cp.os ); + hgl::info::SetString(hfsOSLibraryPath, cp.library ); + hgl::info::SetString(hfsUserDesktopPath, cp.mydesktop); + hgl::info::SetString(hfsCommonDesktopPath, cp.desktop ); + hgl::info::SetString(hfsTempPath, cp.temp ); + hgl::info::SetString(hfsUserDataPath, cp.mydata ); + hgl::info::SetString(hfsUserProgramPath, cp.myprogram); + + hgl::info::SetString(hfsAppFileName, cur_prog ); + + LOG_INFO( OS_TEXT(" current program: ")+cur_prog +OS_TEXT("\n\n") + OS_TEXT(" program start folder: ")+cp.start +OS_TEXT("\n\n") + + OS_TEXT("operator system folder: ")+cp.os +OS_TEXT("\n") + OS_TEXT(" os fonts folder: ")+cp.osfont +OS_TEXT("\n") + OS_TEXT(" common library folder: ")+cp.library +OS_TEXT("\n\n") + + OS_TEXT(" common data folder: ")+cp.common_data +OS_TEXT("\n") + OS_TEXT(" local data folder: ")+cp.local_data +OS_TEXT("\n") + OS_TEXT(" user data folder: ")+cp.mydata +OS_TEXT("\n\n") + + OS_TEXT(" temp file folder: ")+cp.temp +OS_TEXT("\n") + OS_TEXT(" user menu folder: ")+cp.myprogram +OS_TEXT("\n") + OS_TEXT(" user desktop folder: ")+cp.mydesktop +OS_TEXT("\n") + OS_TEXT(" common desktop folder: ")+cp.desktop +OS_TEXT("\n\n") + + OS_TEXT(" Engine folder: ")+cp.engine +OS_TEXT("\n") + OS_TEXT(" Engine Plug-in folder: ")+cp.plug_ins +OS_TEXT("\n")); + } + + struct CheckInterface + { + void (*Check)(SystemInfo *); + }; + + void SystemCheck(SystemInfo *si) + { + PlugIn *pi=LoadPlugIn(OS_TEXT("SystemCheck")); + + if(!pi)return; + + CheckInterface ci; + + pi->GetInterface(2,&ci); + + ci.Check(si); + + UnloadPlugIn(pi); + } +}//namespace hgl diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 8b5265a5..152dfc88 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -1,4 +1,3 @@ add_subdirectory(Base) add_subdirectory(RenderDevice) -add_subdirectory(RenderDriver) add_subdirectory(Platform) diff --git a/src/Platform/Android/AndroidMain.cpp b/src/Platform/Android/AndroidMain.cpp new file mode 100644 index 00000000..4a281536 --- /dev/null +++ b/src/Platform/Android/AndroidMain.cpp @@ -0,0 +1,344 @@ +/* +* Copyright (C) 2010 The Android Open Source Project +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +* +*/ + +#define LOGI(...) ((void)__android_log_print(ANDROID_LOG_INFO, "AndroidProject1.NativeActivity", __VA_ARGS__)) +#define LOGW(...) ((void)__android_log_print(ANDROID_LOG_WARN, "AndroidProject1.NativeActivity", __VA_ARGS__)) + +/** +* Our saved state data. +*/ +struct saved_state +{ + float angle; + int32_t x; + int32_t y; +}; + +/** +* Shared state for our app. +*/ +struct engine +{ + struct android_app* app; + + ASensorManager* sensorManager; + const ASensor* accelerometerSensor; + ASensorEventQueue* sensorEventQueue; + ASensorEvent acceleration_event; + + int animating; + EGLDisplay display; + EGLSurface surface; + EGLContext context; + int32_t width; + int32_t height; + struct saved_state state; +}; + +/** +* Initialize an EGL context for the current display. +*/ +static int engine_init_display(struct engine* engine) +{ + // initialize OpenGL ES and EGL + + /* + * Here specify the attributes of the desired configuration. + * Below, we select an EGLConfig with at least 8 bits per color + * component compatible with on-screen windows + */ + const EGLint config_attrs[] = + { + EGL_DEPTH_SIZE, 0, + EGL_RED_SIZE, 8, + EGL_GREEN_SIZE, 8, + EGL_BLUE_SIZE, 8, + EGL_ALPHA_SIZE, 8, + EGL_STENCIL_SIZE, 8, + EGL_SURFACE_TYPE, EGL_WINDOW_BIT, + EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT, //即使是用es3这里也写es2 + EGL_NONE + }; + + const EGLint context_attrs[] = + { + EGL_CONTEXT_CLIENT_VERSION, 3, + EGL_NONE + }; + + EGLint w, h, format; + EGLint numConfigs; + EGLConfig config; + EGLSurface surface; + EGLContext context; + + EGLDisplay display = eglGetDisplay(EGL_DEFAULT_DISPLAY); + + eglInitialize(display, 0, 0); + + EGLint config_count; + bool depth_check=false; + const EGLint depth_bit_sizes[]={24,16}; + + for(uint i=0;i0) + { + depth_check=true; + break; + } + } + + if(!depth_check) + return(-1); + + /* EGL_NATIVE_VISUAL_ID is an attribute of the EGLConfig that is + * guaranteed to be accepted by ANativeWindow_setBuffersGeometry(). + * As soon as we picked a EGLConfig, we can safely reconfigure the + * ANativeWindow buffers to match, using EGL_NATIVE_VISUAL_ID. */ + eglGetConfigAttrib(display, config, EGL_NATIVE_VISUAL_ID, &format); + + ANativeWindow_setBuffersGeometry(engine->app->window, 0, 0, format); + + surface = eglCreateWindowSurface(display, config, engine->app->window, nullptr); + + context = eglCreateContext(display, config, nullptr, context_attrs); + + if (eglMakeCurrent(display, surface, surface, context) == EGL_FALSE) + { + LOGW("Unable to eglMakeCurrent"); + return -1; + } + + eglQuerySurface(display, surface, EGL_WIDTH, &w); + eglQuerySurface(display, surface, EGL_HEIGHT, &h); + + engine->display = display; + engine->context = context; + engine->surface = surface; + engine->width = w; + engine->height = h; + engine->state.angle = 0; + + // Initialize GL state. + Cube_setupGL(w, h); + + return 0; +} + +/** +* Just the current frame in the display. +*/ + +static void engine_draw_frame(struct engine* engine) +{ + if (engine->display == nullptr) { + // No display. + return; + } + + Cube_prepare(); + + Cube_draw(); + + eglSwapBuffers(engine->display, engine->surface); +} + + +/** +* Tear down the EGL context currently associated with the display. +*/ +static void engine_term_display(struct engine* engine) +{ + if (engine->display != EGL_NO_DISPLAY) + { + eglMakeCurrent(engine->display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); + + if (engine->context != EGL_NO_CONTEXT) + { + eglDestroyContext(engine->display, engine->context); + } + + if (engine->surface != EGL_NO_SURFACE) + { + eglDestroySurface(engine->display, engine->surface); + } + + eglTerminate(engine->display); + } + + engine->animating = 0; + engine->display = EGL_NO_DISPLAY; + engine->context = EGL_NO_CONTEXT; + engine->surface = EGL_NO_SURFACE; + + Cube_tearDownGL(); +} + +/** +* Process the next input event. +*/ +static int32_t engine_handle_input(struct android_app* app, AInputEvent* event) +{ + struct engine* engine = (struct engine*)app->userData; + + if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION) + { + engine->state.x = AMotionEvent_getX(event, 0); + engine->state.y = AMotionEvent_getY(event, 0); + return 1; + } + + return 0; +} + +/** +* Process the next main command. +*/ +static void engine_handle_cmd(struct android_app* app, int32_t cmd) +{ + struct engine* engine = (struct engine*)app->userData; + + switch (cmd) + { + case APP_CMD_SAVE_STATE: // The system has asked us to save our current state. Do so. + engine->app->savedState = malloc(sizeof(struct saved_state)); + *((struct saved_state*)engine->app->savedState) = engine->state; + engine->app->savedStateSize = sizeof(struct saved_state); + break; + + case APP_CMD_INIT_WINDOW: // The window is being shown, get it ready. + if (engine->app->window != nullptr) + { + engine_init_display(engine); + engine_draw_frame(engine); + } + break; + + case APP_CMD_TERM_WINDOW: // The window is being hidden or closed, clean it up. + engine_term_display(engine); + break; + + case APP_CMD_GAINED_FOCUS: // When our app gains focus, we start monitoring the accelerometer. + if (engine->accelerometerSensor != nullptr) + { + ASensorEventQueue_enableSensor(engine->sensorEventQueue,engine->accelerometerSensor); + // We'd like to get 60 events per second (in us). + ASensorEventQueue_setEventRate(engine->sensorEventQueue,engine->accelerometerSensor, (1000L / 60) * 1000); + } + break; + + case APP_CMD_LOST_FOCUS: // When our app loses focus, we stop monitoring the accelerometer. + // This is to avoid consuming battery while not being used. + if (engine->accelerometerSensor != nullptr) + { + ASensorEventQueue_disableSensor(engine->sensorEventQueue,engine->accelerometerSensor); + } + // Also stop animating. + engine->animating = 0; + engine_draw_frame(engine); + break; + } +} + +/** +* This is the main entry point of a native application that is using +* android_native_app_glue. It runs in its own thread, with its own +* event loop for receiving input events and doing other things. +*/ +void android_main(struct android_app* state) +{ + struct engine engine; + + memset(&engine, 0, sizeof(engine)); + state->userData = &engine; + state->onAppCmd = engine_handle_cmd; + state->onInputEvent = engine_handle_input; + engine.app = state; + + // Prepare to monitor accelerometer + engine.sensorManager = ASensorManager_getInstance(); + engine.accelerometerSensor = ASensorManager_getDefaultSensor(engine.sensorManager,ASENSOR_TYPE_ACCELEROMETER); + engine.sensorEventQueue = ASensorManager_createEventQueue(engine.sensorManager,state->looper, LOOPER_ID_USER, nullptr, nullptr); + + if (state->savedState != nullptr) + { + // We are starting with a previous saved state; restore from it. + engine.state = *(struct saved_state*)state->savedState; + } + + engine.animating = 1; + + // loop waiting for stuff to do. + while (1) + { + // Read all pending events. + int ident; + int events; + struct android_poll_source* source; + + // If not animating, we will block forever waiting for events. + // If animating, we loop until all events are read, then continue + // to draw the next frame of animation. + while ((ident = ALooper_pollAll(engine.animating ? 0 : -1, nullptr, &events,(void**)&source)) >= 0) + { + // Process this event. + if (source != nullptr) + { + source->process(state, source); + } + + // If a sensor has data, process it now. + if (ident == LOOPER_ID_USER) + { + if (engine.accelerometerSensor != nullptr) + { + while (ASensorEventQueue_getEvents(engine.sensorEventQueue,&engine->acceleration_event;, 1) > 0) + { + LOGI("accelerometer: x=%f y=%f z=%f", + engine->acceleration_event.acceleration.x, + engine->acceleration_event.acceleration.y, + engine->acceleration_event.acceleration.z); + } + } + } + + // Check if we are exiting. + if (state->destroyRequested != 0) + { + engine_term_display(&engine); + return; + } + } + + if (engine.animating) + { + // Done with events; draw next animation frame. + Cube_update(); + //if (engine.state.angle > 1) { + // engine.state.angle = 0; + //} + + // Drawing is throttled to the screen update rate, so there + // is no need to do timing here. + engine_draw_frame(&engine); + } + } +} diff --git a/src/Platform/Android/JNISupport.cpp b/src/Platform/Android/JNISupport.cpp new file mode 100644 index 00000000..0428ae5b --- /dev/null +++ b/src/Platform/Android/JNISupport.cpp @@ -0,0 +1,25 @@ +#include +#include + +namespace hgl +{ + namespace logger + { + void SetLocalAppdataPath(const char *fn); + }//namespace logger + + void InitAndroidSupport(JNIEnv *env,jobject obj) + { + jclass cls =env->GetObjectClass(obj); + jmethodID getFilesDir =env->GetMethodID(cls, "getFilesDir", "()Ljava/io/File;"); + jobject dirobj =env->CallObjectMethod(obj,getFilesDir); + jclass dir =env->GetObjectClass(dirobj); + jmethodID getStoragePath =env->GetMethodID(dir, "getAbsolutePath", "()Ljava/lang/String;"); + jstring path =(jstring)env->CallObjectMethod(dirobj, getStoragePath); + const char *pathstr =env->GetStringUTFChars(path, 0); + + logger::SetLocalAppdataPath(pathstr); + + env->ReleaseStringUTFChars(path, pathstr); + } +}//namespace hgl diff --git a/src/Platform/Android/LogConsole.cpp b/src/Platform/Android/LogConsole.cpp new file mode 100644 index 00000000..106da24d --- /dev/null +++ b/src/Platform/Android/LogConsole.cpp @@ -0,0 +1,146 @@ +#include +#include +#include +#include +#include + +#ifdef LOG_INFO_TIME +#include +#endif//LOG_INFO_TIME + +#include + +namespace hgl +{ + namespace logger + { + constexpr uint LOG_BUF_SIZE=4096; + + constexpr android_LogPriority android_priority[]={ ANDROID_LOG_ERROR, //llError + ANDROID_LOG_WARN, //llProblem + ANDROID_LOG_INFO, //llHint + ANDROID_LOG_VERBOSE}; //llLog + + /** + * Android控制台日志插件接口 + */ + class LogAndroidConsole:public Logger + { + char endline; + char thread_string[256]; + char time_string[256]; + char log_buf[LOG_BUF_SIZE]; + +#ifdef LOGINFO_THREAD_MUTEX + ThreadMutex mutex; +#endif//LOGINFO_THREAD_MUTEX + + android_LogPriority prio; + + public: + + LogAndroidConsole(LogLevel ll):Logger(ll) + { + prio=android_priority[ll]; + + endline='\n'; + } + + bool Create(const OSString &) + { + return(true); + } + + void Close(){} + +#ifdef LOG_INFO_THREAD + void WriteThreadID() + { + memcpy(thread_string,"[Thread:",8); + + htos(thread_string+8,128-9,pthread_self()); + strcat(thread_string,LOG_BUF_SIZE,']'); + } +#endif//LOG_INFO_THREAD + +#ifdef LOG_INFO_TIME + void WriteTime() + { + memcpy(time_string,"[Time:",6); + + ftos(time_string+6,128-strlen(time_string),GetDoubleTime()); + strcat(time_string,LOG_BUF_SIZE,']'); + } +#endif//LOG_INFO_TIME + + void Write(const u16char *str,int size) + { + #ifdef LOGINFO_THREAD_MUTEX + mutex.Lock(); + #endif//LOGINFO_THREAD_MUTEX + + log_buf[0]=0; + + #ifdef LOG_INFO_THREAD + WriteThreadID(); + strcpy(log_buf,LOG_BUF_SIZE,thread_string); + #endif//LOG_INFO_THREAD + + #ifdef LOG_INFO_TIME + WriteTime(); + strcat(log_buf,LOG_BUF_SIZE,time_string); + #endif//LOG_INFO_TIME + + int len; + + len=u16_to_u8(log_buf+hgl::strlen(log_buf),LOG_BUF_SIZE,str,size); + + if(len>0) + { + log_buf[len++]=0; + + __android_log_write(prio,"",log_buf); + } + #ifdef LOGINFO_THREAD_MUTEX + mutex.Unlock(); + #endif//LOGINFO_THREAD_MUTEX + } + + void Write(const char *str,int size) + { + #ifdef LOGINFO_THREAD_MUTEX + mutex.Lock(); + #endif//LOGINFO_THREAD_MUTEX + + log_buf[0]=0; + + #ifdef LOG_INFO_THREAD + WriteThreadID(); + strcpy(log_buf,LOG_BUF_SIZE,thread_string); + #endif//LOG_INFO_THREAD + + #ifdef LOG_INFO_TIME + WriteTime(); + strcat(log_buf,LOG_BUF_SIZE,time_string); + #endif//LOG_INFO_TIME + + strcpy(log_buf,LOG_BUF_SIZE,str,size); + + __android_log_write(prio,"",log_buf); + + #ifdef LOGINFO_THREAD_MUTEX + mutex.Unlock(); + #endif//LOGINFO_THREAD_MUTEX + } + };//class LogAndroidConsole:public Logger + + Logger *CreateLoggerConsole(const OSString &,LogLevel ll) + { + if(ll +#include + +namespace hgl +{ + namespace logger + { + void SetLocalAppdataPath(const char *fn); + }//namespace logger + + void InitAndroidSupport(struct ANativeActivity *native_activity) + { + logger::SetLocalAppdataPath(native_activity->internalDataPath); + } +}//namespace hgl diff --git a/src/Platform/Android/ProgramPath.cpp b/src/Platform/Android/ProgramPath.cpp new file mode 100644 index 00000000..d87a548f --- /dev/null +++ b/src/Platform/Android/ProgramPath.cpp @@ -0,0 +1,75 @@ +#include +#include +#include +#include + +namespace hgl +{ + namespace filesystem + { + namespace + { + char files_dir[HGL_MAX_PATH]; + } + + void SetLocalAppdataPath(const char *fn) + { + strcpy(files_dir,HGL_MAX_PATH,fn); + } + + void GetLocalAppdataPath(char fn[HGL_MAX_PATH]) + { + strcpy(fn,HGL_MAX_PATH,files_dir); + } + + /** + * 取得当前程序完整路径名称 + */ + bool GetCurrentProgram(OSString &result) + { + os_char *path=new os_char[HGL_MAX_PATH]; + + const int len=readlink("/proc/self/exe",path,HGL_MAX_PATH); + + if(len<=0) + { + delete[] path; + return(false); + } + + path[len]=0; + result.Set(path,len,true); + + return(true); + } + + /** + * 取得当前程序所在路径 + */ + bool GetCurrentProgramPath(OSString &result) + { + os_char *path=new os_char[HGL_MAX_PATH]; + + const int len=readlink("/proc/self/exe",path,HGL_MAX_PATH); + + if(len<=0) + { + delete[] path; + return(false); + } + + os_char *right=hgl::strrchr(path,len,HGL_DIRECTORY_SEPARATOR); + + if(right) + *right=0; + else + path[len]=0; + + result.Set(path,len,true); + + return(true); + } + }//namespace filesystem +}//namespace hgl + + diff --git a/src/Platform/Apple/ProgramPath.mm b/src/Platform/Apple/ProgramPath.mm new file mode 100644 index 00000000..ae6bfec1 --- /dev/null +++ b/src/Platform/Apple/ProgramPath.mm @@ -0,0 +1,42 @@ +#include +#import + +namespace hgl +{ + namespace filesystem + { + void GetLocalAppdataPath(char fn[HGL_MAX_PATH]) + { + NSFileManager *dfm=[NSFileManager defaultManager]; + + const char *str=[[[dfm homeDirectoryForCurrentUser] path] cStringUsingEncoding:NSUTF8StringEncoding]; + + hgl::strcpy(fn,HGL_MAX_PATH,str,strlen(str)); + } + + /** + * 取得当前程序完整路径名称 + */ + bool GetCurrentProgram(UTF8String &result) + { + NSString *ns_string = [[[[NSBundle mainBundle] bundleURL] URLByDeletingPathExtension] path]; + + result.Set([ns_string cStringUsingEncoding:NSUTF8StringEncoding]); + + return(true); + } + + /** + * 取得当前程序所在路径 + */ + bool GetCurrentProgramPath(UTF8String &result) + { + NSString *ns_string = [[[[NSBundle mainBundle] bundleURL] URLByDeletingLastPathComponent] path]; + + result.Set([ns_string cStringUsingEncoding:NSUTF8StringEncoding]); + + return(true); + } + }//namespace filesystem +}//namespace hgl + diff --git a/src/Platform/Apple/Semaphore.cpp b/src/Platform/Apple/Semaphore.cpp new file mode 100644 index 00000000..bfbcebc9 --- /dev/null +++ b/src/Platform/Apple/Semaphore.cpp @@ -0,0 +1,78 @@ +#include +#include +#include +#include + +namespace hgl +{ + void GetWaitTime(struct timespec &,double); + + /** + * @param max_count 最大计数 + */ + Semaphore::Semaphore(int max_count) + { + ptr=dispatch_semaphore_create(0); + + if(!ptr) + { + LOG_ERROR(OS_TEXT("dispatch_semaphore_create error")); + ptr=nullptr; + } + } + + Semaphore::~Semaphore() + { + if(!ptr)return; + + dispatch_release(ptr); + } + + /** + * 发送信号 + * @param n 发送的信号数量 + * @return 是否释放成功 + */ + bool Semaphore::Post(int n) + { + if(!ptr)return(false); + if(n<=0)return(false); + + for(int i=0;i +#include +#include + +namespace hgl +{ + void GetWaitTime(struct timespec &,double); + + CondVar::CondVar() + { + cond_var=new pthread_cond_t; + + pthread_cond_init((pthread_cond_t *)cond_var,nullptr); + } + + CondVar::~CondVar() + { + pthread_cond_destroy((pthread_cond_t *)cond_var); + delete (pthread_cond_t *)cond_var; + } + + bool CondVar::Wait(ThreadMutex *tm,double t) + { + if(t>0) + { + struct timespec abstime; + + GetWaitTime(abstime,t); + + return(!pthread_cond_timedwait((pthread_cond_t *)cond_var,tm->GetThreadMutex(),&abstime)); + } + else + { + return(!pthread_cond_wait((pthread_cond_t *)cond_var,tm->GetThreadMutex())); + } + } + + void CondVar::Signal() + { + pthread_cond_signal((pthread_cond_t *)cond_var); + } + + void CondVar::Broadcast() + { + pthread_cond_broadcast((pthread_cond_t *)cond_var); + } +}//namespace hgl diff --git a/src/Platform/UNIX/DateTime.cpp b/src/Platform/UNIX/DateTime.cpp new file mode 100644 index 00000000..5d0b74c5 --- /dev/null +++ b/src/Platform/UNIX/DateTime.cpp @@ -0,0 +1,125 @@ +#include +#include + +#include +#include + +#include + +#include +#include + +namespace hgl +{ + //和系统时间同步 + void Time::Sync(const double cur_time) + { + tm m; + time_t tt; + + if(cur_time<=0) + { + struct timeval tv; + gettimeofday(&tv, nullptr); + + tt=tv.tv_sec; + micro_seconds=tv.tv_usec; + } + else + { + tt=cur_time; + micro_seconds=(cur_time-tt)*HGL_MICRO_SEC_PER_SEC; + } + + localtime_r(&tt,&m); + + hours =m.tm_hour; + minutes =m.tm_min; + seconds =m.tm_sec; + week_day =m.tm_wday; + + gmt_off =m.tm_gmtoff; + } +}//namespace hgl +//-------------------------------------------------------------------------------------------------- +namespace hgl +{ + void Date::Sync(const double cur_time) + { + tm m; + time_t tt; + + if(cur_time<=0) + { + struct timeval tv; + gettimeofday(&tv, nullptr); + + tt=tv.tv_sec; + } + else + { + tt=cur_time; + } + + localtime_r(&tt,&m); + + year =m.tm_year+1900; + SetMonth(m.tm_mon+1); + SetDay (m.tm_mday); + week_day=m.tm_wday; + year_day=m.tm_yday; + } +}//namespace hgl + +namespace hgl +{ + void ToDateTime(Date &d,Time &t,const double cur_time) + { + tm m; + time_t tt; + uint micro_sec; + + if(cur_time<=0) + { + struct timeval tv; + gettimeofday(&tv, nullptr); + + tt=tv.tv_sec; + micro_sec=tv.tv_usec; + } + else + { + tt=cur_time; + micro_sec=(cur_time-tt)*HGL_MICRO_SEC_PER_SEC; + } + + localtime_r(&tt,&m); + + d.Set(m.tm_year+1900,m.tm_mon+1,m.tm_mday,m.tm_wday,m.tm_yday); + t.Set(m.tm_hour,m.tm_min,m.tm_sec,micro_sec,m.tm_wday); + t.SetGMT(m.tm_gmtoff); + } + + double FromDateTime(const int year,const int month,const int day, + const int hour,const int minute,const int second,const int micro_second, + const int gmt_off) + { + tm at; + + hgl_zero(at); + + at.tm_year =year-1900; + at.tm_mon =month-1; + at.tm_mday =day; + + at.tm_hour =hour; + at.tm_min =minute; + at.tm_sec =second; + + at.tm_gmtoff=gmt_off; + + double result=mktime(&at); + + return(result + (double(micro_second) / HGL_MICRO_SEC_PER_SEC)); + } +}//namespace hgl diff --git a/src/Platform/UNIX/EnumFile.cpp b/src/Platform/UNIX/EnumFile.cpp new file mode 100644 index 00000000..bf66abeb --- /dev/null +++ b/src/Platform/UNIX/EnumFile.cpp @@ -0,0 +1,141 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +namespace hgl +{ + namespace filesystem + { + /** + * 枚举一个目录内的所有文件 + * @param config 枚举配置 + * @return 查找到文件数据,<0表示失败 + */ + int EnumFile::Enum(EnumFileConfig *config) + { + if(!config)RETURN_ERROR(-1); + + if(config->folder_name.IsEmpty())RETURN_ERROR(-4); + + OSString fullname; + int count=0; + + if(config->folder_name.IsEmpty()) + { + fullname='.'; + } + else + { + fullname=config->folder_name; + } + + DIR *dir; + struct_dirent64 *entry; + struct_stat64 statbuf; + FileInfo fi; + char path_buf[HGL_MAX_PATH]={0}; + getcwd(path_buf,HGL_MAX_PATH); + + chdir(fullname); + if((dir = opendir(fullname)) == NULL) + return(-1); + if((entry = hgl_readdir64(dir)) == NULL) + return(-1); + + int sub_count; + + do + { + if(strcmp(entry->d_name,".")==0 + ||strcmp(entry->d_name,"..")==0) + { + continue; + } + + memset(&statbuf,0,sizeof(struct_stat64)); + + if(hgl_lstat64(entry->d_name,&statbuf)==-1) + continue; + + if(S_ISDIR(statbuf.st_mode)) + { + if(!config->proc_folder)continue; + } + else + { + if(!config->proc_file)continue; + + ++count; + } + + memset(&fi,0,sizeof(FileInfo)); + fi.size=statbuf.st_size; + + fi.can_read =statbuf.st_mode&S_IROTH; + fi.can_write=statbuf.st_mode&S_IWOTH; + + fi.is_hiddle=(entry->d_name[0]=='.'); + + fi.mtime=statbuf.st_mtime; + + if(S_ISDIR(statbuf.st_mode)) + { + fi.is_file=false; + fi.is_directory=true; + } + else + { + fi.is_file=true; + fi.is_directory=false; + } + + strcpy(fi.name,HGL_MAX_PATH,entry->d_name); + + if(config->folder_name.IsEmpty()) + { + strcpy(fi.fullname,HGL_MAX_PATH,fi.name); + } + else + { + strcpy(fi.fullname,HGL_MAX_PATH,config->folder_name); + + if(config->folder_name.GetEndChar()!=HGL_DIRECTORY_SEPARATOR) + strcat(fi.fullname,HGL_MAX_PATH,HGL_DIRECTORY_SEPARATOR); + + strcat(fi.fullname,HGL_MAX_PATH,fi.name,HGL_MAX_PATH); + } + + if(fi.is_directory) + { + EnumFileConfig *sub_efc=CreateSubConfig(config,fi); + + if(sub_efc&&config->sub_folder) + { + sub_count=this->Enum(sub_efc); + if(sub_count>0)count+=sub_count; + } + + ProcFolder(config,sub_efc,fi); + + if(sub_efc) + delete sub_efc; + } + else + { + ProcFile(config,fi); + } + } + while((entry=hgl_readdir64(dir))); + + closedir(dir); + + chdir(path_buf); + return(count); + } + }//namespace filesystem +}//namespace hgl diff --git a/src/Platform/UNIX/ExternalModule.cpp b/src/Platform/UNIX/ExternalModule.cpp new file mode 100644 index 00000000..1febf005 --- /dev/null +++ b/src/Platform/UNIX/ExternalModule.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include + +namespace hgl +{ + ExternalModule *LoadExternalModule(const os_char *filename) + { + ExternalModulePointer fp=dlopen(filename,RTLD_LAZY); + + if(!fp) + { + LOG_ERROR(OS_TEXT("Load Module <")+OSString(filename)+OS_TEXT("> error! os info: ")+OSString(dlerror())); + + return(nullptr); + } + + return(new ExternalModule(fp)); + } + + /** + * 加载一个外部模块 + * @param name 模块文件名称 + * @return 是否加载成功 + */ + bool ExternalModule::Load(const os_char *name) + { + Clear(); + + fp=dlopen(name,RTLD_LAZY); + + if(!fp) + { + LOG_ERROR(OS_TEXT("Load Module <")+OSString(name)+OS_TEXT("> error! os info: ")+OSString(dlerror())); + + return(false); + } + + return(true); + } +}//namespace hgl diff --git a/src/Platform/UNIX/Fifo.cpp b/src/Platform/UNIX/Fifo.cpp new file mode 100644 index 00000000..012cabd0 --- /dev/null +++ b/src/Platform/UNIX/Fifo.cpp @@ -0,0 +1,24 @@ +#include +#include +#include + +namespace hgl +{ + /** + * 创建一个管道通信文件 + * @param fn 简略文件名(请不要带路径) + * @return 是否创建成功 + */ + bool Fifo::Create(const char *fn) + { + if(!fn||!(*fn)) + return(false); + + hgl::strcpy(filename,HGL_MAX_PATH-5,"/tmp/"); + hgl::strcpy(filename+5,HGL_MAX_PATH-5,fn); + + fd=mkfifo(filename,0777); + + return(!fd); + } +}//namespace hgl diff --git a/src/Platform/UNIX/File.cpp b/src/Platform/UNIX/File.cpp new file mode 100644 index 00000000..46349951 --- /dev/null +++ b/src/Platform/UNIX/File.cpp @@ -0,0 +1,220 @@ +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include + +namespace hgl +{ + namespace filesystem + { + constexpr int FILE_PROC_BUF_SIZE=HGL_SIZE_1MB; + + /** + * 复制一个文件 + * @param sourcename 源文件名 + * @param targetname 目标文件名 + * @return 文件是否复制成功 + */ + bool FileCopy(const OSString &targetname,const OSString &sourcename) + { + io::FileInputStream fis; + io::FileOutputStream fos; + + if(!fis.Open(sourcename))return(false); + if(!fos.Create(targetname))return(false); + + size_t buf_size=FILE_PROC_BUF_SIZE; + size_t length=fis.GetSize(); + + size_t cur; + + if(buf_size>length) + buf_size=length; + + SharedPtr buf=new char[buf_size]; + + while(length) + { + if(length>buf_size) + cur=buf_size; + else + cur=length; + + if(fis.Read(buf,cur)) + if(fos.Write(buf,cur)) + { + length-=cur; + continue; + } + + return(false); + } + + return(true); + } + + /** + * 删除一个文件 + * @param filename 文件名 + * @return 文件是否成功删除 + */ + bool FileDelete(const OSString &filename) + { + return(unlink(filename.c_str())==0); + } + + /** + * 移动一个文件 + * @param sourcename 源文件名 + * @param targetname 目标文件名 + * @return 文件是否移动成功 + */ + bool FileMove(const OSString &targetname,const OSString &sourcename) + { + if(FileCopy(sourcename,targetname)) + return FileDelete(sourcename); + + return(false); + } + + /** + * 修改文件名 + * @param oldname 旧的文件名 + * @param newname 新的文件名 + * @return 文件名是否修改成功 + */ + bool FileRename(const OSString &newname,const OSString &oldname) + { + return(rename(oldname.c_str(), + newname.c_str())==0); + } + + /** + * 确认文件是否存在 + * @param filename 要查找的文件名称 + * @return 这个文件是否存在 + */ + bool FileExist(const OSString &filename) + { + return access(filename.c_str(),F_OK)>=0; + } + + /** + * 检测文件是否可读 + * @param filename 文件名 + */ + bool FileCanRead(const OSString &filename) + { + return access(filename.c_str(),R_OK)>=0; + } + + /** + * 检测文件是否可写 + * @param filename 文件名 + */ + bool FileCanWrite(const OSString &filename) + { + return access(filename.c_str(),W_OK)>=0; + } + + /** + * 检测文件是否可执行 + * @param filename 文件名 + */ + bool FileCanExec(const OSString &filename) + { + return access(filename.c_str(),X_OK)>=0; + } + + /** + * 判断当前名称是否是一个目录 + * @param name 名称 + */ + bool IsDirectory(const os_char *name) + { + struct_stat64 buf; + + memset(&buf,0,sizeof(struct_stat64)); + + if(hgl_lstat64(name,&buf)==-1) + return(false); //错误,有可能是不能访问 + + return S_ISDIR(buf.st_mode); + } + + /** + * 判断当前名称是否是一个链接 + */ + bool IsLink(const os_char *name) + { + struct_stat64 buf; + + memset(&buf,0,sizeof(struct_stat64)); + + if(hgl_lstat64(name,&buf)==-1) + return(false); //错误,有可能是不能访问 + + return S_ISLNK(buf.st_mode); + } + + bool MakeDirectory(const os_char *name) + { + if(!mkdir(name,S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH))return(true); + + LOG_PROBLEM(OS_TEXT("Create Directory <")+OSString(name)+OS_TEXT("> failed,errno: ")+OSString(errno)); + return(false); + } + + os_char *GetRootPath(os_char *str) + { + if(str[0]==HGL_DIRECTORY_SEPARATOR) + return str+1; + else + return str; + } + + /** + * 删除一个子目录 + * @param name 目录名称 + * @return 目录是否删除成功 + */ + bool DeletePath(const OSString &name) + { + return rmdir(name.c_str()); + } + + /** + * 取得当前所在目录
+ */ + bool GetCurrentPath(OSString &path) + { + const int len=pathconf(".",_PC_PATH_MAX); + + if(len<=0)return(false); + + char *str=new char[len]; + + memset(str,0,len); + + if(!getcwd(str,len)) + { + delete[] str; + return(false); + } + + path.Set(str,strlen(str),true); + return(true); + } + }//namespace filesystem +}//namespace hgl + + diff --git a/src/Platform/UNIX/FileAccess.cpp b/src/Platform/UNIX/FileAccess.cpp new file mode 100644 index 00000000..e01c5c4e --- /dev/null +++ b/src/Platform/UNIX/FileAccess.cpp @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include +#include + +namespace hgl +{ + namespace io + { + bool FileAccess::CreateTemp() + { + char template_filename[HGL_MAX_PATH]="/tmp/cm/XXXXXX"; + + fp=mkstemps(template_filename,HGL_MAX_PATH); + + if(fp==-1) + return(false); + + filename=template_filename; + mode=fomCreate; + + return(true); + } + + int OpenFile(const os_char *fn,FileOpenMode fom) + { + int fp; + + if(fom==fomCreate )fp=hgl_open64(fn,O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);else + if(fom==fomCreateTrunc )fp=hgl_open64(fn,O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);else + if(fom==fomOnlyRead )fp=hgl_open64(fn,O_RDONLY );else + if(fom==fomOnlyWrite )fp=hgl_open64(fn,O_WRONLY );else + if(fom==fomReadWrite )fp=hgl_open64(fn,O_RDWR );else + if(fom==fomAppend )fp=hgl_open64(fn,O_APPEND );else + { + LOG_ERROR(OS_TEXT("UNIX,FileAccess,OpenFile(")+OSString(fn)+OS_TEXT(" mode error: "+OSString(fom))); + RETURN_ERROR(-1); + } + + if(fp==-1) + { + LOG_ERROR(OS_TEXT("UNIX,FileAccess,OpenFile(")+OSString(fn)+OS_TEXT(") open return error: "+OSString(errno))); + } + + return fp; + } + + void CloseFile(int fp) + { + close(fp); + } + + int64 FileAccess::Read(int64 offset,void *buf,int64 size) + { + if(!CanRead())return(-1); + + return hgl_pread64(fp,buf,size,offset); + } + + int64 FileAccess::Write(int64 offset,const void *buf,int64 size) + { + if(!CanWrite())return(-1); + + return hgl_pwrite64(fp,buf,size,offset); + } + }//namespace io +}//namespace hgl diff --git a/src/Platform/UNIX/Pipe.cpp b/src/Platform/UNIX/Pipe.cpp new file mode 100644 index 00000000..9b744f1c --- /dev/null +++ b/src/Platform/UNIX/Pipe.cpp @@ -0,0 +1,13 @@ +#include +#include + +namespace hgl +{ + bool CreatePipe(pipe_pair &pp) + { + if(pipe(pp)) // return 0 表示成功 + return(false); + + return true; + } +}//namespace hgl diff --git a/src/Platform/UNIX/ProcMutex.cpp b/src/Platform/UNIX/ProcMutex.cpp new file mode 100644 index 00000000..bd05b7c5 --- /dev/null +++ b/src/Platform/UNIX/ProcMutex.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include + +namespace hgl +{ + ProcMutex::ProcMutex() + { + lock = nullptr; + } + + bool ProcMutex::Create(const os_char *name) + { + if (lock != nullptr)return(false); + + lock = sem_open(name, O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1); + + if(lock!=SEM_FAILED) + return(true); + + lock = nullptr; + return(false); + } + + void ProcMutex::Clear() + { + if (lock == nullptr)return; + + sem_close(lock); + + lock = nullptr; + } + + bool ProcMutex::Lock() + { + if (lock == nullptr)return(false); + + int err; + do + { + err = sem_wait(lock); + } + while (err && errno == EINTR); + + return !err; + } + + bool ProcMutex::TryLock() + { + if (lock == nullptr)return(false); + + return(sem_trywait(lock)==0); + } + + bool ProcMutex::Unlock() + { + if (lock == nullptr)return(false); + + return(sem_post(lock)==0); + } +}//namespace hgl diff --git a/src/Platform/UNIX/Process.cpp b/src/Platform/UNIX/Process.cpp new file mode 100644 index 00000000..0a5ee189 --- /dev/null +++ b/src/Platform/UNIX/Process.cpp @@ -0,0 +1,85 @@ +#include +#include +#include +#include +#include + +namespace hgl +{ + using namespace filesystem; + + bool Process::SetWorkPath(const OSString &wp) + { + if(!IsDirectory(wp)) + return(false); + + work_path=wp; + return(true); + } + + bool Process::SetExecFile(const OSString &ef) + { + if(!FileCanExec(ef)) + return(false); + + filename=ef; + return(true); + } + + bool Process::Execute() + { + pid=fork(); + + if(pid<0) + _exit(72); //为啥是72,我也不清楚,反正是要退出,多少无所谓。抄的poco + + if(pid==0) + { //fork会复制出一个子进程并从这里开始执行 + if(chdir(work_path.c_str())!=0) + _exit(72); + + char **argv=new char *[args.GetCount()+2]; + + argv[0]=filename; + for(int i=0;i +#include +#include +#include + +namespace hgl +{ + namespace filesystem + { + void GetLocalAppdataPath(os_char fn[HGL_MAX_PATH]) + { + struct passwd pwd; + struct passwd *result; + char *buf; + size_t bufsize=sysconf(_SC_GETPW_R_SIZE_MAX); + + if(bufsize==-1) + bufsize=16384; + + buf=(char *)malloc(bufsize); + + getpwuid_r(getuid(),&pwd,buf,bufsize,&result); + + strcpy(fn,HGL_MAX_PATH,pwd.pw_dir); + + free(buf); + } + + /** + * 取得当前程序完整路径名称 + */ + bool GetCurrentProgram(OSString &result) + { + os_char *path=new os_char[HGL_MAX_PATH]; + + const int len=readlink("/proc/self/exe",path,HGL_MAX_PATH); + + if(len<=0) + { + delete[] path; + return(false); + } + + path[len]=0; + result.Set(path,len,true); + + return(true); + } + + /** + * 取得当前程序所在路径 + */ + bool GetCurrentProgramPath(OSString &result) + { + os_char *path=new os_char[HGL_MAX_PATH]; + + const int len=readlink("/proc/self/exe",path,HGL_MAX_PATH); + + if(len<=0) + { + delete[] path; + return(false); + } + + os_char *right=hgl::strrchr(path,len,HGL_DIRECTORY_SEPARATOR); + + if(right) + *right=0; + else + path[len]=0; + + result.Set(path,len,true); + + return(true); + } + }//namespace filesystem +}//namespace hgl + diff --git a/src/Platform/UNIX/RWLock.cpp b/src/Platform/UNIX/RWLock.cpp new file mode 100644 index 00000000..22995c75 --- /dev/null +++ b/src/Platform/UNIX/RWLock.cpp @@ -0,0 +1,51 @@ +#include +#include + +namespace hgl +{ + void GetWaitTime(struct timespec &,double); + + RWLock::RWLock() + { + lock=new pthread_rwlock_t; + + pthread_rwlock_init((pthread_rwlock_t *)lock,nullptr); + } + + RWLock::~RWLock() + { + pthread_rwlock_destroy((pthread_rwlock_t *)lock); + } + + bool RWLock::TryReadLock() {return !pthread_rwlock_tryrdlock((pthread_rwlock_t *)lock);} + +#if HGL_OS != HGL_OS_macOS + bool RWLock::WaitReadLock(double t) + { + struct timespec abstime; + + GetWaitTime(abstime,t); + + return !pthread_rwlock_timedrdlock((pthread_rwlock_t *)lock,&abstime); + } +#endif//HGL_OS != HGL_OS_macOS + + bool RWLock::ReadLock() {return !pthread_rwlock_rdlock((pthread_rwlock_t *)lock);} + bool RWLock::ReadUnlock() {return !pthread_rwlock_unlock((pthread_rwlock_t *)lock);} + + bool RWLock::TryWriteLock() {return !pthread_rwlock_trywrlock((pthread_rwlock_t *)lock);} + +#if HGL_OS != HGL_OS_macOS + bool RWLock::WaitWriteLock(double t) + { + struct timespec abstime; + + GetWaitTime(abstime,t); + + return !pthread_rwlock_timedwrlock((pthread_rwlock_t *)lock,&abstime); + } +#endif//HGL_OS != HGL_OS_macOS + + bool RWLock::WriteLock() {return !pthread_rwlock_wrlock((pthread_rwlock_t *)lock);} + bool RWLock::WriteUnlock() {return !pthread_rwlock_unlock((pthread_rwlock_t *)lock);} +}//namespace hgl diff --git a/src/Platform/UNIX/Semaphore.cpp b/src/Platform/UNIX/Semaphore.cpp new file mode 100644 index 00000000..d1703022 --- /dev/null +++ b/src/Platform/UNIX/Semaphore.cpp @@ -0,0 +1,87 @@ +#include +#include +#include +#include + +namespace hgl +{ + void GetWaitTime(struct timespec &,double); + + /** + * @param max_count 最大计数 + */ + Semaphore::Semaphore(int max_count) + { + ptr=new sem_t; + + if(sem_init((sem_t *)ptr,PTHREAD_PROCESS_PRIVATE,0)) + { + LOG_ERROR(OS_TEXT("sem_init error,max_count=")+OSString(max_count)); + delete (sem_t *)ptr; + ptr=nullptr; + } + } + + Semaphore::~Semaphore() + { + if(!ptr)return; + + sem_destroy((sem_t *)ptr); + delete (sem_t *)ptr; + } + + /** + * 发送信号 + * @param n 发送的信号数量 + * @return 是否释放成功 + */ + bool Semaphore::Post(int n) + { + if(!ptr)return(false); + if(n<=0)return(false); + + int result=0; + + for(int i=0;i +#include +#include +#include +#include +#include +#include + +namespace hgl +{ + using namespace filesystem; + + bool GetCMGDKPath(OSString &cmgdk_path) + { + constexpr char path_list[][18]= + { + "/usr/share/cmgdk", + "/usr/local/cmgdk" + }; + + char home_path[HGL_MAX_PATH]; + + struct passwd *pwd=getpwuid(getuid()); + + memset(home_path,0,sizeof(home_path)); + + strcpy(home_path,HGL_MAX_PATH,pwd->pw_dir); + strcat(home_path,HGL_MAX_PATH,"/cmgdk",6); + + if(IsDirectory(home_path)) + { + cmgdk_path=home_path; + return(true); + } + + for(int i=0;irl.rlim_max) + rl.rlim_cur=rl.rlim_max; + else + rl.rlim_cur=count; + + if(setrlimit64(resource,&rl)) + { + LOG_ERROR(OS_TEXT("Set resource ")+OSString(resource)+OS_TEXT(" maximum value to ")+OSString((uint64)(rl.rlim_cur))+OS_TEXT(" failed.")); + return(false); + } + + return(true); + } + + bool InitOSupport(ConsoleSystemInitInfo *sii) + { + if(sii->sig.pipe==false) + { + signal(SIGPIPE,SIG_IGN); //屏蔽管道信号,一般send/recv一个断开的Socket会触发此信号,导致进程退出 + } + + if(!SetLimit(RLIMIT_NOFILE,sii->max_open_files)) + return(false); + + return(true); + } +}//namespace hgl diff --git a/src/Platform/UNIX/Thread.cpp b/src/Platform/UNIX/Thread.cpp new file mode 100644 index 00000000..bcc2a618 --- /dev/null +++ b/src/Platform/UNIX/Thread.cpp @@ -0,0 +1,97 @@ +#include +#include +#include +#include +#include +#include + +namespace hgl +{ + extern THREAD_FUNC ThreadFunc(Thread *tc); + + /** + * (线程外部调用)执行当前线程 + * @return 是否创建线程成功 + */ + bool Thread::Start() + { + if(tp) + { + LOG_ERROR(OS_TEXT("Thread::Start() error,tp!=nullptr.")); + return(false); + } + + pthread_attr_t attr; + + pthread_attr_init(&attr); + + pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); + + exit_lock.Lock(); + + if(pthread_create(&tp,&attr,(void *(*)(void *))ThreadFunc,this)) //返回0表示正常 + { + exit_lock.Unlock(); + tp=0; + + pthread_attr_destroy(&attr); + LOG_ERROR(OS_TEXT("Create Thread (pthread_create) failed.errno:")+OSString(errno)); + return(false); + } + + pthread_attr_destroy(&attr); + return(true); + } + + /** + * 是否是当前线程 + */ + bool Thread::IsCurThread() + { + if(!tp) + { + LOG_ERROR(OS_TEXT("Thread::IsCurThread() error,tp=nullptr.")); + return(true); + } + + return pthread_equal(pthread_self(),tp); //返回非0表示一致 + } + + void GetWaitTime(struct timespec &abstime,double t); + + void WaitThreadExit(thread_ptr tp,const double &time_out) + { + if(!tp) + { + LOG_ERROR(OS_TEXT("WaitThreadExit error,tp=nullptr.")); + return; + } + + int retval; + void *res; + +#if !defined(__ANDROID__)&&!defined(HGL_OS_BSD) + if(time_out>0) + { + struct timespec ts; + + GetWaitTime(ts,time_out); + + retval=pthread_timedjoin_np(tp,&res,&ts); + } + else +#endif//__ANDROID__&&BSD + { + retval=pthread_join(tp,&res); + } + +#ifdef _DEBUG + + char thread_addr[(sizeof(thread_ptr)<<1)+1]; + + DataToUpperHexStr(thread_addr,(uint8 *)&tp,sizeof(thread_ptr)); + + LOG_INFO(U8_TEXT("pthread_timedjoin_np/pthread_join [")+UTF8String(thread_addr)+U8_TEXT("] retval:")+UTF8String(retval)); +#endif//_DEBUG + } +}//namespace hgl diff --git a/src/Platform/UNIX/ThreadMutex.cpp b/src/Platform/UNIX/ThreadMutex.cpp new file mode 100644 index 00000000..8146723c --- /dev/null +++ b/src/Platform/UNIX/ThreadMutex.cpp @@ -0,0 +1,67 @@ +#include +#include +#include +#include + +namespace hgl +{ + void GetWaitTime(struct timespec &,double); + + ThreadMutex::ThreadMutex() + { + pthread_mutexattr_t attr; + + pthread_mutexattr_init(&attr); + + pthread_mutex_init(&ptr,&attr); + + pthread_mutexattr_destroy(&attr); + } + + ThreadMutex::~ThreadMutex() + { + pthread_mutex_destroy(&ptr); + } + + /** + * 取得控制权 + * 如果对象处于排斥状态,则等待 + */ + void ThreadMutex::Lock() + { + pthread_mutex_lock(&ptr); + } + + /** + * 尝试取得控制权 + * @return 是否成功取得控制权 + */ + bool ThreadMutex::TryLock() + { + return(!pthread_mutex_trylock(&ptr)); + } + +#if !defined(__APPLE__)&&!defined(__ANDROID__) + /** + * 等待并取得控制权 + * @param time 等待的最大时间,时间为0表示尝试 + * @return 是否取得控制权 + */ + bool ThreadMutex::WaitLock(double t) + { + struct timespec abstime; + + GetWaitTime(abstime,t); + + return !pthread_mutex_timedlock(&ptr, &abstime); + } +#endif//__APPLE__ + + /** + * 放弃控制权 + */ + void ThreadMutex::Unlock() + { + pthread_mutex_unlock(&ptr); + } +}//namespace hgl diff --git a/src/Platform/UNIX/Time.cpp b/src/Platform/UNIX/Time.cpp new file mode 100644 index 00000000..9a8f68c7 --- /dev/null +++ b/src/Platform/UNIX/Time.cpp @@ -0,0 +1,102 @@ +#include +#include + +namespace hgl +{ + void GetWaitTime(struct timespec &abstime,double t) + { + clock_gettime(CLOCK_REALTIME,&abstime); + + abstime.tv_sec+=t; + t-=(long)t; + abstime.tv_nsec+=t*HGL_NANO_SEC_PER_SEC; + + if (abstime.tv_nsec >= HGL_NANO_SEC_PER_SEC) + { + abstime.tv_nsec -= HGL_NANO_SEC_PER_SEC; + ++abstime.tv_sec; + } + } +}//namespace hgl + +namespace hgl +{ + /** + * get current timezone to GMT time offset + * @return time offset (second) + */ + long GetGMTOff() + { + tzset(); + //return(-timezone); // linux ok,but BSD don't support + + time_t rawtime; + struct tm *timeinfo; + + time(&rawtime); + timeinfo=localtime(&rawtime); + + return timeinfo->tm_gmtoff; + } + + /** + * 取得当前时间 + * @return 当前时间(单位:千分之一秒) + */ + uint64 GetTime() + { +// struct timeval tv; +// gettimeofday(&tv, nullptr); +// return ((tv.tv_sec) * HGL_MILLI_SEC_PRE_SEC) + (tv.tv_usec/1000); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME,&ts); + return (ts.tv_sec*HGL_MILLI_SEC_PRE_SEC)+(ts.tv_nsec/1000000); + } + + /** + * 取得当前时间 + * @return 当前时间(单位:百万分之一秒) + */ + uint64 GetMicroTime() + { +// struct timeval tv; +// gettimeofday(&tv, nullptr); +// return (tv.tv_sec) * HGL_MICRO_SEC_PER_SEC + tv.tv_usec; + + struct timespec ts; + clock_gettime(CLOCK_REALTIME,&ts); + return (ts.tv_sec*HGL_MICRO_SEC_PER_SEC)+(ts.tv_nsec/1000); + } + + /** + * 取得当前时间(双精度) + * @return 当前时间(单位:秒) + */ + double GetDoubleTime() ///<取得当前时间(双精度,单位秒) + { +// struct timeval tv; +// gettimeofday(&tv, nullptr); +// return double(tv.tv_sec) + (double(tv.tv_usec)/HGL_MICRO_SEC_PER_SEC); + + struct timespec ts; + clock_gettime(CLOCK_REALTIME,&ts); + return double(ts.tv_sec)+double(ts.tv_nsec)/HGL_NANO_SEC_PER_SEC; + } + + /** + * 等待指定时间 + * @param time 时间(单位:秒) + */ + void WaitTime(double t) + { + if(t<=0)return; + + struct timeval tv; + tv.tv_sec = t; + tv.tv_usec = (t-tv.tv_sec)*HGL_MICRO_SEC_PER_SEC; + select(0, nullptr, nullptr, nullptr, &tv); + + //注:不要使用sleep/nanosleep/clock_nanosleep来代替select,因为它们是真正的暂停执行线程。而sleep是挂起等待,可以被信号打断 + } +}//namespace hgl diff --git a/example/Vulkan/XCBWindow.cpp b/src/Platform/UNIX/XCBWindow.cpp similarity index 100% rename from example/Vulkan/XCBWindow.cpp rename to src/Platform/UNIX/XCBWindow.cpp diff --git a/src/Platform/Win/Clipboard.cpp b/src/Platform/Win/Clipboard.cpp new file mode 100644 index 00000000..f7117864 --- /dev/null +++ b/src/Platform/Win/Clipboard.cpp @@ -0,0 +1,43 @@ +#include +#include + +namespace hgl +{ + namespace os + { + void CopyTextToClipboard(const u16char *str) + { + if(!str||!(*str))return; + + if (!OpenClipboard(nullptr))return; + + EmptyClipboard(); + + HGLOBAL clipbuffer; + u16char * buffer; + + clipbuffer = GlobalAlloc(GMEM_DDESHARE, strlen(str)+1); + buffer = (u16char *)GlobalLock(clipbuffer); + + strcpy(buffer, str); + + GlobalUnlock(clipbuffer); + SetClipboardData(CF_UNICODETEXT, clipbuffer); + CloseClipboard(); + } + + const u16char *GetTextFromClipboard() + { + if (!OpenClipboard(nullptr)) + return 0; + + u16char * buffer = 0; + + HANDLE hData = GetClipboardData( CF_UNICODETEXT ); + buffer = (u16char *)GlobalLock( hData ); + GlobalUnlock( hData ); + CloseClipboard(); + return buffer; + } + }//namespace os +}//namespace hgl diff --git a/src/Platform/Win/CondVar.cpp b/src/Platform/Win/CondVar.cpp new file mode 100644 index 00000000..49f2f43a --- /dev/null +++ b/src/Platform/Win/CondVar.cpp @@ -0,0 +1,38 @@ +#include +#include +#include + +#pragma warning(disable:4800) // BOOL -> bool 性能损失警告 +namespace hgl +{ + CondVar::CondVar() + { + cond_var = new CONDITION_VARIABLE; + InitializeConditionVariable((CONDITION_VARIABLE *)cond_var); + } + + CondVar::~CondVar() + { + delete (CONDITION_VARIABLE *)cond_var; + } + + bool CondVar::Wait(ThreadMutex *tm, double time) + { + return SleepConditionVariableCS((CONDITION_VARIABLE *)cond_var,(CRITICAL_SECTION *)(tm->GetThreadMutex()),(DWORD)(time>0?time*1000:INFINITE)); + } + + bool CondVar::Wait(RWLock *lock, double time, bool read) + { + return SleepConditionVariableSRW((CONDITION_VARIABLE *)cond_var,(SRWLOCK *)(lock->GetRWLock()),(DWORD)(time>0?time*1000:INFINITE),read?CONDITION_VARIABLE_LOCKMODE_SHARED:0); + } + + void CondVar::Signal() + { + WakeConditionVariable((CONDITION_VARIABLE *)cond_var); + } + + void CondVar::Broadcast() + { + WakeAllConditionVariable((CONDITION_VARIABLE *)cond_var); + } +}//namespace hgl diff --git a/src/Platform/Win/DateTime.cpp b/src/Platform/Win/DateTime.cpp new file mode 100644 index 00000000..eba071d5 --- /dev/null +++ b/src/Platform/Win/DateTime.cpp @@ -0,0 +1,154 @@ +#include +#include + +#include +#include + +#include + +#include + +namespace hgl +{ + namespace + { +#define APR_DELTA_EPOCH_IN_USEC 11644473600000000 //转Windows时间到Unix时间的一个差值 + //Windows是1601.1.1 + //Unix是1970.1.1 + //tanks for APR + + static inline void SystemTimeToMicroTime(uint64 *result, SYSTEMTIME *st_input) + { + FILETIME ft; + + SystemTimeToFileTime(st_input, &ft); + + /* Convert FILETIME one 64 bit number so we can work with it. */ + *result = ft.dwHighDateTime; + *result = (*result) << 32; + *result |= ft.dwLowDateTime; + *result /= 10; /* Convert from 100 nano-sec periods to micro-seconds. */ + *result -= APR_DELTA_EPOCH_IN_USEC; /* Convert from Windows epoch to Unix epoch */ + return; + } + + static inline void MicroTimeToFileTime(LPFILETIME pft, uint64 t) + { + LONGLONG ll; + t += APR_DELTA_EPOCH_IN_USEC; + ll = t * 10; + pft->dwLowDateTime = (DWORD)ll; + pft->dwHighDateTime = (DWORD)(ll >> 32); + return; + } + + static inline void MicroTimeToSystemTime(LPSYSTEMTIME pst, uint64 t) + { + FILETIME ft; + + MicroTimeToFileTime(&ft, t); + + FileTimeToSystemTime(&ft, pst); + } + } +}//namespace hgl + +namespace hgl +{ + //和系统时间同步 + void Time::Sync(const double cur_time) + { + uint64 st64; + uint64 lt64; + + SYSTEMTIME st; + SYSTEMTIME local_time; + TIME_ZONE_INFORMATION time_zone; + + if (cur_time <= 0) + { + GetSystemTime(&st); + SystemTimeToMicroTime(&st64, &st); + } + else + { + st64 = cur_time*HGL_MICRO_SEC_PER_SEC; + MicroTimeToSystemTime(&st, st64); + } + + GetTimeZoneInformation(&time_zone); + + SystemTimeToTzSpecificLocalTime(&time_zone, &st, &local_time); + + hours = local_time.wHour; + minutes = local_time.wMinute; + seconds = local_time.wSecond; + micro_seconds = local_time.wMilliseconds * 1000; + week_day = local_time.wDayOfWeek; + + SystemTimeToMicroTime(<64, &local_time); + + gmt_off = lt64 - st64; + } +}//namespace hgl +//-------------------------------------------------------------------------------------------------- +namespace hgl +{ + void Date::Sync(const double cur_time) + { + SYSTEMTIME st; + + if (cur_time <= 0) + GetLocalTime(&st); + else + MicroTimeToSystemTime(&st, cur_time*HGL_MICRO_SEC_PER_SEC); + + year = st.wYear; + month = st.wMonth; + day = st.wDay; + + week_day = st.wDayOfWeek; + } +}//namespace hgl + +namespace hgl +{ + void ToDateTime(Date &d,Time &t,const double cur_time) + { + FILETIME ft,local_ft; + SYSTEMTIME st; + + MicroTimeToFileTime(&ft, cur_time*HGL_MICRO_SEC_PER_SEC); + + FileTimeToSystemTime(&ft, &st); + FileTimeToLocalFileTime(&ft, &local_ft); + + d.Set(st.wYear, st.wMonth, st.wDay, st.wDayOfWeek); + t.Set(st.wHour, st.wMinute, st.wSecond, st.wMilliseconds * 1000, st.wDayOfWeek); + t.SetGMT((local_ft.dwLowDateTime - ft.dwLowDateTime) / 10); + } + + double FromDateTime(const int year,const int month,const int day, + const int hour,const int minute,const int second,const int micro_second, + const int gmt_off) + { + SYSTEMTIME st; + + st.wYear = year; + st.wMonth = month; + st.wDay = day; + st.wDayOfWeek = 0; + + st.wHour = hour; + st.wMinute = minute; + st.wSecond = second; + st.wMilliseconds = micro_second / 1000; + + uint64 result; + SystemTimeToMicroTime(&result, &st); + + result -= gmt_off; + return(double(result) / HGL_MICRO_SEC_PER_SEC); + } +}//namespace hgl + diff --git a/src/Platform/Win/Desktop.cpp b/src/Platform/Win/Desktop.cpp new file mode 100644 index 00000000..f33a6659 --- /dev/null +++ b/src/Platform/Win/Desktop.cpp @@ -0,0 +1,141 @@ +#include +#include +#include +#include +#include + +namespace hgl +{ + namespace os + { + /** + * 弹出一个网页浏览器,并自动打开指定的网址。示例: PopupWebBrowser(L"http://www.hyzgame.com.cn"); + * @param url 网址 + */ + void PopupWebBrowser(const wchar_t *url) + { + ShellExecuteW(nullptr,nullptr,url,nullptr,nullptr,0); + } + + /** + * 弹出邮件客户端软件,并自动指定收件人的email地址。示例: PopupEmailClient(L"hyz@hyzgame.com.cn",L"您好!"); + * @param email 电子邮件地址 + * @param subject 邮件主题 + */ + void PopupEmailClient(const WideString &email,const WideString &subject) + { + wchar_t url[MAX_PATH]=L"mailto:"; + + strcat(url, MAX_PATH, email); + + const wchar_t subject_header[] = L"?Subject=\""; + const size_t subject_header_size = sizeof(subject_header)/sizeof(wchar_t); + + strcat(url, MAX_PATH, subject_header, subject_header_size); + strcat(url, MAX_PATH, subject); + strcat(url, MAX_PATH, L'\"'); + + ShellExecuteW(nullptr,nullptr,url,nullptr,nullptr,0); + } + + /** + * 创建快捷方式 + * @param sc 快捷方式配置 + * @return 是否成功 + */ + bool CreateShortCut(const ShortCut &sc) + { + IShellLinkW *psl=nullptr; + IPersistFile *pPf=nullptr; + + WideString lnk_filename=sc.lnk_filename; + + lnk_filename += L".lnk"; + + HRESULT hresult; + + hresult=CoCreateInstance(CLSID_ShellLink,nullptr,CLSCTX_INPROC_SERVER,IID_IShellLinkW,(LPVOID*)&psl); + + if(hresult!=S_OK) + return(false); + + hresult=psl->QueryInterface(IID_IPersistFile,(LPVOID*)&pPf); + + if(hresult!=S_OK) + return(false); + + if(!sc.work_directory.IsEmpty()) + { + hresult=psl->SetWorkingDirectory(sc.work_directory.c_str()); + + if(hresult!=S_OK) + return(false); + } + + if(!sc.param.IsEmpty()) + { + hresult=psl->SetArguments(sc.param.c_str()); + + if(hresult!=S_OK) + return(false); + } + + hresult=psl->SetPath(sc.filename.c_str()); + + if(hresult!=S_OK) + return(false); + + if(!sc.icon_filename.IsEmpty()) + if(filesystem::FileExist(sc.icon_filename)) + { + hresult=psl->SetIconLocation(sc.icon_filename.c_str(),0); + + if(hresult!=S_OK) + return(false); + } + + if(!sc.descript.IsEmpty()) + { + hresult=psl->SetDescription(sc.descript.c_str()); + + if(hresult!=S_OK) + return(false); + } + + hresult=pPf->Save(lnk_filename.c_str(),TRUE); + + if(hresult!=S_OK) + return(false); + + if(pPf) + pPf->Release(); + + if(psl) + psl->Release(); + + return true; + } + + //#if (NTDDI_VERSION >= NTDDI_VISTA) + // /** + // * 取得文件图标 + // * @param filename 文件名 + // * @param width 图标宽度 + // * @param height 图标高度 + // * @param color 图标色彩数 + // * @return 图标象素数据(请自行delete[],另返回NULL表示失败) + // */ + // void *GetFileIcon(const wchar_t *filename,int &width,int &height,int &color) + // { + // IShellItemImageFactory *pShellItemImageFactory = nullptr; + // IBindCtx *m_pBindContext; + // + // //该函数要求ie7.0,但无法确定 + // if(SHCreateItemFromParsingName(filename + // m_pBindContext, + // IID_PPV_ARGS(&pShellItemImageFactory) + // )!=S_OK)return(false); + // } + //#endif//NTDDI_VERSION >= NTDDI_VISTA + }//namespace os +}//namespace hgl diff --git a/src/Platform/Win/EnumFile.cpp b/src/Platform/Win/EnumFile.cpp new file mode 100644 index 00000000..93c6ca10 --- /dev/null +++ b/src/Platform/Win/EnumFile.cpp @@ -0,0 +1,131 @@ +#include +#include + +#include +#include + +namespace hgl +{ + namespace filesystem + { + /** + * 枚举一个目录内的所有文件 + * @param config 枚举配置 + * @return 查找到文件数据,<0表示失败 + */ + int EnumFile::Enum(EnumFileConfig *config) + { + if(!config)RETURN_ERROR(-1); + + if(config->folder_name.IsEmpty() + &&config->find_name.IsEmpty())RETURN_ERROR(-4); + + OSString full_findname; + int count=0; + + if(config->folder_name.IsEmpty()) + { + full_findname=config->find_name; + } + else + { + full_findname=MergeFilename(config->folder_name,config->find_name); + } + + WIN32_FIND_DATAW FindFileData; + HANDLE hFind; + + hFind = FindFirstFileW(full_findname, &FindFileData); + if (hFind == INVALID_HANDLE_VALUE) + return(-1); + + FileInfo fi; + int sub_count; + + do + { + if(strcmp(FindFileData.cFileName,OS_TEXT("."))==0 + || strcmp(FindFileData.cFileName,OS_TEXT(".."))==0) + { + continue; + } + + if(FindFileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) + { + if(!config->proc_folder)continue; + } + else + { + if(!config->proc_file)continue; + + ++count; + } + + memset(&fi,0,sizeof(FileInfo)); + + strcpy(fi.name,HGL_MAX_PATH,FindFileData.cFileName); + + if(config->folder_name.IsEmpty()) + { + strcpy(fi.fullname, HGL_MAX_PATH, fi.name); + } + else + { + strcpy(fi.fullname, HGL_MAX_PATH, config->folder_name); + + if(config->folder_name.GetEndChar()!=HGL_DIRECTORY_SEPARATOR) + strcat(fi.fullname, HGL_MAX_PATH, HGL_DIRECTORY_SEPARATOR); + + const int rp =config->find_name.FindChar(HGL_DIRECTORY_SEPARATOR);//防止查询名称内仍有路径 + + if(rp!=-1) + strcat(fi.fullname, HGL_MAX_PATH,config->find_name.c_str(),rp); + + strcat(fi.fullname, HGL_MAX_PATH, fi.name, HGL_MAX_PATH); + } + + fi.size = FindFileData.nFileSizeHigh; + fi.size <<= 32; + fi.size |= FindFileData.nFileSizeLow; + + fi.is_hiddle=FindFileData.dwFileAttributes&FILE_ATTRIBUTE_HIDDEN; + + fi.can_read =true; + fi.can_write=!(FindFileData.dwFileAttributes&FILE_ATTRIBUTE_READONLY); + + fi.mtime=*(uint64 *)&FindFileData.ftLastWriteTime; + + if(FindFileData.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) + { + fi.is_file=false; + fi.is_directory=true; + + EnumFileConfig *sub_efc=CreateSubConfig(config,fi); + + if(sub_efc&&config->sub_folder) + { + sub_count=this->Enum(sub_efc); + if(sub_count>0)count+=sub_count; + } + + ProcFolder(config,sub_efc,fi); + + if(sub_efc) + delete sub_efc; + } + else + { + fi.is_file=true; + fi.is_directory=false; + + ProcFile(config,fi); + } + } + while(FindNextFileW(hFind, &FindFileData)); + + FindClose(hFind); + + return(count); + } + }//namespace filesystem +}//namespace hgl diff --git a/src/Platform/Win/EnumVolume.cpp b/src/Platform/Win/EnumVolume.cpp new file mode 100644 index 00000000..173e9d21 --- /dev/null +++ b/src/Platform/Win/EnumVolume.cpp @@ -0,0 +1,89 @@ +#include +#include +#include +#include + +namespace hgl +{ + namespace filesystem + { + int EnumVolume(List &vi_list,const VolumeCheckConfig &cfg) + { + if(cfg.isErrorConfig()) + return(-1); + + HANDLE handle; + u16char volume_name[HGL_MAX_PATH+1]; + u16char path_name[HGL_MAX_PATH]; + int count=0; + + handle=FindFirstVolumeW(volume_name,HGL_MAX_PATH); + + if(handle==INVALID_HANDLE_VALUE)return(-2); + + do + { + hgl::filesystem::VolumeInfo vi; + + memset(&vi,0,sizeof(hgl::filesystem::VolumeInfo)); + + DWORD length; + + GetVolumePathNamesForVolumeNameW(volume_name,path_name,HGL_MAX_PATH,&length); //这个函数要win xp/2003才能用 + + path_name[length]=0; + + hgl::strcpy(vi.name,HGL_MAX_PATH,volume_name); + hgl::strcpy(vi.path,HGL_MAX_PATH,path_name); + + UINT type=GetDriveTypeW(path_name); + + if(type==DRIVE_REMOVABLE){ if(!cfg.removable )continue;vi.driver_type=hgl::filesystem::VolumeInfo::dtRemovable; }else + if(type==DRIVE_FIXED ){ if(!cfg.fixed )continue;vi.driver_type=hgl::filesystem::VolumeInfo::dtFixed; }else + if(type==DRIVE_REMOTE ){ if(!cfg.remote )continue;vi.driver_type=hgl::filesystem::VolumeInfo::dtRemote; }else + if(type==DRIVE_RAMDISK ){ if(!cfg.ram_disk )continue;vi.driver_type=hgl::filesystem::VolumeInfo::dtRamDisk; }else + if(type==DRIVE_CDROM ){ if(!cfg.cdrom )continue;vi.driver_type=hgl::filesystem::VolumeInfo::dtCDROM; }else + { + if(cfg.unknow)vi.driver_type=hgl::filesystem::VolumeInfo::dtNone; + continue; + } + + uint32 file_system_flags; + + if(GetVolumeInformationW(path_name, + vi.volume_label, + 255, + (unsigned long *)&vi.serial, + (unsigned long *)&vi.filename_max_length, + (unsigned long *)&file_system_flags, + vi.file_system, + 255)) + { + vi.unicode=file_system_flags&FILE_UNICODE_ON_DISK; + } + else + { + LOG_PROBLEM(U16_TEXT("Get <")+UTF16String(path_name)+U16_TEXT("> info failed!Windows error code: ")+UTF16String((uint)GetLastError())); + } + + if(GetDiskFreeSpaceExW(path_name, + (ULARGE_INTEGER *)&vi.available_space, + (ULARGE_INTEGER *)&vi.total_space, + (ULARGE_INTEGER *)&vi.free_space)) + { + vi_list.Add(vi); + } + else + { + LOG_PROBLEM(U16_TEXT("Get disk free space <")+UTF16String(path_name)+U16_TEXT("> data failed,Windows error code: ")+UTF16String((uint)GetLastError())); + } + + count++; + } while(FindNextVolumeW(handle,volume_name,HGL_MAX_PATH)); + + FindVolumeClose(handle); + + return(count); + } + }//namespace filesystem +}//namespace hgl diff --git a/src/Platform/Win/ExternalModule.cpp b/src/Platform/Win/ExternalModule.cpp new file mode 100644 index 00000000..80c9ed5a --- /dev/null +++ b/src/Platform/Win/ExternalModule.cpp @@ -0,0 +1,54 @@ +#include +#include +#include + +namespace hgl +{ + ExternalModule *LoadExternalModule(const os_char *filename) + { + ExternalModulePointer fp=LoadLibraryW(filename); + + if(!fp) + { + uint dw=GetLastError(); + os_char *str=nullptr; + + FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,nullptr,dw, + MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),str,0,nullptr); + + LOG_ERROR(OS_TEXT("LoadModule <")+OSString(filename)+OS_TEXT("> error! os info: ")+OSString(dw)+OSString::charOf(',')+str); + + return(nullptr); + } + + return(new ExternalModule(fp)); + } + + /** + * 加载一个外部模块 + * @param name 模块文件名称 + * @return 是否加载成功 + */ + bool ExternalModule::Load(const os_char *name) + { + Clear(); + + fp=LoadLibraryW(name); + + if(!fp) + { + const uint dw=GetLastError(); + u16char *str=nullptr; + + FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER|FORMAT_MESSAGE_FROM_SYSTEM,nullptr,dw, + MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT),str,0,nullptr); + + LOG_ERROR(L"LoadModule <"+UTF16String(name)+L"> error! os info: "+UTF16String(dw)+UTF16String::charOf(L',')+str); + + return(false); + } + + return(true); + } +}//namespace hgl + diff --git a/src/Platform/Win/Fifo.cpp b/src/Platform/Win/Fifo.cpp new file mode 100644 index 00000000..e69de29b diff --git a/src/Platform/Win/File.cpp b/src/Platform/Win/File.cpp new file mode 100644 index 00000000..46cb1dca --- /dev/null +++ b/src/Platform/Win/File.cpp @@ -0,0 +1,217 @@ +#include +#include +#include +#include + +#include + +#include +#include + +namespace hgl +{ + namespace filesystem + { + constexpr int FILE_PROC_BUF_SIZE=HGL_SIZE_1MB; + + /** + * 复制一个文件 + * @param sourcename 源文件名 + * @param targetname 目标文件名 + * @return 文件是否复制成功 + */ + bool FileCopy(const OSString &targetname,const OSString &sourcename) + { + return(::CopyFileW(sourcename,targetname,false)); + } + + /** + * 删除一个文件 + * @param filename 文件名 + * @return 文件是否成功删除 + */ + bool FileDelete(const OSString &filename) + { + return(::DeleteFileW(filename)); + } + + /** + * 移动一个文件 + * @param sourcename 源文件名 + * @param targetname 目标文件名 + * @return 文件是否移动成功 + */ + bool FileMove(const OSString &targetname,const OSString &sourcename) + { + return(::MoveFileW(sourcename,targetname)); + } + + /** + * 修改文件名 + * @param oldname 旧的文件名 + * @param newname 新的文件名 + * @return 文件名是否修改成功 + */ + bool FileRename(const OSString &newname,const OSString &oldname) + { + return(::MoveFileW(oldname,newname)); + } + + /** + * 确认文件是否存在 + * @param filename 要查找的文件名称 + * @return 这个文件是否存在 + */ + bool FileExist(const OSString &filename) + { + WIN32_FIND_DATAW wfd; + HANDLE hFind; + + hFind=FindFirstFileW(filename, &wfd); + + if(hFind==INVALID_HANDLE_VALUE) + return(false); + + FindClose(hFind); + return(true); + } + + /** + * 检测文件是否可读 + * @param filename 文件名 + */ + bool FileCanRead(const OSString &filename) + { + const DWORD attr=GetFileAttributesW(filename); + + if(attr==INVALID_FILE_ATTRIBUTES) + return(false); + + if(attr&(FILE_ATTRIBUTE_DEVICE|FILE_ATTRIBUTE_DIRECTORY)) //不是个文件 + return(false); + + if(attr&FILE_ATTRIBUTE_OFFLINE) + return(false); + + return(true); + } + + /** + * 检测文件是否可写 + * @param filename 文件名 + */ + bool FileCanWrite(const OSString &filename) + { + const DWORD attr=GetFileAttributesW(filename); + + if(attr==INVALID_FILE_ATTRIBUTES) + return(false); + + if(attr&(FILE_ATTRIBUTE_DEVICE|FILE_ATTRIBUTE_DIRECTORY)) //不是个文件 + return(false); + + if(attr&FILE_ATTRIBUTE_OFFLINE) + return(false); + + return (attr&FILE_ATTRIBUTE_READONLY)?false:true; + } + + /** + * 检测文件是否可执行 + * @param filename 文件名 + */ + bool FileCanExec(const OSString &filename) + { + int index = filename.FindRightChar('.'); + + if (index == -1)return(false); + + if (index > filename.Length() - 4) + return(false); + + const os_char *ext = filename.c_str() + index + 1; + + if (!ext)return(false); + + if (stricmp(ext, "exe") == 0)return(true); + if (stricmp(ext, "com") == 0)return(true); + if (stricmp(ext, "bat") == 0)return(true); + if (stricmp(ext, "msi") == 0)return(true); + if (stricmp(ext, "msp") == 0)return(true); + + return(false); + } + + /** + * 判断当前名称是否是一个目录 + * @param name 名称 + */ + bool IsDirectory(const os_char *name) + { + DWORD attrib = GetFileAttributesW(name); + + if (attrib == INVALID_FILE_ATTRIBUTES) + return(false); + + return attrib&FILE_ATTRIBUTE_DIRECTORY; + } + + bool MakeDirectory(const os_char *name) + { + if(::CreateDirectoryW(name,nullptr))return(true); + + const uint win_error=GetLastError(); + + LOG_PROBLEM(OS_TEXT("Create Directory <")+OSString(name)+OS_TEXT("> failed,errno: ")+OSString(win_error)); + return(false); + } + + os_char *GetRootPath(os_char *str) + { + if(str[1]==OS_TEXT(':')) + return str+3; + + return str; + } + + /** + * 删除一个子目录 + * @param name 目录名称 + * @return 目录是否删除成功 + */ + bool DeletePath(const OSString &name) + { + return(RemoveDirectoryW(name)); + } + + /** + * 取得当前所在目录
+ */ + bool GetCurrentPath(OSString &path) + { + int len; + u16char *dir; + + len=GetCurrentDirectoryW(0,nullptr); + + if(len==0) + return(nullptr); + + dir=new u16char[len+1]; + + if(GetCurrentDirectoryW(len,dir)) + { + if(len==3&&dir[1]==OS_TEXT(':')) + len=2; //如果是"C:\"这种情况,去掉"\" + + dir[len]=0; + + path.Set(dir,len,true); + return(true); + } + + delete[] dir; + return(false); + } + }//namespace filesystem +}//namespace hgl diff --git a/src/Platform/Win/FileAccess.cpp b/src/Platform/Win/FileAccess.cpp new file mode 100644 index 00000000..6326b724 --- /dev/null +++ b/src/Platform/Win/FileAccess.cpp @@ -0,0 +1,68 @@ +#include +#include +#include +#include +#include + +namespace hgl +{ + namespace io + { + bool FileAccess::CreateTemp() + { + const uint buf_size=HGL_MAX_PATH; + + u16char PathBuffer[buf_size]; + u16char TempName[buf_size]; + + GetTempPathW(buf_size,PathBuffer); + + GetTempFileNameW(PathBuffer,L"NEW",0,TempName); + + return Open(TempName,fomCreate); + } + + int OpenFile(const os_char *fn,FileOpenMode fom) + { + int fp; + + errno_t result; + + if(fom==fomCreate )result=_wsopen_s(&fp,fn,_O_BINARY|_O_WRONLY|_O_CREAT ,_SH_DENYNO,S_IREAD|_S_IWRITE);else + if(fom==fomCreateTrunc )result=_wsopen_s(&fp,fn,_O_BINARY|_O_WRONLY|_O_CREAT|_O_TRUNC ,_SH_DENYNO,S_IREAD|_S_IWRITE);else +// if(fom==fomCreateTemp )result=_wsopen_s(&fp,fn,_O_BINARY|_O_WRONLY|_O_CREAT|_O_TEMPORARY ,_SH_DENYNO,S_IREAD|_S_IWRITE);else //某些平台不支持,所以全都不使用fomCreateTemp,统一使用CreateTemp + if(fom==fomOnlyRead )result=_wsopen_s(&fp,fn,_O_BINARY|_O_RDONLY ,_SH_DENYNO,S_IREAD|_S_IWRITE);else + if(fom==fomOnlyWrite )result=_wsopen_s(&fp,fn,_O_BINARY|_O_WRONLY ,_SH_DENYNO,S_IREAD|_S_IWRITE);else + if(fom==fomReadWrite )result=_wsopen_s(&fp,fn,_O_BINARY|_O_RDWR ,_SH_DENYNO,S_IREAD|_S_IWRITE);else + if(fom==fomAppend )result=_wsopen_s(&fp,fn,_O_BINARY|_O_APPEND ,_SH_DENYNO,S_IREAD|_S_IWRITE);else + RETURN_ERROR(-1); + + return(fp); + } + + void CloseFile(int fp) + { + _close(fp); + } + + int64 FileAccess::Read(int64 offset,void *buf,int64 size) + { + if(!CanRead())return(-1); + + if(_lseeki64(fp,offset,soBegin)==offset) + return _read(fp,buf,size); + else + return -1; + } + + int64 FileAccess::Write(int64 offset,const void *buf,int64 size) + { + if(!CanWrite())return(-1); + + if(_lseeki64(fp,offset,soBegin)==offset) + return _write(fp,buf,size); + else + return -1; + } + }//namespace io +}//namespace hgl diff --git a/src/Platform/Win/KeyConvert.cpp b/src/Platform/Win/KeyConvert.cpp new file mode 100644 index 00000000..7bf02029 --- /dev/null +++ b/src/Platform/Win/KeyConvert.cpp @@ -0,0 +1,171 @@ +#include +#include +#include + +#ifdef _DEBUG +#include +#endif//_DEBUG + +namespace hgl +{ + static KeyboardButton KeyConvert[256]; + + void InitKeyConvert() + { + int i; + + memset(KeyConvert,0,sizeof(KeyConvert)); + + KeyConvert[VK_ESCAPE ]=kbEsc; + for(i=VK_F1;i<=VK_F12;i++)KeyConvert[i]=(KeyboardButton)(kbF1+i-VK_F1); + + KeyConvert['`' ]=kbGrave; + for(i='0';i<='9';i++)KeyConvert[i]=(KeyboardButton)(kb0+i-'0'); + KeyConvert['-' ]=kbMinus; + KeyConvert['=' ]=kbEquals; + KeyConvert['\\' ]=kbBackSlash; + KeyConvert[VK_BACK ]=kbBackSpace; + + KeyConvert[VK_TAB ]=kbTab; + KeyConvert['Q' ]=kbQ; + KeyConvert['W' ]=kbW; + KeyConvert['E' ]=kbE; + KeyConvert['R' ]=kbR; + KeyConvert['T' ]=kbT; + KeyConvert['Y' ]=kbY; + KeyConvert['U' ]=kbU; + KeyConvert['I' ]=kbI; + KeyConvert['O' ]=kbO; + KeyConvert['P' ]=kbP; + KeyConvert['[' ]=kbLeftBracket; + KeyConvert[']' ]=kbRightBracket; + + KeyConvert[VK_CAPITAL ]=kbCapsLock; + KeyConvert['A' ]=kbA; + KeyConvert['S' ]=kbS; + KeyConvert['D' ]=kbD; + KeyConvert['F' ]=kbF; + KeyConvert['G' ]=kbG; + KeyConvert['H' ]=kbH; + KeyConvert['J' ]=kbJ; + KeyConvert['K' ]=kbK; + KeyConvert['L' ]=kbL; + KeyConvert[';' ]=kbSemicolon; + KeyConvert['\'' ]=kbApostrophe; + KeyConvert[VK_RETURN ]=kbEnter; + + KeyConvert[VK_LSHIFT ]=kbLeftShift; + KeyConvert['Z' ]=kbZ; + KeyConvert['X' ]=kbX; + KeyConvert['C' ]=kbC; + KeyConvert['V' ]=kbV; + KeyConvert['B' ]=kbB; + KeyConvert['N' ]=kbN; + KeyConvert['M' ]=kbM; + KeyConvert[',' ]=kbComma; + KeyConvert['.' ]=kbPeriod; + KeyConvert['/' ]=kbSlash; + KeyConvert[VK_RSHIFT ]=kbRightShift; + + KeyConvert[VK_LCONTROL ]=kbLeftCtrl; + KeyConvert[VK_LWIN ]=kbLeftOS; + KeyConvert[VK_LMENU ]=kbLeftAlt; + KeyConvert[VK_SPACE ]=kbSpace; + KeyConvert[VK_RMENU ]=kbRightAlt; + KeyConvert[VK_RWIN ]=kbRightOS; + KeyConvert[VK_RCONTROL ]=kbRightCtrl; + + KeyConvert[VK_PAUSE ]=kbPause; + // KeyConvert[VK_CLEAR ]=kbClear; + + KeyConvert[VK_NUMPAD0 ]=kbNum0; + KeyConvert[VK_NUMPAD1 ]=kbNum1; + KeyConvert[VK_NUMPAD2 ]=kbNum2; + KeyConvert[VK_NUMPAD3 ]=kbNum3; + KeyConvert[VK_NUMPAD4 ]=kbNum4; + KeyConvert[VK_NUMPAD5 ]=kbNum5; + KeyConvert[VK_NUMPAD6 ]=kbNum6; + KeyConvert[VK_NUMPAD7 ]=kbNum7; + KeyConvert[VK_NUMPAD8 ]=kbNum8; + KeyConvert[VK_NUMPAD9 ]=kbNum9; + + KeyConvert[VK_DECIMAL ]=kbNumDecimal; + KeyConvert[VK_DIVIDE ]=kbNumDivide; + KeyConvert[VK_MULTIPLY ]=kbNumMultiply; + KeyConvert[VK_SUBTRACT ]=kbNumSubtract; + KeyConvert[VK_ADD ]=kbNumAdd; + + KeyConvert[VK_UP ]=kbUp; + KeyConvert[VK_DOWN ]=kbDown; + KeyConvert[VK_LEFT ]=kbLeft; + KeyConvert[VK_RIGHT ]=kbRight; + + KeyConvert[VK_INSERT ]=kbInsert; + KeyConvert[VK_DELETE ]=kbDelete; + KeyConvert[VK_HOME ]=kbHome; + KeyConvert[VK_END ]=kbEnd; + KeyConvert[VK_PRIOR ]=kbPageUp; + KeyConvert[VK_NEXT ]=kbPageDown; + + KeyConvert[VK_NUMLOCK ]=kbNumLock; + KeyConvert[VK_SCROLL ]=kbScrollLock; + + //KeyConvert[VK_SHIFT ]=kbLeftShift; + //KeyConvert[VK_CONTROL ]=kbLeftCtrl; + //KeyConvert[VK_MENU ]=kbLeftAlt; + + KeyConvert[VK_OEM_1 ]=kbSemicolon; + KeyConvert[VK_OEM_PLUS ]=kbEquals; + KeyConvert[VK_OEM_COMMA ]=kbComma; + KeyConvert[VK_OEM_MINUS ]=kbMinus; + KeyConvert[VK_OEM_PERIOD]=kbPeriod; + KeyConvert[VK_OEM_2 ]=kbSlash; + KeyConvert[VK_OEM_3 ]=kbGrave; + KeyConvert[VK_OEM_4 ]=kbLeftBracket; + KeyConvert[VK_OEM_5 ]=kbBackSlash; + KeyConvert[VK_OEM_6 ]=kbRightBracket; + KeyConvert[VK_OEM_7 ]=kbApostrophe; + } + + KeyboardButton ConvertOSKey(uint key) + { + if(key<0||key>=256)return(kb_NONE); + + if(key==VK_SHIFT) + { + if((GetAsyncKeyState(VK_LSHIFT)>>15)&1) + return kbLeftShift; + else + return kbRightShift; + } + else + if(key==VK_CONTROL) + { + if((GetAsyncKeyState(VK_LCONTROL)>>15)&1) + return kbLeftCtrl; + else + return kbRightCtrl; + } + if(key==VK_MENU) + { + if((GetAsyncKeyState(VK_LMENU)>>15)&1) + return kbLeftAlt; + else + return kbRightAlt; + } + +#ifdef _DEBUG + if(KeyConvert[key]==0) + { + wchar_t name[64]; + + ::GetKeyNameTextW(key,name,64); + + LOG_INFO(WideString(L"Unknow Key: " )+WideString(key) + +WideString(L" ,name: " )+WideString(name)); + } +#endif _DEBUG + + return KeyConvert[key]; + } +}//namespace hgl diff --git a/src/Platform/Win/LogConsole.cpp b/src/Platform/Win/LogConsole.cpp new file mode 100644 index 00000000..9e04a813 --- /dev/null +++ b/src/Platform/Win/LogConsole.cpp @@ -0,0 +1,66 @@ +#include +#include +#include + +namespace hgl +{ + namespace logger + { + constexpr uint LOG_BUF_SIZE=4096; + + class LogWinConsole:public Logger + { + private: + + DWORD result; + + void *console_handle; + + u16char buf[LOG_BUF_SIZE]; + + public: + + LogWinConsole(LogLevel ll):Logger(ll) + { + console_handle=GetStdHandle(STD_OUTPUT_HANDLE); + } + + bool Create(const UTF16String &) + { + return(true); + } + + ~LogWinConsole() + { + Close(); + } + + void Close() + { + CloseHandle(console_handle); + } + + void Write(const u16char *str,int size) + { + WriteConsoleW(console_handle,str,size,&result,nullptr); + WriteConsoleW(console_handle,L"\n", 1, &result, nullptr); + } + + void Write(const char *str,int size) + { + const int len=u8_to_u16(buf,LOG_BUF_SIZE,str,size); + + if(len<=0)return; + + buf[len]=L'\n'; + + WriteConsoleW(console_handle,buf,len+1,&result,nullptr); + } + };//class LogWinConsole + + Logger *CreateLoggerConsole(const OSString &,LogLevel ll) + { + return(new LogWinConsole(ll)); + } + }//namespace logger +}//namespace hgl diff --git a/src/Platform/Win/LogDialog.cpp b/src/Platform/Win/LogDialog.cpp new file mode 100644 index 00000000..9103e41f --- /dev/null +++ b/src/Platform/Win/LogDialog.cpp @@ -0,0 +1,53 @@ +#include +#include +#include + +namespace hgl +{ + namespace logger + { + class LogWinDialog:public Logger + { + UTF16String name; + + u16char buf[4096]; + + public: + + LogWinDialog(LogLevel ll):Logger(ll) + { + name=project_code; + } + + bool Create(const UTF16String &) + { + return(true); + } + + void Close() + { + } + + void Write(const u16char *str,int) + { + MessageBoxW(nullptr,str,name,MB_OK); + } + + void Write(const char *str,int size) + { + const int len=u8_to_u16(buf,4096,str,size); + + if(len<=0)return; + + buf[len] = 0; + + MessageBoxW(nullptr,buf,name,MB_OK); + } + };//class LogWinDialog + + Logger *CreateLoggerDialog(const OSString &,LogLevel ll) + { + return(new LogWinDialog(ll)); + } + }//namespace logger +}//namespace hgl diff --git a/src/Platform/Win/Pipe.cpp b/src/Platform/Win/Pipe.cpp new file mode 100644 index 00000000..c8e36e4a --- /dev/null +++ b/src/Platform/Win/Pipe.cpp @@ -0,0 +1,16 @@ +#include + +namespace hgl +{ + bool CreatePipe(pipe_pair &pp) + { + SECURITY_ATTRIBUTES sa; + + sa.nLength=sizeof(SECURITY_ATTRIBUTES); + sa.bInheritHandle=TRUE; + sa.lpSecurityDescriptor=nullptr; + + return CreatePipe(&(pp[0]),&(pp[1]),&sa,0); + } +}//namespace hgl + diff --git a/src/Platform/Win/ProcMutex.cpp b/src/Platform/Win/ProcMutex.cpp new file mode 100644 index 00000000..403d3416 --- /dev/null +++ b/src/Platform/Win/ProcMutex.cpp @@ -0,0 +1,65 @@ +#include +#include + +namespace hgl +{ + ProcMutex::ProcMutex() + { + lock = nullptr; + } + + bool ProcMutex::Create(const os_char *name) + { + if (lock != nullptr)return(false); + + lock = CreateMutexW(NULL, FALSE, name); + + if(GetLastError()==ERROR_ALREADY_EXISTS) + { + CloseHandle(lock); + lock=nullptr; + } + + return lock; + } + + void ProcMutex::Clear() + { + if (lock == nullptr)return; + + CloseHandle(lock); + + lock = nullptr; + } + + bool ProcMutex::Lock() + { + if (lock == nullptr)return(false); + + DWORD rv = WaitForSingleObject(lock, INFINITE); + + if (rv == WAIT_OBJECT_0 || rv == WAIT_ABANDONED) + return(true); + + return(false); + } + + bool ProcMutex::TryLock() + { + if (lock == nullptr)return(false); + + DWORD rv = WaitForSingleObject(lock, 0); + + if (rv == WAIT_OBJECT_0 || rv == WAIT_ABANDONED) + return(true); + + return(false); + } + + bool ProcMutex::Unlock() + { + if (lock == nullptr)return(false); + + return(!ReleaseMutex(lock)); + } +}//namespace hgl diff --git a/src/Platform/Win/ProgramPath.cpp b/src/Platform/Win/ProgramPath.cpp new file mode 100644 index 00000000..a73a8b3b --- /dev/null +++ b/src/Platform/Win/ProgramPath.cpp @@ -0,0 +1,49 @@ +#include +#include +#include + +namespace hgl +{ + namespace filesystem + { + void GetLocalAppdataPath(os_char fn[HGL_MAX_PATH]) + { + SHGetFolderPathW(nullptr, CSIDL_LOCAL_APPDATA, nullptr, 0, fn); + } + + /** + * 取得当前程序完整路径名称 + */ + bool GetCurrentProgram(OSString &result) + { + os_char *path=new os_char[HGL_MAX_PATH]; + + GetModuleFileNameW(nullptr,path,HGL_MAX_PATH); + + result = path; + delete[] path; + + return(true); + } + + /** + * 取得当前程序所在路径 + */ + bool GetCurrentProgramPath(OSString &result) + { + os_char *path=new os_char[HGL_MAX_PATH]; + + int len=GetModuleFileNameW(nullptr,path,HGL_MAX_PATH); + + os_char *right=hgl::strrchr(path,len,HGL_DIRECTORY_SEPARATOR); + + if(right) + *right=0; + + result = path; + delete[] path; + + return(true); + } + }//namespace filesystem +}//namespace hgl diff --git a/src/Platform/Win/RWLock.cpp b/src/Platform/Win/RWLock.cpp new file mode 100644 index 00000000..3a1018b1 --- /dev/null +++ b/src/Platform/Win/RWLock.cpp @@ -0,0 +1,25 @@ +#include + +#pragma warning(disable:4800) // BOOL -> bool 性能损失警告 +namespace hgl +{ + RWLock::RWLock() + { + lock = new SRWLOCK; + + InitializeSRWLock((SRWLOCK *)lock); + } + + RWLock::~RWLock() + { + delete (SRWLOCK *)lock; + } + + bool RWLock::TryReadLock() { return TryAcquireSRWLockShared((SRWLOCK *)lock); } + bool RWLock::ReadLock() { AcquireSRWLockShared((SRWLOCK *)lock); return(true); } + bool RWLock::ReadUnlock() { ReleaseSRWLockShared((SRWLOCK *)lock); return(true); } + + bool RWLock::TryWriteLock() { return TryAcquireSRWLockExclusive((SRWLOCK *)lock); } + bool RWLock::WriteLock() { AcquireSRWLockExclusive((SRWLOCK *)lock); return(true); } + bool RWLock::WriteUnlock() { ReleaseSRWLockExclusive((SRWLOCK *)lock); return(true); } +}//namespace hgl diff --git a/src/Platform/Win/Semaphore.cpp b/src/Platform/Win/Semaphore.cpp new file mode 100644 index 00000000..94967c64 --- /dev/null +++ b/src/Platform/Win/Semaphore.cpp @@ -0,0 +1,54 @@ +#include +#include + +#include +#pragma warning(disable:4800) // int -> bool 性能损失警告 + +namespace hgl +{ + /** + * @param max_count 最大计数 + */ + Semaphore::Semaphore(int max_count) + { + ptr=CreateSemaphore(nullptr,0,max_count,nullptr); + + if(!ptr) + LOG_ERROR(OS_TEXT("CreateSemaphore error,max_count=")+OSString(max_count)); + } + + Semaphore::~Semaphore() + { + CloseHandle(ptr); + } + + /** + * 发送信号 + * @param n 发送的信号数量 + * @return 是否释放成功 + */ + bool Semaphore::Post(int n) + { + if(n<=0)return(false); + return(ReleaseSemaphore(ptr,n,nullptr)); + } + + /** + * 尝试获取一个信号 + * @return 是否有取得信号 + */ + bool Semaphore::TryAcquire() + { + return(WaitForSingleObject(ptr,0)==WAIT_OBJECT_0); + } + + /** + * 等待并获取一个信号 + * @param time 等待的最长时间,使用0表示无限等待.(单位秒) + * @return 是否等待到了,如果超过最长时间,仍未等到即为超时,返回false + */ + bool Semaphore::Acquire(double time_out) + { + return(WaitForSingleObject(ptr,time_out>0?DWORD(time_out*1000):INFINITE)==WAIT_OBJECT_0); + } +}//namespace hgl diff --git a/src/Platform/Win/SystemInfo.cpp b/src/Platform/Win/SystemInfo.cpp new file mode 100644 index 00000000..b26d4b68 --- /dev/null +++ b/src/Platform/Win/SystemInfo.cpp @@ -0,0 +1,99 @@ +#include +//#include +#include +#include +#include +#include +#include + +namespace hgl +{ + bool GetTempPath(WideString &temp_path,unsigned long s) + { + HKEY hKey; + DWORD type; + + LONG result = RegOpenKeyExW(HKEY_CURRENT_USER,L"Environment",0,KEY_READ,&hKey); + + if(result==ERROR_SUCCESS) + { + wchar_t temp[HGL_MAX_PATH]; + DWORD size=HGL_MAX_PATH; + + result = RegQueryValueExW( hKey,L"TEMP", NULL, &type, (LPBYTE)temp, &size ); + + RegCloseKey(hKey); + + if(result==ERROR_SUCCESS) + { + wchar_t path[HGL_MAX_PATH]; + + ExpandEnvironmentStringsW(temp,path,s); + temp_path=path; + return(true); + } + } + + return(false); + } + + bool GetCMGDKPath(WideString &cmgdk_path) + { + HKEY hKey; + DWORD type; + + LONG result = RegOpenKeyExW(HKEY_CURRENT_USER,L"Environment",0,KEY_READ,&hKey); + + if(result==ERROR_SUCCESS) + { + wchar_t path[HGL_MAX_PATH]; + DWORD size=HGL_MAX_PATH; + + result = RegQueryValueExW( hKey,L"CMGDK", NULL, &type, (LPBYTE)path, &size ); + + RegCloseKey(hKey); + + cmgdk_path=path; + + return(result==ERROR_SUCCESS); + } + + return(false); + } + + void GetOSPath(CMGDKPATH &cp) + { + wchar_t path[HGL_MAX_PATH]; + + #define GET_FOLDER(str,attrib) SHGetFolderPathW(nullptr,attrib,nullptr,0,path); \ + cp.str=path; + + GET_FOLDER(os ,CSIDL_WINDOWS ); + GET_FOLDER(library ,CSIDL_SYSTEM ); + GET_FOLDER(osfont ,CSIDL_FONTS ); + + hgl::GetTempPath(cp.temp,HGL_MAX_PATH); + + GET_FOLDER(common_data ,CSIDL_COMMON_APPDATA ); + GET_FOLDER(local_data ,CSIDL_LOCAL_APPDATA ); + + GET_FOLDER(mydata ,CSIDL_APPDATA ); + GET_FOLDER(myprogram ,CSIDL_STARTMENU ); + GET_FOLDER(mydesktop ,CSIDL_DESKTOPDIRECTORY ); + + GET_FOLDER(desktop ,CSIDL_COMMON_DESKTOPDIRECTORY ); + + #undef GET_FOLDER + } + + bool InitOSupport(ConsoleSystemInitInfo *sii) + { + if(sii->CheckDebugger&&IsDebuggerPresent()) + { + LOG_ERROR(OS_TEXT("本程序不能运行在调试模式下!")); + return(false); + } + + return(true); + } +}//namespace hgl diff --git a/src/Platform/Win/Thread.cpp b/src/Platform/Win/Thread.cpp new file mode 100644 index 00000000..96079b39 --- /dev/null +++ b/src/Platform/Win/Thread.cpp @@ -0,0 +1,63 @@ +#include +#include + +namespace hgl +{ + extern THREAD_FUNC ThreadFunc(Thread *tc); + + /** + * (线程外部调用)执行当前线程,线程优先级为tplevel + * @param tplevel 线程优先级 + * @return 是否创建线程成功 + */ + bool Thread::Start() + { + unsigned long threadid; + + exit_lock.Lock(); + + tp=::CreateThread(0,0,(PTHREAD_START_ROUTINE)ThreadFunc,this,0,&threadid); + + if(!tp) + { + exit_lock.Unlock(); + LOG_ERROR(OS_TEXT("Create Thread failed,Windows ErrorCode: ")+OSString((uint)GetLastError())); + return(false); + } + + return(true); + } + + /** + * 是否是当前线程 + */ + bool Thread::IsCurThread() + { + return(tp==GetCurrentThread()); + } + + void WaitThreadExit(thread_ptr tp,const double &time_out) + { + if(!tp)return; + + WaitForSingleObject(tp,time_out>0?time_out*1000:INFINITE); + } + + /** + * 等待多个线程中的一个完成 + * @param mt 线程 + * @param count 线程数量 + * @param time_out 等待的时间,如果为0表示等到线程运行结束为止。默认为0 + */ + void WaitThread(Thread **mt,int count,double time_out) + { + void **obj=new void *[count]; + + for(int i=0;itp; + + WaitForMultipleObjects(count,obj,false,time_out>0?time_out*1000:INFINITE); + + delete[] obj; + } +}//namespace hgl diff --git a/src/Platform/Win/ThreadMutex.cpp b/src/Platform/Win/ThreadMutex.cpp new file mode 100644 index 00000000..88158630 --- /dev/null +++ b/src/Platform/Win/ThreadMutex.cpp @@ -0,0 +1,55 @@ +#include + +#include + +#pragma warning(disable:4800) // BOOL -> bool 性能损失警告 +namespace hgl +{ + ThreadMutex::ThreadMutex() + { + InitializeCriticalSection(&ptr); + } + + ThreadMutex::~ThreadMutex() + { + Unlock(); + + DeleteCriticalSection(&ptr); + } + + /** + * 取得控制权 + * 如果对象处于排斥状态,则等待 + */ + void ThreadMutex::Lock() + { + EnterCriticalSection(&ptr); + } + + /** + * 尝试取得控制权 + * @return 是否成功取得控制权 + */ + bool ThreadMutex::TryLock() + { + return(TryEnterCriticalSection(&ptr)); + } + + /** + * 等待并取得控制权 + * @param time 等待的最大时间,时间为0表示尝试 + * @return 是否取得控制权 + */ + bool ThreadMutex::WaitLock(double time_out) + { + return(!WaitForSingleObject(&ptr,time_out*1000)); + } + + /** + * 放弃控制权 + */ + void ThreadMutex::Unlock() + { + LeaveCriticalSection(&ptr); + } +}//namespace hgl diff --git a/src/Platform/Win/Time.cpp b/src/Platform/Win/Time.cpp new file mode 100644 index 00000000..e680fe00 --- /dev/null +++ b/src/Platform/Win/Time.cpp @@ -0,0 +1,90 @@ +#include +#include + +namespace hgl +{ + namespace + { +#define APR_DELTA_EPOCH_IN_USEC 11644473600000000 //转Windows时间到Unix时间的一个差值 + //Windows是1601.1.1 + //Unix是1970.1.1 + //tanks for APR + + static inline void FileTimeToMicroTime(uint64 *result, FILETIME *input) + { + /* Convert FILETIME one 64 bit number so we can work with it. */ + *result = input->dwHighDateTime; + *result = (*result) << 32; + *result |= input->dwLowDateTime; + *result /= 10; /* Convert from 100 nano-sec periods to micro-seconds. */ + *result -= APR_DELTA_EPOCH_IN_USEC; /* Convert from Windows epoch to Unix epoch */ + return; + } + }//namespace + + long GetGMTOff() + { + SYSTEMTIME st; + FILETIME ft; + uint64 local_time; + uint64 utc_time; + + GetLocalTime(&st); + SystemTimeToFileTime(&st, &ft); + FileTimeToMicroTime(&local_time, &ft); + + GetSystemTime(&st); + SystemTimeToFileTime(&st, &ft); + FileTimeToMicroTime(&utc_time, &ft); + + return(utc_time - local_time); + } + + /** + * 取得当前时间 + * @return 当前时间(单位:百万分之一秒) + */ + uint64 GetMicroTime() + { + SYSTEMTIME st; + FILETIME ft; + uint64 result; + + GetLocalTime(&st); + + SystemTimeToFileTime(&st, &ft); + + FileTimeToMicroTime(&result, &ft); + + return(result); + } + + /** + * 取得当前时间 + * @return 当前时间(单位:千分之一秒) + */ + uint64 GetTime() + { + return(GetMicroTime() / 1000); + } + + /** + * 取得当前时间(双精度) + * @return 当前时间(单位:秒) + */ + double GetDoubleTime() ///<取得当前时间(双精度,单位秒) + { + return(double(GetMicroTime()) / HGL_MICRO_SEC_PER_SEC); + } + + /** + * 等待指定时间 + * @param time 时间(单位:秒) + */ + void WaitTime(double t) + { + if(t<=0)return; + + ::Sleep(DWORD(t*HGL_MILLI_SEC_PRE_SEC)); + } +}//namespace hgl diff --git a/example/Vulkan/WinWindow.cpp b/src/Platform/Win/WinWindow.cpp similarity index 98% rename from example/Vulkan/WinWindow.cpp rename to src/Platform/Win/WinWindow.cpp index 9063ef84..3a7701c3 100644 --- a/example/Vulkan/WinWindow.cpp +++ b/src/Platform/Win/WinWindow.cpp @@ -1,5 +1,5 @@ -#include"Window.h" -#include"VK.h" +#include +#include #include #include diff --git a/src/RenderDevice/CMakeLists.txt b/src/RenderDevice/CMakeLists.txt index c18906cf..96f5da34 100644 --- a/src/RenderDevice/CMakeLists.txt +++ b/src/RenderDevice/CMakeLists.txt @@ -1,2 +1 @@ -add_library(ULRE.RenderDevice STATIC GLFW/RenderDeviceGLFW.cpp - GLFW/RenderWindowGLFW.cpp) +add_subdirectory(Vulkan) diff --git a/src/RenderDevice/GLFW/RenderDeviceGLFW.cpp b/src/RenderDevice/GLFW/RenderDeviceGLFW.cpp deleted file mode 100644 index 4f762d52..00000000 --- a/src/RenderDevice/GLFW/RenderDeviceGLFW.cpp +++ /dev/null @@ -1,248 +0,0 @@ -#include -#include -#include -#include - -namespace hgl -{ - namespace graph - { - namespace gl - { - void InitOpenGLExt(); - } - } - - RenderWindow *CreateRenderWindowGLFW(GLFWwindow *,bool is_fullscreen); - - namespace - { - static bool init_glew=false; - static RenderDevice *render_device_glfw=nullptr; - - void InitGLEWCore() - { - if(!init_glew) - init_glew=glewInit(); - } - - void CloseGLEWCore() - { - glewTerminate(); - init_glew=false; - } - - void glfw_error_callback(int err,const char *desc) - { - std::cerr<<"glfw return error["< video_mode_list; - - public: - - const VideoMode *GetCurVideoMode()const override{return cur_video_mode;} - const ObjectList &GetVideoModeList()const override{return video_mode_list;} - }; - - VideoMode *ConvertVideoMode(const GLFWvidmode *mode) - { - if(!mode) - return nullptr; - - VideoMode *vm=new VideoMode; - - vm->width =mode->width; - vm->height =mode->height; - vm->freq =mode->refreshRate; - - vm->red =mode->redBits; - vm->green =mode->greenBits; - vm->blue =mode->blueBits; - - vm->bit =vm->red+vm->green+vm->blue; - - return vm; - } - - DisplayGLFW *GetDisplayAttrib(GLFWmonitor *gm) - { - DisplayGLFW *m=new DisplayGLFW; - - m->glfw_monitor=gm; - m->name=glfwGetMonitorName(gm); - - glfwGetMonitorPhysicalSize(gm,&(m->width),&(m->height)); - glfwGetMonitorPos(gm,&(m->x),&(m->y)); - - { - const GLFWvidmode *mode=glfwGetVideoMode(gm); - - m->cur_video_mode=ConvertVideoMode(mode); - } - - { - int count; - - const GLFWvidmode *ml=glfwGetVideoModes(gm,&count); - - for(int i=0;ivideo_mode_list.Add(ConvertVideoMode(ml+i)); - } - - return m; - } - - void SetGLFWWindowHint(const RenderSetup *gs) - { - glfwWindowHint(GLFW_SAMPLES, gs->msaa); - - glfwWindowHint(GLFW_CLIENT_API, gs->opengl.es?GLFW_OPENGL_ES_API:GLFW_OPENGL_API); - - glfwWindowHint(GLFW_CONTEXT_CREATION_API, gs->opengl.egl?GLFW_EGL_CONTEXT_API:GLFW_NATIVE_CONTEXT_API); - - if(gs->opengl.es) - { - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, gs->opengl.major); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, gs->opengl.minor); - } - else if(gs->opengl.core) - { - glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //核心模式 - glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true); //向前兼容模式(无旧特性) - - glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, gs->opengl.major); - glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, gs->opengl.minor); - } - else - { - //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE); //兼容模式 - } - - glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, gs->opengl.debug); //调试模式 - - glfwWindowHint(GLFW_VISIBLE, true); //是否显示 - - if(gs->no_use_stencil )glfwWindowHint(GLFW_STENCIL_BITS, 0 ); else - if(gs->stencil >0)glfwWindowHint(GLFW_STENCIL_BITS, gs->stencil ); - if(gs->alpha >0)glfwWindowHint(GLFW_ALPHA_BITS, gs->alpha ); - if(gs->depth >0)glfwWindowHint(GLFW_DEPTH_BITS, gs->depth ); - - if(gs->accum.red >0)glfwWindowHint(GLFW_ACCUM_RED_BITS, gs->accum.red ); - if(gs->accum.green >0)glfwWindowHint(GLFW_ACCUM_GREEN_BITS, gs->accum.green ); - if(gs->accum.blue >0)glfwWindowHint(GLFW_ACCUM_BLUE_BITS, gs->accum.blue ); - if(gs->accum.alpha >0)glfwWindowHint(GLFW_ACCUM_ALPHA_BITS, gs->accum.alpha ); - } - } - - class RenderDeviceGLFW:public RenderDevice - { - DisplayGLFW *default_display=nullptr; - - public: - - RenderDeviceGLFW() - { - render_device_glfw=this; - } - - ~RenderDeviceGLFW() - { - CloseGLEWCore(); - glfwTerminate(); - render_device_glfw=nullptr; - } - - const bool Init()override{return true;} - const void Close()override{}; - - const UTF8String GetName()override - { - return UTF8String("GLFW ")+UTF8String(glfwGetVersionString()); - } - - const void GetDisplayList(List &disp_list) override - { - int count=0; - - GLFWmonitor **ml=glfwGetMonitors(&count); - - for(int i=0;iMaximize); - glfwWindowHint(GLFW_RESIZABLE,ws->Resize); - - GLFWwindow *win=glfwCreateWindow( width, - height, - ws->Name, - nullptr, - nullptr); - - if(!win)return(nullptr); - - glfwMakeContextCurrent(win); - InitGLEWCore(); - graph::gl::InitOpenGLExt(); - - return(CreateRenderWindowGLFW(win,false)); - } - - RenderWindow *Create(const Display *disp,const VideoMode *vm,const RenderSetup *rs) override - { - SetGLFWWindowHint(rs); - - glfwWindowHint(GLFW_RED_BITS, vm->red); - glfwWindowHint(GLFW_GREEN_BITS, vm->green); - glfwWindowHint(GLFW_BLUE_BITS, vm->blue); - glfwWindowHint(GLFW_REFRESH_RATE, vm->freq); - - GLFWwindow *win=glfwCreateWindow( vm->width, - vm->height, - "ULRE", - disp?((DisplayGLFW *)disp)->glfw_monitor:nullptr, - nullptr); - - if(!win)return(nullptr); - - glfwMakeContextCurrent(win); - InitGLEWCore(); - graph::gl::InitOpenGLExt(); - - return(CreateRenderWindowGLFW(win,true)); - } - };//class RenderDevice - - RenderDevice *CreateRenderDeviceGLFW() - { - if(render_device_glfw) - return(nullptr); - - if(!glfwInit()) - return(nullptr); - - glfwSetErrorCallback(glfw_error_callback); - - return(new RenderDeviceGLFW()); - } -}//namespace hgl diff --git a/src/RenderDevice/GLFW/RenderWindowGLFW.cpp b/src/RenderDevice/GLFW/RenderWindowGLFW.cpp deleted file mode 100644 index 3cad17f2..00000000 --- a/src/RenderDevice/GLFW/RenderWindowGLFW.cpp +++ /dev/null @@ -1,65 +0,0 @@ -#include -#include - -namespace hgl -{ - class RenderWindowGLFW:public RenderWindow - { - GLFWwindow *glfw_win; - - public: - - RenderWindowGLFW(GLFWwindow *w,bool is_fullscreen) - { - glfw_win=w; - full_screen=is_fullscreen; - - glfwGetWindowSize(glfw_win,&width,&height); - } - - ~RenderWindowGLFW() - { - glfwDestroyWindow(glfw_win); - } - - void ToMin()override{glfwIconifyWindow(glfw_win);} - void ToMax()override{glfwMaximizeWindow(glfw_win);} - - void Show()override{glfwShowWindow(glfw_win);} - void Hide()override{glfwHideWindow(glfw_win);} - - void SetCaption(const UTF8String &name) override - { - glfwSetWindowTitle(glfw_win,name.c_str()); - this->caption=name; - } - - void SetSize(int w,int h) override - { - glfwSetWindowSize(glfw_win,w,h); - this->width=w; - this->height=h; - } - - void MakeToCurrent()override{glfwMakeContextCurrent(glfw_win);} - - void SwapBuffer()override{glfwSwapBuffers(glfw_win);} - - void WaitEvent(const double &time_out)override - { - if(time_out>0) - glfwWaitEventsTimeout(time_out); - else - glfwWaitEvents(); - } - - void PollEvent()override{glfwPollEvents();} - - bool IsOpen()override{return(!glfwWindowShouldClose(glfw_win));} - };//class RenderWindowGLFW:public RenderWindow - - RenderWindow *CreateRenderWindowGLFW(GLFWwindow *win,bool is_fullscreen) - { - return(new RenderWindowGLFW(win,is_fullscreen)); - } -}//namespace hgl diff --git a/src/RenderDevice/Vulkan/CMakeLists.txt b/src/RenderDevice/Vulkan/CMakeLists.txt new file mode 100644 index 00000000..38f893f3 --- /dev/null +++ b/src/RenderDevice/Vulkan/CMakeLists.txt @@ -0,0 +1,21 @@ +add_library(ULRE.RenderDevice.Vulkan STATIC VKFormat.cpp + VKInstance.cpp + VKPhysicalDevice.cpp + VKImageView.cpp + VKCommandBuffer.cpp + VKDeviceAttribute.cpp + VKDeviceCreater.cpp + VKDevice.cpp + VKDeviceBuffer.cpp + VKBuffer.cpp + VKDescriptorSets.cpp + VKRenderPass.cpp + VKShaderModule.cpp + VKShaderModuleManage.cpp + VKVertexAttributeBinding.cpp + VKPipeline.cpp + VKSemaphore.cpp + VKFramebuffer.cpp + VKFence.cpp + VKMaterial.cpp + VKRenderable.cpp) diff --git a/example/Vulkan/VKBuffer.cpp b/src/RenderDevice/Vulkan/VKBuffer.cpp similarity index 95% rename from example/Vulkan/VKBuffer.cpp rename to src/RenderDevice/Vulkan/VKBuffer.cpp index ccf1ba87..8d75c707 100644 --- a/example/Vulkan/VKBuffer.cpp +++ b/src/RenderDevice/Vulkan/VKBuffer.cpp @@ -1,4 +1,4 @@ -#include"VKBuffer.h" +#include VK_NAMESPACE_BEGIN Buffer::~Buffer() diff --git a/example/Vulkan/VKCommandBuffer.cpp b/src/RenderDevice/Vulkan/VKCommandBuffer.cpp similarity index 93% rename from example/Vulkan/VKCommandBuffer.cpp rename to src/RenderDevice/Vulkan/VKCommandBuffer.cpp index caedc016..d8e86d75 100644 --- a/example/Vulkan/VKCommandBuffer.cpp +++ b/src/RenderDevice/Vulkan/VKCommandBuffer.cpp @@ -1,11 +1,11 @@ -#include"VKCommandBuffer.h" -#include"VKRenderPass.h" -#include"VKFramebuffer.h" -#include"VKPipeline.h" -#include"VKBuffer.h" -#include"VKMaterial.h" -#include"VKRenderable.h" -#include"VKDescriptorSets.h" +#include +#include +#include +#include +#include +#include +#include +#include VK_NAMESPACE_BEGIN CommandBuffer::CommandBuffer(VkDevice dev,const VkExtent2D &extent,VkCommandPool cp,VkCommandBuffer cb) diff --git a/example/Vulkan/VKDescriptorSets.cpp b/src/RenderDevice/Vulkan/VKDescriptorSets.cpp similarity index 97% rename from example/Vulkan/VKDescriptorSets.cpp rename to src/RenderDevice/Vulkan/VKDescriptorSets.cpp index ee0c3d3b..e32092a7 100644 --- a/example/Vulkan/VKDescriptorSets.cpp +++ b/src/RenderDevice/Vulkan/VKDescriptorSets.cpp @@ -1,5 +1,5 @@ -#include"VKDescriptorSets.h" -#include"VKDevice.h" +#include +#include VK_NAMESPACE_BEGIN namespace diff --git a/example/Vulkan/VKDevice.cpp b/src/RenderDevice/Vulkan/VKDevice.cpp similarity index 94% rename from example/Vulkan/VKDevice.cpp rename to src/RenderDevice/Vulkan/VKDevice.cpp index 19ed6306..7f1f1a87 100644 --- a/example/Vulkan/VKDevice.cpp +++ b/src/RenderDevice/Vulkan/VKDevice.cpp @@ -1,14 +1,14 @@ -#include"VKDevice.h" +#include #include -#include"VKImageView.h" -#include"VKCommandBuffer.h" -//#include"VKDescriptorSet.h" -#include"VKRenderPass.h" -#include"VKFramebuffer.h" -#include"VKFence.h" -#include"VKSemaphore.h" -#include"VKShaderModuleManage.h" -#include"VKDescriptorSets.h" +#include +#include +//#include +#include +#include +#include +#include +#include +#include VK_NAMESPACE_BEGIN Device::Device(DeviceAttribute *da) diff --git a/example/Vulkan/VKDeviceAttribute.cpp b/src/RenderDevice/Vulkan/VKDeviceAttribute.cpp similarity index 97% rename from example/Vulkan/VKDeviceAttribute.cpp rename to src/RenderDevice/Vulkan/VKDeviceAttribute.cpp index 615f4822..7c042480 100644 --- a/example/Vulkan/VKDeviceAttribute.cpp +++ b/src/RenderDevice/Vulkan/VKDeviceAttribute.cpp @@ -1,6 +1,6 @@ -#include"VKDeviceAttribute.h" -#include"VKPhysicalDevice.h" -#include"VKImageView.h" +#include +#include +#include #include VK_NAMESPACE_BEGIN diff --git a/example/Vulkan/VKDeviceBuffer.cpp b/src/RenderDevice/Vulkan/VKDeviceBuffer.cpp similarity index 97% rename from example/Vulkan/VKDeviceBuffer.cpp rename to src/RenderDevice/Vulkan/VKDeviceBuffer.cpp index 537a1a32..04a0b116 100644 --- a/example/Vulkan/VKDeviceBuffer.cpp +++ b/src/RenderDevice/Vulkan/VKDeviceBuffer.cpp @@ -1,5 +1,5 @@ -#include"VKDevice.h" -#include"VKBuffer.h" +#include +#include VK_NAMESPACE_BEGIN namespace diff --git a/example/Vulkan/VKDeviceCreater.cpp b/src/RenderDevice/Vulkan/VKDeviceCreater.cpp similarity index 98% rename from example/Vulkan/VKDeviceCreater.cpp rename to src/RenderDevice/Vulkan/VKDeviceCreater.cpp index f2d5911c..cf38d5be 100644 --- a/example/Vulkan/VKDeviceCreater.cpp +++ b/src/RenderDevice/Vulkan/VKDeviceCreater.cpp @@ -1,7 +1,7 @@ -#include"VKDevice.h" -#include"VKInstance.h" -#include"VKPhysicalDevice.h" -#include"VKFramebuffer.h" +#include +#include +#include +#include VK_NAMESPACE_BEGIN VkSurfaceKHR CreateRenderDevice(VkInstance,Window *); diff --git a/example/Vulkan/VKFence.cpp b/src/RenderDevice/Vulkan/VKFence.cpp similarity index 72% rename from example/Vulkan/VKFence.cpp rename to src/RenderDevice/Vulkan/VKFence.cpp index c1e3f53f..37248ec1 100644 --- a/example/Vulkan/VKFence.cpp +++ b/src/RenderDevice/Vulkan/VKFence.cpp @@ -1,4 +1,4 @@ -#include"VKFence.h" +#include VK_NAMESPACE_BEGIN Fence::~Fence() { diff --git a/example/Vulkan/VKFormat.cpp b/src/RenderDevice/Vulkan/VKFormat.cpp similarity index 99% rename from example/Vulkan/VKFormat.cpp rename to src/RenderDevice/Vulkan/VKFormat.cpp index 464848e1..ffb73d51 100644 --- a/example/Vulkan/VKFormat.cpp +++ b/src/RenderDevice/Vulkan/VKFormat.cpp @@ -1,4 +1,4 @@ -#include"VK.h" +#include VK_NAMESPACE_BEGIN diff --git a/example/Vulkan/VKFramebuffer.cpp b/src/RenderDevice/Vulkan/VKFramebuffer.cpp similarity index 89% rename from example/Vulkan/VKFramebuffer.cpp rename to src/RenderDevice/Vulkan/VKFramebuffer.cpp index b63cc7af..e88c8f4e 100644 --- a/example/Vulkan/VKFramebuffer.cpp +++ b/src/RenderDevice/Vulkan/VKFramebuffer.cpp @@ -1,7 +1,7 @@ -#include"VKFramebuffer.h" -#include"VKDevice.h" -#include"VKImageView.h" -#include"VKRenderPass.h" +#include +#include +#include +#include VK_NAMESPACE_BEGIN Framebuffer::~Framebuffer() diff --git a/example/Vulkan/VKInstance.cpp b/src/RenderDevice/Vulkan/VKInstance.cpp similarity index 98% rename from example/Vulkan/VKInstance.cpp rename to src/RenderDevice/Vulkan/VKInstance.cpp index cda915a6..94218ff9 100644 --- a/example/Vulkan/VKInstance.cpp +++ b/src/RenderDevice/Vulkan/VKInstance.cpp @@ -1,6 +1,6 @@ -#include"VKInstance.h" -#include"VKSurfaceExtensionName.h" -#include"VKPhysicalDevice.h" +#include +#include +#include #include VK_NAMESPACE_BEGIN diff --git a/example/Vulkan/VKMaterial.cpp b/src/RenderDevice/Vulkan/VKMaterial.cpp similarity index 93% rename from example/Vulkan/VKMaterial.cpp rename to src/RenderDevice/Vulkan/VKMaterial.cpp index 6eba788a..51a28136 100644 --- a/example/Vulkan/VKMaterial.cpp +++ b/src/RenderDevice/Vulkan/VKMaterial.cpp @@ -1,10 +1,10 @@ -#include"VKMaterial.h" -#include"VKDevice.h" -#include"VKDescriptorSets.h" -#include"VKShaderModule.h" -#include"VKVertexAttributeBinding.h" -#include"VKRenderable.h" -#include"VKBuffer.h" +#include +#include +#include +#include +#include +#include +#include VK_NAMESPACE_BEGIN Material *CreateMaterial(Device *dev,ShaderModuleMap *shader_maps) { diff --git a/example/Vulkan/VKPhysicalDevice.cpp b/src/RenderDevice/Vulkan/VKPhysicalDevice.cpp similarity index 97% rename from example/Vulkan/VKPhysicalDevice.cpp rename to src/RenderDevice/Vulkan/VKPhysicalDevice.cpp index d0c161f1..70953e7c 100644 --- a/example/Vulkan/VKPhysicalDevice.cpp +++ b/src/RenderDevice/Vulkan/VKPhysicalDevice.cpp @@ -1,4 +1,4 @@ -#include"VKPhysicalDevice.h" +#include VK_NAMESPACE_BEGIN PhysicalDevice::PhysicalDevice(VkInstance inst,VkPhysicalDevice pd) diff --git a/example/Vulkan/VKPipeline.cpp b/src/RenderDevice/Vulkan/VKPipeline.cpp similarity index 97% rename from example/Vulkan/VKPipeline.cpp rename to src/RenderDevice/Vulkan/VKPipeline.cpp index cbe67bd2..74d90a37 100644 --- a/example/Vulkan/VKPipeline.cpp +++ b/src/RenderDevice/Vulkan/VKPipeline.cpp @@ -1,7 +1,7 @@ -#include"VKPipeline.h" -#include"VKDevice.h" -#include"VKMaterial.h" -#include"VKRenderPass.h" +#include +#include +#include +#include VK_NAMESPACE_BEGIN Pipeline::~Pipeline() diff --git a/example/Vulkan/VKRenderPass.cpp b/src/RenderDevice/Vulkan/VKRenderPass.cpp similarity index 73% rename from example/Vulkan/VKRenderPass.cpp rename to src/RenderDevice/Vulkan/VKRenderPass.cpp index 7f191dd6..35e02c0f 100644 --- a/example/Vulkan/VKRenderPass.cpp +++ b/src/RenderDevice/Vulkan/VKRenderPass.cpp @@ -1,4 +1,4 @@ -#include"VKRenderPass.h" +#include VK_NAMESPACE_BEGIN RenderPass::~RenderPass() { diff --git a/example/Vulkan/VKRenderable.cpp b/src/RenderDevice/Vulkan/VKRenderable.cpp similarity index 90% rename from example/Vulkan/VKRenderable.cpp rename to src/RenderDevice/Vulkan/VKRenderable.cpp index eaf41542..ecd94c67 100644 --- a/example/Vulkan/VKRenderable.cpp +++ b/src/RenderDevice/Vulkan/VKRenderable.cpp @@ -1,6 +1,6 @@ -#include"VKRenderable.h" -#include"VKBuffer.h" -#include"VKShaderModule.h" +#include +#include +#include VK_NAMESPACE_BEGIN Renderable::Renderable(const VertexShaderModule *vsm) diff --git a/example/Vulkan/VKSemaphore.cpp b/src/RenderDevice/Vulkan/VKSemaphore.cpp similarity index 72% rename from example/Vulkan/VKSemaphore.cpp rename to src/RenderDevice/Vulkan/VKSemaphore.cpp index 1b707099..63ec2f6a 100644 --- a/example/Vulkan/VKSemaphore.cpp +++ b/src/RenderDevice/Vulkan/VKSemaphore.cpp @@ -1,4 +1,4 @@ -#include"VKSemaphore.h" +#include VK_NAMESPACE_BEGIN Semaphore::~Semaphore() { diff --git a/example/Vulkan/VKShaderModule.cpp b/src/RenderDevice/Vulkan/VKShaderModule.cpp similarity index 95% rename from example/Vulkan/VKShaderModule.cpp rename to src/RenderDevice/Vulkan/VKShaderModule.cpp index f0a5e8cb..646b182e 100644 --- a/example/Vulkan/VKShaderModule.cpp +++ b/src/RenderDevice/Vulkan/VKShaderModule.cpp @@ -1,6 +1,6 @@ -#include"VKShaderModule.h" -#include"VKVertexAttributeBinding.h" -#include"VKShaderParse.h" +#include +#include +#include VK_NAMESPACE_BEGIN ShaderModule::ShaderModule(int id,VkPipelineShaderStageCreateInfo *sci,const ShaderParse *sp) diff --git a/example/Vulkan/VKShaderModuleManage.cpp b/src/RenderDevice/Vulkan/VKShaderModuleManage.cpp similarity index 88% rename from example/Vulkan/VKShaderModuleManage.cpp rename to src/RenderDevice/Vulkan/VKShaderModuleManage.cpp index 7a370308..7144017b 100644 --- a/example/Vulkan/VKShaderModuleManage.cpp +++ b/src/RenderDevice/Vulkan/VKShaderModuleManage.cpp @@ -1,9 +1,9 @@ -#include"VKShaderModuleManage.h" -#include"VKShaderModule.h" -#include"VKMaterial.h" -#include"VKDevice.h" -#include"AssetsManage.h" -#include"VKShaderParse.h" +#include +#include +#include +#include +#include +#include VK_NAMESPACE_BEGIN Material *CreateMaterial(Device *dev,ShaderModuleMap *shader_maps); @@ -61,10 +61,11 @@ const ShaderModule *ShaderModuleManage::CreateShader(const VkShaderStageFlagBits return sm; } -const ShaderModule *ShaderModuleManage::CreateShader(const VkShaderStageFlagBits shader_stage_bit,const UTF8String &filename) +const ShaderModule *ShaderModuleManage::CreateShader(const VkShaderStageFlagBits shader_stage_bit,const OSString &filename) { uint32_t spv_size; - void *spv_data=LoadFileToMemory(filename,spv_size); + void *spv_data; + spv_size=hgl::filesystem::LoadFileToMemory(filename,&spv_data); if(!spv_data) return(nullptr); diff --git a/example/Vulkan/VKVertexAttributeBinding.cpp b/src/RenderDevice/Vulkan/VKVertexAttributeBinding.cpp similarity index 94% rename from example/Vulkan/VKVertexAttributeBinding.cpp rename to src/RenderDevice/Vulkan/VKVertexAttributeBinding.cpp index add0154c..adbc75f4 100644 --- a/example/Vulkan/VKVertexAttributeBinding.cpp +++ b/src/RenderDevice/Vulkan/VKVertexAttributeBinding.cpp @@ -1,5 +1,5 @@ -#include"VKVertexAttributeBinding.h" -#include"VKShaderModule.h" +#include +#include VK_NAMESPACE_BEGIN VertexAttributeBinding::VertexAttributeBinding(VertexShaderModule *s) diff --git a/example/Vulkan/VkImageView.cpp b/src/RenderDevice/Vulkan/VkImageView.cpp similarity index 96% rename from example/Vulkan/VkImageView.cpp rename to src/RenderDevice/Vulkan/VkImageView.cpp index 33358dde..98608022 100644 --- a/example/Vulkan/VkImageView.cpp +++ b/src/RenderDevice/Vulkan/VkImageView.cpp @@ -1,4 +1,4 @@ -#include"VKImageView.h" +#include VK_NAMESPACE_BEGIN ImageView::~ImageView() diff --git a/src/RenderDriver/BufferData.cpp b/src/RenderDriver/BufferData.cpp deleted file mode 100644 index 01f802d4..00000000 --- a/src/RenderDriver/BufferData.cpp +++ /dev/null @@ -1,85 +0,0 @@ -#include - -namespace hgl -{ - namespace graph - { - class BufferDataSelfAlloc:public BufferData - { - friend BufferData *CreateBufferData(const GLsizeiptr &count); - - public: - - using BufferData::BufferData; - ~BufferDataSelfAlloc() - { - delete[] buffer_data; - } - };//class BufferDataSelfAlloc:public BufferData - - BufferData *CreateBufferData(const GLsizeiptr &total_bytes) - { - if(total_bytes<=0) - return(nullptr); - - char *data=new char[total_bytes]; - - if(!data) - return(nullptr); - - return(new BufferDataSelfAlloc(data,total_bytes)); - } - - BufferData *CreateBufferData(void *data,const GLsizeiptr &count) - { - if(!data) - return(nullptr); - - if(count<=0) - return(nullptr); - - return(new BufferData((char *)data,count)); - } - } - namespace graph - { - class VertexBufferDataSelfAlloc:public VertexBufferData - { - friend VertexBufferData *CreateVertexBufferData(const GLenum &dt,const uint &dbytes,const uint &dcm,const GLsizeiptr &count); - - public: - - using VertexBufferData::VertexBufferData; - ~VertexBufferDataSelfAlloc() - { - delete[] buffer_data; - } - };//class BufferDataSelfAlloc:public VertexBufferData - - VertexBufferData *CreateVertexBufferData(const GLenum &dt,const uint &dbytes,const uint &dcm,const GLsizeiptr &count) - { - if(dbytes<=0||dcm<=0||dcm>=5||count<=0) - return(nullptr); - - const uint total_bytes=dbytes*dcm*count; - - char *data=new char[total_bytes]; - - if(!data) - return(nullptr); - - return(new VertexBufferDataSelfAlloc(dt,dbytes,dcm,count,data)); - } - - VertexBufferData *CreateVertexBufferData(void *data,const GLenum &dt,const uint &dbytes,const uint &dcm,const GLsizeiptr &count) - { - if(!data) - return(nullptr); - - if(dbytes<=0||dcm<=0||dcm>=5||count<=0) - return(nullptr); - - return(new VertexBufferData(dt,dbytes,dcm,count,(char *)data)); - } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/BufferObject.cpp b/src/RenderDriver/BufferObject.cpp deleted file mode 100644 index 078dbb7d..00000000 --- a/src/RenderDriver/BufferObject.cpp +++ /dev/null @@ -1,183 +0,0 @@ -#include -namespace hgl -{ - namespace graph - { - namespace gl - { - namespace dsa - { - GLuint CreateBuffer() - { - GLuint index; - - glCreateBuffers(1,&index); - - return index; - } - - void BufferAlloc(GLenum type,GLuint index,GLsizeiptr size) - { - glNamedBufferStorage(index,size,nullptr,GL_MAP_WRITE_BIT); - } - - void BufferData(GLenum type,GLuint index,void *data,GLsizeiptr size,GLenum user_pattern) - { - glNamedBufferData(index,size,data,user_pattern); - } - - void BufferSubData(GLenum type,GLuint index,void *data,GLsizeiptr start,GLsizeiptr size) - { - glNamedBufferSubData(index,start,size,data); - } - }//namespace dsa - - namespace dsa_ext - { - void BufferAlloc(GLenum type,GLuint index,GLsizeiptr size) - { - glNamedBufferStorageEXT(type,size,nullptr,GL_MAP_WRITE_BIT_EXT); - } - - void BufferData(GLenum type,GLuint index,void *data,GLsizeiptr size,GLenum user_pattern) - { - glNamedBufferDataEXT(index,size,data,user_pattern); - } - - void BufferSubData(GLenum type,GLuint index,void *data,GLsizeiptr start,GLsizeiptr size) - { - glNamedBufferSubDataEXT(index,start,size,data); - } - }//namespace dsa - - namespace bind_storage - { - - } - - namespace bind - { - GLuint CreateBuffer() - { - GLuint index; - - glGenBuffers(1,&index); - - return index; - } - - void BufferAlloc(GLenum type,GLuint index,GLsizeiptr size) - { - glBindBuffer(type,index); - glBufferStorage(type,size,nullptr,GL_MAP_WRITE_BIT); - } - - void BufferData(GLenum type,GLuint index,void *data,GLsizeiptr size,GLenum user_pattern) - { - glBindBuffer(type,index); - glBufferData(type,size,data,user_pattern); - } - - void BufferSubData(GLenum type,GLuint index,void *data,GLsizeiptr start,GLsizeiptr size) - { - glBindBuffer(type,index); - glBufferSubData(type,start,size,data); - } - } - - static GLuint(*CreateBuffer)(); - static void(*BufferAlloc)(GLenum type,GLuint index,GLsizeiptr size); - static void(*BufferData)(GLenum type,GLuint index,void *data,GLsizeiptr size,GLenum user_pattern); - static void(*BufferSubData)(GLenum type,GLuint index,void *data,GLsizeiptr start,GLsizeiptr size); - - void InitBufferObjectAPI() - { - if(glCreateBuffers - ||glNamedBufferData - ||glNamedBufferSubData) //dsa - { - hgl::graph::gl::CreateBuffer=dsa::CreateBuffer; - hgl::graph::gl::BufferAlloc=dsa::BufferAlloc; - hgl::graph::gl::BufferData=dsa::BufferData; - hgl::graph::gl::BufferSubData=dsa::BufferSubData; - } - else - if(glNamedBufferDataEXT - ||glNamedBufferSubDataEXT) - { - hgl::graph::gl::CreateBuffer=bind::CreateBuffer; - hgl::graph::gl::BufferAlloc=dsa_ext::BufferAlloc; - hgl::graph::gl::BufferData=dsa_ext::BufferData; - hgl::graph::gl::BufferSubData=dsa_ext::BufferSubData; - } - else - { - hgl::graph::gl::CreateBuffer=bind::CreateBuffer; - hgl::graph::gl::BufferAlloc=bind::BufferAlloc; - hgl::graph::gl::BufferData=bind::BufferData; - hgl::graph::gl::BufferSubData=bind::BufferSubData; - } - } - }//namespace gl - - BufferObject::BufferObject(GLenum type) - { - buffer_index=gl::CreateBuffer(); - buffer_type=type; - - user_pattern=0; - buffer_bytes=0; - buffer_data=nullptr; - } - - BufferObject::~BufferObject() - { - SAFE_CLEAR(buffer_data); - - glDeleteBuffers(1,&buffer_index); - } - - bool BufferObject::Create(GLsizeiptr size) - { - if(size<=0)return(false); - - gl::BufferAlloc(buffer_type,buffer_index,size); - - return true; - } - - bool BufferObject::Submit(void *data,GLsizeiptr size,GLenum up) - { - if(!data||size<=0)return(false); - - user_pattern=up; - buffer_bytes=size; - gl::BufferData(buffer_type,buffer_index,data,size,user_pattern); - - return(true); - } - - bool BufferObject::Submit(const BufferData *buf_data,GLenum up) - { - if(!buf_data)return(false); - - void * data=buf_data->GetData(); - GLsizeiptr size=buf_data->GetTotalBytes(); - - if(!data||size<=0)return(false); - - buffer_data=buf_data; - - return Submit(data,size,up); - } - - bool BufferObject::Change(void *data,GLsizeiptr start,GLsizeiptr size) - { - if(!data||start<0||size<=0)return(false); - - gl::BufferSubData(buffer_type,buffer_index,data,start,size); - - return(true); - } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/CMakeLists.txt b/src/RenderDriver/CMakeLists.txt deleted file mode 100644 index 18caafe5..00000000 --- a/src/RenderDriver/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -FILE(GLOB_RECURSE GRAPH_INC_FILES "${ROOT_INCLUDE_PATH}/hgl/graph/*.h") -SET(GRAPH_SRC_FILES OpenGLDebug.cpp - OpenGLExt.cpp - GLSL.cpp - Shader.cpp - BufferData.cpp - BufferObject.cpp - VertexArray.cpp - Renderable.cpp - RenderState.cpp - TextureFormat.cpp - Texture1D.cpp - Texture1DDSA.cpp - Texture2D.cpp - Texture2DDSA.cpp) - -source_group("Headers" FILES ${GRAPH_INC_FILES}) -source_group("Sources" FILES ${GRAPH_SRC_FILES}) - -add_library(ULRE.RenderDriver STATIC ${GRAPH_INC_FILES} - ${GRAPH_SRC_FILES}) - diff --git a/src/RenderDriver/GLCore/CMakeLists.txt b/src/RenderDriver/GLCore/CMakeLists.txt deleted file mode 100644 index 8b137891..00000000 --- a/src/RenderDriver/GLCore/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/RenderDriver/GLCore/RenderDriverGLCore.cpp b/src/RenderDriver/GLCore/RenderDriverGLCore.cpp deleted file mode 100644 index 1ee0df10..00000000 --- a/src/RenderDriver/GLCore/RenderDriverGLCore.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include - -namespace hgl -{ - namespace graph - { - class RenderDriverGLCore:public RenderDriver - { - public: - - void SetCurStatus(const RenderStatus &rs) override - { - } - - void ClearColorBuffer() override - { - } - - void ClearDepthBuffer() override - { - } - };//class RenderDriverGLCore:public RenderDriver - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/GLES/CMakeLists.txt b/src/RenderDriver/GLES/CMakeLists.txt deleted file mode 100644 index e02abfc9..00000000 --- a/src/RenderDriver/GLES/CMakeLists.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/src/RenderDriver/GLSL.cpp b/src/RenderDriver/GLSL.cpp deleted file mode 100644 index 3e9dbedd..00000000 --- a/src/RenderDriver/GLSL.cpp +++ /dev/null @@ -1,397 +0,0 @@ -#include -#include -#include -#include -#include - -namespace hgl -{ - namespace graph - { - namespace - { - constexpr uint OpenGLShaderType[ShaderType::stEnd]= - { - GL_VERTEX_SHADER, ///<顶点着色程序 - GL_TESS_CONTROL_SHADER, ///<镶嵌控制着色程序(需OpenGL 4.0或ARB_tessellation_shader) - GL_TESS_EVALUATION_SHADER, ///<镶嵌评估着色程序(需OpenGL 4.0或ARB_tessellation_shader) - GL_GEOMETRY_SHADER, ///<几何着色程序 - GL_FRAGMENT_SHADER, ///<片断着色程序 - GL_COMPUTE_SHADER ///<计算着色程序(需OpenGL 4.3或ARB_compute_shader) - }; - } - - const char ShaderTypeName[ShaderType::stEnd][32]= - { - "Vertex", - "TessControl", - "TessEvaluation", - "Geometry", - "Fragment", - "Compute" - }; - - namespace - { - /** - * 编译一段shader - * @param type 类型 - * @param name 名称 - * @param shader_source 代码 - * @return 编译成功的shader句柄 - * @return 0 编译失败 - */ - GLuint CompileShader(GLenum type,const char *name,const char *shader_source) - { - if(!shader_source)return(0); - - GLuint shader=glCreateShader(type); - - glShaderSource(shader,1,&shader_source,0); - - glCompileShader(shader); - - GLint compiled,log_length; - - glGetShaderiv(shader,GL_COMPILE_STATUS,&compiled); - - if(compiled) - return(shader); - - glGetShaderiv(shader,GL_INFO_LOG_LENGTH,&log_length); - - GLint char_writen; - char *log=new char[log_length]; - - glGetShaderInfoLog(shader,log_length,&char_writen,log); - - LOG_HINT(UTF8String(name)+U8_TEXT(" shader compile error\n\n")+ UTF8String(log)); - - delete[] log; - - LOG_ERROR(shader_source); - - glDeleteShader(shader); - - return(0); - } - }//namespace - - void Shader::Clear() - { - for(int i=0;i=ShaderType::stEnd)return(false); - if(shader_index[shader_type])return(false); - - if(!shader_codes - ||!(*shader_codes))return(false); - - shader_index[shader_type]=CompileShader(OpenGLShaderType[shader_type],ShaderTypeName[shader_type],shader_codes); - - if(!shader_index[shader_type]) - return(false); - - return(true); - } - - bool Shader::Build() - { - program=glCreateProgram(); - - for(int i=0;i -#include -#include - -namespace hgl -{ - namespace graph - { - namespace opengl_debug_message - { - const char *source_name[]= - { - "API", - "Windows System", - "Shader Compiler", - "Third Party", - "Application", - "Other" - }; - - const char *type_name[]= - { - "error", - "Deprecated Behavior", - "Undefined Behavior", - "Portability", - "Performance", - "Other", - "Marker", - "Push Group", - "Pop Group", - }; - - struct severity_info - { - GLenum severity; - char str[32]; - }; - - const severity_info severity_name[]= - { - {GL_DEBUG_SEVERITY_NOTIFICATION ,"notification"}, - {GL_DEBUG_SEVERITY_HIGH ,"high"}, - {GL_DEBUG_SEVERITY_MEDIUM ,"medium"}, - {GL_DEBUG_SEVERITY_LOW ,"low"}, - {0,"unkown"} - }; - - void GLAPIENTRY OpenGLDebugProc(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void * /*userParam*/) - { - UTF8String severity_string; - - for(int i=0;;i++) - { - if(severity_name[i].severity==severity - ||severity_name[i].severity==0) - { - severity_string=severity_name[i].str; - break; - } - } - - LOG_INFO(U8_TEXT("OpenGL DebugMessage: source[") - +UTF8String(source_name[source-GL_DEBUG_SOURCE_API_ARB]) - +U8_TEXT("] type[") - +UTF8String(type_name[type-GL_DEBUG_TYPE_ERROR_ARB]) - +U8_TEXT("] severity[") - +severity_string - +U8_TEXT("] message:")+UTF8String(message,length)); - } - }//opengl_debug_message - - namespace opengl_debug_message_amd - { - const char *category_name[]= - { - "API", - "Windows System", - "Deprecation", - "Undefined Behavior", - "Performance", - "Shader Compiler", - "Application", - "Other" - }; - - const char *severity_name[]= - { - "high", - "medium", - "low" - }; - - void GLAPIENTRY OpenGLDebugProc(GLuint id, GLenum category, GLenum severity, GLsizei length, const GLchar* message, void * /*userParam*/) - { - LOG_INFO(U8_TEXT("OpenGL DebugMessage: id[") - +UTF8String(id) - +U8_TEXT("] category[") - +UTF8String(category_name[category-GL_DEBUG_CATEGORY_API_ERROR_AMD]) - +U8_TEXT("] severity[") - +UTF8String(severity_name[severity-GL_DEBUG_SEVERITY_HIGH_AMD]) - +U8_TEXT("] message:")+UTF8String(message,length)); - } - }//namespace opengl_debug_message_amd - - void InitOpenGLDebug() - { - if(GLEW_VERSION_4_3||GLEW_KHR_debug) - { - glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); - - glDebugMessageCallback(opengl_debug_message::OpenGLDebugProc,nullptr); - - glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DEBUG_SEVERITY_NOTIFICATION, 0,nullptr,GL_FALSE); - } - else - if(GLEW_ARB_debug_output) - { - glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB); - - glDebugMessageCallbackARB(opengl_debug_message::OpenGLDebugProc,nullptr); - - glDebugMessageControlARB(GL_DEBUG_SOURCE_API_ARB, GL_DEBUG_TYPE_OTHER_ARB, GL_DEBUG_SEVERITY_NOTIFICATION, 0,nullptr,GL_FALSE); - } - else - if(GLEW_AMD_debug_output) - { - glDebugMessageCallbackAMD(opengl_debug_message_amd::OpenGLDebugProc,nullptr); - - glDebugMessageEnableAMD(GL_DEBUG_CATEGORY_API_ERROR_AMD, GL_DEBUG_LOGGED_MESSAGES_AMD, 0,nullptr,GL_FALSE); - } - } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/OpenGLExt.cpp b/src/RenderDriver/OpenGLExt.cpp deleted file mode 100644 index 55be7890..00000000 --- a/src/RenderDriver/OpenGLExt.cpp +++ /dev/null @@ -1,17 +0,0 @@ -#include - -namespace hgl -{ - namespace graph - { - namespace gl - { - void InitBufferObjectAPI(); - - void InitOpenGLExt() - { - InitBufferObjectAPI(); - } - }//namespace gl - } -}//namespace hgl diff --git a/src/RenderDriver/RenderState.cpp b/src/RenderDriver/RenderState.cpp deleted file mode 100644 index f710f2cb..00000000 --- a/src/RenderDriver/RenderState.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include - -namespace hgl -{ - namespace graph - { - void ColorState::Apply() - { - glColorMask(red,green,blue,alpha); - - if(clear_color) - glClearBufferfv(GL_COLOR,0,clear_color_value); - } - - void DepthState::Apply() - { - glDepthMask((GLenum)depth_mask); - glDepthFunc((GLenum)depth_func); - - if(depth_test) - glEnable(GL_DEPTH_TEST); - else - glDisable(GL_DEPTH_TEST); - - if(clear_depth) - glClearBufferfv(GL_DEPTH,0,&clear_depth_value); - } - - void CullFaceState::Apply() - { - if(enabled) - { - glEnable(GL_CULL_FACE); - glCullFace((GLenum)mode); - } - else - glDisable(GL_CULL_FACE); - } - - void PolygonModeState::Apply() - { - glPolygonMode((GLenum)face, - (GLenum)mode); - } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/Renderable.cpp b/src/RenderDriver/Renderable.cpp deleted file mode 100644 index 23eb580e..00000000 --- a/src/RenderDriver/Renderable.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include - -namespace hgl -{ - namespace graph - { - /** - * 取得可绘制数据数量 - * @return 可绘制的顶点数量 - */ - uint Renderable::GetDrawCount() - { - ElementBuffer *eb=vao->GetElement(); - - if(eb) - return eb->GetCount(); - - ArrayBuffer *pb=vao->GetPosition(); - - if(!pb) - return 0; - - return pb->GetCount(); - } - - bool Renderable::Draw() - { - glBindVertexArray(vao->GetVAO()); - - ElementBuffer *eb=vao->GetElement(); - - if(!eb) - { - ArrayBuffer *pb=vao->GetPosition(); - - if(!pb) - return(false); - - glDrawArrays(primitive,0,pb->GetCount()); - } - else - { - glDrawElements(primitive,eb->GetCount(),eb->GetDataType(),nullptr); - } - - return(true); - } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/Shader.cpp b/src/RenderDriver/Shader.cpp deleted file mode 100644 index af9f4adc..00000000 --- a/src/RenderDriver/Shader.cpp +++ /dev/null @@ -1,265 +0,0 @@ -#include -//#include - -namespace hgl -{ - namespace graph - { - /** - * 取得属性索引地址 - * @param name 属性名称 - * @return 索引地址 - * @return -1 出错 - */ - int Shader::GetAttribLocation(const char *name) - { - if(!name||!(*name))return(-1); - - int result; - - if(!attrib_location.Get(name,result)) - { - result=_GetAttribLocation(name); - - attrib_location.Add(name,result); - } - - return result; - } - - /** - * 取得一个变量的地址 - * @param name 变量名称 - * @return 地址 - * @return -1 出错 - */ - int Shader::GetUniformLocation(const char *name) ///<取得一个变量的地址 - { - if(!name||!(*name))return(-1); - - int result; - - if(!uniform_location.Get(name,result)) - { - result=_GetUniformLocation(name); - - uniform_location.Add(name,result); - } - - return result; - } - - // /** - // * 取得一个Shader只读数据区索引 - // * @param name 数据区名称 - // * @return 数据区索引 - // * @return -1 出错 - // */ - // int Shader::GetUniformBlockIndex(const char *name) - // { - // if(!name||!(*name))return(-1); - // - // int result; - // - // if(!uniform_block_index.Get(name,result)) - // { - // result=_GetUniformBlockIndex(name); - // - // uniform_block_index.Add(name,result); - // } - // - // return result; - // } - // - // /** - // * 取得一个Shader数据存储区索引 - // * @param name 数据存储区名称 - // * @return 数据存储区索引 - // * @return -1 出错 - // */ - // int Shader::GetShaderStorageIndex(const char *name) - // { - // if(!name||!(*name))return(-1); - // - // int result; - // - // if(!ssbo_index.Get(name,result)) - // { - // result=_GetShaderStorageIndex(name); - // - // ssbo_index.Add(name,result); - // } - // - // return result; - // } - - #define HGL_GLSL_SetUniform1234(func,type) bool Shader::SetUniform1##func(const char *uniform_name,type v0) \ - { \ - if(!uniform_name||!*uniform_name)return(false); \ - \ - const int location=GetUniformLocation(uniform_name); \ - \ - if(location==-1)return(false); \ - \ - return SetUniform1##func(location,v0); \ - } \ - \ - bool Shader::SetUniform2##func(const char *uniform_name,type v0,type v1) \ - { \ - if(!uniform_name||!*uniform_name)return(false); \ - \ - const int location=GetUniformLocation(uniform_name); \ - \ - if(location==-1)return(false); \ - \ - return SetUniform2##func(location,v0,v1); \ - } \ - \ - bool Shader::SetUniform3##func(const char *uniform_name,type v0,type v1,type v2) \ - { \ - if(!uniform_name||!*uniform_name)return(false); \ - \ - const int location=GetUniformLocation(uniform_name); \ - \ - if(location==-1)return(false); \ - \ - return SetUniform3##func(location,v0,v1,v2); \ - } \ - \ - bool Shader::SetUniform4##func(const char *uniform_name,type v0,type v1,type v2,type v3) \ - { \ - if(!uniform_name||!*uniform_name)return(false); \ - \ - const int location=GetUniformLocation(uniform_name); \ - \ - if(location==-1)return(false); \ - \ - return SetUniform4##func(location,v0,v1,v2,v3); \ - } - HGL_GLSL_SetUniform1234(f,float); - HGL_GLSL_SetUniform1234(i,int); - HGL_GLSL_SetUniform1234(ui,unsigned int); - - #undef HGL_GLSL_SetUniform1234 - - #define HGL_GLSL_SetUniformPointer(func,type) bool Shader::SetUniform##func(const char *uniform_name,int count,const type *value) \ - { \ - if(!uniform_name||!*uniform_name||count<=0||!value)return(false); \ - \ - const int location=GetUniformLocation(uniform_name); \ - \ - if(location==-1)return(false); \ - \ - return SetUniform##func(location,count,value); \ - } - - HGL_GLSL_SetUniformPointer(1fv,float); - HGL_GLSL_SetUniformPointer(2fv,float); - HGL_GLSL_SetUniformPointer(3fv,float); - HGL_GLSL_SetUniformPointer(4fv,float); - - HGL_GLSL_SetUniformPointer(1iv,int); - HGL_GLSL_SetUniformPointer(2iv,int); - HGL_GLSL_SetUniformPointer(3iv,int); - HGL_GLSL_SetUniformPointer(4iv,int); - - HGL_GLSL_SetUniformPointer(1uiv,unsigned int); - HGL_GLSL_SetUniformPointer(2uiv,unsigned int); - HGL_GLSL_SetUniformPointer(3uiv,unsigned int); - HGL_GLSL_SetUniformPointer(4uiv,unsigned int); - - #undef HGL_GLSL_SetUniformPointer - - #define HGL_GLSL_SetUniformMatrixPointer(func) bool Shader::SetUniformMatrix##func(const char *uniform_name,const float *mat) \ - { \ - if(!uniform_name||!*uniform_name||*mat)return(false); \ - \ - const int location=GetUniformLocation(uniform_name); \ - \ - if(location==-1)return(false); \ - \ - return SetUniformMatrix##func(location,mat); \ - } - - HGL_GLSL_SetUniformMatrixPointer(2fv); - HGL_GLSL_SetUniformMatrixPointer(3fv); - HGL_GLSL_SetUniformMatrixPointer(4fv); - - HGL_GLSL_SetUniformMatrixPointer(2x3fv); - HGL_GLSL_SetUniformMatrixPointer(3x2fv); - HGL_GLSL_SetUniformMatrixPointer(2x4fv); - HGL_GLSL_SetUniformMatrixPointer(4x2fv); - HGL_GLSL_SetUniformMatrixPointer(3x4fv); - HGL_GLSL_SetUniformMatrixPointer(4x3fv); - - #undef HGL_GLSL_SetUniformMatrixPointer - - // /** - // * 取得一个Shader只读数据区的访问对象 - // * @param name 对象名称 - // * @param level 访问级别 - // * @return 对象指针 - // */ - // UBO *Shader::GetUniformBlock(const char *name,uint level) - // { - // if(!name||!(*name)) - // { - // LOG_ERROR(U8_TEXT("UBO name error:")); - // return(nullptr); - // } - // - // UBO *ubo=uniform_block_object[name]; - // - // if(ubo) - // return ubo; - // - // const int index=GetUniformBlockIndex(name); - // - // if(index<0) - // { - // LOG_ERROR(U8_TEXT("UBO name error:")+UTF8String(name)); - // return(nullptr); - // } - // - // ubo=new UBO(name,program,index,level); - // - // uniform_block_object.Add(name,ubo); - // - // return ubo; - // } - // - // /** - // * 取得一个Shader数据存储区的访问对象 - // * @param name 对象名称 - // * @param level 访问级别 - // * @return 对象指针 - // */ - // SSBO *Shader::GetShaderStorage(const char *name,uint level) - // { - // if(!name||!(*name)) - // { - // LOG_ERROR(U8_TEXT("SSBO name error:")); - // return(nullptr); - // } - // - // SSBO *ssbo=ssbo_object[name]; - // - // if(ssbo) - // return ssbo; - // - // const int index=GetShaderStorageIndex(name); - // - // if(index<0) - // { - // LOG_ERROR(U8_TEXT("SSBO name error:")+UTF8String(name)); - // return(nullptr); - // } - // - // ssbo=new SSBO(name,program,index,level); - // - // ssbo_object.Add(name,ssbo); - // - // return ssbo; - // } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/Texture1D.cpp b/src/RenderDriver/Texture1D.cpp deleted file mode 100644 index b4d823ab..00000000 --- a/src/RenderDriver/Texture1D.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include -#include -#include - -namespace hgl -{ - namespace graph - { - bool Texture1D::SetImage(Texture1DData *ptr) - { - if (!ptr) - { - LOG_ERROR(OS_TEXT("param error,ptr=nullptr")); - RETURN_FALSE; - } - - if (!ptr->length) - { - LOG_ERROR(OS_TEXT("size error,image length=") + OSString(ptr->length)); - RETURN_FALSE; - } - - length = ptr->length; - - video_format = ptr->GetVideoFormat(); - pixel_format = ptr->GetPixelFormat(); - - if (!_SetImage(ptr)) - { - length=0; - RETURN_FALSE; - } - - return(true); - } - - int Texture1D::GetImage(void *data_pointer, TSF fmt, int level) - { - if (!TextureSourceFormatCheck(fmt)) - { - LOG_ERROR(OS_TEXT("glTexture1D::GetImage,fmt error =") + OSString(fmt)); - return(-1); - } - - return _GetImage(data_pointer,fmt,level); - } - - bool Texture1D::ChangeImage(uint s, uint l, void *data, uint bytes, TSF sf) - { - if (s >= length - || l>length - s - || !data - || !TextureSourceFormatCheck(sf)) - RETURN_FALSE; - - return _ChangeImage(s,l,data,bytes,sf); - } - }//namespace graph - - namespace graph - { - Texture1D *CreateTexture1DDSA(); - Texture1D *CreateTexture1DBind(); - - Texture1D *CreateTexture1D() - { -// if(IsSupportDSA()) - return CreateTexture1DDSA(); -// else -// return CreateTexture1DBind(); - } - - Texture1D *CreateTexture1D(Texture1DData *ptr) - { - Texture1D *tex=CreateTexture1D(); - - if(!tex)RETURN_ERROR_NULL; - - tex->SetImage(ptr); - return(tex); - } - - Texture1D *CreateTexture1D(uint length, TSF format) - { - Texture1D *tex = CreateTexture1D(); - - if (!tex)RETURN_ERROR_NULL; - - tex->SetImage(length,format); - return(tex); - } - - Texture1D *CreateTexture1D(uint length, void *bitmap, uint bitmap_bytes, TSF source_format, uint video_format) - { - Texture1D *tex = CreateTexture1D(); - - if (!tex)RETURN_ERROR_NULL; - - tex->SetImage(length, bitmap,bitmap_bytes,source_format, video_format); - return(tex); - } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/Texture1DDSA.cpp b/src/RenderDriver/Texture1DDSA.cpp deleted file mode 100644 index 2a1a61a4..00000000 --- a/src/RenderDriver/Texture1DDSA.cpp +++ /dev/null @@ -1,98 +0,0 @@ -#include -#include - -namespace hgl -{ - namespace graph - { - class Texture1DDSA:public Texture1D - { - public: - - using Texture1D::Texture1D; - - bool _SetImage(Texture1DData *tex) override - { - glTextureStorage1D(texture_id, 1, tex->video_format, tex->length); - - if(!tex->bitmap) - return(true); - - if(tex->source_format->compress) //原本就是压缩格式 - glCompressedTextureSubImage1D(texture_id, 0, 0, tex->length, tex->video_format, tex->bitmap_bytes, tex->bitmap); - else //正常非压缩格式 - glTextureSubImage1D(texture_id, 0, 0, tex->length, tex->source_format->pixel_format, tex->source_format->data_type, tex->bitmap); - - if(tex->gen_mipmaps) - { - glGenerateTextureMipmap(texture_id); - - // glTexEnvf(GL_TEXTURE_FILTER_CONTROL,GL_TEXTURE_LOD_BIAS,-1.5f); //设置LOD偏向,负是更精细,正是更模糊 - } - - return(true); - } - - int _GetImage(void *data_pointer, TSF fmt, int level) override - { - int compress; - int bytes; - - const TextureFormat *tsf = TextureFormatInfoList + fmt; - - glGetTextureLevelParameteriv(texture_id, level, GL_TEXTURE_COMPRESSED, &compress); - - if (compress) - { - glGetTextureLevelParameteriv(texture_id, level, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &bytes); - - if (data_pointer) - glGetCompressedTextureImage(texture_id, level, bytes, data_pointer); - } - else - { - if (tsf->video_bytes == 0)return(-1); - - bytes = length*tsf->video_bytes; - - if (data_pointer) - glGetTextureImage(texture_id, level, tsf->pixel_format, tsf->data_type, bytes, data_pointer); - } - - return(bytes); - } - - bool _ChangeImage(uint s, uint l, void *data, uint bytes, TSF sf) override - { - const TextureFormat *sfmt = TextureFormatInfoList + sf; //原始数据格式 - - if (sfmt->compress) - glCompressedTextureSubImage1D(texture_id, 0, s, l, sfmt->video_format, bytes, data); - else - glTextureSubImage1D(texture_id, 0, s, l, sfmt->pixel_format, sfmt->data_type, data); - - return(true); - } - - void GenMipmaps() override - { - glGenerateTextureMipmap(texture_id); - } - - void GetMipmapLevel(int &base_level,int &max_level) override - { - glGetTextureParameteriv(texture_id,GL_TEXTURE_BASE_LEVEL,&base_level); - glGetTextureParameteriv(texture_id,GL_TEXTURE_MAX_LEVEL,&max_level); - } - };//class Texture1DDSA:public Texture1D - - Texture1D *CreateTexture1DDSA() - { - uint id; - - glCreateTextures(GL_TEXTURE_1D,1,&id); - - return(new Texture1DDSA(id)); - } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/Texture2D.cpp b/src/RenderDriver/Texture2D.cpp deleted file mode 100644 index 37b0aa8e..00000000 --- a/src/RenderDriver/Texture2D.cpp +++ /dev/null @@ -1,126 +0,0 @@ -#include -#include -//#include - -namespace hgl -{ - namespace graph - { - bool Texture2D::SetImage(Texture2DData *ptr) - { - if (!ptr) - { - LOG_ERROR(OS_TEXT("param error,ptr=nullptr")); - RETURN_FALSE; - } - - if (!ptr->width || !ptr->height) - { - LOG_ERROR(OS_TEXT("size error,width=") + OSString(ptr->width) + OS_TEXT(",height=") + OSString(ptr->height)); - return(false); - } - - width = ptr->width; - height = ptr->height; - - video_format = ptr->GetVideoFormat(); - pixel_format = ptr->GetPixelFormat(); - - if (!_SetImage(ptr)) - { - width=height= 0; - RETURN_FALSE; - } - - return(true); - } - - int Texture2D::GetImage(void *data_pointer, TSF fmt, int level) - { - if (!TextureSourceFormatCheck(fmt)) - { - LOG_ERROR(OS_TEXT("glTexture2D::GetImage,fmt error =") + OSString(fmt)); - return(-1); - } - - return _GetImage(data_pointer,fmt,level,width,height); - } - - bool Texture2D::ChangeImage(uint l, uint t, uint w, uint h, void *data, uint bytes, TSF sf) - { - if (l>width || t>height - || w>width - l - || h>height - t - || !data - || !TextureSourceFormatCheck(sf)) - RETURN_FALSE; - - return _ChangeImage(l,t,w,h, data, bytes, sf); - } - }//namespace graph - - namespace graph - { - Texture2D *CreateTexture2DDSA(); - Texture2D *CreateTexture2DBind(); - - Texture2D *CreateTexture2D() - { - // if(GLEW_VERSION_4_5||GLEW_ARB_direct_state_access||GL_EXT_direct_state_access) - return CreateTexture2DDSA(); - // else - // return CreateTexture2DBind(); - } - - Texture2D *CreateTexture2D(Texture2DData *ptr) - { - Texture2D *tex = CreateTexture2D(); - - if (!tex)RETURN_ERROR_NULL; - - tex->SetImage(ptr); - return(tex); - } - - Texture2D *CreateTexture2D(uint width, uint height, TSF format) - { - Texture2D *tex = CreateTexture2D(); - - if (!tex)RETURN_ERROR_NULL; - - tex->SetImage(width,height,format); - return(tex); - } - - Texture2D *CreateTexture2D(uint width, uint height, void *bitmap, uint bitmap_bytes, TSF source_format, uint video_format) - { - Texture2D *tex = CreateTexture2D(); - - if (!tex)RETURN_ERROR_NULL; - - tex->SetImage(width,height, bitmap, bitmap_bytes, source_format, video_format); - return(tex); - } - -// Texture2D *CreateTexture2D(const OSString &filename,uint video_format) -// { -// Texture2D *tex = CreateTexture2D(); -// -// if (!tex)RETURN_ERROR_NULL; -// -// Bitmap2D bmp; -// -// if(!LoadBitmapFromFile(&bmp,filename)) -// RETURN_ERROR_NULL; -// -// tex->SetImage(bmp.GetWidth(), -// bmp.GetHeight(), -// bmp.GetData(), -// bmp.GetDataLength(), -// bmp.GetFormat(), -// video_format); -// -// return(tex); -// } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/Texture2DDSA.cpp b/src/RenderDriver/Texture2DDSA.cpp deleted file mode 100644 index fa074cb1..00000000 --- a/src/RenderDriver/Texture2DDSA.cpp +++ /dev/null @@ -1,98 +0,0 @@ -#include -#include - -namespace hgl -{ - namespace graph - { - class Texture2DDSA:public Texture2D - { - public: - - using Texture2D::Texture2D; - - bool _SetImage(Texture2DData *tex) override - { - glTextureStorage2D(texture_id, 1, tex->video_format, tex->width, tex->height); - - if(!tex->bitmap) - return(true); - - if(tex->source_format->compress) //原本就是压缩格式 - glCompressedTextureSubImage2D(texture_id, 0, 0, 0, tex->width, tex->height, tex->video_format, tex->bitmap_bytes, tex->bitmap); - else //正常非压缩格式 - glTextureSubImage2D(texture_id, 0, 0, 0, tex->width, tex->height, tex->source_format->pixel_format, tex->source_format->data_type, tex->bitmap); - - if(tex->gen_mipmaps) - { - glGenerateTextureMipmap(texture_id); - - // glTexEnvf(GL_TEXTURE_FILTER_CONTROL,GL_TEXTURE_LOD_BIAS,-1.5f); //设置LOD偏向,负是更精细,正是更模糊 - } - - return(true); - } - - int _GetImage(void *data_pointer, TSF fmt, int level,int width,int height) override - { - int compress; - int bytes; - - const TextureFormat *tsf = TextureFormatInfoList + fmt; - - glGetTextureLevelParameteriv(texture_id, level, GL_TEXTURE_COMPRESSED, &compress); - - if (compress) - { - glGetTextureLevelParameteriv(texture_id, level, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &bytes); - - if (data_pointer) - glGetCompressedTextureImage(texture_id, level, bytes, data_pointer); - } - else - { - if (tsf->video_bytes == 0)return(-1); - - bytes = width*height*tsf->video_bytes; - - if (data_pointer) - glGetTextureImage(texture_id, level, tsf->pixel_format, tsf->data_type, bytes, data_pointer); - } - - return(bytes); - } - - bool _ChangeImage(uint l, uint t, uint w, uint h, void *data, uint bytes, TSF sf) override - { - const TextureFormat *sfmt = TextureFormatInfoList + sf; //原始数据格式 - - if (sfmt->compress) - glCompressedTextureSubImage2D(texture_id, 0, l, t, w, h, sfmt->video_format, bytes, data); - else - glTextureSubImage2D(texture_id, 0, l, t, w, h, sfmt->pixel_format, sfmt->data_type, data); - - return(true); - } - - void GenMipmaps() override - { - glGenerateTextureMipmap(texture_id); - } - - void GetMipmapLevel(int &base_level,int &max_level) override - { - glGetTextureParameteriv(texture_id,GL_TEXTURE_BASE_LEVEL,&base_level); - glGetTextureParameteriv(texture_id,GL_TEXTURE_MAX_LEVEL,&max_level); - } - };//class Texture2DDSA - - Texture2D *CreateTexture2DDSA() - { - uint id; - - glCreateTextures(GL_TEXTURE_2D,1,&id); - - return(new Texture2DDSA(id)); - } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/TextureFormat.cpp b/src/RenderDriver/TextureFormat.cpp deleted file mode 100644 index b939f1fe..00000000 --- a/src/RenderDriver/TextureFormat.cpp +++ /dev/null @@ -1,137 +0,0 @@ -#include -namespace hgl -{ - namespace graph - { - //贴图数据源格式 - const TextureFormat TextureFormatInfoList[]= - { - {HGL_SF_NONE, "", false, 0, 0, GL_RGBA, GL_UNSIGNED_BYTE ,0,0}, - - {HGL_SF_R8, "R8", false, 0, GL_R8, GL_RED, GL_UNSIGNED_BYTE ,1,1}, - {HGL_SF_RG8, "RG8", false, 0, GL_RG8, GL_RG, GL_UNSIGNED_BYTE ,2,2}, - {HGL_SF_RGB8, "RGB8", false, 0, GL_RGB8, GL_RGB, GL_UNSIGNED_BYTE ,3,3}, - {HGL_SF_RGBA8, "RGBA8", false, 0, GL_RGBA8, GL_RGBA, GL_UNSIGNED_BYTE ,4,4}, - - {HGL_SF_SRGB8, "SRGB8", false, 0, GL_SRGB8, GL_SRGB, GL_UNSIGNED_BYTE ,4,4}, - {HGL_SF_SRGBA8, "SRGBA8", false, 0, GL_SRGB8_ALPHA8, GL_SRGB_ALPHA, GL_UNSIGNED_BYTE ,5,5}, - - {HGL_SF_R16, "R16", false, 0, GL_R16, GL_RED, GL_UNSIGNED_SHORT ,2,2}, - {HGL_SF_RG16, "RG16", false, 0, GL_RG16, GL_RG, GL_UNSIGNED_SHORT ,4,4}, - {HGL_SF_RGB16, "RGB16", false, 0, GL_RGB16, GL_RGB, GL_UNSIGNED_SHORT ,6,6}, - {HGL_SF_RGBA16, "RGBA16", false, 0, GL_RGBA16, GL_RGBA, GL_UNSIGNED_SHORT ,8,8}, - - {HGL_SF_R16F, "R16F", false, 0, GL_R16F, GL_RED, GL_FLOAT ,2,2}, - {HGL_SF_RG16F, "RG16F", false, 0, GL_RG16F, GL_RG, GL_FLOAT ,4,4}, - {HGL_SF_RGB16F, "RGB16F", false, 0, GL_RGB16F, GL_RGB, GL_FLOAT ,6,6}, - {HGL_SF_RGBA16F, "RGBA16F", false, 0, GL_RGBA16F, GL_RGBA, GL_FLOAT ,8,8}, - - {HGL_SF_R32F, "R32F", false, 0, GL_R32F, GL_RED, GL_FLOAT ,4,4}, - {HGL_SF_RG32F, "RG32F", false, 0, GL_RG32F, GL_RG, GL_FLOAT ,8,8}, - {HGL_SF_RGB32F, "RGB32F", false, 0, GL_RGB32F, GL_RGB, GL_FLOAT ,12,12}, - {HGL_SF_RGBA32F, "RGBA32F", false, 0, GL_RGBA32F, GL_RGBA, GL_FLOAT ,16,16}, - - {HGL_SF_UNCOMPRESSED, "", false, 0, 0, 0, 0 ,0,0}, - - {HGL_SF_R3_G3_B2, "R3_G3_B2", false, 0, GL_R3_G3_B2, GL_RGB, GL_UNSIGNED_BYTE_3_3_2 ,1,1}, - {HGL_SF_RGB565, "RGB565", false, 0, GL_RGB565, GL_RGB, GL_UNSIGNED_SHORT_5_6_5 ,2,2}, - - {HGL_SF_RGBA4, "RGBA4", false, 0, GL_RGBA4, GL_RGBA, GL_UNSIGNED_SHORT_4_4_4_4 ,2,2}, - {HGL_SF_RGB5_A1, "RGB5_A1", false, 0, GL_RGB5_A1, GL_RGBA, GL_UNSIGNED_SHORT_5_5_5_1 ,2,2}, - {HGL_SF_RGB10_A2, "RGB10_A2", false, 0, GL_RGB10_A2, GL_RGBA, GL_UNSIGNED_INT_10_10_10_2 ,4,4}, - - {HGL_SF_RG11F_B10F, "RG11F_B10F", false, 0, GL_R11F_G11F_B10F, GL_RGB, GL_UNSIGNED_INT_10F_11F_11F_REV ,4,4}, - {HGL_SF_RGB9_E5, "RGB9_E5", false, 0, GL_RGB9_E5, GL_RGB, GL_UNSIGNED_INT_5_9_9_9_REV ,4,4}, - - {HGL_SF_DEPTH, "", false, 0, 0, 0, 0 ,0,0}, - - {HGL_SF_DEPTH16, "DEPTH16", false, 0, GL_DEPTH_COMPONENT16, GL_DEPTH, GL_UNSIGNED_SHORT ,2,2}, - {HGL_SF_DEPTH24, "DEPTH24", false, 0, GL_DEPTH_COMPONENT24, GL_DEPTH, GL_UNSIGNED_BYTE ,3,3}, - {HGL_SF_DEPTH32, "DEPTH32", false, 0, GL_DEPTH_COMPONENT32, GL_DEPTH, GL_UNSIGNED_INT ,4,4}, - - {HGL_SF_DEPTH32F, "DEPTH32F", false, 0, GL_DEPTH_COMPONENT32F, GL_DEPTH, GL_FLOAT ,4,4}, - - {HGL_SF_INDEX, "", false, 0, 0, 0, 0 ,0,0}, - - {HGL_SF_INDEX_16_RGB, "16RGB", false, 16, GL_LUMINANCE4, GL_RGB, GL_UNSIGNED_BYTE ,0,0}, - {HGL_SF_INDEX_16_RGBA, "16RGBA", false, 16, GL_LUMINANCE4, GL_RGBA, GL_UNSIGNED_BYTE ,0,0}, - {HGL_SF_INDEX_256_RGB, "256RGB", false, 256,GL_LUMINANCE8, GL_RGB, GL_UNSIGNED_BYTE ,0,0}, - {HGL_SF_INDEX_256_RGBA, "256RGBA", false, 256,GL_LUMINANCE8, GL_RGBA, GL_UNSIGNED_BYTE ,0,0}, - - {HGL_SF_COMPRESSED, "", false, 0, 0, 0, 0 ,0,0}, -/* - {HGL_SF_CR, "CR", true, 0, GL_COMPRESSED_RED, GL_RED, 0,0,0}, //注:GL_COMPRESSED RED/RG/RGB/RGBA/SRGB/SRGBA这6个格式 - {HGL_SF_CRG, "CRG", true, 0, GL_COMPRESSED_RG, GL_RG, 0,0,0}, //只能用于glTexImage,由于显卡并不一定确定最终用什么算法, - {HGL_SF_CRGB, "CRGB", true, 0, GL_COMPRESSED_RGB, GL_RGB, 0,0,0}, //所以用glGetCompressTexImage取出的数据,不能在glCompressTexImage中用 - {HGL_SF_CRGBA, "CRGBA", true, 0, GL_COMPRESSED_RGBA, GL_RGBA, 0,0,0}, - - {HGL_SF_CSRGB, "CSRGB", true, 0, GL_COMPRESSED_SRGB, GL_SRGB, 0,0,0}, - {HGL_SF_CSRGBA, "CSRGBA", true, 0, GL_COMPRESSED_SRGB_ALPHA, GL_SRGB_ALPHA, 0,0,0}, -*/ - {HGL_SF_DXT1RGB, "DXT1RGB", true, 0, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_RGB, 0,0,0}, - {HGL_SF_DXT1RGBA, "DXT1RGBA", true, 0, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_RGBA, 0,0,0}, - {HGL_SF_DXT3RGBA, "DXT3RGBA", true, 0, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_RGBA, 0,0,0}, - {HGL_SF_DXT5RGBA, "DXT5RGBA", true, 0, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_RGBA, 0,0,0}, - - {HGL_SF_LATC1, "LATC1", true, 0, GL_COMPRESSED_LUMINANCE_LATC1_EXT, GL_RED, 0,0,0}, - {HGL_SF_LATC1s, "LATC1s", true, 0, GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT, GL_RED, 0,0,0}, - {HGL_SF_LATC2, "LATC2", true, 0, GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT, GL_RG, 0,0,0}, - {HGL_SF_LATC2s, "LATC2s", true, 0, GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT, GL_RG, 0,0,0}, - - {HGL_SF_RGTC1, "RGTC1", true, 0, GL_COMPRESSED_RED_RGTC1, GL_RED, 0,0,0}, - {HGL_SF_RGTC1s, "RGTC1s", true, 0, GL_COMPRESSED_SIGNED_RED_RGTC1, GL_RED, 0,0,0}, - {HGL_SF_RGTC2, "RGTC2", true, 0, GL_COMPRESSED_RG_RGTC2, GL_RG, 0,0,0}, - {HGL_SF_RGTC2s, "RGTC2s", true, 0, GL_COMPRESSED_SIGNED_RG_RGTC2, GL_RG, 0,0,0}, - - {HGL_SF_BPTC_RGBf, "BPTC_RGBf", true, 0, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT, GL_RGB, 0,0,0}, - {HGL_SF_BPTC_RGBuf, "BPTC_RGBuf", true, 0, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT, GL_RGB, 0,0,0}, - {HGL_SF_BPTC_RGBA, "BPTC_RGBA", true, 0, GL_COMPRESSED_RGBA_BPTC_UNORM, GL_RGBA, 0,0,0}, - {HGL_SF_BPTC_SRGBA, "BPTC_SRGBA", true, 0, GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM, GL_SRGB_ALPHA, 0,0,0}, - - {HGL_SF_ETC2_RGB8, "ETC2_RGB8", true, 0, GL_COMPRESSED_RGB8_ETC2, GL_RGB, 0,0,0}, - {HGL_SF_ETC2_SRGB8, "ETC2_SRGB8", true, 0, GL_COMPRESSED_SRGB8_ETC2, GL_SRGB, 0,0,0}, - {HGL_SF_ETC2_RGB8A1, "ETC2_RGB8A1", true, 0, GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_RGBA, 0,0,0}, - {HGL_SF_ETC2_SRGB8A1, "ETC2_SRGB8A1", true, 0, GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2, GL_SRGB_ALPHA, 0,0,0}, - {HGL_SF_ETC2_RGBA8, "ETC2_RGBA8", true, 0, GL_COMPRESSED_RGBA8_ETC2_EAC, GL_RGBA, 0,0,0}, - {HGL_SF_ETC2_SRGBA8, "ETC2_SRGBA8", true, 0, GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC, GL_SRGB_ALPHA, 0,0,0}, - - {HGL_SF_EAC_R11, "EAC_R11", true, 0, GL_COMPRESSED_R11_EAC, GL_RED, 0,0,0}, - {HGL_SF_EAC_R11s, "EAC_R11s", true, 0, GL_COMPRESSED_SIGNED_R11_EAC, GL_RED, 0,0,0}, - {HGL_SF_EAC_RG11, "EAC_RG11", true, 0, GL_COMPRESSED_RG11_EAC, GL_RG, 0,0,0}, - {HGL_SF_EAC_RG11s, "EAC_RG11s", true, 0, GL_COMPRESSED_SIGNED_RG11_EAC, GL_RG, 0,0,0} - };//const TextureFormat TextureFormatInfoList[] - - const int TextureFormatCount=sizeof(TextureFormatInfoList)/sizeof(TextureFormat); - - bool TextureSourceFormatCheck(const TextureSourceFormat &tsf) - { - if(tsf<=HGL_SF_NONE - ||tsf>=HGL_SF_END - ||tsf==HGL_SF_UNCOMPRESSED - ||tsf==HGL_SF_INDEX - ||tsf==HGL_SF_COMPRESSED) - return(false); - - return(true); - } - - bool TextureSourceFormatDepthCheck(const TextureSourceFormat &tsf) - { - return (tsf>HGL_SF_DEPTH&&tsf -#include - -namespace hgl -{ - namespace graph - { - namespace - { - static GLint HGL_MAX_VERTEX_ATTRIBS=0; - } - - int VertexArray::GetMaxVertexAttrib() - { - if(HGL_MAX_VERTEX_ATTRIBS<=0) - glGetIntegerv(GL_MAX_VERTEX_ATTRIBS,&HGL_MAX_VERTEX_ATTRIBS); - - return HGL_MAX_VERTEX_ATTRIBS; - } - - VertexArray::VertexArray() - { - vbo_list.PreMalloc(HGL_MAX_VERTEX_ATTRIBS); - - element_buffer=nullptr; - - glCreateVertexArrays(1,&vao); - } - - VertexArray::~VertexArray() - { - glDeleteVertexArrays(1,&vao); - } - - /** - * 添加一个顶点数据缓冲区 - * @param shader_location 这个缓冲区对应的SHADER地址 - * @param vb 数据缓冲区 - * @return 绑定点索引 - * @return -1 失败 - */ - int VertexArray::AddBuffer(int shader_location,ArrayBuffer *vb) - { - if(!vb)return(false); - if(vb->GetBufferType()!=GL_ARRAY_BUFFER)return(false); - - const int binding_index = vbo_list.GetCount(); //一个VAO中的绑定点,必须从0开始,而且必须紧密排列 - - glVertexArrayAttribBinding(vao, shader_location, binding_index); - - if(vb->GetDataType()==GL_INT ) glVertexArrayAttribIFormat( vao,shader_location,vb->GetComponent(),vb->GetDataType(),0);else - if(vb->GetDataType()==GL_DOUBLE ) glVertexArrayAttribLFormat( vao,shader_location,vb->GetComponent(),vb->GetDataType(),0);else - glVertexArrayAttribFormat( vao,shader_location,vb->GetComponent(),vb->GetDataType(),GL_FALSE,0); - - glEnableVertexArrayAttrib(vao,shader_location); - glVertexArrayVertexBuffer(vao,binding_index,vb->GetBufferIndex(),0,vb->GetStride()); - - vbo_list.Add(vb); - - return binding_index; - } - - /** - * 设置索引缓冲区 - */ - bool VertexArray::SetElement(ElementBuffer *eb) - { - if(!eb)return(false); - if(eb->GetBufferType()!=GL_ELEMENT_ARRAY_BUFFER)return(false); - element_buffer=eb; - - glVertexArrayElementBuffer(vao,eb->GetBufferIndex()); - return(true); - } - - /** - * 设置一个顶点缓冲区 - * @param shader_location 这个缓冲区对应的SHADER地址 - * @param vb 数据缓冲区 - */ - bool VertexArray::SetPosition(int shader_location,ArrayBuffer *vb) - { - if(!vb)return(false); - - if(!AddBuffer(shader_location,vb)<0) - return(false); - - position_buffer=vb; - return(true); - } - }//namespace graph -}//namespace hgl diff --git a/src/RenderDriver/VertexBufferObject.cpp b/src/RenderDriver/VertexBufferObject.cpp deleted file mode 100644 index eba67176..00000000 --- a/src/RenderDriver/VertexBufferObject.cpp +++ /dev/null @@ -1,47 +0,0 @@ -#include - -namespace hgl -{ - namespace graph - { - class VertexBufferObjectDSA:public VertexBufferObject - { - public: - - using VertexBufferObject::VertexBufferObject; - ~VertexBufferObjectDSA() - { - glDeleteBuffers(1,&buffer_index); - } - - void Update() override - { - glNamedBufferData(buffer_index,total_bytes,data,user_pattern); - } - - void Change(const GLsizeiptr start,const GLsizeiptr size) override - { - glNamedBufferSubData(buffer_index,start,size,((char *)data)+start); - } - - void Change(const GLsizeiptr start,const GLsizeiptr size,const void *new_data) override - { - glNamedBufferSubData(buffer_index,start,size,new_data); - } - };//class VertexBufferControlDSA - - VertexBufferObject *CreateVertexBufferObjectDSA(uint type) - { - uint index; - - glCreateBuffers(1,&index); - } - - VertexBufferObject *CreateVBO(const GLenum &buf_type, - const GLenum &dsup, - const uint &data_type,const uint &data_bytes,const uint &data_comp, - const GLsizeiptr &size) - { - } - }//namespace graph -}//namespace hgl