From 019ffdf4c580472fda692bb82ba63f86e44c9c53 Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Sat, 7 Nov 2026 18:40:52 -0600 Subject: [PATCH] feat(model): ModelSceneActor animation event sounds ClassicAPI extensions: actor:SetPlayAnimationSounds(enabled) and scene:SetGroundTerrain([terrainTypeID]), each with its getter. Each actor model now gets the engine's event callback (CM2Model::SetEventCallback, 0x007133A0), as a unit's model does (0x00607800). model/SceneEvents.cpp sorts the events by their four-character tag, as the unit dispatcher CGUnit_C::OnModelEvent (0x005FFBD0) does. It receives the $CSL, $CSR and $CST missile releases, which moved there from SceneSpell.cpp. When the actor opts in, it also plays the sounds that a unit plays. They come from the CreatureSoundData of the display: its own row, else its model data's, as GetSoundData (0x0060AFB0) picks it. - $FD1 to $FD4: the fidgets at +0x38 (0x006232C0). - $FDX: the stand vocal at +0x20, with the world's 41-in-101 chance and a 10 s limit shared by all actors. It never plays for the active player's copy (0x006236B0, 0x00623490). - $WNG and $WGG: the wing flap at +0x2C and the glide at +0x30. The dispatcher plays them as vocal kinds 7 and 10, through slot 34 (push 7 / push 0xA, call [eax+0x88]). - $FSD: the engine's GetFootstepSound (0x00458450), by the scene's ground terrain, with FootstepSounds on. - $DTH: the dry thud from the engine's death-thud table (0x00C4E0F4), by size class (GetUnitSoundSize 0x00625500) and the ground. - $CSD: the event's own SoundEntries id, with EmoteSounds on. - $TRD: the precast sound (SpellVisual +0x38) of a PlaySpellVisual that is still preparing (0x0062FAA0). The sounds are off by default, so stock scenes such as the dressing room stay silent. They play in 2D through the by-ID player. A scene without a ground terrain has no footsteps and no death thud. $CSS, $CAH and $AH0 to $AH3 play nothing: they present a pending swing (0x006247D0), and an actor never swings at anything. The unit's display ID is kept on the actor so that its sound data can be found. --- README.md | 4 +- docs/API.md | 56 +++++++++ src/Offsets.h | 47 ++++++++ src/model/Scene.cpp | 45 ++++++++ src/model/Scene.h | 16 ++- src/model/SceneActor.cpp | 45 ++++++-- src/model/SceneEvents.cpp | 237 ++++++++++++++++++++++++++++++++++++++ src/model/SceneSpell.cpp | 18 +-- 8 files changed, 441 insertions(+), 27 deletions(-) create mode 100644 src/model/SceneEvents.cpp diff --git a/README.md b/README.md index 973a2dcd..6983c946 100644 --- a/README.md +++ b/README.md @@ -89,8 +89,8 @@ In the Frame rows, a name that starts with `:` is a method of the widget that th | [Frame: StatusBar](docs/API.md#statusbarsetreversefillisreversefill--statusbargetreversefill) | `:SetReverseFill` / `:GetReverseFill`, `:SetRotatesTexture` / `:GetRotatesTexture`, `:SetFillStyle` / `:GetFillStyle`, `:SetColorFill`, `:SetStatusBarDesaturated` / `:IsStatusBarDesaturated`, `:SetStatusBarDesaturation` / `:GetStatusBarDesaturation`, `:SetTimerDuration` / `:GetTimerDuration`, `:SetValue` / `:SetMinMaxValues` with `interpolation`, `:GetInterpolatedValue`, `:IsInterpolating`, `:SetToTargetValue` | | [Frame: Slider](docs/API.md#sliderenable--sliderdisable--sliderisenabled) | `:Enable` / `:Disable` / `:IsEnabled` | | [Frame: Cooldown](docs/API.md#createframecooldown--name-parent-template) | `CreateFrame("Cooldown")`, `:SetCooldown`, `:SetCooldownDuration`, `:SetCooldownFromExpirationTime`, `:Clear`, `:GetCooldownTimes`, `:GetCooldownDuration`, `:GetCooldownDisplayDuration`, `:Pause` / `:Resume`, `:SetPaused` / `:IsPaused`, `:SetReverse` / `:GetReverse`, `:SetDrawEdge` / `:GetDrawEdge`, `:SetDrawSwipe` / `:GetDrawSwipe`, `:SetDrawBling` / `:GetDrawBling`, `:SetSwipeColor`, `:SetEdgeColor`, `:SetSwipeTexture`, `:SetEdgeTexture`, `:SetBlingTexture`, `:SetRotation` / `:GetRotation`, `:SetHideCountdownNumbers` / `:GetHideCountdownNumbers`, `:GetCountdownFontString`, `:SetCountdownAbbrevThreshold` / `:GetCountdownAbbrevThreshold`, `:SetCountdownMillisecondsThreshold` / `:GetCountdownMillisecondsThreshold`, `:SetMinimumCountdownDuration` / `:GetMinimumCountdownDuration`, `OnCooldownDone`, `CooldownFrame_Set`, `CooldownFrame_Clear`, `CooldownFrame_SetDisplayAsPercentage` | -| [Frame: ModelScene](docs/API.md#modelscene) | `CreateFrame("ModelScene")`, `` (`drawLayer`, `fogNear`, `fogFar`, ``, ``), `:CreateActor`, `:GetNumActors`, `:GetActorAtIndex`, `:SetCameraPosition` / `:GetCameraPosition`, `:SetCameraOrientationByYawPitchRoll`, `:SetCameraOrientationByAxisVectors`, `:GetCameraForward`, `:GetCameraRight`, `:GetCameraUp`, `:SetCameraFieldOfView` / `:GetCameraFieldOfView`, `:SetCameraNearClip` / `:GetCameraNearClip`, `:SetCameraFarClip` / `:GetCameraFarClip`, `:SetViewInsets` / `:GetViewInsets`, `:SetViewTranslation` / `:GetViewTranslation`, `:Project3DPointTo2D`, `:SetLightType` / `:GetLightType`, `:SetLightVisible` / `:IsLightVisible`, `:SetLightDirection` / `:GetLightDirection`, `:SetLightPosition` / `:GetLightPosition`, `:SetLightAmbientColor` / `:GetLightAmbientColor`, `:SetLightDiffuseColor` / `:GetLightDiffuseColor`, `:SetFogColor` / `:GetFogColor`, `:SetFogNear` / `:GetFogNear`, `:SetFogFar` / `:GetFogFar`, `:ClearFog`, `:SetDrawLayer` / `:GetDrawLayer`, `:SetPaused`, `:SetAllowOverlappedModels` / `:GetAllowOverlappedModels` | -| [Frame: ModelSceneActor](docs/API.md#actorsetmodelbycreaturedisplayiddisplayid--useactiveplayercustomizations) | `:SetModelByCreatureDisplayID`, `:SetModelByPath`, `:SetModelByUnit`, `:SetModelByUnitCreatureDisplayID`, `:GetModelUnitGUID`, `:Dress`, `:Undress`, `:UndressSlot`, `:TryOn`, `:DressPlayerSlot`, `:IsSlotAllowed` / `:IsSlotVisible`, `:GetItemTransmogInfo`, `:GetItemTransmogInfoList`, `:SetItemTransmogInfo`, `:SetSheathed` / `:GetSheathed`, `:SetSheathedCategory`, `:UseUnitSheatheCategory`, `:SetAutoDress` / `:GetAutoDress`, `:IsGeoReady`, `:ClearModel`, `:IsLoaded`, `:GetModelPath`, `:SetPosition` / `:GetPosition`, `:SetYaw` / `:GetYaw`, `:SetPitch` / `:GetPitch`, `:SetRoll` / `:GetRoll`, `:SetScale` / `:GetScale`, `:SetUseCenterForOrigin` / `:IsUsingCenterForOrigin`, `:GetActiveBoundingBox`, `:GetMaxBoundingBox`, `:Show` / `:Hide` / `:SetShown` / `:IsShown` / `:IsVisible`, `:SetAlpha` / `:GetAlpha`, `:SetAnimation` / `:GetAnimation`, `:GetAnimationVariation`, `:SetAnimationBlendOperation` / `:GetAnimationBlendOperation`, `:SetPaused` / `:GetPaused`, `:SetSpellVisualKit` / `:GetSpellVisualKit`, `:PlayAnimationKit` / `:StopAnimationKit`, `:AttachToMount`, `:DetachFromMount`, `:CalculateMountScale`, `:GetAttachmentPosition`, `:AttachToActor`, `:DetachFromActor`, `:PlaySpellVisual`, `OnLoad`, `OnUpdate`, `OnModelLoading`, `OnModelLoaded`, `OnModelCleared`, `OnAnimFinished`, `` templates | +| [Frame: ModelScene](docs/API.md#modelscene) | `CreateFrame("ModelScene")`, `` (`drawLayer`, `fogNear`, `fogFar`, ``, ``), `:CreateActor`, `:GetNumActors`, `:GetActorAtIndex`, `:SetCameraPosition` / `:GetCameraPosition`, `:SetCameraOrientationByYawPitchRoll`, `:SetCameraOrientationByAxisVectors`, `:GetCameraForward`, `:GetCameraRight`, `:GetCameraUp`, `:SetCameraFieldOfView` / `:GetCameraFieldOfView`, `:SetCameraNearClip` / `:GetCameraNearClip`, `:SetCameraFarClip` / `:GetCameraFarClip`, `:SetViewInsets` / `:GetViewInsets`, `:SetViewTranslation` / `:GetViewTranslation`, `:Project3DPointTo2D`, `:SetLightType` / `:GetLightType`, `:SetLightVisible` / `:IsLightVisible`, `:SetLightDirection` / `:GetLightDirection`, `:SetLightPosition` / `:GetLightPosition`, `:SetLightAmbientColor` / `:GetLightAmbientColor`, `:SetLightDiffuseColor` / `:GetLightDiffuseColor`, `:SetFogColor` / `:GetFogColor`, `:SetFogNear` / `:GetFogNear`, `:SetFogFar` / `:GetFogFar`, `:ClearFog`, `:SetDrawLayer` / `:GetDrawLayer`, `:SetPaused`, `:SetAllowOverlappedModels` / `:GetAllowOverlappedModels`, `:SetGroundTerrain` / `:GetGroundTerrain` | +| [Frame: ModelSceneActor](docs/API.md#actorsetmodelbycreaturedisplayiddisplayid--useactiveplayercustomizations) | `:SetModelByCreatureDisplayID`, `:SetModelByPath`, `:SetModelByUnit`, `:SetModelByUnitCreatureDisplayID`, `:GetModelUnitGUID`, `:Dress`, `:Undress`, `:UndressSlot`, `:TryOn`, `:DressPlayerSlot`, `:IsSlotAllowed` / `:IsSlotVisible`, `:GetItemTransmogInfo`, `:GetItemTransmogInfoList`, `:SetItemTransmogInfo`, `:SetSheathed` / `:GetSheathed`, `:SetSheathedCategory`, `:UseUnitSheatheCategory`, `:SetAutoDress` / `:GetAutoDress`, `:IsGeoReady`, `:ClearModel`, `:IsLoaded`, `:GetModelPath`, `:SetPosition` / `:GetPosition`, `:SetYaw` / `:GetYaw`, `:SetPitch` / `:GetPitch`, `:SetRoll` / `:GetRoll`, `:SetScale` / `:GetScale`, `:SetUseCenterForOrigin` / `:IsUsingCenterForOrigin`, `:GetActiveBoundingBox`, `:GetMaxBoundingBox`, `:Show` / `:Hide` / `:SetShown` / `:IsShown` / `:IsVisible`, `:SetAlpha` / `:GetAlpha`, `:SetAnimation` / `:GetAnimation`, `:GetAnimationVariation`, `:SetAnimationBlendOperation` / `:GetAnimationBlendOperation`, `:SetPaused` / `:GetPaused`, `:SetSpellVisualKit` / `:GetSpellVisualKit`, `:PlayAnimationKit` / `:StopAnimationKit`, `:AttachToMount`, `:DetachFromMount`, `:CalculateMountScale`, `:GetAttachmentPosition`, `:AttachToActor`, `:DetachFromActor`, `:PlaySpellVisual`, `:SetPlayAnimationSounds` / `:GetPlayAnimationSounds`, `OnLoad`, `OnUpdate`, `OnModelLoading`, `OnModelLoaded`, `OnModelCleared`, `OnAnimFinished`, `` templates | | [Frame: ScrollingMessageFrame](docs/API.md#smfsethyperlinksenabledenabled--smfgethyperlinksenabled) | `:SetHyperlinksEnabled` / `:GetHyperlinksEnabled`, `:GetMessageInfo` (with the extra `:AddMessage` values), `:BackFillMessage` (adds a message as the oldest), `:RemoveMessagesByPredicate`, `:SetScrollOffset` / `:GetScrollOffset`, `:GetMaxScrollRange`, `:ScrollByAmount`, `:SetInsertMode` / `:GetInsertMode`, `:AddOnDisplayRefreshedCallback` | | [Frame: scripts](docs/API.md#onenable-and-ondisable-scripts) | `OnEnable`, `OnDisable`, `OnMinMaxChanged`, `OnAttributeChanged`, `OnCharComposition`, `OnTextChanged` (`userInput`), `PreClick`, `PostClick`, `SetModernScriptArgs` / `GetModernScriptArgs` | | [FriendList](docs/API.md#friendlist) | `AddOrRemoveFriend`, `C_FriendList.GetFriendInfo`, `C_FriendList.GetFriendInfoByIndex`, `C_FriendList.GetNumFriends`, `C_FriendList.GetNumOnlineFriends`, `C_FriendList.GetNumWhoResults`, `C_FriendList.GetWhoInfo`, `C_FriendList.IsFriend`, `C_FriendList.IsIgnored`, `C_FriendList.IsIgnoredByGuid`, `C_FriendList.IsWhoQueryPending`, `C_FriendList.SendWhoQueryByName`, `C_FriendList.SetFriendNotes`, `C_FriendList.SetFriendNotesByIndex` | diff --git a/docs/API.md b/docs/API.md index 3420c28f..82466fb5 100644 --- a/docs/API.md +++ b/docs/API.md @@ -840,6 +840,7 @@ build instructions. - [`scene:SetDrawLayer(layer)` / `scene:GetDrawLayer()`](#scenesetdrawlayerlayer--scenegetdrawlayer) - [`scene:SetPaused(paused [, affectsGlobalPause])`](#scenesetpausedpaused--affectsglobalpause) - [`scene:SetAllowOverlappedModels(allow)` / `scene:GetAllowOverlappedModels()`](#scenesetallowoverlappedmodelsallow--scenegetallowoverlappedmodels) + - [`scene:SetGroundTerrain([terrainTypeID])` / `scene:GetGroundTerrain()`](#scenesetgroundterrainterraintypeid--scenegetgroundterrain) - [`actor:SetModelByCreatureDisplayID(displayID [, useActivePlayerCustomizations])`](#actorsetmodelbycreaturedisplayiddisplayid--useactiveplayercustomizations) - [`actor:SetModelByPath(path [, useMips])`](#actorsetmodelbypathpath--usemips) - [`actor:SetModelByUnit(unit [, sheatheWeapons, autoDress, hideWeapons, usePlayerNativeForm, holdBowString, customRaceID])`](#actorsetmodelbyunitunit--sheatheweapons-autodress-hideweapons-useplayernativeform-holdbowstring-customraceid) @@ -875,6 +876,7 @@ build instructions. - [`actor:GetAttachmentPosition(attachmentID)`](#actorgetattachmentpositionattachmentid) - [`actor:AttachToActor(parent, attachmentID)`](#actorattachtoactorparent-attachmentid) - [`actor:DetachFromActor()`](#actordetachfromactor) + - [`actor:SetPlayAnimationSounds(enabled)` / `actor:GetPlayAnimationSounds()`](#actorsetplayanimationsoundsenabled--actorgetplayanimationsounds) - [`actor:PlaySpellVisual(spellID [, target [, castTimeMs]])`](#actorplayspellvisualspellid--target--casttimems) - [Actor scripts](#actor-scripts) - [`` templates](#actor-templates) @@ -19270,6 +19272,31 @@ current frame. `false` starts the animations again from the same frame. Stores a flag. It is `false` by default. The flag has no effect: a scene always draws, also when another model frame covers it. +### `scene:SetGroundTerrain([terrainTypeID])` / `scene:GetGroundTerrain()` + +Sets the ground that the actors of the scene stand on. The ground selects +the sounds of their footsteps and death thuds (see +[`actor:SetPlayAnimationSounds`](#actorsetplayanimationsoundsenabled--actorgetplayanimationsounds)). +`terrainTypeID` is a row of `TerrainType.dbc`: + +| ID | Ground | +|---|---| +| `0` | Dirt | +| `1` | Metallic | +| `2` | Stone | +| `3` | Snow | +| `4` | Wood | +| `5` | Grass | +| `6` | Leaves | +| `7` | Sand | +| `8` | Soggy | +| `9` | Dusty grass | + +Without `terrainTypeID`, the scene has no ground, and the actors make no +footsteps and no death thuds. This is the default. `scene:GetGroundTerrain()` +returns the ID, or nothing when the scene has no ground. This is a +ClassicAPI extension. + ### `actor:SetModelByCreatureDisplayID(displayID [, useActivePlayerCustomizations])` Shows a creature by its display ID (a `CreatureDisplayInfo` ID) and returns @@ -19642,6 +19669,35 @@ actor's position, turn and scale then count from the scene again. It returns `false` when the actor hangs on no actor. This also takes a rider off its mount. This is a ClassicAPI extension. +### `actor:SetPlayAnimationSounds(enabled)` / `actor:GetPlayAnimationSounds()` + +Sets whether the animations of the model play their sounds, as the +animations of a creature or a player do in the world. It is `false` by +default. When it is `true`, the animations play these sounds: + +- The wing flaps and wing glides of flying creatures. +- The fidget sounds and the stand voice of the creature. The stand voice + does not play every time, and all actors together play it at most once + every 10 seconds. A copy of your own character does not play it. +- Footsteps and the death thud. These need a ground on the scene + ([`scene:SetGroundTerrain`](#scenesetgroundterrainterraintypeid--scenegetgroundterrain)), + and footsteps need the `FootstepSounds` setting. +- The sounds that some animations carry, with the `EmoteSounds` setting. +- During the preparation of + [`actor:PlaySpellVisual`](#actorplayspellvisualspellid--target--casttimems), + the preparation sound of some spells. + +The sounds come from the creature display that the actor shows. An actor +that shows a model file has only the sounds that its animations carry. The +sounds play in 2D, like `PlaySound`. Attacks play no weapon sounds, because +an actor does not hit anything. This is a ClassicAPI extension. + +```lua +scene:SetGroundTerrain(5) -- grass +wolf:SetPlayAnimationSounds(true) +wolf:SetAnimation(5) -- run +``` + ### `actor:PlaySpellVisual(spellID [, target [, castTimeMs]])` Plays the visual of a spell that this actor casts at `target`, and returns diff --git a/src/Offsets.h b/src/Offsets.h index c9f0f697..6c092195 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -6295,6 +6295,9 @@ enum Offsets { OFF_SPELLVISUAL_MISSILE_ATTACHMENT = 0x24, OFF_SPELLVISUAL_MISSILE_SOUND = 0x28, OFF_SPELLVISUAL_IMPACT_MODEL = 0x30, + // The sound a player plays on its $TRD event while it prepares the spell + // (CGPlayer_C::PlayPrecastSound 0x0062FAA0). + OFF_SPELLVISUAL_PRECAST_SOUND = 0x38, // s_spellVisualAttachments: int[11] = {20, 34, 19, 21, 22, 17, 23, 24, // 25, 15, 16}, read from the binary; the first nine are the kit effect // columns' attachments. @@ -6506,6 +6509,50 @@ enum Offsets { // display's into the unit's +0x9C and seats the rider at +0x98 (always // 1.0) over it. Parsed from the DBC: 2404 = 1.0, 14332 = 1.5. OFF_CREATUREDISPLAYINFO_SCALE = 0x10, + // The unit's sound data and size class come from the display, else its + // model data: GetSoundData (0x0060AFB0, display +0x08 else model data + // +0x34) and GetUnitSoundSize (0x00625500, display +0x24 unless -1, else + // model data +0x0C). Verified by parsing the DBCs: display 49 has sound + // 0 and size class 1 at +0x24; model data 49 has sound 49 and size 1. + OFF_CREATUREDISPLAYINFO_SOUND_ID = 0x08, + OFF_CREATUREDISPLAYINFO_SIZE_CLASS = 0x24, + OFF_CREATUREMODELDATA_SIZE_CLASS = 0x0C, + OFF_CREATUREMODELDATA_SOUND_ID = 0x34, + // CreatureSoundData.dbc (30 columns; class 0x00C0DE4C, docs/DBCs.md). The + // columns the unit's model events read (benilla objectlayer/sounds): the + // stand vocal $FDX plays (+0x20, kind 5), the footstep id (+0x24, a + // FootstepTerrainLookup CreatureFootstepID), and the four fidgets $FD1 to + // $FD4 play (+0x38). Row 49 (human male): 2941, 186, 2942, 2943, 0, + // 2944, 191, 192, footstep 7, ..., fidget 5519. + VAR_CREATURESOUNDDATA_RECORDS = 0x00C0DE54, + VAR_CREATURESOUNDDATA_COUNT = 0x00C0DE58, + OFF_CREATURESOUNDDATA_STAND = 0x20, + OFF_CREATURESOUNDDATA_FOOTSTEP = 0x24, + // The wing flap (+0x2C, vocal kind 7) and glide (+0x30, kind 10) that + // the $WNG and $WGG events play through slot 34 (0x005FFBD0: `push 7` / + // `push 0xA`, `call [eax+0x88]`). Onyxia's row 191: flap 5059. + OFF_CREATURESOUNDDATA_WING_FLAP = 0x2C, + OFF_CREATURESOUNDDATA_WING_GLIDE = 0x30, + OFF_CREATURESOUNDDATA_FIDGET = 0x38, // int[4] + // TerrainType.dbc (6 columns; ids 0 Dirt .. 10 None). Its +0x10 is the + // TerrainTypeSounds id the footstep and death-thud tables are indexed by. + VAR_TERRAINTYPE_RECORDS = 0x00C0D684, + VAR_TERRAINTYPE_COUNT = 0x00C0D688, + OFF_TERRAINTYPE_SOUND_ID = 0x10, + // GetFootstepSound — `int __fastcall(int creatureFootstepID /*ecx*/, int + // terrainTypeID /*edx*/, int wet /*stack*/)`, RET 0x4 (disassembly + // 0x00458450): the FootstepTerrainLookup sound for the TerrainType row's + // +0x10, dry or wet, or 0 for an unknown terrain or footstep id. + FUN_GET_FOOTSTEP_SOUND = 0x00458450, + // The death thud table: five size classes of {?, count, pairs *}, 12 + // bytes each, the pair {dry, wet} indexed by TerrainTypeSounds id and + // bounded by count (PlayDeathThud 0x006236E0: `cmp ecx,[eax+0xC4E0F8]`, + // `mov eax,[eax+0xC4E0FC]`). + VAR_DEATH_THUD_SOUNDS = 0x00C4E0F4, + DEATH_THUD_SIZE_CLASSES = 5, + DEATH_THUD_STRIDE = 12, + OFF_DEATH_THUD_COUNT = 0x04, + OFF_DEATH_THUD_PAIRS = 0x08, VAR_CREATUREMODELDATA_RECORDS = 0x00C0DE68, VAR_CREATUREMODELDATA_COUNT = 0x00C0DE6C, OFF_CREATUREMODELDATA_MODEL_PATH = 0x08, diff --git a/src/model/Scene.cpp b/src/model/Scene.cpp index b92922c6..04cd40f5 100644 --- a/src/model/Scene.cpp +++ b/src/model/Scene.cpp @@ -142,6 +142,7 @@ struct Fields { // In the frame's own units: left, right, top, bottom; then x, y (y up). float viewInsets[4]; float viewTranslation[2]; + int32_t groundTerrain; // SetGroundTerrain: a TerrainType id, or -1 }; constexpr size_t kObjectSize = Offsets::MODEL_FRAME_SIZE + sizeof(Fields); @@ -550,6 +551,7 @@ void *__fastcall CreateModelScene(void *parent) { f.nearClip = kDefaultNearClip; f.farClip = kDefaultFarClip; f.drawLayer = Offsets::DRAWLAYER_ARTWORK; + f.groundTerrain = -1; InitLight(frame); InitFog(frame); InstallCamera(frame); @@ -788,6 +790,31 @@ int __fastcall Script_GetViewTranslation(void *L) { return 2; } +// The ground the actors' footsteps and death thuds sound on, as a unit's +// terrain type (+0xC60) chooses them in the world. nil: no ground. +int __fastcall Script_SetGroundTerrain(void *L) { + void *frame = Self(L); + if (frame == nullptr) + return 0; + if (Game::Lua::Type(L, 2) <= Game::Lua::TYPE_NIL) { + F(frame).groundTerrain = -1; + return 0; + } + if (!NumberArgs(L, 2, 1, Game::Lua::ObjectDisplayName(frame), + "SetGroundTerrain([terrainTypeID])")) + return 0; + F(frame).groundTerrain = static_cast(Game::Lua::ToNumber(L, 2)); + return 0; +} + +int __fastcall Script_GetGroundTerrain(void *L) { + void *frame = Self(L); + if (frame == nullptr || F(frame).groundTerrain < 0) + return 0; + Game::Lua::PushNumber(L, F(frame).groundTerrain); + return 1; +} + int __fastcall Script_SetAllowOverlappedModels(void *L) { if (void *frame = Self(L)) F(frame).allowOverlappedModels = Game::Lua::ToBoolean(L, 2) != 0 ? 1 : 0; @@ -950,6 +977,8 @@ const Game::Lua::FrameMethodEntry g_methods[] = { {"SetDrawLayer", &Script_SetDrawLayer}, {"GetDrawLayer", &Script_GetDrawLayer}, {"SetPaused", &Script_SetPaused}, + {"SetGroundTerrain", &Script_SetGroundTerrain}, + {"GetGroundTerrain", &Script_GetGroundTerrain}, {"SetAllowOverlappedModels", &Script_SetAllowOverlappedModels}, {"GetAllowOverlappedModels", &Script_GetAllowOverlappedModels}, {"Project3DPointTo2D", &Script_Project3DPointTo2D}, @@ -1070,6 +1099,18 @@ const Game::Doc::Field kFarFogRet[] = {Req("far", "number")}; const Game::Doc::Function kSetDrawLayer{"Sets the layer the scene draws in.", kLayerArg, {}}; const Game::Doc::Function kGetDrawLayer{"Returns the layer the scene draws in.", {}, kLayerRets}; const Game::Doc::Function kSetPaused{"Stops or restarts the actors' animations.", kPausedArgs, {}}; +const Game::Doc::Field kGroundTerrainArg[] = { + Opt("terrainTypeID", "number", nullptr, + "A TerrainType.dbc row: 0 Dirt, 1 Metallic, 2 Stone, 3 Snow, 4 Wood, 5 Grass, 6 Leaves, 7 " + "Sand, 8 Soggy, 9 DustyGrass. Without it, the scene has no ground."), +}; +const Game::Doc::Field kGroundTerrainRet[] = {Opt("terrainTypeID", "number")}; +const Game::Doc::Function kSetGroundTerrain{ + "Sets the ground that the footsteps and death thuds of the actors sound on.", + kGroundTerrainArg, {}, nullptr, true}; +const Game::Doc::Function kGetGroundTerrain{ + "Returns the ground terrain of the scene, or nothing when it has none.", {}, + kGroundTerrainRet, nullptr, true}; const Game::Doc::Field kOverlappedArg[] = {Req("allowOverlappedModels", "bool")}; const Game::Doc::Field kOverlappedRet[] = {Req("allowOverlappedModels", "bool")}; const Game::Doc::Function kSetAllowOverlappedModels{ @@ -1136,6 +1177,8 @@ const Game::Doc::Method g_methodDocs[] = { {"SetPaused", &kSetPaused}, {"SetAllowOverlappedModels", &kSetAllowOverlappedModels}, {"GetAllowOverlappedModels", &kGetAllowOverlappedModels}, + {"SetGroundTerrain", &kSetGroundTerrain}, + {"GetGroundTerrain", &kGetGroundTerrain}, {"Project3DPointTo2D", &kProject3DPointTo2D}, {"SetViewInsets", &kSetViewInsets}, {"GetViewInsets", &kGetViewInsets}, @@ -1201,4 +1244,6 @@ bool NumberArgs(void *L, int first, int count, const char *owner, const char *us float FloatArg(void *L, int index) { return static_cast(Game::Lua::ToNumber(L, index)); } +int GroundTerrain(void *sceneFrame) { return F(sceneFrame).groundTerrain; } + } // namespace Model::Scene diff --git a/src/model/Scene.h b/src/model/Scene.h index 6d90ed6e..e54543ab 100644 --- a/src/model/Scene.h +++ b/src/model/Scene.h @@ -96,6 +96,10 @@ class Actor : public Animation::Object { std::string modelPath; const uint8_t *dressRecord = nullptr; // CreatureDisplayInfoExtra, until dressed float displayScale = 1.0f; // a creature display's CreatureModelScale, else 1 + // The CreatureDisplayInfo the model shows (a creature display's, or the + // unit's UNIT_FIELD_DISPLAYID), for its sound data; 0 for a model file. + uint32_t displayID = 0; + bool playAnimationSounds = false; // SetPlayAnimationSounds // The character component dressing the model: a display's dress, or the // clone of a unit's. void *dresser = nullptr; @@ -170,10 +174,18 @@ void Link(Actor &caster); void Place(Actor &caster); // Drops every cast, missile and impact model of the caster. void Drop(Actor &caster); -// The model event callback (Offsets::FUN_M2MODEL_SET_EVENT_CALLBACK). +} // namespace Casts + +// The actor model's animation events (model/SceneEvents.cpp). +namespace Events { +// The model event callback (Offsets::FUN_M2MODEL_SET_EVENT_CALLBACK), user +// data the actor: missile releases for Casts, and the event sounds. void __stdcall OnModelEvent(uint32_t tag, uint32_t data, const float *point, uint32_t unknown, uint32_t userLow, uint32_t userHigh); -} // namespace Casts +} // namespace Events + +// The scene's ground terrain (SetGroundTerrain): a TerrainType id, or -1. +int GroundTerrain(void *sceneFrame); // Registers the actor class in the current Lua state. void RegisterActorClass(); diff --git a/src/model/SceneActor.cpp b/src/model/SceneActor.cpp index 06ea6247..cf3a3f88 100644 --- a/src/model/SceneActor.cpp +++ b/src/model/SceneActor.cpp @@ -234,6 +234,7 @@ void ReleaseModel(Actor &actor) { actor.dresser = nullptr; actor.dressRecord = nullptr; actor.displayScale = 1.0f; + actor.displayID = 0; actor.unitGuid = 0; actor.lanes[0] = actor.lanes[1] = Outfit::HeldLane{}; actor.weapons = Outfit::Weapons{}; @@ -265,7 +266,7 @@ void Actor::SetModel(void *newModel, const char *path, const uint8_t *newDressRe dressRecord = newDressRecord; const auto user = static_cast(reinterpret_cast(this)); M2::SetAnimDoneCallback(model, reinterpret_cast(&OnAnimDone), user, 0); - M2::SetEventCallback(model, reinterpret_cast(&Casts::OnModelEvent), user, 0); + M2::SetEventCallback(model, reinterpret_cast(&Events::OnModelEvent), user, 0); M2::SetRenderCallback(model, reinterpret_cast(Offsets::FUN_SIMPLEMODELFFX_LIGHT_FOG_CB), SceneFrame()); ApplyAlpha(); @@ -308,6 +309,7 @@ bool Actor::SetUnitModel(uint64_t guid) { } // SetModel keeps the unit fields: there is no model to clear. SetModel(copy, nullptr, nullptr); + displayID = Game::Read(descriptor, Offsets::OFF_UNIT_FIELD_DISPLAYID); Model::DisplayInfo::LightChildren(SceneFrame(), copy); return true; } @@ -627,12 +629,14 @@ bool ShowCreatureDisplay(Actor &actor, uint32_t displayID) { void *model = Model::DisplayInfo::CreateDisplayModel(Model::Pane::Scene(actor.SceneFrame()), displayID, &path); actor.SetModel(model, path, Model::DisplayInfo::DressRecord(displayID)); - if (model != nullptr) - actor.displayScale = Game::Read( - DBC::Record(Offsets::VAR_CREATUREDISPLAYINFO_RECORDS, - Offsets::VAR_CREATUREDISPLAYINFO_COUNT, displayID), - Offsets::OFF_CREATUREDISPLAYINFO_SCALE); - return model != nullptr; + if (model == nullptr) + return false; + actor.displayID = displayID; + actor.displayScale = Game::Read( + DBC::Record(Offsets::VAR_CREATUREDISPLAYINFO_RECORDS, + Offsets::VAR_CREATUREDISPLAYINFO_COUNT, displayID), + Offsets::OFF_CREATUREDISPLAYINFO_SCALE); + return true; } int __fastcall Script_SetModelByCreatureDisplayID(void *L) { @@ -1060,6 +1064,20 @@ int __fastcall Script_PlaySpellVisual(void *L) { return 1; } +int __fastcall Script_SetPlayAnimationSounds(void *L) { + if (Actor *actor = Self(L)) + actor->playAnimationSounds = Game::Lua::ToBoolean(L, 2) != 0; + return 0; +} + +int __fastcall Script_GetPlayAnimationSounds(void *L) { + Actor *actor = Self(L); + if (actor == nullptr) + return 0; + Game::Lua::PushBool(L, actor->playAnimationSounds); + return 1; +} + int __fastcall Script_DetachFromActor(void *L) { Actor *child = Self(L); if (child == nullptr) @@ -1358,6 +1376,8 @@ const Game::Lua::FrameMethodEntry kMethods[] = { {"AttachToActor", &Script_AttachToActor}, {"DetachFromActor", &Script_DetachFromActor}, {"PlaySpellVisual", &Script_PlaySpellVisual}, + {"SetPlayAnimationSounds", &Script_SetPlayAnimationSounds}, + {"GetPlayAnimationSounds", &Script_GetPlayAnimationSounds}, {"ClearModel", &Script_ClearModel}, {"IsLoaded", &Script_IsLoaded}, {"GetModelPath", &Script_GetModelPath}, @@ -1639,6 +1659,15 @@ const Game::Doc::Function kPlaySpellVisual{ "the missile and the impact, with their animations and sounds. False when the spell has no " "visual or this actor shows no model.", kPlaySpellVisualArgs, kMountSuccessRet, nullptr, true}; +const Game::Doc::Field kAnimationSoundsArg[] = {Req("enabled", "bool")}; +const Game::Doc::Function kSetPlayAnimationSounds{ + "Sets whether the model's animations play their sounds, as a unit's do in the world: fidgets, " + "the stand vocal, wing flaps, and on a scene with a ground terrain, footsteps and the death thud. Off by " + "default.", + kAnimationSoundsArg, {}, nullptr, true}; +const Game::Doc::Function kGetPlayAnimationSounds{ + "Returns whether the model's animations play their sounds.", {}, kAnimationSoundsArg, nullptr, + true}; const Game::Doc::Function kDetachFromActor{ "Takes this actor off the actor it hangs on. False when it hangs on none.", {}, kMountSuccessRet, nullptr, true}; @@ -1716,6 +1745,8 @@ const Game::Doc::Method kMethodDocs[] = { {"AttachToActor", &kAttachToActor}, {"DetachFromActor", &kDetachFromActor}, {"PlaySpellVisual", &kPlaySpellVisual}, + {"SetPlayAnimationSounds", &kSetPlayAnimationSounds}, + {"GetPlayAnimationSounds", &kGetPlayAnimationSounds}, {"ClearModel", &kClearModel}, {"IsLoaded", &kIsLoaded}, {"GetModelPath", &kGetModelPath}, diff --git a/src/model/SceneEvents.cpp b/src/model/SceneEvents.cpp new file mode 100644 index 00000000..2aa9a63e --- /dev/null +++ b/src/model/SceneEvents.cpp @@ -0,0 +1,237 @@ +// 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 . + +// An actor model's animation events. Each actor model gets the engine's event +// callback, as a unit's model does (CGUnit_C::SetModelCallbacks, 0x00607800), +// and the events reach this file the way a unit's reach its dispatcher +// (CGUnit_C::OnModelEvent, 0x005FFBD0, keyed by the four-character tag): +// +// - $CSL / $CSR / $CST release a PlaySpellVisual missile (model/SceneSpell.cpp), +// always. +// - With SetPlayAnimationSounds (a ClassicAPI extension, off by default so +// the stock scenes stay as quiet as before), the sounds a unit plays from +// its own data, here from the CreatureSoundData of the display the actor +// shows (GetSoundData 0x0060AFB0: the display's row, else its model +// data's): +// $FD1..$FD4 the fidget sounds, +0x38 (0x006232C0; $FD5..$FD9 play none) +// $FDX the stand vocal, +0x20: 41 in 101, at most once in 10 s +// for all units, never for the active player (0x006236B0, +// 0x00623490) +// $FSD the footstep: +0x24 by the ground's terrain through the +// engine's GetFootstepSound, with FootstepSounds on +// (0x00623390); the ground is the scene's SetGroundTerrain +// $DTH the death thud by the size class and the ground, from the +// engine's own table (0x006236E0) +// $WNG, $WGG the wing flap +0x2C and glide +0x30 (vocal kinds 7 and 10, +// which have no chance or rate limit) +// $CSD the event's payload as a SoundEntries id, with EmoteSounds +// on (0x00623C10) +// $TRD the precast sound (visual +0x38) of the spell being +// prepared (0x0062FAA0) +// The world plays these at the unit's position in 3D; a frame plays them +// 2D, as PlaySound. A scene without a ground terrain has no footsteps and +// no death thud, as nothing tells it what the actor stands on. +// +// Not played: the combat tags $CSS, $CAH and $AH0..$AH3 present a pending +// swing (0x006247D0) and play nothing without one, and an actor never swings +// at anything; footprints, splashes and camera shakes are world effects. + +#include "model/Scene.h" + +#include "Game.h" +#include "Offsets.h" +#include "cvar/Factory.h" +#include "dbc/Lookup.h" +#include "sound/Play.h" +#include "time/Clock.h" +#include "unit/Identity.h" + +#include +#include +#include + +namespace Model::Scene::Events { + +namespace { + +// The tags, as the engine compares them: four characters in a dword. +constexpr uint32_t Tag(char a, char b, char c, char d) { + return static_cast(static_cast(a)) | + static_cast(static_cast(b)) << 8 | + static_cast(static_cast(c)) << 16 | + static_cast(static_cast(d)) << 24; +} +constexpr uint32_t kCSL = Tag('$', 'C', 'S', 'L'); +constexpr uint32_t kCSR = Tag('$', 'C', 'S', 'R'); +constexpr uint32_t kCST = Tag('$', 'C', 'S', 'T'); +constexpr uint32_t kFD1 = Tag('$', 'F', 'D', '1'); +constexpr uint32_t kFD4 = Tag('$', 'F', 'D', '4'); +constexpr uint32_t kFDX = Tag('$', 'F', 'D', 'X'); +constexpr uint32_t kFSD = Tag('$', 'F', 'S', 'D'); +constexpr uint32_t kDTH = Tag('$', 'D', 'T', 'H'); +constexpr uint32_t kWNG = Tag('$', 'W', 'N', 'G'); +constexpr uint32_t kWGG = Tag('$', 'W', 'G', 'G'); +constexpr uint32_t kCSD = Tag('$', 'C', 'S', 'D'); +constexpr uint32_t kTRD = Tag('$', 'T', 'R', 'D'); +static_assert(kCSR == 0x52534324 && kWNG == 0x474E5724, "tags compare as the engine's dwords"); + +constexpr int kStandChance = 40; // 0x008626D4[5]: pass at <= 40 of 0..100 +constexpr uint32_t kStandIntervalMs = 10000; // 0x00623290 +uint32_t g_lastStandMs = 0; +bool g_standPlayed = false; + +// The display's sound data row, else its model data's. +const uint8_t *SoundData(uint32_t displayID) { + const uint8_t *display = DBC::Record(Offsets::VAR_CREATUREDISPLAYINFO_RECORDS, + Offsets::VAR_CREATUREDISPLAYINFO_COUNT, displayID); + if (display == nullptr) + return nullptr; + auto row = [](uint32_t id) { + return DBC::Record(Offsets::VAR_CREATURESOUNDDATA_RECORDS, + Offsets::VAR_CREATURESOUNDDATA_COUNT, id); + }; + if (const uint8_t *own = row(Game::Read(display, Offsets::OFF_CREATUREDISPLAYINFO_SOUND_ID))) + return own; + const uint8_t *modelData = + DBC::Record(Offsets::VAR_CREATUREMODELDATA_RECORDS, Offsets::VAR_CREATUREMODELDATA_COUNT, + Game::Read(display, Offsets::OFF_CREATUREDISPLAYINFO_MODEL_ID)); + return modelData != nullptr + ? row(Game::Read(modelData, Offsets::OFF_CREATUREMODELDATA_SOUND_ID)) + : nullptr; +} + +// GetUnitSoundSize: the display's size class unless -1, else its model +// data's; -1 when neither is known. +int SizeClass(uint32_t displayID) { + const uint8_t *display = DBC::Record(Offsets::VAR_CREATUREDISPLAYINFO_RECORDS, + Offsets::VAR_CREATUREDISPLAYINFO_COUNT, displayID); + if (display == nullptr) + return -1; + const auto size = Game::Read(display, Offsets::OFF_CREATUREDISPLAYINFO_SIZE_CLASS); + if (size != -1) + return size; + const uint8_t *modelData = + DBC::Record(Offsets::VAR_CREATUREMODELDATA_RECORDS, Offsets::VAR_CREATUREMODELDATA_COUNT, + Game::Read(display, Offsets::OFF_CREATUREDISPLAYINFO_MODEL_ID)); + return modelData != nullptr + ? Game::Read(modelData, Offsets::OFF_CREATUREMODELDATA_SIZE_CLASS) + : -1; +} + +bool CVarOn(const char *name) { return CVar::Factory::GetInt(CVar::Factory::Find(name), 0) != 0; } + +void Play(int32_t soundID) { + if (soundID > 0) + Sound::Play::PlayKitID(soundID); +} + +void PlayStand(const Actor &actor, const uint8_t *soundData) { + if (actor.unitGuid != 0 && actor.unitGuid == Unit::Identity::PlayerGuid()) + return; + if (std::rand() % 101 > kStandChance) + return; + const uint32_t now = Time::Clock::NowMs(); + if (g_standPlayed && Time::Clock::Elapsed(g_lastStandMs, now) < kStandIntervalMs) + return; + g_standPlayed = true; + g_lastStandMs = now; + Play(Game::Read(soundData, Offsets::OFF_CREATURESOUNDDATA_STAND)); +} + +void PlayFootstep(const Actor &actor, const uint8_t *soundData) { + using GetFootstepSound_t = int(__fastcall *)(int footstepID, int terrainTypeID, int wet); + const int terrain = GroundTerrain(actor.SceneFrame()); + if (terrain < 0 || !CVarOn("FootstepSounds")) + return; + Play(reinterpret_cast(Offsets::FUN_GET_FOOTSTEP_SOUND)( + Game::Read(soundData, Offsets::OFF_CREATURESOUNDDATA_FOOTSTEP), terrain, 0)); +} + +// PlayDeathThud's dry thud: the engine's table by size class and the +// terrain's TerrainTypeSounds id, bounded as it bounds it. +void PlayDeathThud(const Actor &actor) { + const int terrain = GroundTerrain(actor.SceneFrame()); + const int size = SizeClass(actor.displayID); + if (terrain < 0 || size < 0 || size >= Offsets::DEATH_THUD_SIZE_CLASSES) + return; + const uint8_t *terrainRow = DBC::Record(Offsets::VAR_TERRAINTYPE_RECORDS, + Offsets::VAR_TERRAINTYPE_COUNT, + static_cast(terrain)); + if (terrainRow == nullptr) + return; + const auto soundIndex = Game::Read(terrainRow, Offsets::OFF_TERRAINTYPE_SOUND_ID); + const uintptr_t table = static_cast(Offsets::VAR_DEATH_THUD_SOUNDS) + + static_cast(size) * Offsets::DEATH_THUD_STRIDE; + if (soundIndex < 0 || soundIndex >= Game::Read(table + Offsets::OFF_DEATH_THUD_COUNT)) + return; + const auto *pairs = Game::Read(table + Offsets::OFF_DEATH_THUD_PAIRS); + Play(pairs[soundIndex * 2]); +} + +void PlayPrecast(const Actor &actor) { + for (const SpellCast &cast : actor.spellCasts) + if (cast.phase == SpellCast::Phase::Precast) { + Play(Game::Read(cast.visual, Offsets::OFF_SPELLVISUAL_PRECAST_SOUND)); + return; + } +} + +void PlaySound(Actor &actor, uint32_t tag, uint32_t data) { + if (tag == kCSD) { + if (CVarOn("EmoteSounds")) + Play(static_cast(data)); + return; + } + if (tag == kTRD) { + PlayPrecast(actor); + return; + } + if (tag == kDTH) { + PlayDeathThud(actor); + return; + } + const uint8_t *soundData = SoundData(actor.displayID); + if (soundData == nullptr) + return; + if (tag >= kFD1 && tag <= kFD4 && (tag & 0x00FFFFFF) == (kFD1 & 0x00FFFFFF)) + Play(Game::Read(soundData, + Offsets::OFF_CREATURESOUNDDATA_FIDGET + ((tag >> 24) - '1') * 4)); + else if (tag == kFDX) + PlayStand(actor, soundData); + else if (tag == kFSD) + PlayFootstep(actor, soundData); + else if (tag == kWNG) + Play(Game::Read(soundData, Offsets::OFF_CREATURESOUNDDATA_WING_FLAP)); + else if (tag == kWGG) + Play(Game::Read(soundData, Offsets::OFF_CREATURESOUNDDATA_WING_GLIDE)); +} + +} // namespace + +void __stdcall OnModelEvent(uint32_t tag, uint32_t data, const float *point, uint32_t /*unknown*/, + uint32_t userLow, uint32_t /*userHigh*/) { + auto *actor = reinterpret_cast(static_cast(userLow)); + if (tag == kCSL || tag == kCSR || tag == kCST) { + // The unit's callback drops a point that is not a number (0x00607840). + if (point == nullptr || std::isnan(point[0]) || std::isnan(point[1]) || std::isnan(point[2])) + return; + actor->releaseEvent = true; + for (int i = 0; i < 3; ++i) + actor->releasePoint[i] = point[i]; + return; + } + if (actor->playAnimationSounds) + PlaySound(*actor, tag, data); +} + +} // namespace Model::Scene::Events diff --git a/src/model/SceneSpell.cpp b/src/model/SceneSpell.cpp index 99c329ab..37fed8f4 100644 --- a/src/model/SceneSpell.cpp +++ b/src/model/SceneSpell.cpp @@ -73,10 +73,8 @@ namespace Model::Scene::Casts { namespace { -constexpr uint32_t kEventCSL = 0x4C534324; // '$CSL' -constexpr uint32_t kEventCSR = 0x52534324; // '$CSR' -constexpr uint32_t kEventCST = 0x54534324; // '$CST' -constexpr uint32_t kReleaseEvents[] = {kEventCSL, kEventCSR, kEventCST}; +// The release events, '$CSL', '$CSR', '$CST'. +constexpr uint32_t kReleaseEvents[] = {0x4C534324, 0x52534324, 0x54534324}; constexpr int kAnimStand = 0; constexpr int kAnimCombatWound = 9; constexpr int kAnimInFlight = 144; @@ -466,16 +464,4 @@ void Drop(Actor &caster) { caster.releaseEvent = false; } -void __stdcall OnModelEvent(uint32_t tag, uint32_t /*data*/, const float *point, - uint32_t /*unknown*/, uint32_t userLow, uint32_t /*userHigh*/) { - if (tag != kEventCSL && tag != kEventCSR && tag != kEventCST) - return; - if (point == nullptr || std::isnan(point[0]) || std::isnan(point[1]) || std::isnan(point[2])) - return; // the unit's callback drops a point that is not a number (0x00607840) - auto *actor = reinterpret_cast(static_cast(userLow)); - actor->releaseEvent = true; - for (int i = 0; i < 3; ++i) - actor->releasePoint[i] = point[i]; -} - } // namespace Model::Scene::Casts