Skip to content

fix: various trading issues#970

Merged
OH296 merged 6 commits intoAdeptus-Dominus:mainfrom
OH296:veh_spawn_bitws
Aug 16, 2025
Merged

fix: various trading issues#970
OH296 merged 6 commits intoAdeptus-Dominus:mainfrom
OH296:veh_spawn_bitws

Conversation

@OH296
Copy link
Copy Markdown
Collaborator

@OH296 OH296 commented Aug 14, 2025

Purpose and Description

  • add support fooor vehicle trading
  • make sure fleets are better at finding player fleets to spawn with
  • allow fleets to drop players shit at nearest imperial world or nearest world with aany player presence if no oother optiioins available

Testing done

  • None, and I understand the risks.

Related things and/or additional context

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 14, 2025

📝 Walkthrough

Summary by CodeRabbit

  • New Features
    • Bulk buy/sell in the shop (hold Shift for x5).
    • Vehicles can now be included in trade deals and delivered by traders.
  • Improvements
    • Clearer shop labels and tooltips for items and costs.
    • More reliable hover/click detection in the shop.
    • Smarter fleet movement and arrival behaviour around trade locations.
    • Vehicle creation supports customised loadouts and placement when applicable.
  • Bug Fixes
    • Ensured consistent stock and order updates during bulk purchases.
    • Improved handling when no valid carrier is available for new vehicles.

Walkthrough

By the Omnissiah: wraps shop rendering in a draw-state lifecycle, replaces rectangle hit-tests and hashed labels with scr_hit/direct strings, adds shift-based x5 bulk purchases, extends scr_add_vehicle with an otherdata payload and updates call sites, adds vehicle trade/deployment flows, rewrites fleet arrival logic, and adds garrison helpers and unit-fetch refactor.

Changes

Cohort / File(s) Summary
Shop draw/state and bulk UI
objects/obj_shop/Draw_0.gml
Wraps render region with add/pop_draw_return_values; switches rectangle tests to scr_hit; replaces hashed-label rendering with direct strings; introduces _mult_count (shift => x5) for bulk buy/sell; updates cost, purchase, tooltip and name display logic.
Vehicle addition API refactor
scripts/scr_add_vehicle/scr_add_vehicle.gml
Changes signature to accept otherdata={} and defaulted loadout args; tightens var scoping; adds location overrides, home-world and carrier fallback logic, early-exit when no carrier, and configurable weapon/upgrade/accessory assignment.
Call sites updated to new vehicle API
scripts/scr_event_code/scr_event_code.gml, scripts/scr_specialist_point_handler/scr_specialist_point_handler.gml, scripts/scr_trade_dep/scr_trade_dep.gml
Updates scr_add_vehicle invocations to pass otherdata (e.g. {}) or adapt to new signature; trade deployment spawns vehicles with orbit/location info.
Trade payload: vehicles
scripts/scr_trade/scr_trade.gml
Adds vehic trade_type handling; records offered vehicles under trading_object.vehicles with count/quality.
Trade deployment handling
scripts/scr_trade_dep/scr_trade_dep.gml
Adds block to consume _goods.vehicles, spawning vehicles via scr_add_vehicle per entry with orbit-based placement.
Fleet arrival/targeting logic
scripts/scr_fleet_functions/scr_fleet_functions.gml
Rewrites scr_efleet_arrive_at_trade_loc to use orbit/viewer-aware validation, chase-target selection, destination fallbacks and disposition adjustments; adds early is_orbiting() call in arrival flow.
Garrison utilities for fleet logic
scripts/scr_unit_quick_find_pane/scr_unit_quick_find_pane.gml
Adds static has_troops(name) and player_force_stars() helpers used by fleet/orbit decisions.
Unit lookup refactor
scripts/scr_check_equip/scr_check_equip.gml
Replaces direct obj_ini.TTRPG[c][i] access with fetch_unit([c,i]) in non-combat path; behaviour otherwise unchanged.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

PR: Fix, PR: Feature, Type: Refactor, Size: Big

Suggested reviewers

  • Blogaugis
  • EttyKitty

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 81b4a63 and 6d34931.

