Skip to content
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

Refactor: extract some methods of the 2D renderers from the Engine #2391

Closed
wants to merge 38 commits into from

Conversation

eyworldwide
Copy link
Member

@eyworldwide eyworldwide commented Sep 26, 2024

What kind of change does this PR introduce? (Bug fix, feature, docs update, ...)

Extract some methods of the 2D renderers from the Engine. The code of Engine should be clean!

Just like this._textDefaultFont is implemented through Font.createFromOS, it would be more reasonable for _spriteDefaultMaterial to be implemented through the static method of its renderer class.

Summary by CodeRabbit

  • New Features

    • Introduced new methods for creating materials specific to sprite masking, sprite rendering, and text rendering.
    • Added a new enum RenderQueueMaskType to categorize render queue masks.
    • Enhanced rendering capabilities with optimized material configurations for better performance.
  • Refactor

    • Centralized material creation logic from the Engine class to respective renderer classes, improving maintainability and reducing complexity.
    • Updated mask management logic for better encapsulation and rendering processes.
  • Bug Fixes

    • Removed outdated material creation methods from the Engine class to streamline functionality.

singlecoder and others added 30 commits September 2, 2024 16:20
Copy link

coderabbitai bot commented Sep 26, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces several static methods for creating materials in the SpriteMask, SpriteRenderer, and TextRenderer classes. These methods configure materials for sprite masking, sprite rendering, and text rendering, respectively. The Engine class has been updated to utilize these new methods, centralizing material creation and removing its previous material-related methods. Additionally, changes were made to the MaskManager, RenderQueue, and other components to enhance stencil state management and rendering processes.

Changes

Files Change Summary
packages/core/src/2d/sprite/SpriteMask.ts Added static method _createSpriteMaskMaterial to create a material for sprite masking.
packages/core/src/2d/sprite/SpriteRenderer.ts Added static method _createSpriteMaterial to create a material for rendering sprites with blending.
packages/core/src/2d/text/TextRenderer.ts Added static method _createTextMaterial to create a material specifically for rendering text.
packages/core/src/Engine.ts Updated imports and refactored to use new static methods for material creation; removed old material methods.
packages/core/src/RenderPipeline/MaskManager.ts Renamed properties for encapsulation, added methods for drawing and clearing masks, and updated logic for mask management.
packages/core/src/RenderPipeline/RenderQueue.ts Introduced new static properties and methods for handling stencil states and mask interactions.
packages/core/src/enums/SpriteMaskLayer.ts Added new enum value Nothing to represent a "None mask layer."
packages/core/src/index.ts Exported SpriteMaskLayer enum from the ./enums/SpriteMaskLayer module.
packages/core/src/shader/state/RenderState.ts Updated constructor to include an optional customStencilStates parameter.
packages/core/src/shader/state/StencilState.ts Enhanced _apply and _platformApply methods to accept custom states for more flexible stencil management.

Possibly related PRs

Suggested labels

enhancement, medium priority, animation

Suggested reviewers

  • GuoLei1990

Poem

🐰 In a world of sprites and text so bright,
New materials crafted, a coder's delight!
With shaders and states, they dance and play,
In the realm of rendering, they lead the way.
Hooray for the changes, let the pixels gleam,
A hop and a skip, we’re living the dream! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 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

codecov bot commented Sep 26, 2024

Codecov Report

Attention: Patch coverage is 54.07407% with 62 lines in your changes missing coverage. Please review.

Please upload report for BASE (dev/1.4@afb7423). Learn more about missing BASE report.

Files with missing lines Patch % Lines
packages/core/src/RenderPipeline/MaskManager.ts 33.33% 28 Missing ⚠️
packages/core/src/shader/state/StencilState.ts 19.04% 17 Missing ⚠️
packages/core/src/RenderPipeline/RenderQueue.ts 44.82% 16 Missing ⚠️
packages/core/src/2d/sprite/SpriteRenderer.ts 93.33% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             dev/1.4    #2391   +/-   ##
==========================================
  Coverage           ?   74.97%           
==========================================
  Files              ?      524           
  Lines              ?    27424           
  Branches           ?     4132           
