feat(渲染): 将渲染后端从OpenGL切换为Vulkan并添加相关依赖

- 更新xmake.lua配置,将渲染后端改为Vulkan
- 添加vulkan-memory-allocator依赖包
- 移除不必要的vulkan-1系统链接
- 新增渲染器接口头文件和Vulkan平台头文件
- 添加Hello World示例程序展示Vulkan渲染功能
This commit is contained in:
ChestnutYueyue 2026-02-21 19:10:57 +08:00
parent 23b573d4fe
commit 6195d57814
6 changed files with 34539 additions and 8 deletions

147
Examples/hello_world.cpp Normal file
View File

@ -0,0 +1,147 @@
/**
* @file hello_world.cpp
* @brief Hello World
*/
#include <extra2d/app/application.h>
#include <extra2d/platform/window_module.h>
#include <extra2d/core/service_locator.h>
#include <extra2d/services/logger_service.h>
#include <extra2d/render/renderer.h>
#include <extra2d/core/color.h>
#include <extra2d/core/math_types.h>
#include <iostream>
using namespace extra2d;
int main(int argc, char* argv[]) {
std::cout << "========================================" << std::endl;
std::cout << " Extra2D - Hello World Example" << std::endl;
std::cout << "========================================" << std::endl;
auto& app = Application::get();
app.appName = "Hello World - Extra2D";
app.appVersion = "1.0.0";
app.use<WindowModule>([](WindowCfg& cfg) {
cfg.title = "Hello World - Extra2D";
cfg.w = 1024;
cfg.h = 768;
cfg.vsync = true;
});
if (!app.init()) {
std::cerr << "Failed to initialize application" << std::endl;
return 1;
}
auto logger = ServiceLocator::instance().get<ILogger>();
if (logger) {
logger->info("Hello World example initialized");
}
auto renderer = IRenderer2D::create(true);
if (!renderer) {
std::cerr << "Failed to create renderer" << std::endl;
return 1;
}
auto window = app.window();
if (!window) {
std::cerr << "Failed to get window" << std::endl;
return 1;
}
if (!renderer->init(window->native())) {
std::cerr << "Failed to initialize renderer" << std::endl;
return 1;
}
if (logger) {
logger->info("Renderer: %s (Vulkan: %s)",
renderer->backendName(),
renderer->isVulkan() ? "yes" : "no");
}
float totalTime = 0.0f;
while (app.running() && !window->shouldClose()) {
float dt = app.dt();
totalTime += dt;
renderer->beginFrame();
i32 width = renderer->width();
i32 height = renderer->height();
Viewport viewport;
viewport.x = 0;
viewport.y = 0;
viewport.width = width;
viewport.height = height;
renderer->setViewport(viewport);
ClearCommand clearCmd;
clearCmd.color = Color(20, 20, 30, 255);
clearCmd.clearColor = true;
clearCmd.clearDepth = true;
renderer->clear(clearCmd);
float centerX = static_cast<float>(width) / 2.0f;
float centerY = static_cast<float>(height) / 2.0f;
float pulse = 0.5f + 0.5f * std::sin(totalTime * 2.0f);
Color textColor(
static_cast<u8>(100 + 155 * pulse),
static_cast<u8>(200 + 55 * pulse),
static_cast<u8>(255),
255
);
float rectWidth = 320.0f;
float rectHeight = 70.0f;
float rectX = centerX - rectWidth / 2;
float rectY = centerY - rectHeight / 2;
Color rectColor(50, 50, 70, 255);
renderer->drawRect(Vec2{rectX, rectY}, Vec2{rectWidth, rectHeight}, rectColor, true);
Color borderColor(
static_cast<u8>(100 + 100 * pulse),
static_cast<u8>(180 + 50 * pulse),
255,
255
);
renderer->drawRect(Vec2{rectX, rectY}, Vec2{rectWidth, rectHeight}, borderColor, false);
for (int i = 0; i < 5; ++i) {
float x = 100.0f + i * 200.0f;
float y = static_cast<float>(height) - 50.0f;
float radius = 20.0f;
float phase = totalTime * 1.5f + i * 0.5f;
float offsetY = std::sin(phase) * 20.0f;
Color circleColor(
static_cast<u8>(50 + i * 30),
static_cast<u8>(100 + i * 20),
static_cast<u8>(150 + i * 20),
200
);
renderer->drawCircle(Vec2{x, y + offsetY}, radius, circleColor, true, 16);
}
renderer->flushBatch();
renderer->endFrame();
renderer->present();
window->poll();
}
renderer->shutdown();
app.shutdown();
std::cout << "Application terminated successfully" << std::endl;
return 0;
}