📒 Files selected for processing (3)
  • objects/obj_shop/Draw_0.gml (8 hunks)
  • scripts/scr_add_vehicle/scr_add_vehicle.gml (2 hunks)
  • scripts/scr_fleet_functions/scr_fleet_functions.gml (2 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.gml

⚙️ CodeRabbit Configuration File

**/*.gml: - Macro constants require a space between the constant name and value. Without it, the compiler will throw an error. I.e. #macro ARR_body_parts["arm"] will crash the game, because there is no space between the array and the name of the macro.

Files:

  • scripts/scr_fleet_functions/scr_fleet_functions.gml
  • scripts/scr_add_vehicle/scr_add_vehicle.gml
  • objects/obj_shop/Draw_0.gml
**/*.*

⚙️ CodeRabbit Configuration File

**/*.*: - Having humanly understandable and maintainable code is always the top most priority.

Files:

  • scripts/scr_fleet_functions/scr_fleet_functions.gml
  • scripts/scr_add_vehicle/scr_add_vehicle.gml
  • objects/obj_shop/Draw_0.gml
🧠 Learnings (1)
📚 Learning: 2025-07-01T20:29:44.075Z
Learnt from: OH296
PR: Adeptus-Dominus/ChapterMaster#902
File: objects/obj_shop/Create_0.gml:550-655
Timestamp: 2025-07-01T20:29:44.075Z
Learning: In GML shop item initialization code, when setting nobuy flags for shop items, the nobuy[i] = 1 assignment must occur before incrementing the index (i += 1). Setting nobuy after incrementing i will apply the flag to the wrong item, potentially making restricted items purchasable or blocking intended purchasable items.

Applied to files:

  • objects/obj_shop/Draw_0.gml
🔇 Additional comments (3)
scripts/scr_add_vehicle/scr_add_vehicle.gml (1)

35-42: Sacred indices: Carrier selection logic validated

The use of -1 as sentinel value properly handles 0-indexed arrays. Well done, initiate.

scripts/scr_fleet_functions/scr_fleet_functions.gml (2)

332-340: Acceptable fleet pursuit logic

The action coordinate assignment properly handles both active and idle targets.


540-540: Blessed addition of orbit state refresh

The is_orbiting() call properly updates fleet orbital status upon arrival.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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 or @coderabbitai title 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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@github-actions github-actions bot added Size: Medium Type: Fix This is a fix for a bug labels Aug 14, 2025
Copy link
Copy Markdown
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: 12

🔭 Outside diff range comments (4)
scripts/scr_check_equip/scr_check_equip.gml (2)

18-36: Uninitialised unit used in combat branch → null dereference risk

When obj_ncombat exists, unit is never assigned, yet it is dereferenced later (Lines 38–69). Invoke fetch_unit before the combat/non-combat split to appease the Machine Spirit and avoid void-reference faults.

Apply this patch to initialise unit unconditionally:

-        if (!instance_exists(obj_ncombat)){ 
-                unit = fetch_unit([c,i]);
+        unit = fetch_unit([c,i]);
+        if (!instance_exists(obj_ncombat)){ 
             if (system!="") and (planet_or_ship_id>0){
                 if (unit.is_at_location(system,planet_or_ship_id,-1)){
                     marine_present=true;
                 }
             }
             if (system="") and (planet_or_ship_id>0){
                 if (unit.is_at_location("",0,planet_or_ship_id)){
                     marine_present=true;
                 }
             }
         } else {
             try {
                 if (obj_ncombat.fighting[c][i]==1){
                     marine_present=true;
                 } 
             } catch (_){}
         }

25-27: Assignment used instead of comparison in condition

The test (system="") assigns an empty string. You want equality. This will misroute logic like a misaligned cog.

Correct with:

-                if (system="") and (planet_or_ship_id>0){
+                if (system=="") and (planet_or_ship_id>0){
scripts/scr_specialist_point_handler/scr_specialist_point_handler.gml (1)

448-455: Capacity desynchronisation: you relocate vehicles after creation without undoing carrier increment

scr_add_vehicle now auto-embarks on carriers when not at home world and capacity exists, incrementing ship_carrying. You then forcibly relocate to a hanger (veh_lid=-1), but do not decrement ship_carrying. The Machine Spirit will tally falsely.

Pass the hanger location up-front to scr_add_vehicle and remove post-hoc field edits:

-                repeat(item.count){
-                    var vehicle = scr_add_vehicle(item.name,obj_controller.new_vehicles);
-                    var build_loc = array_random_element(obj_controller.player_forge_data.vehicle_hanger);
-                    obj_ini.veh_loc[vehicle[0]][vehicle[1]] = build_loc[0];
-                    obj_ini.veh_wid[vehicle[0]][vehicle[1]] = build_loc[1];
-                    obj_ini.veh_lid[vehicle[0]][vehicle[1]] = -1;
-                }
+                repeat(item.count){
+                    var build_loc = array_random_element(obj_controller.player_forge_data.vehicle_hanger);
+                    var vehicle = scr_add_vehicle(item.name, obj_controller.new_vehicles, { loc: build_loc[0], wid: build_loc[1], lid: -1 });
+                }

This avoids touching ship_carrying at all for these builds and keeps state blessedly consistent.

scripts/scr_fleet_functions/scr_fleet_functions.gml (1)

409-419: Critical: Eldar return path uses undefined variables and assigns into wrong identifiers

  • nearest_star_with_ownership is called with xx, yy, but the function elsewhere is used as nearest_star_with_ownership(owner). xx/yy are undefined here.
  • cur_star=targ.x/y is clearly wrong; you want to set action coordinates.
  • targ itself is unused/undefined.

Apply this fix:

-        if (owner==eFACTION.Eldar){
-            cur_star = nearest_star_with_ownership(xx,yy, eFACTION.Eldar);
-            if (cur_star!="none"){
-                cur_star=targ.x;
-                cur_star=targ.y;  
-            }                      
-        } else {
+        if (owner == eFACTION.Eldar) {
+            cur_star = nearest_star_with_ownership(eFACTION.Eldar);
+            if (cur_star != "none") {
+                action_x = cur_star.x;
+                action_y = cur_star.y;
+                set_fleet_movement();
+            }
+        } else {
             action_x=home_x;
             action_y=home_y; 
             set_fleet_movement();                       
         }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4b24c3d and 81b4a63.

📒 Files selected for processing (9)
  • objects/obj_shop/Draw_0.gml (8 hunks)
  • scripts/scr_add_vehicle/scr_add_vehicle.gml (2 hunks)
  • scripts/scr_check_equip/scr_check_equip.gml (1 hunks)
  • scripts/scr_event_code/scr_event_code.gml (1 hunks)
  • scripts/scr_fleet_functions/scr_fleet_functions.gml (2 hunks)
  • scripts/scr_specialist_point_handler/scr_specialist_point_handler.gml (1 hunks)
  • scripts/scr_trade/scr_trade.gml (1 hunks)
  • scripts/scr_trade_dep/scr_trade_dep.gml (1 hunks)
  • scripts/scr_unit_quick_find_pane/scr_unit_quick_find_pane.gml (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.gml

⚙️ CodeRabbit Configuration File

**/*.gml: - Macro constants require a space between the constant name and value. Without it, the compiler will throw an error. I.e. #macro ARR_body_parts["arm"] will crash the game, because there is no space between the array and the name of the macro.

Files:

  • scripts/scr_specialist_point_handler/scr_specialist_point_handler.gml
  • scripts/scr_trade/scr_trade.gml
  • scripts/scr_check_equip/scr_check_equip.gml
  • scripts/scr_trade_dep/scr_trade_dep.gml
  • scripts/scr_unit_quick_find_pane/scr_unit_quick_find_pane.gml
  • scripts/scr_event_code/scr_event_code.gml
  • scripts/scr_fleet_functions/scr_fleet_functions.gml
  • objects/obj_shop/Draw_0.gml
  • scripts/scr_add_vehicle/scr_add_vehicle.gml
**/*.*

⚙️ CodeRabbit Configuration File

**/*.*: - Having humanly understandable and maintainable code is always the top most priority.

Files:

  • scripts/scr_specialist_point_handler/scr_specialist_point_handler.gml
  • scripts/scr_trade/scr_trade.gml
  • scripts/scr_check_equip/scr_check_equip.gml
  • scripts/scr_trade_dep/scr_trade_dep.gml
  • scripts/scr_unit_quick_find_pane/scr_unit_quick_find_pane.gml
  • scripts/scr_event_code/scr_event_code.gml
  • scripts/scr_fleet_functions/scr_fleet_functions.gml
  • objects/obj_shop/Draw_0.gml
  • scripts/scr_add_vehicle/scr_add_vehicle.gml
🧠 Learnings (1)
📚 Learning: 2025-07-01T20:29:44.075Z
Learnt from: OH296
PR: Adeptus-Dominus/ChapterMaster#902
File: objects/obj_shop/Create_0.gml:550-655
Timestamp: 2025-07-01T20:29:44.075Z
Learning: In GML shop item initialization code, when setting nobuy flags for shop items, the nobuy[i] = 1 assignment must occur before incrementing the index (i += 1). Setting nobuy after incrementing i will apply the flag to the wrong item, potentially making restricted items purchasable or blocking intended purchasable items.

Applied to files:

  • objects/obj_shop/Draw_0.gml
🔇 Additional comments (12)
scripts/scr_check_equip/scr_check_equip.gml (1)

38-69: Guard against missing/invalid unit before equipment checks

Even with the initialisation fix, defensively skip if unit is undefined or invalid to prevent further heresy.

If fetch_unit can ever return undefined/null, consider:

if (!is_undefined(unit)) {
  // existing checks
}

Confirm fetch_unit’s contract; if it can fail, add the guard. I can draft a follow-up patch if desired.

scripts/scr_trade/scr_trade.gml (1)

106-114: Vehicle trade payload wiring looks correct

The “vehic” trade branch mirrors existing equip/merc patterns and populates trading_object.vehicles as expected for scr_trade_dep to consume. Blessed.

scripts/scr_event_code/scr_event_code.gml (1)

200-201: Rhino spawn: signature alignment looks correct, but consider passing real otherdata

Invocation matches the extended scr_add_vehicle(type, target_company, otherdata, ...) API. Passing {} is valid as “no loadout”. If this Rhino is meant to appear anywhere specific (loc/wid/lid now supported in otherdata across the PR), consider supplying those so the unit doesn’t end up orphaned.

Would you like me to thread through a sensible default location payload here to parallel trade/dep flows (e.g., orbit of the unit’s current system)?

scripts/scr_unit_quick_find_pane/scr_unit_quick_find_pane.gml (1)

17-19: Static has_troops accessor: simple and useful

The helper cleanly exposes presence checks over garrison_log and keeps calling sites tidy. No objections.

scripts/scr_fleet_functions/scr_fleet_functions.gml (2)

542-543: Good: refreshing orbit state before arrival logic

Calling is_orbiting() before the post-move processing reduces desync between position and orbit flags. Sanctified.


351-383: Destination fallback chain: good coverage, but ensure viewer is present

This chain is sensible (player world -> any player presence -> imperial world). It still assumes a valid viewer earlier. After safeguarding the viewer (as proposed above), this becomes robust.

objects/obj_shop/Draw_0.gml (6)

17-22: UI labels clarified

Replacing hashed strings with “Stocked” and “MC” improves legibility. Praise be.


54-59: Hit-testing switch to scr_hit

Good unification. scr_hit appears used consistently across the UI; this aligns behaviour and avoids divergent rectangles.


90-99: Cost rendering logic: OK, but unify multiplier application

The cost path correctly multiplies by 5 when shift-buying (non-production). Keep this in sync with the purchase deduction logic below to avoid divergence.


220-223: Draw return-value stack: balanced pushes/pops

add_draw_return_values() paired with pop_draw_return_values() around slate draw is balanced. No stack leakage detected in this routine.


267-268: Global draw return-value pop matches top-level push

Top add_draw_return_values() is correctly balanced here. Well maintained state stack.


112-114: sell_item signature change: verify support for quantity parameter

By the Omnissiah — repo scan found a single caller and no function definition. Confirm the implementation supports sell_item(i, count, mod) or update callers.

  • objects/obj_shop/Draw_0.gml:112–114
    var sell_mult_count = keyboard_check(vk_shift) ? 5 : 1;
    sell_item(i, sell_mult_count, _sell_mod)
    

Action: verify sell_item is declared (script/resource or function) with the new signature, or adjust this call accordingly.

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
coderabbitai[bot]
coderabbitai bot previously approved these changes Aug 16, 2025
@OH296
Copy link
Copy Markdown
Collaborator Author

OH296 commented Aug 16, 2025

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Aug 16, 2025

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@OH296 OH296 merged commit beaf8e9 into Adeptus-Dominus:main Aug 16, 2025
3 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Aug 19, 2025
@coderabbitai coderabbitai bot mentioned this pull request Feb 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Size: Medium Type: Fix This is a fix for a bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant