Skip to content

Conversation

btipling
Copy link
Owner

@btipling btipling commented Sep 22, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new dolphin rendering scene, enhancing visual diversity.
    • Added support for multiple light sources in shaders, improving lighting effects.
    • Implemented new fragment and vertex shaders for Blinn-Phong lighting and texture handling.
    • Enhanced shader attachment logic to accommodate additional fragment shader types.
  • Bug Fixes

    • Updated shader paths to ensure correct shader files are used.
  • Refactor

    • Improved shader handling logic to accommodate new fragment shader types and enhance performance.
    • Streamlined lighting calculations in shaders for better flexibility.
  • Chores

    • Cleaned up unused shader files and declarations for better maintainability.

Copy link

coderabbitai bot commented Sep 22, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes include the addition of new shaders, modifications to existing shaders, and updates to scene management in the rendering pipeline. A new Dolphin object is introduced for rendering, with associated shaders and resource management functions. The fragment and vertex shaders are updated to accommodate multiple light sources and ambient lighting. Additionally, the initialization of scenes is altered to include the new seven_dolphin type, enhancing the overall rendering capabilities of the application.

Changes

Files Change Summary
src/foundations/rhi/Shader.zig Added constant frag_texture_header and modified shader attachment logic for .texture.
src/foundations/scenes/cgpoc/chapter6/shuttle/Shuttle.zig Updated embedded vertex shader file path.
src/foundations/scenes/cgpoc/chapter7/chapter7.zig Added import statement for Dolphin.
src/foundations/scenes/cgpoc/chapter7/dolphin/Dolphin.zig Introduced Dolphin object with rendering functionality, including methods for navigation, initialization, deinitialization, drawing, and rendering.
src/foundations/scenes/cgpoc/chapter7/dolphin/blinn_phong_frag.glsl New fragment shader for Blinn-Phong lighting.
src/foundations/scenes/cgpoc/chapter7/lighting/blinn_phong_frag.glsl Modified lighting calculations to support multiple light sources and ambient light.
src/foundations/scenes/cgpoc/chapter7/lighting/phong_frag.glsl Updated lighting calculations to accommodate multiple light sources and ambient light.
src/foundations/shaders/frag_bindless.glsl Removed bindless sampler layout declaration.
src/foundations/shaders/frag_bindless_header.glsl Added bindless sampler layout declaration.
src/foundations/shaders/frag_blinn_phong_lighting.glsl Modified lighting functions to handle multiple light sources and ambient light.
src/foundations/shaders/frag_texture.glsl Removed layout binding declaration for uniform sampler.
src/foundations/shaders/frag_texture_header.glsl Added uniform sampler2D variable declaration.
src/foundations/shaders/i_obj_vert.glsl Updated position calculation in vertex shader.
src/foundations/shaders/i_obj_wavefront_vert.glsl Deleted file containing vertex shader function.
src/foundations/shaders/lighting.glsl Updated lighting functions to accept more light sources and ambient light parameters.
src/foundations/ui/ui_state.zig Added seven_dolphin scene type and corresponding entry in the scenes union.

Possibly related PRs

Poem

In the meadow where shaders bloom,
A dolphin dances, dispelling gloom.
With lights aglow and textures bright,
Rendering magic, a wondrous sight!
Hopping through code, a rabbit's delight,
Celebrating changes, oh what a night! 🐇✨


Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    -- I pushed a fix in commit <commit_id>, please review it.
    -- Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    -- @coderabbitai generate unit testing code for this file.
    -- @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    -- @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    -- @coderabbitai read src/utils.ts and generate unit testing code.
    -- @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    -- @coderabbitai help me debug CodeRabbit configuration file.

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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 15

Outside diff range and nitpick comments (5)
src/foundations/scenes/cgpoc/chapter7/dolphin/blinn_phong_frag.glsl (3)

5-5: Consider using a dynamic array or a smaller fixed size for f_ls.

The local array f_ls is initialized with a fixed size of 10, but only the first element is used in the code. If the actual number of lights needed is much smaller, this could be wasteful in terms of performance and memory usage.

Consider using a dynamic array or a smaller fixed size based on the actual number of lights required for the scene.


8-8: Consider making the global ambient color configurable or adjusting the values.

The global ambient color is currently hardcoded with RGB values of (0.7, 0.7, 0.7), which results in a relatively bright ambient light. This might not be suitable for all scenes or lighting conditions and could wash out the details and contrast of the rendered object.