View File

@ -0,0 +1,311 @@
#ifndef __khrplatform_h_
#define __khrplatform_h_
/*
** Copyright (c) 2008-2018 The Khronos Group Inc.
**
** Permission is hereby granted, free of charge, to any person obtaining a
** copy of this software and/or associated documentation files (the
** "Materials"), to deal in the Materials without restriction, including
** without limitation the rights to use, copy, modify, merge, publish,
** distribute, sublicense, and/or sell copies of the Materials, and to
** permit persons to whom the Materials are furnished to do so, subject to
** the following conditions:
**
** The above copyright notice and this permission notice shall be included
** in all copies or substantial portions of the Materials.
**
** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*/
/* Khronos platform-specific types and definitions.
*
* The master copy of khrplatform.h is maintained in the Khronos EGL
* Registry repository at https://github.com/KhronosGroup/EGL-Registry
* The last semantic modification to khrplatform.h was at commit ID:
* 67a3e0864c2d75ea5287b9f3d2eb74a745936692
*
* Adopters may modify this file to suit their platform. Adopters are
* encouraged to submit platform specific modifications to the Khronos
* group so that they can be included in future versions of this file.
* Please submit changes by filing pull requests or issues on
* the EGL Registry repository linked above.
*
*
* See the Implementer's Guidelines for information about where this file
* should be located on your system and for more details of its use:
* http://www.khronos.org/registry/implementers_guide.pdf
*
* This file should be included as
* #include <KHR/khrplatform.h>
* by Khronos client API header files that use its types and defines.
*
* The types in khrplatform.h should only be used to define API-specific types.
*
* Types defined in khrplatform.h:
* khronos_int8_t signed 8 bit
* khronos_uint8_t unsigned 8 bit
* khronos_int16_t signed 16 bit
* khronos_uint16_t unsigned 16 bit
* khronos_int32_t signed 32 bit
* khronos_uint32_t unsigned 32 bit
* khronos_int64_t signed 64 bit
* khronos_uint64_t unsigned 64 bit
* khronos_intptr_t signed same number of bits as a pointer
* khronos_uintptr_t unsigned same number of bits as a pointer
* khronos_ssize_t signed size
* khronos_usize_t unsigned size
* khronos_float_t signed 32 bit floating point
* khronos_time_ns_t unsigned 64 bit time in nanoseconds
* khronos_utime_nanoseconds_t unsigned time interval or absolute time in
* nanoseconds
* khronos_stime_nanoseconds_t signed time interval in nanoseconds
* khronos_boolean_enum_t enumerated boolean type. This should
* only be used as a base type when a client API's boolean type is
* an enum. Client APIs which use an integer or other type for
* booleans cannot use this as the base type for their boolean.
*
* Tokens defined in khrplatform.h:
*
* KHRONOS_FALSE, KHRONOS_TRUE Enumerated boolean false/true values.
*
* KHRONOS_SUPPORT_INT64 is 1 if 64 bit integers are supported; otherwise 0.
* KHRONOS_SUPPORT_FLOAT is 1 if floats are supported; otherwise 0.
*
* Calling convention macros defined in this file:
* KHRONOS_APICALL
* KHRONOS_APIENTRY
* KHRONOS_APIATTRIBUTES
*
* These may be used in function prototypes as:
*
* KHRONOS_APICALL void KHRONOS_APIENTRY funcname(
* int arg1,
* int arg2) KHRONOS_APIATTRIBUTES;
*/
#if defined(__SCITECH_SNAP__) && !defined(KHRONOS_STATIC)
# define KHRONOS_STATIC 1
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APICALL
*-------------------------------------------------------------------------
* This precedes the return type of the function in the function prototype.
*/
#if defined(KHRONOS_STATIC)
/* If the preprocessor constant KHRONOS_STATIC is defined, make the
* header compatible with static linking. */
# define KHRONOS_APICALL
#elif defined(_WIN32)
# define KHRONOS_APICALL __declspec(dllimport)
#elif defined (__SYMBIAN32__)
# define KHRONOS_APICALL IMPORT_C
#elif defined(__ANDROID__)
# define KHRONOS_APICALL __attribute__((visibility("default")))
#else
# define KHRONOS_APICALL
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIENTRY
*-------------------------------------------------------------------------
* This follows the return type of the function and precedes the function
* name in the function prototype.
*/
#if defined(_WIN32) && !defined(_WIN32_WCE) && !defined(__SCITECH_SNAP__)
/* Win32 but not WinCE */
# define KHRONOS_APIENTRY __stdcall
#else
# define KHRONOS_APIENTRY
#endif
/*-------------------------------------------------------------------------
* Definition of KHRONOS_APIATTRIBUTES
*-------------------------------------------------------------------------
* This follows the closing parenthesis of the function prototype arguments.
*/
#if defined (__ARMCC_2__)
#define KHRONOS_APIATTRIBUTES __softfp
#else
#define KHRONOS_APIATTRIBUTES
#endif
/*-------------------------------------------------------------------------
* basic type definitions
*-----------------------------------------------------------------------*/
#if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || defined(__GNUC__) || defined(__SCO__) || defined(__USLC__)
/*
* Using <stdint.h>
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
/*
* To support platform where unsigned long cannot be used interchangeably with
* inptr_t (e.g. CHERI-extended ISAs), we can use the stdint.h intptr_t.
* Ideally, we could just use (u)intptr_t everywhere, but this could result in
* ABI breakage if khronos_uintptr_t is changed from unsigned long to
* unsigned long long or similar (this results in different C++ name mangling).
* To avoid changes for existing platforms, we restrict usage of intptr_t to
* platforms where the size of a pointer is larger than the size of long.
*/
#if defined(__SIZEOF_LONG__) && defined(__SIZEOF_POINTER__)
#if __SIZEOF_POINTER__ > __SIZEOF_LONG__
#define KHRONOS_USE_INTPTR_T
#endif
#endif
#elif defined(__VMS ) || defined(__sgi)
/*
* Using <inttypes.h>
*/
#include <inttypes.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(_WIN32) && !defined(__SCITECH_SNAP__)
/*
* Win32
*/
typedef __int32 khronos_int32_t;
typedef unsigned __int32 khronos_uint32_t;
typedef __int64 khronos_int64_t;
typedef unsigned __int64 khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif defined(__sun__) || defined(__digital__)
/*
* Sun or Digital
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#if defined(__arch64__) || defined(_LP64)
typedef long int khronos_int64_t;
typedef unsigned long int khronos_uint64_t;
#else
typedef long long int khronos_int64_t;
typedef unsigned long long int khronos_uint64_t;
#endif /* __arch64__ */
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#elif 0
/*
* Hypothetical platform with no float or int64 support
*/
typedef int khronos_int32_t;
typedef unsigned int khronos_uint32_t;
#define KHRONOS_SUPPORT_INT64 0
#define KHRONOS_SUPPORT_FLOAT 0
#else
/*
* Generic fallback
*/
#include <stdint.h>
typedef int32_t khronos_int32_t;
typedef uint32_t khronos_uint32_t;
typedef int64_t khronos_int64_t;
typedef uint64_t khronos_uint64_t;
#define KHRONOS_SUPPORT_INT64 1
#define KHRONOS_SUPPORT_FLOAT 1
#endif
/*
* Types that are (so far) the same on all platforms
*/
typedef signed char khronos_int8_t;
typedef unsigned char khronos_uint8_t;
typedef signed short int khronos_int16_t;
typedef unsigned short int khronos_uint16_t;
/*
* Types that differ between LLP64 and LP64 architectures - in LLP64,
* pointers are 64 bits, but 'long' is still 32 bits. Win64 appears
* to be the only LLP64 architecture in current use.
*/
#ifdef KHRONOS_USE_INTPTR_T
typedef intptr_t khronos_intptr_t;
typedef uintptr_t khronos_uintptr_t;
#elif defined(_WIN64)
typedef signed long long int khronos_intptr_t;
typedef unsigned long long int khronos_uintptr_t;
#else
typedef signed long int khronos_intptr_t;
typedef unsigned long int khronos_uintptr_t;
#endif
#if defined(_WIN64)
typedef signed long long int khronos_ssize_t;
typedef unsigned long long int khronos_usize_t;
#else
typedef signed long int khronos_ssize_t;
typedef unsigned long int khronos_usize_t;
#endif
#if KHRONOS_SUPPORT_FLOAT
/*
* Float type
*/
typedef float khronos_float_t;
#endif
#if KHRONOS_SUPPORT_INT64
/* Time types
*
* These types can be used to represent a time interval in nanoseconds or
* an absolute Unadjusted System Time. Unadjusted System Time is the number
* of nanoseconds since some arbitrary system event (e.g. since the last
* time the system booted). The Unadjusted System Time is an unsigned
* 64 bit value that wraps back to 0 every 584 years. Time intervals
* may be either signed or unsigned.
*/
typedef khronos_uint64_t khronos_utime_nanoseconds_t;
typedef khronos_int64_t khronos_stime_nanoseconds_t;
#endif
/*
* Dummy value used to pad enum types to 32 bits.
*/
#ifndef KHRONOS_MAX_ENUM
#define KHRONOS_MAX_ENUM 0x7FFFFFFF
#endif
/*
* Enumerated boolean type
*
* Values other than zero should be considered to be true. Therefore
* comparisons should not be made against KHRONOS_TRUE.
*/
typedef enum {
KHRONOS_FALSE = 0,
KHRONOS_TRUE = 1,
KHRONOS_BOOLEAN_ENUM_FORCE_SIZE = KHRONOS_MAX_ENUM
} khronos_boolean_enum_t;
#endif /* __khrplatform_h_ */

