From dbcc03c537ce7b2c3eb88bafa9fe2044f335b124 Mon Sep 17 00:00:00 2001 From: SX <50966843+S-S-X@users.noreply.github.com> Date: Fri, 3 Jan 2025 00:42:04 +0200 Subject: [PATCH] Backport tool charge helpers set_charge/get_charge from other Technic mod --- technic/doc/api.md | 7 +++++++ technic/helpers.lua | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) diff --git a/technic/doc/api.md b/technic/doc/api.md index 8ae6963f..2fd0a489 100644 --- a/technic/doc/api.md +++ b/technic/doc/api.md @@ -47,6 +47,13 @@ Helper functions * Some configuration function * `technic.tube_inject_item(pos, start_pos, velocity, item)` * Same as `pipeworks.tube_inject_item` +* `technic.get_RE_charge(itemstack)` + * Returns current charge level of tool. +* `technic.set_RE_charge(itemstack, charge)` + * Sets tool charge level. +* `technic.use_RE_charge(itemstack, charge)` + * Attempt to use charge and return `true`/`false` indicating success. + * Always succeeds without checking charge level if creative is enabled. Registration functions ---------------------- diff --git a/technic/helpers.lua b/technic/helpers.lua index 5361fa38..3cd4ba58 100644 --- a/technic/helpers.lua +++ b/technic/helpers.lua @@ -77,6 +77,43 @@ function technic.refill_RE_charge(stack) return stack end +function technic.set_RE_charge(stack, charge) + local max_charge = technic.power_tools[stack:get_name()] + if max_charge then + technic.set_RE_wear(stack, charge, max_charge) + local meta = minetest.deserialize(stack:get_metadata()) or {} + meta.charge = math.min(math.max(0, charge), max_charge) + stack:set_metadata(minetest.serialize(meta)) + end +end + +technic.set_charge = technic.set_RE_charge + +function technic.get_RE_charge(stack) + local max_charge = technic.power_tools[stack:get_name()] + if max_charge then + local meta = minetest.deserialize(stack:get_metadata()) or {} + return meta.charge or 0, max_charge + end + return 0, 0 +end + +technic.get_charge = technic.get_RE_charge + +function technic.use_RE_charge(stack, amount) + if technic.creative_mode or amount <= 0 then + -- Do not check charge in creative mode or when trying to use zero amount + return true + end + local charge = technic.get_RE_charge(stack) + if charge < amount then + -- Not enough energy available + return false + end + technic.set_RE_charge(stack, charge - amount) + -- Charge used successfully + return true +end -- If the node is loaded, returns it. If it isn't loaded, load it and return nil. function technic.get_or_load_node(pos)