Consider making the global ambient color configurable or adjusting the values based on the specific requirements of the scene to achieve the desired visual outcome.


9-9: Consider making the blending factors configurable or adaptable.

The current code equally weights the texture color and the lighting contribution (0.5 each) in the final fragment color. While this might produce acceptable results in some cases, it might not always be the desired visual outcome, depending on the specific material properties, lighting conditions, and artistic intent.

Consider making the blending factors configurable or adaptable based on the material properties and the desired visual style. This could provide more flexibility and control over the final appearance of the rendered object.

src/foundations/scenes/cgpoc/chapter7/dolphin/blinn_phong_vert.glsl (1)

10-10: Clarify the purpose of f_xup.

The normal matrix calculation is correct. However, please provide more context on the purpose and origin of f_xup to improve code readability and maintainability.

src/foundations/scenes/cgpoc/chapter7/dolphin/Dolphin.zig (1)

101-101: Consider implementing or removing the empty updateCamera function

The updateCamera function is currently empty. If it's intended for future use, add a TODO comment specifying the planned implementation. If not needed, consider removing it to clean up the code.

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b14514f and a62a711.

Files selected for processing (18)
  • src/foundations/rhi/Shader.zig (2 hunks)
  • src/foundations/scenes/cgpoc/chapter6/shuttle/Shuttle.zig (1 hunks)
  • src/foundations/scenes/cgpoc/chapter7/chapter7.zig (1 hunks)
  • src/foundations/scenes/cgpoc/chapter7/dolphin/Dolphin.zig (1 hunks)
  • src/foundations/scenes/cgpoc/chapter7/dolphin/blinn_phong_frag.glsl (1 hunks)
  • src/foundations/scenes/cgpoc/chapter7/dolphin/blinn_phong_vert.glsl (1 hunks)
  • src/foundations/scenes/cgpoc/chapter7/lighting/blinn_phong_frag.glsl (1 hunks)
  • src/foundations/scenes/cgpoc/chapter7/lighting/phong_frag.glsl (1 hunks)
  • src/foundations/scenes/scenes.zig (1 hunks)
  • src/foundations/shaders/frag_bindless.glsl (0 hunks)
  • src/foundations/shaders/frag_bindless_header.glsl (1 hunks)
  • src/foundations/shaders/frag_blinn_phong_lighting.glsl (1 hunks)
  • src/foundations/shaders/frag_texture.glsl (0 hunks)
  • src/foundations/shaders/frag_texture_header.glsl (1 hunks)
  • src/foundations/shaders/i_obj_vert.glsl (1 hunks)
  • src/foundations/shaders/i_obj_wavefront_vert.glsl (0 hunks)
  • src/foundations/shaders/lighting.glsl (2 hunks)
  • src/foundations/ui/ui_state.zig (2 hunks)
Files not reviewed due to no reviewable changes (3)
  • src/foundations/shaders/frag_bindless.glsl
  • src/foundations/shaders/frag_texture.glsl
  • src/foundations/shaders/i_obj_wavefront_vert.glsl
Additional comments not posted (22)
src/foundations/shaders/frag_texture_header.glsl (1)

2-2: LGTM!

The addition of the uniform sampler2D f_samp variable bound to location 0 is a necessary step towards supporting textures in the lighting models, which aligns with the PR objective.

Ensure that the application code sets up the texture correctly and binds it to the same texture unit (0) before rendering.

src/foundations/shaders/frag_bindless_header.glsl (1)

3-3: LGTM!

The new uniform variable f_samp with the bindless_sampler layout qualifier is declared correctly. This change enhances the shader's capability to utilize bindless textures, allowing for more efficient texture sampling. It aligns well with the PR objective of supporting lighting models with textures.

src/foundations/scenes/cgpoc/chapter7/chapter7.zig (1)

2-2: LGTM!

The import statement for the Dolphin component is syntactically correct and follows the expected pattern for importing a component from a separate file.

The public visibility of the constant is appropriate if the Dolphin component is intended to be used by other modules that import this file.

src/foundations/shaders/i_obj_vert.glsl (1)

10-10: Verify the intended behavior of the additional transformation.

The change incorporates an additional multiplication by f_xup matrix, which affects the final position of the vertex. This appears to be an intentional change to support lighting models with textures, as mentioned in the PR objectives.

