diff --git a/README.md b/README.md index 8cdb1ef1..e1950212 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,7 @@ reference in **[docs/API.md](docs/API.md)**. | [Map](docs/API.md#map) | `C_Map.CanSetUserWaypointOnMap`, `C_Map.ClearUserWaypoint`, `C_Map.GetAreaInfo`, `C_Map.GetAreas`, `C_Map.GetAreaTriggerInfo`, `C_Map.GetAreaTriggers`, `C_Map.GetBestMapForUnit`, `C_Map.GetFallbackWorldMapID`, `C_Map.GetMapAreaIDs`, `C_Map.GetMapArtLayers`, `C_Map.GetMapArtLayerTextures`, `C_Map.GetMapChildrenInfo`, `C_Map.GetMapInfo`, `C_Map.GetMapInfoAtPosition`, `C_Map.GetMapOverlays`, `C_Map.GetMapPosFromWorldPos`, `C_Map.GetMapRectOnMap`, `C_Map.GetMapWorldSize`, `C_Map.GetPlayerMapPosition`, `C_Map.GetUserWaypoint`, `C_Map.GetUserWaypointFromHyperlink`, `C_Map.GetUserWaypointHyperlink`, `C_Map.GetUserWaypointPositionForMap`, `C_Map.GetWorldPosFromMapPos`, `C_Map.HasUserWaypoint`, `C_Map.MapHasArt`, `C_Map.SetUserWaypoint` | | [MapExplorationInfo](docs/API.md#mapexplorationinfo) | `C_MapExplorationInfo.GetExploredAreaIDsAtPosition`, `C_MapExplorationInfo.GetExploredMapTextures`, `C_MapExplorationInfo.GetUnexploredMapTextures` | | [MerchantFrame](docs/API.md#merchantframe) | `C_MerchantFrame.GetBuybackItemID`, `C_MerchantFrame.GetItemInfo`, `C_MerchantFrame.GetNumJunkItems`, `C_MerchantFrame.IsMerchantItemRefundable`, `C_MerchantFrame.IsSellAllJunkEnabled`, `C_MerchantFrame.SellAllJunkItems` | +| [Model](docs/API.md#model) | `DressUpModel:TryOn` (links, recipes, names), `DressUpModel:UndressSlot`, `Model:SetGlow`, `PlayerModel:RefreshCamera`, `PlayerModel:SetCamDistanceScale`, `PlayerModel:SetCreature`, `PlayerModel:SetDisplayInfo`, `PlayerModel:SetPortraitZoom`, `PlayerModel:SetRotation` (`animate`) | | [NamePlate](docs/API.md#nameplate) | `C_NamePlate.GetNamePlateForGUID`, `C_NamePlate.GetNamePlateForUnit`, `C_NamePlate.GetNamePlateGUIDs`, `C_NamePlate.GetNamePlates` | | [NameCache](docs/API.md#namecache) | `C_PlayerCache.GetPlayerInfoByName`, `C_PlayerCache.IsEnabled`, `C_PlayerCache.IsScanEnabled`, `C_PlayerCache.RememberPlayer`, `C_PlayerCache.SetEnabled`, `C_PlayerCache.SetScanEnabled`, `GetPlayerInfoByGUID`, `UnitNameFromGUID` | | [NewItems](docs/API.md#newitems) | `C_NewItems.ClearAll`, `C_NewItems.IsNewItem`, `C_NewItems.RemoveNewItem` | diff --git a/docs/API.md b/docs/API.md index 6fdfc131..0322f287 100644 --- a/docs/API.md +++ b/docs/API.md @@ -571,8 +571,15 @@ build instructions. - [`C_MerchantFrame.IsSellAllJunkEnabled()`](#c_merchantframeissellalljunkenabled) - [Model](#model) - - [`model:SetDisplayInfo(creatureDisplayID)`](#modelsetdisplayinfocreaturedisplayid) + - [`model:SetDisplayInfo(displayID)`](#modelsetdisplayinfodisplayid) - [`model:SetCreature(creatureID)`](#modelsetcreaturecreatureid) + - [`model:SetPortraitZoom(zoom)`](#modelsetportraitzoomzoom) + - [`model:SetCamDistanceScale(scale)`](#modelsetcamdistancescalescale) + - [`model:RefreshCamera()`](#modelrefreshcamera) + - [`model:SetRotation(rotation [, animate])`](#modelsetrotationrotation--animate) + - [`DressUpModel:UndressSlot(slot)`](#dressupmodelundressslotslot) + - [`DressUpModel:TryOn(item)`](#dressupmodeltryonitem) + - [`Model:SetGlow(value)`](#modelsetglowvalue) - [ChatBubbles](#chatbubbles) - [`C_ChatBubbles.GetAllChatBubbles([includeForbidden])`](#c_chatbubblesgetallchatbubblesincludeforbidden) @@ -13716,76 +13723,140 @@ local name = ids and C_Map.GetAreaInfo(ids[1]) ## Model -### `model:SetDisplayInfo(creatureDisplayID)` +These methods are on `PlayerModel` frames unless the heading says +otherwise. `DressUpModel` and `TabardModel` frames are `PlayerModel` +frames too, so they have the same methods. A `PlayerModel` sets its own +light and camera, so a model shows correctly without `SetLight` or +`SetCamera`. -Points a Model frame at a creature by its display ID. This is the -alternative to `Model:SetModel(path)`, which needs a raw model file path. +### `model:SetDisplayInfo(displayID)` -The engine resolves the display ID to a model file through two DBC tables: -`CreatureDisplayInfo`, then `CreatureModelData`. It loads the model the same -way `SetModel` does, then applies the creature's skin textures. So the model -shows the correct look for that display, not an untextured base. - -A Model frame provides no light of its own. Call `SetLight` after -`SetDisplayInfo`, or the model renders as a black silhouette. Call -`SetCamera(0)` to frame it. - -An unknown or missing display ID falls back to the engine's placeholder -model. +Shows a creature on the model by its display ID (a `CreatureDisplayInfo` +ID). The model gets the creature's skin textures. A character-based display (an NPC on the shared `Character\\` -base model) is dressed the same way a spawned NPC is: baked body texture, -hair, face, facial hair, and equipment, including the attached helm and -shoulder models. The dressing runs when the model file finishes loading, -a moment after the call. Weapons do not show: the server sends NPC -weapons only for spawned units, and no client table carries them. +model) is dressed the same way a spawned NPC is: baked body texture, hair, +face, facial hair, and equipment, with the attached helm and shoulder +models. The dressing starts when the model file finishes loading, a short +time after the call. Weapons do not show: the server sends NPC weapons only +for spawned units, and no client table holds them. -This is the single-creature form. An optional second argument -`mountDisplayID` that shows the creature on a mount is not supported -here: a mount needs a second, attached model, and the Model frame holds -one model. +A display ID of 0, or an ID that is not in `CreatureDisplayInfo`, does not +change the model. The model stays on the display until the next +`SetDisplayInfo`, `SetCreature`, or `SetUnit` call. This is also true when +you hide the frame and show it again. ```lua -local m = CreateFrame("Model", "PreviewModel", UIParent) -m:SetSize(200, 260) -m:SetPoint("CENTER") +local m = CreateFrame("PlayerModel", "PreviewModel", UIParent) +m:SetWidth(200) +m:SetHeight(260) +m:SetPoint("CENTER", 0, 0) m:SetDisplayInfo(330) -- a human NPC -m:SetCamera(0) -m:SetLight(1, 0, 0, -1, -1, 1, 1, 1, 1) -- else it is a black silhouette ``` ### `model:SetCreature(creatureID)` -Points a Model frame at a creature by its **entry ID** — the creature's -database ID, not a display ID. This is the companion to `SetDisplayInfo`. +Shows a creature on the model by its creature ID (the creature's database +ID, not a display ID). The model is the same as `SetDisplayInfo` with the +creature's display ID. -The engine looks the entry ID up in the client creature cache, reads the display -ID, then loads the model exactly like `SetDisplayInfo`. The same light and camera -notes apply. - -**Limitation.** The lookup only works for a creature the client has cached. A -creature caches after you see it, target it, or mouse over it, or from -`creaturecache.wdb` at login. There is no client-side entry-to-display table, -so an uncached creature ID is a no-op — the frame keeps its previous model. - -For an uncached creature, request its data first, then set it when the data -arrives: +The creature must be in the client creature cache. The client adds a +creature to the cache when you see it, target it, or put the mouse on it. +The client also loads the cache from `creaturecache.wdb` at login. If the +creature is not in the cache, the call does not change the model. To show +such a creature, request its data. When the data arrives, call +`SetCreature`: ```lua -local creatureID = 448 -- the creature's entry (database) ID +local creatureID = 448 C_CreatureInfo.RequestLoadCreatureByID(creatureID) local f = CreateFrame("Frame") f:RegisterEvent("CREATURE_DATA_LOAD_RESULT") f:SetScript("OnEvent", function() if arg1 == creatureID and arg2 then -- (creatureID, success) - model:SetCreature(creatureID) - model:SetCamera(0) - model:SetLight(1, 0, 0, -1, -1, 1, 1, 1, 1) + PreviewModel:SetCreature(creatureID) end end) ``` +### `model:SetPortraitZoom(zoom)` + +Moves the camera between the full-body view and the model's portrait view. +`0` is the full-body view (the default). `1` is the portrait view: the head +and shoulders, as in a unit-frame portrait. A value between 0 and 1 gives a +view between the two. + +A model that has no portrait camera keeps the full-body view. + +```lua +-- a 3D portrait for a unit frame +local p = CreateFrame("PlayerModel", nil, PlayerFrame) +p:SetWidth(64) +p:SetHeight(64) +p:SetPoint("TOPLEFT", PlayerFrame, "TOPLEFT", 0, 0) +p:SetUnit("player") +p:SetPortraitZoom(1) +``` + +### `model:SetCamDistanceScale(scale)` + +Changes the distance of the camera from the model. `1` is the default +distance. `2` moves the camera two times farther away. `0.5` moves it half +the distance. The method uses 0.1 for a value less than 0.1. A value of 0 or +less is an error. + +This works together with `SetPortraitZoom`: the scale applies to the view +that `SetPortraitZoom` selects. + +### `model:RefreshCamera()` + +Configures the camera again for the current model. The model configures +its camera when it finishes loading. Usually, you do not need this method. + +### `model:SetRotation(rotation [, animate])` + +Turns the model to a facing, in radians. By default the model turns with a +short step animation. If `animate` is `false`, the model turns at once, +with no animation. + +```lua +PreviewModel:SetRotation(math.pi / 2, false) +``` + +### `DressUpModel:UndressSlot(slot)` + +Removes the item in one inventory slot from a `DressUpModel`. `slot` is an +inventory slot number: 1 head, 3 shoulder, 4 shirt, 5 chest, 6 waist, +7 legs, 8 feet, 9 wrist, 10 hands, 15 back, 16 main hand, 17 off hand, +19 tabard. Other slot numbers do nothing. + +```lua +DressUpModel:UndressSlot(1) -- remove the helm +``` + +### `DressUpModel:TryOn(item)` + +Puts an item on a `DressUpModel`. `item` is one of these: + +- An item ID. +- An item link, or an `item:` string. +- A trade-skill recipe link (`enchant:`). The model tries on the item that + the recipe makes. +- The name of an item that you carry, equipped or in your bags. + +If `item` is none of these, the game shows the error "That item can't be +equipped". The model chooses the hand for a weapon itself. + +```lua +DressUpModel:TryOn("|cff1eff00|Hitem:2077:0:0:0|h[Magician Staff]|h|r") +``` + +### `Model:SetGlow(value)` + +This method exists on every `Model` frame, for code from later clients. It +has no effect in the game. + ## ChatBubbles ### `C_ChatBubbles.GetAllChatBubbles([includeForbidden])` diff --git a/src/Offsets.h b/src/Offsets.h index c8aa8414..b8ddcaa7 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -2921,9 +2921,9 @@ enum Offsets { // text-state methods vanilla's EditBox lacks. VAR_EDITBOX_METHOD_REGISTRY = 0x00CF5378, - // Model frame — backs `Model:SetDisplayInfo(creatureDisplayID)` - // (`Model::DisplayInfo`). Registry ctx per docs/raw_methods.txt (table - // 0x00878948, 23 methods: SetModel/SetSequence/ReplaceIconTexture/…). + // Model frame — backs `Model:SetGlow` (`Model::Glow`). Registry ctx per + // docs/raw_methods.txt (table 0x00878948, 23 methods: SetModel/ + // SetSequence/ReplaceIconTexture/…). VAR_MODEL_METHOD_REGISTRY = 0x00CF0C8C, // Model frame-script type id, lazily assigned by the engine on the first // Model method call (`Script_SetModel` FUN_0076d950 prologue: @@ -2969,16 +2969,113 @@ enum Offsets { STR_FS_THIS_NON_TABLE = 0x00847EF8, STR_FS_THIS_NON_OBJECT = 0x00847EC0, STR_FS_WRONG_OBJECT_TYPE = 0x00847E98, - // FUN_0076cfe0(model /*ecx*/, int replaceableType, const char *path) — - // loads `path` as a texture and binds it to the model's replaceable-texture - // slot `replaceableType`. Worker behind `Model:ReplaceIconTexture` (which - // passes type 14); creature skins use MONSTER_1/2/3 = 11/12/13. - FUN_MODEL_SET_REPLACEABLE_TEXTURE = 0x0076CFE0, // The loaded model instance a CSimpleModelFFX keeps at +0x318. It is the // SAME CModel class CGUnits keep at unit+0xD8 — verified via // FUN_007110d0 (the geoset-range setter), whose submesh walk and +0x98 // visibility-array writes match the instance layout probed in-game. OFF_SIMPLEMODELFFX_MODEL_INSTANCE = 0x318, + // The frame's installed camera (a handle; SimpleModelInstallCamera + // 0x0076CE80 AddRefs what it stores) and its facing in radians. + OFF_SIMPLEMODEL_CAMERA = 0x31C, + OFF_SIMPLEMODEL_FACING = 0x39C, + // vtable slot 38: the per-paint root-transform rebuild (PlayerModel's + // 0x00505C50 also ends a turn). `__thiscall(frame)`. + VTBL_SIMPLEMODEL_UPDATE_MODEL = 0x98, + // `CM2Scene *__thiscall(frame)` — the frame's scene, made on first use. + FUN_SIMPLEMODEL_GET_SCENE = 0x0076CFC0, + + // ---- PlayerModel / DressUpModel / TabardModel (benilla ui/playermodel) -- + // CGCharacterModelBase: a Model frame (0x3F8 bytes) that shows a copy of a + // unit's model or a creature display. DressUpModel and TabardModel extend + // it (0x410 bytes). Type ids from the prologues of Script_SetUnit + // (0x00505D70) and DressUpModel Script_Undress (0x00504C00); registry ctx + // per docs/BlizzardScriptAPI.md. The dispatcher walks the type hierarchy, + // so a PlayerModel method reaches DressUpModel and TabardModel too. + VAR_PLAYERMODEL_METHOD_REGISTRY = 0x00BE09D8, + VAR_PLAYERMODEL_LUA_TYPE_ID = 0x00BE0A24, + VAR_DRESSUPMODEL_METHOD_REGISTRY = 0x00BE0938, + VAR_DRESSUPMODEL_LUA_TYPE_ID = 0x00BE0920, + // The pane's creature display record: a creature-cache record whose + // +0x2C (OFF_CREATURE_DISPLAYID) is the only field read, by + // AttachDisplayModel. The constructor, SetUnit (0x00505B50) and SetDisplay + // write it; the show hook (0x00505D49) reads it to rebuild the model. + // Those four are the only accesses in 0x00500000..0x00507000. + OFF_PLAYERMODEL_DISPLAY_RECORD = 0x3F0, + // SetDisplay — `__thiscall(pane, record)`: clears the unit GUID, stores + // the record and, if the frame is visible, builds the model. + FUN_PLAYERMODEL_SET_DISPLAY = 0x00505CB0, + // AttachDisplayModel — `__thiscall(pane, record)`: creates the display's + // model in the pane's scene, applies its skins (ApplyCreatureDisplay + // 0x004797B0), installs it (vtable +0x90), registers the done callback + // and arms Stand. No character compositor: 4.3.4's SetUpModel adds it. + FUN_PLAYERMODEL_ATTACH_DISPLAY_MODEL = 0x00505A70, + // ConfigureCamera — `__thiscall(pane)`, run by the model-ready hook + // (0x00505B30): a frozen copy of the model's camera index 1, or a fixed + // camera at the bounding-box centre. 4.3.4's ConfigureCamera is this plus + // the portrait-zoom and distance-scale steps. + FUN_PLAYERMODEL_CONFIGURE_CAMERA = 0x00505890, + // The engine's Lua PlayerModel:SetRotation(angle) — `int __fastcall(L)`. + FUN_SCRIPT_PLAYERMODEL_SET_ROTATION = 0x00505F00, + + // DressUpModel fields (benilla ui/dressup): the character component, and + // the main- and off-hand lanes, 8 bytes each: byte 0 item class (0 = + // empty), byte 3 inventory type, byte 4 sheathe type. + OFF_DRESSUPMODEL_COMPONENT = 0x3F8, + OFF_DRESSUPMODEL_MAIN_HAND_LANE = 0x3FC, + OFF_DRESSUPMODEL_OFF_HAND_LANE = 0x404, + // UnequipCharacterSlot — `__thiscall(component, slot 0..11)`. + FUN_CHARCOMP_UNEQUIP_SLOT = 0x00478960, + // DetachHeldItemSlot — `__fastcall(model, bodySlot 0xF/0x10, + // sheatheType, bool shield)`; Undress passes `invType == 14` as shield. + FUN_DETACH_HELD_ITEM_SLOT = 0x0047A310, + // TryOnItem — `__thiscall(pane, itemID)`: the worker behind TryOn. + FUN_DRESSUPMODEL_TRY_ON_ITEM = 0x00504540, + // CGGameUI::DisplayError — `__cdecl(id, ...)`: shows a catalogue game + // error. TryOnItem shows 0x13 (ERR_NOT_EQUIPPABLE) at 0x00504B2F. + FUN_GAMEUI_DISPLAY_ERROR = 0x00496720, + GAME_ERROR_NOT_EQUIPPABLE = 0x13, + + // ---- M2 model cameras -------------------------------------------------- + // GetCameraCount — `__thiscall(model)`: data +0x124 after waiting for the + // shared data. GetCamera — `__thiscall(model, index)`, unchecked. + // GetCameraById (0x00713540) indexes with M2LookupIndex's result + // unchecked, so a model without that id reads past the array; we look the + // id up ourselves and bound it by the count. M2LookupIndex is + // `__fastcall(id, table)` → uint16, 0xFFFF past the table's end; the + // camera-id table is {count, uint16 *} at `[model+0x30]+0x130` + 0x12C. + FUN_M2MODEL_GET_CAMERA_COUNT = 0x007134D0, + FUN_M2MODEL_GET_CAMERA = 0x00713590, + FUN_M2_LOOKUP_INDEX = 0x00710310, + OFF_M2MODEL_SHARED = 0x30, + OFF_M2SHARED_DATA = 0x130, + OFF_M2DATA_CAMERA_ID_LOOKUP = 0x12C, + // SetAnimated — `__thiscall(model, bool)`; M2SceneAnimateAndCollect — + // `__thiscall(scene, const float *cameraPos)`. ConfigureCamera runs both + // (with the frame's facing zeroed) before it copies a model camera. + FUN_M2MODEL_SET_ANIMATED = 0x00710B90, + FUN_M2SCENE_ANIMATE = 0x00707680, + + // ---- Camera properties (benilla camera#properties) ------------------- + // Get/SetVectorProperty `__fastcall(camera, id, float[3] [, keep])`, + // Get/SetScalarProperty `__fastcall(camera, id [, float])`. Ids: 7 eye, + // 8 target, 4 field of view. + FUN_CAMERA_GET_VECTOR = 0x007ABF80, + FUN_CAMERA_GET_SCALAR = 0x007AC0B0, + FUN_CAMERA_SET_VECTOR = 0x007AC250, + FUN_CAMERA_SET_SCALAR = 0x007AC3A0, + CAMERA_PROP_FOV = 4, + CAMERA_PROP_EYE = 7, + CAMERA_PROP_TARGET = 8, + + // ---- ModelFFX glow (benilla glue/select#the-modelffx-frame) ---------- + // The glue ModelFFX frame's show (vtable slot 12, 0x0046FA60) writes the + // glow strength 0.30 (0x008380B4) to the light state's +0x110 and makes + // ffxGlow current; the effect reads it per draw. GetLightState is + // `__stdcall()`. ModelFFX's vtable is 0x00803960. + FUN_MODELFFX_ON_SHOW = 0x0046FA60, + FUN_GET_LIGHT_STATE = 0x006D48B0, + OFF_LIGHT_STATE_GLOW = 0x110, + VTBL_MODELFFX = 0x00803960, // --- Character-model compositor ("CharComponent", `Model::DisplayInfo`) -- // The engine object that dresses a character-based model: resolves the @@ -9154,6 +9251,9 @@ enum Offsets { // mechanic on an effect rather than the spell-level Mechanic (0x14), so // bleed / DoT detection needs this array in addition to that field. OFF_SPELL_RECORD_EFFECT_MECHANIC = 0x13C, // int32[3] + // EffectItemType[3] (column 103): the item a CREATE_ITEM effect makes. + // Verified on recipes 2660 / 3275 / 2963 → items 2862 / 1251 / 2996. + OFF_SPELL_RECORD_EFFECT_ITEM_TYPE = 0x19C, // int32[3] SPELL_RECORD_EFFECT_COUNT = 3, // SPELL_EFFECT_* id array (`Effect[3]`) — five arrays before diff --git a/src/creature/Info.cpp b/src/creature/Info.cpp index 31e74a81..0daf88a9 100644 --- a/src/creature/Info.cpp +++ b/src/creature/Info.cpp @@ -377,15 +377,8 @@ bool FactionGroupForRace(int raceID, const char **english, const char **localize return false; // no named group } -// Public accessor for Model::DisplayInfo's SetCreature — the same peek -// GetCreatureInfoByID uses, reduced to the display-ID field. 0 = uncached. -uint32_t DisplayID(uint32_t creatureID) { - if (creatureID == 0) - return 0; - const uint8_t *rec = PeekCreature(creatureID); - if (rec == nullptr) - return 0; - return Game::Read(rec, Offsets::OFF_CREATURE_DISPLAYID); +const uint8_t *CacheRecord(uint32_t creatureID) { + return creatureID != 0 ? PeekCreature(creatureID) : nullptr; } } // namespace Creature::Info diff --git a/src/creature/Info.h b/src/creature/Info.h index 31307d35..60c09956 100644 --- a/src/creature/Info.h +++ b/src/creature/Info.h @@ -17,12 +17,12 @@ namespace Creature::Info { -// The cached model display ID for a creature/NPC entry, or 0 when the creature -// is not in the client creature cache (creaturecache.wdb, or queried this -// session). A synchronous peek — no network query. Backs `Model:SetCreature`: -// the cache being keyed by entry ID and carrying a display ID is exactly the -// entry-ID → model mapping vanilla has no DBC for. -uint32_t DisplayID(uint32_t creatureID); +// The client creature-cache record for a creature/NPC entry, or null when the +// creature is not cached (creaturecache.wdb, or queried this session). A +// synchronous peek — no network query. The record outlives the session's +// frames, which is why PlayerModel panes keep a pointer to it: it is what the +// engine's SetDisplay takes, and `PlayerModel:SetCreature` passes it there. +const uint8_t *CacheRecord(uint32_t creatureID); // The faction group a player race belongs to, resolved the way // `Script_UnitFactionGroup` does it for a player whose object isn't in the diff --git a/src/model/Camera.cpp b/src/model/Camera.cpp new file mode 100644 index 00000000..a45ea1f8 --- /dev/null +++ b/src/model/Camera.cpp @@ -0,0 +1,286 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `PlayerModel:SetPortraitZoom(zoom)`, `SetCamDistanceScale(scale)` and +// `RefreshCamera()` — 4.3.4's CGCharacterModelBase camera methods. +// +// Vanilla's pane camera is ConfigureCamera (FUN_PLAYERMODEL_CONFIGURE_CAMERA), +// run when the pane's model is ready: a frozen copy of the model's camera 1, +// or a fixed camera aimed at the bounding-box centre. 4.3.4's ConfigureCamera +// (CharacterModelBase.cpp, 0x00A03790) is that same choice followed by two +// steps, ported here verbatim onto the installed camera: +// +// - portrait zoom: move eye, target and field of view from the pane camera +// toward the model's portrait camera (id 0) by `zoom` — 1 frames the head +// the way unit-frame portraits do; +// - distance scale: scale the eye's distance from the target by `scale`, +// floored at 0.1 and kept at least 0.1 yards out. +// +// Both run in a co-hook after the original, so a pane with the defaults (zoom +// 0, scale 1) keeps vanilla's camera untouched. Vanilla has no room for the +// two values in the pane, so they live in a side table keyed by frame. +// +// Before reading the portrait camera, the model is animated once with the +// frame's facing at 0 — the pass ConfigureCamera itself runs before it copies +// camera 1, and the one the engine's portrait baker (BakePortrait 0x00525200) +// runs before it reads camera 0. 4.3.4 subtracts the frame's position from +// both model cameras; vanilla's ConfigureCamera does not subtract it from +// camera 1, so the portrait camera is used as is, in the same space. + +#include "Game.h" +#include "Offsets.h" + +#include +#include +#include + +namespace Model::Camera { +namespace { + +struct Settings { + float portraitZoom = 0.0f; + float distanceScale = 1.0f; +}; +std::unordered_map g_settings; + +using GetVector_t = void(__fastcall *)(void *camera, uint32_t id, float *out); +using GetScalar_t = float(__fastcall *)(void *camera, uint32_t id); +using SetVector_t = void(__fastcall *)(void *camera, uint32_t id, const float *value, + uint32_t keep); +using SetScalar_t = void(__fastcall *)(void *camera, uint32_t id, float value); +using GetCameraCount_t = uint32_t(__thiscall *)(void *model); +using GetCamera_t = void *(__thiscall *)(void *model, uint32_t index); +using LookupIndex_t = uint16_t(__fastcall *)(uint32_t id, const void *table); +using SetAnimated_t = void(__thiscall *)(void *model, int animated); +using GetScene_t = void *(__thiscall *)(void *frame); +using SceneAnimate_t = void(__thiscall *)(void *scene, const float *cameraPos); +using UpdateModel_t = void(__thiscall *)(void *frame); +using ModelLoaded_t = int(__thiscall *)(void *model, int tryLoad, int recurseChildren); +using ConfigureCamera_t = void(__thiscall *)(void *pane); + +struct Vec3 { + float x, y, z; +}; + +Vec3 GetVector(void *camera, uint32_t id) { + Vec3 v{}; + reinterpret_cast(Offsets::FUN_CAMERA_GET_VECTOR)(camera, id, &v.x); + return v; +} + +void SetVector(void *camera, uint32_t id, const Vec3 &v) { + reinterpret_cast(Offsets::FUN_CAMERA_SET_VECTOR)(camera, id, &v.x, 0); +} + +float GetScalar(void *camera, uint32_t id) { + return reinterpret_cast(Offsets::FUN_CAMERA_GET_SCALAR)(camera, id); +} + +void SetScalar(void *camera, uint32_t id, float value) { + reinterpret_cast(Offsets::FUN_CAMERA_SET_SCALAR)(camera, id, value); +} + +// The model's camera with id `id` (0 = portrait), or null when it has none — +// GetCameraById's lookup, bounded the way 4.3.4 null-checks its result. +void *CameraById(void *model, uint32_t id) { + const uint32_t count = + reinterpret_cast(Offsets::FUN_M2MODEL_GET_CAMERA_COUNT)(model); + const uint8_t *data = Game::Read( + Game::Read(model, Offsets::OFF_M2MODEL_SHARED), Offsets::OFF_M2SHARED_DATA); + const uint16_t index = reinterpret_cast(Offsets::FUN_M2_LOOKUP_INDEX)( + id, data + Offsets::OFF_M2DATA_CAMERA_ID_LOOKUP); + if (index >= count) + return nullptr; + return reinterpret_cast(Offsets::FUN_M2MODEL_GET_CAMERA)(model, index); +} + +// ConfigureCamera's own evaluation pass: facing 0, rebuild the root +// transform, animate the scene, restore the facing. +void AnimateUnrotated(void *pane, void *model) { + float &facing = Game::Ref(pane, Offsets::OFF_SIMPLEMODEL_FACING); + const float saved = facing; + facing = 0.0f; + const void *vtable = Game::Read(pane, 0); + Game::Read(vtable, Offsets::VTBL_SIMPLEMODEL_UPDATE_MODEL)(pane); + reinterpret_cast(Offsets::FUN_M2MODEL_SET_ANIMATED)(model, 1); + const float origin[3] = {0.0f, 0.0f, 0.0f}; + void *scene = reinterpret_cast(Offsets::FUN_SIMPLEMODEL_GET_SCENE)(pane); + reinterpret_cast(Offsets::FUN_M2SCENE_ANIMATE)(scene, origin); + facing = saved; +} + +Vec3 Lerp(const Vec3 &from, const Vec3 &to, float t) { + return {(to.x - from.x) * t + from.x, (to.y - from.y) * t + from.y, + (to.z - from.z) * t + from.z}; +} + +// 4.3.4 ConfigureCamera's last two steps, on the camera vanilla installed. +void ApplySettings(void *pane, const Settings &s) { + void *model = Game::Read(pane, Offsets::OFF_SIMPLEMODELFFX_MODEL_INSTANCE); + void *camera = Game::Read(pane, Offsets::OFF_SIMPLEMODEL_CAMERA); + if (model == nullptr || camera == nullptr) + return; + + if (s.portraitZoom != 0.0f) { + AnimateUnrotated(pane, model); + if (void *portrait = CameraById(model, 0)) { + const Vec3 eye = GetVector(camera, Offsets::CAMERA_PROP_EYE); + const Vec3 target = GetVector(camera, Offsets::CAMERA_PROP_TARGET); + const float fov = GetScalar(camera, Offsets::CAMERA_PROP_FOV); + const Vec3 portraitEye = GetVector(portrait, Offsets::CAMERA_PROP_EYE); + const Vec3 portraitTarget = GetVector(portrait, Offsets::CAMERA_PROP_TARGET); + const float portraitFov = GetScalar(portrait, Offsets::CAMERA_PROP_FOV); + SetVector(camera, Offsets::CAMERA_PROP_EYE, Lerp(eye, portraitEye, s.portraitZoom)); + SetVector(camera, Offsets::CAMERA_PROP_TARGET, + Lerp(target, portraitTarget, s.portraitZoom)); + SetScalar(camera, Offsets::CAMERA_PROP_FOV, + (portraitFov - fov) * s.portraitZoom + fov); + } + } + + if (s.distanceScale != 1.0f) { + const Vec3 eye = GetVector(camera, Offsets::CAMERA_PROP_EYE); + const Vec3 target = GetVector(camera, Offsets::CAMERA_PROP_TARGET); + const float scale = s.distanceScale < 0.1f ? 0.1f : s.distanceScale; + const float dx = eye.x - target.x; + const float dy = eye.y - target.y; + const float dz = eye.z - target.z; + float sx = dx * scale; + float sy = dy * scale; + float sz = dz * scale; + if (sz * sz + sy * sy + sx * sx < 0.010000001f) { + const float inv = 1.0f / std::sqrt(dy * dy + dz * dz + dx * dx); + sx = dx * inv * 0.1f; + sy = dy * inv * 0.1f; + sz = dz * inv * 0.1f; + } + SetVector(camera, Offsets::CAMERA_PROP_EYE, {sx + target.x, sy + target.y, sz + target.z}); + } +} + +ConfigureCamera_t g_origConfigureCamera = nullptr; + +void __fastcall ConfigureCamera_h(void *pane, void * /*edx*/) { + g_origConfigureCamera(pane); + const auto it = g_settings.find(pane); + if (it != g_settings.end()) + ApplySettings(pane, it->second); +} + +const Game::HookAutoRegister _cameraHook{ + Offsets::FUN_PLAYERMODEL_CONFIGURE_CAMERA, reinterpret_cast(&ConfigureCamera_h), + reinterpret_cast(&g_origConfigureCamera)}; + +// 4.3.4 reconfigures whenever the pane has a model. Here the model must also +// be loaded: ConfigureCamera reads its cameras and bounds, and an unloaded +// model is configured by the ready hook when it arrives, settings included. +void Reconfigure(void *pane) { + void *model = Game::Read(pane, Offsets::OFF_SIMPLEMODELFFX_MODEL_INSTANCE); + if (model == nullptr || + !reinterpret_cast(Offsets::FUN_MODEL_INSTANCE_LOADED)(model, 0, 0)) + return; + reinterpret_cast(Offsets::FUN_PLAYERMODEL_CONFIGURE_CAMERA)(pane); +} + +void *ResolvePane(void *L) { + return Game::Lua::ResolveTypedObject(L, 1, Offsets::VAR_PLAYERMODEL_LUA_TYPE_ID); +} + +int __fastcall Script_SetPortraitZoom(void *L) { + void *pane = ResolvePane(L); + if (pane == nullptr) + return 0; + if (!Game::Lua::IsNumber(L, 2)) { + Game::Lua::Error(L, "Usage: SetPortraitZoom(zoom)"); + return 0; + } + const auto zoom = static_cast(Game::Lua::ToNumber(L, 2)); + Settings &s = g_settings[pane]; + if (s.portraitZoom != zoom) { + s.portraitZoom = zoom; + Reconfigure(pane); + } + return 0; +} + +int __fastcall Script_SetCamDistanceScale(void *L) { + void *pane = ResolvePane(L); + if (pane == nullptr) + return 0; + if (!Game::Lua::IsNumber(L, 2)) { + Game::Lua::Error(L, "Usage: SetCamDistanceScale(scale)"); + return 0; + } + const double value = Game::Lua::ToNumber(L, 2); + if (value <= 0.0) { + Game::Lua::Error(L, "SetCamDistanceScale: Scale value must be greater than 0"); + return 0; + } + const float scale = value >= 0.1 ? static_cast(value) : 0.1f; + Settings &s = g_settings[pane]; + if (s.distanceScale != scale) { + s.distanceScale = scale; + Reconfigure(pane); + } + return 0; +} + +int __fastcall Script_RefreshCamera(void *L) { + if (void *pane = ResolvePane(L)) + Reconfigure(pane); + return 0; +} + +const Game::Lua::FrameMethodEntry g_methods[] = { + {"SetPortraitZoom", &Script_SetPortraitZoom}, + {"SetCamDistanceScale", &Script_SetCamDistanceScale}, + {"RefreshCamera", &Script_RefreshCamera}, +}; + +const Game::Doc::Field kZoomArgs[] = { + Game::Doc::Req("zoom", "number", "0 for the full-body camera, 1 for the portrait camera."), +}; +const Game::Doc::Function kSetPortraitZoom{ + "Moves the camera between the full-body view and the model's portrait view.", kZoomArgs, + {}}; +const Game::Doc::Field kScaleArgs[] = { + Game::Doc::Req("scale", "number", "The camera distance multiplier; 1 is the default."), +}; +const Game::Doc::Function kSetCamDistanceScale{ + "Scales the camera's distance from the model.", kScaleArgs, {}}; +const Game::Doc::Function kRefreshCamera{ + "Configures the camera again for the current model.", {}, {}}; +const Game::Doc::Method g_methodDocs[] = { + {"SetPortraitZoom", &kSetPortraitZoom}, + {"SetCamDistanceScale", &kSetCamDistanceScale}, + {"RefreshCamera", &kRefreshCamera}, +}; + +void RegisterLuaFunctions() { + Game::Lua::RegisterFrameMethods( + reinterpret_cast(Offsets::VAR_PLAYERMODEL_METHOD_REGISTRY), g_methods, + static_cast(sizeof(g_methods) / sizeof(g_methods[0])), g_methodDocs, + static_cast(sizeof(g_methodDocs) / sizeof(g_methodDocs[0]))); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +// Frames are rebuilt on /reload and a new frame can reuse an old address. +void PrepareForReload() { + g_settings.clear(); +} + +const Game::ReloadAutoRegister _reloadReg{&PrepareForReload}; + +} // namespace +} // namespace Model::Camera diff --git a/src/model/DisplayInfo.cpp b/src/model/DisplayInfo.cpp index dca9e371..365fdd2e 100644 --- a/src/model/DisplayInfo.cpp +++ b/src/model/DisplayInfo.cpp @@ -11,28 +11,40 @@ // You should have received a copy of the GNU General Public License along with // ClassicAPI. If not, see . -// `Model:SetDisplayInfo(creatureDisplayID)` — backport of the modern Model -// method that points a Model frame at a creature by its display ID, instead of -// requiring a `.mdx` file path (`Model:SetModel`). Vanilla already loads models -// by path; this just prepends the DBC resolution modern clients do internally: +// `PlayerModel:SetDisplayInfo(displayID)` and `PlayerModel:SetCreature(creatureID)` +// — 4.3.4's CGCharacterModelBase methods (CharacterModelBase_Scripts.cpp), on +// vanilla's own pane path. // -// creatureDisplayID → CreatureDisplayInfo[id] +0x04 ModelID -// → CreatureModelData[ModelID] +0x08 ModelPath -// → Model:SetModel's worker (vtable +0x94) -// → apply the display's TextureVariation skins -// → character displays: dress via the engine compositor -// (baked skin, hair, geosets, equipment — see the -// "Character-display dressing" section below) +// Vanilla's PlayerModel already shows a creature display: SetDisplay +// (FUN_PLAYERMODEL_SET_DISPLAY) stores a creature-cache record in the pane and +// AttachDisplayModel (FUN_PLAYERMODEL_ATTACH_DISPLAY_MODEL) builds the model +// from the record's display ID — skins via ApplyCreatureDisplay, Stand armed, +// the done callback, the pane camera, and a rebuild every time the pane is +// shown again. The pet stable drives it. What it lacks is 4.3.4's character +// step: SetUpModel dresses a display with a CreatureDisplayInfoExtra record +// through the character compositor, where vanilla leaves a humanoid NPC +// white-skinned with every geoset on. // -// The load path is the engine's own (`Script_SetModel` FUN_0076d950 calls the -// same vtable +0x94 worker); we add the display-ID front end and the same -// dressing a spawned unit gets. It is the foundational "display ID → loaded -// model" step — a rendered portrait-by-display-ID -// (SetPortraitTextureFromCreatureDisplayID) would build render-to-texture on -// top of this, but a live Model frame needs neither. +// So: +// - AttachDisplayModel is co-hooked to add that step: after the original +// builds the model, a character display is dressed through the engine +// compositor (the DressJob below, a field-for-field mirror of the unit +// path CGUnit_C::UpdateCharacterCustomization). +// - SetCreature passes the creature's cache record straight to SetDisplay — +// the same record 4.3.4 passes (CreatureStats_C) and the stable passes. +// - SetDisplayInfo has a display ID and no cache record. The pane only ever +// reads the record's display-ID field (OFF_PLAYERMODEL_DISPLAY_RECORD), so +// each pane gets a record of its own holding just that field, which lives +// as long as the pane can point at it. // -// SetCreature(creatureID) is the entry-ID cousin: it resolves through the client -// creature cache to a display ID, then runs the same load — see its note below. +// SetCreature only resolves creatures already in the cache (creaturecache.wdb +// or queried this session); an uncached entry is a no-op. A caller can +// `C_CreatureInfo.RequestLoadCreatureByID` first and call this after +// `CREATURE_DATA_LOAD_RESULT`. +// +// Still not shown: weapons. NPC weapons come from the server-pushed +// UNIT_VIRTUAL_ITEM_SLOT_DISPLAY fields on live units, not from any client +// DBC, so a display ID alone can't produce them. #include "Game.h" #include "Offsets.h" @@ -44,72 +56,11 @@ #include #include #include -#include +#include namespace Model::DisplayInfo { namespace { -// The Model model-load worker at vtable +0x94 — the one Script_SetModel -// invokes after resolving self. Single-use here, so kept local. -constexpr int kVmtLoadModel = 0x94; - -using LoadModel_t = void(__thiscall *)(void *self, const char *path); -using SetReplaceableTexture_t = void(__thiscall *)(void *model, int type, const char *path); - -template -Fn Vmethod(void *obj, int byteOffset) { - auto *vtbl = *reinterpret_cast(obj); - return *reinterpret_cast(vtbl + byteOffset); -} - -// Resolve arg1 to a Model object, or nullptr if it is not a Model. The -// type-check matters especially here because we call a Model vtable slot -// directly — a non-Model region would dispatch a wrong method. Non-raising, -// which is the contract the callers below already had. -void *ResolveModel(void *L) { - return Game::Lua::ResolveModel(L, 1, /*raiseError=*/false); -} - -// Apply a creature display's TextureVariation skins to the just-loaded model. -// The variation columns are bare filenames that live in the model's own -// directory; they fill the model's MONSTER_1/2/3 replaceable-texture slots -// (M2/MDX texture types 11/12/13). FUN_0076cfe0 no-ops when no model is loaded, -// so this is safe to call unconditionally after the load. -void ApplySkins(void *model, const char *modelPath, const uint8_t *displayRec) { - std::string dir(modelPath); - const auto slash = dir.find_last_of("\\/"); - dir = (slash == std::string::npos) ? std::string() : dir.substr(0, slash + 1); - - auto setTexture = reinterpret_cast( - Offsets::FUN_MODEL_SET_REPLACEABLE_TEXTURE); - constexpr int kMonsterSlot[3] = {11, 12, 13}; - for (int i = 0; i < 3; ++i) { - const char *variation = Game::Read( - displayRec, Offsets::OFF_CREATUREDISPLAYINFO_TEXTURE_VARIATION + i * 4); - if (variation == nullptr || variation[0] == '\0') - continue; - const std::string skin = dir + variation; - setTexture(model, kMonsterSlot[i], skin.c_str()); - } -} - -// --- Character-display dressing via the engine compositor ------------------- -// -// Character-based displays (CreatureDisplayInfo.extendedDisplayInfoID != 0) use -// a shared Character\Race\Sex base model that the engine "dresses" per display: -// baked body texture, hair texture, hair / facial-hair geosets (beards, -// earrings, teeth), and equipment geosets (sleeves, robe→trousers, boots, -// tabard, cape). Units run this through a compositor object -// (CGUnit_C::UpdateCharacterCustomization, FUN_005fb200) once their model -// loads; SetPortraitTexture waits on the same compositor, which is why -// portraits always look right. We drive the identical compositor for the -// Model frame, mirroring the unit flow field for field — see the -// FUN_CHARCOMP_* notes in Offsets.h. -// -// Still not shown: weapons. NPC weapons come from the server-pushed -// UNIT_VIRTUAL_ITEM_SLOT_DISPLAY fields on live units, not from any client -// DBC, so a display ID alone can't produce them. - // The compositor info struct FUN_CHARCOMP_SET_INFO copies (0x5B dwords). // Layout read straight out of FUN_005fb200's NPC branch. struct CharCompInfo { @@ -306,88 +257,89 @@ void OnWorldTick() { const Tick::WorldTick::AutoSubscribe g_tick{&OnWorldTick}; -// Resolve a creature display ID to its model file and skins, and load it into -// the Model frame. Shared by SetDisplayInfo (display ID direct) and SetCreature -// (creature entry ID -> cache -> display ID). No-op for an unknown display ID. -void LoadDisplay(void *model, int displayID) { - if (displayID <= 0) - return; - const uint8_t *displayRec = DBC::Record(Offsets::VAR_CREATUREDISPLAYINFO_RECORDS, - Offsets::VAR_CREATUREDISPLAYINFO_COUNT, - static_cast(displayID)); - if (displayRec == nullptr) - return; - const uint32_t modelID = Game::Read( - displayRec, Offsets::OFF_CREATUREDISPLAYINFO_MODEL_ID); +// ---- AttachDisplayModel co-hook --------------------------------------------- - const char *modelPath = DBC::StringField(Offsets::VAR_CREATUREMODELDATA_RECORDS, - Offsets::VAR_CREATUREMODELDATA_COUNT, - modelID, - Offsets::OFF_CREATUREMODELDATA_MODEL_PATH); - if (modelPath == nullptr) - return; +using AttachDisplayModel_t = void(__thiscall *)(void *pane, const uint8_t *record); +AttachDisplayModel_t g_origAttach = nullptr; - // Any pending or kept dress for this frame is about to point at the - // wrong model — drop it before the load swaps the instance. - if (DressJob *job = FindJob(model)) +// 4.3.4's SetUpModel order: build the model, then dress it when the display +// has an Extra record. +void __fastcall AttachDisplayModel_h(void *pane, void * /*edx*/, const uint8_t *record) { + // Any pending or kept dress for this pane is about to point at the wrong + // model — drop it before the original swaps the instance. + if (DressJob *job = FindJob(pane)) CancelJob(*job); - Vmethod(model, kVmtLoadModel)(model, modelPath); - ApplySkins(model, modelPath, displayRec); + g_origAttach(pane, record); - // Character-based display (Character\Race\Sex base): dress it through the - // engine compositor, else body and hair render white with every geoset on. - const uint32_t extID = Game::Read( - displayRec, Offsets::OFF_CREATUREDISPLAYINFO_EXTENDED_ID); - if (extID != 0) { - const uint8_t *extraRec = DBC::Record(Offsets::VAR_CREATUREDISPLAYINFOEXTRA_RECORDS, - Offsets::VAR_CREATUREDISPLAYINFOEXTRA_COUNT, extID); - if (extraRec != nullptr) - ScheduleDress(model, extraRec); - } + if (record == nullptr) + return; + const uint8_t *displayRec = DBC::Record( + Offsets::VAR_CREATUREDISPLAYINFO_RECORDS, Offsets::VAR_CREATUREDISPLAYINFO_COUNT, + Game::Read(record, Offsets::OFF_CREATURE_DISPLAYID)); + if (displayRec == nullptr) + return; + const uint32_t extID = + Game::Read(displayRec, Offsets::OFF_CREATUREDISPLAYINFO_EXTENDED_ID); + if (extID == 0) + return; + const uint8_t *extraRec = DBC::Record(Offsets::VAR_CREATUREDISPLAYINFOEXTRA_RECORDS, + Offsets::VAR_CREATUREDISPLAYINFOEXTRA_COUNT, extID); + if (extraRec != nullptr) + ScheduleDress(pane, extraRec); } +const Game::HookAutoRegister _attachHook{ + Offsets::FUN_PLAYERMODEL_ATTACH_DISPLAY_MODEL, + reinterpret_cast(&AttachDisplayModel_h), + reinterpret_cast(&g_origAttach)}; + +// ---- Lua methods -------------------------------------------------------------- + +using SetDisplay_t = void(__thiscall *)(void *pane, const uint8_t *record); + +void SetDisplay(void *pane, const uint8_t *record) { + reinterpret_cast(Offsets::FUN_PLAYERMODEL_SET_DISPLAY)(pane, record); +} + +// The record a pane shows for SetDisplayInfo: only the display-ID field is +// ever read. One per pane, never freed — the pane keeps the pointer and +// rebuilds from it on every show, and panes live as long as the UI. +struct DisplayRecord { + uint8_t bytes[Offsets::OFF_CREATURE_DISPLAYID + sizeof(uint32_t)]; +}; +std::unordered_map g_displayRecords; + int __fastcall Script_SetDisplayInfo(void *L) { - if (Game::Lua::Type(L, 1) != Game::Lua::TYPE_TABLE || !Game::Lua::IsNumber(L, 2)) { - Game::Lua::Error(L, "Usage: Model:SetDisplayInfo(creatureDisplayID)"); + void *pane = Game::Lua::ResolveTypedObject(L, 1, Offsets::VAR_PLAYERMODEL_LUA_TYPE_ID); + if (pane == nullptr) + return 0; + if (!Game::Lua::IsNumber(L, 2)) { + Game::Lua::Error(L, "Usage: SetDisplayInfo(displayID)"); return 0; } - void *model = ResolveModel(L); - if (model == nullptr) { - Game::Lua::Error(L, "Model:SetDisplayInfo(): self is not a Model"); + const auto displayID = static_cast(Game::Lua::ToNumber(L, 2)); + if (displayID == 0) return 0; - } - LoadDisplay(model, static_cast(Game::Lua::ToNumber(L, 2))); + DisplayRecord &rec = g_displayRecords[pane]; + std::memset(rec.bytes, 0, sizeof(rec.bytes)); + std::memcpy(rec.bytes + Offsets::OFF_CREATURE_DISPLAYID, &displayID, sizeof(displayID)); + SetDisplay(pane, rec.bytes); return 0; } -// `Model:SetCreature(creatureID)` — the creature-entry cousin of SetDisplayInfo. -// Vanilla has no client-side creature-entry -> display table in a DBC; that -// mapping lives in the creature cache (creaturecache.wdb / SMSG_CREATURE_QUERY_ -// RESPONSE), keyed by entry ID and carrying the display ID. So this resolves the -// entry through the cache, then loads exactly as SetDisplayInfo does. -// -// Limitation: only creatures already cached (queried this session or loaded from -// the WDB at login) resolve; an uncached entry is a no-op. A caller that needs an -// uncached creature can `C_CreatureInfo.RequestLoadCreatureByID` first, then call -// this after `CREATURE_DATA_LOAD_RESULT`. int __fastcall Script_SetCreature(void *L) { - if (Game::Lua::Type(L, 1) != Game::Lua::TYPE_TABLE || !Game::Lua::IsNumber(L, 2)) { - Game::Lua::Error(L, "Usage: Model:SetCreature(creatureID)"); + void *pane = Game::Lua::ResolveTypedObject(L, 1, Offsets::VAR_PLAYERMODEL_LUA_TYPE_ID); + if (pane == nullptr) + return 0; + if (!Game::Lua::IsNumber(L, 2)) { + Game::Lua::Error(L, "Usage: SetCreature(creatureID)"); return 0; } - void *model = ResolveModel(L); - if (model == nullptr) { - Game::Lua::Error(L, "Model:SetCreature(): self is not a Model"); - return 0; - } - const int creatureID = static_cast(Game::Lua::ToNumber(L, 2)); - if (creatureID <= 0) - return 0; - const uint32_t displayID = Creature::Info::DisplayID(static_cast(creatureID)); - if (displayID == 0) - return 0; // not cached -> no-op (see limitation above) - LoadDisplay(model, static_cast(displayID)); + const uint8_t *record = + Creature::Info::CacheRecord(static_cast(Game::Lua::ToNumber(L, 2))); + if (record != nullptr) + SetDisplay(pane, record); return 0; } @@ -396,11 +348,26 @@ const Game::Lua::FrameMethodEntry g_methods[] = { {"SetCreature", &Script_SetCreature}, }; +const Game::Doc::Field kDisplayArgs[] = { + Game::Doc::Req("displayID", "number", "A CreatureDisplayInfo ID."), +}; +const Game::Doc::Function kSetDisplayInfo{ + "Shows a creature display on the model, dressed like the creature.", kDisplayArgs, {}}; +const Game::Doc::Field kCreatureArgs[] = { + Game::Doc::Req("creatureID", "number", "A creature ID that is in the creature cache."), +}; +const Game::Doc::Function kSetCreature{ + "Shows a creature on the model by its creature ID.", kCreatureArgs, {}}; +const Game::Doc::Method g_methodDocs[] = { + {"SetDisplayInfo", &kSetDisplayInfo}, + {"SetCreature", &kSetCreature}, +}; + void RegisterLuaFunctions() { Game::Lua::RegisterFrameMethods( - reinterpret_cast(Offsets::VAR_MODEL_METHOD_REGISTRY), - g_methods, - static_cast(sizeof(g_methods) / sizeof(g_methods[0]))); + reinterpret_cast(Offsets::VAR_PLAYERMODEL_METHOD_REGISTRY), g_methods, + static_cast(sizeof(g_methods) / sizeof(g_methods[0])), g_methodDocs, + static_cast(sizeof(g_methodDocs) / sizeof(g_methodDocs[0]))); } const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; diff --git a/src/model/DressUp.cpp b/src/model/DressUp.cpp new file mode 100644 index 00000000..7becf8f4 --- /dev/null +++ b/src/model/DressUp.cpp @@ -0,0 +1,196 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `DressUpModel:UndressSlot(slot)` and the 4.3.4 `DressUpModel:TryOn(item)` +// (DressUpModelFrame_Scripts.cpp). +// +// UndressSlot is one step of vanilla's own Undress (DressUpModel::ClearModel +// 0x00504490), which 4.3.4 split per slot: a component slot is cleared with +// UnequipCharacterSlot, a held lane is detached with DetachHeldItemSlot and +// zeroed. The slot map is 4.3.4's, from inventory slot to component slot. +// +// TryOn keeps vanilla's worker (TryOnItem, FUN_DRESSUPMODEL_TRY_ON_ITEM) and +// takes 4.3.4's argument forms in front of it: an item ID, an item link or +// `item:` string, a trade-skill `enchant:` link (the item its recipe makes), +// or the name of an item the player carries. Anything else shows +// ERR_NOT_EQUIPPABLE, as 4.3.4 does. 4.3.4's optional hand argument +// ("mainhand" / "offhand") is not supported: vanilla's worker picks the hand +// itself. + +#include "Game.h" +#include "Offsets.h" +#include "dbc/Lookup.h" +#include "item/Arg.h" +#include "item/ID.h" +#include "item/Location.h" + +#include +#include +#include +#include + +namespace Model::DressUp { +namespace { + +using UnequipSlot_t = void(__thiscall *)(void *component, uint32_t slot); +using DetachHeldItem_t = void(__fastcall *)(void *model, uint32_t bodySlot, uint32_t sheatheType, + bool shield); +using TryOnItem_t = void(__thiscall *)(void *pane, uint32_t itemID); +using DisplayError_t = void(__cdecl *)(uint32_t id, ...); + +// Body slots of the two held lanes. +constexpr uint32_t kBodySlotMainHand = 0xF; +constexpr uint32_t kBodySlotOffHand = 0x10; +constexpr uint8_t kInvTypeShield = 14; + +void *ResolvePane(void *L) { + return Game::Lua::ResolveTypedObject(L, 1, Offsets::VAR_DRESSUPMODEL_LUA_TYPE_ID); +} + +// ClearModel's lane step: detach the held item and zero the lane. +void ClearLane(void *pane, uintptr_t laneOffset, uint32_t bodySlot) { + uint8_t *lane = Game::Ptr(pane, laneOffset); + if (lane[0] == 0) + return; + reinterpret_cast(Offsets::FUN_DETACH_HELD_ITEM_SLOT)( + Game::Read(pane, Offsets::OFF_SIMPLEMODELFFX_MODEL_INSTANCE), bodySlot, lane[4], + lane[3] == kInvTypeShield); + std::memset(lane, 0, 8); +} + +// Component slot for a 0-based inventory slot, or -1 (4.3.4 UndressSlot). +int ComponentSlot(int slot0) { + switch (slot0) { + case 0: return 0; // head + case 2: return 1; // shoulder + case 3: return 2; // shirt + case 4: return 3; // chest + case 5: return 4; // waist + case 6: return 5; // legs + case 7: return 6; // feet + case 8: return 7; // wrist + case 9: return 8; // hands + case 14: return 10; // back + case 18: return 9; // tabard + default: return -1; + } +} + +int __fastcall Script_UndressSlot(void *L) { + void *pane = ResolvePane(L); + if (pane == nullptr) + return 0; + if (!Game::Lua::IsNumber(L, 2)) { + Game::Lua::Error(L, "Usage: %s:UndressSlot(slotIndex)", Game::Lua::ObjectDisplayName(pane)); + return 0; + } + const int slot0 = static_cast(Game::Lua::ToNumber(L, 2)) - 1; + void *component = Game::Read(pane, Offsets::OFF_DRESSUPMODEL_COMPONENT); + if (Game::Read(pane, Offsets::OFF_SIMPLEMODELFFX_MODEL_INSTANCE) == nullptr || + component == nullptr) + return 0; + if (slot0 == 15) { + ClearLane(pane, Offsets::OFF_DRESSUPMODEL_MAIN_HAND_LANE, kBodySlotMainHand); + } else if (slot0 == 16) { + ClearLane(pane, Offsets::OFF_DRESSUPMODEL_OFF_HAND_LANE, kBodySlotOffHand); + } else { + const int compSlot = ComponentSlot(slot0); + if (compSlot >= 0) + reinterpret_cast(Offsets::FUN_CHARCOMP_UNEQUIP_SLOT)( + component, static_cast(compSlot)); + } + return 0; +} + +// The item a trade-skill recipe makes, from an `enchant:` link: a +// TRADESPELL whose first effect makes an item (4.3.4's test). +uint32_t RecipeItem(const char *link) { + const char *enchant = std::strstr(link, "enchant:"); + if (enchant == nullptr) + return 0; + const long spellID = std::strtol(enchant + 8, nullptr, 10); + if (spellID <= 0) + return 0; + const uint8_t *spell = DBC::Record(Offsets::VAR_SPELL_RECORDS, Offsets::VAR_SPELL_RECORD_COUNT, + static_cast(spellID)); + if (spell == nullptr || + (Game::Read(spell, Offsets::OFF_SPELL_RECORD_ATTRIBUTES) & + Offsets::SPELL_ATTR_TRADESPELL) == 0) + return 0; + return Game::Read(spell, Offsets::OFF_SPELL_RECORD_EFFECT_ITEM_TYPE); +} + +int __fastcall Script_TryOn(void *L) { + void *pane = ResolvePane(L); + if (pane == nullptr) + return 0; + uint32_t itemID = 0; + if (Game::Lua::Type(L, 2) == Game::Lua::TYPE_NUMBER) { + itemID = static_cast(Game::Lua::ToNumber(L, 2)); + } else if (Game::Lua::Type(L, 2) == Game::Lua::TYPE_STRING) { + // Copied: the name search below stomps the Lua stack. + char s[256]; + std::snprintf(s, sizeof(s), "%s", Game::Lua::ToString(L, 2)); + if (std::strstr(s, "enchant:") != nullptr) { + itemID = RecipeItem(s); + } else { + // An item link, `item:` string or numeric string resolves to an ID; + // any other string is the name of an item the player carries. + const Item::Arg::Resolved arg = Item::Arg::ResolveString(s); + Item::Location::ByGUIDResult found{}; + if (arg.itemID != 0) + itemID = static_cast(arg.itemID); + else if (arg.name != nullptr && Item::Location::FindByArg(L, arg, &found)) + itemID = static_cast(Item::ID::FromCGItem(found.item)); + } + } + if (itemID == 0) { + reinterpret_cast(Offsets::FUN_GAMEUI_DISPLAY_ERROR)( + Offsets::GAME_ERROR_NOT_EQUIPPABLE); + return 0; + } + reinterpret_cast(Offsets::FUN_DRESSUPMODEL_TRY_ON_ITEM)(pane, itemID); + return 0; +} + +const Game::Lua::FrameMethodEntry g_methods[] = { + {"UndressSlot", &Script_UndressSlot}, + {"TryOn", &Script_TryOn}, +}; + +const Game::Doc::Field kUndressArgs[] = { + Game::Doc::Req("slot", "number", "An inventory slot, 1 (head) to 19 (tabard)."), +}; +const Game::Doc::Function kUndressSlot{ + "Removes the item in one inventory slot from the model.", kUndressArgs, {}}; +const Game::Doc::Field kTryOnArgs[] = { + Game::Doc::Req("item", "ItemInfo", + "An item ID, item link, trade-skill recipe link, or the name of an item you carry."), +}; +const Game::Doc::Function kTryOn{"Puts an item on the model.", kTryOnArgs, {}}; +const Game::Doc::Method g_methodDocs[] = { + {"UndressSlot", &kUndressSlot}, + {"TryOn", &kTryOn}, +}; + +void RegisterLuaFunctions() { + Game::Lua::RegisterFrameMethods( + reinterpret_cast(Offsets::VAR_DRESSUPMODEL_METHOD_REGISTRY), g_methods, + static_cast(sizeof(g_methods) / sizeof(g_methods[0])), g_methodDocs, + static_cast(sizeof(g_methodDocs) / sizeof(g_methodDocs[0]))); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace +} // namespace Model::DressUp diff --git a/src/model/Glow.cpp b/src/model/Glow.cpp new file mode 100644 index 00000000..6f04d8df --- /dev/null +++ b/src/model/Glow.cpp @@ -0,0 +1,57 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `Model:SetGlow(value)` — 4.3.4's Model method (CSimpleModel_Scripts.cpp). +// +// In 4.3.4 it calls the virtual CSimpleModel::SetGlow, which does nothing on a +// Model; only the glue screen's ModelFFX overrides it, to set the strength of +// its glow effect. In the game every Model is a plain Model, so the method +// checks its arguments the way 4.3.4 does and changes nothing. + +#include "Game.h" +#include "Offsets.h" + +namespace Model::Glow { +namespace { + +int __fastcall Script_SetGlow(void *L) { + void *model = Game::Lua::ResolveModel(L); + if (model == nullptr) + return 0; + if (!Game::Lua::IsNumber(L, 2)) + Game::Lua::Error(L, "Usage: %s:SetGlow(value)", Game::Lua::ObjectDisplayName(model)); + return 0; +} + +const Game::Lua::FrameMethodEntry g_methods[] = { + {"SetGlow", &Script_SetGlow}, +}; + +const Game::Doc::Field kArgs[] = { + Game::Doc::Req("value", "number", "The glow strength."), +}; +const Game::Doc::Function kSetGlow{"Sets the glow strength of the model. It has no effect in the game.", + kArgs, {}}; +const Game::Doc::Method g_methodDocs[] = { + {"SetGlow", &kSetGlow}, +}; + +void RegisterLuaFunctions() { + Game::Lua::RegisterFrameMethods(reinterpret_cast(Offsets::VAR_MODEL_METHOD_REGISTRY), + g_methods, 1, g_methodDocs, 1); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace +} // namespace Model::Glow diff --git a/src/model/Rotation.cpp b/src/model/Rotation.cpp new file mode 100644 index 00000000..b80acbb3 --- /dev/null +++ b/src/model/Rotation.cpp @@ -0,0 +1,70 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +// `PlayerModel:SetRotation(rotation [, animate])` — 4.3.4's second argument. +// +// Vanilla's SetRotation (FUN_SCRIPT_PLAYERMODEL_SET_ROTATION) always turns the +// model with a shuffle animation (TurnTo 0x00505BB0). 4.3.4's RotateModel +// (CharacterModelBase.cpp) does the same when `animate` is true or absent, and +// with `animate` false only stores the facing: no shuffle, no turn latch. So a +// false `animate` stores the facing here and anything else runs vanilla's +// method unchanged. + +#include "Game.h" +#include "Offsets.h" + +namespace Model::Rotation { +namespace { + +constexpr int kTypeNone = -1; // lua_type of an absent argument + +using LuaMethod_t = int(__fastcall *)(void *L); + +int __fastcall Script_SetRotation(void *L) { + if (Game::Lua::Type(L, 3) == kTypeNone || Game::Lua::ToBoolean(L, 3) != 0) + return reinterpret_cast(Offsets::FUN_SCRIPT_PLAYERMODEL_SET_ROTATION)(L); + void *pane = Game::Lua::ResolveTypedObject(L, 1, Offsets::VAR_PLAYERMODEL_LUA_TYPE_ID); + if (pane == nullptr) + return 0; + if (!Game::Lua::IsNumber(L, 2)) { + Game::Lua::Error(L, "Usage: SetRotation(rotation (in radians))"); + return 0; + } + Game::Ref(pane, Offsets::OFF_SIMPLEMODEL_FACING) = + static_cast(Game::Lua::ToNumber(L, 2)); + return 0; +} + +const Game::Lua::FrameMethodEntry g_methods[] = { + {"SetRotation", &Script_SetRotation}, +}; + +const Game::Doc::Field kArgs[] = { + Game::Doc::Req("rotation", "number", "The facing in radians."), + Game::Doc::Opt("animate", "bool", "true", "False turns the model without the shuffle animation."), +}; +const Game::Doc::Function kSetRotation{"Turns the model to a facing.", kArgs, {}}; +const Game::Doc::Method g_methodDocs[] = { + {"SetRotation", &kSetRotation}, +}; + +void RegisterLuaFunctions() { + Game::Lua::RegisterFrameMethods( + reinterpret_cast(Offsets::VAR_PLAYERMODEL_METHOD_REGISTRY), g_methods, 1, + g_methodDocs, 1); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace +} // namespace Model::Rotation