Lightningwolf

can you also work with minetest luaniti

Kodari AI
KodariOct 7 at 1:39 pm 1
LuanitiMineTestBridge
LuanitiMineTestBridge is a Minecraft plugin that bridges the Lua-based Luaniti game engine with the Minetest world format. It enables seamless conversion of Minecraft worlds to Minetest-compatible terrain, translating block types, entities, and biome data. The plugin provides real-time synchronization between Minecraft servers and Minetest instances, allowing players to explore their Minecraft creations in the Minetest engine. Key features include automatic block mapping, entity preservation, terrain generation algorithms, and a bidirectional sync protocol. It supports custom Lua scripts for advanced world transformations and includes a user-friendly configuration system for mapping Minecraft blocks to Minetest equivalents. The plugin also offers performance optimization tools for large world conversions, ensuring smooth gameplay experiences across both platforms.

Yesβ€”I can help build Luanti (formerly Minetest) mods in Lua, including nodes, items, entities, callbacks, and mod configuration. What would you like to make?

Lightningwolf

make a riptide trident code here is the base code revamp only the trident:

πŸ“Ž 1 file 47,185 chars
πŸ“„
pasted-code-1791380520093.txt
txt 1371 lines
β–Ά
local S = core.get_translator("mobs")
local FS = function(...) return core.formspec_escape(S(...)) end
local max_per_block = tonumber(core.settings:get("max_objects_per_block") or 99)

local players_wind_charge_cooldown = {}
local trial_spawned_mobs = {}   -- [object_ref] = true

local trial_chambers = {}
local trial_storage = core.get_mod_storage()
local trial_count = trial_storage:get_int("chamber_count") or 0

-- Load saved chamber positions
for i = 1, trial_count do
    local saved = trial_storage:get_string("chamber_" .. i)
    if saved ~= "" then
        local pos = core.string_to_pos(saved)
        if pos then
            table.insert(trial_chambers, pos)
        end
    end
end

-- ======================
--  Loot Tables
-- ======================

local TRIAL_LOOT_NORMAL = {
    {item = "default:copper_ingot", min = 2, max = 6, weight = 18},
    {item = "default:gold_ingot", min = 1, max = 4, weight = 15},
    {item = "default:diamond", min = 1, max = 2, weight = 10},
    {item = "default:mese_crystal", min = 1, max = 3, weight = 12},

    {item = "trial_chamber:breeze_rod", min = 1, max = 3, weight = 12},
    {item = "trial_chamber:wind_charge", min = 2, max = 6, weight = 10},
    {item = "trial_chamber:trial_key", min = 1, max = 1, weight = 2},
    {item = "trial_chamber:power_shard", min = 1, max = 1, weight = 2},

    {item = "tnt:gunpowder", min = 1, max = 4, weight = 8},
    {item = "default:obsidian", min = 1, max = 2, weight = 6},
}

local TRIAL_LOOT_OMINOUS = {
    {item = "default:diamond", min = 2, max = 5, weight = 12},
    {item = "default:mese_crystal", min = 3, max = 7, weight = 15},
    {item = "default:gold_ingot", min = 3, max = 8, weight = 10},

    {item = "trial_chamber:breeze_rod", min = 2, max = 5, weight = 15},
    {item = "trial_chamber:heavy_core", min = 1, max = 1, weight = 6},
    {item = "trial_chamber:ominous_trial_key", min = 1, max = 1, weight = 2},
    {item = "trial_chamber:trial_key", min = 1, max = 2, weight = 2},

    {item = "x_enchanting:mending_orb", min = 1, max = 3, weight = 10},
    {item = "x_enchanting:mending_bottle", min = 1, max = 2, weight = 6},

    {item = "tnt:gunpowder", min = 2, max = 6, weight = 5},
    {item = "default:obsidian", min = 2, max = 4, weight = 4},
    {item = "default:steel_ingot", min = 1, max = 3, weight = 6},
}

local TRIAL_TIERS = {
    {   -- Tier 1
        mobs = {"zombies4test:survivorzombie"},
        count = 10,
        reward = "trial_chamber:trial_key",
    },
    {   -- Tier 2
        mobs = {"mobs_mc:zombie", "mobs_mc:skeleton", "mobs_mc:evoker"},
        count = 15,
        reward = "trial_chamber:trial_key",
    },
    {   -- Tier 3
        mobs = {"mobs_mc:spider", "zombies4test:spitterzombie", "mobs_mc:skeleton", "mobs_mc:evoker"},
        count = 20,
        reward = "trial_chamber:ominous_trial_key",
    },
    {   -- Tier 4
        mobs = {"zombies4test:juggernaut", "mobs_mc:skeleton", "mobs_mc:creeper", "mobs_mc:evoker"},
        count = 25,
        reward = "trial_chamber:ominous_trial_key",
    },
}

-- ===== Mace fall damage helper =====
local function get_fall_blocks(player)
    local vel = player:get_velocity()
    if not vel then return 0 end
    return math.max(0, -1 * math.abs(vel.y) * vel.y / 40)
end

-- ======================
--  Loot helpers
-- ======================
local function choose_loot(loot_table)
    local total_weight = 0
    for _, loot in ipairs(loot_table) do
        total_weight = total_weight + loot.weight
    end

    local roll = math.random(1, total_weight)

    for _, loot in ipairs(loot_table) do
        roll = roll - loot.weight
        if roll <= 0 then
            local count = math.random(loot.min, loot.max)
            return ItemStack(loot.item .. " " .. count)
        end
    end

    return ItemStack("default:diamond")
end

local function eject_rewards(pos, loot_table)
    local drop_pos = vector.new(pos.x, pos.y + 1, pos.z)

    for i = 1, 10 do
        minetest.after((i - 1) * 0.5, function()
            local stack = choose_loot(loot_table)
            minetest.item_drop(stack, nil, drop_pos)
            minetest.sound_play("trial_vault_unlock", {
                pos = pos,
                max_hear_distance = 10,
            })
        end)
    end
end

