A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat: Add unified shader loading system (.esshader format)
esenginee2623ede955f
diff --git a/CMakeLists.txt b/CMakeLists.txtindex 1fd9f012f..844c49bda 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -39,6 +39,8 @@ set(ESENGINE_SOURCESsrc/esengine/core/Engine.cppsrc/esengine/core/Log.cppsrc/esengine/resource/ResourceManager.cpp+ src/esengine/resource/ShaderParser.cpp+ src/esengine/resource/loaders/ShaderLoader.cppsrc/esengine/renderer/RenderContext.cppsrc/esengine/renderer/Renderer.cppsrc/esengine/renderer/Shader.cppdiff --git a/assets/shaders/axis.esshader b/assets/shaders/axis.esshadernew file mode 100644index 000000000..e4d1e18de--- /dev/null+++ b/assets/shaders/axis.esshader@@ -0,0 +1,25 @@+#pragma shader "Axis"++#pragma vertex+attribute vec3 a_position;+attribute vec4 a_color;++uniform mat4 u_viewProj;++varying vec4 v_color;++void main() {+ gl_Position = u_viewProj * vec4(a_position, 1.0);+ v_color = a_color;+}+#pragma end++#pragma fragment+precision mediump float;++varying vec4 v_color;++void main() {+ gl_FragColor = v_color;+}+#pragma enddiff --git a/assets/shaders/grid.esshader b/assets/shaders/grid.esshadernew file mode 100644index 000000000..b97efd9e5--- /dev/null+++ b/assets/shaders/grid.esshader@@ -0,0 +1,21 @@+#pragma shader "Grid"++#pragma vertex+attribute vec3 a_position;++uniform mat4 u_viewProj;++void main() {+ gl_Position = u_viewProj * vec4(a_position, 1.0);+}+#pragma end++#pragma fragment+precision mediump float;++uniform vec4 u_color;++void main() {+ gl_FragColor = u_color;+}+#pragma enddiff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cppindex 7ccb4b2bf..200c043c9 100644--- a/src/esengine/resource/ResourceManager.cpp+++ b/src/esengine/resource/ResourceManager.cpp@@ -10,6 +10,7 @@*/#include "ResourceManager.hpp"+#include "loaders/ShaderLoader.hpp"#include "../core/Log.hpp"#include "../renderer/Shader.hpp"#include "../renderer/Texture.hpp"@@ -82,6 +83,25 @@ ShaderHandle ResourceManager::loadShader(const std::string& vertPath, const std:return shaders_.add(std::move(shader), cacheKey);}+ShaderHandle ResourceManager::loadUnifiedShader(const std::string& path, const std::string& platform) {+ auto cached = shaders_.findByPath(path);+ if (cached.isValid()) {+ shaders_.addRef(cached);+ stats_.cacheHits++;+ return cached;+ }++ ShaderLoader loader;+ auto result = loader.loadFromFile(path, platform);+ if (!result.isOk()) {+ stats_.cacheMisses++;+ return ShaderHandle();+ }++ stats_.cacheMisses++;+ return shaders_.add(std::move(result.shader), path);+}+Shader* ResourceManager::getShader(ShaderHandle handle) {return shaders_.get(handle);}diff --git a/src/esengine/resource/ResourceManager.hpp b/src/esengine/resource/ResourceManager.hppindex 86902fefd..97c8f363b 100644--- a/src/esengine/resource/ResourceManager.hpp+++ b/src/esengine/resource/ResourceManager.hpp@@ -124,6 +124,14 @@ public:*/ShaderHandle loadShader(const std::string& vertPath, const std::string& fragPath);+ /**+ * @brief Loads a unified shader from .esshader file (with caching)+ * @param path Path to the .esshader file+ * @param platform Platform variant (empty for auto-detect)+ * @return Handle to the shader, or invalid handle on failure+ */+ ShaderHandle loadUnifiedShader(const std::string& path, const std::string& platform = "");+/*** @brief Gets a shader by handle* @param handle The shader handlediff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppnew file mode 100644index 000000000..e354c3607--- /dev/null+++ b/src/esengine/resource/ShaderParser.cpp@@ -0,0 +1,326 @@+/**+ * @file ShaderParser.cpp+ * @brief Parser for unified .esshader file format+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */++#include "ShaderParser.hpp"+#include "../core/Log.hpp"++#include <sstream>+#include <algorithm>+#include <regex>++namespace esengine::resource {++// =============================================================================+// Parser State+// =============================================================================++enum class ParseState {+ Global,+ Properties,+ Vertex,+ Fragment,+ Variant+};++// =============================================================================+// Public Methods+// =============================================================================++ParsedShader ShaderParser::parse(const std::string& source) {+ ParsedShader result;+ result.valid = false;++ if (source.empty()) {+ result.errorMessage = "Empty shader source";+ return result;+ }++ std::istringstream stream(source);+ std::string line;+ ParseState state = ParseState::Global;+ std::string currentVariantName;+ std::ostringstream currentSection;+ u32 lineNumber = 0;++ while (std::getline(stream, line)) {+ lineNumber++;+ std::string directive, argument;+ parseDirective(line, directive, argument);++ if (directive == "shader") {+ if (argument.size() >= 2 && argument.front() == '"' && argument.back() == '"') {+ result.name = argument.substr(1, argument.size() - 2);+ } else {+ result.name = argument;+ }+ continue;+ }++ if (directive == "version") {+ result.version = argument;+ continue;+ }++ if (directive == "properties") {+ if (state != ParseState::Global) {+ result.errorMessage = "Unexpected #pragma properties at line " + std::to_string(lineNumber);+ return result;+ }+ state = ParseState::Properties;+ continue;+ }++ if (directive == "vertex") {+ if (state != ParseState::Global) {+ result.errorMessage = "Unexpected #pragma vertex at line " + std::to_string(lineNumber);+ return result;+ }+ state = ParseState::Vertex;+ currentSection.str("");+ currentSection.clear();+ continue;+ }++ if (directive == "fragment") {+ if (state != ParseState::Global) {+ result.errorMessage = "Unexpected #pragma fragment at line " + std::to_string(lineNumber);+ return result;+ }+ state = ParseState::Fragment;+ currentSection.str("");+ currentSection.clear();+ continue;+ }++ if (directive == "variant") {+ if (state != ParseState::Global) {+ result.errorMessage = "Unexpected #pragma variant at line " + std::to_string(lineNumber);+ return result;+ }+ state = ParseState::Variant;+ currentVariantName = argument;+ currentSection.str("");+ currentSection.clear();+ continue;+ }++ if (directive == "end") {+ switch (state) {+ case ParseState::Properties:+ break;+ case ParseState::Vertex:+ result.stages[ShaderStage::Vertex] = currentSection.str();+ break;+ case ParseState::Fragment:+ result.stages[ShaderStage::Fragment] = currentSection.str();+ break;+ case ParseState::Variant:+ result.variants[currentVariantName] = currentSection.str();+ currentVariantName.clear();+ break;+ default:+ break;+ }+ state = ParseState::Global;+ continue;+ }++ switch (state) {+ case ParseState::Global:+ if (!trim(line).empty() && line[0] != '/' && trim(line).substr(0, 2) != "//") {+ result.sharedCode += line + "\n";+ }+ break;++ case ParseState::Properties: {+ std::string trimmedLine = trim(line);+ if (!trimmedLine.empty() && trimmedLine.find("uniform") != std::string::npos) {+ ShaderProperty prop = parsePropertyAnnotation(line);+ if (!prop.name.empty()) {+ result.properties.push_back(prop);+ }+ }+ break;+ }++ case ParseState::Vertex:+ case ParseState::Fragment:+ case ParseState::Variant:+ currentSection << line << "\n";+ break;+ }+ }++ if (state != ParseState::Global) {+ result.errorMessage = "Unexpected end of file - missing #pragma end";+ return result;+ }++ if (result.stages.find(ShaderStage::Vertex) == result.stages.end()) {+ result.errorMessage = "Missing vertex shader stage";+ return result;+ }++ if (result.stages.find(ShaderStage::Fragment) == result.stages.end()) {+ result.errorMessage = "Missing fragment shader stage";+ return result;+ }++ result.valid = true;+ return result;+}++std::string ShaderParser::assembleStage(const ParsedShader& parsed,+ ShaderStage stage,+ const std::string& platform) {+ if (!parsed.valid) {+ return "";+ }++ auto stageIt = parsed.stages.find(stage);+ if (stageIt == parsed.stages.end()) {+ return "";+ }++ std::ostringstream assembled;++ if (!parsed.version.empty()) {+ assembled << "#version " << parsed.version << "\n";+ }++ if (!platform.empty()) {+ auto variantIt = parsed.variants.find(platform);+ if (variantIt != parsed.variants.end()) {+ assembled << variantIt->second;+ }+ }++ if (!parsed.sharedCode.empty()) {+ assembled << parsed.sharedCode;+ }++ assembled << stageIt->second;++ return assembled.str();+}++// =============================================================================+// Private Methods+// =============================================================================++void ShaderParser::parseDirective(const std::string& line,+ std::string& directive,+ std::string& argument) {+ directive.clear();+ argument.clear();++ std::string trimmedLine = trim(line);+ if (trimmedLine.substr(0, 7) != "#pragma") {+ return;+ }++ std::string rest = trim(trimmedLine.substr(7));+ if (rest.empty()) {+ return;+ }++ usize spacePos = rest.find_first_of(" \t");+ if (spacePos == std::string::npos) {+ directive = rest;+ } else {+ directive = rest.substr(0, spacePos);+ argument = trim(rest.substr(spacePos + 1));+ }+}++ShaderProperty ShaderParser::parsePropertyAnnotation(const std::string& line) {+ ShaderProperty prop;++ std::regex uniformRegex(R"(uniform\s+(\w+)\s+(\w+)\s*;)");+ std::smatch match;+ if (!std::regex_search(line, match, uniformRegex)) {+ return prop;+ }++ std::string glslType = match[1].str();+ prop.name = match[2].str();++ if (glslType == "float") {+ prop.type = ShaderPropertyType::Float;+ } else if (glslType == "vec2") {+ prop.type = ShaderPropertyType::Vec2;+ } else if (glslType == "vec3") {+ prop.type = ShaderPropertyType::Vec3;+ } else if (glslType == "vec4") {+ prop.type = ShaderPropertyType::Vec4;+ } else if (glslType == "int") {+ prop.type = ShaderPropertyType::Int;+ } else if (glslType == "sampler2D") {+ prop.type = ShaderPropertyType::Texture;+ } else {+ prop.type = ShaderPropertyType::Unknown;+ }++ std::regex annotationRegex(R"(@property\s*\(([^)]*)\))");+ if (std::regex_search(line, match, annotationRegex)) {+ std::string params = match[1].str();++ std::regex typeRegex(R"(type\s*=\s*(\w+))");+ if (std::regex_search(params, match, typeRegex)) {+ prop.type = stringToPropertyType(match[1].str());+ }++ std::regex defaultRegex(R"(default\s*=\s*([^,)]+))");+ if (std::regex_search(params, match, defaultRegex)) {+ prop.defaultValue = trim(match[1].str());+ }++ std::regex nameRegex(R"regex(name\s*=\s*"([^"]+)")regex");+ if (std::regex_search(params, match, nameRegex)) {+ prop.displayName = match[1].str();+ }+ }++ if (prop.displayName.empty()) {+ prop.displayName = prop.name;+ if (prop.displayName.substr(0, 2) == "u_") {+ prop.displayName = prop.displayName.substr(2);+ }+ if (!prop.displayName.empty()) {+ prop.displayName[0] = static_cast<char>(std::toupper(prop.displayName[0]));+ }+ }++ return prop;+}++ShaderPropertyType ShaderParser::stringToPropertyType(const std::string& typeStr) {+ if (typeStr == "float") return ShaderPropertyType::Float;+ if (typeStr == "vec2") return ShaderPropertyType::Vec2;+ if (typeStr == "vec3") return ShaderPropertyType::Vec3;+ if (typeStr == "vec4") return ShaderPropertyType::Vec4;+ if (typeStr == "color") return ShaderPropertyType::Color;+ if (typeStr == "int") return ShaderPropertyType::Int;+ if (typeStr == "texture") return ShaderPropertyType::Texture;+ return ShaderPropertyType::Unknown;+}++std::string ShaderParser::trim(const std::string& str) {+ const char* whitespace = " \t\r\n";+ usize start = str.find_first_not_of(whitespace);+ if (start == std::string::npos) {+ return "";+ }+ usize end = str.find_last_not_of(whitespace);+ return str.substr(start, end - start + 1);+}++} // namespace esengine::resourcediff --git a/src/esengine/resource/ShaderParser.hpp b/src/esengine/resource/ShaderParser.hppnew file mode 100644index 000000000..2ceab7be2--- /dev/null+++ b/src/esengine/resource/ShaderParser.hpp@@ -0,0 +1,139 @@+/**+ * @file ShaderParser.hpp+ * @brief Parser for unified .esshader file format+ * @details Parses single-file shader format containing multiple stages+ * (vertex, fragment) with optional properties and platform variants.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "../core/Types.hpp"++#include <string>+#include <vector>+#include <unordered_map>++namespace esengine::resource {++// =============================================================================+// Shader Stage Enum+// =============================================================================++enum class ShaderStage : u8 {+ Vertex,+ Fragment+};++// =============================================================================+// Shader Property+// =============================================================================++enum class ShaderPropertyType : u8 {+ Float,+ Vec2,+ Vec3,+ Vec4,+ Color,+ Int,+ Texture,+ Unknown+};++struct ShaderProperty {+ std::string name; ///< Uniform name+ ShaderPropertyType type; ///< Property type+ std::string defaultValue; ///< Default value as string+ std::string displayName; ///< Display name for editor+};++// =============================================================================+// Parsed Shader+// =============================================================================++/**+ * @brief Result of parsing an .esshader file+ *+ * @details Contains all extracted information from a unified shader file+ * including stages, properties, and platform variants.+ */+struct ParsedShader {+ std::string name; ///< Shader name+ std::string version; ///< GLSL version+ std::string sharedCode; ///< Code shared by all stages+ std::unordered_map<ShaderStage, std::string> stages; ///< Stage source code+ std::unordered_map<std::string, std::string> variants; ///< Platform variants+ std::vector<ShaderProperty> properties; ///< Exposed properties+ std::string errorMessage; ///< Parse error if any+ bool valid = false; ///< True if parsing succeeded+};++// =============================================================================+// ShaderParser Class+// =============================================================================++/**+ * @brief Parser for .esshader unified shader format+ *+ * @details Parses shader files that contain multiple stages in a single file.+ * Uses #pragma directives to separate sections.+ *+ * File format:+ * @code+ * #pragma shader "MyShader"+ * #pragma version 300 es+ *+ * #pragma properties+ * uniform sampler2D u_texture; // @property(type=texture)+ * #pragma end+ *+ * #pragma vertex+ * // vertex shader code+ * #pragma end+ *+ * #pragma fragment+ * // fragment shader code+ * #pragma end+ * @endcode+ */+class ShaderParser {+public:+ /**+ * @brief Parses shader source into structured format+ * @param source The complete .esshader file content+ * @return Parsed shader data with valid flag indicating success+ */+ static ParsedShader parse(const std::string& source);++ /**+ * @brief Assembles final GLSL source for a specific stage+ * @param parsed The parsed shader data+ * @param stage The shader stage to assemble+ * @param platform Platform variant name (empty for default)+ * @return Complete GLSL source ready for compilation+ */+ static std::string assembleStage(const ParsedShader& parsed,+ ShaderStage stage,+ const std::string& platform = "");++private:+ static void parseDirective(const std::string& line,+ std::string& directive,+ std::string& argument);++ static ShaderProperty parsePropertyAnnotation(const std::string& line);++ static ShaderPropertyType stringToPropertyType(const std::string& typeStr);++ static std::string trim(const std::string& str);+};++} // namespace esengine::resourcediff --git a/src/esengine/resource/loaders/ShaderLoader.cpp b/src/esengine/resource/loaders/ShaderLoader.cppnew file mode 100644index 000000000..e2927b70b--- /dev/null+++ b/src/esengine/resource/loaders/ShaderLoader.cpp@@ -0,0 +1,114 @@+/**+ * @file ShaderLoader.cpp+ * @brief Shader resource loader implementation+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */++#include "ShaderLoader.hpp"+#include "../../platform/FileSystem.hpp"+#include "../../core/Log.hpp"++#include <algorithm>++namespace esengine::resource {++// =============================================================================+// Public Methods+// =============================================================================++ShaderLoadResult ShaderLoader::loadFromFile(const std::string& path,+ const std::string& platform) {+ ShaderLoadResult result;++ if (!FileSystem::fileExists(path)) {+ result.errorMessage = "Shader file not found: " + path;+ ES_LOG_ERROR("ShaderLoader: {}", result.errorMessage);+ return result;+ }++ std::string source = FileSystem::readTextFile(path);+ if (source.empty()) {+ result.errorMessage = "Failed to read shader file: " + path;+ ES_LOG_ERROR("ShaderLoader: {}", result.errorMessage);+ return result;+ }++ result = loadFromSource(source, platform);+ result.dependencies.push_back(path);++ if (result.isOk()) {+ ES_LOG_DEBUG("ShaderLoader: Loaded shader from {}", path);+ }++ return result;+}++ShaderLoadResult ShaderLoader::loadFromSource(const std::string& source,+ const std::string& platform) {+ ShaderLoadResult result;++ ParsedShader parsed = ShaderParser::parse(source);+ if (!parsed.valid) {+ result.errorMessage = "Shader parse error: " + parsed.errorMessage;+ ES_LOG_ERROR("ShaderLoader: {}", result.errorMessage);+ return result;+ }++ std::string effectivePlatform = platform.empty() ? getDefaultPlatform() : platform;++ std::string vertexSrc = ShaderParser::assembleStage(parsed, ShaderStage::Vertex, effectivePlatform);+ std::string fragmentSrc = ShaderParser::assembleStage(parsed, ShaderStage::Fragment, effectivePlatform);++ if (vertexSrc.empty()) {+ result.errorMessage = "Failed to assemble vertex shader";+ ES_LOG_ERROR("ShaderLoader: {}", result.errorMessage);+ return result;+ }++ if (fragmentSrc.empty()) {+ result.errorMessage = "Failed to assemble fragment shader";+ ES_LOG_ERROR("ShaderLoader: {}", result.errorMessage);+ return result;+ }++ result.shader = Shader::create(vertexSrc, fragmentSrc);+ if (!result.shader || !result.shader->isValid()) {+ result.errorMessage = "Failed to compile shader";+ result.shader.reset();+ ES_LOG_ERROR("ShaderLoader: {}", result.errorMessage);+ return result;+ }++ ES_LOG_DEBUG("ShaderLoader: Successfully compiled shader '{}'", parsed.name);+ return result;+}++std::string ShaderLoader::getDefaultPlatform() {+#ifdef ES_PLATFORM_WEB+ return "WEBGL";+#else+ return "DESKTOP";+#endif+}++bool ShaderLoader::canLoad(const std::string& path) {+ auto extensions = getSupportedExtensions();+ for (const auto& ext : extensions) {+ if (path.size() >= ext.size() &&+ path.compare(path.size() - ext.size(), ext.size(), ext) == 0) {+ return true;+ }+ }+ return false;+}++std::vector<std::string> ShaderLoader::getSupportedExtensions() {+ return {".esshader"};+}++} // namespace esengine::resourcediff --git a/src/esengine/resource/loaders/ShaderLoader.hpp b/src/esengine/resource/loaders/ShaderLoader.hppnew file mode 100644index 000000000..64bb45e9d--- /dev/null+++ b/src/esengine/resource/loaders/ShaderLoader.hpp@@ -0,0 +1,100 @@+/**+ * @file ShaderLoader.hpp+ * @brief Shader resource loader for .esshader files+ * @details Loads unified shader files and creates Shader resources.+ *+ * @author ESEngine Team+ * @date 2026+ *+ * @copyright Copyright (c) 2026 ESEngine Team+ * Licensed under the MIT License.+ */+#pragma once++// =============================================================================+// Includes+// =============================================================================++#include "../../core/Types.hpp"+#include "../ShaderParser.hpp"+#include "../../renderer/Shader.hpp"++#include <string>++namespace esengine::resource {++// =============================================================================+// Load Result+// =============================================================================++/**+ * @brief Result of shader loading operation+ */+struct ShaderLoadResult {+ Unique<Shader> shader; ///< Loaded shader (nullptr on failure)+ std::string errorMessage; ///< Error message if loading failed+ std::vector<std::string> dependencies; ///< File dependencies for hot reload++ /** @brief Checks if loading succeeded */+ bool isOk() const { return shader != nullptr; }+};++// =============================================================================+// ShaderLoader Class+// =============================================================================++/**+ * @brief Loader for unified .esshader files+ *+ * @details Parses .esshader format and creates GPU shader resources.+ * Supports platform variants for cross-platform compatibility.+ *+ * @code+ * ShaderLoader loader;+ * auto result = loader.loadFromFile("shaders/sprite.esshader");+ * if (result.isOk()) {+ * Shader* shader = result.shader.get();+ * }+ * @endcode+ */+class ShaderLoader {+public:+ /**+ * @brief Loads a shader from .esshader file+ * @param path Path to the .esshader file+ * @param platform Platform variant to use (empty for auto-detect)+ * @return Load result with shader or error message+ */+ ShaderLoadResult loadFromFile(const std::string& path,+ const std::string& platform = "");++ /**+ * @brief Loads a shader from source string+ * @param source Complete .esshader content+ * @param platform Platform variant to use (empty for auto-detect)+ * @return Load result with shader or error message+ */+ ShaderLoadResult loadFromSource(const std::string& source,+ const std::string& platform = "");++ /**+ * @brief Gets the default platform identifier for current build+ * @return Platform string (e.g., "WEBGL", "DESKTOP")+ */+ static std::string getDefaultPlatform();++ /**+ * @brief Checks if a file path is a supported shader format+ * @param path File path to check+ * @return True if the file extension is supported+ */+ static bool canLoad(const std::string& path);++ /**+ * @brief Gets supported file extensions+ * @return List of supported extensions (e.g., {".esshader"})+ */+ static std::vector<std::string> getSupportedExtensions();+};++} // namespace esengine::resource