Please verify that the change produces the intended behavior and does not introduce any unintended side effects. Consider adding a test case to ensure the correctness of the transformation.

src/foundations/scenes/cgpoc/chapter7/dolphin/blinn_phong_frag.glsl (4)

6-6: Verify the initialization of the f_lights array.

Ensure that the f_lights array is properly initialized and contains at least one element before accessing it. If the array is empty or not properly initialized, it could lead to undefined behavior or rendering issues.

Run the following script to verify the initialization:

#!/bin/bash
# Description: Verify the initialization of the `f_lights` array.

# Test: Search for the declaration and initialization of `f_lights`. Expect: At least one occurrence.
rg --type glsl $'f_lights'

9-9: Verify the implementation and correctness of the f_blinn_phong_lighting function.

Ensure that the f_blinn_phong_lighting function is properly implemented and returns the expected lighting contribution based on the provided material, light array, light count, and global ambient color. Incorrect implementation could lead to incorrect lighting or visual artifacts in the rendered output.

Run the following script to verify the implementation:

#!/bin/bash
# Description: Verify the implementation of the `f_blinn_phong_lighting` function.

# Test: Search for the definition of the `f_blinn_phong_lighting` function. Expect: One occurrence.
ast-grep --lang glsl --pattern $'f_blinn_phong_lighting($_, $_, $_, $_) {
  $$$
}'

4-4: Verify the initialization of the f_materials array.

Ensure that the f_materials array is properly initialized and contains at least one element before accessing it. If the array is empty or not properly initialized, it could lead to undefined behavior or rendering issues.

Run the following script to verify the initialization:


7-7: Verify the setup of the sampler and texture coordinates.

Ensure that the f_samp sampler and f_tc texture coordinates are properly initialized and valid before using them for texture sampling. Incorrect setup could lead to visual artifacts or unexpected appearance of the rendered object.

Run the following script to verify the setup:

Verification successful

Further verify the declarations of f_samp and f_tc by searching the entire codebase.

Please run the following scripts to search for the declarations and initializations of f_samp and f_tc without restricting the file type:


Correct the shell script syntax and retry searching for f_samp and f_tc.

Please run the following corrected scripts to search for the declarations and initializations of f_samp and f_tc across all files:


Correct the shell script syntax and retry searching for f_samp and f_tc.

Please run the following corrected scripts to search for the declarations and initializations of f_samp and f_tc across all files:


Sampler and texture coordinates are properly set up and used.

The verification process has confirmed that both f_samp (sampler) and f_tc (texture coordinates) are correctly initialized and used throughout the codebase. The sampler is properly set up in the Zig code before being used in shaders, and the texture coordinates are correctly passed between vertex and fragment shaders. There are no apparent issues with their implementation or usage.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the setup of the sampler and texture coordinates.

# Test: Search for the declaration and initialization of `f_samp` and `f_tc`. Expect: At least one occurrence each.
rg --type glsl $'f_samp'
rg --type glsl $'f_tc'

Length of output: 192


Script:

#!/bin/bash
# Description: Search for declarations and initializations of `f_samp` and `f_tc` across all files.

# Search for `f_samp`
rg 'sampler|'f_samp' -A 2

# Search for `f_tc`
rg 'vec[234]|f_tc' -A 2

Length of output: 93


Script:

#!/bin/bash
# Description: Search for declarations and initializations of `f_samp` and `f_tc` across all files.

# Search for `f_samp`
rg "sampler|f_samp" -A 2

# Search for `f_tc`
rg "vec[234]|f_tc" -A 2

Length of output: 149555


Script:

#!/bin/bash
# Description: Search for declarations and initializations of `f_samp` and `f_tc` across all files.

# Search for `f_samp`
rg "sampler|f_samp" -A 2

# Search for `f_tc`
rg "vec[234]|f_tc" -A 2

Length of output: 149555

src/foundations/scenes/cgpoc/chapter7/dolphin/blinn_phong_vert.glsl (3)

2-9: LGTM!

The transformation matrix is constructed correctly using the provided input vectors.


12-14: LGTM!

The vertex position and normals are transformed correctly and assigned to the appropriate output variables.


16-17: LGTM!

The final clip space position and texture coordinates are computed and assigned correctly.

src/foundations/scenes/scenes.zig (1)

23-23: Provide more context about the seven_dolphin scene.

