### Implement Categorized Logging in Lua Source: https://context7.com/aussiemon/darktide-source-code/llms.txt Shows how to use the Log system for categorized logging with different severity levels (DEBUG, INFO, WARNING, EXCEPTION, ERROR). It covers setting global and category-specific log levels and querying current settings. ```lua -- Log levels: DEBUG (1), INFO (2), WARNING (3), EXCEPTION (4), ERROR (5) Log.set_global_log_level(2) -- INFO and above -- Categorized logging Log.debug("MySystem", "Debug message with value: %d", some_value) Log.info("MySystem", "Player %s connected", player_name) Log.warning("MySystem", "Resource %s not found, using default", resource_name) Log.exception("MySystem", "Failed to load: %s", error_message) Log.error("MySystem", "Critical error: %s", error_message) -- Set category-specific log level Log.set_category_log_level("NetworkManager", Log.DEBUG) -- Enable debug for specific category Log.reset_category_log_level("NetworkManager") -- Reset to global level -- Query log levels local level, tag = Log.global_log_level() -- Returns: 2, "INFO" Log.print_log_levels() -- Print all category log levels ``` -------------------------------- ### Manage Player Gear and Inventory (Lua) Source: https://context7.com/aussiemon/darktide-source-code/llms.txt This Lua snippet details how to use the GearService to manage player inventory, equipment, and gear. It includes functions for fetching all gear, fetching inventory with filters, paginated fetching, deleting single items or batches, attaching cosmetic overrides, and managing cache and event handlers. ```lua local gear_service = Managers.data_service.gear -- Fetch all gear (returns promise) gear_service:fetch_gear():next(function(gear_list) for gear_id, gear_data in pairs(gear_list) do Log.info("Gear", "Item: %s, Type: %s", gear_id, gear_data.masterDataInstance.id) end end):catch(function(error) Log.error("Gear", "Failed to fetch: %s", tostring(error)) end) -- Fetch inventory for specific character with filters local slot_filter = { "slot_primary", "slot_secondary" } local type_filter = { "WEAPON_MELEE", "WEAPON_RANGED" } gear_service:fetch_inventory(character_id, slot_filter, type_filter):next(function(items) for item_id, item in pairs(items) do local item_name = item.display_name local item_type = item.item_type end end) -- Fetch with pagination gear_service:fetch_inventory_paged(character_id, 100, slot_filter):next(function(items) -- Process first page end) -- Delete gear gear_service:delete_gear(gear_id):next(function(result) Log.info("Gear", "Deleted item successfully") end) -- Batch delete gear_service:delete_gear_batch({ gear_id1, gear_id2, gear_id3 }):next(function(results) for _, result in ipairs(results) do Log.info("Gear", "Deleted: %s", result.gearId) end end) -- Attach cosmetic override gear_service:attach_item_as_override(cosmetic_id, "slot_primary_skin", weapon_gear_id) -- Cache management gear_service:invalidate_gear_cache() gear_service:populate_gear_cache() -- Handle gear changes gear_service:on_gear_created(gear_id, gear_data) gear_service:on_gear_updated(gear_id, gear_data) gear_service:on_gear_deleted(gear_id) gear_service:on_character_deleted(character_id) ``` -------------------------------- ### Define and Use Classes in Lua Source: https://context7.com/aussiemon/darktide-source-code/llms.txt Demonstrates how to define new classes, implement constructors and methods, and utilize inheritance and interfaces within the Lua scripting environment. This system supports automatic cleanup of instances. ```lua -- Define a new class local MyClass = class("MyClass") -- Constructor MyClass.init = function(self, param1, param2) self._value = param1 self._data = param2 end -- Instance method MyClass.get_value = function(self) return self._value end -- Destructor (called automatically on delete) MyClass.destroy = function(self) self._value = nil end -- Create instance local instance = MyClass:new("hello", { foo = "bar" }) print(instance:get_value()) -- "hello" -- Delete instance (calls destroy automatically) instance:delete() -- Class with inheritance local ChildClass = class("ChildClass", "MyClass") ChildClass.init = function(self, param1, param2, extra) ChildClass.super.init(self, param1, param2) -- Call parent constructor self._extra = extra end -- Implement interfaces implements(ChildClass, SomeInterface) ``` -------------------------------- ### Platform and Build Detection (Lua) Source: https://context7.com/aussiemon/darktide-source-code/llms.txt Provides global constants to detect the current platform (Windows, Xbox, PlayStation) and build configuration (version, identifier, dedicated server status, Steam integration, GDK). ```lua -- Platform checks if IS_WINDOWS then -- Windows PC specific code elseif IS_XBS then -- Xbox Series X/S specific code elseif IS_PLAYSTATION then -- PS5 specific code end -- Build info local build_version = BUILD -- e.g., "release", "debug" local build_id = BUILD_IDENTIFIER local is_dedicated = DEDICATED_SERVER local is_steam = HAS_STEAM local is_gdk = IS_GDK -- Xbox Game Development Kit on PC -- Application settings local settings = APPLICATION_SETTINGS local tick_rate = GameParameters.tick_rate ``` -------------------------------- ### Manage Events with Pub/Sub Pattern in Lua Source: https://context7.com/aussiemon/darktide-source-code/llms.txt Illustrates the use of the EventManager for implementing a publish-subscribe pattern, enabling decoupled communication between game systems. It covers registering callbacks, triggering events, and unregistering listeners. ```lua -- Register for events (object, event_name, callback_name pairs) Managers.event:register(self, "event_player_spawned", "on_player_spawned", "event_player_died", "on_player_died", "event_buff_added", "on_buff_added" ) -- Callback implementation in the registered object MySystem.on_player_spawned = function(self, player, spawn_position) Log.info("MySystem", "Player %s spawned at position", player:name()) end -- Register with extra parameters (curry-style) Managers.event:register_with_parameters(self, "event_damage_dealt", "on_damage", unit) -- Trigger events from anywhere Managers.event:trigger("event_player_spawned", player, spawn_position) Managers.event:trigger("event_damage_dealt", attacker, target, damage_amount) -- Unregister when done (important for cleanup) Managers.event:unregister(self, "event_player_spawned") Managers.event:unregister(self, "event_player_died") ``` -------------------------------- ### Lua Game State Machine for Game Lifecycle Management Source: https://context7.com/aussiemon/darktide-source-code/llms.txt The GameStateMachine in Lua manages game state transitions, such as boot, loading, gameplay, and menus, ensuring proper lifecycle handling. It allows defining states with `on_enter`, `update`, and `on_exit` methods, and provides functionality to force state changes and register for state change notifications. ```lua -- Create state machine with initial state local params = { package_manager = package_manager, localization_manager = localization_manager, next_state = "StateGame", } local state_machine = GameStateMachine:new( nil, -- parent StateBoot, -- start_state class params, -- initial params nil, -- creation_context nil, -- state_change_callbacks "", -- parent_name "Main", -- name true -- log_breadcrumbs ) -- State class implementation local StateGame = class("StateGame") StateGame.on_enter = function(self, parent, params, creation_context) self._world = params.world Log.info("StateGame", "Entering game state") end StateGame.update = function(self, dt, t) -- Game logic here if should_change_state then return StateMenu, { reason = "paused" } -- Return next state end return nil -- Stay in current state end StateGame.on_exit = function(self, exit_params) Log.info("StateGame", "Exiting game state") end -- Update loop state_machine:update(dt) state_machine:render() state_machine:post_update(dt, t) -- Force state change state_machine:force_change_state(StateMenu, { from = "game" }, { cleanup = true }) -- Register for state change notifications state_machine:register_on_state_change_callback("my_listener", function(old_state, new_state) Log.info("StateMachine", "Changed from %s to %s", old_state, new_state) end) ``` -------------------------------- ### Manage Buffs and Status Effects with BuffExtension (Lua) Source: https://context7.com/aussiemon/darktide-source-code/llms.txt The BuffExtension manages status effects, stat modifiers, keywords, and proc events on units. It allows adding and removing buffs, checking for their presence, managing stacks, refreshing durations, and interacting with the keyword and stat buff systems. Proc events can also be triggered. ```lua -- Access buff extension local buff_ext = ScriptUnit.extension(unit, "buff_system") -- Add buffs (server-side) local buff_index = buff_ext:add_internally_controlled_buff("buff_template_name", t, "owner_unit", caster_unit, "buff_lerp_value", 0.5 ) -- Add multiple stacks at once buff_ext:add_internally_controlled_buff_with_stacks("buff_name", 3, t) -- Remove buff by index buff_ext:remove_externally_controlled_buff(buff_index) -- Check for buffs local has_buff = buff_ext:has_buff_using_buff_template("regen_buff") local has_with_owner = buff_ext:has_buff_using_buff_template_with_owner("buff_name", owner_unit) local has_any = buff_ext:has_buff_using_buff_templates("buff1", "buff2", "buff3") local has_active = buff_ext:has_active_buff_with_buff_template("proc_buff") -- Stack management local stacks = buff_ext:current_stacks("stacking_buff") local start_time = buff_ext:buff_start_time("buff_name") local progress = buff_ext:buff_duration_progress("buff_name") -- 0.0 to 1.0 buff_ext:refresh_duration_of_stacking_buff("buff_name", t) buff_ext:add_duration_of_stacking_buff("buff_name", 5.0) -- Add 5 seconds -- Keyword system (tags for state checking) local has_keyword = buff_ext:has_keyword("burning") local has_any_keyword = buff_ext:has_any_keyword({ "stun", "knockdown", "suppressed" }) local had_recently = buff_ext:had_keyword("blocking", 1.0) -- Within last 1 second local all_keywords = buff_ext:keywords() -- Stat buffs (modifiers to character stats) local stat_buffs = buff_ext:stat_buffs() local damage_multiplier = stat_buffs.damage_dealt -- e.g., 1.25 for +25% local speed_modifier = stat_buffs.movement_speed -- Proc events (trigger effects based on game events) local param_table = buff_ext:request_proc_event_param_table() if param_table then param_table.damage_amount = 100 param_table.attack_type = "melee" buff_ext:add_proc_event("on_hit", param_table) end ``` -------------------------------- ### Lua Promise System for Asynchronous Operations Source: https://context7.com/aussiemon/darktide-source-code/llms.txt The Lua Promise system facilitates asynchronous operations by allowing chainable callbacks for backend communication and deferred computations. It supports creating, resolving, rejecting, chaining, and canceling promises, along with utility functions like `Promise.all`, `Promise.race`, and `Promise.delay`. ```lua -- Create a promise local promise = Promise:new(function(resolve, reject) -- Async operation if success then resolve(result_data) else reject({ message = "Operation failed", code = 500 }) end end) -- Chain promises with next/catch promise:next(function(data) Log.info("Promise", "Got data: %s", tostring(data)) return transformed_data -- Pass to next handler end):catch(function(error) Log.error("Promise", "Error: %s", error.message) end) -- Create pre-resolved/rejected promises local resolved = Promise.resolved({ items = {} }) local rejected = Promise.rejected({ message = "Not found" }) -- Wait for all promises local all_promise = Promise.all(promise1, promise2, promise3) all_promise:next(function(results) local result1, result2, result3 = unpack(results) end) -- Race - first to resolve wins local race_promise = Promise.race(promise1, promise2) -- Delayed promise (resolve after time) Promise.delay(2.0):next(function() Log.info("Promise", "2 seconds elapsed") end) -- Chain array of operations sequentially Promise.chain({ item1, item2, item3 }, function(item) return process_item(item) -- Returns promise end):next(function(results) -- All items processed in order end) -- Check promise state if promise:is_pending() then -- Still waiting elseif promise:is_fulfilled() then -- Completed successfully elseif promise:is_rejected() then -- Failed elseif promise:is_canceled() then -- Canceled end -- Cancel a pending promise promise:cancel() ``` -------------------------------- ### Manage Player Weapon State and Actions (Lua) Source: https://context7.com/aussiemon/darktide-source-code/llms.txt This snippet demonstrates how to access and manage player weapon states, actions, ammo, stamina, and combat mechanics using the PlayerUnitWeaponExtension in Lua. It covers accessing components for inventory, actions, blocking, aiming, stamina, shooting status, weapon templates, and targeting lock views. ```lua -- Access weapon extension local weapon_ext = ScriptUnit.extension(unit, "weapon_system") -- Weapon state components (read-only access) local inventory = weapon_ext._inventory_component local weapon_action = weapon_ext._weapon_action_component local block = weapon_ext._block_component local alternate_fire = weapon_ext._alternate_fire_read_component local stamina = weapon_ext._stamina_read_component -- Check blocking state local is_blocking = block.is_blocking local has_blocked = block.has_blocked local is_perfect_block = block.is_perfect_blocking -- Check alternate fire (aim down sights, special mode) local is_aiming = alternate_fire.is_active local aim_start_time = alternate_fire.start_t -- Stamina management local stamina_fraction = stamina.current_fraction -- 0.0 to 1.0 local regen_paused = stamina.regeneration_paused -- Shooting status local shooting_status = weapon_ext._shooting_status_component local is_shooting = shooting_status.shooting local shot_count = shooting_status.num_shots -- Get current weapon template local WeaponTemplate = require("scripts/utilities/weapon/weapon_template") local weapon_template = WeaponTemplate.current_weapon_template(weapon_action) local weapon_name = weapon_template and weapon_template.name -- Weapon lock view (for lock-on targeting) local lock_view = weapon_ext._weapon_lock_view_component local lock_state = lock_view.state -- "in_active", "searching", "locked" local lock_pitch = lock_view.pitch local lock_yaw = lock_view.yaw ``` -------------------------------- ### Access Backend Data Services (Lua) Source: https://context7.com/aussiemon/darktide-source-code/llms.txt This snippet shows how to access various backend data services through the Managers.data_service interface in Lua. It covers services for mission boards, talents, profiles, accounts, stores, gear, social features, crafting, and contracts. ```lua -- Access data services through Managers local data_service = Managers.data_service -- Available services local mission_board = data_service.mission_board local talents = data_service.talents local profiles = data_service.profiles local account = data_service.account local store = data_service.store local gear = data_service.gear local social = data_service.social local crafting = data_service.crafting local contracts = data_service.contracts ``` -------------------------------- ### Manage Unit Health and Damage with HealthExtension (Lua) Source: https://context7.com/aussiemon/darktide-source-code/llms.txt The HealthExtension manages unit health, damage, healing, and death for all damageable entities. It allows querying health state, dealing damage, applying healing, tracking damage sources, setting invulnerability, and forcing kills. Access is typically obtained via ScriptUnit.extension(unit, "health_system"). ```lua -- Health extension is automatically attached to units with health local health_ext = ScriptUnit.extension(unit, "health_system") -- Query health state local current_hp = health_ext:current_health() local max_hp = health_ext:max_health() local percent = health_ext:current_health_percent() -- 0.0 to 1.0 local damage_taken = health_ext:damage_taken() local is_alive = health_ext:is_alive() local health_depleted = health_ext:health_depleted() -- Deal damage local actual_damage = health_ext:add_damage( damage_amount, -- float: raw damage permanent_damage, -- float: permanent damage (wounds) hit_actor, -- actor that was hit damage_profile, -- damage profile table attack_type, -- "melee", "ranged", etc. attack_direction, -- Vector3 direction attacking_unit -- unit that dealt damage ) -- Heal local actual_heal = health_ext:add_heal(heal_amount, "heal_type_name") -- Track last damage source health_ext:set_last_damaging_unit(attacker_unit, "head", was_critical, hit_position) local last_attacker = health_ext:last_damaging_unit() local hit_zone = health_ext:last_hit_zone_name() local was_crit = health_ext:last_hit_was_critical() -- Invulnerability and unkillable flags health_ext:set_invulnerable(true) -- Ignore all damage health_ext:set_unkillable(true) -- Can take damage but won't die local is_invuln = health_ext:is_invulnerable() -- Force kill health_ext:kill() -- Triggers death immediately -- Get players who damaged this unit local damaging_players = health_ext:damaging_players() ``` -------------------------------- ### HumanPlayer Class Management (Lua) Source: https://context7.com/aussiemon/darktide-source-code/llms.txt Manages player identity, profile, archetype, unit status, orientation, slot, spawn point, and telemetry. It allows for creating player instances and modifying their properties. ```lua -- Create player instance local player = HumanPlayer:new( unique_id, session_id, channel_id, peer_id, local_player_id, profile, slot, account_id, viewport_name, telemetry_game_session, last_mission_id ) -- Identity local peer = player:peer_id() local account = player:account_id() local character = player:character_id() local name = player:name() local player_type = player:type() -- "HumanPlayer" -- Profile local profile = player:profile() player:set_profile(new_profile) -- Triggers "event_player_set_profile" -- Archetype info local archetype = player:archetype_name() -- "veteran", "zealot", etc. local breed = player:breed_name() -- "human" local companion = player:companion_name() -- Player unit local unit = player.player_unit local is_alive = player:unit_is_alive() -- Orientation (camera/look direction) player:set_orientation(yaw, pitch, roll) local orientation = player:get_orientation() local yaw = orientation.yaw local pitch = orientation.pitch -- Slot management local slot = player:slot() player:set_slot(new_slot) -- Spawn point player:set_wanted_spawn_point(spawn_point) local spawn = player:wanted_spawn_point() -- Telemetry local session = player:telemetry_game_session() local subject = player:telemetry_subject() -- { account_id, character_id } ``` -------------------------------- ### Resolution Lookup Table Update (Lua) Source: https://context7.com/aussiemon/darktide-source-code/llms.txt Manages UI scaling information by updating the RESOLUTION_LOOKUP table. It can be forced to update or updated with a custom scale multiplier for effects like zoom. ```lua -- Global resolution info local width = RESOLUTION_LOOKUP.width local height = RESOLUTION_LOOKUP.height local scale = RESOLUTION_LOOKUP.scale local inverse_scale = RESOLUTION_LOOKUP.inverse_scale local is_fullscreen = RESOLUTION_LOOKUP.fullscreen local was_modified = RESOLUTION_LOOKUP.modified -- Force update (call after resolution change) UPDATE_RESOLUTION_LOOKUP(true) -- force_update = true -- With custom scale multiplier (for zoom effects) UPDATE_RESOLUTION_LOOKUP(false, 1.5) -- 150% scale -- Use in UI calculations local ui_width = width * inverse_scale local button_size = 100 * scale ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.