Skip to content

Commit

Permalink
Implament 2d Render
Browse files Browse the repository at this point in the history
* implament 2d render

* add 2d render support properly

* fixes: debug window programmer error

* update log levels

* update shader system

* fix logging on windows

* load exising shaders from disk

* use direct addresing for batched textures

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update src/Renderer/Texture.h

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
  • Loading branch information
arozx and coderabbitai[bot] authored Feb 6, 2025
1 parent f17764f commit 85628e1
Show file tree
Hide file tree
Showing 40 changed files with 2,040 additions and 751 deletions.
3 changes: 3 additions & 0 deletions .vs/CMakeWorkspaceSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"enableCMake": true
}
2 changes: 1 addition & 1 deletion .vs/ProjectSettings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"CurrentProjectSetting": "x64-Debug"
"CurrentProjectSetting": "x64-Release"
}
20 changes: 18 additions & 2 deletions .vs/VSWorkspaceState.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
{
"DevContainersInfoBarHidden": true,
"ActiveTargetSystem": "Local Machine",
"OutputFoldersPerTargetSystem": {
"Local Machine": [
"out\\build\\x64-Debug",
Expand All @@ -11,6 +10,23 @@
"WSL: Arch": [
"out\\build\\x64-Debug",
"out\\install\\x64-Debug"
],
"WSL: Ubuntu-22.04": [
"out\\build\\x64-Debug",
"out\\install\\x64-Debug",
"out\\build\\x64-Release",
"out\\install\\x64-Release"
]
}
},
"ActiveTargetSystem": "Local Machine",
"ExpandedNodes": [
"\\sandbox",
"\\sandbox\\src",
"\\src",
"\\src\\Renderer",
"\\src\\Scene",
"\\src\\Scripting"
],
"SelectedNode": "\\CMakeLists.txt",
"PreviewInSolutionExplorer": false
}
7 changes: 5 additions & 2 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ set(ENGINE_SOURCES
src/Renderer/Buffer.cpp
src/Renderer/OpenGLBuffer.cpp
src/Renderer/Renderer.cpp
src/Renderer/Renderer2D.cpp
src/Shader/Shader.cpp
src/ImGui/ImGuiLayer.cpp
src/Renderer/VertexArray.cpp
Expand All @@ -84,6 +85,8 @@ set(ENGINE_SOURCES
external/stb_image/src/stb_image.cpp
src/Scripting/LuaScriptSystem.cpp
src/Scene/Scene.cpp
src/Shader/ShaderLibrary.cpp
src/Shader/ShaderFactory.cpp
${IMGUI_SOURCES}
)

Expand All @@ -94,14 +97,14 @@ target_include_directories(voxel-engine PUBLIC
${CMAKE_SOURCE_DIR}/src
${IMGUI_DIR}
${IMGUI_DIR}/backends
${CMAKE_SOURCE_DIR}/build/vcpkg_installed/x86-windows/include
${CMAKE_SOURCE_DIR}/external/stb_image/src
${CMAKE_SOURCE_DIR}/external/json
${CMAKE_SOURCE_DIR}/external/glad/include
${CMAKE_SOURCE_DIR}/build/vcpkg_installed/x86-windows/include
${CMAKE_SOURCE_DIR}/external/sol2
)

include_directories("/usr/include/lua5.4")

target_link_libraries(voxel-engine PUBLIC
glfw
OpenGL::GL
Expand Down
16 changes: 16 additions & 0 deletions assets/shaders/batch_renderer_2d.frag
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#version 330 core

in vec4 v_Color;
in vec2 v_TexCoord;
in float v_TexIndex;
in float v_TilingFactor;

uniform sampler2D u_Textures[32];

out vec4 FragColor;

void main() {
vec4 texColor = v_Color;
texColor *= texture(u_Textures[int(v_TexIndex)], v_TexCoord * v_TilingFactor);
FragColor = texColor;
}
22 changes: 22 additions & 0 deletions assets/shaders/batch_renderer_2d.vert
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
#version 330 core

layout (location = 0) in vec3 a_Position;
layout (location = 1) in vec4 a_Color;
layout (location = 2) in vec2 a_TexCoord;
layout (location = 3) in float a_TexIndex;
layout (location = 4) in float a_TilingFactor;

uniform mat4 u_ViewProjection;

out vec4 v_Color;
out vec2 v_TexCoord;
out float v_TexIndex;
out float v_TilingFactor;

void main() {
v_Color = a_Color;
v_TexCoord = a_TexCoord;
v_TexIndex = a_TexIndex;
v_TilingFactor = a_TilingFactor;
gl_Position = u_ViewProjection * vec4(a_Position, 1.0);
}
20 changes: 15 additions & 5 deletions imgui.ini
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ Collapsed=0

[Window][Stats]
Pos=35,54
Size=300,357
Size=300,426
Collapsed=0
DockId=0x00000002,0

Expand All @@ -51,8 +51,8 @@ Collapsed=0
DockId=0x00000003,0

[Window][Recent Events]
Pos=1098,15
Size=180,265
Pos=528,38
Size=367,265
Collapsed=0
DockId=0x00000006,0

Expand All @@ -63,7 +63,17 @@ Collapsed=0
DockId=0x00000005,0

[Window][Lua Console]
Pos=388,23
Pos=377,394
Size=520,600
Collapsed=0

[Window][Renderer Stats]
Pos=8,51
Size=158,106
Collapsed=0

[Window][LuaConsole##Window]
Pos=403,332
Size=520,600
Collapsed=0

Expand All @@ -75,7 +85,7 @@ Column 0 Sort=0v
DockNode ID=0x00000001 Pos=35,54 Size=300,426 Split=Y
DockNode ID=0x00000002 Parent=0x00000001 SizeRef=300,289 Selected=0x590DF097
DockNode ID=0x00000003 Parent=0x00000001 SizeRef=300,54 Selected=0xAC3EC402
DockNode ID=0x00000004 Pos=911,15 Size=367,265 Split=X
DockNode ID=0x00000004 Pos=528,38 Size=367,265 Split=X
DockNode ID=0x00000005 Parent=0x00000004 SizeRef=75,236 Selected=0x5B89BA50
DockNode ID=0x00000006 Parent=0x00000004 SizeRef=73,236 Selected=0x1A7C4B8A

87 changes: 74 additions & 13 deletions sandbox/assets/scripts/engine.lua
Original file line number Diff line number Diff line change
@@ -1,50 +1,77 @@
---* NOTE: all numbers in Lua are floats
---@meta

---@class engine
--- Terrain
---@field setTerrainHeight fun(height: number) # Sets the base height for terrain generation
---@field generateTerrainMesh fun(seed: number) # Regenerates terrain with given seed
---@field setClearColor fun(r: number, g: number, b: number, a: number) # Sets the renderer clear color
---@field isKeyPressed fun(keycode: number): boolean # Checks if a key is pressed
---@field getMousePosition fun(): number, number # Gets current mouse position
--- Logging
---@field trace fun(message: string) # Logs a trace message
---@field log fun(message: string) # Logs an info message
---@field warn fun(message: string) # Logs an warn message
---@field error fun(message: string) # Logs an error message
---@field fatal fun(message: string) # Logs an error message and terminates the application
--- Debug
---@field profileFunction fun(name: string) # Profiles the current function
---@field profileScope fun(name: string) # Profiles the current function & assigns a name
--- Script System
---@field loadScript fun(filepath: string): boolean # Loads and executes a Lua script file
---@field setCameraPosition fun(x: number, y: number, z: number) # Sets camera position
---@field setCameraRotation fun(pitch: number, yaw: number) # Sets camera rotation
---@field getCameraPosition fun(): number, number, number # Gets camera position
---@field moveCameraForward fun(deltaTime: number) # Move camera forward
---@field moveCameraBackward fun(deltaTime: number) # Move camera backward
---@field moveCameraLeft fun(deltaTime: number) # Move camera left
---@field moveCameraRight fun(deltaTime: number) # Move camera right
---@field moveCameraUp fun(deltaTime: number) # Move camera up
---@field moveCameraDown fun(deltaTime: number) # Move camera down
---@field rotateCameraWithMouse fun(xOffset: number, yOffset: number, sensitivity: number) # Rotate camera with mouse
--- Window
---@field setViewport fun(x: number, y: number, width: number, height: number) # Sets the viewport dimensions
---@field setClearColor fun(r: number, g: number, b: number, a: number) # Sets the renderer clear color
---Camera Setup
---@field setCameraType fun(type: string) # Sets the camera type ("orthographic" or "perspective")
---@field getCameraType fun(): string # Gets the current camera type
--- Input
---@field isMouseButtonPressed fun(button: number): boolean # Checks if a mouse button is pressed
---@field isKeyPressed fun(keycode: number): boolean # Checks if a key is pressed
---@field setMouseSensitivity fun(sensitivity: number) # Sets mouse sensitivity
---@field getMouseSensitivity fun(): number # Gets current mouse sensitivity
---@field getMousePosition fun(): number, number # Gets current mouse position
--- Movement
---@field setMovementSpeed fun(speed: number) # Sets movement speed
---@field getMovementSpeed fun(): number # Gets current movement speed
--- Camera Properties
---@field toggleCameraControls fun() # Toggles camera controls on/off
---@field toggleMovementLock fun() # Toggles movement lock
---@field toggleSmoothCamera fun() # Toggles smooth camera movement
--- Camera
---@field setCameraPosition fun(x: number, y: number, z: number) # Sets camera position
---@field setCameraRotation fun(pitch: number, yaw: number) # Sets camera rotation
---@field getCameraPosition fun(): number, number, number # Gets camera position
---@field moveCameraForward fun(deltaTime: number) # Move camera forward
---@field moveCameraBackward fun(deltaTime: number) # Move camera backward
---@field moveCameraLeft fun(deltaTime: number) # Move camera left
---@field moveCameraRight fun(deltaTime: number) # Move camera right
---@field moveCameraUp fun(deltaTime: number) # Move camera up
---@field moveCameraDown fun(deltaTime: number) # Move camera down
---@field rotateCameraWithMouse fun(xOffset: number, yOffset: number, sensitivity: number) # Rotate camera with mouse
--- ImGui Controls
---@field showTransformControls fun(show: boolean) # Shows/hides transform controls window
---@field showProfiler fun(show: boolean) # Shows/hides profiler window
---@field showRendererSettings fun(show: boolean) # Shows/hides renderer settings window
---@field showEventDebugger fun(show: boolean) # Shows/hides event debugger window
---@field showTerrainControls fun(show: boolean) # Shows/hides terrain controls window
---@field showFPSCounter fun(show: boolean) # Shows/hides FPS counter
--- Scene Management
---@field createScene fun(name: string): boolean # Creates a new scene with the given name
---@field setActiveScene fun(name: string): boolean # Sets the active scene by name
---@field deleteScene fun(name: string): boolean # Deletes a scene by name
---@field getActiveSceneName fun(): string # Gets the name of the active scene
--- Render System
---@field setRenderType fun(type: string) # Sets the renderer (2D or 3D)
---@field getRenderType fun(): string # Gets the renderer type (2D or 3D)
---@field getObject fun(name: string) # Gets an object by name
---@field is3D fun(): boolean # Checks if the current scene is 3D
--- 2D Render System
---@field renderer2DInitialize fun() # Creates a 2D renderer instance
---@field renderer2DBeginScene fun() # Begins a scene
---@field renderer2DEndScene fun() # Ends a scene
---@field drawQuad fun(x: number, y: number, width: number, height: number, r: number, g: number, b: number, a: number) # Draw a single quad
---@field drawTexturedQuad fun(x: number, y: number, width: number, height: number, texture, tiling_factor: number) # Draw a single quad with a texture
---@field createCheckerTexture fun() # Create a checkered texture from quads
--- 3D Render System
---@field createCube fun(scene: string) # Creates a cube in the scene
engine = {}

-- Key code constants
Expand Down Expand Up @@ -246,3 +273,37 @@ function engine.deleteScene(name) end
---Gets the name of the active scene
---@return string name The name of the active scene (empty string if no active scene)
function engine.getActiveSceneName() end

--- Sets the renderer type (2D or 3D)
--- @param type string 2D or 3D
function setRenderType(type) end

--- Gets the renderer type (2D or 3D)
--- @return type string
function getRenderType() end

--- Starts a scene with camera as context
function engine.renderer2d_begin_scene() end

--- Ends the current scene
function engine.renderer2d_end_scene() end

--- Draws a single quad
--- @param x number The x coordinate of the quad
--- @param y number The y coordinate of the quad
--- @param width number The width of the quad
--- @param height number The height of the quad
--- @param r number The red value of the quad
--- @param g number The greem value of the quad
--- @param b number The blue value of the quad
--- @param a number The alpha value of the quad
function engine.draw_quad(x, y, width, height, r, g, b, a) end

--- Draws a single textured quad
--- @param x number The x coordinate of the quad
--- @param y number The y coordinate of the quad
--- @param width number The width of the quad
--- @param height number The height of the quad
--- @param texture string The texture to use
--- @param tiling_factor number The tiling_factor
function engine.draw_textured_quad(x, y, width, height, texture, tiling_factor) end
19 changes: 8 additions & 11 deletions sandbox/assets/scripts/init.lua
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
engine.trace("Starting init.lua execution")

-- Create build directory structure first
-- Create build directory structure
local buildDir = "build/assets/scripts"
local scriptDir = "sandbox/assets/scripts"

Expand Down Expand Up @@ -29,7 +27,7 @@ local function copyScript(name)
end

if not isPathSafe(name) then
engine.error(string.format("Invalid script name (potential path traversal): %s", name))
engine.warn(string.format("Invalid script name (potential path traversal): %s", name))
return false
end

Expand All @@ -38,7 +36,7 @@ local function copyScript(name)

local source, sourceErr = io.open(sourcePath, "rb")
if not source then
engine.error(string.format("Could not open source script ", sourcePath, ": ", sourceErr))
engine.warn(string.format("Could not open source script ", sourcePath, ": ", sourceErr))
return false
end

Expand All @@ -47,43 +45,42 @@ local function copyScript(name)
local size = source:seek("end")
source:seek("set")
if size > MAX_FILE_SIZE then
engine.error(string.format("Script %s is too large (%d bytes > %d bytes limit)",
engine.warn(string.format("Script %s is too large (%d bytes > %d bytes limit)",
sourcePath, size, MAX_FILE_SIZE))
closeFiles(source)
return false
end

local content = source:read("*all")
if not content then
engine.error(string.format("Failed to read from ", sourcePath))
engine.warn(string.format("Failed to read from ", sourcePath))
closeFiles(source)
return false
end

local dest, destErr = io.open(destPath, "wb")
if not dest then
engine.error(string.format("Failed to create destination file", destPath, ": ", destErr))
engine.warn(string.format("Failed to create destination file", destPath, ": ", destErr))
closeFiles(source)
return false
end

local success = dest:write(content)
if not success then
engine.error(string.format("Failed to write to ", destPath))
engine.warn(string.format("Failed to write to ", destPath))
closeFiles(source, dest)
return false
end

closeFiles(source, dest)
engine.trace(string.format("Successfully copied: ", name))
return true
end

-- Only copy scripts, don't execute them
local scripts = { "main.lua", "engine.lua" }
for _, script in ipairs(scripts) do
if not copyScript(script) then
engine.error("Failed to copy " .. script)
engine.warn("Failed to copy " .. script)
return
end
end
Expand Down
Loading

0 comments on commit 85628e1

Please sign in to comment.