The change from seven_lighting to seven_dolphin aligns with the PR objectives of supporting lighting models with textures. However, it would be helpful to provide more information about the specific configuration and features of the seven_dolphin scene.

  • How does the seven_dolphin scene differ from the seven_lighting scene in terms of its lighting models and texture support?
  • What specific improvements or additions does the seven_dolphin scene bring to the project?

Providing this context will help reviewers better understand the purpose and impact of this change.

src/foundations/ui/ui_state.zig (2)

35-35: LGTM!

The addition of the seven_dolphin enum value to the scene_type enum is consistent with the existing code and aligns with the PR objective of supporting lighting models with textures.


72-72: Verify the usage of the new seven_dolphin scene type and Dolphin structure.

The addition of the seven_dolphin union entry to the scenes union is consistent with the existing code and aligns with the PR objective of supporting lighting models with textures. However, please ensure that the corresponding changes have been made in other parts of the codebase to handle the rendering and management of the new Dolphin scene.

Run the following script to verify the usage of the new scene type and structure:

Verification successful

Usage of the new seven_dolphin scene type and Dolphin structure verified.

The seven_dolphin scene type is properly initialized and utilized in both ui_state.zig and scenes.zig. Additionally, the Dolphin structure from scenes_list.cgpoc.chapter7 is correctly referenced in ui_state.zig. No further modifications are necessary.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new `seven_dolphin` scene type and `Dolphin` structure.

# Test 1: Search for the usage of the `seven_dolphin` scene type. Expect: At least one occurrence.
rg --type zig $'seven_dolphin'

# Test 2: Search for the usage of the `Dolphin` structure. Expect: At least one occurrence.
rg --type zig $'scenes_list\.cgpoc\.chapter7\.Dolphin'

Length of output: 406

src/foundations/scenes/cgpoc/chapter6/shuttle/Shuttle.zig (1)

9-9: Verify the impact of the vertex shader change.

The change in the vertex shader file path looks good. However, please ensure that the new vertex shader (i_obj_vert.glsl) is compatible with the rest of the code and produces the desired visual output for the shuttle object.

Run the following script to verify the rendering of the shuttle object:

Please visually inspect the rendered shuttle object to confirm that it appears as expected with the new vertex shader.

src/foundations/rhi/Shader.zig (2)

52-52: LGTM!

The addition of the frag_texture_header constant follows the existing pattern and naming convention for fragment shader headers. The embedded GLSL code will be used to support a new type of fragment shader for handling textures.


101-103: Looks good!

The new conditional branch correctly handles the .texture fragment shader type by adding the frag_texture_header to the shader source. This change is consistent with the existing logic for other shader types and ensures that the appropriate header is included for texture shaders.

src/foundations/shaders/frag_blinn_phong_lighting.glsl (1)

9-9: Function call to f_blinn_phong_lighting appears correct

The updated function call to f_blinn_phong_lighting includes the light array f_ls, the number of lights 1, and the global ambient light f_global_ambient. This aligns with the changes made for supporting multiple lights and ambient lighting.

src/foundations/scenes/cgpoc/chapter7/lighting/blinn_phong_frag.glsl (1)

14-14: Verify the correct usage of f_blinn_phong_lighting with new parameters

The function call to f_blinn_phong_lighting now includes additional parameters. Ensure that the function definition is updated accordingly and that all its internal logic handles these changes correctly.

Run the following script to check the function definition:

Verification successful

Verified: f_blinn_phong_lighting usage and implementation are correct

The function f_blinn_phong_lighting is correctly defined with the updated parameters: Material, Light[], uint, and vec4. The internal logic appropriately handles the additional vec4 f_ambient parameter, ensuring accurate lighting calculations.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Locate the definition of `f_blinn_phong_lighting` and verify its parameters.

# Expected: Function signature matches the updated call with parameters (Material, Light[], int, vec4).
rg --type-add glsl:'*.glsl' -tglsl "vec4 f_blinn_phong_lighting" -A 2

Length of output: 372


Script:

#!/bin/bash
# Description: Retrieve the full definition and implementation of `f_blinn_phong_lighting` to verify the handling of additional parameters.

rg --type-add glsl:'*.glsl' -A 20 "vec4 f_blinn_phong_lighting" src/foundations/shaders/lighting.glsl

Length of output: 959


Script:

#!/bin/bash
# Description: Retrieve the remaining lines of the `f_blinn_phong_lighting` function to complete the verification of parameter handling.

