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

Differentiate Random Stats by Random Make Type #302

Merged
merged 13 commits into from
Feb 8, 2025

Conversation

Zintixx
Copy link
Collaborator

@Zintixx Zintixx commented Feb 7, 2025

Summary by CodeRabbit

  • New Features

    • Enhanced item customization by supporting multiple variations and weighted options, providing a broader range of attribute differences.
    • Introduced a new enumeration for randomization types to improve item metadata handling.
    • Improved randomization logic for item stats to ensure more consistent and reliable outcomes.
  • Refactor

    • Streamlined type handling and error messaging for smoother attribute changes.
    • Simplified method signatures for better usability in random option retrieval.
  • Chores

    • Upgraded an underlying dependency to boost system stability.

Copy link
Contributor

coderabbitai bot commented Feb 7, 2025

Walkthrough

This pull request comprises updates across various components. The Maple2.File.Ingest project now references a newer parser version. In mapper files, explicit type casting and changes to collection types enable multiple item variations. Model components have been updated with a new RandomMakeType enum, revised metadata fields, and table structures now using arrays and a new Set<T> record. Server-side changes refactor error handling in scroll processing and simplify random option processing by updating method signatures and introducing helper functions.

Changes

File(s) Change Summary
Maple2.File.Ingest/...csproj Updated Maple2.File.Parser.Tadeucci package version from 2.2.0 to 2.2.1.
Maple2.File.Ingest/Mapper/(ItemMapper.cs, TableMapper.cs) In ItemMapper, added explicit casting for RandomType; in TableMapper, updated variation collections from single Range instances to lists/arrays.
Maple2.Model/(Enum/ItemOptionMakeType.cs, Metadata/ItemMetadata.cs, Metadata/Table/ItemOptionTable.cs) Introduced new enum RandomMakeType; updated ItemMetadataOption type from int to RandomMakeType; revised variation table records to use arrays and added new Set<T> record.
Maple2.Server.Game/(PacketHandlers/ChangeAttributesScrollHandler.cs, Util/ItemStatsCalculator.cs) Refactored error handling to use ChangeAttributesScrollError and updated random option processing with revised method signatures and helper functions.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant ISC as ItemStatsCalculator
    participant GV as GetValue (Helper)
    participant GIV as GetItemVariationValue (Helper)
    
    C->>ISC: Call RandomizeValues(type, itemOption, itemMetadata, ref option, rollMax)
    ISC->>GV: Compute value based on item metadata and random type
    GV-->>ISC: Return computed value
    ISC->>GIV: Calculate item variation details using computed value
    GIV-->>ISC: Return updated variation option
    ISC-->>C: Return modified ItemStats.Option
Loading

Possibly related PRs

Suggested reviewers

  • AngeloTadeucci

Poem

I'm a rabbit coding fast,
Hopping through changes made to last.
New types and arrays now lead the way,
With errors handled in a brighter day.
I nibble carrots and bugs with glee,
Celebrating our refactored spree!
🥕🐇 Happy code adventures to thee!


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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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
Contributor

@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

🧹 Nitpick comments (8)
Maple2.Model/Metadata/Table/ItemOptionTable.cs (2)

57-57: Clarify or rename the 'Variation' field.

The newly added 'Variation' field can be confusing. Consider naming it something more descriptive, such as 'Delta', 'Offset', or 'RangeDelta', to enhance clarity regarding its usage and intent.


66-66: Consider a more descriptive name for 'Set'.

"Set" often implies a collection with distinct elements, which may cause confusion. A more descriptive name such as 'WeightedValue' or 'ValueWeightEntry' would better convey the purpose of holding a value with a weight.

Maple2.Model/Enum/ItemOptionMakeType.cs (1)

3-6: Add XML documentation for the enum members.

Consider adding XML doc comments explaining when to use 'Base' vs. 'Range' to make the meaning of each value clear. This helps maintainers and future contributors, especially if the enum is expanded later.

Maple2.File.Ingest/Mapper/TableMapper.cs (1)

531-536: Consider adding weight configuration.

The TODO comment about weight suggests that this feature is incomplete. Consider implementing the weight configuration or creating a follow-up issue.

Would you like me to help create an issue to track the implementation of the weight configuration?

Maple2.Server.Game/Util/ItemStatsCalculator.cs (3)

82-83: Check concurrency for multiple calls.

These lines retrieve an ItemOption from a shared table and then call GetRandomOption and RandomizeValues. If multiple threads update item metadata or read from the same table simultaneously, confirm that TableMetadata.ItemOptionRandomTable is thread-safe. Also confirm item references are safely updated in a locked context if needed.