View File

@ -0,0 +1,130 @@
#pragma once
#include <extra2d/core/types.h>
#include <extra2d/core/math_types.h>
#include <extra2d/core/color.h>
#include <extra2d/render/render_types.h>
#include <extra2d/render/texture.h>
#include <extra2d/render/shader.h>
#include <extra2d/render/batch.h>
#include <memory>
#include <string>
#include <vector>
namespace extra2d {
class Camera2D;
class TextureAsset;
class FontAsset;
class SceneNode;
using RendererRef = Ref<class IRenderer2D>;
class IRenderer2D {
public:
virtual ~IRenderer2D() = default;
virtual bool init(void* nativeWindow) = 0;
virtual void shutdown() = 0;
virtual void resize(i32 width, i32 height) = 0;
virtual void beginFrame() = 0;
virtual void endFrame() = 0;
virtual void present() = 0;
virtual void setViewport(const Viewport& viewport) = 0;
virtual void setScissor(const Scissor& scissor) = 0;
virtual void clear(const ClearCommand& cmd) = 0;
virtual void setCamera(const Camera2D* camera) = 0;
virtual void resetCamera() = 0;
virtual void setBlendMode(BlendMode mode) = 0;
virtual void setRenderState(const RenderState& state) = 0;
virtual TextureRef createTexture(const TextureDesc& desc) = 0;
virtual TextureRef createTextureFromAsset(Ref<TextureAsset> asset) = 0;
virtual void destroyTexture(TextureRef texture) = 0;
virtual Ref<ITextureArray> createTextureArray(i32 width, i32 height,
u32 maxLayers,
TextureFormat format) = 0;
virtual ShaderRef createShader(const std::string& vertexSrc,
const std::string& fragmentSrc) = 0;
virtual void destroyShader(ShaderRef shader) = 0;
virtual void drawSprite(TextureRef texture,
const Vec2& position,
const Vec2& size,
const Vec2& scale,
float rotation,
const Vec2& anchor,
const TextureRegion& region,
const Color& tint,
float opacity) = 0;
virtual void drawSpriteBatch(const std::vector<SpriteVertex>& vertices,
const std::vector<u32>& indices,
TextureRef texture) = 0;
virtual void drawText(Ref<FontAsset> font,
const std::string& text,
const Vec2& position,
float fontSize,
const Color& color,
float opacity) = 0;
virtual void drawRect(const Rect& rect, const Color& color, bool filled) = 0;
virtual void drawRect(const Vec2& position, const Vec2& size,
const Color& color, bool filled) = 0;
virtual void drawCircle(const Vec2& center, float radius,
const Color& color, bool filled,
u32 segments = 32) = 0;
virtual void drawLine(const Vec2& start, const Vec2& end,
const Color& color, float thickness = 1.0f) = 0;
virtual void drawLines(const std::vector<Vec2>& points,
const Color& color,
float thickness = 1.0f) = 0;
virtual void drawPolygon(const std::vector<Vec2>& points,
const Color& color,
bool filled) = 0;
virtual void drawShapeBatch(const std::vector<ShapeVertex>& vertices,
const std::vector<u32>& indices,
PrimitiveType primitive) = 0;
virtual void flushBatch() = 0;
virtual i32 width() const = 0;
virtual i32 height() const = 0;
virtual bool isVulkan() const = 0;
virtual const char* backendName() const = 0;
static RendererRef create(bool preferVulkan = true);
};
struct RenderStats {
u32 drawCalls = 0;
u32 quadCount = 0;
u32 vertexCount = 0;
u32 indexCount = 0;
u32 textureSwitches = 0;
u32 shaderSwitches = 0;
void reset() {
drawCalls = 0;
quadCount = 0;
vertexCount = 0;
indexCount = 0;
textureSwitches = 0;
shaderSwitches = 0;
}
};
}