rg --type-add glsl:'*.glsl' -A 50 "vec4 f_blinn_phong_lighting" src/foundations/shaders/lighting.glsl

Length of output: 1893

src/foundations/scenes/cgpoc/chapter7/lighting/phong_frag.glsl (2)

15-15: Verify the correctness of num_lights parameter in f_phong_lighting.

Ensure that the third argument passed to f_phong_lighting accurately reflects the number of initialized lights in f_ls to prevent unintended behavior.

Run the following script to confirm that the num_lights parameter matches the number of initialized lights:

#!/bin/bash
# Description: Check that the num_lights parameter equals the number of initialized lights.

# Count the number of initialized lights in f_ls
initialized_lights=$(rg --type glsl -o 'f_ls\[\d+\]' src/foundations/scenes/cgpoc/chapter7/lighting/ | sort | uniq | wc -l)

# Extract the num_lights argument passed to f_phong_lighting
num_lights=$(rg --type glsl 'f_phong_lighting\([^,]+, [^,]+, (\d+),' src/foundations/scenes/cgpoc/chapter7/lighting/ | grep -oP '\d+')

echo "Initialized lights: $initialized_lights"
echo "Num lights in function call: $num_lights"

# Expected: The numbers should match.

8-13: Ensure consistency in light source initialization.

While you've initialized two light sources, make sure that any future additions to f_ls are handled appropriately to prevent potential out-of-bounds errors or uninitialized data when num_lights increases.

Run the following script to check for any references to f_ls beyond the initialized indices:

src/foundations/shaders/lighting.glsl (1)

55-55: Verify Consistency of Specular Exponent Calculation

In f_blinn_phong_lighting, the specular exponent is calculated using f_mat.shininess * 4.0, whereas in f_phong_lighting, it's calculated with f_mat.shininess alone. Please confirm if this discrepancy is intentional to ensure consistent lighting effects.

Also applies to: 80-80

Comment on lines +5 to +6
Light f_ls[10];
f_ls[0] = f_lights[0];
Copy link

@coderabbitai coderabbitai bot Sep 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Initialize all lights or adjust the array size

The array f_ls is declared with a fixed size of 10, but only f_ls[0] is initialized. If the lighting calculations utilize other elements of the array, there is a risk of accessing uninitialized data. Consider initializing all elements of f_ls or adjusting the array size to match the actual number of lights.

Apply this diff to adjust the array size:

-Light f_ls[10];
+Light f_ls[1];

Or, if you intend to support multiple lights, initialize all required lights:

const int NUM_LIGHTS = 10;
Light f_ls[NUM_LIGHTS];
for (int i = 0; i < NUM_LIGHTS; ++i) {
    f_ls[i] = f_lights[i];
}

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@coderabbitai I supply a number arg to f_blinn_phong_lighting

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@btipling, thank you for the clarification. I recall that in this codebase, arrays like f_ls are declared with larger sizes to accommodate future use, and the actual number of active lights is supplied to f_blinn_phong_lighting. My apologies for the oversight; I'll keep this in mind for future reviews.


Learnings used
Learnt from: btipling
PR: btipling/foundations#35
File: src/foundations/scenes/cgpoc/chapter7/lighting/phong_frag.glsl:0-0
Timestamp: 2024-09-23T00:22:00.064Z
Learning: In the codebase, arrays like `f_ls` for light sources may be declared with larger sizes (e.g., `Light f_ls[10]`) to accommodate future use of additional lights. The actual number of active lights is supplied as an argument to functions like `f_phong_lighting`.


fo_frag_color = f_blinn_phong_lighting(f_m, f_l);
vec4 f_global_ambient = vec4(0.7, 0.7, 0.7, 1.0);
Copy link

@coderabbitai coderabbitai bot Sep 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider making f_global_ambient a uniform variable

Currently, f_global_ambient is hardcoded within the shader. To provide greater flexibility and allow dynamic adjustment of ambient light, consider declaring f_global_ambient as a uniform variable. This change enables you to modify the ambient light from your application without altering the shader code.

Apply this diff to declare f_global_ambient as a uniform:

-    vec4 f_global_ambient = vec4(0.7, 0.7, 0.7, 1.0);
+    uniform vec4 f_global_ambient;

Then, set the uniform value from your application code as needed.

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.

Suggested change
vec4 f_global_ambient = vec4(0.7, 0.7, 0.7, 1.0);
uniform vec4 f_global_ambient;

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@btipling Great, thank you for fixing the issue!