Also applies to: 86-86, 88-88


113-122: Expand doc comments for 'RandomizeValues'.

Although the summary is present, consider documenting the different behaviors for RandomMakeType to enhance maintainability. An overview of how each parameter affects the final randomization logic would help future contributors.


320-356: Consider potential concurrency issues with Random.Shared.

Random.Shared is threadsafe, but heavy concurrent usage can cause unexpected number distributions. If precise random distribution is required, consider a dedicated Random instance per thread or method.

Maple2.Server.Game/PacketHandlers/ChangeAttributesScrollHandler.cs (1)

105-105: Double-check “impossible” conditions.

These lines indicate states that should never occur if data is consistent. Adding logs or asserts is helpful, but ensure the end-user receives a clear message if something truly impossible ever arises.

Also applies to: 109-110, 114-114, 120-120

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a10c122 and 2246b20.

📒 Files selected for processing (8)
  • Maple2.File.Ingest/Maple2.File.Ingest.csproj (1 hunks)
  • Maple2.File.Ingest/Mapper/ItemMapper.cs (1 hunks)
  • Maple2.File.Ingest/Mapper/TableMapper.cs (4 hunks)
  • Maple2.Model/Enum/ItemOptionMakeType.cs (1 hunks)
  • Maple2.Model/Metadata/ItemMetadata.cs (1 hunks)
  • Maple2.Model/Metadata/Table/ItemOptionTable.cs (1 hunks)
  • Maple2.Server.Game/PacketHandlers/ChangeAttributesScrollHandler.cs (6 hunks)
  • Maple2.Server.Game/Util/ItemStatsCalculator.cs (6 hunks)
✅ Files skipped from review due to trivial changes (1)
  • Maple2.File.Ingest/Maple2.File.Ingest.csproj
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (20)
Maple2.Model/Metadata/Table/ItemOptionTable.cs (2)

52-55: Ensure multi-range usage is handled downstream.

Previously these dictionaries stored a single Range value per attribute; now they store arrays of Range values. Make sure that all consumers of these fields fully account for multiple entries. If downstream code was relying on a single range, it must now handle iterating through the array to avoid incorrect assumptions or index errors.


61-64: Verify handling of new 'Set[]' structures.

These properties were updated from arrays of primitives (int[]/float[]) to arrays of 'Set' records. Confirm that any logic accessing or modifying these arrays now handles both 'Value' and 'Weight' correctly. Also, verify whether these weights are aggregated, normalized, or used elsewhere in ways that differ from simple numeric arrays.

Maple2.Model/Metadata/ItemMetadata.cs (1)

94-94: Validate external data for Enum usage.

Changing the property type from int to RandomMakeType is a good improvement for type safety. Verify any external data or legacy code that sets this field to ensure valid enum values are always provided, preventing unexpected behavior from out-of-range assignments.

Maple2.File.Ingest/Mapper/ItemMapper.cs (1)

126-126: LGTM! Verify enum values match the data.

The explicit casting to RandomMakeType enum improves type safety. However, ensure that the enum values in RandomMakeType (Base and Range) correctly correspond to the values in data.option.randomMakeType.

Run the following script to verify the values:

✅ Verification successful

🏁 Script executed:

#!/bin/bash
# Description: Verify that the RandomMakeType enum values match the data.

# Test: Search for randomMakeType values in the codebase
rg -A 5 'randomMakeType'

# Test: Search for the RandomMakeType enum definition
ast-grep --pattern $'enum RandomMakeType {
  $$$
}'

Length of output: 685


I'll run a new script to locate the definition of the RandomMakeType enum and verify its values.


🏁 Script executed:

#!/bin/bash
# Search for the definition of the RandomMakeType enum in the repository
rg "enum RandomMakeType" -n .

Length of output: 104


🏁 Script executed:

#!/bin/bash
# Display content of the file containing RandomMakeType enum definition
cat Maple2.Model/Enum/ItemOptionMakeType.cs

Length of output: 207


Enum value mapping confirmed: The definition in Maple2.Model/Enum/ItemOptionMakeType.cs shows that RandomMakeType has Base = 0 and Range = 1—exactly as required. The explicit casting in Maple2.File.Ingest/Mapper/ItemMapper.cs ensures that a numeric value in data.option.randomMakeType is correctly interpreted as either Base or Range. No discrepancies were found.

Maple2.File.Ingest/Mapper/TableMapper.cs (6)

463-466: LGTM! Dictionary value types changed to support multiple variations.

The change from single instances to lists enables storing multiple variations for each attribute, which aligns with the PR objective.


475-481: LGTM! Proper handling of multiple variations.