local function fill_chest(pos, loot_table, min_stacks, max_stacks)
    local meta = core.get_meta(pos)
    local inv = meta:get_inventory()

    if not inv then
        core.log("warning", "[trial_chamber] Could not get chest inventory at "
            .. core.pos_to_string(pos))
        return
    end

    if inv:get_size("main") == 0 then
        inv:set_size("main", 32)
    end

    local size = inv:get_size("main")
    if size == 0 then
        core.log("warning", "[trial_chamber] Chest has no inventory at "
            .. core.pos_to_string(pos))
        return
    end

    local num_stacks = math.random(
        min_stacks or 3,
        math.min(max_stacks or 8, size)
    )

    local slots_used = 0

    for i = 1, size do
        if slots_used >= num_stacks then break end

        if math.random(100) <= 70 then
            local stack = choose_loot(loot_table)
            if not stack:is_empty() then
                inv:set_stack("main", i, stack)
                slots_used = slots_used + 1
            end
        end
    end
end

local function get_distance(a, b)
    if not a or not b then return 50 end
    local x, y, z = a.x - b.x, a.y - b.y, a.z - b.z
    return math.sqrt(x * x + y * y + z * z)
end

-- ======================
--  Power Shard
-- ======================
minetest.register_craftitem("trial_chamber:power_shard", {
    description = "Power Shard",
    inventory_image = "echo_shard.png",
    stack_max = 64,
    on_use = function(itemstack, user, pointed_thing)
        if pointed_thing.type ~= "node" then return itemstack end
        local pos = pointed_thing.under
        local node = minetest.get_node(pos)
        if node.name ~= "trial_chamber:trial_spawner" then
            minetest.chat_send_player(user:get_player_name(), "Use this on a Trial Spawner.")
            return itemstack
        end
        local meta = minetest.get_meta(pos)
        local current = meta:get_int("power") or 0
        meta:set_int("power", current + 1)
        minetest.chat_send_player(user:get_player_name(), "Spawner empowered! Next wave will have more mobs.")
        itemstack:take_item()
        return itemstack
    end,
})