21074
Extra2D/include/glad/glad.h Normal file

File diff suppressed because one or more lines are too long

12868
Extra2D/src/glad/glad.c Normal file

File diff suppressed because one or more lines are too long

View File

@ -3,7 +3,7 @@
-- Build System: Xmake -- Build System: Xmake
-- --
-- 窗口后端: GLFW -- 窗口后端: GLFW
-- 渲染后端: OpenGL -- 渲染后端: Vulkan
-- ============================================== -- ==============================================
-- 项目元信息 -- 项目元信息
@ -32,7 +32,7 @@ option_end()
-- 添加依赖包 -- 添加依赖包
-- ============================================== -- ==============================================
add_requires("glm", "nlohmann_json", "glfw", "zstd", "lz4", "zlib", "vulkan-headers", "vulkan-loader") add_requires("glm", "nlohmann_json", "glfw", "zstd", "lz4", "zlib", "vulkan-headers", "vulkan-loader", "vulkan-memory-allocator")
-- ============================================== -- ==============================================
-- 引擎库目标 -- 引擎库目标
@ -52,10 +52,10 @@ target("extra2d")
add_includedirs("Extra2D/include/extra2d/platform", {public = true}) add_includedirs("Extra2D/include/extra2d/platform", {public = true})
-- 依赖包 -- 依赖包
add_packages("glm", "nlohmann_json", "glfw", "zstd", "lz4", "zlib", "vulkan-headers", "vulkan-loader", {public = true}) add_packages("glm", "nlohmann_json", "glfw", "zstd", "lz4", "zlib", "vulkan-headers", "vulkan-loader", "vulkan-memory-allocator", {public = true})
-- 系统库链接 -- 系统库链接
add_syslinks("winmm", "imm32", "version", "setupapi", "vulkan-1", {public = true}) add_syslinks("winmm", "imm32", "version", "setupapi", {public = true})
-- 启用压缩库 -- 启用压缩库
add_defines("E2D_USE_ZSTD", "E2D_USE_LZ4", "E2D_USE_ZLIB", {public = true}) add_defines("E2D_USE_ZSTD", "E2D_USE_LZ4", "E2D_USE_ZLIB", {public = true})
@ -97,8 +97,8 @@ target("extra2d_tests")
add_deps("extra2d") add_deps("extra2d")
-- 依赖包 -- 依赖包
add_packages("glm", "nlohmann_json", "glfw", "zstd", "lz4", "zlib", "vulkan-headers", "vulkan-loader") add_packages("glm", "nlohmann_json", "glfw", "zstd", "lz4", "zlib")
add_syslinks("winmm", "imm32", "version", "setupapi", "vulkan-1") add_syslinks("winmm", "imm32", "version", "setupapi")
-- 编译器标志 (MSVC) -- 编译器标志 (MSVC)
add_cxflags("/W4", {force = true}) add_cxflags("/W4", {force = true})
@ -131,8 +131,8 @@ target("asset_packer")
add_deps("extra2d") add_deps("extra2d")
-- 依赖包 -- 依赖包
add_packages("glm", "nlohmann_json", "glfw", "zstd", "lz4", "zlib", "vulkan-headers", "vulkan-loader") add_packages("glm", "nlohmann_json", "glfw", "zstd", "lz4", "zlib")
add_syslinks("winmm", "imm32", "version", "setupapi", "vulkan-1") add_syslinks("winmm", "imm32", "version", "setupapi")
-- 编译器标志 (MSVC) -- 编译器标志 (MSVC)
add_cxflags("/W4", {force = true}) add_cxflags("/W4", {force = true})
@ -146,3 +146,4 @@ target("asset_packer")
add_cxflags("/O2", {force = true}) add_cxflags("/O2", {force = true})
end end
target_end() target_end()