The implementation correctly handles both new and existing attributes by:

  1. Checking if the attribute exists
  2. Appending to existing list or creating new list
  3. Using collection initializer syntax for better readability

483-487: LGTM! Consistent error handling for special attributes.

The error handling for special attributes mirrors the basic attributes implementation, maintaining consistency in the codebase.


514-519: LGTM! Proper conversion to immutable arrays.

The implementation correctly converts lists to arrays before returning, ensuring immutability of the returned collections.


524-527: LGTM! Consistent type changes in ParseItemEquipVariation.

The changes to support multiple variations are consistently applied to the equip variation parsing.


548-551: Consider adding weight configuration.

Similar TODO comment about weight in float entries. Consider implementing the weight configuration or creating a follow-up issue.

Maple2.Server.Game/Util/ItemStatsCalculator.cs (4)

9-9: No issue with the new import statement.

The addition of "using Maple2.Tools" is presumably needed for classes or extensions introduced by that namespace. This looks fine.


40-42: Confirm handling when TryGetValue fails.

When TableMetadata.ItemOptionRandomTable does not contain the key, the code simply skips setting Random stats. Consider logging or returning the partial stats object so the caller understands that no random option was applied.


129-135: Validate the usage of Random indices.

The code repeatedly calls “Random.Shared.Next(2, 18)” but never uses the 'index' variable. If this is intentional, consider removing the unused calls or clarifying why the index is being generated.

Also applies to: 139-145


299-300: Method wrapper seems fine.

Wrapping RandomItemOption behind GetRandomOption centralizes calls and clarifies the API.

Maple2.Server.Game/PacketHandlers/ChangeAttributesScrollHandler.cs (6)

12-12: Confirm that the extension methods are needed.

The new using Maple2.Tools.Extensions suggests extension methods are now used. If they’re no longer used, you can remove this import for cleanliness.


60-60: Error enum usage ensures clearer code.

Replacing direct references or magic constants with structured error codes (e.g., s_itemremake_scroll_error_invalid_scroll) is a good practice for maintainability. Make sure these error codes map to user-friendly messages on the client side.

Also applies to: 66-66, 70-70, 74-74


83-83: Lock attribute existence checks.

Lines 83-97 check if a locked attribute exists. This logic looks correct. Consider unit tests for corner cases (e.g., zero locked attributes, invalid attribute in multi-lock scenario).

Also applies to: 85-85, 90-90, 97-97


138-138: Scroll consumption checks.

The code calls Inventory.Consume for the scroll and lock item. If a concurrency or partial failure occurs between them, confirm whether a transaction or rollback logic is needed.

Also applies to: 142-142


154-154: Finalize item with new stats.

When “Select” is confirmed, the code sets “item.Stats[ItemStats.Type.Random]” from “session.ChangeAttributesItem”. This final assignment is straightforward. Confirm that session.ChangeAttributesItem is always cleared or updated to avoid accidental reuse.

Also applies to: 161-161, 167-167


178-178: Scroll compatibility checks.

These lines validate the target item’s rarity, type, level, and scroll conditions. Everything seems logically consistent. If future logic changes the valid item range, remember to update these checks.

Also applies to: 181-181, 184-184, 189-189, 192-192, 196-196, 199-199, 202-202

Copy link
Contributor

@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

🧹 Nitpick comments (2)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (2)

151-238: Consider extracting range logic into separate methods.

The GetValue method is quite long and handles multiple concerns. Consider extracting the range-based logic into separate methods for better maintainability.

+    private int GetRangeValue(int levelFactor, ItemEquipVariationTable.Set<int>[]? tableValues, ItemEquipVariationTable.Set<float>[]? tableRates, bool rollMax) {
+        var (start, end, maxIndex) = GetRangeBounds(levelFactor);
+        if (rollMax) {
+            if (tableValues != null) return tableValues[maxIndex].Value;
+            if (tableRates != null) return (int)(tableRates[maxIndex].Value * 1000);
+        }
+        
+        var weightedValues = new WeightedSet<int>();
+        var weightedRates = new WeightedSet<float>();
+        
+        for (int i = start; i < end; i++) {
+            if (tableValues != null) {
+                weightedValues.Add(tableValues[i].Value, tableValues[i].Weight);
+            } else if (tableRates != null) {
+                weightedRates.Add(tableRates[i].Value, tableRates[i].Weight);
+            }
+        }
+        
+        return tableValues != null ? weightedValues.Get() : (int)(weightedRates.Get() * 1000);
+    }
+
+    private static (int start, int end, int maxIndex) GetRangeBounds(int levelFactor) =>
+        levelFactor switch {
+            < 50 => (0, 3, 2),
+            < 70 => (2, 10, 9),
+            _ => (10, 18, 17)
+        };