==========================================
  Hits               ?    20560           
  Misses             ?     6829           
  Partials           ?       35           
Flag Coverage Δ
unittests 74.97% <54.07%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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: 3

🧹 Outside diff range and nitpick comments (2)
packages/core/src/2d/sprite/SpriteMask.ts (1)

29-39: LGTM! Consider adding JSDoc comments for better documentation.

The new static method _createSpriteMaskMaterial effectively encapsulates the creation and configuration of the sprite mask material. This aligns well with the PR objectives of extracting rendering-related functionality from the Engine class.

Consider adding JSDoc comments to describe the method's purpose, parameters, and return value. For example:

/**
 * Creates and configures a Material instance for sprite masking.
 * @param engine - The engine instance used to create the material.
 * @returns A configured Material instance for sprite masking.
 */
static _createSpriteMaskMaterial(engine): Material {
  // ... existing implementation ...
}
packages/core/src/2d/sprite/SpriteRenderer.ts (1)

31-58: Specify access modifier for _createSpriteMaterial method

The _createSpriteMaterial method does not have an access modifier specified. If this method is intended for internal use, consider marking it as private or protected to reflect its intended accessibility.

Apply this diff to specify the access modifier:

-static _createSpriteMaterial(engine: Engine, maskInteraction: SpriteMaskInteraction): Material {
+private static _createSpriteMaterial(engine: Engine, maskInteraction: SpriteMaskInteraction): Material {
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 214b8e6 and ee29a4f.

📒 Files selected for processing (4)
  • packages/core/src/2d/sprite/SpriteMask.ts (2 hunks)
  • packages/core/src/2d/sprite/SpriteRenderer.ts (2 hunks)
  • packages/core/src/2d/text/TextRenderer.ts (3 hunks)
  • packages/core/src/Engine.ts (2 hunks)
🧰 Additional context used
🪛 GitHub Check: lint
packages/core/src/2d/text/TextRenderer.ts

[failure] 12-12:
Replace ·BlendFactor,·BlendOperation,·CullMode,·RenderQueueType,·Shader,·ShaderData,·ShaderProperty· with ⏎··BlendFactor,⏎··BlendOperation,⏎··CullMode,⏎··RenderQueueType,⏎··Shader,⏎··ShaderData,⏎··ShaderProperty⏎

packages/core/src/Engine.ts

[failure] 237-237:
Insert ⏎·····


[failure] 238-238:
Replace this,·SpriteMaskInteraction.VisibleInsideMask with ⏎······this,⏎······SpriteMaskInteraction.VisibleInsideMask⏎····


[failure] 239-239:
Replace this,·SpriteMaskInteraction.VisibleOutsideMask with ⏎······this,⏎······SpriteMaskInteraction.VisibleOutsideMask⏎····

🔇 Additional comments (5)
packages/core/src/2d/sprite/SpriteMask.ts (1)

29-39: Verify the usage of the new _createSpriteMaskMaterial method.

The new static method _createSpriteMaskMaterial is not used within this file. To ensure it's properly integrated into the codebase:

  1. Confirm that this method is used in the Engine class or other relevant classes to create the sprite mask material.
  2. Verify that any previous implementation in the Engine class for creating sprite mask materials has been replaced with a call to this new method.

To help verify the integration, you can run the following script:

This will help ensure that the refactoring has been completed consistently across the codebase.

✅ Verification successful

The _createSpriteMaskMaterial method is properly integrated.

  • The new static method _createSpriteMaskMaterial is utilized within the Engine class as shown in packages/core/src/Engine.ts:
    • this._spriteMaskDefaultMaterial = SpriteMask._createSpriteMaskMaterial(this);
  • There are no remaining references to old implementations (createSpriteMaskMaterial or _spriteMaskDefaultMaterial) outside of their declarations, ensuring a clean refactoring.
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for usages of _createSpriteMaskMaterial in the codebase
rg --type typescript "_createSpriteMaskMaterial" -C 5

# Search for potential old implementations in the Engine class
rg --type typescript "class Engine" -A 50 | rg "createSpriteMaskMaterial|_spriteMaskDefaultMaterial"

Length of output: 226


Script:

#!/bin/bash
# Search for usages of _createSpriteMaskMaterial in .ts and .tsx files
rg "_createSpriteMaskMaterial" -g "*.ts" -g "*.tsx" -C 5

# Search for potential old implementations in the Engine class within .ts and .tsx files
rg "class Engine" -g "*.ts" -g "*.tsx" -A 50 | rg "createSpriteMaskMaterial|_spriteMaskDefaultMaterial"

Length of output: 2515

packages/core/src/2d/text/TextRenderer.ts (3)

Line range hint 12-24: LGTM: Import statements are correctly updated.

The new import statements for shader-related enums and the Material class are appropriately added and grouped with related imports. This change supports the new _createTextMaterial method.

🧰 Tools
🪛 GitHub Check: lint

[failure] 12-12:
Replace ·BlendFactor,·BlendOperation,·CullMode,·RenderQueueType,·Shader,·ShaderData,·ShaderProperty· with ⏎··BlendFactor,⏎··BlendOperation,⏎··CullMode,⏎··RenderQueueType,⏎··Shader,⏎··ShaderData,⏎··ShaderProperty⏎


36-51: LGTM: Well-implemented _createTextMaterial method.

This new static method effectively encapsulates the creation of a default text material, improving the separation of concerns by moving this logic from the Engine class to the TextRenderer class. The material configuration is appropriate for 2D text rendering:

  1. Uses the correct "Text" shader.
  2. Configures alpha blending for proper text transparency.
  3. Disables depth writing and culling, which is suitable for 2D rendering.
  4. Sets the render queue to transparent.
  5. Marks the material as ignored by the garbage collector, which is good for potentially shared resources.

This refactoring enhances modularity and makes the code more maintainable.


Line range hint 1-1000: Summary: Excellent refactoring of text material creation.

This change successfully refactors the creation of the default text material from the Engine class to the TextRenderer class. The new _createTextMaterial method is well-implemented and improves the separation of concerns. This refactoring enhances the modularity and maintainability of the codebase without introducing any apparent negative impacts on the existing functionality.

Great job on this clean and focused improvement!

packages/core/src/Engine.ts (1)

10-10: Appropriate import of 2D renderer classes

The addition of SpriteMask, SpriteMaskInteraction, SpriteRenderer, and TextRenderer from the "./2d" module aligns with the refactoring objective to encapsulate rendering-related functionalities within their respective classes.

packages/core/src/2d/sprite/SpriteRenderer.ts Outdated Show resolved Hide resolved
packages/core/src/2d/sprite/SpriteRenderer.ts Show resolved Hide resolved
packages/core/src/Engine.ts Outdated Show resolved Hide resolved
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: 1

🧹 Outside diff range and nitpick comments (2)
packages/core/src/Engine.ts (1)

237-250: LGTM: Default sprite materials creation refactored

The creation of default sprite materials has been successfully refactored to use SpriteRenderer._createSpriteMaterial, which aligns with the PR objective of extracting 2D renderer methods from the Engine class.

Consider adjusting the formatting slightly for consistency:

-    this._spriteDefaultMaterial = spriteDefaultMaterials[SpriteMaskInteraction.None] = SpriteRenderer._createSpriteMaterial(
-      this,
-      SpriteMaskInteraction.None
-    );
+    this._spriteDefaultMaterial = spriteDefaultMaterials[SpriteMaskInteraction.None] = SpriteRenderer._createSpriteMaterial(this, SpriteMaskInteraction.None);

Apply this change to the other two similar blocks as well for consistency.

🧰 Tools
🪛 GitHub Check: lint

[failure] 238-238:
Replace ·SpriteRenderer._createSpriteMaterial(⏎······this,⏎······SpriteMaskInteraction.None⏎···· with ⏎······SpriteRenderer._createSpriteMaterial(this,·SpriteMaskInteraction.None

packages/core/src/2d/text/TextRenderer.ts (1)

12-12: Reformat the import statement for better readability

According to the static analysis hint, reformatting the import statement on line 12 enhances readability by listing each imported item on a separate line.

Apply this diff to reformat the import statement:

-import { BlendFactor, BlendOperation, CullMode, RenderQueueType, Shader, ShaderData, ShaderProperty } from "../../shader";
+import {
+  BlendFactor,
+  BlendOperation,
+  CullMode,
+  RenderQueueType,
+  Shader,
+  ShaderData,
+  ShaderProperty
+} from "../../shader";
🧰 Tools
🪛 GitHub Check: lint

[failure] 12-12:
Replace ·BlendFactor,·BlendOperation,·CullMode,·RenderQueueType,·Shader,·ShaderData,·ShaderProperty· with ⏎··BlendFactor,⏎··BlendOperation,⏎··CullMode,⏎··RenderQueueType,⏎··Shader,⏎··ShaderData,⏎··ShaderProperty⏎

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between ee29a4f and ca9450d.

📒 Files selected for processing (4)
  • packages/core/src/2d/sprite/SpriteMask.ts (2 hunks)
  • packages/core/src/2d/sprite/SpriteRenderer.ts (2 hunks)
  • packages/core/src/2d/text/TextRenderer.ts (3 hunks)
  • packages/core/src/Engine.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/core/src/2d/sprite/SpriteMask.ts
  • packages/core/src/2d/sprite/SpriteRenderer.ts
🧰 Additional context used
🪛 GitHub Check: lint
packages/core/src/2d/text/TextRenderer.ts

[failure] 12-12:
Replace ·BlendFactor,·BlendOperation,·CullMode,·RenderQueueType,·Shader,·ShaderData,·ShaderProperty· with ⏎··BlendFactor,⏎··BlendOperation,⏎··CullMode,⏎··RenderQueueType,⏎··Shader,⏎··ShaderData,⏎··ShaderProperty⏎

packages/core/src/Engine.ts

[failure] 238-238:
Replace ·SpriteRenderer._createSpriteMaterial(⏎······this,⏎······SpriteMaskInteraction.None⏎···· with ⏎······SpriteRenderer._createSpriteMaterial(this,·SpriteMaskInteraction.None

🔇 Additional comments (2)
packages/core/src/Engine.ts (2)

10-10: LGTM: Import statements updated to support refactoring

The new imports for SpriteMask, SpriteMaskInteraction, SpriteRenderer, and TextRenderer from "./2d" align with the PR objective of extracting 2D renderer methods from the Engine class.


253-254: LGTM: Default text and sprite mask materials creation refactored

The creation of default text and sprite mask materials has been successfully refactored to use TextRenderer._createTextMaterial and SpriteMask._createSpriteMaskMaterial respectively. This change aligns with the PR objective of extracting 2D renderer methods from the Engine class and improves code organization.

Comment on lines +36 to +51
static _createTextMaterial(engine: Engine): Material {
const material = new Material(engine, Shader.find("Text"));
const renderState = material.renderState;
const target = renderState.blendState.targetBlendState;
target.enabled = true;
target.sourceColorBlendFactor = BlendFactor.SourceAlpha;
target.destinationColorBlendFactor = BlendFactor.OneMinusSourceAlpha;
target.sourceAlphaBlendFactor = BlendFactor.One;
target.destinationAlphaBlendFactor = BlendFactor.OneMinusSourceAlpha;
target.colorBlendOperation = target.alphaBlendOperation = BlendOperation.Add;
renderState.depthState.writeEnabled = false;
renderState.rasterState.cullMode = CullMode.Off;
renderState.renderQueueType = RenderQueueType.Transparent;
material.isGCIgnored = true;
return material;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use TypeScript access modifiers instead of underscore prefixes

The method _createTextMaterial uses an underscore prefix to indicate it's intended for internal use. In TypeScript, it's recommended to use the private or protected access modifiers to enforce encapsulation rather than relying on naming conventions.

Apply this diff to make the method private:

-static _createTextMaterial(engine: Engine): Material {
+private static _createTextMaterial(engine: Engine): Material {

Committable suggestion was skipped due to low confidence.

@eyworldwide eyworldwide changed the base branch from main to dev/1.4 September 26, 2024 07:33
@eyworldwide
Copy link
Member Author

eyworldwide commented Sep 26, 2024

see: singlecoder#15

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.

4 participants