-
Notifications
You must be signed in to change notification settings - Fork 0
chapter 15, simulating water #43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
WalkthroughThis pull request introduces several changes across multiple files, focusing on enhancing functionality and resource management in various components. Key modifications include increasing the maximum file size limit for asset loading, adding new material constants for water simulation, implementing a structure for Euler angles, and introducing new shaders for simulating water effects. Additionally, the Changes
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 16
🧹 Outside diff range and nitpick comments (41)
src/foundations/lighting/material/clear_water.zig (1)
8-8: Consider moving the import statement to the top of the file.While the code works as is, it's conventional to place imports at the top of the file for better readability and organization.
+const Material = @import("../Material.zig"); + pub const ClearWater: Material = .{ .ambient = .{ 0.6, 0.6, 0.6, 1 }, .diffuse = .{ 0.9, 0.9, 0.9, 1 }, .specular = .{ 1, 1, 1, 1 }, .shininess = 10.0, }; - -const Material = @import("../Material.zig");src/foundations/lighting/material/pool_water.zig (1)
12-12: Consider moving the import statement to the top of the file.While the code works as is, it's a common convention to place imports at the beginning of the file for better readability and dependency management.
+const Material = @import("../Material.zig"); + pub const PoolWater: Material = .{ // Darker blue base color for underwater feel .ambient = .{ 0.05, 0.15, 0.25, 0.7 }, // Lighter blue-green for main water color with transparency .diffuse = .{ 0.1, 0.3, 0.4, 0.8 }, // Close to sky color for reflections (194/255, 216/255, 241/255) .specular = .{ 0.76, 0.847, 0.945, 0.9 }, // High shininess for water's reflective surface .shininess = 96.0, }; - -const Material = @import("../Material.zig");src/foundations/scenes/cgpoc/chapter15/simulating_water/skybox_frag.glsl (2)
4-11: Consider documenting the f_waterdata components.While the first component of f_waterdata is used for water presence, the purpose of the other components is unclear. Consider adding a comment explaining the purpose of each component in the vec3.
+// f_waterdata.x: Water presence flag (0 = no water, >0 = water) +// f_waterdata.y: Reserved for future use +// f_waterdata.z: Reserved for future use uniform vec3 f_waterdata;
20-24: Consider enhancing the water visualization.The current water implementation uses a solid dark blue color, which might be oversimplified. Consider adding:
- Alpha blending for transparency
- Fresnel effect for realistic water reflections
- Using the skybox texture with distortion for reflections
Example enhancement:
if (f_waterdata[0] > 0) { - fo_frag_color = vec4(0.0, 0.0, 0.2, 1.0); + vec3 view_dir = normalize(-fo_vert); + float fresnel = pow(1.0 - max(dot(view_dir, fo_normal), 0.0), 5.0); + vec3 reflection = texture(f_skybox, reflect(-view_dir, fo_normal)).rgb; + vec3 water_color = vec3(0.0, 0.0, 0.2); + fo_frag_color = vec4(mix(water_color, reflection, fresnel), 0.9); } else {src/ft3d/README.md (1)
Line range hint
1-5: Add documentation for the wave texture type.The README introduces marble and striped textures but doesn't mention the newly added wave texture type. Consider adding a description of what the wave texture is and its intended use case.
Example addition:
- Use to generate 3D textures. Currently supports marble and striped textures + Use to generate 3D textures. Currently supports: + - Marble textures: Creates marble-like patterns + - Striped textures: Generates striped patterns + - Wave textures: Simulates water wave patterns for water simulation effects🧰 Tools
🪛 LanguageTool
[uncategorized] ~3-~3: A comma may be missing after the conjunctive/linking adverb ‘Currently’.
Context: # ft3d Use to generate 3D textures. Currently supports marble and striped textures `...(SENT_START_CONJUNCTIVE_LINKING_ADVERB_COMMA)
src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_wave.glsl (3)
1-3: Add documentation for the wave sampler.Consider adding comments to describe:
- The expected texture format and dimensions
- The data layout within the 3D texture
- The coordinate system and units used
+// 3D texture containing wave height data +// Format: R channel represents wave height +// Coordinates: (x, depth, z) where depth represents the vertical slice layout(bindless_sampler) uniform sampler3D f_wave_samp;
4-6: Document function parameters and global dependencies.The function relies on undeclared global variables (
f_tcandf_waterdata). This makes the code harder to understand and maintain.+// Estimates the normal vector of the water surface at the current fragment +// Parameters: +// f_w_offset: Sampling offset distance for adjacent points +// f_w_map_scale: Scale factor for texture coordinates +// f_w_h_scale: Scale factor for wave height +// Global dependencies: +// f_tc: Current texture coordinates (vec2) +// f_waterdata: Water parameters array where f_waterdata[1] is depth offset vec3 f_estimate_wave_normal(float f_w_offset, float f_w_map_scale, float f_w_h_scale)
7-9: Optimize texture sampling and improve readability.The texture sampling code is repetitive and could be simplified. Also, the coordinate calculations could be made more readable.
- float f_h1 = 1.0 - (texture(f_wave_samp, vec3(((f_tc.s)) * f_w_map_scale, f_depth_offset, ((f_tc.t) + f_w_offset) * f_w_map_scale))).r * f_w_h_scale; - float f_h2 = 1.0 - (texture(f_wave_samp, vec3(((f_tc.s) - f_w_offset) * f_w_map_scale, f_depth_offset, ((f_tc.t) - f_w_offset) * f_w_map_scale))).r * f_w_h_scale; - float f_h3 = 1.0 - (texture(f_wave_samp, vec3(((f_tc.s) + f_w_offset) * f_w_map_scale, f_depth_offset, ((f_tc.t) - f_w_offset) * f_w_map_scale))).r * f_w_h_scale; + vec2 scaled_tc = f_tc * f_w_map_scale; + float sample_height(vec2 offset) { + vec3 sample_pos = vec3(scaled_tc + offset, f_depth_offset); + return 1.0 - texture(f_wave_samp, sample_pos).r * f_w_h_scale; + } + float f_h1 = sample_height(vec2(0.0, f_w_offset)); + float f_h2 = sample_height(vec2(-f_w_offset, -f_w_offset)); + float f_h3 = sample_height(vec2(f_w_offset, -f_w_offset));src/foundations/lighting/materials.zig (1)
16-17: LGTM! Well-structured material additions for water simulation.The addition of
PoolWaterandClearWatermaterials follows the established pattern of material organization, with good separation of concerns by having distinct types for different water appearances. This modular approach will make it easier to maintain and extend water simulation capabilities.src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWaterUI.zig (3)
1-2: Add documentation and consider using vec3 for light direction.The light direction is stored as a vec4 but only xyz components are used in the UI. Consider:
- Adding documentation to explain the purpose of these fields
- Using a vec3 instead since the w-component (0) suggests this is a direction vector and isn't modified
+/// Represents the direction of the light source in world space (xyz components) -light_direction: [4]f32 = .{ 4.0, 2.0, -3.75, 0 }, +light_direction: [3]f32 = .{ 4.0, 2.0, -3.75 }, +/// Indicates whether the light direction has been modified since last frame light_updated: bool = true,
8-12: Define constants for magic numbers.The window positioning and sizing use magic numbers. Consider defining these as named constants for better maintainability.
+const WINDOW_OFFSET_X: f32 = 50; +const WINDOW_OFFSET_Y: f32 = 50; +const WINDOW_WIDTH: f32 = 550; +const WINDOW_HEIGHT: f32 = 680; + pub fn draw(self: *Textures3DUI) void { const vp: *c.ImGuiViewport = c.igGetMainViewport(); - const pos = c.ImVec2_ImVec2_Float(vp.WorkPos.x + 50, vp.WorkPos.y + 50); + const pos = c.ImVec2_ImVec2_Float(vp.WorkPos.x + WINDOW_OFFSET_X, vp.WorkPos.y + WINDOW_OFFSET_Y); c.igSetNextWindowPos(pos.*, c.ImGuiCond_FirstUseEver, c.ImVec2_ImVec2_Float(0, 0).*); - const size = c.ImVec2_ImVec2_Float(550, 680); + const size = c.ImVec2_ImVec2_Float(WINDOW_WIDTH, WINDOW_HEIGHT);
14-17: Improve slider labels and configuration.The current implementation has several areas for improvement:
- Slider labels are cryptic (##trx, ##try, ##trz)
- Slider ranges are hardcoded
- No tooltips to explain the values
+const LIGHT_MIN_RANGE: f32 = -20.0; +const LIGHT_MAX_RANGE: f32 = 20.0; + _ = c.igText("translation"); -if (c.igSliderFloat("##trx", &self.light_direction[0], -20.0, 20.0, "%.3f", c.ImGuiSliderFlags_None)) self.light_updated = true; -if (c.igSliderFloat("##try", &self.light_direction[1], -20.0, 20.0, "%.3f", c.ImGuiSliderFlags_None)) self.light_updated = true; -if (c.igSliderFloat("##trz", &self.light_direction[2], -20.0, 20.0, "%.3f", c.ImGuiSliderFlags_None)) self.light_updated = true; +if (c.igSliderFloat("X##light_dir", &self.light_direction[0], LIGHT_MIN_RANGE, LIGHT_MAX_RANGE, "%.3f", c.ImGuiSliderFlags_None)) { + if (c.igIsItemHovered(c.ImGuiHoveredFlags_None)) c.igSetTooltip("Light direction X component"); + self.light_updated = true; +} +if (c.igSliderFloat("Y##light_dir", &self.light_direction[1], LIGHT_MIN_RANGE, LIGHT_MAX_RANGE, "%.3f", c.ImGuiSliderFlags_None)) { + if (c.igIsItemHovered(c.ImGuiHoveredFlags_None)) c.igSetTooltip("Light direction Y component"); + self.light_updated = true; +} +if (c.igSliderFloat("Z##light_dir", &self.light_direction[2], LIGHT_MIN_RANGE, LIGHT_MAX_RANGE, "%.3f", c.ImGuiSliderFlags_None)) { + if (c.igIsItemHovered(c.ImGuiHoveredFlags_None)) c.igSetTooltip("Light direction Z component"); + self.light_updated = true; +}src/foundations/scenes/cgpoc/chapter15/simulating_water/floor_vert.glsl (1)
39-39: Consider making the texture scale configurable.The texture coordinate scaling factor of 250 is hardcoded. Consider making this a uniform variable to allow dynamic adjustment of the tiling scale.
+uniform float f_texture_scale = 250.0; - f_tc = f_texture_coords * 250; + f_tc = f_texture_coords * f_texture_scale;src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_top_vert.glsl (2)
1-11: LGTM! Consider adding documentation.The input attributes are well-organized with explicit locations. Consider adding comments to document the purpose of each attribute, especially
f_i_colorvsf_colorand the transformation columns.
19-21: Maintain consistent naming convention.The output variables use inconsistent prefixes:
fo_lightandfo_posuse "fo_"f_view_puses "f_"Consider using the same prefix for all output variables.
Apply this diff:
out vec3 fo_light; out vec4 fo_pos; -out vec3 f_view_p; +out vec3 fo_view_p;src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_bot_vert.glsl (1)
33-36: Consider performance optimizations.
The normal matrix calculation (
transpose(inverse(mat3(m_matrix)))) is computationally expensive. Consider:
- Precomputing it on the CPU side
- Passing it as a uniform if the model matrix doesn't change frequently
The position transformations could be optimized by combining matrices:
- Combine model and view matrices if possible
- Precompute MVP matrix instead of separate multiplications
src/foundations/assets/loader.zig (1)
Line range hint
63-91: Enhance error handling for large files.The current implementation panics with "asset too big" when file size exceeds the limit. Consider:
- Returning a proper error instead of panicking
- Adding file size validation before reading
- Implementing graceful fallback for large files
Here's a suggested improvement:
fn read(self: *Self, file_name: []const u8) ![]u8 { std.debug.print("loading asset: {s} in {s}\n", .{ file_name, self.absolute_root_path }); var app_data_dir = std.fs.openDirAbsolute(self.absolute_root_path, .{}) catch @panic("failed to open app dir"); defer app_data_dir.close(); var fd = app_data_dir.openFile(file_name, .{}) catch |err| { if (err == std.fs.File.OpenError.FileNotFound) { return LoaderError.FileNotFound; } @panic("Failed opening asset"); }; defer fd.close(); - return fd.readToEndAlloc(self.allocator, max_file_size) catch @panic("asset too big"); + // Check file size first + const file_size = (try fd.stat()).size; + if (file_size > max_file_size) { + return error.FileTooLarge; + } + return fd.readToEndAlloc(self.allocator, max_file_size) catch |err| { + return switch (err) { + error.FileTooBig => error.FileTooLarge, + else => @panic("Failed reading asset"), + }; + }; }Also update the error set:
pub const LoaderError = error{ FileNotFound, + FileTooLarge, };src/ft3d/Args.zig (1)
37-37: LGTM! Consider adding documentation for the wave texture type.The addition of the
wavevariant totexture_type_optis well-placed and aligns with the water simulation objective.Consider adding a doc comment to describe the wave texture type's purpose and expected behavior:
pub const texture_type_opt = enum { striped, marble, wood, cloud, static, + /// Generates a wave-like texture pattern for water simulation wave, };src/foundations/object/ObjectQuad.zig (2)
29-45: LGTM! Note about plane orientation.The plane constants are well-defined with correct winding order (counter-clockwise when viewed from positive X). The plane is oriented in the YZ plane (at x=0), which is worth noting for future usage in water simulation.
Consider documenting this orientation choice in a comment, as it might be important for water simulation calculations.
88-127: Consider parameterizing hardcoded values.The function implementation looks solid, but there are hardcoded values that might limit reusability:
- Color is fixed to magenta (1,0,1,1)
- Normal is fixed to (1,0,0)
Consider making these configurable:
pub fn initPlane( program: u32, instance_data: []const rhi.instanceData, + color: ?[4]f32, + normal: ?[3]f32, label: [:0]const u8, ) Quad { // ... rhi_data[i] = .{ .position = positions[i], .texture_coords = plane_texture_coordinates[i], - .color = .{ 1, 0, 1, 1 }, - .normal = .{ 1, 0, 0 }, + .color = color orelse .{ 1, 0, 1, 1 }, + .normal = normal orelse .{ 1, 0, 0 }, }; // ... }src/foundations/scenes/cgpoc/chapter14/clipping_plane/ClippingPlane.zig (1)
287-287: LGTM! Consider documenting the dual-instance setup.The explicit type annotation improves code clarity. Since this torus uses two instances with different alpha values (0.25 and 1.0), consider adding a comment explaining the visual effect this creates.
Add a comment like:
+ // Dual-instance setup: First instance (alpha=0.25) creates a transparent preview, + // second instance (alpha=1.0) shows the final clipped shape var torus: object.object = .{ .torus = object.Torus.init(prog, i_datas[0..], "torus") };src/foundations/rhi/Texture.zig (1)
75-100: Consider adding mipmaps support for render textures.The implementation looks good and follows the established patterns. However, you might want to consider adding mipmap support like in the
setupfunction, especially if the render texture will be sampled at different scales.c.glTextureStorage2D(name, 1, c.GL_RGBA8, @intCast(width), @intCast(height)); c.glTextureParameteri(name, c.GL_TEXTURE_MIN_FILTER, c.GL_LINEAR); c.glTextureParameteri(name, c.GL_TEXTURE_MAG_FILTER, c.GL_LINEAR); +// Optional: Add mipmaps if needed +// c.glTextureParameteri(name, c.GL_TEXTURE_MIN_FILTER, c.GL_LINEAR_MIPMAP_LINEAR); +// c.glGenerateTextureMipmap(name);src/foundations/math/rotation.zig (2)
59-85: Consider enhancing code clarity and maintainability.While the implementation is mathematically correct, consider these improvements:
- Extract the gimbal lock threshold (0.9999) as a named constant
- Add comments explaining the mathematical basis of the conversion formulas
+ const GIMBAL_LOCK_THRESHOLD = 0.9999; + + /// Converts a quaternion to Euler angles (pitch, heading, bank) + /// Uses the following conversion formulas: + /// sin(pitch) = -2(yz - wx) + /// heading = atan2(xz + wy, 0.5 - x² - y²) + /// bank = atan2(xy + wz, 0.5 - x² - z²) pub fn quatToEuler(q: Quat) Euler { const w: f32 = q[0]; const x: f32 = q[1]; const y: f32 = q[2]; const z: f32 = q[3]; var p: f32 = 0; var h: f32 = 0; var b: f32 = 0; const sin_pitch = -2.0 * (y * z - w * x); - if (@abs(sin_pitch) > 0.9999) { + if (@abs(sin_pitch) > GIMBAL_LOCK_THRESHOLD) {
87-116: Consider adding test coverage for gimbal lock scenario.While the current tests cover basic and combined rotations, they don't explicitly test the gimbal lock handling. Consider adding a test case where sin_pitch approaches ±1 to verify the special case handling.
test quatToEuler { + // Test gimbal lock case (pitch = 90 degrees) + const gimbal_q = axisAngleToQuat(.{ + .angle = degreesToRadians(90), + .axis = .{ 0, 1, 0 }, + }); + const gimbal_r = quatToEuler(gimbal_q); + const gimbal_e: Euler = .{ + .pitch = std.math.pi / 2.0, + .heading = 0, + .bank = 0, + }; + try std.testing.expect(float.equal_e(gimbal_e.pitch, gimbal_r.pitch)); + try std.testing.expect(float.equal_e(gimbal_e.heading, gimbal_r.heading)); + try std.testing.expect(float.equal_e(gimbal_e.bank, gimbal_r.bank)); + // Existing tests...src/foundations/scenes/cgpoc/chapter14/textures_3d/Textures3D.zig (3)
38-38: Consider using a dynamic array for shadow objects.While the size increase is correct, using a fixed-size array requires manual updates when adding new objects. Consider using an ArrayList or similar dynamic collection to make the code more maintainable.
-shadow_objects: [6]rendering.DirectionalShadowPass.ShadowObject = undefined, +shadow_objects: std.ArrayList(rendering.DirectionalShadowPass.ShadowObject),
270-275: Consider adding error handling for texture binding.While the drawing logic follows the established pattern, consider adding error handling or logging when texture binding fails, as this could help with debugging rendering issues.
{ - if (self.wave_tex) |t| { - t.bind(); + if (self.wave_tex) |t| { + t.bind() catch |err| { + std.log.err("Failed to bind wave texture: {}", .{err}); + }; } rhi.drawObject(self.wave_block); }
355-377: Add documentation and enhance error handling.While the implementation follows the established pattern, consider these improvements:
- Add documentation explaining the wave block's purpose and behavior.
- Add error handling for texture setup failures.
+/// Renders a wave block with a 3D texture for water simulation. +/// The block is positioned at y=2.5 and uses a wave.vol texture for the effect. fn renderWaveBlock(self: *Textures3D) void { const m = math.matrix.translateVec(.{ 0, 2.5, 0 }); const block = self.renderParallelepiped(m); self.wave_tex = rhi.Texture.init(self.ctx.args.disable_bindless) catch null; self.wave_tex.?.texture_unit = 1; if (self.wave_tex) |*t| { - const data = self.ctx.textures_3d_loader.loadAsset("cgpoc\\wave.vol") catch null; + const data = self.ctx.textures_3d_loader.loadAsset("cgpoc\\wave.vol") catch |err| { + std.log.err("Failed to load wave texture: {}", .{err}); + return; + }; t.setup3D( data, tex_dims, tex_dims, tex_dims, block.mesh.program, c.GL_CLAMP_TO_EDGE, "f_tex_samp", "wave_3d", - ) catch { + ) catch |err| { + std.log.err("Failed to setup wave texture: {}", .{err}); self.wave_tex = null; }; } self.wave_block = .{ .parallelepiped = block }; }src/foundations/physics/camera.zig (1)
352-375: Add bounds checking and documentationConsider these improvements:
- Add documentation explaining the function's purpose and behavior
- Add bounds checking for the bank angle to prevent unexpected behavior
Example implementation:
+/// Flips the camera's vertical orientation by rotating around the right axis. +/// This function only works when not in fly mode and uses the current pitch +/// orientation to determine the flip angle. pub fn flipVerticalOrientation( self: *Self, ) void { if (self.fly_mode) return; const ea = math.rotation.quatToEuler(self.camera_orientation_pitch); + // Ensure bank angle is within reasonable bounds to prevent unstable flips + const bank = std.math.clamp(ea.bank, -std.math.pi / 2.0, std.math.pi / 2.0); const a: math.rotation.AxisAngle = .{ - .angle = -ea.bank * 2.0, + .angle = -bank * 2.0, .axis = world_right, };src/foundations/scenes/cgpoc/chapter15/simulating_water/skybox_vert.glsl (1)
19-24: Consider definingf_cubemap_xupas a constant or uniformIf
f_cubemap_xupis a constant matrix used across multiple shaders, it might be beneficial to define it as a uniform or move it to a shared include file for reusability and maintainability.src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_bot_frag.glsl (1)
26-27: Define occlusion distances using named constants for clarityTo improve code readability and maintainability, consider defining
f_occlusion_startandf_occlusion_endusing named constants instead of inline calculations with magic numbers.Apply this diff:
+const float kOcclusionStartDistance = 10.0; // 0.01 * 1000.0 +const float kOcclusionEndDistance = 100.0; // 0.1 * 1000.0 -float f_occlusion_start = 0.01 * 1000.0; -float f_occlusion_end = 0.1 * 1000.0; +float f_occlusion_start = kOcclusionStartDistance; +float f_occlusion_end = kOcclusionEndDistance;src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_top_frag.glsl (2)
51-54: Use Schlick's approximation for a more accurate Fresnel effectThe current Fresnel calculation may not produce physically accurate results. Consider using Schlick's approximation for better visual realism and performance efficiency.
Apply this diff to implement Schlick's approximation:
vec3 f_n_fres = normalize(fo_normal); float f_cos_fres = dot(f_V, f_n_fres); -float f_fresnel = acos(f_cos_fres); -f_fresnel = pow(clamp(f_fresnel - 0.3, 0.0, 1.0), 3); +float f_fresnel = pow(1.0 - f_cos_fres, 5.0);
55-55: Remove unnecessary semicolonLine 55 contains an extraneous semicolon that is unnecessary and could cause confusion.
Apply this diff to remove the semicolon:
-;src/foundations/scenes/cgpoc/chapter15/simulating_water/floor_frag.glsl (3)
22-23: Define occlusion distances as named constants for clarityUsing magic numbers in calculations can make the code harder to read and maintain. Consider defining the occlusion start and end distances as named constants to improve clarity.
For example:
const float F_OCCLUSION_START_DISTANCE = 10.0; // 0.01 * 1000.0 const float F_OCCLUSION_END_DISTANCE = 100.0; // 0.1 * 1000.0 float f_occlusion_start = F_OCCLUSION_START_DISTANCE; float f_occlusion_end = F_OCCLUSION_END_DISTANCE;
46-49: Prevent negative tile distortion strength for robustnessThe calculation of
f_tile_distort_strmay result in negative values whenf_frag_distanceis less than10.0, potentially causing unintended distortions. Consider clamping the value to ensure it remains non-negative.Apply this change to clamp the distortion strength:
float f_tile_distort_str = max(0.0, 0.005 * (f_frag_distance - 10.0));
54-58: Clarify conditional logic with parentheses and verify threshold valuesThe condition in the
ifstatement combines multiple logical operations, which can be confusing due to operator precedence. Add parentheses to make the logic explicit. Additionally, verify if the threshold value0.95is intentional or if it should be1.0for better alignment with the checker pattern.Rewritten condition with added parentheses:
if ( (mod(f_z_distorted, 2.0) <= 0.95 && mod(f_y_distorted, 2.0) > 0.95) || (mod(f_z_distorted, 2.0) > 0.95 && mod(f_y_distorted, 2.0) <= 0.95) ) { f_surface_color = vec4(0.01, 0.01, 0.01, 1.0); } else { f_surface_color = vec4(0.9, 0.9, 0.9, 0.9); }Also, consider adjusting the threshold values if needed:
// Replace 0.95 with 1.0 if appropriate if ( (mod(f_z_distorted, 2.0) <= 1.0 && mod(f_y_distorted, 2.0) > 1.0) || (mod(f_z_distorted, 2.0) > 1.0 && mod(f_y_distorted, 2.0) <= 1.0) ) { // ... }src/foundations/rhi/Framebuffer.zig (1)
63-93: Enhance error reporting incheckStatusby returning specific error variantsCurrently,
checkStatuslogs specific framebuffer status issues but returns a genericFrameBufferError.FramebufferIncompleteerror. To improve error handling, consider expandingFrameBufferErrorto include specific variants for each framebuffer status. This will allow calling code to handle different framebuffer issues more precisely.You might define additional error variants in
FrameBufferError:pub const FrameBufferError = error{ FramebufferIncomplete, + FramebufferUndefined, + FramebufferIncompleteAttachment, + FramebufferMissingAttachment, + FramebufferIncompleteDrawBuffer, + FramebufferIncompleteReadBuffer, + FramebufferUnsupported, + FramebufferIncompleteMultisample, + FramebufferIncompleteLayerTargets, FramebufferStatusCheckFailure, };Then, modify
checkStatusto return these specific errors:switch (status) { c.GL_FRAMEBUFFER_COMPLETE => return, c.GL_FRAMEBUFFER_UNDEFINED => { std.debug.print("Framebuffer undefined - probably means FBO 0 is bound {d}\n", .{self.name}); + return FrameBufferError.FramebufferUndefined; }, c.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT => { std.debug.print("Framebuffer incomplete: attachment points are framebuffer incomplete {d}\n", .{self.name}); + return FrameBufferError.FramebufferIncompleteAttachment; }, c.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT => { std.debug.print("Framebuffer incomplete: no attachments set {d}\n", .{self.name}); + return FrameBufferError.FramebufferMissingAttachment; }, c.GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER => { std.debug.print("Framebuffer incomplete: draw buffer {d}\n", .{self.name}); + return FrameBufferError.FramebufferIncompleteDrawBuffer; }, c.GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER => { std.debug.print("Framebuffer incomplete: read buffer {d}\n", .{self.name}); + return FrameBufferError.FramebufferIncompleteReadBuffer; }, c.GL_FRAMEBUFFER_UNSUPPORTED => { std.debug.print("Framebuffer incomplete: unsupported format combination {d}\n", .{self.name}); + return FrameBufferError.FramebufferUnsupported; }, c.GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE => { std.debug.print("Framebuffer incomplete: multisample settings mismatch {d}\n", .{self.name}); + return FrameBufferError.FramebufferIncompleteMultisample; }, c.GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS => { std.debug.print("Framebuffer incomplete: layer targets mismatch {d}\n", .{self.name}); + return FrameBufferError.FramebufferIncompleteLayerTargets; }, else => { std.debug.print("Framebuffer status unknown: {d} for {d}\n", .{ status, self.name }); + return FrameBufferError.FramebufferIncomplete; }, } - return FrameBufferError.FramebufferIncomplete;This change will make error handling more granular and informative.
src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWater.zig (1)
254-281: RefactorsetupReflectionandsetupRefractionto eliminate code duplication.The
setupReflectionandsetupRefractionfunctions share similar logic with minor differences in texture names and units. Refactoring these functions into a single, parameterized function can reduce code duplication, enhance maintainability, and make future updates easier.Consider creating a new function, e.g.,
setupRenderTexture, that accepts parameters such as texture names, texture units, and assigns the resulting textures and framebuffers to the appropriate fields. This change promotes code reuse and simplifies the structure.Also applies to: 283-310
src/ft3d/Wave.zig (4)
11-11: Suggestion: Handle Out-Of-Memory errors gracefullyCurrently, the code panics with
@panic("OOM")when memory allocation fails. While panicking provides immediate feedback, it abruptly terminates the program and may not be ideal for all contexts. Consider returning an error instead, allowing the caller to handle the OOM condition appropriately.Apply this diff to handle errors gracefully:
- pub fn init(allocator: std.mem.Allocator) *Static { + pub fn init(allocator: std.mem.Allocator) !*Static { - var sp = allocator.create(Static) catch @panic("OOM"); + var sp = try allocator.create(Static); ... - ) catch @panic("OOM"); + ) catch return error.OutOfMemory;Note: You'll need to update the function's return type to include possible errors (e.g.,
!*Static) and handle errors usingtryorcatchas appropriate.Also applies to: 20-20
2-3: Improve Variable Naming for ClarityThe variables
dimsanddimare similar in name but represent different concepts (dimsis the size of dimensions,dimis the number of channels). This could lead to confusion.Consider renaming
dimtochannel_countornum_channelsto enhance readability.Apply this diff to rename the variable:
- dim: usize = 4, + channel_count: usize = 4,Remember to update all occurrences of
dimthroughout the code.
62-64: Clarify the Reason for Clamping Color Values to 75The color channel values are clamped between
0and75:const r_channel: f32 = @min(@max(brightness * 255.0, 0), 75.0);Capping the maximum value at
75limits the brightness of the texture. If this is intended to achieve a specific visual effect, please document the rationale. Otherwise, consider using the full range (0to255) to utilize the entire color spectrum.
25-30: Suggestion: Nullify Pointers After DeinitializationAfter deinitializing
noise_3danddata, onlyself.datais set toundefined. To prevent potential use-after-free errors or dangling pointers, consider also settingself.noise_3dtoundefined.Apply this diff to update the code:
self.noise_3d.deinit(allocator); + self.noise_3d = undefined; self.data.deinit(allocator); self.data = undefined;
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
📒 Files selected for processing (31)
src/foundations/assets/loader.zig(1 hunks)src/foundations/lighting/material/clear_water.zig(1 hunks)src/foundations/lighting/material/pool_water.zig(1 hunks)src/foundations/lighting/materials.zig(1 hunks)src/foundations/math/rotation.zig(2 hunks)src/foundations/object/ObjectQuad.zig(2 hunks)src/foundations/physics/camera.zig(2 hunks)src/foundations/rhi/Framebuffer.zig(2 hunks)src/foundations/rhi/Texture.zig(1 hunks)src/foundations/scenes/cgpoc/cgpoc.zig(1 hunks)src/foundations/scenes/cgpoc/chapter14/blend/Blend.zig(1 hunks)src/foundations/scenes/cgpoc/chapter14/clipping_plane/ClippingPlane.zig(2 hunks)src/foundations/scenes/cgpoc/chapter14/textures_3d/Textures3D.zig(6 hunks)src/foundations/scenes/cgpoc/chapter15/chapter15.zig(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWater.zig(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWaterUI.zig(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/floor_frag.glsl(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/floor_vert.glsl(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/skybox_frag.glsl(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/skybox_vert.glsl(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_bot_frag.glsl(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_bot_vert.glsl(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_top_frag.glsl(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_top_vert.glsl(1 hunks)src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_wave.glsl(1 hunks)src/foundations/scenes/scenes.zig(1 hunks)src/foundations/ui/ui_state.zig(2 hunks)src/ft3d/Args.zig(2 hunks)src/ft3d/Generator.zig(2 hunks)src/ft3d/README.md(1 hunks)src/ft3d/Wave.zig(1 hunks)
✅ Files skipped from review due to trivial changes (2)
- src/foundations/scenes/cgpoc/cgpoc.zig
- src/foundations/scenes/cgpoc/chapter15/chapter15.zig
🔇 Additional comments (40)
src/foundations/lighting/material/pool_water.zig (1)
1-10: Material properties look well-defined for water simulation.
The color values and properties are thoughtfully chosen to create a realistic water effect:
- Ambient color provides a good underwater base tone
- Diffuse color with partial transparency creates the water body effect
- Specular color matching sky blue enhances realism for reflections
- Shininess value of 96.0 appropriately simulates water's reflective surface
However, consider verifying these values in different lighting conditions.
Let's check if these material properties are consistent with other water-related materials in the codebase:
✅ Verification successful
Let me check the actual material definitions in the water-related files to compare the properties.
Material properties are well-defined and consistent with the codebase
The material properties for PoolWater are appropriate and complement the existing ClearWater material in the codebase. While ClearWater is designed for general transparent water with neutral colors (ambient: 0.6, diffuse: 0.9), the PoolWater material correctly uses:
- Lower ambient values with blue tint (0.05, 0.15, 0.25) for depth
- Partial transparency (0.7-0.9 alpha) suitable for pool water
- Higher shininess (96.0 vs 10.0) appropriate for still pool water surface
Both materials are actively used in the water simulation scene, confirming their practical application.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for other material definitions with similar properties
rg -l "ambient.*diffuse.*specular.*shininess" --type zig
# Look for other water-related materials
rg -l "water|Water" --type zig
Length of output: 424
Script:
#!/bin/bash
# Check contents of water-related material files
cat src/foundations/lighting/material/clear_water.zig
cat src/foundations/lighting/material/pool_water.zig
# Check if there are any other material definitions in materials.zig
rg "const.*Material.*=.*{" src/foundations/lighting/materials.zig -A 10
# Check water simulation implementation for any material requirements
rg "Material" src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWater.zig -A 5
Length of output: 1215
src/foundations/scenes/cgpoc/chapter15/simulating_water/skybox_frag.glsl (2)
1-2: LGTM! Appropriate GLSL version and extension.
The shader uses GLSL 4.60 and correctly requires the bindless texture extension.
14-16: Verify skybox texture coordinate normalization.
While the shader uses the skybox texture coordinates directly, it's important to ensure they're properly normalized in the vertex shader to prevent sampling artifacts.
#!/bin/bash
# Check for skybox vertex shader implementation
echo "Checking for skybox vertex shader..."
fd "skybox_vert.glsl" "src/foundations/scenes/cgpoc/chapter15/simulating_water/"src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWaterUI.zig (2)
4-4: LGTM!
The type definition is correctly implemented using Zig's @this() for getting the current file's type.
22-24: LGTM!
The imports are well-organized and include all necessary dependencies.
src/foundations/scenes/cgpoc/chapter15/simulating_water/floor_vert.glsl (3)
1-11: LGTM! Well-structured input declarations.
The input attributes are properly defined with explicit locations and appropriate types for water simulation requirements.
19-20: Verify output variable declarations.
Several output variables used in the main function (fo_vert, fo_normal, f_tc, f_frag_color) are not explicitly declared. These might be defined in the commented-out vertex_outs.glsl, but we should verify this.
✅ Verification successful
Let me check the actual content of vertex_outs.glsl to verify the declarations.
Output variables are properly declared in vertex_outs.glsl
All missing output variables (fo_vert, fo_normal, f_tc, f_frag_color) are correctly declared in the included vertex_outs.glsl file. The original concern about undeclared outputs has been resolved.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if the missing output variables are defined in vertex_outs.glsl
# Expected: Find declarations for fo_vert, fo_normal, f_tc, and f_frag_color
rg -l "out\s+vec[34]\s+(fo_vert|fo_normal|f_tc|f_frag_color)" "src/foundations/shaders/vertex_outs.glsl"
Length of output: 145
Script:
#!/bin/bash
# Get the content of vertex_outs.glsl to verify the output declarations
cat src/foundations/shaders/vertex_outs.glsl
Length of output: 165
13-17:
Uncomment required includes to fix compilation errors.
The shader uses f_lights[0] on line 30, but the light definition include is commented out. Similarly, camera-related variables might be needed for view transformations. Please uncomment the necessary includes or verify if these definitions are provided through alternative means.
-//#include "src/foundations/shaders/light.glsl"
+#include "src/foundations/shaders/light.glsl"
-//#include "src/foundations/shaders/camera.glsl"
+#include "src/foundations/shaders/camera.glsl"
-//#include "src/foundations/shaders/vertex_outs.glsl"
+#include "src/foundations/shaders/vertex_outs.glsl"⛔ Skipped due to learnings
Learnt from: btipling
PR: btipling/foundations#41
File: src/foundations/scenes/graphics/particles/particles_frag.glsl:8-10
Timestamp: 2024-10-25T04:49:44.473Z
Learning: In this codebase, GLSL shader files use `//#include` comments to indicate include statements that are processed by the custom includer. Do not suggest uncommenting these lines.
src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_top_vert.glsl (2)
13-17:
Uncomment required include statements.
The shader uses variables that should be defined in the commented-out include files:
f_lights[0]requires "light.glsl"f_mvprequires "camera.glsl"fo_vert,fo_normal,f_tc,f_frag_colorrequire "vertex_outs.glsl"
These missing includes will cause compilation errors.
Apply this diff:
-//#include "src/foundations/shaders/light.glsl"
-//#include "src/foundations/shaders/camera.glsl"
-//#include "src/foundations/shaders/vertex_outs.glsl"
+#include "src/foundations/shaders/light.glsl"
+#include "src/foundations/shaders/camera.glsl"
+#include "src/foundations/shaders/vertex_outs.glsl"Also applies to: 31-31, 38-41, 42-42
⛔ Skipped due to learnings
Learnt from: btipling
PR: btipling/foundations#41
File: src/foundations/scenes/graphics/particles/particles_frag.glsl:8-10
Timestamp: 2024-10-25T04:49:44.473Z
Learning: In this codebase, GLSL shader files use `//#include` comments to indicate include statements that are processed by the custom includer. Do not suggest uncommenting these lines.
23-44: Verify light array bounds.
The shader assumes f_lights[0] exists without validation. While this might be guaranteed by the application, it's worth verifying that the light array is properly initialized.
✅ Verification successful
Light array access is safe and properly defined
The verification shows that f_lights is properly defined in a shader storage buffer (std430) with dynamic array size in light.glsl, which is included in the vertex shader. The array is bound at binding point 1, making the access to f_lights[0] safe as the buffer must be properly bound and sized by the application before shader execution.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Check if the light array is properly initialized in the application code
# Test: Search for light array initialization
rg -A 5 "f_lights\s*=|f_lights\[\s*0\s*\]\s*=" --type cpp --type c --type glsl
# Test: Search for uniform buffer containing lights
ast-grep --pattern 'uniform\s+\w+\s*{\s*$$$\s*Light\s+f_lights\s*(\[.*\])?\s*;\s*$$$\s*}'
Length of output: 201
Script:
#!/bin/bash
# Search for light array declarations and usage in shader files
fd -e glsl -x rg -l "Light\s+f_lights"
# Search for light array size or initialization
fd -e glsl -x rg -A 5 "Light\s+f_lights\[.*\]"
# Search for uniform block definitions containing lights
fd -e glsl -x rg -A 5 "uniform\s+\w+\s*\{.*Light.*\}"
Length of output: 2962
Script:
#!/bin/bash
# Let's check the specific shader file and its includes for light array declaration
rg -A 5 "Light\s+f_lights|uniform\s+\w+\s*\{" src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_top_vert.glsl
# Check for any includes in the shader file that might contain light declarations
rg "^#include" src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_top_vert.glsl
Length of output: 220
Script:
#!/bin/bash
# Let's first check if the file exists and see its content
cat src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_top_vert.glsl
# Also check for any light-related uniform declarations in nearby files in the same directory
fd -e glsl . src/foundations/scenes/cgpoc/chapter15/simulating_water/ -x rg -A 5 "uniform\s+\w+\s*\{.*Light.*\}|Light\s+f_lights"
Length of output: 1461
Script:
#!/bin/bash
# Check the content of the included light.glsl file
cat src/foundations/shaders/light.glsl
# Also check if there are any other files that might include light.glsl and define the uniform block
fd -e glsl -x rg -A 5 '#include.*light\.glsl' {}
Length of output: 4541
src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_bot_vert.glsl (2)
1-11: LGTM! Well-structured input attributes.
The shader uses an appropriate GLSL version and has well-organized input attributes with proper semantic locations for vertex data, transformation matrices, and colors.
13-17:
Uncomment required include statements.
The shader uses variables that should be defined in these include files:
f_lights[0]from light.glslv_matrixfrom camera.glsl- Potentially
fo_vert,f_tc,f_frag_colorfrom vertex_outs.glsl
These commented includes will cause compilation errors.
Apply this diff:
-//#include "src/foundations/shaders/light.glsl"
-//#include "src/foundations/shaders/camera.glsl"
-//#include "src/foundations/shaders/vertex_outs.glsl"
+#include "src/foundations/shaders/light.glsl"
+#include "src/foundations/shaders/camera.glsl"
+#include "src/foundations/shaders/vertex_outs.glsl"⛔ Skipped due to learnings
Learnt from: btipling
PR: btipling/foundations#41
File: src/foundations/scenes/graphics/particles/particles_frag.glsl:8-10
Timestamp: 2024-10-25T04:49:44.473Z
Learning: In this codebase, GLSL shader files use `//#include` comments to indicate include statements that are processed by the custom includer. Do not suggest uncommenting these lines.
src/foundations/scenes/scenes.zig (1)
24-24: LGTM! Verify scene type and assets.
The change aligns with the PR objectives of implementing water simulation. The initialization looks correct and type-safe.
Let's verify the scene type exists and required assets are properly handled:
✅ Verification successful
Scene type and implementation verified successfully
The verification confirms:
- Scene type
fifteen_simulating_wateris properly defined insrc/foundations/ui/ui_state.zig - Water simulation is fully implemented in
SimulatingWater.zigwith all required lifecycle methods (init, deinit, update, draw) - Required shader assets are embedded and properly handled:
- Floor shaders (vert/frag)
- Surface top/bottom shaders (vert/frag)
- Skybox shaders (vert/frag)
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify scene type and asset requirements
# Test 1: Check if the scene type exists
echo "Checking for scene type definition..."
rg -l "fifteen_simulating_water.*scene_type" src/ui/
# Test 2: Check if water simulation implementation exists
echo "Checking for water simulation implementation..."
fd -e zig "SimulatingWater" src/foundations/scenes/cgpoc/chapter15/
# Test 3: Check for water-related shader assets
echo "Checking for water shader assets..."
fd -e glsl -e vert -e frag "water" assets/shaders/
Length of output: 749
Script:
#!/bin/bash
# Let's try different search patterns and paths
# Test 1: Search for scene type enum definition
echo "Checking for scene type definition..."
rg -l "fifteen_simulating_water" .
# Test 2: Check water simulation files content
echo "Checking water simulation implementation..."
rg "pub fn init|pub fn deinit|pub fn update|pub fn draw" src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWater.zig
# Test 3: Check for shader references in water simulation
echo "Checking shader references..."
rg "shader|\.vert|\.frag" src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWater.zig
Length of output: 2798
src/ft3d/Generator.zig (2)
75-81: LGTM! Implementation follows established patterns.
The new .wave case follows the same initialization, data filling, and cleanup pattern as other texture types, ensuring consistent memory management and error handling.
106-106: LGTM! Import statement properly placed.
The Wave module import follows the established pattern of module imports in this file.
src/foundations/assets/loader.zig (1)
2-2: Verify the need for 4GB max file size.
The maximum file size has been increased from ~128MB to ~4GB. While this might be needed for water simulation assets, it could lead to memory issues:
- Loading large files entirely into memory could cause OOM errors
- No streaming mechanism for large files
- Could impact performance when loading assets
Consider the following improvements:
- Implement streaming/chunking for large files
- Add progress reporting for better UX
- Consider memory-mapped files for better memory management
Let's verify if this change is really needed:
src/ft3d/Args.zig (1)
70-71: LGTM! The validation logic is properly implemented.
The validation logic for the wave texture type follows the established pattern and maintains consistent error handling.
src/foundations/ui/ui_state.zig (2)
96-96: LGTM! The union field is properly typed.
The new union field correctly maps to the SimulatingWater type from chapter 15.
Let's verify that the SimulatingWater type exists and is exported:
#!/bin/bash
# Search for the SimulatingWater type definition
ast-grep --pattern 'pub const SimulatingWater = struct {
$$$
}'47-47: LGTM! The enum addition follows conventions.
The new scene type fifteen_simulating_water is correctly placed and follows the established naming pattern.
Let's verify that the referenced chapter module exists:
✅ Verification successful
The enum addition is correctly implemented and verified
The verification confirms that:
- The
SimulatingWaterstruct exists insrc/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWater.zig - The module structure follows the expected pattern:
chapter15/simulating_water - The type is properly imported through the module chain:
cgpoc.chapter15.SimulatingWater - The scene is properly integrated into the scene management system
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Verify the existence of the chapter 15 module
fd "chapter15" --type d
Length of output: 67
Script:
#!/bin/bash
# Let's try different approaches to find the chapter 15 related code
# 1. Search for any files containing "chapter15" or "chapter 15" in their name or content
rg -i "chapter\s*15|simulating.?water" --type zig
# 2. Look for SimulatingWater struct definition
ast-grep --pattern 'const SimulatingWater = struct {
$$$
}'
# 3. Search for water simulation related files
fd -e zig "water"
Length of output: 4223
src/foundations/object/ObjectQuad.zig (1)
131-131: LGTM! Good safety improvement.
The change to []const rhi.instanceData improves type safety by preventing unintended modifications to the instance data.
src/foundations/scenes/cgpoc/chapter14/blend/Blend.zig (2)
237-237: LGTM! Explicit type annotation improves clarity.
The addition of explicit type annotation object.object makes the code more readable and maintainable by clearly indicating the expected type.
Line range hint 1-245: Verify file location relative to PR context.
This file is located in the chapter14 directory, but the PR title mentions "chapter 15, simulating water". Please verify if:
- This file should be moved to the chapter15 directory, or
- This is intentionally reusing chapter14's blend implementation for water simulation effects.
✅ Verification successful
File location is correct in chapter14
Based on the verification results:
- The blend functionality is a separate, reusable component in chapter14
- There's no duplicate or corresponding blend file in chapter15
- Chapter15 has its own water simulation implementation in a separate directory
- The blend implementation appears to be a standalone feature that can be used across chapters
The file is correctly placed in chapter14 as a reusable component, and its location doesn't need to be changed despite being referenced in a PR about chapter15's water simulation.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if there's a corresponding file in chapter15 or if other files reference this one
echo "Checking for corresponding files in chapter15..."
fd --type f "Blend.zig" "src/foundations/scenes/cgpoc/chapter15"
echo "Checking for references to this blend implementation..."
rg --type zig "scenes/cgpoc/chapter14/blend" "src/foundations/scenes/cgpoc/chapter15"
Length of output: 374
Script:
#!/bin/bash
# Let's check for any imports or references to blend functionality in chapter15
echo "Checking for blend-related imports in chapter15..."
rg --type zig "blend|Blend" "src/foundations/scenes/cgpoc/chapter15" -B 2 -A 2
# Check if there are any other blend implementations
echo "Checking for other blend implementations..."
fd "blend" "src/foundations/scenes/cgpoc"
# Check the PR description or related files for context
echo "Checking for water simulation files..."
fd "water|Water" "src/foundations/scenes/cgpoc/chapter15"
Length of output: 905
Script:
#!/bin/bash
# Let's check the content of SimulatingWater.zig to see if it uses the blend functionality
echo "Checking SimulatingWater.zig for blend usage..."
rg -A 5 -B 5 "blend|Blend" "src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWater.zig"
# Check imports in SimulatingWater.zig
echo "Checking imports in SimulatingWater.zig..."
ast-grep --pattern 'const $_ = @import("$_");' "src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWater.zig"
Length of output: 429
src/foundations/scenes/cgpoc/chapter14/clipping_plane/ClippingPlane.zig (1)
243-243: LGTM! Consider documenting blend mode implications.
The explicit type annotation improves code clarity. Since this object uses alpha blending (blend = true), ensure proper render order is maintained for correct transparency.
✅ Verification successful
Render order for transparent objects is properly handled
The codebase shows only three transparent objects (blend = true), and they are in separate scenes:
- Plane visualization in PlaneDistance scene
- Clipping plane in ClippingPlane scene (current file)
- Bobble in Blend scene
Since these transparent objects don't coexist in the same scene, there are no ordering concerns. The draw order in ClippingPlane.zig is appropriate with the plane being drawn before other objects.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if there are other transparent objects that might need ordering
rg -A 2 "mesh\.blend\s*=\s*true"
Length of output: 951
Script:
#!/bin/bash
# Check if there's a consistent render order pattern for transparent objects
rg -B 3 -A 3 "draw\(" src/foundations/scenes/cgpoc/chapter14/clipping_plane/ClippingPlane.zig
Length of output: 554
src/foundations/rhi/Texture.zig (1)
119-119: LGTM! More appropriate emoji choice.
The frame picture emoji (🖼️) is a better semantic fit for textures than the taco emoji (🌮).
src/foundations/math/rotation.zig (1)
6-10: LGTM! Well-structured Euler angles representation.
The struct follows standard conventions for 3D rotation representation with clear field names.
src/foundations/scenes/cgpoc/chapter14/textures_3d/Textures3D.zig (3)
31-32: LGTM! New fields follow consistent pattern.
The new wave_block and wave_tex fields maintain consistency with other block implementations in the struct.
134-138: LGTM! Proper initialization of wave block and shadow object.
The initialization follows the established pattern and properly sets up the wave block and its shadow object.
153-154: LGTM! Proper cleanup of wave block and texture.
The cleanup operations for wave_block and wave_tex follow the established pattern and ensure proper resource management.
Also applies to: 161-162
src/foundations/physics/camera.zig (2)
235-235: LGTM: Input handling for vertical orientation flip
The implementation follows the established pattern and correctly checks the fly mode state before triggering the flip operation.
352-375: Verify the impact on water simulation
Since this PR is about water simulation, we should verify how this camera flip affects the water rendering.
Let's check for water-related shader uniforms that might be affected by camera orientation:
✅ Verification successful
Based on the search results, I can now provide a definitive response about the camera flip's impact on water simulation:
Camera flip is intentionally used for water reflection rendering
The flipVerticalOrientation() is specifically used in the water simulation code for rendering reflections:
- It's called when rendering water reflections to flip the camera view
- The flip is properly restored after reflection rendering is complete
- The code includes safeguards (like
lock_flip) to manage the flip state - The water data is updated appropriately with the camera changes
This is a standard technique for rendering water reflections and the implementation is correct and intentional.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Search for water-related shader uniforms that use camera matrices
rg -l "uniform.*matrix.*water" --type glsl
# Search for water-related rendering code that uses camera matrices
rg "water.*camera|camera.*water" --type-add zig:*.zig
Length of output: 269
Script:
#!/bin/bash
# Let's check the water simulation code to understand how camera orientation affects it
rg -A 10 "is_under_water" --type-add 'zig:*.zig'
# Also check for any shader files that might be using camera matrices
fd '\.(glsl|vert|frag)$' -x cat {}
Length of output: 131837
Script:
#!/bin/bash
# Let's check how the camera orientation affects water rendering by examining the water simulation code
rg -A 10 "flipVerticalOrientation" --type-add 'zig:*.zig'
# Also check for any water-related code that uses camera matrices
rg "water.*camera_orientation|camera_orientation.*water" --type-add 'zig:*.zig'
Length of output: 4027
src/foundations/scenes/cgpoc/chapter15/simulating_water/skybox_vert.glsl (2)
40-40: Verify the order of matrix multiplications in f_pos calculation
Ensure that the multiplication order in the line:
vec4 f_pos = f_mvp * f_cubemap_t * f_transform * vec4(f_position.xyz, 1.0);is correct and produces the intended transformation. The order of matrix multiplication is crucial as it affects how transformations are applied to the vertex positions.
42-42: Confirm the transformation sequence for fo_skybox_tc calculation
The texture coordinates are computed as:
fo_skybox_tc = (f_transform * f_cubemap_xup * vec4(f_position.xyz, 1.0)).xyz;Please verify that the order of transformations (f_transform followed by f_cubemap_xup) aligns with the intended mapping of texture coordinates for the skybox.
src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_bot_frag.glsl (2)
31-31: Ensure correctness of parameters in f_estimate_wave_normal
Verify that the arguments 0.8, 32.0, and 2.0 passed to f_estimate_wave_normal are appropriate and align with the function's expected parameters.
18-21:
Uncomment include directives to include necessary shader code
The include directives are commented out, which will result in missing function and variable declarations such as f_camera_pos, f_materials, f_lights, and f_estimate_wave_normal. This will cause compilation errors. Please uncomment the include statements to include the necessary shader code.
Apply this diff to uncomment the include directives:
-//#include "src/foundations/shaders/camera.glsl"
-//#include "src/foundations/shaders/material.glsl"
-//#include "src/foundations/shaders/light.glsl"
-//#include "src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_wave.glsl"
+#include "src/foundations/shaders/camera.glsl"
+#include "src/foundations/shaders/material.glsl"
+#include "src/foundations/shaders/light.glsl"
+#include "src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_wave.glsl"⛔ Skipped due to learnings
Learnt from: btipling
PR: btipling/foundations#41
File: src/foundations/scenes/graphics/particles/particles_frag.glsl:8-10
Timestamp: 2024-10-25T04:49:44.473Z
Learning: In this codebase, GLSL shader files use `//#include` comments to indicate include statements that are processed by the custom includer. Do not suggest uncommenting these lines.
src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_top_frag.glsl (1)
15-18:
Uncomment necessary #include statements to resolve undefined references
The #include directives for essential shader files are commented out. This will result in undefined variables and functions such as f_camera_pos, f_lights, f_materials, and f_estimate_wave_normal. Uncomment these directives to ensure the shader compiles correctly.
Apply this diff to fix the issue:
-//#include "src/foundations/shaders/camera.glsl"
-//#include "src/foundations/shaders/material.glsl"
-//#include "src/foundations/shaders/light.glsl"
-//#include "src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_wave.glsl"
+#include "src/foundations/shaders/camera.glsl"
+#include "src/foundations/shaders/material.glsl"
+#include "src/foundations/shaders/light.glsl"
+#include "src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_wave.glsl"⛔ Skipped due to learnings
Learnt from: btipling
PR: btipling/foundations#41
File: src/foundations/scenes/graphics/particles/particles_frag.glsl:8-10
Timestamp: 2024-10-25T04:49:44.473Z
Learning: In this codebase, GLSL shader files use `//#include` comments to indicate include statements that are processed by the custom includer. Do not suggest uncommenting these lines.
src/foundations/scenes/cgpoc/chapter15/simulating_water/floor_frag.glsl (1)
14-17:
Uncomment shader includes to resolve undefined references
The include directives for essential shader files are commented out. This results in undefined references to variables and functions such as f_camera_pos, f_estimate_wave_normal, f_materials, and f_lights. Uncomment these include statements to ensure all dependencies are properly included and to prevent compilation errors.
Apply this diff to uncomment the include statements:
-//#include "src/foundations/shaders/camera.glsl"
-//#include "src/foundations/shaders/material.glsl"
-//#include "src/foundations/shaders/light.glsl"
-//#include "src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_wave.glsl"
+#include "src/foundations/shaders/camera.glsl"
+#include "src/foundations/shaders/material.glsl"
+#include "src/foundations/shaders/light.glsl"
+#include "src/foundations/scenes/cgpoc/chapter15/simulating_water/surface_wave.glsl"⛔ Skipped due to learnings
Learnt from: btipling
PR: btipling/foundations#41
File: src/foundations/scenes/graphics/particles/particles_frag.glsl:8-10
Timestamp: 2024-10-25T04:49:44.473Z
Learning: In this codebase, GLSL shader files use `//#include` comments to indicate include statements that are processed by the custom includer. Do not suggest uncommenting these lines.
src/foundations/rhi/Framebuffer.zig (2)
39-39: Attaching the depth texture in setupForColorRendering
The call to self.attachDepthTexture(depth_texture); ensures that the depth texture is properly attached to the framebuffer. This is crucial for depth-based rendering effects.
31-35: Function signature updated to include depth_texture parameter
The addition of depth_texture: Texture to the setupForColorRendering function allows for the attachment of a depth texture alongside the color texture. This is essential for rendering scenes that require depth testing.
Please ensure all calls to setupForColorRendering are updated to include the new depth_texture parameter.
You can run the following script to verify all usages of setupForColorRendering:
✅ Verification successful
Let me check the actual implementation and calls to understand the context better.
All calls to setupForColorRendering are properly updated with depth texture parameter
The verification shows that all existing calls to setupForColorRendering in the codebase are already passing both the render_texture and depth_texture parameters correctly. Both instances in SimulatingWater.zig provide the required depth texture argument, matching the updated function signature.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Find all calls to 'setupForColorRendering' and check if they pass the correct number of arguments.
rg 'setupForColorRendering\(' -B 1 -A 1
Length of output: 819
Script:
#!/bin/bash
# Get more context around the calls and implementation
rg 'setupForColorRendering' -B 5 -A 5
Length of output: 3158
src/foundations/scenes/cgpoc/chapter15/simulating_water/SimulatingWater.zig (1)
363-365: Ensure proper deinitialization of old self.lights before reassigning.
While you correctly deinitialize self.lights at line 361, make sure that any resources held by the old self.lights are fully released before overwriting it with the new lights_buf. Confirm that no references to the old self.lights remain elsewhere in the code to prevent memory leaks.
Run the following script to check for references to self.lights:
✅ Verification successful
Based on the search results, I can generate the final response as we have sufficient information. The search shows that self.lights is consistently deinitialized before reassignment across multiple similar implementations in the codebase. In the specific file under review (SimulatingWater.zig), we can see that self.lights.deinit() is properly called at line 361 before the reassignment at line 365.
The current implementation correctly handles deinitialization of self.lights
The code follows the established pattern seen throughout the codebase where self.lights is properly deinitialized before reassignment. The implementation at lines 361-365 is correct and safe:
- Line 361: Calls
self.lights.deinit()to release resources - Line 365: Assigns the new buffer
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Find references to `self.lights` outside of `updateLights` function.
# Search for occurrences of `self.lights` in the codebase, excluding `updateLights`.
rg 'self\.lights' --glob '!SimulatingWater.zig:332-366' --no-heading --line-number
Length of output: 2828
src/ft3d/Wave.zig (1)
66-68: Verify the Correctness of Index Calculation in Data Assignment
The index i used for accessing self.data.items is calculated as:
var i = w * self.dims * self.dims * self.dim;
i += h * self.dims * self.dim;
i += d * self.dim;Given the nested loops iterate over h, d, and w, please verify that this indexing correctly maps the 3D coordinates to the 1D array. An incorrect calculation could result in data being written to the wrong locations, causing unexpected behavior or crashes.
| pub const ClearWater: Material = .{ | ||
| .ambient = .{ 0.6, 0.6, 0.6, 1 }, | ||
| .diffuse = .{ 0.9, 0.9, 0.9, 1 }, | ||
| .specular = .{ 1, 1, 1, 1 }, | ||
| .shininess = 10.0, | ||
| }; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Adjust material properties for more realistic water simulation.
The current material properties might not accurately represent real water characteristics:
- The diffuse color (0.9) is too high for water, which typically absorbs more light than it diffusely reflects
- The shininess value (10.0) is too low, resulting in broad specular highlights. Water typically has sharper, more focused highlights
Consider these adjustments for more realistic water simulation:
pub const ClearWater: Material = .{
- .ambient = .{ 0.6, 0.6, 0.6, 1 },
- .diffuse = .{ 0.9, 0.9, 0.9, 1 },
+ .ambient = .{ 0.4, 0.4, 0.4, 1 },
+ .diffuse = .{ 0.3, 0.3, 0.3, 1 },
.specular = .{ 1, 1, 1, 1 },
- .shininess = 10.0,
+ .shininess = 32.0,
};📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| pub const ClearWater: Material = .{ | |
| .ambient = .{ 0.6, 0.6, 0.6, 1 }, | |
| .diffuse = .{ 0.9, 0.9, 0.9, 1 }, | |
| .specular = .{ 1, 1, 1, 1 }, | |
| .shininess = 10.0, | |
| }; | |
| pub const ClearWater: Material = .{ | |
| .ambient = .{ 0.4, 0.4, 0.4, 1 }, | |
| .diffuse = .{ 0.3, 0.3, 0.3, 1 }, | |
| .specular = .{ 1, 1, 1, 1 }, | |
| .shininess = 32.0, | |
| }; |
| out vec4 fo_frag_color; | ||
| uniform vec3 f_waterdata; | ||
|
|
||
| //#include "src/foundations/shaders/camera.glsl" |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
💡 Codebase verification
The camera.glsl include is required - uncomment it
The vertex shader uses f_camera_pos and f_mvp variables which are defined in camera.glsl. These are needed for:
- Positioning the skybox relative to camera (
f_camera_pos) - Transforming vertices with model-view-projection matrix (
f_mvp)
The commented include should be uncommented to make these variables available.
🔗 Analysis chain
Verify if camera.glsl include is needed.
The commented include directive suggests camera-related functionality might be required. If it's not needed, consider removing the comment to avoid confusion.
🏁 Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Check if camera.glsl is used in other related shaders
echo "Checking for camera.glsl usage in related shaders..."
rg -l "camera.glsl" "src/foundations/scenes/cgpoc/chapter15/simulating_water/"
Length of output: 328
Script:
#!/bin/bash
# Check contents of both vertex and fragment shaders
echo "=== Checking skybox_vert.glsl ==="
cat src/foundations/scenes/cgpoc/chapter15/simulating_water/skybox_vert.glsl
echo -e "\n=== Checking skybox_frag.glsl ==="
cat src/foundations/scenes/cgpoc/chapter15/simulating_water/skybox_frag.glsl
# Check if camera uniforms or variables are used in the shaders
echo -e "\n=== Checking for camera-related variables ==="
rg -i "camera|view|projection" src/foundations/scenes/cgpoc/chapter15/simulating_water/skybox_*.glsl
Length of output: 2709
| ```text | ||
| zig build ft3d -- --type wave --output texture3d --name wave.vol && mv -Force .\texture3d\wave.vol C:\Users\swart\AppData\Local\foundations_game_engine\textures_3d\cgpoc && zig build run | ||
| ``` |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Make the development command more portable and cross-platform compatible.
The current command contains several issues:
- Hardcoded user-specific path (
C:\Users\swart\...) makes it non-portable - PowerShell-specific syntax (
-Force) may not work on Unix-like systems
Consider using environment variables or relative paths, and providing cross-platform examples:
- zig build ft3d -- --type wave --output texture3d --name wave.vol && mv -Force .\texture3d\wave.vol C:\Users\swart\AppData\Local\foundations_game_engine\textures_3d\cgpoc && zig build run
+ # Windows (PowerShell)
+ zig build ft3d -- --type wave --output texture3d --name wave.vol && mv -Force texture3d/wave.vol $env:LOCALAPPDATA/foundations_game_engine/textures_3d/cgpoc && zig build run
+
+ # Unix-like systems
+ zig build ft3d -- --type wave --output texture3d --name wave.vol && mv texture3d/wave.vol ~/.local/share/foundations_game_engine/textures_3d/cgpoc && zig build run📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ```text | |
| zig build ft3d -- --type wave --output texture3d --name wave.vol && mv -Force .\texture3d\wave.vol C:\Users\swart\AppData\Local\foundations_game_engine\textures_3d\cgpoc && zig build run | |
| ``` | |
| ```text | |
| # Windows (PowerShell) | |
| zig build ft3d -- --type wave --output texture3d --name wave.vol && mv -Force texture3d/wave.vol $env:LOCALAPPDATA/foundations_game_engine/textures_3d/cgpoc && zig build run | |
| # Unix-like systems | |
| zig build ft3d -- --type wave --output texture3d --name wave.vol && mv texture3d/wave.vol ~/.local/share/foundations_game_engine/textures_3d/cgpoc && zig build run | |
| ``` |
| vec3 f_v1 = vec3(0.0, f_h1, -1.0); | ||
| vec3 f_v2 = vec3(-1.0, f_h2, 1.0); | ||
| vec3 f_v3 = vec3(1.0, f_h3, 1.0); | ||
| vec3 f_v4 = f_v2 - f_v1; | ||
| vec3 f_v5 = f_v3 - f_v1; | ||
| vec3 f_wn = normalize(cross(f_v4, f_v5)); | ||
| return normalize(vec3(f_wn.y, f_wn.z, f_wn.x)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Consider numerical stability and performance optimizations.
The normal calculation could benefit from some improvements:
- The magic numbers in vector construction could be made more explicit
- The cross product calculation could be optimized
- Consider adding epsilon checks for degenerate cases
- vec3 f_v1 = vec3(0.0, f_h1, -1.0);
- vec3 f_v2 = vec3(-1.0, f_h2, 1.0);
- vec3 f_v3 = vec3(1.0, f_h3, 1.0);
- vec3 f_v4 = f_v2 - f_v1;
- vec3 f_v5 = f_v3 - f_v1;
- vec3 f_wn = normalize(cross(f_v4, f_v5));
+ // Construct vectors from sample points forming a triangle
+ const float GRID_SPACING = 1.0;
+ vec3 f_v1 = vec3(0.0, f_h1, -GRID_SPACING);
+ vec3 f_v2 = vec3(-GRID_SPACING, f_h2, GRID_SPACING);
+ vec3 f_v3 = vec3(GRID_SPACING, f_h3, GRID_SPACING);
+
+ // Calculate edges and normal
+ vec3 edge1 = f_v2 - f_v1;
+ vec3 edge2 = f_v3 - f_v1;
+ vec3 f_wn = normalize(cross(edge1, edge2));
+
+ // Check for degenerate cases
+ const float EPSILON = 1e-6;
+ if (length(f_wn) < EPSILON) {
+ return vec3(0.0, 1.0, 0.0); // Default to upward normal
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| vec3 f_v1 = vec3(0.0, f_h1, -1.0); | |
| vec3 f_v2 = vec3(-1.0, f_h2, 1.0); | |
| vec3 f_v3 = vec3(1.0, f_h3, 1.0); | |
| vec3 f_v4 = f_v2 - f_v1; | |
| vec3 f_v5 = f_v3 - f_v1; | |
| vec3 f_wn = normalize(cross(f_v4, f_v5)); | |
| return normalize(vec3(f_wn.y, f_wn.z, f_wn.x)); | |
| // Construct vectors from sample points forming a triangle | |
| const float GRID_SPACING = 1.0; | |
| vec3 f_v1 = vec3(0.0, f_h1, -GRID_SPACING); | |
| vec3 f_v2 = vec3(-GRID_SPACING, f_h2, GRID_SPACING); | |
| vec3 f_v3 = vec3(GRID_SPACING, f_h3, GRID_SPACING); | |
| // Calculate edges and normal | |
| vec3 edge1 = f_v2 - f_v1; | |
| vec3 edge2 = f_v3 - f_v1; | |
| vec3 f_wn = normalize(cross(edge1, edge2)); | |
| // Check for degenerate cases | |
| const float EPSILON = 1e-6; | |
| if (length(f_wn) < EPSILON) { | |
| return vec3(0.0, 1.0, 0.0); // Default to upward normal | |
| } | |
| return normalize(vec3(f_wn.y, f_wn.z, f_wn.x)); |
| f_t_column2, | ||
| f_t_column3 | ||
| ); | ||
| Light f_light = f_lights[0]; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Address undefined variables.
The shader uses several undefined variables:
f_lights(line 30)v_matrix(line 35)f_mvp(line 41)
These are likely defined in the commented-out include files. Please ensure all required variables are properly defined.
Also applies to: 35-35, 41-41
| self.refraction_tex = render_texture; | ||
|
|
||
| var depth_texture = rhi.Texture.init(self.ctx.args.disable_bindless) catch @panic("unable to create refraction texture"); | ||
| errdefer render_texture.deinit(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct the errdefer to deinitialize depth_texture instead of render_texture.
Similarly, in the setupRefraction function at line 295, the errdefer should deinitialize depth_texture, not render_texture. This ensures that depth_texture is properly cleaned up in error scenarios.
Apply this diff to fix the issue:
var depth_texture = rhi.Texture.init(self.ctx.args.disable_bindless) catch @panic("unable to create refraction texture");
-errdefer render_texture.deinit();
+errdefer depth_texture.deinit();📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| errdefer render_texture.deinit(); | |
| errdefer depth_texture.deinit(); |
| var lights_buf = rhi.Buffer.init(ld, "lights"); | ||
| errdefer lights_buf.deinit(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid prematurely deinitializing lights_buf to prevent invalid memory access.
Similarly, the errdefer lights_buf.deinit(); will deinitialize lights_buf upon exiting the init function. Since lights_buf is assigned to self.lights at line 104, self.lights will reference deinitialized memory. Remove the errdefer to keep self.lights valid.
Apply this diff to fix the issue:
const ld: rhi.Buffer.buffer_data = .{ .lights = lights[0..] };
var lights_buf = rhi.Buffer.init(ld, "lights");
-errdefer lights_buf.deinit();📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| var lights_buf = rhi.Buffer.init(ld, "lights"); | |
| errdefer lights_buf.deinit(); | |
| var lights_buf = rhi.Buffer.init(ld, "lights"); |
| var lights_buf = rhi.Buffer.init(ld, "lights"); | ||
| errdefer lights_buf.deinit(); | ||
| self.lights = lights_buf; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Prevent deinitialization of self.lights to avoid invalid memory access.
In the updateLights function, errdefer lights_buf.deinit(); will deinitialize lights_buf when the function exits. Since lights_buf is assigned to self.lights at line 365, self.lights will point to deinitialized memory after the function returns. Remove the errdefer to ensure self.lights remains valid.
Apply this diff to fix the issue:
const ld: rhi.Buffer.buffer_data = .{ .lights = lights[0..] };
var lights_buf = rhi.Buffer.init(ld, "lights");
-errdefer lights_buf.deinit();
self.lights = lights_buf;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| var lights_buf = rhi.Buffer.init(ld, "lights"); | |
| errdefer lights_buf.deinit(); | |
| self.lights = lights_buf; | |
| var lights_buf = rhi.Buffer.init(ld, "lights"); | |
| self.lights = lights_buf; |
| self.reflection_tex = render_texture; | ||
|
|
||
| var depth_texture = rhi.Texture.init(self.ctx.args.disable_bindless) catch @panic("unable to create reflection texture"); | ||
| errdefer render_texture.deinit(); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct the errdefer to deinitialize depth_texture instead of render_texture.
At line 266 in the setupReflection function, the errdefer is incorrectly deinitializing render_texture instead of depth_texture. This can lead to depth_texture not being deinitialized properly in case of an error. Update the errdefer to reference depth_texture.
Apply this diff to fix the issue:
var depth_texture = rhi.Texture.init(self.ctx.args.disable_bindless) catch @panic("unable to create reflection texture");
-errdefer render_texture.deinit();
+errdefer depth_texture.deinit();📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| errdefer render_texture.deinit(); | |
| var depth_texture = rhi.Texture.init(self.ctx.args.disable_bindless) catch @panic("unable to create reflection texture"); | |
| errdefer depth_texture.deinit(); |
| sp.* = .{ | ||
| .noise_3d = n, | ||
| }; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Critical Issue: Overwriting existing fields in sp
The assignment sp.* = .{ .noise_3d = n, }; reinitializes the entire sp struct, potentially overwriting existing fields like dims, dim, and data with default values or undefined. This can lead to unexpected behavior since those fields may no longer hold their intended values after this operation.
To avoid this, assign only the noise_3d field directly.
Apply this diff to fix the issue:
- sp.* = .{
- .noise_3d = n,
- };
+ sp.noise_3d = n;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| sp.* = .{ | |
| .noise_3d = n, | |
| }; | |
| sp.noise_3d = n; |
Summary by CodeRabbit
Release Notes
New Features
ClearWaterandPoolWaterfor enhanced visual effects.SimulatingWatermodule, including reflection and refraction.SimulatingWaterUI.setupRenderTextureandsetupDepthTexturefunctions.Bug Fixes
Documentation
Chores
waveto the texture options.