(_/)
( •_•)
🐇

fo_frag_color = f_blinn_phong_lighting(f_m, f_ls, f_l_dirs);
Light f_ls[10];
f_ls[0] = f_lights[0];
f_ls[0].direction = vec4(fo_light_1_dir, 1.0);
Copy link

@coderabbitai coderabbitai bot Sep 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incorrect w-component for directional light vectors

Setting the w-component to 1.0 denotes a positional vector, not a directional one. For directional lights, the w-component should be 0.0 to represent a vector at infinity.

Apply this diff to fix the w-component:

-f_ls[0].direction = vec4(fo_light_1_dir, 1.0);
+f_ls[0].direction = vec4(fo_light_1_dir, 0.0);

-f_ls[1].direction = vec4(fo_light_2_dir, 1.0);
+f_ls[1].direction = vec4(fo_light_2_dir, 0.0);

Also applies to: 12-12

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@btipling Thank you for fixing the issue in commit 02cf5c1!

((^o^)/)

Light f_ls[2] = Light[2](f_lights[0], f_lights[1]);
vec3 f_l_dirs[2] = vec3[2](fo_light_1_dir, fo_light_2_dir);
fo_frag_color = f_blinn_phong_lighting(f_m, f_ls, f_l_dirs);
Light f_ls[10];
Copy link

@coderabbitai coderabbitai bot Sep 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Uninitialized elements in the light array may cause issues

Only the first two elements of f_ls are initialized, while the remaining entries are uninitialized. If f_blinn_phong_lighting accesses these uninitialized elements, it could lead to undefined behavior or errors.

Consider resizing the light array to match the number of lights in use:

-Light f_ls[10];
+Light f_ls[2];

Alternatively, ensure all elements of f_ls are properly initialized before use.

Also applies to: 14-14

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I supply a number arg to f_blinn_phong_lighting

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@btipling, thank you for the clarification. Since you're supplying the number of lights to f_blinn_phong_lighting, and the function uses this argument to limit access to the array, uninitialized elements in f_ls should not cause any issues. I appreciate the explanation.

(_/)
(o.O)
( )


Learnings added
Learnt from: btipling
PR: btipling/foundations#35
File: src/foundations/scenes/cgpoc/chapter7/lighting/blinn_phong_frag.glsl:8-8
Timestamp: 2024-09-23T00:22:35.464Z
Learning: In GLSL shaders, when passing an array to functions like `f_blinn_phong_lighting` along with a count parameter, it's acceptable to have uninitialized elements in the array as long as the function uses the count to limit access to the initialized elements.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

f_ls[0].direction = vec4(fo_light_1_dir, 1.0);
f_ls[1] = f_lights[1];
f_ls[1].direction = vec4(fo_light_2_dir, 1.0);
vec4 f_global_ambient = vec4(0.7, 0.7, 0.7, 1.0);
Copy link

@coderabbitai coderabbitai bot Sep 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make f_global_ambient a uniform for flexibility

Hardcoding the global ambient light limits flexibility. By declaring f_global_ambient as a uniform, you allow the ambient light to be configured externally, accommodating different scenes and lighting conditions.

Apply this diff to adjust f_global_ambient:

-vec4 f_global_ambient = vec4(0.7, 0.7, 0.7, 1.0);
+uniform vec4 f_global_ambient;

Remember to set f_global_ambient from the application code supplying shader uniforms.

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.

Suggested change
vec4 f_global_ambient = vec4(0.7, 0.7, 0.7, 1.0);
uniform vec4 f_global_ambient;

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@btipling, thanks for fixing this!

(_/)
( ^.^ )
(") (")

vec3 f_H = normalize(f_L + f_V).xyz;

float cosTheta = dot(f_L, f_N);
float cosPhi = dot(f_H, f_N);

vec4 f_global_ambient = vec4(0.7, 0.7, 0.7, 1.0);
vec3 f_ambient = ((f_global_ambient * f_mat.ambient) + (f_light.ambient * f_mat.ambient)).xyz;
vec3 f_ambient = ((f_ambient * f_mat.ambient) + (f_light.ambient * f_mat.ambient)).xyz;
Copy link

@coderabbitai coderabbitai bot Sep 22, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Avoid Shadowing the Parameter f_ambient