-- ======================
--  Trial Spawner
-- ======================
core.register_node("trial_chamber:trial_spawner", {
    tiles = {"trial_spawner.png"},
    drawtype = "glasslike",
    paramtype = "light",
    walkable = true,
    description = S("Trial Spawner"),
    groups = {cracky = 3, pickaxe = 1},
    is_ground_content = false,
    _mcl_hardness = 1,
    _mcl_blast_resistance = 5,
    sounds = mobs.node_sound_stone_defaults(),

    on_construct = function(pos)
        local meta = core.get_meta(pos)
        meta:set_int("power", 0)
        meta:set_int("spawned", 0)
        meta:set_int("rewarded", 0)
        meta:set_string("infotext", S("Trial Spawner - Tier @1", 1))
    end,

    on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
        local name = clicker:get_player_name()
        local meta = core.get_meta(pos)
        local power = meta:get_int("power")
        local tier = math.min(power + 1, #TRIAL_TIERS)
        minetest.chat_send_player(name, S("Trial Spawner - Tier @1 of @2", tier, #TRIAL_TIERS))
    end,
})

core.register_abm({
    label = "Trial spawner node",
    nodenames = {"trial_chamber:trial_spawner"},
    interval = 0.1,
    chance = 2,
    catch_up = false,

    action = function(pos, node, active_object_count, active_object_count_wider)
        if active_object_count_wider >= max_per_block then return end

        local meta = core.get_meta(pos)
        local power = meta:get_int("power") or 0
        local tier_index = math.min(power + 1, #TRIAL_TIERS)
        local tier = TRIAL_TIERS[tier_index]
        if not tier then return end

        local mob_list = tier.mobs
        local max_count = tier.count
        local reward = tier.reward

        local objs = core.get_objects_inside_radius(pos, 9)
        local count = 0
        for _, obj in ipairs(objs) do
            local ent = obj:get_luaentity()
            if ent and ent.name then
                for _, mob in ipairs(mob_list) do
                    if ent.name == mob then
                        count = count + 1
                        break
                    end
                end
            end
        end

        local spawned = meta:get_int("spawned")
        local rewarded = meta:get_int("rewarded")

        if spawned >= max_count and count == 0 and rewarded == 0 then
            local drop_pos = vector.new(pos.x, pos.y + 1, pos.z)
            for i = 1, max_count do
                minetest.after((i-1) * 0.3, function()
                    minetest.item_drop(ItemStack(reward), nil, drop_pos)
                    minetest.sound_play("trial_vault_unlock", {pos = pos, max_hear_distance = 10})
                end)
            end
            meta:set_int("rewarded", 1)
            meta:set_int("spawned", 0)
            return
        end

        if spawned >= max_count then return end
        if count >= max_count then return end

        local players = core.get_connected_players()
        local found = false
        for _, player in ipairs(players) do
            if get_distance(player:get_pos(), pos) <= 15 then
                found = true
                break
            end
        end
        if not found then return end

        local mob = mob_list[math.random(#mob_list)]

        local reg = core.registered_entities[mob].fly_in
        if type(reg) ~= "table" then reg = {reg or "air"} end

        local minp = {x = pos.x - 5, y = pos.y - 1, z = pos.z - 5}
        local maxp = {x = pos.x + 5, y = pos.y + 1, z = pos.z + 5}
        local air = core.find_nodes_in_area(minp, maxp, reg)

        if #air > 0 then
            local spawn_pos = air[math.random(#air)]
            spawn_pos.y = spawn_pos.y + 0.5

            local obj = core.add_entity(spawn_pos, mob)
            if obj then
                meta:set_int("spawned", spawned + 1)
            else
                minetest.log("warning", "[trial_chamber] Failed to spawn " .. tostring(mob))
            end
        end
    end
})

-- ======================
--  Keys
-- ======================
minetest.register_craftitem("trial_chamber:trial_key", {
    description = "Trial key",
    inventory_image = "trial_key.png",
    on_use = function(itemstack) return itemstack end,
})

minetest.register_craftitem("trial_chamber:ominous_trial_key", {
    description = "Ominous Trial key",
    inventory_image = "ominous_trial_key.png",
    on_use = function(itemstack) return itemstack end,
})

-- ======================
--  Key Vaults
-- ======================
local DEFAULT_REWARD = "default:diamond"
local REWARD_COUNT = 1

local function consume_wielded(player)
    local stack = player:get_wielded_item()
    if stack:get_count() <= 1 then
        player:set_wielded_item(ItemStack(""))
    else
        stack:set_count(stack:get_count() - 1)
        player:set_wielded_item(stack)
    end
end

minetest.register_node("trial_chamber:key_vault", {
    description = S("Key Vault"),
    tiles = {"mcl_vaults_vault_top_on.png", "mcl_vaults_vault_bottom.png",
             "mcl_vaults_vault_side_on.png", "mcl_vaults_vault_side_on.png",
             "mcl_vaults_vault_side_on.png", "mcl_vaults_vault_front_on.png"},
    drawtype = "nodebox",
    node_box = {type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}},
    paramtype = "light",
    paramtype2 = "facedir",
    groups = {cracky = 2, oddly_breakable_by_hand = 2},
    is_ground_content = false,
    sounds = default.node_sound_stone_defaults(),

    on_construct = function(pos)
        local meta = minetest.get_meta(pos)
        meta:set_string("key_item", "")
        meta:set_string("reward_item", DEFAULT_REWARD)
        meta:set_int("reward_count", REWARD_COUNT)
    end,

    on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
        if not clicker or not clicker:is_player() then return end
        local name = clicker:get_player_name()
        local key_item = "trial_chamber:trial_key"

        if clicker:get_wielded_item():get_name() == key_item then
            consume_wielded(clicker)
            eject_rewards(pos, TRIAL_LOOT_NORMAL)
            minetest.sound_play("trial_vault_unlock", {pos = pos, max_hear_distance = 10})
        else
            minetest.chat_send_player(name, S("This vault requires @1.", key_item))
        end
    end,
})

minetest.register_node("trial_chamber:Ominous_key_vault", {
    description = S("Ominous Key Vault"),
    tiles = {"mcl_vaults_vault_ominous_top_on.png", "mcl_vaults_vault_bottom.png",
             "mcl_vaults_vault_ominous_side_on.png", "mcl_vaults_vault_ominous_side_on.png",
             "mcl_vaults_vault_ominous_side_on.png", "mcl_vaults_vault_ominous_front_on.png"},
    drawtype = "nodebox",
    node_box = {type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}},
    paramtype = "light",
    paramtype2 = "facedir",
    groups = {cracky = 2, oddly_breakable_by_hand = 2},
    is_ground_content = false,
    sounds = default.node_sound_stone_defaults(),

    on_construct = function(pos)
        local meta = minetest.get_meta(pos)
        meta:set_string("key_item", "")
        meta:set_string("reward_item", DEFAULT_REWARD)
        meta:set_int("reward_count", REWARD_COUNT)
    end,

    on_rightclick = function(pos, node, clicker, itemstack, pointed_thing)
        if not clicker or not clicker:is_player() then return end
        local name = clicker:get_player_name()
        local key_item = "trial_chamber:ominous_trial_key"

        if clicker:get_wielded_item():get_name() == key_item then
            consume_wielded(clicker)
            eject_rewards(pos, TRIAL_LOOT_OMINOUS)
            minetest.sound_play("trial_vault_unlock", {pos = pos, max_hear_distance = 10})
        else
            minetest.chat_send_player(name, S("This vault requires @1.", key_item))
        end
    end,
})

-- ======================
--  Heavy Core + Breeze Rod
-- ======================
minetest.register_node("trial_chamber:heavy_core", {
    description = S("Heavy core"),
    tiles = {"mcl_tools_heavy_core_top.png", "mcl_tools_heavy_core_bottom.png",
             "mcl_tools_heavy_core_side.png", "mcl_tools_heavy_core_side.png",
             "mcl_tools_heavy_core_side.png", "mcl_tools_heavy_core_side.png"},
    drawtype = "nodebox",
    node_box = {type = "fixed", fixed = {-0.3, -0.3, -0.3, 0.3, 0.3, 0.3}},
    paramtype = "light",
    paramtype2 = "facedir",
    groups = {cracky = 2, oddly_breakable_by_hand = 2},
    is_ground_content = false,
    sounds = default.node_sound_stone_defaults()
})

minetest.register_craftitem("trial_chamber:breeze_rod", {
    description = "breeze_rod",
    inventory_image = "mcl_mobitems_breeze_rod.png",
    stack_max = 99,
})

-- ======================
--  Mace
-- ======================
minetest.register_tool("trial_chamber:mace", {
    description = "Mace",
    inventory_image = "mace.png",
    stack_max = 1,
    groups = {mace = 1},
    tool_capabilities = {
        full_punch_interval = 0.5,
        max_drop_level = 1,
        damage_groups = { fleshy = 6 },
    },
    range = 6,

    on_use = function(itemstack, user, pointed_thing)
        if pointed_thing.type ~= "object" then return itemstack end

        local target = pointed_thing.ref
        if not target then return itemstack end

        local blocks = get_fall_blocks(user)

        local smash_bonus = 0
        if blocks > 1.5 then
            smash_bonus = (blocks - 3) * 2
            if smash_bonus < 0 then smash_bonus = 0 end
            if smash_bonus > 10 then smash_bonus = 10 end
        end

        local total_damage = 6 + smash_bonus

        target:punch(user, 1.0, {
            full_punch_interval = 0.5,
            damage_groups = { fleshy = total_damage },
        })

        if smash_bonus > 0 then
            local pos = target:get_pos()
            minetest.add_particlespawner({
                amount = 30, time = 0.1,
                minpos = pos, maxpos = pos,
                minvel = {x=-3, y=0, z=-3}, maxvel = {x=3, y=1, z=3},
                minexptime = 0.5, maxexptime = 1,
                minsize = 1, maxsize = 2,
            })
            minetest.sound_play("default_dig_metal", {object = user, gain = 1.0})
        end
        return itemstack
    end,
})

core.register_craft({
    output = "trial_chamber:mace",
    type = "shapeless",
    recipe = {"trial_chamber:breeze_rod", "trial_chamber:heavy_core"}
})

-- ======================
--  Wind Charge
-- ======================
wind_charges = {}
local registered_nodes = minetest.registered_nodes

local function is_solid_node_near(pos)
    local radius = 0.12
    local offsets = {
        {x = radius, y = 0, z = 0}, {x = -radius, y = 0, z = 0},
        {x = 0, y = radius, z = 0}, {x = 0, y = -radius, z = 0},
        {x = 0, y = 0, z = radius}, {x = 0, y = 0, z = -radius}
    }
    for i = 1, #offsets do
        local p = vector.add(pos, offsets[i])
        local node = minetest.get_node_or_nil(p)
        local def = node and registered_nodes[node.name]
        if def and def.walkable then return true end
    end
    return false
end

minetest.register_entity("trial_chamber:wind_projectile", {
    initial_properties = {
        physical = true,
        collisionbox = {-0.1, -0.1, -0.1, 0.1, 0.1, 0.1},
        visual = "sprite",
        textures = {"wind_charge.png"},
        visual_size = {x = 0.5, y = 0.5},
        collide_with_objects = false,
    },

    lifetime = 8,
    timer = 0,
    spawn_time = 0,

    explode = function(self)
        local pos = self.object:get_pos()
        minetest.sound_play("wind_charge_explode", {
            pos = pos, max_hear_distance = 24, gain = 1.0,
        })

        minetest.add_particlespawner({
            amount = 8, time = 0.1,
            minpos = pos, maxpos = pos,
            minvel = {x = -5, y = 0, z = -5},
            maxvel = {x = 5, y = 2, z = 5},
            minacc = {x = 0, y = 0, z = 0},
            maxacc = {x = 0, y = -5, z = 0},
            minexptime = 0.1, maxexptime = 0.2,
            minsize = 5, maxsize = 8,
            texture = "wind_charge_explode_particle.png",
            glow = 5,
        })

        local objs = minetest.get_objects_inside_radius(pos, 7)
        for _, obj in ipairs(objs) do
            local obj_pos = obj:get_pos()
            local dist = vector.distance(pos, obj_pos)
            local dir = vector.direction(pos, obj_pos)
            local power = 16 * (1 - math.min(dist / 4, 1))
            obj:add_velocity(vector.multiply(dir, power))
        end

        self.object:remove()
    end,

    on_punch = function(self) self:explode() return 0 end,

    on_activate = function(self, staticdata)
        local data = minetest.deserialize(staticdata or "") or {}
        self.spawn_time = data.spawn_time or os.time()
    end,

    get_staticdata = function(self)
        return minetest.serialize({spawn_time = self.spawn_time})
    end,

    on_step = function(self, dtime)
        self.timer = self.timer + dtime
        if os.time() - self.spawn_time >= self.lifetime then
            self:explode()
            return
        end

        local pos = self.object:get_pos()

        for obj in minetest.objects_inside_radius(pos, 0.35) do
            local luaentity = obj:get_luaentity()
            if luaentity
            and luaentity.name == "trial_chamber:thrown_ender_pearl"
            and luaentity.activate_from_windcharge then
                luaentity:activate_from_windcharge()
                self.object:remove()
                return
            end
        end

        if is_solid_node_near(pos) then
            self:explode()
            return
        end
    end,
})

-- ═════════════════════════════════════════════════════════════
--  Trident helpers
-- ═════════════════════════════════════════════════════════════

local TRIDENT      = "trial_chamber:trident"
local TRIDENT_PROJ = "trial_chamber:trident_projectile"

-- Minecraft Java Edition values (1.21)
local MC = {
    -- Melee
    melee_damage       = 9,
    melee_speed        = 1.1,
    melee_range        = 3,

    -- Throw
    throw_damage       = 8,
    throw_charge_time  = 0.5,

    -- Riptide
    riptide_damage     = 8,

    -- Loyalty
    loyalty_speed      = {0, 6, 12, 18},

    -- Impaling
    impaling_bonus     = {0, 2.5, 5, 7.5, 10, 12.5},

    -- Durability
    max_durability     = 250,
}

-- Riptide / throw runtime constants (derived from MC table)
local RIPTIDE_LAUNCH_SPEED = 76              -- m/s, matches ~21-block riptide
local RIPTIDE_COOLDOWN     = 0.5             -- seconds between riptides
local RIPTIDE_DURATION     = 0.35            -- seconds velocity is sustained
local MIN_CHARGE_TO_THROW  = 0.1             -- fraction: below this, don't throw
local CHARGE_TIME_MAX      = MC.throw_charge_time  -- 0.5s
local THROW_SPEED_MIN      = 20              -- m/s at minimum charge
local THROW_SPEED_MAX      = 56              -- m/s at full charge

local RIPTIDE_GRAVITY       = 0.0   -- slightly lower = longer hang
local RIPTIDE_FLIGHT_TIME   = 1.0    -- shorter = higher initial speed (dist / time)

-- Enchantment helpers
local function get_trident_enchants(itemstack)
    local meta = itemstack:get_meta()
    return {
        loyalty    = meta:get_int("loyalty")    or 0,
        riptide    = meta:get_int("riptide")    or 0,
        channeling = meta:get_int("channeling") or 0,
        impaling   = meta:get_int("impaling")   or 0,
    }
end

local function set_trident_enchants(itemstack, e)
    local meta = itemstack:get_meta()
    meta:set_int("loyalty",    e.loyalty    or 0)
    meta:set_int("riptide",    e.riptide    or 0)
    meta:set_int("channeling", e.channeling or 0)
    meta:set_int("impaling",   e.impaling   or 0)
    return itemstack
end

-- Riptide is incompatible with Loyalty and Channeling (MC rule).
-- Riptide wins; the other two are zeroed out.
local function resolve_enchants(e)
    if e.riptide > 0 then
        e.loyalty    = 0
        e.channeling = 0
    end
    return e
end

-- Thunderstorm check for Channeling. Wire this to whatever weather
-- mod you actually use; this version silently returns false if none
-- of the known APIs are present.
local function is_thunderstorm(pos)
    -- climate_api
    if core.global_exists("climate_api") and climate_api.environment then
        local ok, presets = pcall(climate_api.environment.get_weather_presets,
            {get_pos = function() return pos end})
        if ok and type(presets) == "table" then
            for _, w in ipairs(presets) do
                w = tostring(w):lower()
                if w:find("thunder") or w:find("storm") then
                    return true
                end
            end
        end
    end
    -- climate_mod (per-player weather table)
    if core.global_exists("climate_mod") and climate_mod.current_weather then
        -- climate_mod keys weather by player name; a positional check
        -- isn't reliable. Return false here unless you have a per-player
        -- context β€” channeling will still work if climate_api is present.
    end
    return false
end

local riptiding_players = {}
local charging_players  = {}
local charge_hud        = {}

-- ═════════════════════════════════════════════════════════════
--  Water / rain check
-- ═════════════════════════════════════════════════════════════
local function is_in_water_or_rain(player)
    local pos = player:get_pos()
    pos.y = pos.y + 1

    local feet = core.get_node({x = pos.x, y = pos.y - 1, z = pos.z})
    local head = core.get_node({x = pos.x, y = pos.y + 1, z = pos.z})
    local feet_def = core.registered_nodes[feet.name]
    local head_def = core.registered_nodes[head.name]
    local feet_liquid = feet_def and feet_def.liquidtype and feet_def.liquidtype ~= "none"
    local head_liquid = head_def and head_def.liquidtype and head_def.liquidtype ~= "none"
    if feet_liquid or head_liquid then return true end

    if core.global_exists("climate_api") and climate_api.environment
       and type(climate_api.environment.get_weather_presets) == "function" then
        local ok, presets = pcall(climate_api.environment.get_weather_presets, player)
        if ok and type(presets) == "table" then
            for _, wname in ipairs(presets) do
                wname = tostring(wname):lower()
                if wname:find("rain") or wname:find("storm")
                   or wname:find("thunder") or wname:find("snow") then
                    return true
                end
            end
        end
    end

    if core.global_exists("climate_mod") and climate_mod.current_weather then
        local pname = player:get_player_name()
        local list = climate_mod.current_weather[pname]
        if list then
            for _, wname in ipairs(list) do
                wname = tostring(wname):lower()
                if wname:find("rain") or wname:find("storm")
                   or wname:find("thunder") or wname:find("snow") then
                    return true
                end
            end
        end
    end

    return false
end

-- ═════════════════════════════════════════════════════════════
--  Fire trident (throw OR riptide)
-- ═════════════════════════════════════════════════════════════
local riptide_cooldown = {}

local function fire_trident(player, itemstack, charge_pct)
    local name = player:get_player_name()
    local ench = resolve_enchants(get_trident_enchants(itemstack))

    -- Riptide β€” ONLY if enchanted AND wet
    if ench.riptide > 0 and is_in_water_or_rain(player) then
        local now = core.get_gametime()
        if riptide_cooldown[name] and (now - riptide_cooldown[name]) < RIPTIDE_COOLDOWN then
            return itemstack
        end
        riptide_cooldown[name] = now

                local dir   = player:get_look_dir()

        -- Flight distance per level. Tuned so a ~45Β°-down look
        -- lands you roughly 9/15/21 blocks away.
        local dist  = ({9, 15, 21})[math.min(ench.riptide, 3)]
        local speed = dist / RIPTIDE_FLIGHT_TIME

        -- Break ground/liquid contact so the first physics tick
        -- doesn't zero our vertical velocity.
        local p = player:get_pos()
        player:set_pos({x = p.x, y = p.y + 0.2, z = p.z})

        -- Reduced gravity for the flight arc (restored in globalstep)
        player:set_physics_override({gravity = RIPTIDE_GRAVITY})

        -- Launch: follow look direction, with a small guaranteed
        -- upward pop so a downward look still clears the ground.
        player:add_velocity({
            x = dir.x * speed,
            y = dir.y * speed,
            z = dir.z * speed,
        })

        -- Continuous particle trail attached to the player
        local trail = core.add_particlespawner({
            amount = 6,
            time   = RIPTIDE_FLIGHT_TIME,
            attached = player,
            minpos = {x=-0.4, y=-0.4, z=-0.4},
            maxpos = {x= 0.4, y= 0.4, z= 0.4},
            minvel = {x=0, y=0, z=0},
            maxvel = {x=0, y=0, z=0},
            minexptime = 0.35,
            maxexptime = 0.7,
            minsize = 1.5,
            maxsize = 3.0,
            texture = "wind_charge_explode_particle.png",
            glow    = 5,
        })

        riptiding_players[name] = {
            timer        = RIPTIDE_DURATION,
            flight_timer = RIPTIDE_FLIGHT_TIME,
            hit_done     = false,
            -- NEW: horizontal component to sustain
            vx = dir.x * speed,
            vz = dir.z * speed,
        }

        itemstack:add_wear(65535 / 100)
        player:set_wielded_item(itemstack)
        return itemstack
    end

    -- Throw
    if charge_pct < MIN_CHARGE_TO_THROW then
        return itemstack
    end

    local speed = THROW_SPEED_MIN + (THROW_SPEED_MAX - THROW_SPEED_MIN) * charge_pct
    local dir   = player:get_look_dir()

    local pos = player:get_pos()
    pos.y = pos.y + 1.5
    pos = vector.add(pos, vector.multiply(dir, 0.8))

    local staticdata = core.serialize({
        owner      = name,
        loyalty    = ench.loyalty,
        impaling   = ench.impaling,
        channeling = ench.channeling > 0,
    })

    local obj = core.add_entity(pos, TRIDENT_PROJ, staticdata)
    if obj then
        obj:set_velocity(vector.multiply(dir, speed))
        core.sound_play("default_grass_footstep",
            {pos = pos, gain = 1.2, max_hear_distance = 12})
        itemstack:take_item()
        player:set_wielded_item(itemstack)
    end
    return itemstack
end

-- ═════════════════════════════════════════════════════════════
--  Globalstep
-- ═════════════════════════════════════════════════════════════
local riptide_check_timer = 0

core.register_globalstep(function(dtime)
    riptide_check_timer = riptide_check_timer + dtime
    if riptide_check_timer < 0.05 then return end
    riptide_check_timer = 0

    -- Riptide sustain + collision
    for name, data in pairs(riptiding_players) do
        local player = core.get_player_by_name(name)
        if not player then
            riptiding_players[name] = nil
        else
            -- Count down collision window
            if data.timer > 0 then
                data.timer = data.timer - 0.05
            end

            -- Count down flight time; restore gravity when done
            if data.flight_timer then
                data.flight_timer = data.flight_timer - 0.05
                if data.flight_timer <= 0 then
                    player:set_physics_override({gravity = 1})
                    data.flight_timer = nil
                else
                    -- Keep horizontal speed constant against air drag.
                    -- Leave Y alone so gravity still shapes the arc.
                    local v = player:get_velocity()
                    player:set_velocity({
                        x = data.vx,
                        y = v.y,
                        z = data.vz,
                    })
                end
            end

            -- Done: remove from table only when both timers are finished
            if data.timer <= 0 and not data.flight_timer then
                riptiding_players[name] = nil
            else
                -- Collision damage window (unchanged)
                if data.timer > 0 and not data.hit_done then
                    local ppos = player:get_pos()
                    local objs = core.get_objects_inside_radius(ppos, 1.5)
                    for _, obj in ipairs(objs) do
                        if obj ~= player then
                            local dmg = MC.riptide_damage
                            local vel = player:get_velocity()
                            if vel and vel.y < -0.1 then
                                dmg = dmg * 1.5
                            end
                            if obj:is_player() then
                                obj:set_hp(obj:get_hp() - dmg)
                            else
                                obj:punch(player, 1.0, {
                                    full_punch_interval = 0.5,
                                    damage_groups = {fleshy = dmg},
                                }, nil)
                            end
                            core.sound_play("default_dig_metal", {
                                pos = ppos, gain = 1.0, max_hear_distance = 20,
                            })
                            data.hit_done = true
                            break
                        end
                    end
                end
            end
        end
    end

    -- Charge tracking (auto-fire at 100%)
    for name, data in pairs(charging_players) do
        local player = core.get_player_by_name(name)
        if not player then
            if charge_hud[name] then charge_hud[name] = nil end
            charging_players[name] = nil
        else
            local item = player:get_wielded_item()
            if item:get_name() ~= TRIDENT then
                if charge_hud[name] then
                    player:hud_remove(charge_hud[name])
                    charge_hud[name] = nil
                end
                charging_players[name] = nil
            else
                -- Cancel charge if Riptide player walks into dry area
                local ench = resolve_enchants(get_trident_enchants(item))
                if ench.riptide > 0 and not is_in_water_or_rain(player) then
                    if charge_hud[name] then
                        player:hud_remove(charge_hud[name])
                        charge_hud[name] = nil
                    end
                    charging_players[name] = nil
                else
                    local now = core.get_us_time() / 1000000
                    local elapsed = now - data.start
                    data.peak = elapsed

                    local pct = math.min(100, math.floor((elapsed / MC.throw_charge_time) * 100))
                    local color = pct >= 100 and 0x00ff00 or 0xFFFFFF
                    local hud_text = string.format("Charge: %d%%", pct)

                    if charge_hud[name] then
                        player:hud_change(charge_hud[name], "text", hud_text)
                        player:hud_change(charge_hud[name], "number", color)
                    else
                        charge_hud[name] = player:hud_add({
                            hud_elem_type = "text",
                            position = {x = 0.5, y = 0.85},
                            text = hud_text,
                            number = color,
                            alignment = {x = 0, y = 0},
                            offset = {x = 0, y = 0},
                            scale = {x = 100, y = 100},
                        })
                    end

                    if elapsed > (data.last_sound or 0) + 0.25 then
                        data.last_sound = elapsed
                        core.sound_play("default_dig_metal", {
                            to_player = name, gain = 0.15,
                        })
                    end

                    -- Auto-fire at 100%
                    if elapsed >= MC.throw_charge_time then
                        if charge_hud[name] then
                            player:hud_remove(charge_hud[name])
                            charge_hud[name] = nil
                        end
                        fire_trident(player, item, 1.0)
                        charging_players[name] = nil
                    end
                end
            end
        end
    end
end)

core.register_on_leaveplayer(function(player)
    local name = player:get_player_name()
    if charge_hud[name] then
        player:hud_remove(charge_hud[name])
        charge_hud[name] = nil
    end
    charging_players[name] = nil
    riptiding_players[name] = nil
    player:set_physics_override({gravity = 1})
end)

-- ═════════════════════════════════════════════════════════════
--  The Trident tool
-- ═════════════════════════════════════════════════════════════
core.register_tool(TRIDENT, {
    description = "Trident\nLMB: melee (9 dmg)\nRMB: charge & throw\nRiptide in water/rain: launch",
    inventory_image = "mcl_tridents_trident_item.png",
    wield_image = "mcl_tridents_trident_item.png",
    wield_scale = {x = 1.6, y = 1.6, z = 1},
    stack_max = 1,
    groups = {tools = 1, weapon = 1},

    tool_capabilities = {
        full_punch_interval = 1.0 / MC.melee_speed,  -- ~0.909s
        max_drop_level = 1,
        damage_groups = {fleshy = MC.melee_damage},   -- 9
        punch_attack_uses = MC.max_durability,        -- 250
    },

    range = MC.melee_range,

    on_use = function(itemstack, user, pointed_thing)
    -- LMB on an entity β†’ melee handled by tool_capabilities; do NOT charge
        if pointed_thing and pointed_thing.type == "object" then
            return itemstack
        end

        local name = user:get_player_name()
        local ench = resolve_enchants(get_trident_enchants(itemstack))

        -- If already charging β†’ fire early
        if charging_players[name] then
            local data = charging_players[name]
            if charge_hud[name] then
                user:hud_remove(charge_hud[name]); charge_hud[name] = nil
            end
            charging_players[name] = nil
            return fire_trident(user, itemstack,
                math.min(1.0, data.peak / CHARGE_TIME_MAX))
        end

        -- Riptide: instant launch if wet and enchanted
        if ench.riptide > 0 and is_in_water_or_rain(user) then
            return fire_trident(user, itemstack, 1.0)
        end

        -- Start charging
        charging_players[name] = {
            start = core.get_us_time() / 1000000,
            peak = 0,
            last_sound = 0,
        }
        return itemstack
    end,
})

core.register_entity(TRIDENT_PROJ, {
    initial_properties = {
        physical = true,
        collide_with_objects = false,
        collisionbox = {-0.25, -0.25, -0.25, 0.25, 0.25, 0.25},
        visual = "wielditem",
        wield_item = TRIDENT,
        visual_size = {x = 0.8, y = 0.8},
    },

    owner        = nil,
    owner_name   = "",
    loyalty      = 0,     -- enchantment level
    impaling     = 0,
    channeling   = false,
    stuck        = false,
    returning    = false,
    return_timer = 0,
    lifetime     = 0,

    on_activate = function(self, staticdata)
        if staticdata and staticdata ~= "" then
            local data = core.deserialize(staticdata)
            if type(data) == "table" then
                self.owner_name = data.owner or ""
                self.loyalty    = data.loyalty or 0
                self.impaling   = data.impaling or 0
                self.channeling = data.channeling or false
            end
        end
        self.owner      = core.get_player_by_name(self.owner_name)
        self.spawn_time = core.get_gametime()
        self.object:set_armor_groups({immaterial = 1})
    end,

    get_staticdata = function(self)
        return core.serialize({
            owner      = self.owner_name,
            loyalty    = self.loyalty,
            impaling   = self.impaling,
            channeling = self.channeling,
        })
    end,

    -- Loyalty: fly back to owner
    start_return = function(self)
        if self.returning then return end
        self.returning = true
        self.stuck = false
        self.object:set_acceleration({x = 0, y = 0, z = 0})
        self.object:set_velocity({x = 0, y = 0, z = 0})
    end,

    on_step = function(self, dtime)
        self.lifetime = self.lifetime + dtime
        if self.lifetime > 30 then
            self.object:remove()
            return
        end



        -- Returning logic
        if self.returning then
            local owner = core.get_player_by_name(self.owner_name)
            if not owner then
                self.object:remove(); return
            end

            local opos = owner:get_pos()
            local pos  = self.object:get_pos()
            local dir  = vector.direction(pos, opos)
            local dist = vector.distance(pos, opos)
            local speed = MC.loyalty_speed[self.loyalty] or 6

            self.object:set_velocity(vector.multiply(dir, speed))

            if dist < 1.5 then
                local inv = owner:get_inventory()
                if inv:room_for_item("main", TRIDENT) then
                    inv:add_item("main", TRIDENT)
                    self.object:remove()
                end
            end
            return
        end

        -- Orientation
        local vel = self.object:get_velocity()
        if vel and (vel.x ~= 0 or vel.y ~= 0 or vel.z ~= 0) then
            local yaw   = math.atan2(vel.x, vel.z)
            local pitch = -math.atan2(vel.y, math.sqrt(vel.x^2 + vel.z^2))
            self.object:set_rotation({x = pitch, y = yaw, z = 0})
        end

        -- Entity hit
        local pos = self.object:get_pos()
        if not pos then return end

        for _, obj in ipairs(core.get_objects_inside_radius(pos, 0.75)) do
            if obj ~= self.object then
                local is_owner = obj:is_player()
                    and obj:get_player_name() == self.owner_name
                if not is_owner then
                    -- Impaling bonus
                    local dmg = MC.throw_damage
                    local le = obj:get_luaentity()
                    if le and le.type == "animal" and le.is_aquatic then
                        dmg = dmg + (MC.impaling_bonus[self.impaling] or 0)
                    end

                    if obj:is_player() then
                        obj:set_hp(obj:get_hp() - dmg)
                    else
                        obj:punch(self.object, 1.0, {
                            full_punch_interval = 1.0,
                            damage_groups = {fleshy = dmg},
                        }, vel)
                    end

                    -- Channeling: lightning on hit during thunderstorm
                    if self.channeling and is_thunderstorm(obj:get_pos()) then
                        core.add_entity(obj:get_pos(), "trial_chamber:lightning_strike")
                    end

                    -- Wear the trident
                    -- (handled by caller via on_pickup, or just remove here)
                    self.object:remove()
                    return
                end
            end
        end

        -- Node hit
        local node = core.get_node(pos)
        local def  = core.registered_nodes[node.name]
        if def and def.walkable then
            if self.loyalty > 0 then
                self:start_return()
            else
                self.object:set_velocity({x = 0, y = 0, z = 0})
                self.object:set_acceleration({x = 0, y = 0, z = 0})
                self.stuck = true
            end
        end
    end,

    on_punch = function(self, puncher)
        if puncher and puncher:is_player() then
            local inv = puncher:get_inventory()
            if inv:room_for_item("main", TRIDENT) then
                inv:add_item("main", TRIDENT)
                self.object:remove()
            end
        end
    end,
})

-- ======================
--  Find Trial command
-- ======================
core.register_chatcommand("find_trial", {
    description = "Find the nearest Trial Chamber",
    func = function(name)
        local player = core.get_player_by_name(name)
        if not player then return false, "Player not found." end
        if #trial_chambers == 0 then
            return false, "No Trial Chambers have been generated yet."
        end

        local player_pos = player:get_pos()
        local nearest, nearest_distance = nil, math.huge

        for _, chamber_pos in ipairs(trial_chambers) do
            local distance = vector.distance(player_pos, chamber_pos)
            if distance < nearest_distance then
                nearest_distance = distance
                nearest = chamber_pos
            end
        end

        return true, string.format(
            "Nearest Trial Chamber: X=%d Y=%d Z=%d | %.0f blocks away",
            nearest.x, nearest.y, nearest.z, nearest_distance
        )
    end,
})

-- ======================
--  World generation
-- ======================
local CHAMBER_SIZE_X = 90
local CHAMBER_SIZE_Z = 90
local CHAMBER_SIZE_Y = 25

local CHAMBER_Y_MIN = -100
local CHAMBER_Y_MAX = -300

local CHAMBER_CHANCE = 75

core.register_on_generated(function(minp, maxp, seed)
    if minp.y > CHAMBER_Y_MIN or maxp.y < CHAMBER_Y_MAX then
        return
    end

    if math.random(1, CHAMBER_CHANCE) ~= 1 then
        return
    end

    local y = math.random(CHAMBER_Y_MAX, CHAMBER_Y_MIN)
    local pos = {
        x = math.floor((minp.x + maxp.x) / 2),
        y = y,
        z = math.floor((minp.z + maxp.z) / 2),
    }

    local schematic_path = core.get_modpath("trial_chamber")
        .. "/schems/trial_chamber.mts"

    local result = core.place_schematic(
        pos, schematic_path, "random", nil, true,
        "place_center_x, place_center_z"
    )

    if result == nil then
        print("[TRIAL] ERROR: Could not load trial_chamber.mts")
        return
    end

    print("[TRIAL] CHAMBER GENERATED AT:", pos.x, pos.y, pos.z)

    table.insert(trial_chambers, vector.copy(pos))
    trial_count = trial_count + 1
    trial_storage:set_int("chamber_count", trial_count)
    trial_storage:set_string("chamber_" .. trial_count, core.pos_to_string(pos))

    local chest_min = {
        x = pos.x - CHAMBER_SIZE_X / 2,
        y = pos.y - CHAMBER_SIZE_Y / 2,
        z = pos.z - CHAMBER_SIZE_Z / 2,
    }
    local chest_max = {
        x = pos.x + CHAMBER_SIZE_X / 2,
        y = pos.y + CHAMBER_SIZE_Y / 2,
        z = pos.z + CHAMBER_SIZE_Z / 2,
    }

    local chest_nodes = core.find_nodes_in_area(
        chest_min, chest_max, {"default:chest"}
    )

    core.log("action", "[trial_chamber] Found " .. #chest_nodes .. " chest(s) in chamber")

    for _, chest_pos in ipairs(chest_nodes) do
        fill_chest(chest_pos, TRIAL_LOOT_NORMAL, 3, 8)
    end
end)

-- /ench_trident  
-- Examples:
--   /ench_trident riptide 3
--   /ench_trident loyalty 3
--   /ench_trident channeling 1
--   /ench_trident impaling 5
core.register_chatcommand("ench_trident", {
    params = " ",
    description = "Enchant the held trident (testing)",
    func = function(name, param)
        local player = core.get_player_by_name(name)
        if not player then return false, "Player not found." end

        local enchant, lvl_str = param:match("^(%S+)%s+(%d+)$")
        if not enchant then
            return false, "Usage: /ench_trident  "
        end
        local level = tonumber(lvl_str)
        if not level then return false, "Level must be a number." end

        local valid = {
            riptide    = {max = 3},
            loyalty    = {max = 3},
            channeling = {max = 1},
            impaling   = {max = 5},
        }
        if not valid[enchant] then
            return false, "Unknown enchant. Use: riptide, loyalty, channeling, impaling."
        end
        if level < 0 or level > valid[enchant].max then
            return false, "Level must be 0-" .. valid[enchant].max .. "."
        end

        local stack = player:get_wielded_item()
        if stack:get_name() ~= TRIDENT then
            return false, "Hold a trident in your hand first."
        end

        -- Read current enchants and set the one we're changing
        local ench = get_trident_enchants(stack)
        ench[enchant] = level

        -- Riptide overrides Loyalty/Channeling
        ench = resolve_enchants(ench)

        set_trident_enchants(stack, ench)
        player:set_wielded_item(stack)

        return true, string.format("Set %s = %d on the held trident.",
            enchant, level)
    end,
})
Kodari AI
KodariOct 7 at 1:44 pm 2

Plan: create a minimal Luanti mod manifest and a standalone trident implementation with wet-weather Riptide, charged throws, and recoverable projectiles; leave the rest of the trial-chamber systems out.

Created a standalone Luanti mod with just the trident mechanics. Riptide launches the player in water or rain, with a cooldown, temporary gravity change, and collision damage. Charged throws, enchantment metadata, Loyalty returns, and /ench_trident are included.

Use /ench_trident riptide 3 while holding the trident to try it out.

Lightningwolf

hello?

Kodari AI
KodariOct 7 at 1:49 pm 1

Hi! What are you building?

Lightningwolf

so this works as similer to mc trident as possible? no diffrence?

Kodari AI
KodariOct 7 at 1:51 pm 1

Not exactly. It recreates the main trident mechanics, but there are still differences from Minecraft:

  • Throwing can auto-fire after half a second instead of behaving like Minecraft’s charge-and-release.

  • Throwing doesn’t apply the usual durability cost.

  • Riptide can activate in snow, which isn’t vanilla behavior.

  • Pickup, Channeling, and hit detection are simplified or behave differently.

So it’s trident-like, but not β€œno difference.”

Lightningwolf

but the riptide can fly just like in mc?

Kodari AI
KodariOct 7 at 1:54 pm 1

Yesβ€”it launches you through the air in the direction you’re looking, like Riptide in Minecraft. It’s not an exact match, though: this version sets your velocity directly and reduces gravity for about 0.65 seconds, so the flight can feel different.

Lightningwolf

is it possible to make it an exact match somehow?

Kodari AI
KodariOct 7 at 1:56 pm 1

Not exactly in this project: it’s a Luanti mod, not a Minecraft plugin, so it can’t invoke Minecraft’s built-in Riptide physics. We can tune its launch, gravity, and collision behavior to feel much closer, but a perfect match would require Minecraft’s own engine.

Lightningwolf

is it possible to make it an exact match somehow?

Kodari AI
KodariOct 7 at 2:00 pm 1

If this stays a Luanti mod, noβ€”not exactly. It uses custom velocity and gravity, and Luanti’s physics differ from Minecraft’s. We can tune it to feel closer, but matching vanilla perfectly isn’t realistic.

For exact vanilla Riptide, it would need to run in Minecraft and let Minecraft handle the trident mechanics.

Lightningwolf

is it not just a charge then like launch with like no gravity or close like that?

Kodari AI
KodariOct 7 at 2:01 pm 1

Pretty muchβ€”it’s a launch, but not a charge-and-release mechanic, and vanilla doesn’t turn gravity off. Using a Riptide trident in water or rain gives you a strong boost in the direction you’re looking; normal gravity continues, so you follow an arc. To get closer, use a launch impulse and leave gravity and collisions alone rather than reducing gravity temporarily.

Lightningwolf

so cant we do that? :/

Kodari AI
KodariOct 7 at 2:02 pm 1

Yeah, we can do that. Make Riptide apply a launch boost in the direction you’re looking, then leave normal gravity and collisions alone. It should feel much closer to Minecraft’s arcβ€”though Luanti’s physics still mean it won’t be perfectly identical.

Kodari can make mistakes. Review important code before using.
Files
init.lua
mod.conf
Code
2 542