321-356: Add XML documentation for GetItemVariationValue method.

The method lacks XML documentation explaining its purpose, parameters, and return value.

+    /// <summary>
+    /// Calculates the variation value for a given attribute based on its type and current value/rate.
+    /// </summary>
+    /// <param name="basicAttribute">The basic attribute to calculate variation for</param>
+    /// <param name="specialAttribute">The special attribute to calculate variation for</param>
+    /// <param name="value">The current value</param>
+    /// <param name="rate">The current rate</param>
+    /// <returns>The calculated variation value. If the input is a rate, the return value will be multiplied by 1000</returns>
     private int GetItemVariationValue(BasicAttribute? basicAttribute = null, SpecialAttribute? specialAttribute = null, int value = 0, float rate = 0)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2246b20 and 10b395e.

📒 Files selected for processing (1)
  • Maple2.Server.Game/Util/ItemStatsCalculator.cs (6 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: build
  • GitHub Check: format
🔇 Additional comments (2)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (2)

39-44: LGTM! Improved error handling with TryGetValue pattern.

The refactoring improves the code by using the safer TryGetValue pattern and simplifying the random option retrieval logic.


299-301: LGTM! Simplified method signature.

The method has been simplified by removing the output parameter and returning the value directly.

Copy link
Contributor

@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: 0

🧹 Nitpick comments (1)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (1)

363-399: Extract magic number into a named constant.

The conversion factor 1000 is used multiple times. Consider extracting it into a named constant for better maintainability.

+    private const int RATE_CONVERSION_FACTOR = 1000;

     private int GetItemVariationValue(BasicAttribute? basicAttribute = null, SpecialAttribute? specialAttribute = null, int value = 0, float rate = 0) {
         // ...
-        int convertedVariation = (int) range.Variation * 1000;
-        int convertedRate = (int) rate * 1000;
+        int convertedVariation = (int) range.Variation * RATE_CONVERSION_FACTOR;
+        int convertedRate = (int) rate * RATE_CONVERSION_FACTOR;
         // ...
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10b395e and b96eaf0.

📒 Files selected for processing (2)
  • Maple2.Server.Game/PacketHandlers/ChangeAttributesScrollHandler.cs (6 hunks)
  • Maple2.Server.Game/Util/ItemStatsCalculator.cs (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • Maple2.Server.Game/PacketHandlers/ChangeAttributesScrollHandler.cs
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build
🔇 Additional comments (5)
Maple2.Server.Game/Util/ItemStatsCalculator.cs (5)

39-44: LGTM! Improved null safety and method signature.

The changes improve the code by using the null-safe TryGetValue pattern and removing the output parameter anti-pattern.


82-88: Add bounds checking for array access.

While the null checking is improved, array access should include bounds checking to prevent potential IndexOutOfRangeException.


112-116: LGTM! Improved method documentation.

The XML documentation clearly describes the parameters and their purpose.


342-344: LGTM! Simplified method signature.

The method now has a cleaner signature without output parameters.


146-281: 🛠️ Refactor suggestion

Refactor to use named constants for array indices.

The GetValue function uses multiple hardcoded indices (e.g., 4, 17, etc.) which could lead to maintenance issues and potential bugs.

Consider defining named constants for these indices:

+    private const int PET_LOW_RARITY_MAX_INDEX = 4;
+    private const int PET_HIGH_RARITY_MAX_INDEX = 17;
+    private const int LEVEL_FACTOR_LOW_MAX_INDEX = 2;
+    private const int LEVEL_FACTOR_MID_MAX_INDEX = 9;
+    private const int LEVEL_FACTOR_HIGH_MAX_INDEX = 17;

     int GetValue(Item item, ItemOption itemOptionMetadata, BasicAttribute? attribute = null, SpecialAttribute? specialAttribute = null, ItemEquipVariationTable.Set<int>[]? tableValues = null, ItemEquipVariationTable.Set<float>[]? tableRates = null, bool rollMax = false) {
         // ...
-        if (tableValues != null) {
-            return tableValues[4].Value;
+        if (tableValues != null && tableValues.Length > PET_LOW_RARITY_MAX_INDEX) {
+            return tableValues[PET_LOW_RARITY_MAX_INDEX].Value;
         }
         // ... apply similar changes to other indices

Likely invalid or redundant comment.

@AngeloTadeucci AngeloTadeucci merged commit c66d72a into AngeloTadeucci:master Feb 8, 2025
3 checks passed
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.

2 participants