The local variable f_ambient declared inside the function shadows the parameter f_ambient. This can lead to confusion and potential bugs. Consider renaming the local variable to avoid shadowing.

Apply this diff to fix the issue:

- vec3 f_ambient = ((f_ambient * f_mat.ambient) + (f_light.ambient * f_mat.ambient)).xyz;
+ vec3 ambient_light = ((f_ambient * f_mat.ambient) + (f_light.ambient * f_mat.ambient)).xyz;

Update subsequent references to f_ambient within the function to ambient_light.

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.

Suggested change
vec3 f_ambient = ((f_ambient * f_mat.ambient) + (f_light.ambient * f_mat.ambient)).xyz;
vec3 ambient_light = ((f_ambient * f_mat.ambient) + (f_light.ambient * f_mat.ambient)).xyz;

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@btipling, glad to see the issue has been fixed!

(^.^/)

Comment on lines +21 to +77
pub fn init(allocator: std.mem.Allocator, ctx: scenes.SceneContext) *Dolphin {
const pd = allocator.create(Dolphin) catch @panic("OOM");
errdefer allocator.destroy(pd);
const integrator = physics.Integrator(physics.SmoothDeceleration).init(.{});
const cam = physics.camera.Camera(*Dolphin, physics.Integrator(physics.SmoothDeceleration)).init(
allocator,
ctx.cfg,
pd,
integrator,
.{ 0, 2, -3 },
std.math.pi - std.math.pi / 4.0,
);
errdefer cam.deinit(allocator);

const mats = [_]lighting.Material{
.{
.ambient = [4]f32{ 0.2, 0.2, 0.2, 1.0 },
.diffuse = [4]f32{ 0.8, 0.8, 0.8, 1.0 },
.specular = [4]f32{ 0.5, 0.5, 0.5, 1.0 },
.shininess = 32.0,
},
};

const bd: rhi.Buffer.buffer_data = .{ .materials = mats[0..] };
var mats_buf = rhi.Buffer.init(bd);
errdefer mats_buf.deinit();

const lights = [_]lighting.Light{
.{
.ambient = [4]f32{ 0.1, 0.1, 0.1, 1.0 },
.diffuse = [4]f32{ 1.0, 1.0, 1.0, 1.0 },
.specular = [4]f32{ 1.0, 1.0, 1.0, 1.0 },
.location = [4]f32{ 0.0, 0.0, 0.0, 1.0 },
.direction = [4]f32{ 0.75, -0.5, -0.5, 0.0 },
.cutoff = 0.0,
.exponent = 0.0,
.attenuation_constant = 1.0,
.attenuation_linear = 0.0,
.attenuation_quadratic = 0.0,
.light_kind = .direction,
},
};
const ld: rhi.Buffer.buffer_data = .{ .lights = lights[0..] };
var lights_buf = rhi.Buffer.init(ld);
errdefer lights_buf.deinit();

pd.* = .{
.allocator = allocator,
.view_camera = cam,
.dolphin_texture = null,
.ctx = ctx,
.materials = mats_buf,
.lights = lights_buf,
};
pd.renderDolphin();
return pd;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review error handling and use of errdefer in init function

The init function employs errdefer statements for resource cleanup, but it does not return an error type. If an error occurs (e.g., allocator.create(Dolphin) fails and panics), the errdefer statements won't execute because panicking bypasses them. This can lead to resource leaks.

Consider refactoring the function to return an error type and handle errors appropriately. This ensures that errdefer statements execute for proper resource cleanup.

Apply this diff to adjust the function signature and error handling:

-pub fn init(allocator: std.mem.Allocator, ctx: scenes.SceneContext) *Dolphin {
+pub fn init(allocator: std.mem.Allocator, ctx: scenes.SceneContext) !*Dolphin {
     const pd = allocator.create(Dolphin) catch return error.OutOfMemory;
     errdefer allocator.destroy(pd);
     // ... additional error handling for other operations ...
     return pd;
 }

Ensure that all fallible operations within init are properly handled, and propagate errors using !.

Committable suggestion was skipped due to low confidence.

@btipling btipling merged commit 046c5cc into main Sep 23, 2024
@btipling btipling deleted the bt/dolphin branch September 23, 2024 01:38
@coderabbitai coderabbitai bot mentioned this pull request Sep 23, 2024
@coderabbitai coderabbitai bot mentioned this pull request Oct 5, 2024
@coderabbitai coderabbitai bot mentioned this pull request Nov 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant