11 Commits

1384 changed files with 112294 additions and 1080 deletions
+3
View File
@@ -0,0 +1,3 @@
/config.local
/tmp
/cache
+8
View File
@@ -0,0 +1,8 @@
[cache]
type = "hardlink,copy"
[core]
remote = customization
['remote "customization"']
url = s3://warcraft-client/dvc/moonwell-client-sources/customization
endpointurl = https://storage.yandexcloud.net
region = ru-central1
+3
View File
@@ -0,0 +1,3 @@
# Add patterns of files dvc should ignore, which could improve
# the performance. Learn more at
# https://dvc.org/doc/user-guide/dvcignore
+4
View File
@@ -2,6 +2,7 @@ WOW_HOME=C:\Games\World of Warcraft 3.3.5
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_SESSION_TOKEN=
AWS_DEFAULT_REGION=
AWS_BUCKET=
AWS_ENDPOINT=
@@ -10,3 +11,6 @@ AWS_USE_PATH_STYLE_ENDPOINT=
PRODUCTION_REALMLIST=
PTR_REALMLIST=
LOCAL_REALMLIST=
SSH_USER=root
SSH_HOST=strictlypragmatic.ru
+1 -1
View File
@@ -5,8 +5,8 @@ manifest.json
.vscode
dist
build/
/new customization mpqs/*.mpq
Wow*.exe
*.backup.exe
Logs/
local-assets/
!Wow_Original.exe
+2 -1
View File
@@ -15,7 +15,8 @@
url = https://github.com/WarcraftXL/wxl-db2.git
[submodule "vendor/modules/wxl-modern-m2"]
path = vendor/modules/wxl-modern-m2
url = https://github.com/WarcraftXL/wxl-modern-m2.git
url = https://github.com/sindoring/wxl-modern-m2.git
branch = agent/guard-oversized-m2-batches
[submodule "vendor/modules/wxl-modern-wmo"]
path = vendor/modules/wxl-modern-wmo
url = https://github.com/WarcraftXL/wxl-modern-wmo.git
-2
View File
@@ -66,8 +66,6 @@ wxl_add_external_extension(wxl-unit-outline "${WXL_EXTERNAL_MODULES_DIR}/wxl-uni
# MoonWell-owned extensions. wxl-fdid-moonwell sorts after wxl-db2 and before
# the modern asset extensions, so it can layer custom CSV mappings over wxl.fdid.
wxl_add_external_extension(MoonWell "${WXL_LOCAL_MODULES_DIR}/moonwell")
wxl_add_external_extension(MoonwellCustomization
"${WXL_LOCAL_MODULES_DIR}/moonwell-customization")
wxl_add_external_extension(wxl-fdid-moonwell "${WXL_LOCAL_MODULES_DIR}/moonwell-fdid")
wxl_add_external_extension(wxl-moonwell-storage-fallback
"${WXL_LOCAL_MODULES_DIR}/moonwell-storage-fallback")
+355
View File
@@ -0,0 +1,355 @@
# Совместимость CVPatch и расширенной кастомизации
Документ описывает фактический набор графических MPQ MoonWell для клиента
**WoW 3.3.5a, build 12340**, их порядок загрузки, конфликты DBC, сборку слоя
совместимости и серверные требования парикмахерской.
## Исходные данные и происхождение
Старые архивы `patch-ruRU-A..W` относятся к **CVPatch (Collection Visual
Patch)** от Vary/vvladoon. Найденная тема оригинального проекта:
<https://forum.uwow.biz/threads/cvpatch-collection-visual-patch-lich-king-3-3-5.296264/>
Источник новых архивов утрачен. Единственная сохранённая подпись находится в
`new customization mpqs/readme.txt`:
- `patch-a-001.mpq` — `Model and Textures NPC`;
- `patch-b-002.mpq` — `Characters HD The War Within`;
- `patch-k.mpq` — `Interface`.
Новые архивы нельзя считать официальным или полностью автономным комплектом
для 3.3.5a: в них отсутствовал совместимый `BarberShopStyle.dbc`, а часть DBC
содержит данные более новых версий игры.
## Установленная часть CVPatch
| Патч | Назначение | Зависимости и пересечения |
|---|---|---|
| A | Основные модели существ, гуманоидов и транспорта | Основа для старого B |
| B | Альтернативные модели существ, гуманоидов и транспорта | Требует A |
| E | Текстуры экипировки в повышенном разрешении | Независимый |
| H | HD-модели игровых персонажей Leeviathan | Перекрывается новыми X/Y на одинаковых путях |
| I | Новые модели и текстуры брони и оружия | Изначально требовал H; его item-поля сохраняются при слиянии |
| M | Карты классических подземелий и пещер | Независимый |
| S | Эффекты заклинаний и способностей | Содержит собственные spell DBC |
| T | Текстуры зданий и зон | Независимый |
| U | Окружение Низины Арати и Ущелья Песни Войны | Независимый |
| W | Вода | Независимый |
Старые буквенные имена не меняются. X, Y и Z специально выбраны после W,
чтобы новый комплект и исправления имели приоритет без переименования CVPatch.
## Новые исходные архивы
### `patch-a-001.mpq` → `patch-ruRU-X.MPQ`
Размер исходника — около 2,49 GiB, `(listfile)` содержит 29 495 файлов:
- 16 023 запечённых NPC-текстуры в `Textures\bakednpctextures`;
- 13 465 файлов моделей, skin, анимаций и текстур в `Character`;
- модели стандартных рас и ряда NPC-рас: Vrykul, Naga, Taunka, Forest Troll и
других;
- 28 120 BLP, 1 245 ANIM, 94 SKIN и 29 M2;
- 7 DBC.
DBC внутри X:
| DBC | Строк | Роль |
|---|---:|---|
| `CharacterFacialHairStyles.dbc` | 272 | Штатный объём лицевой кастомизации |
| `CharHairGeosets.dbc` | 370 | Штатный объём причёсок |
| `CharSections.dbc` | 10 060 | Секции текстур персонажей |
| `CreatureDisplayInfoExtra.dbc` | 15 477 | Дополнительные параметры отображения существ |
| `EmotesTextSound.dbc` | 782 | Звуки текстовых эмоций |
| `HelmetGeosetVisData.dbc` | 21 | Скрытие geoset под шлемами |
| `SpellVisualKitModelAttach.dbc` | 594 | Крепление моделей визуальных эффектов |
X нужен текущему комбинированному комплекту для NPC-моделей и запечённых
текстур. Для новых причёсок главным является Y, который загружается позже и
перекрывает одноимённые таблицы X.
### `patch-b-002.mpq` → `patch-ruRU-Y.MPQ`
Размер исходника — около 2,80 GiB, `(listfile)` содержит 36 191 файл:
- 36 180 файлов в `Character`;
- HD-модели и текстуры десяти стандартных игровых рас WotLK;
- 34 934 BLP, 1 021 ANIM, 125 BONE, 80 SKIN и 20 M2;
- 11 DBC с существенно расширенной кастомизацией.
DBC внутри Y:
| DBC | Строк | Роль |
|---|---:|---|
| `CharacterFacialHairStyles.dbc` | 3 616 | Бороды, серьги, рога и другие лицевые варианты |
| `CharHairGeosets.dbc` | 854 | Geoset и номера причёсок |
| `CharHairTextures.dbc` | 177 | Текстуры волос |
| `CharSections.dbc` | 614 212 | Расширенные секции кожи, лица, волос и их сочетаний |
| `CharVariations.dbc` | 62 | Наборы вариаций персонажей |
| `ChrRaces.dbc` | 41 | Описания рас, включая данные за пределами штатного WotLK |
| `CreatureDisplayInfo.dbc` | 24 282 | Display ID моделей |
| `CreatureDisplayInfoExtra.dbc` | 15 477 | Раса, пол, внешность и предметные поля display ID |
| `CreatureFamily.dbc` | 40 | Семейства существ |
| `CreatureModelData.dbc` | 1 353 | Пути и параметры моделей |
| `HelmetGeosetVisData.dbc` | 65 | Расширенные правила отображения под шлемами |
Y обязателен для расширенной кастомизации. Z не содержит копии всех этих
таблиц и не заменяет Y.
Наличие современных race ID в DBC не добавляет новые игровые расы в ядро или
интерфейс 3.3.5a. Текущая интеграция поддерживает расширение внешности десяти
штатных рас. Новые игровые расы потребуют отдельной доработки клиента, UI,
сетевого протокола и сервера.
### `patch-k.mpq` — не устанавливается
Размер — около 53 MiB, `(listfile)` содержит 673 файла только в `Interface`:
- 547 BLP;
- 68 SKIN и 24 M2 для экранов входа и выбора персонажа;
- 15 Lua, 12 XML, TOC и вспомогательные файлы.
Архив меняет `Interface\Glues`, `Interface\GlueXML`, модели экранов входа и
создания персонажа. Он намеренно исключён из сборки, потому что перекрывает
кастомный интерфейс MoonWell. Устанавливать его вручную поверх текущего клиента
нельзя без отдельного разбора и слияния UI.
## Итоговый порядок загрузки
В локализованной цепочке `Data\ruRU` используется следующий порядок:
1. штатные архивы клиента, включая `patch-ruRU-3.MPQ`;
2. старые CVPatch `patch-ruRU-A..W`;
3. `patch-ruRU-X.MPQ` — неизменённая копия `patch-a-001.mpq`;
4. `patch-ruRU-Y.MPQ` — неизменённая копия `patch-b-002.mpq`;
5. `patch-ruRU-Z.MPQ` — сгенерированный слой совместимости MoonWell.
Z является последней инстанцией для конфликтующих DBC. Нельзя переносить его
раньше X/Y или устанавливать другой locale MPQ после Z, который содержит те же
таблицы.
## Содержимое `patch-ruRU-Z.MPQ`
В текущей сборке Z содержит:
- `BarberShopStyle.dbc` — расширенная таблица парикмахерской;
- `CreatureDisplayInfoExtra.dbc` — результат слияния новых display ID и
предметных полей CVPatch I;
- `SpellVisualKitModelAttach.dbc` — более полная версия из CVPatch S;
- `CreatureModelData.dbc` — сгенерированное слияние штатных, CVPatch и новых
моделей;
- `CreatureDisplayInfo.dbc` — сгенерированное слияние display ID;
- `WXLFileData.csv` и `WXLSpellOverrides.tsv` для WarcraftXL.
Последние четыре файла добавляются упаковщиком автоматически; поэтому состав
папки `src\Data\ruRU\patch-ruRU-Z` и готового MPQ не обязан совпадать буквально.
### Правила слияния DBC
`tool/scripts/build-customization-compat.ps1` выполняет следующие операции:
- берёт штатную базу из `patch-ruRU-3.MPQ`;
- сохраняет уникальные изменения `CreatureModelData` из CVPatch A;
- сохраняет уникальные изменения `CreatureDisplayInfo` из CVPatch B;
- отдаёт приоритет Y при реальном конфликте одной и той же строки;
- переносит изменённые item-поля `CreatureDisplayInfoExtra` из CVPatch I в
новые строки Y;
- восстанавливает `SpellVisualKitModelAttach.dbc` из CVPatch S;
- генерирует расширенный `BarberShopStyle.dbc`;
- обновляет входные `CreatureModelData.dbc` и `CreatureDisplayInfo.dbc` для
генератора MoonWell creatures.
Так Z не позволяет Y случайно уничтожить старые изменения существ, экипировки
и эффектов, а генерация MoonWell creatures не уничтожает новые display ID.
## Расширенная парикмахерская
### Причина исходного падения
Y расширил:
- `CharHairGeosets.dbc` с 370 до 854 строк;
- `CharacterFacialHairStyles.dbc` с 272 до 3 616 строк.
При этом исходные новые MPQ не содержали `BarberShopStyle.dbc`. Клиент продолжал
использовать штатную таблицу на 491 строку. При выборе нового варианта функция
`GetBarberShopTotalCost` не находила запись, после чего WoW падал с
`ERROR #132 / ACCESS_VIOLATION`. В зафиксированном крэше вызов шёл от
`BarberShopFrameSelector1Next`.
### Как сформирована новая таблица
Генератор:
- сохраняет все 491 штатную строку и исходную строковую таблицу байт-в-байт;
- добавляет отсутствующие причёски из `CharHairGeosets.dbc` Y;
- добавляет отсутствующую растительность и украшения из
`CharacterFacialHairStyles.dbc` Y;
- работает только с сочетаниями расы, пола и типа, уже существующими в штатном
`BarberShopStyle.dbc`, то есть с поддерживаемыми расами WotLK;
- сохраняет штатные строки типа 3 для особой кастомизации рыцарей смерти;
- назначает новые уникальные ID после максимального штатного ID;
- проверяет отсутствие дубликатов и полноту покрытия.
Результат:
- 3 765 строк всего;
- 152 новые причёски;
- 3 122 новых варианта растительности, серёг и других особенностей;
- максимальный номер лицевого варианта — 255, что помещается в поле внешности
персонажа 3.3.5a.
В исходном комплекте нет названий новых стилей. Поэтому сейчас они отображаются
как `New hairstyle N` и `New appearance N`. Это только подписи: на выбор модели
и сохранение внешности они не влияют.
## Что требуется клиенту и серверу
| Компонент | Клиент | Сервер |
|---|---|---|
| `patch-ruRU-X.MPQ` | Да, для текущего комплекта NPC/персонажей | Нет |
| `patch-ruRU-Y.MPQ` | Да, для моделей, текстур и основных customization DBC | Нет |
| `patch-ruRU-Z.MPQ` | Да, для совместимости и исправления парикмахерской | Нет как MPQ |
| Сгенерированный `BarberShopStyle.dbc` | Уже находится внутри Z | Да, отдельным DBC |
| Остальные клиентские DBC из X/Y | Загружаются из MPQ | Для текущих десяти рас не копируются |
Серверную копию нужно положить в каталог DBC worldserver, обычно:
```text
<server>/data/dbc/BarberShopStyle.dbc
```
После замены требуется полный перезапуск worldserver: DBC загружаются при
старте. Клиентская и серверная копии `BarberShopStyle.dbc` должны быть одним и
тем же сгенерированным файлом. Без серверной копии клиент больше не должен
падать при переключении, но сервер может отклонить применение нового стиля или
неверно рассчитать его стоимость.
Готовая серверная копия после запуска генератора находится в:
```text
build/customization-compat/server-dbc/BarberShopStyle.dbc
```
Тот же отслеживаемый исходник для Z находится в:
```text
src/Data/ruRU/patch-ruRU-Z/DBFilesClient/BarberShopStyle.dbc
```
Не следует копировать на сервер `ChrRaces.dbc`, `CharSections.dbc` или весь
набор DBC из Y без отдельной задачи и проверки ядра.
## Сборка
### Предварительные условия
В `.env` должен быть задан корректный `WOW_HOME`. В клиенте должны находиться:
- штатный `Data\ruRU\patch-ruRU-3.MPQ`;
- CVPatch A, B, I и S, используемые генератором как источники слияния;
- остальные CVPatch, если они должны остаться в итоговой установке.
В репозитории должны оставаться:
- `new customization mpqs\patch-a-001.mpq`;
- `new customization mpqs\patch-b-002.mpq`;
- `tool\target\release\mpqread.exe`.
### Пересоздание DBC совместимости
```powershell
.\tool\scripts\build-customization-compat.ps1
```
Скрипт обновляет:
```text
assets/dbc/3.3.5a/CreatureModelData.dbc
assets/dbc/3.3.5a/CreatureDisplayInfo.dbc
src/Data/ruRU/patch-ruRU-Z/DBFilesClient/CreatureDisplayInfoExtra.dbc
src/Data/ruRU/patch-ruRU-Z/DBFilesClient/SpellVisualKitModelAttach.dbc
src/Data/ruRU/patch-ruRU-Z/DBFilesClient/BarberShopStyle.dbc
build/customization-compat/server-dbc/BarberShopStyle.dbc
```
### Упаковка MPQ
```powershell
.\tool\target\release\tool.exe .\src .\dist
```
Упаковщик:
- собирает Z из исходников и сгенерированных MoonWell DBC;
- не копирует внешние графические X/Y в `dist` и не включает их в managed manifest;
- не добавляет `patch-k.mpq`.
Для полной локальной сборки и синхронизации клиента можно использовать:
```powershell
.\run.ps1 -Env local
```
Этот сценарий также собирает WarcraftXL, останавливает блокирующие процессы и
синхронизирует весь `dist` в `WOW_HOME`. Для проверки только изменения Z можно
собрать архив упаковщиком и скопировать лишь
`dist\Data\ruRU\patch-ruRU-Z.MPQ`.
Сборка этих архивов не должна автоматически изменять `manifest.json`. Манифест
обновляется владельцем проекта отдельно после локальной проверки.
## Исходники MPQ и установленные копии
Файлы в `new customization mpqs` используются только как локальные источники
генератора таблиц совместимости. В готовом клиенте X и Y управляются отдельно от
репозиторных патчей.
Списки репозиторных и внешних графических патчей находятся в
`patch-layout.json`. `deploy.ps1`, `run.ps1`, генератор манифеста и S3 uploader
синхронизируют только список `repositoryPatches`. Пути из `graphicsPatches`
сохраняются без копирования и удаления. Если один путь указан в обоих списках,
`repositoryPatches` имеет приоритет.
Z не консолидирует многогигабайтные модели и текстуры X/Y. Удаление X или Y из
клиента не освобождается наличием текущих DBC в Z.
## Проверка после сборки
Минимальный сценарий локальной проверки:
1. Полностью закрыть WoW перед заменой MPQ.
2. Проверить наличие X, Y и Z в `Data\ruRU`.
3. Запустить клиент и открыть создание персонажа.
4. Проверить оба пола и основные расы, пролистать причёски и лицевые варианты.
5. Создать тестового персонажа, войти в мир и проверить модель после повторного
входа.
6. Открыть парикмахерскую и несколько раз нажать вперёд/назад у каждого
селектора.
7. Проверить отображение стоимости и отсутствие `ERROR #132`.
8. Применить новый стиль, выйти из мира и войти снова.
9. Проверить старую броню, NPC-модели и эффекты заклинаний, которые могли быть
затронуты конфликтующими DBC.
Для шага 8 сервер уже должен использовать сгенерированный
`BarberShopStyle.dbc`.
## Диагностика
| Симптом | Вероятная причина |
|---|---|
| Новых причёсок нет | Отсутствует Y или более поздний MPQ перекрыл его `CharHairGeosets`/`CharSections` |
| Модель отсутствует или отображается неверно | X/Y не скопированы полностью либо повреждены многогигабайтные архивы |
| Падение при переключении в парикмахерской | Z отсутствует, загружен раньше Y или его `BarberShopStyle.dbc` перекрыт |
| Вариант выбирается, но не применяется | На сервере остался штатный `BarberShopStyle.dbc` или worldserver не перезапущен |
| Исчезли старые NPC/display ID | Z не пересобран после изменения источников CVPatch или Y |
| Проблемы со старой экипировкой | Потеряны item-поля CVPatch I в `CreatureDisplayInfoExtra.dbc` |
| Изменился экран входа/создания персонажа | `patch-k.mpq` был установлен вручную |
Перед заменой рабочего Z рекомендуется сохранять предыдущий архив. Последняя
локальная резервная копия, созданная во время исправления парикмахерской:
```text
build/customization-compat/client-backup/patch-ruRU-Z.before-barbershop.MPQ
```
+82
View File
@@ -0,0 +1,82 @@
# DragonUI_NewEra compatibility
Compatibility was audited against `ghbset/DragonUI_NewEra` commit
`37a29d640f97545ff1bb7d4b0ba7a5329cce1b8c` (2026-08-09).
## Status
DragonUI_NewEra is bundled in `patch-ruRU-5` as a required MoonWell system
component. It is enabled by default and hidden from the AddOns list together
with DragonUI and `!!!ClassicAPI`.
The MoonWell DragonUI exposes the integration seams used by NewEra:
- global `DragonUI` addon table;
- `ModuleRegistry`;
- `MoversSystem` and the editable-frame API;
- `OptionsPanel` and `PanelControls` after `DragonUI_Options` is loaded;
- `Fonts`, `SafeCall`, `CombatQueue`, and global `SetAtlasTexture`.
NewEra remains a separate addon folder rather than being merged into DragonUI.
Its TOC retains:
```toc
## Interface: 30300
## Dependencies: DragonUI, !!!ClassicAPI
## OptionalDeps: DragonUI_Options
```
`DragonUI_NewEra` is an extension, not a replacement for the HUD modules. It
does not need `X-DragonUI-Overrides` unless a future NewEra module explicitly
takes ownership of `mainbars`, `minimap`, `buffs`, or another registered HUD
module.
## Bundled sources
The system package contains:
```text
Interface/AddOns/!!!ClassicAPI/ b3da3000bba23a2c31aa9c9b7c0232d5973789e6
Interface/AddOns/DragonUI_NewEra/ 37a29d640f97545ff1bb7d4b0ba7a5329cce1b8c
```
Upstream Git metadata, screenshots, and top-level build tools are excluded.
Runtime sources, assets, and the upstream QA harness are retained. The exact
revisions are also recorded in addon TOC metadata as `X-Upstream-Commit`.
Neither audited upstream contains an explicit repository-wide redistribution
license. MoonWell maintainers must obtain and archive redistribution permission
before a public release. The source revisions above preserve provenance but do
not replace that permission.
## Known ownership conflict
Both MoonWellClient and NewEra provide an Encounter Journal / Adventure Guide
and the `ToggleEncounterJournal` entry point. MoonWell's journal is currently
authoritative because it receives server-backed data. NewEra's encounter
journal files are intentionally omitted from its system TOC, and its dead
options toggle is hidden.
The NewEra combined-bag module is marked work in progress upstream. Treat it as
opt-in and do not use it as the default replacement for DragonUI/Blizzard bags
without a separate gameplay test pass.
NewEra ships 94 power-of-two BLP atlases with one dimension above the project's
conservative 512-pixel authoring limit; the largest are 2048x2048. Upstream
marks their BLP2 encodings as 3.3.5a-loadable and they package successfully,
but every affected panel still requires an in-client render pass on MoonWell's
exact executable before release. If that client rejects them, split the atlases
without changing their public atlas names instead of silently scaling UI
geometry.
## Release checklist
1. Update only from reviewed, pinned DragonUI_NewEra and ClassicAPI revisions.
2. Obtain and record licenses or permissions for code, fonts, sounds, and BLPs.
3. Keep DragonUI_NewEra as its own folder and TOC; do not merge it into
DragonUI or FrameXML.
4. Keep NewEra Encounter Journal disabled until ownership is deliberately
migrated from MoonWellClient.
5. Test Character, Spellbook, Talents, Professions, Auction House, LFG, Social,
Collections, and the DragonUI options tab on build 12340.
6. Test login with NewEra disabled: the default DragonUI must remain complete.
+105
View File
@@ -0,0 +1,105 @@
# DragonUI: replacement addons
MoonWell ships DragonUI as the default interface. Players can replace an
individual DragonUI module without copying or editing the bundled addon.
## Replacement addon structure
The replacement must use its own folder and addon name. Do not create another
folder named `DragonUI`; files inside an MPQ and loose files with the same
virtual path do not form a supported update mechanism.
```text
MyDragonUIMinimap/
|-- MyDragonUIMinimap.toc
`-- MyDragonUIMinimap.lua
```
`MyDragonUIMinimap.toc`:
```toc
## Interface: 30300
## Title: My DragonUI Minimap
## Dependencies: DragonUI
## X-DragonUI-Overrides: minimap
## X-DragonUI-Override-Priority: 100
MyDragonUIMinimap.lua
```
The `X-DragonUI-Overrides` declaration is required. DragonUI reads it before
dependent addons execute and does not apply the bundled implementation. A list
may contain several comma-separated module identifiers.
`MyDragonUIMinimap.lua`:
```lua
local provider = {}
function provider:Activate(dragonUI, moduleName)
-- Create or show the replacement here.
end
function provider:Deactivate(dragonUI, moduleName)
-- Hide frames and unregister events created by this provider.
end
local ok, reason = DragonUI:RegisterModuleOverride(
"minimap",
"MyDragonUIMinimap",
provider,
{ priority = 100 }
)
if not ok then
DEFAULT_CHAT_FRAME:AddMessage("MyDragonUIMinimap: " .. tostring(reason))
end
```
The owner passed to `RegisterModuleOverride` must match the addon folder/TOC
name. Supported provider activation names are `Activate`, `Apply`, `Enable`, or
`OnEnable`; cleanup names are `Deactivate`, `Restore`, `Disable`, or
`OnDisable`.
## Public API (version 1)
```lua
DragonUI.PUBLIC_API_VERSION
DragonUI:RegisterModuleOverride(moduleName, owner, provider[, options])
DragonUI:UnregisterModuleOverride(moduleName, owner)
DragonUI:IsModuleOverridden(moduleName)
DragonUI:GetModuleOverride(moduleName) -- owner, provider
```
DragonUI also sends the Ace message `DRAGONUI_OVERRIDE_CHANGED` with
`moduleName, owner`. `owner` is nil after the final provider is removed.
Registering a replacement at runtime without TOC metadata is supported only
for a module that can be restored safely. For a load-once module the call
returns `true, "RELOAD_REQUIRED"`; add the metadata and reload the UI.
## Bundled module identifiers
The registry currently exposes these identifiers:
```text
bagsort, boss, buffs, buttons, castbar, chatmods, combuctor, cooldowns,
darkmode, itemquality, keybinding, mainbars, micromenu, minimap, multicast,
noop, petbar, player, questtracker, rage_indicator, stance, tooltip,
unitframe_layers, vehicle
```
Target/focus/party frames still contain legacy startup code and will be added
to the public registry before they are advertised as independently replaceable.
## Conflict resolution
When multiple enabled addons claim the same module, the highest numeric
`X-DragonUI-Override-Priority` wins. Equal priorities are resolved by addon
name to make the result deterministic. A declaration that never registers a
provider is rejected at `PLAYER_LOGIN`, and DragonUI restores its bundled
module so the player is not left without that UI element.
Module suppression is session-only. DragonUI restores the player's saved
enabled/disabled choice during `PLAYER_LOGOUT`, so removing a replacement addon
automatically brings back the previous DragonUI configuration.
+45
View File
@@ -47,6 +47,8 @@ git submodule update --remote vendor/warcraftxl vendor/modules/*
- Visual Studio 2022 с C++ toolchain для Win32;
- CMake 3.20+;
- Rust/Cargo для существующего MPQ-сборщика;
- Python 3 и DVC с поддержкой S3 для содержимого внешних графических патчей
(`py -m pip install -r requirements-dvc.txt`);
- локальный оригинальный `Wow_Original.exe` с SHA-256
`AA63A5750D60EF16746C686B3D5E26876D98953EAB08B1C026CD0FAF78E88CB8`.
@@ -109,6 +111,27 @@ $env:WOW_HOME = 'C:\Program Files (x86)\World of Warcraft'
.\run.ps1
```
Для быстрой разработки интерфейса без пересборки MPQ:
```powershell
# Наложить src\Data\...\Interface на клиент и следить за изменениями
.\hotreload.ps1
# То же самое, но запустить клиент и автоматически завершить сессию после его выхода
.\hotreload.ps1 -Launch
# Явно указать клиент, если WOW_HOME не задан
.\hotreload.ps1 -ClientPath 'D:\Games\World of Warcraft'
# Подключиться к другому серверу вместо локального
.\hotreload.ps1 -Realmlist 'logon.example.org'
```
Во время сессии изменённые файлы сразу копируются в `WOW_HOME\Interface`; увидеть изменения в игре
можно после `/reload`. По `Ctrl+C` или после выхода запущенного через `-Launch` клиента временные
файлы удаляются, а существовавшие до запуска файлы восстанавливаются. По умолчанию на время сессии
в `Data\ruRU\realmlist.wtf` записывается `127.0.0.1`; исходный realmlist также восстанавливается.
Диагностика запуска находится в `Logs\wxl-core.log` и `Logs\d3d9proxy.log` внутри клиента.
## MPQ-пакеты
@@ -123,6 +146,28 @@ WarcraftXL не требуется и в объектное хранилище
- `patch-ruRU-5` — русская локализация и интерфейс;
- `patch-Z` — Mythic+ ресурсы и клиентские данные.
## DragonUI и пользовательские замены
DragonUI поставляется как включённый системный интерфейс. Игрок не заменяет
файлы из MPQ: отдельный аддон может заранее объявить, какие модули он берёт под
свой контроль, и зарегистрировать собственную реализацию после загрузки
DragonUI. Формат TOC, Lua API, приоритеты и рабочий пример описаны в
[`DRAGONUI_OVERRIDES.md`](DRAGONUI_OVERRIDES.md).
DragonUI_NewEra и его `!!!ClassicAPI` входят в системный интерфейс MoonWell.
Зафиксированные upstream-версии, состав поставки и решение конфликта двух
Encounter Journal описаны в [`DRAGONUI_NEWERA.md`](DRAGONUI_NEWERA.md).
Управляемые репозиторием MPQ и внешние графические патчи перечислены отдельно в
`patch-layout.json`. Сборка и deploy синхронизируют только `repositoryPatches` и
не изменяют `graphicsPatches`. При пересечении списков репозиторный патч имеет
приоритет.
Распакованное содержимое больших патчей кастомизации хранится через DVC в
`assets/graphics/`, а бинарные объекты — в настроенном S3. Инструкции по первичной
загрузке, изменению и импорту MPQ находятся в
[`assets/graphics/README.md`](assets/graphics/README.md).
## Лицензирование
WarcraftXL распространяется по GPL-3.0 и подключён как отдельный неизменённый upstream submodule.
Binary file not shown.
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
/patch-X
+6
View File
@@ -0,0 +1,6 @@
outs:
- md5: 012ce72d8dfdf089b20a28f6e6158b58.dir
size: 1195310
nfiles: 4
hash: md5
path: patch-X
+14
View File
@@ -0,0 +1,14 @@
/patch-ruRU-X
/patch-ruRU-Y
/backup-ruRU
/patch-ruRU-6
/patch-ruRU-A
/patch-ruRU-B
/patch-ruRU-E
/patch-ruRU-H
/patch-ruRU-I
/patch-ruRU-M
/patch-ruRU-S
/patch-ruRU-T
/patch-ruRU-U
/patch-ruRU-W
@@ -0,0 +1,6 @@
outs:
- md5: b120587dfcd255f78392ca52705a00ff.dir
size: 38876467
nfiles: 161
hash: md5
path: backup-ruRU
@@ -0,0 +1,6 @@
outs:
- md5: 9ca2ee746d80e8a0c951c5ef476ae654.dir
size: 1064210
nfiles: 3
hash: md5
path: patch-ruRU-6
@@ -0,0 +1,6 @@
outs:
- md5: 97232ae859eaa1a16b137efd1a2e9122.dir
size: 2748988973
nfiles: 8817
hash: md5
path: patch-ruRU-A
@@ -0,0 +1,6 @@
outs:
- md5: bb686aebf7c9cae2c02433abde9a9f19.dir
size: 771051083
nfiles: 2911
hash: md5
path: patch-ruRU-B
@@ -0,0 +1,6 @@
outs:
- md5: d6b2fe0e3f23c47dc944ca4a8f82d97a.dir
size: 9275755440
nfiles: 21977
hash: md5
path: patch-ruRU-E
@@ -0,0 +1,6 @@
outs:
- md5: 5e95536d2c6f6ff792f05b800105bedc.dir
size: 3727395837
nfiles: 40296
hash: md5
path: patch-ruRU-H
@@ -0,0 +1,6 @@
outs:
- md5: 5db07768b0814c970d84a99b6072fd9f.dir
size: 31453961
nfiles: 186
hash: md5
path: patch-ruRU-I
@@ -0,0 +1,6 @@
outs:
- md5: e927ae98c9971f378a82feb3299fdcb8.dir
size: 69521651
nfiles: 1552
hash: md5
path: patch-ruRU-M
@@ -0,0 +1,6 @@
outs:
- md5: 449383bbe05ebebb6bad2c37da7793c4.dir
size: 142167464
nfiles: 1751
hash: md5
path: patch-ruRU-S
@@ -0,0 +1,6 @@
outs:
- md5: fc19500b5ce0fd312a415a3118afd58d.dir
size: 656858260
nfiles: 1810
hash: md5
path: patch-ruRU-T
@@ -0,0 +1,6 @@
outs:
- md5: 783909a6c2ebed5d4f43516fe1ea68bb.dir
size: 460642379
nfiles: 1837
hash: md5
path: patch-ruRU-U
@@ -0,0 +1,6 @@
outs:
- md5: e2a1448eb0e443797acd577fc4b67249.dir
size: 44597910
nfiles: 484
hash: md5
path: patch-ruRU-W
@@ -0,0 +1,6 @@
outs:
- md5: 3d322d290959d1ead612f3b76860a1ea.dir
size: 3984134962
nfiles: 29495
hash: md5
path: patch-ruRU-X
@@ -0,0 +1,6 @@
outs:
- md5: 42f3a8ac35674e33c0a4420c84cadcb8.dir
size: 11053212781
nfiles: 36191
hash: md5
path: patch-ruRU-Y
+66
View File
@@ -0,0 +1,66 @@
# Графические MPQ-патчи
В этой директории через DVC версионируется распакованное содержимое всех 15 патчей из
`graphicsPatches` в `patch-layout.json`. Git хранит небольшие файлы `*.dvc`, а сами ресурсы —
в S3 remote `customization`. Хэшированные пути в S3 являются внутренней адресацией DVC:
исходное дерево с обычными именами восстанавливается командой `dvc pull`.
## Первичная настройка
```powershell
py -m pip install -r requirements-dvc.txt
Copy-Item .env.example .env # если локального .env ещё нет
.\configure-dvc.ps1
py -m dvc pull
```
Можно скачать один патч, передав его указатель явно:
```powershell
py -m dvc pull assets/graphics/Data/ruRU/patch-ruRU-X.dvc
```
Секреты записываются только в `.dvc/config.local`; этот файл исключён из Git. Вместо ключей
из `.env` можно использовать AWS profile: `.\configure-dvc.ps1 -Profile moonwell`.
## Изменение ресурсов
DVC-кэш использует hardlink на NTFS. Перед ручным изменением дерева отвяжите его от кэша:
```powershell
py -m dvc unprotect assets/graphics/Data/ruRU/patch-ruRU-X
# изменить, добавить или удалить файлы
py -m dvc add assets/graphics/Data/ruRU/patch-ruRU-X
py -m dvc push
git add assets/graphics/Data/ruRU/patch-ruRU-X.dvc
```
Сначала выполняйте `dvc push`, затем коммитьте Git-указатель, чтобы коммит не ссылался на ещё
не загруженные объекты.
## Импорт MPQ
`mpqextract` принимает встроенный `(listfile)` и любое количество внешних listfile. Он извлекает
все известные пути, а блоки с неизвестными именами сохраняет в `__mpqmeta__/unresolved/`.
Манифест `__mpqmeta__/unresolved.json` связывает каждый blob с MPQ-хэшами и индексом блока,
поэтому содержимое архива не теряется даже при неполном listfile.
```powershell
cargo run --release --manifest-path tool/Cargo.toml --bin mpqextract -- `
'patch.mpq' 'assets/graphics/Data/ruRU/patch-ruRU-N' 'master-list.txt'
```
В `patch-ruRU-A`, `B`, `S`, `T`, `U` и `W` есть такие безымянные блоки. Для их безопасной
пересборки нужен авторитетный listfile с исходными путями; пока он не найден, исходные MPQ в
дистрибуционном S3 остаются каноническими архивами. `mpqpack` намеренно отказывается собирать
дерево с `__mpqmeta__`, поскольку подмена путей хэшами изменила бы семантику патча.
Полностью разрешённое дерево собирается так:
```powershell
cargo run --release --manifest-path tool/Cargo.toml --bin mpqpack -- `
'assets/graphics/Data/ruRU/patch-ruRU-X' 'build/graphics/patch-ruRU-X.MPQ'
```
Сводка исходных объектов, DVC-хэшей и количества разрешённых блоков находится в
`assets/graphics/sources.json`.
+157
View File
@@ -0,0 +1,157 @@
{
"sourcePrefix": "s3://warcraft-client/World of Warcraft/",
"patches": [
{
"archive": "Data/patch-X.MPQ",
"archiveBytes": 496584,
"dvcPointer": "assets/graphics/Data/patch-X.dvc",
"dvcMd5": "012ce72d8dfdf089b20a28f6e6158b58.dir",
"extractedBytes": 1195310,
"trackedFiles": 4,
"resolvedFiles": 4,
"unresolvedBlocks": 0
},
{
"archive": "Data/ruRU/backup-ruRU.MPQ",
"archiveBytes": 23981093,
"dvcPointer": "assets/graphics/Data/ruRU/backup-ruRU.dvc",
"dvcMd5": "b120587dfcd255f78392ca52705a00ff.dir",
"extractedBytes": 38876467,
"trackedFiles": 161,
"resolvedFiles": 161,
"unresolvedBlocks": 0
},
{
"archive": "Data/ruRU/patch-ruRU-6.MPQ",
"archiveBytes": 375062,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-6.dvc",
"dvcMd5": "9ca2ee746d80e8a0c951c5ef476ae654.dir",
"extractedBytes": 1064210,
"trackedFiles": 3,
"resolvedFiles": 3,
"unresolvedBlocks": 0
},
{
"archive": "Data/ruRU/patch-ruRU-A.mpq",
"archiveBytes": 1451338841,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-A.dvc",
"dvcMd5": "97232ae859eaa1a16b137efd1a2e9122.dir",
"extractedBytes": 2748988973,
"trackedFiles": 8817,
"resolvedFiles": 5649,
"unresolvedBlocks": 3167
},
{
"archive": "Data/ruRU/patch-ruRU-B.mpq",
"archiveBytes": 384938550,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-B.dvc",
"dvcMd5": "bb686aebf7c9cae2c02433abde9a9f19.dir",
"extractedBytes": 771051083,
"trackedFiles": 2911,
"resolvedFiles": 1679,
"unresolvedBlocks": 1231
},
{
"archive": "Data/ruRU/patch-ruRU-E.mpq",
"archiveBytes": 1862937450,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-E.dvc",
"dvcMd5": "d6b2fe0e3f23c47dc944ca4a8f82d97a.dir",
"extractedBytes": 9275755440,
"trackedFiles": 21977,
"resolvedFiles": 21977,
"unresolvedBlocks": 0
},
{
"archive": "Data/ruRU/patch-ruRU-H.MPQ",
"archiveBytes": 2154531136,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-H.dvc",
"dvcMd5": "5e95536d2c6f6ff792f05b800105bedc.dir",
"extractedBytes": 3727395837,
"trackedFiles": 40296,
"resolvedFiles": 40296,
"unresolvedBlocks": 0
},
{
"archive": "Data/ruRU/patch-ruRU-I.mpq",
"archiveBytes": 14891516,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-I.dvc",
"dvcMd5": "5db07768b0814c970d84a99b6072fd9f.dir",
"extractedBytes": 31453961,
"trackedFiles": 186,
"resolvedFiles": 186,
"unresolvedBlocks": 0
},
{
"archive": "Data/ruRU/patch-ruRU-M.MPQ",
"archiveBytes": 48772900,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-M.dvc",
"dvcMd5": "e927ae98c9971f378a82feb3299fdcb8.dir",
"extractedBytes": 69521651,
"trackedFiles": 1552,
"resolvedFiles": 1552,
"unresolvedBlocks": 0
},
{
"archive": "Data/ruRU/patch-ruRU-S.mpq",
"archiveBytes": 80492633,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-S.dvc",
"dvcMd5": "449383bbe05ebebb6bad2c37da7793c4.dir",
"extractedBytes": 142167464,
"trackedFiles": 1751,
"resolvedFiles": 1432,
"unresolvedBlocks": 318
},
{
"archive": "Data/ruRU/patch-ruRU-T.mpq",
"archiveBytes": 418595462,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-T.dvc",
"dvcMd5": "fc19500b5ce0fd312a415a3118afd58d.dir",
"extractedBytes": 656858260,
"trackedFiles": 1810,
"resolvedFiles": 1731,
"unresolvedBlocks": 78
},
{
"archive": "Data/ruRU/patch-ruRU-U.mpq",
"archiveBytes": 233678341,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-U.dvc",
"dvcMd5": "783909a6c2ebed5d4f43516fe1ea68bb.dir",
"extractedBytes": 460642379,
"trackedFiles": 1837,
"resolvedFiles": 1372,
"unresolvedBlocks": 464
},
{
"archive": "Data/ruRU/patch-ruRU-W.mpq",
"archiveBytes": 29433979,
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-W.dvc",
"dvcMd5": "e2a1448eb0e443797acd577fc4b67249.dir",
"extractedBytes": 44597910,
"trackedFiles": 484,
"resolvedFiles": 381,
"unresolvedBlocks": 102
},
{
"archive": "Data/ruRU/patch-ruRU-X.MPQ",
"archiveBytes": 2673854694,
"archiveSha256": "CD8CED6FA6C863D509DAE458E6DD44C3986B8B57731B6DC6192FE94125F8C1FD",
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-X.dvc",
"dvcMd5": "3d322d290959d1ead612f3b76860a1ea.dir",
"extractedBytes": 3984134962,
"trackedFiles": 29495,
"resolvedFiles": 29495,
"unresolvedBlocks": 0
},
{
"archive": "Data/ruRU/patch-ruRU-Y.MPQ",
"archiveBytes": 3001665276,
"archiveSha256": "534D496C1A1EE023B910ABC80B727BA88BB09CD2F5767100FC18EE41F4306B90",
"dvcPointer": "assets/graphics/Data/ruRU/patch-ruRU-Y.dvc",
"dvcMd5": "42f3a8ac35674e33c0a4420c84cadcb8.dir",
"extractedBytes": 11053212781,
"trackedFiles": 36191,
"resolvedFiles": 36191,
"unresolvedBlocks": 0
}
]
}
+53 -21
View File
@@ -75,8 +75,53 @@ function Enable-LargeAddressAware {
}
}
function Initialize-MissingSubmodules {
param(
[Parameter(Mandatory)]
[string]$RepositoryPath
)
$modulesFile = Join-Path $RepositoryPath '.gitmodules'
if (-not (Test-Path -LiteralPath $modulesFile -PathType Leaf)) {
return
}
$configuredModules = @(
& git -C $RepositoryPath config --file .gitmodules --get-regexp '^submodule\..*\.path$'
)
if ($LASTEXITCODE -gt 1) {
throw "Failed to read submodules from $modulesFile"
}
foreach ($configuredModule in $configuredModules) {
$fields = $configuredModule -split '\s+', 2
if ($fields.Count -ne 2) {
continue
}
$relativePath = $fields[1].Trim()
$modulePath = Join-Path $RepositoryPath $relativePath
$gitMarker = Join-Path $modulePath '.git'
# Updating an initialized submodule checks out the SHA recorded by its parent and detaches
# any active development branch. Only initialize genuinely missing worktrees.
if (-not (Test-Path -LiteralPath $gitMarker)) {
Write-Host "Initializing missing submodule: $modulePath"
& git -C $RepositoryPath submodule update --init -- $relativePath
if ($LASTEXITCODE -ne 0) {
throw "Failed to initialize submodule: $modulePath"
}
}
if (Test-Path -LiteralPath $modulePath -PathType Container) {
Initialize-MissingSubmodules -RepositoryPath $modulePath
}
}
}
$ErrorActionPreference = 'Stop'
$repoRoot = $PSScriptRoot
. (Join-Path $repoRoot 'pipeline-layout.ps1')
$cmake = 'C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe'
if (-not (Test-Path -LiteralPath $cmake)) {
$cmakeCommand = Get-Command cmake -ErrorAction SilentlyContinue
@@ -84,8 +129,7 @@ if (-not (Test-Path -LiteralPath $cmake)) {
$cmake = $cmakeCommand.Source
}
& git -C $repoRoot submodule update --init --recursive
if ($LASTEXITCODE -ne 0) { throw 'Failed to initialize WarcraftXL submodules.' }
Initialize-MissingSubmodules -RepositoryPath $repoRoot
$win32BuildDir = Join-Path $repoRoot 'build\warcraftxl-win32'
$stockExe = Join-Path $repoRoot 'Wow_Original.exe'
@@ -110,19 +154,7 @@ $win32ArtifactDir = Join-Path $win32BuildDir "vendor\warcraftxl\$Configuration"
$warcraftXL = Join-Path $win32ArtifactDir 'WarcraftXL.dll'
$selectedProxy = Join-Path $win32ArtifactDir 'd3d9.dll'
$recoveryProxy = Join-Path $win32BuildDir "artifacts\$Configuration\d3d9-native.dll"
$extensionNames = @(
'MoonWell',
'MoonwellCustomization',
'wxl-db2',
'wxl-fdid-moonwell',
'wxl-grasswind',
'wxl-modern-adt',
'wxl-modern-blp',
'wxl-modern-m2',
'wxl-modern-wmo',
'wxl-moonwell-storage-fallback',
'wxl-unit-outline'
)
$extensionNames = Get-MoonWellExtensionNames
if ($NativeRenderer) {
Write-Warning '-NativeRenderer is no longer needed: WarcraftXL 1.1 uses native D3D9 by default.'
@@ -134,6 +166,8 @@ function Install-WarcraftXLArtifacts {
[string]$Destination
)
Remove-MoonWellRuntimeGarbage -Destination $Destination
$utils = Join-Path $Destination 'Utils'
New-Item `
-ItemType Directory `
@@ -141,12 +175,6 @@ function Install-WarcraftXLArtifacts {
-Force |
Out-Null
$legacyHost = Join-Path $utils 'WarcraftXLHost.exe'
if (Test-Path -LiteralPath $legacyHost -PathType Leaf) {
Remove-Item -LiteralPath $legacyHost -Force
Write-Host "Removed obsolete WarcraftXL 1.0 host: $legacyHost"
}
$destinationExe = Join-Path $Destination 'Wow.exe'
Copy-Item `
@@ -209,6 +237,10 @@ if ($Deploy) {
if (-not [string]::IsNullOrWhiteSpace($PackagePath)) {
$PackagePath = [System.IO.Path]::GetFullPath($PackagePath)
Assert-SafePackagePath `
-PackagePath $PackagePath `
-RepositoryPath $repoRoot `
-ClientPath $ClientPath
Install-WarcraftXLArtifacts -Destination $PackagePath
Write-Host "Packaged stock Wow.exe and WarcraftXL artifacts in $PackagePath"
}
+4
View File
@@ -9,6 +9,8 @@ import sys
from pathlib import Path
from typing import Optional
from patch_layout import PATCH_LAYOUT
IGNORED_TOP_LEVEL_DIRS = {
"Cache",
@@ -49,6 +51,8 @@ def is_ignored(rel_path: Path) -> bool:
return True
if len(rel_path.parts) == 1 and rel_path.name in IGNORED_TOP_LEVEL_FILES:
return True
if PATCH_LAYOUT.is_external_graphics_patch(rel_path.as_posix()):
return True
return any(part in IGNORED_DIRS_ANYWHERE for part in rel_path.parts[:-1])
+56
View File
@@ -0,0 +1,56 @@
param(
[string]$EnvFile = (Join-Path $PSScriptRoot '.env'),
[string]$Profile
)
$ErrorActionPreference = 'Stop'
function Get-EnvValue([string]$Path, [string]$Name) {
if (-not (Test-Path -LiteralPath $Path)) {
return $null
}
$line = Get-Content -LiteralPath $Path |
Where-Object { $_ -match "^$([regex]::Escape($Name))=" } |
Select-Object -First 1
if ($line) {
return $line.Substring($Name.Length + 1).Trim()
}
return $null
}
function Invoke-Dvc([string[]]$Arguments) {
& py -m dvc @Arguments
if ($LASTEXITCODE -ne 0) {
throw "DVC command failed: dvc $($Arguments -join ' ')"
}
}
if (-not (Test-Path -LiteralPath (Join-Path $PSScriptRoot '.dvc\config'))) {
throw 'DVC is not initialized in this repository.'
}
& py -c 'import dvc, dvc_s3' *> $null
if ($LASTEXITCODE -ne 0) {
throw 'DVC with S3 support is not installed. Run: py -m pip install -r requirements-dvc.txt'
}
if ($Profile) {
Invoke-Dvc @('remote', 'modify', '--local', 'customization', 'profile', $Profile)
} else {
$accessKey = Get-EnvValue $EnvFile 'AWS_ACCESS_KEY_ID'
$secretKey = Get-EnvValue $EnvFile 'AWS_SECRET_ACCESS_KEY'
$sessionToken = Get-EnvValue $EnvFile 'AWS_SESSION_TOKEN'
if (-not $accessKey -or -not $secretKey) {
throw "AWS credentials are missing in $EnvFile. Pass -Profile or fill AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY."
}
Invoke-Dvc @('remote', 'modify', '--local', 'customization', 'access_key_id', $accessKey)
Invoke-Dvc @('remote', 'modify', '--local', 'customization', 'secret_access_key', $secretKey)
if ($sessionToken) {
Invoke-Dvc @('remote', 'modify', '--local', 'customization', 'session_token', $sessionToken)
}
}
Write-Host 'Local DVC credentials configured. They are stored in ignored .dvc/config.local.'
+31 -6
View File
@@ -13,6 +13,7 @@ param(
$ErrorActionPreference = 'Stop'
$repoRoot = $PSScriptRoot
. (Join-Path $repoRoot 'pipeline-layout.ps1')
function Import-ProjectEnvironment {
$envFile = Join-Path $repoRoot '.env'
@@ -46,6 +47,10 @@ $PackagePath = [System.IO.Path]::GetFullPath($PackagePath)
if (-not (Test-Path -LiteralPath $ClientPath -PathType Container)) {
throw "Client directory was not found: $ClientPath"
}
Assert-SafePackagePath `
-PackagePath $PackagePath `
-RepositoryPath $repoRoot `
-ClientPath $ClientPath
$runningClients = @(Get-Process Wow -ErrorAction SilentlyContinue | Where-Object {
$_.Path -and $_.Path.StartsWith($ClientPath, [System.StringComparison]::OrdinalIgnoreCase)
@@ -64,11 +69,21 @@ $env:WOW_HOME = $ClientPath
Write-Host "MoonWell client: $ClientPath"
Write-Host "Package staging: $PackagePath"
Write-Host '[1/5] Initializing WarcraftXL dependencies...'
& git -C $repoRoot submodule update --init --recursive
if ($LASTEXITCODE -ne 0) { throw 'Git submodule initialization failed.' }
Write-Host '[1/5] Preserving initialized WarcraftXL worktrees...'
New-Item -ItemType Directory -Path $PackagePath -Force | Out-Null
$previousPackageFiles = @(
Get-RelativeFilePaths -Root $PackagePath
)
if (-not $SkipDataBuild) {
Write-Host 'Resetting package staging to prevent stale build artifacts...'
Reset-MoonWellPackageStaging `
-PackagePath $PackagePath `
-RepositoryPath $repoRoot `
-ClientPath $ClientPath
} else {
New-Item -ItemType Directory -Path $PackagePath -Force | Out-Null
Remove-MoonWellRuntimeGarbage -Destination $PackagePath
}
if (-not $SkipDataBuild) {
Write-Host '[2/5] Building MPQ patches...'
@@ -99,6 +114,18 @@ if ($NativeRenderer) { $buildArguments.NativeRenderer = $true }
if ($LASTEXITCODE -ne 0) { throw 'WarcraftXL deployment failed.' }
Write-Host '[4/5] Synchronizing package files...'
$python = Get-Command python -ErrorAction SilentlyContinue
if (-not $python) { throw 'Python was not found; package validation cannot run.' }
& $python.Source (Join-Path $repoRoot 'validate_package.py') --dir $PackagePath
if ($LASTEXITCODE -ne 0) { throw 'Package validation failed.' }
$currentPackageFiles = @(Get-RelativeFilePaths -Root $PackagePath)
Remove-StalePackageFilesFromClient `
-ClientPath $ClientPath `
-PreviousFiles $previousPackageFiles `
-CurrentFiles $currentPackageFiles
Remove-MoonWellRuntimeGarbage -Destination $ClientPath
& robocopy $PackagePath $ClientPath /E /R:2 /W:1 /NFL /NDL /NJH /NJS /NP
$robocopyExitCode = $LASTEXITCODE
if ($robocopyExitCode -ge 8) {
@@ -107,8 +134,6 @@ if ($robocopyExitCode -ge 8) {
if (-not $SkipManifest) {
Write-Host '[5/5] Building launcher manifest...'
$python = Get-Command python -ErrorAction SilentlyContinue
if (-not $python) { throw 'Python was not found; launcher manifest was not generated.' }
& $python.Source (Join-Path $repoRoot 'build_manifest.py') `
--dir $PackagePath --output (Join-Path $repoRoot 'manifest.json')
if ($LASTEXITCODE -ne 0) { throw 'Launcher manifest generation failed.' }
-39
View File
@@ -1,39 +0,0 @@
# Asset manifest
## Blood Elf Female
- Retail build: `WOW-68887patch12.0.7_Retail`
- Race ID: `10`
- ChrModelID: `20`
- Character model FileDataID: `1100258`
- Option: Demon Hunter Horns
- Retail OptionID: `126`
- Runtime element type: Geoset in an attached collection M2
- Collection model FileDataID: `7760202`
- Collection compatibility: `RETAIL_WITH_WXL`
- Runtime virtual path: `MoonWell\Customization\BloodElfFemale\7760202_be_f.m2`
- Prototype attachment point: `11` (stock head point). Retail collection point `19` is absent from
the 3.3.5 Blood Elf model and cannot safely be force-attached.
| Prototype choice | Retail ChoiceID | Retail ElementID | GeosetID | Compatibility |
|---|---:|---:|---:|---|
| None | 1850 | — | — | RETAIL_WITH_WXL |
| Betrayer | 1851 | 2051 | 2401 | RETAIL_WITH_WXL |
| Beast | 1852 | 2052 | 2402 | RETAIL_WITH_WXL |
| Dreadlord | 1853 | 2053 | 2403 | RETAIL_WITH_WXL |
The source catalog reports two collection textures:
| FileDataID | Internal path | Type | Purpose |
|---:|---|---|---|
| 1277002 | `item\objectcomponents\collections\bloodelf_female_dh_belt.blp` | BLP | Collection material dependency |
| 2764488 | `item\objectcomponents\collections\bloodelffemale_dh_horns.blp` | BLP | Collection material dependency |
Skin files exported with the model are FileDataID `7766030` (base), `7766031`, `7766032`, and
`7766033` (LODs). The MVP requests the base sibling `7760202_be_f00.skin`.
No fallback asset is committed or silently substituted. Classification is `RETAIL_WITH_WXL`, not
`RETAIL_NATIVE`: stock 3.3.5 cannot parse this modern collection without the WarcraftXL modern-M2
extension. If it fails in a real client session, the documented next fallback is a small WotLK M2
mounted at the same virtual path; such a placeholder would be classified `WOTLK_FALLBACK` and must be
recorded here before use.
-12
View File
@@ -1,12 +0,0 @@
# Glue integration follow-up
The runtime prototype intentionally does not alter character creation. WarcraftXL v1.1 exposes typed
Glue/Lua bindings in `game/Glue.hpp` and `game/Script.hpp`, while the existing MoonWell extension shows
the validated `Lua.RegisterFunction` / `Lua.ValidateFunctionPointer` bridge used by build 12340.
A safe follow-up is to register
`ModelFrame:SetMoonwellCustomization(optionID, choiceID)` through that existing bridge, resolve the
Glue model's `CharModelObject`, and pass it to the same `CustomizationState` and renderer used here.
Cleanup must follow Glue model destruction rather than `OnWorldLeave`. This should be implemented only
after the runtime collection attachment has passed interactive visual/lifetime testing; no extra client
offset or duplicate renderer is justified for the current vertical slice.
-92
View File
@@ -1,92 +0,0 @@
# MoonwellCustomization vertical slice
## Scope
`MoonwellCustomization.dll` is a runtime-only WarcraftXL 1.1 extension for WoW 3.3.5a build
12340. It changes only an active Blood Elf Female player. State is kept in memory and is deliberately
separate from rendering; there are no server packets, database changes, AzerothCore changes, or new
Wow.exe offsets.
The data flow is:
`CustomizationOption (126) -> CustomizationChoice -> CustomizationElement (Geoset) -> collection M2`
The explicit prototype state is None plus three retail choices. The renderer owns one independent
collection render context at a time. Reapplying the same choice is a no-op; replacing a choice releases
the old context first. The overlay copies the active character's placement and bone palette without
joining the stock attachment readiness chain. `OnWorldLeave` always releases it and drops all borrowed
player pointers.
## Verified WarcraftXL API
The repository pins `vendor/warcraftxl` to `v1.1.220` (`4895cef`) on the `v1.1` branch. Source code,
not README assumptions, establishes the following behavior:
- `WXL_Query`/`WXL_Load` are the extension entry points; the runtime loads DLLs found below
`Extensions/<name>/`.
- `WXL_Api::UiAddPanel` registers an immediate-mode overlay panel. WarcraftXL v1.1 hard-codes `F9`
as its overlay toggle; press it and select **MoonWell Customization**.
- `world::ActivePlayerGuid` and `world::ResolveObject(..., kTypeMaskPlayer)` find the active player;
`unit::Model` returns its body-model/scene-node binding.
- The upstream typed `SceneNode` and `CharModelObject` views provide owner, race, gender, and root
scene node. The extension adds no offsets.
- `m2::GetRenderCtx` always creates a new scene model; `AttachToScene(..., slot 19, true)` attaches a
collection M2. Core explicitly documents 19 as the collection-M2 attachment point.
- `OnM2SkinFinalize` is the safe pre-finalize window to filter collection geosets. Runtime changes
call `FinalizeSkin` once; a recursion guard prevents its event from re-entering the filter.
- `OnBuildBonePalette` is post-engine and therefore the safe point to copy the parent character bone
palette into the collection model immediately before upload.
- `OnItemSlotChange` and `OnItemSlotClear` schedule a replacement on the next logic tick, after native
equipment work. Native equipment is never overridden.
- `OnWorldLeave` is the cleanup event. Events and UI run on WarcraftXL's main/render paths; no worker
thread calls client model bindings.
## Build
From a Visual Studio 2022 developer environment or PowerShell:
```powershell
.\build-warcraftxl.ps1 -Configuration Release
```
The required artifact is:
`build\warcraftxl-win32\Release\MoonwellCustomization.dll`
The target is Win32. The top-level CMake build compiles the extension together with the existing
WarcraftXL SDK sources; there is no second CMake project.
## Install and run
1. Install the asset files described in `docs/wow-export-assets.md` into a client MPQ.
2. Copy the DLL to
`Extensions\MoonwellCustomization\MoonwellCustomization.dll` under the client directory. The build
script does this automatically when invoked with `-Deploy -ClientPath <client>`.
3. Start the stock build-12340 client through the installed WarcraftXL `d3d9.dll` proxy.
4. Press `F9` to open the WarcraftXL overlay and select **MoonWell Customization**.
5. On Blood Elf Female, press None / Betrayer / Beast / Dreadlord. None must remove the collection;
repeated selections must not stack it. Equip and remove a helmet, then log out and back in.
6. On every other race or gender, the panel reports that the prototype is unsupported and exposes no
choice controls.
Expected log lines are tagged `[MoonwellCustomization]`: `loaded`, `player detected`, race/gender,
apply, model load, attach, detach, unsupported player, and actionable failure text.
## Known limits
- The repository intentionally excludes Blizzard assets. Without the collection M2 and sibling skin,
the client loader can fall back to its placeholder model; that is an asset-install failure, not a
successful visual test.
- Retail collection model 7760202 is a modern MD21 asset. It requires the existing `wxl-modern-m2`,
`wxl-modern-blp`, `wxl-db2`, and FDID extensions in this repository.
- Bone copying assumes the retail Blood Elf Female collection uses the same ordered skeleton as its
parent model. The code clamps to the smaller palette, but a retail build changing bone order would
need an explicit bone map.
- `FinalizeSkin` in WXL 1.1 has small internal re-finalize leaks. The implementation therefore performs
it only on an actual choice change/equipment refresh, never per frame.
- This source-level build proves compilation and packaging. A successful visual result and crash-free
logout still require an interactive client session with the external assets installed.
The next minimal step toward a broader retail-like system is to move the static option table to an
external, versioned catalog and add renderers for Texture and independent M2Attachment elements while
keeping the same `optionID -> choiceID` state boundary.
-42
View File
@@ -1,42 +0,0 @@
# Exporting the Blood Elf Female prototype assets
The local wow.export checkout has no documented headless CLI, so this document does not invent one.
Its MoonWell exporter generated the inspected catalog at:
`moonwell-customization/wotlk-races/catalog.json`
The exact source is retail `WOW-68887patch12.0.7_Retail`. Use wow.export's UI to select that product,
then export the WotLK races customization catalog/asset set. From the generated output, take:
| FileDataID | Exported file / internal path | Type | Why |
|---:|---|---|---|
| 7760202 | `assets/collections/7760202/7760202_be_f.m2` | M2 | Blood Elf Female collection containing Demon Hunter horn geosets |
| 7766030 | `assets/collections/7760202/7760202_be_f00.skin` | SKIN | Base geometry/index profile required by the M2 |
| 1277002 | `item/objectcomponents/collections/bloodelf_female_dh_belt.blp` | BLP | Declared collection texture dependency |
| 2764488 | `item/objectcomponents/collections/bloodelffemale_dh_horns.blp` | BLP | Declared collection texture dependency |
Do not add these files to git. Stage them under the ignored `local-assets/` directory, then put them in
a local MPQ with these virtual names:
```text
MoonWell\Customization\BloodElfFemale\7760202_be_f.m2
MoonWell\Customization\BloodElfFemale\7760202_be_f00.skin
item\objectcomponents\collections\bloodelf_female_dh_belt.blp
item\objectcomponents\collections\bloodelffemale_dh_horns.blp
```
Install that MPQ as a high-priority `Data\patch-*.MPQ` beside the existing MoonWell patches. Keep the
three LOD skins (`7766031`–`7766033`) locally for later testing, but the current MVP does not request
them explicitly.
To reproduce the DB result without changing wow.export, run the repository's read-only catalog helper:
```powershell
node tools/find_customization_assets.js `
C:\Users\sindo\wow.export\moonwell-customization\wotlk-races\catalog.json `
"Blood Elf" female Horns
```
It must report OptionID `126`, then ChoiceIDs `1851`, `1852`, `1853`. Their skinned-model elements
map geoset type `24` and IDs `1`, `2`, `3` to skin sections `2401`, `2402`, `2403`. The helper reads
already-exported JSON only; it does not access CASC and is not a runtime dependency.
+388
View File
@@ -0,0 +1,388 @@
[CmdletBinding()]
param(
[string]$ClientPath = '',
[ValidatePattern('^[^\r\n]+$')]
[string]$Realmlist = '127.0.0.1',
[ValidateRange(100, 10000)]
[int]$PollIntervalMilliseconds = 500,
[switch]$NoInitialSync,
[switch]$Launch
)
$ErrorActionPreference = 'Stop'
$repoRoot = [System.IO.Path]::GetFullPath($PSScriptRoot).TrimEnd('\')
function Import-ProjectEnvironment {
$envFile = Join-Path $repoRoot '.env'
if (-not (Test-Path -LiteralPath $envFile -PathType Leaf)) {
return
}
foreach ($line in Get-Content -LiteralPath $envFile -Encoding UTF8) {
if ($line -notmatch '^\s*([^#][^=]+)=(.*)$') {
continue
}
$name = $matches[1].Trim()
$value = $matches[2].Trim().Trim('"').Trim("'")
if ($name -and -not (Test-Path "Env:$name")) {
Set-Item -Path "Env:$name" -Value $value
}
}
}
function Get-InterfaceSourceRoots {
param([Parameter(Mandatory)][string]$RepositoryPath)
$dataRoot = Join-Path $RepositoryPath 'src\Data'
if (-not (Test-Path -LiteralPath $dataRoot -PathType Container)) {
throw "Patch source directory was not found: $dataRoot"
}
$roots = @()
foreach ($dataEntry in Get-ChildItem -LiteralPath $dataRoot -Directory | Sort-Object Name) {
$directInterface = Join-Path $dataEntry.FullName 'Interface'
if (Test-Path -LiteralPath $directInterface -PathType Container) {
$roots += [System.IO.Path]::GetFullPath($directInterface).TrimEnd('\')
}
if ($dataEntry.Name -match '^[a-z]{2}[A-Z]{2}$') {
foreach ($localePatch in Get-ChildItem -LiteralPath $dataEntry.FullName -Directory | Sort-Object Name) {
$localeInterface = Join-Path $localePatch.FullName 'Interface'
if (Test-Path -LiteralPath $localeInterface -PathType Container) {
$roots += [System.IO.Path]::GetFullPath($localeInterface).TrimEnd('\')
}
}
}
}
return @($roots)
}
function Get-EffectiveInterfaceFiles {
param([Parameter(Mandatory)][string[]]$SourceRoots)
# Later patch roots win, matching the order in which locale and higher patch
# layers override earlier archives in the client.
$files = @{}
foreach ($sourceRoot in $SourceRoots) {
$sourcePrefix = $sourceRoot + '\'
foreach ($file in Get-ChildItem -LiteralPath $sourceRoot -Recurse -Force -File) {
$relativePath = $file.FullName.Substring($sourcePrefix.Length)
if ($relativePath.EndsWith('.manifest.json', [System.StringComparison]::OrdinalIgnoreCase)) {
continue
}
$files[$relativePath] = [pscustomobject]@{
RelativePath = $relativePath
SourcePath = $file.FullName
Signature = '{0}:{1}' -f $file.Length, $file.LastWriteTimeUtc.Ticks
}
}
}
return $files
}
function Get-SafeTargetPath {
param([Parameter(Mandatory)][string]$RelativePath)
$targetPath = [System.IO.Path]::GetFullPath((Join-Path $interfaceRoot $RelativePath))
if (-not $targetPath.StartsWith($interfacePrefix, [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Interface path escapes the client Interface directory: $RelativePath"
}
return $targetPath
}
function Add-CreatedDirectory {
param([Parameter(Mandatory)][string]$DirectoryPath)
if (Test-Path -LiteralPath $DirectoryPath -PathType Container) {
return
}
$missing = @()
$candidate = $DirectoryPath
while ($candidate.StartsWith($interfacePrefix, [System.StringComparison]::OrdinalIgnoreCase) -and
-not (Test-Path -LiteralPath $candidate -PathType Container)) {
$missing += $candidate
$candidate = Split-Path -Parent $candidate
}
New-Item -ItemType Directory -Path $DirectoryPath -Force | Out-Null
foreach ($created in $missing) {
$createdDirectories[$created] = $true
}
}
function Install-HotReloadFile {
param(
[Parameter(Mandatory)][string]$RelativePath,
[Parameter(Mandatory)][string]$SourcePath,
[switch]$Quiet
)
$targetPath = Get-SafeTargetPath -RelativePath $RelativePath
if (-not $ownedTargets.ContainsKey($RelativePath)) {
$hadOriginal = Test-Path -LiteralPath $targetPath -PathType Leaf
$backupPath = $null
if ($hadOriginal) {
$backupPath = Join-Path $backupRoot $RelativePath
Add-CreatedDirectory -DirectoryPath (Split-Path -Parent $backupPath)
Copy-Item -LiteralPath $targetPath -Destination $backupPath -Force
}
$ownedTargets[$RelativePath] = [pscustomobject]@{
RelativePath = $RelativePath
TargetPath = $targetPath
HadOriginal = $hadOriginal
BackupPath = $backupPath
}
}
Add-CreatedDirectory -DirectoryPath (Split-Path -Parent $targetPath)
Copy-Item -LiteralPath $SourcePath -Destination $targetPath -Force
if (-not $Quiet) {
Write-Host "Updated: Interface\$RelativePath" -ForegroundColor Green
}
}
function Restore-HotReloadTarget {
param(
[Parameter(Mandatory)]$State,
[switch]$Quiet
)
if ($State.HadOriginal) {
Add-CreatedDirectory -DirectoryPath (Split-Path -Parent $State.TargetPath)
Copy-Item -LiteralPath $State.BackupPath -Destination $State.TargetPath -Force
if (-not $Quiet) {
Write-Host "Restored: Interface\$($State.RelativePath)"
}
} elseif (Test-Path -LiteralPath $State.TargetPath -PathType Leaf) {
Remove-Item -LiteralPath $State.TargetPath -Force
if (-not $Quiet) {
Write-Host "Removed: Interface\$($State.RelativePath)"
}
}
}
Import-ProjectEnvironment
if ([string]::IsNullOrWhiteSpace($ClientPath)) {
$ClientPath = $env:WOW_HOME
}
if ([string]::IsNullOrWhiteSpace($ClientPath)) {
throw 'ClientPath was not supplied and WOW_HOME is not set.'
}
$clientRoot = [System.IO.Path]::GetFullPath($ClientPath).TrimEnd('\')
$clientPrefix = $clientRoot + '\'
$wowExecutable = Join-Path $clientRoot 'Wow.exe'
if (-not (Test-Path -LiteralPath $wowExecutable -PathType Leaf)) {
throw "Wow.exe was not found in the client directory: $clientRoot"
}
if ($clientRoot.Equals($repoRoot, [System.StringComparison]::OrdinalIgnoreCase) -or
$repoRoot.StartsWith($clientRoot + '\', [System.StringComparison]::OrdinalIgnoreCase)) {
throw 'The client directory must be separate from the repository.'
}
$sourceRoots = @(Get-InterfaceSourceRoots -RepositoryPath $repoRoot)
if (-not $sourceRoots.Count) {
throw 'No src\Data\...\Interface patch directories were found.'
}
$interfaceRoot = Join-Path $clientRoot 'Interface'
$interfaceRoot = [System.IO.Path]::GetFullPath($interfaceRoot).TrimEnd('\')
$interfacePrefix = $interfaceRoot + '\'
$systemTempRoot = [System.IO.Path]::GetFullPath([System.IO.Path]::GetTempPath()).TrimEnd('\')
$systemTempPrefix = $systemTempRoot + '\'
$backupRoot = [System.IO.Path]::GetFullPath((
Join-Path $systemTempRoot ('MoonWell-hotreload-' + [Guid]::NewGuid().ToString('N'))
))
if (-not $backupRoot.StartsWith($systemTempPrefix, [System.StringComparison]::OrdinalIgnoreCase) -or
-not ([System.IO.Path]::GetFileName($backupRoot)).StartsWith(
'MoonWell-hotreload-',
[System.StringComparison]::OrdinalIgnoreCase
)) {
throw "Unsafe hot reload backup path: $backupRoot"
}
$ownedTargets = @{}
$createdDirectories = @{}
$createdRealmlistDirectories = @()
$realmlistState = $null
$cleanupFailed = $false
$launchedProcess = $null
New-Item -ItemType Directory -Path $interfaceRoot, $backupRoot -Force | Out-Null
Write-Host 'MoonWell Interface hot reload'
Write-Host " Client: $clientRoot"
Write-Host " Sources: $($sourceRoots.Count) patch directories"
try {
$realmlistPath = [System.IO.Path]::GetFullPath((
Join-Path $clientRoot 'Data\ruRU\realmlist.wtf'
))
if (-not $realmlistPath.StartsWith(
$clientPrefix,
[System.StringComparison]::OrdinalIgnoreCase
)) {
throw "Realmlist path escapes the client directory: $realmlistPath"
}
$realmlistDirectory = Split-Path -Parent $realmlistPath
$candidateDirectory = $realmlistDirectory
while ($candidateDirectory.StartsWith(
$clientPrefix,
[System.StringComparison]::OrdinalIgnoreCase
) -and
-not (Test-Path -LiteralPath $candidateDirectory -PathType Container)) {
$createdRealmlistDirectories += $candidateDirectory
$candidateDirectory = Split-Path -Parent $candidateDirectory
}
New-Item -ItemType Directory -Path $realmlistDirectory -Force | Out-Null
$hadOriginalRealmlist = Test-Path -LiteralPath $realmlistPath -PathType Leaf
$realmlistBackupPath = $null
if ($hadOriginalRealmlist) {
$realmlistBackupPath = Join-Path $backupRoot 'realmlist.wtf.original'
Copy-Item -LiteralPath $realmlistPath -Destination $realmlistBackupPath -Force
}
$realmlistState = [pscustomobject]@{
Path = $realmlistPath
HadOriginal = $hadOriginalRealmlist
BackupPath = $realmlistBackupPath
}
Set-Content -LiteralPath $realmlistPath -Value "set realmlist $Realmlist" -Encoding ASCII
Write-Host " Realmlist: $Realmlist"
$previousFiles = Get-EffectiveInterfaceFiles -SourceRoots $sourceRoots
if (-not $NoInitialSync) {
Write-Host "Installing $($previousFiles.Count) loose Interface files..."
foreach ($entry in $previousFiles.GetEnumerator()) {
Install-HotReloadFile `
-RelativePath $entry.Value.RelativePath `
-SourcePath $entry.Value.SourcePath `
-Quiet
}
Write-Host 'Initial Interface overlay is ready.' -ForegroundColor Green
} else {
Write-Host 'Initial sync skipped; only subsequent changes will be overlaid.'
}
if ($Launch) {
Write-Host 'Launching Wow.exe...'
$launchedProcess = Start-Process `
-FilePath $wowExecutable `
-WorkingDirectory $clientRoot `
-PassThru
Write-Host 'Watching until the launched client exits. Press Ctrl+C to stop earlier.'
} else {
Write-Host 'Watching for changes. Press Ctrl+C to stop and clean the client.'
}
while ($true) {
Start-Sleep -Milliseconds $PollIntervalMilliseconds
if ($launchedProcess) {
$launchedProcess.Refresh()
if ($launchedProcess.HasExited) {
Write-Host 'The launched client has exited.'
break
}
}
$currentFiles = Get-EffectiveInterfaceFiles -SourceRoots $sourceRoots
foreach ($entry in $currentFiles.GetEnumerator()) {
$relativePath = $entry.Key
$previous = $previousFiles[$relativePath]
if ($null -eq $previous -or $previous.Signature -ne $entry.Value.Signature -or
$previous.SourcePath -ne $entry.Value.SourcePath) {
Install-HotReloadFile `
-RelativePath $entry.Value.RelativePath `
-SourcePath $entry.Value.SourcePath
}
}
foreach ($entry in $previousFiles.GetEnumerator()) {
if (-not $currentFiles.ContainsKey($entry.Key) -and $ownedTargets.ContainsKey($entry.Key)) {
Restore-HotReloadTarget -State $ownedTargets[$entry.Key]
}
}
$previousFiles = $currentFiles
}
} finally {
Write-Host "Cleaning $($ownedTargets.Count) hot reload files from the client..."
foreach ($state in $ownedTargets.Values) {
try {
Restore-HotReloadTarget -State $state -Quiet
} catch {
$cleanupFailed = $true
Write-Warning "Could not clean Interface\$($state.RelativePath): $($_.Exception.Message)"
}
}
if ($null -ne $realmlistState) {
try {
if ($realmlistState.HadOriginal) {
Copy-Item `
-LiteralPath $realmlistState.BackupPath `
-Destination $realmlistState.Path `
-Force
} elseif (Test-Path -LiteralPath $realmlistState.Path -PathType Leaf) {
Remove-Item -LiteralPath $realmlistState.Path -Force
}
} catch {
$cleanupFailed = $true
Write-Warning "Could not restore realmlist.wtf: $($_.Exception.Message)"
}
}
foreach ($directoryPath in @($createdRealmlistDirectories | Sort-Object Length -Descending)) {
try {
if ((Test-Path -LiteralPath $directoryPath -PathType Container) -and
-not @(Get-ChildItem -LiteralPath $directoryPath -Force).Count) {
Remove-Item -LiteralPath $directoryPath -Force
}
} catch {
$cleanupFailed = $true
Write-Warning "Could not remove empty directory $directoryPath"
}
}
foreach ($directoryPath in @($createdDirectories.Keys | Sort-Object Length -Descending)) {
try {
if ((Test-Path -LiteralPath $directoryPath -PathType Container) -and
-not @(Get-ChildItem -LiteralPath $directoryPath -Force).Count) {
Remove-Item -LiteralPath $directoryPath -Force
}
} catch {
$cleanupFailed = $true
Write-Warning "Could not remove empty directory $directoryPath"
}
}
if ($cleanupFailed) {
Write-Warning "Cleanup was incomplete. Original-file backups were kept in: $backupRoot"
} else {
if (Test-Path -LiteralPath $backupRoot) {
$resolvedBackupRoot = (Resolve-Path -LiteralPath $backupRoot).Path
if (-not $resolvedBackupRoot.Equals(
$backupRoot,
[System.StringComparison]::OrdinalIgnoreCase
) -or
-not $resolvedBackupRoot.StartsWith(
$systemTempPrefix,
[System.StringComparison]::OrdinalIgnoreCase
)) {
throw "Refusing to remove unexpected backup path: $resolvedBackupRoot"
}
Remove-Item -LiteralPath $resolvedBackupRoot -Recurse -Force
}
Write-Host 'Hot reload overlay removed; original client files restored.' -ForegroundColor Green
}
}
@@ -1,70 +0,0 @@
#pragma once
#include <array>
#include <cstdint>
namespace moonwell::customization
{
enum class ElementType : uint8_t
{
None,
M2Attachment,
Geoset,
Texture,
};
struct CustomizationElement
{
ElementType type;
uint32_t geosetId;
const char* modelPath;
};
struct CustomizationChoice
{
uint32_t id;
const char* name;
std::array<CustomizationElement, 1> elements;
};
struct CustomizationOption
{
uint32_t id;
const char* name;
std::array<CustomizationChoice, 4> choices;
};
inline constexpr uint32_t kBloodElfRace = 10;
inline constexpr uint32_t kFemaleGender = 1;
inline constexpr uint32_t kCollectionFileDataId = 7760202;
// Stock 3.3.5 Blood Elf models have no retail collection point 19.
// Use the native head attachment point; forcing absent point 19 makes
// the parent's drawable gate fail and hides the whole character.
inline constexpr uint32_t kCollectionAttachmentSlot = 11;
inline constexpr char kCollectionPath[] =
"MoonWell\\Customization\\BloodElfFemale\\7760202_be_f.m2";
// WOTLK_FALLBACK: native 3.3.5 head components for Blood Elf Female.
// The retail collection needs a real bone map to the differently ordered
// 3.3.5 skeleton, so the working vertical slice uses native components.
inline constexpr CustomizationOption kHornsOption = {
126,
"Head Decorations (WotLK fallback)",
{{
{1850, "None", {{{ElementType::None, 0, nullptr}}}},
{1851, "Blindfold", {{{ElementType::M2Attachment, 0,
"ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Blindfold_A_01_BeF.m2"}}}},
{1852, "Circlet I", {{{ElementType::M2Attachment, 0,
"ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Circlet_A_01_BeF.m2"}}}},
{1853, "Circlet II", {{{ElementType::M2Attachment, 0,
"ITEM\\OBJECTCOMPONENTS\\HEAD\\Helm_Circlet_B_01_BeF.m2"}}}},
}},
};
inline const CustomizationChoice* FindChoice(uint32_t id)
{
for (const auto& choice : kHornsOption.choices)
if (choice.id == id) return &choice;
return nullptr;
}
}
@@ -1,436 +0,0 @@
#include "CustomizationRenderer.hpp"
#include <wxl/PluginApi.h>
#include "engine/events/Event.hpp"
#include "game/M2.hpp"
#include "game/World.hpp"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <limits>
#include <windows.h>
namespace moonwell::customization
{
namespace m2 = wxl::game::m2;
namespace world = wxl::game::world;
namespace sm2 = wxl::structure::m2;
namespace
{
bool IsReadableRange(const void* address, size_t size)
{
if (!address || !size) return false;
const uintptr_t begin = reinterpret_cast<uintptr_t>(address);
if (size > std::numeric_limits<uintptr_t>::max() - begin) return false;
const uintptr_t end = begin + size;
uintptr_t cursor = begin;
while (cursor < end)
{
MEMORY_BASIC_INFORMATION memory{};
if (!VirtualQuery(reinterpret_cast<const void*>(cursor), &memory, sizeof memory))
return false;
if (memory.State != MEM_COMMIT ||
(memory.Protect & (PAGE_NOACCESS | PAGE_GUARD)) != 0)
return false;
const uintptr_t regionEnd = reinterpret_cast<uintptr_t>(memory.BaseAddress) +
memory.RegionSize;
if (regionEnd <= cursor) return false;
cursor = std::min(regionEnd, end);
}
return true;
}
}
void CustomizationRenderer::SetError(const char* message)
{
lastError_ = message;
api_->Log(WXL_LOG_ERROR, "MoonwellCustomization", "failed: %s", message);
}
bool CustomizationRenderer::DetectPlayer()
{
playerDetected_ = false;
supported_ = false;
charModelObject_ = nullptr;
parentRenderContext_ = nullptr;
race_ = gender_ = 0;
const auto guid = world::ActivePlayerGuid();
void* player = guid ? world::ResolveObject(guid, world::kTypeMaskPlayer) : nullptr;
if (!player)
{
lastError_ = "Waiting for active player object";
return false;
}
// The native equipment events are the public WXL seam that supplies
// the actual CharModelObject. Unit::Model is not useful for identity:
// it exposes a different model layer. Match the root instance's world
// transform to the active player's authoritative world position so an
// event for another visible character cannot be adopted accidentally.
auto* cmo = static_cast<m2::off::CharModelObject*>(observedCharModelObject_);
if (!cmo || !cmo->sceneNode)
{
lastError_ = "Waiting for active player CharModelObject event";
return false;
}
auto* root = static_cast<m2::off::M2Instance*>(cmo->sceneNode);
float playerPosition[3]{};
world::UnitPosition(player, playerPosition);
const float dxRow = root->placement[12] - playerPosition[0];
const float dyRow = root->placement[13] - playerPosition[1];
const float dzRow = root->placement[14] - playerPosition[2];
const float rowDistanceSq = dxRow * dxRow + dyRow * dyRow + dzRow * dzRow;
const float dxColumn = root->placement[3] - playerPosition[0];
const float dyColumn = root->placement[7] - playerPosition[1];
const float dzColumn = root->placement[11] - playerPosition[2];
const float columnDistanceSq = dxColumn * dxColumn + dyColumn * dyColumn + dzColumn * dzColumn;
if (std::min(rowDistanceSq, columnDistanceSq) > 9.0f)
{
lastError_ = "Waiting for matching active player CharModelObject";
return false;
}
if (cmo->raceId == 0 ||
cmo->raceId > 11 || cmo->genderId > 1)
{
lastError_ = "Active player CharModelObject is not ready";
return false;
}
charModelObject_ = cmo;
parentRenderContext_ = cmo->sceneNode;
race_ = cmo->raceId;
gender_ = cmo->genderId;
playerDetected_ = true;
supported_ = race_ == kBloodElfRace && gender_ == kFemaleGender;
lastError_ = supported_ ? "Ready" : "Prototype supports Blood Elf Female only.";
api_->Log(WXL_LOG_INFO, "MoonwellCustomization", "player detected");
api_->Log(WXL_LOG_INFO, "MoonwellCustomization", "race=%u gender=%u", race_, gender_);
if (!supported_)
api_->Log(WXL_LOG_WARN, "MoonwellCustomization", "unsupported player race");
return true;
}
void CustomizationRenderer::OnWorldEnter()
{
inWorld_ = true;
detectDelay_ = 0.0f;
DetectPlayer();
}
void CustomizationRenderer::OnWorldLeave()
{
inWorld_ = false;
Detach();
observedCharModelObject_ = nullptr;
charModelObject_ = nullptr;
parentRenderContext_ = nullptr;
playerDetected_ = supported_ = false;
race_ = gender_ = 0;
detectDelay_ = 0.0f;
refreshRequested_ = false;
geosetApplied_ = false;
attached_ = false;
finalizeInProgress_ = false;
lastError_ = "Outside world";
}
void CustomizationRenderer::OnUpdate(float dt)
{
// OnWorldEnter is an edge notification and can be missed when the
// extension is loaded after a world transition has already begun.
// Reconcile against the authoritative active-player GUID so the
// renderer also recovers after late loads and unusual glue flows.
const auto activePlayerGuid = world::ActivePlayerGuid();
if (!activePlayerGuid)
{
if (inWorld_) OnWorldLeave();
return;
}
if (!inWorld_)
{
inWorld_ = true;
detectDelay_ = 0.0f;
lastError_ = "Waiting for active player model";
}
if (!playerDetected_)
{
detectDelay_ -= dt;
if (detectDelay_ <= 0.0f)
{
detectDelay_ = 0.25f;
DetectPlayer();
}
return;
}
if (refreshRequested_)
{
refreshRequested_ = false;
const uint32_t choiceId = CurrentChoice();
if (choiceId != 0 && choiceId != kHornsOption.choices[0].id)
{
Detach();
if (const auto* choice = FindChoice(choiceId)) Attach(*choice);
}
}
if (attachmentRenderContext_ && attachmentModel_ && !geosetApplied_)
{
const auto* choice = FindChoice(CurrentChoice());
if (choice && choice->elements[0].type == ElementType::Geoset)
FilterGeoset(attachmentModel_, choice->elements[0].geosetId, true);
}
// CreateSceneModel loads asynchronously. Attaching it before the stock
// readiness gate succeeds makes the parent character non-drawable too.
// Keep it unattached while loading, then join the stock head point only after the
// child itself reports drawable.
if (attachmentRenderContext_ && parentRenderContext_)
{
auto* child = static_cast<m2::off::M2Instance*>(attachmentRenderContext_);
auto* parent = static_cast<m2::off::M2Instance*>(parentRenderContext_);
const auto* choice = FindChoice(CurrentChoice());
const bool collectionGeoset = choice &&
choice->elements[0].type == ElementType::Geoset;
if (collectionGeoset && !attached_)
{
std::memcpy(child->placement, parent->placement, sizeof child->placement);
child->viewDistSq = parent->viewDistSq;
child->alphaBase = parent->alphaBase;
}
if (geosetApplied_ && !attached_)
{
const int drawable = wxl::game::Native<m2::off::M2_IsDrawableFn>(
m2::off::kIsDrawable)(child, nullptr, 0, 0);
if (drawable)
{
m2::AttachToScene(parentRenderContext_, child,
kCollectionAttachmentSlot, false);
if (reinterpret_cast<void*>(static_cast<uintptr_t>(child->parent)) ==
parentRenderContext_)
{
attached_ = true;
lastError_ = "Ready";
api_->Log(WXL_LOG_INFO, "MoonwellCustomization",
"attached ready overlay slot=%u", kCollectionAttachmentSlot);
}
else
{
lastError_ = "Native head attachment was rejected";
}
}
else
{
lastError_ = "Collection loaded; waiting for drawable readiness";
}
}
}
}
void CustomizationRenderer::OnEquipmentChanged(void* charModelObject)
{
if (!playerDetected_ && charModelObject)
{
observedCharModelObject_ = charModelObject;
DetectPlayer();
}
// Item events are emitted around native equipment maintenance. Rebuild on
// the next logic tick so native slot work is complete before slot 19 is touched.
if (charModelObject == charModelObject_)
{
const auto* choice = FindChoice(CurrentChoice());
if (choice && choice->elements[0].type != ElementType::None)
refreshRequested_ = true;
}
}
void CustomizationRenderer::OnSkinFinalize(void* model)
{
if (!model || model != attachmentModel_ || finalizeInProgress_) return;
const auto* choice = FindChoice(CurrentChoice());
if (choice && choice->elements[0].type == ElementType::Geoset)
FilterGeoset(model, choice->elements[0].geosetId, false);
}
void CustomizationRenderer::OnBuildBonePalette(void* renderContext)
{
if (!renderContext || renderContext != attachmentRenderContext_) return;
const auto* choice = FindChoice(CurrentChoice());
if (!choice || choice->elements[0].type != ElementType::Geoset) return;
auto* child = static_cast<m2::off::M2Instance*>(renderContext);
auto* parent = static_cast<m2::off::M2Instance*>(parentRenderContext_);
if (!parent || !child->bonePalettePtr || !parent->bonePalettePtr)
return;
m2::M2Model childModel(reinterpret_cast<void*>(child->model));
m2::M2Model parentModel(reinterpret_cast<void*>(parent->model));
if (!childModel || !parentModel || !childModel.GetHeader() || !parentModel.GetHeader()) return;
const uint32_t count = std::min(childModel.GetHeader()->bones.count,
parentModel.GetHeader()->bones.count);
if (count)
std::memcpy(reinterpret_cast<void*>(child->bonePalettePtr),
reinterpret_cast<const void*>(parent->bonePalettePtr),
static_cast<size_t>(count) * m2::off::kBonePaletteStride);
}
bool CustomizationRenderer::FilterGeoset(void* rawModel, uint32_t geosetId, bool finalize)
{
m2::M2Model model(rawModel);
auto* skin = model ? model.GetSkin() : nullptr;
if (!IsReadableRange(skin, sizeof *skin) || !skin->indices ||
!skin->submeshes || !skin->indexCount || !skin->submeshCount)
return false;
// A newly created async scene model can expose the skin object before
// its offset-valued arrays have been relocated to pointers. Do not
// touch those arrays until both complete ranges are readable.
constexpr uint32_t kMaxIndexCount = 10u * 1024u * 1024u;
constexpr uint32_t kMaxSubmeshCount = 100u * 1024u;
if (skin->indexCount > kMaxIndexCount || skin->submeshCount > kMaxSubmeshCount ||
!IsReadableRange(skin->indices,
static_cast<size_t>(skin->indexCount) * sizeof(uint16_t)) ||
!IsReadableRange(skin->submeshes,
static_cast<size_t>(skin->submeshCount) * sizeof(sm2::M2SkinSection)))
return false;
bool found = false;
for (uint32_t i = 0; i < skin->submeshCount; ++i)
{
const sm2::M2SkinSection& section = skin->submeshes[i];
const uint32_t start = (uint32_t(section.level) << 16) | section.indexStart;
const uint32_t count = section.indexCount;
if (start > skin->indexCount || count > skin->indexCount - start) continue;
if (section.skinSectionId == geosetId)
{
found = true;
continue;
}
std::fill_n(skin->indices + start, count, uint16_t(0));
}
if (!found)
{
SetError("requested customization geoset is absent from collection skin");
return false;
}
if (finalize)
{
finalizeInProgress_ = true;
model.FinalizeSkin();
finalizeInProgress_ = false;
}
attachmentModel_ = rawModel;
geosetApplied_ = true;
return true;
}
bool CustomizationRenderer::Attach(const CustomizationChoice& choice)
{
if (!supported_ || !charModelObject_ || !parentRenderContext_)
{
SetError("supported player model is unavailable");
return false;
}
const auto& element = choice.elements[0];
if (!element.modelPath)
{
SetError("customization model path is absent");
return false;
}
api_->Log(WXL_LOG_INFO, "MoonwellCustomization", "loading model %s", element.modelPath);
auto* parent = static_cast<m2::off::M2Instance*>(parentRenderContext_);
void* scene = reinterpret_cast<void*>(static_cast<uintptr_t>(parent->scene));
if (!scene)
{
SetError("active player scene is unavailable");
return false;
}
// CreateSceneModel's native receiver is the owning scene, not the
// CharModelObject. Passing the CMO makes the loader interpret cmo+4
// as the scene's model table and faults inside 0x0081C4F0.
void* child = m2::GetRenderCtx(scene, const_cast<char*>(element.modelPath));
if (!child)
{
SetError("CreateSceneModel returned null");
return false;
}
attachmentRenderContext_ = child;
auto* instance = static_cast<m2::off::M2Instance*>(child);
attachmentModel_ = reinterpret_cast<void*>(instance->model);
geosetApplied_ = element.type != ElementType::Geoset;
attached_ = false;
// Native WotLK head components must retain their own local transform;
// AttachToScene composes it with the parent's head point. Collection
// geosets use a full-character coordinate system and are seeded below.
if (element.type == ElementType::Geoset)
{
auto* parentInstance = static_cast<m2::off::M2Instance*>(parentRenderContext_);
std::memcpy(instance->placement, parentInstance->placement, sizeof instance->placement);
instance->viewDistSq = parentInstance->viewDistSq;
instance->alphaBase = parentInstance->alphaBase;
}
api_->Log(WXL_LOG_INFO, "MoonwellCustomization", "created overlay geoset=%u",
choice.elements[0].geosetId);
lastError_ = "Loading collection model";
return true;
}
void CustomizationRenderer::Detach()
{
if (!attachmentRenderContext_) return;
if (attached_ && parentRenderContext_)
m2::DetachSlot(parentRenderContext_, kCollectionAttachmentSlot);
else
m2::ReleaseRenderCtx(attachmentRenderContext_);
attachmentRenderContext_ = nullptr;
attachmentModel_ = nullptr;
geosetApplied_ = false;
attached_ = false;
finalizeInProgress_ = false;
api_->Log(WXL_LOG_INFO, "MoonwellCustomization", "detached");
}
bool CustomizationRenderer::Apply(uint32_t optionId, uint32_t choiceId)
{
const auto* choice = FindChoice(choiceId);
if (!choice || optionId != kHornsOption.id) return false;
if (!supported_)
{
lastError_ = "Prototype supports Blood Elf Female only.";
return false;
}
const bool isNone = choice->elements[0].type == ElementType::None;
if (CurrentChoice() == choiceId && (isNone || attachmentRenderContext_)) return true;
api_->Log(WXL_LOG_INFO, "MoonwellCustomization", "apply option=%u choice=%u",
optionId, choiceId);
Detach();
state_.SetChoice(optionId, choiceId);
if (isNone) return true;
return Attach(*choice);
}
}
@@ -1,57 +0,0 @@
#pragma once
#include "CustomizationState.hpp"
#include <cstdint>
struct WXL_Api;
namespace moonwell::customization
{
class CustomizationRenderer
{
public:
explicit CustomizationRenderer(const WXL_Api* api) : api_(api) {}
void OnWorldEnter();
void OnWorldLeave();
void OnUpdate(float dt);
void OnEquipmentChanged(void* charModelObject);
void OnSkinFinalize(void* model);
void OnBuildBonePalette(void* renderContext);
bool Apply(uint32_t optionId, uint32_t choiceId);
bool PlayerDetected() const { return playerDetected_; }
bool Supported() const { return supported_; }
uint32_t Race() const { return race_; }
uint32_t Gender() const { return gender_; }
uint32_t CurrentChoice() const { return state_.Choice(kHornsOption.id); }
const char* LastError() const { return lastError_; }
private:
bool DetectPlayer();
bool Attach(const CustomizationChoice& choice);
void Detach();
bool FilterGeoset(void* model, uint32_t geosetId, bool finalize);
void SetError(const char* message);
const WXL_Api* api_ = nullptr;
CustomizationState state_;
void* observedCharModelObject_ = nullptr;
void* charModelObject_ = nullptr;
void* parentRenderContext_ = nullptr;
void* attachmentRenderContext_ = nullptr;
void* attachmentModel_ = nullptr;
uint32_t race_ = 0;
uint32_t gender_ = 0;
float detectDelay_ = 0.0f;
bool inWorld_ = false;
bool playerDetected_ = false;
bool supported_ = false;
bool refreshRequested_ = false;
bool geosetApplied_ = false;
bool attached_ = false;
bool finalizeInProgress_ = false;
const char* lastError_ = "Waiting for player";
};
}
@@ -1,29 +0,0 @@
#pragma once
#include "CustomizationData.hpp"
#include <cstdint>
namespace moonwell::customization
{
class CustomizationState
{
public:
uint32_t Choice(uint32_t optionId) const
{
return optionId == kHornsOption.id ? hornsChoice_ : 0;
}
bool SetChoice(uint32_t optionId, uint32_t choiceId)
{
if (optionId != kHornsOption.id || !FindChoice(choiceId)) return false;
hornsChoice_ = choiceId;
return true;
}
void Clear() { hornsChoice_ = 0; }
private:
uint32_t hornsChoice_ = 0;
};
}
@@ -1,115 +0,0 @@
#include "CustomizationRenderer.hpp"
#include <wxl/PluginApi.h>
#include "engine/events/Event.hpp"
#include <cstdint>
#include <cstdio>
#include <memory>
namespace moonwell::customization
{
namespace ev = wxl::events;
const WXL_Api* g_api = nullptr;
std::unique_ptr<CustomizationRenderer> g_renderer;
void __cdecl OnWorldEnter(void*, const void*) { g_renderer->OnWorldEnter(); }
void __cdecl OnWorldLeave(void*, const void*) { g_renderer->OnWorldLeave(); }
void __cdecl OnUpdate(void*, const void* raw)
{
const auto* args = static_cast<const ev::UpdateArgs*>(raw);
g_renderer->OnUpdate(args ? args->dt : 0.0f);
}
void __cdecl OnItemSlotChange(void*, const void* raw)
{
const auto* args = static_cast<const ev::ItemSlotChangeArgs*>(raw);
if (args) g_renderer->OnEquipmentChanged(args->charModelObj);
}
void __cdecl OnItemSlotClear(void*, const void* raw)
{
const auto* args = static_cast<const ev::ItemSlotClearArgs*>(raw);
if (args) g_renderer->OnEquipmentChanged(args->charModelObj);
}
void __cdecl OnSkinFinalize(void*, const void* raw)
{
const auto* args = static_cast<const ev::M2SkinFinalizeArgs*>(raw);
if (args) g_renderer->OnSkinFinalize(args->model);
}
void __cdecl OnBuildBonePalette(void*, const void* raw)
{
const auto* args = static_cast<const ev::BuildBonePaletteArgs*>(raw);
if (args) g_renderer->OnBuildBonePalette(args->renderCtx);
}
void DrawPanel(void*)
{
char line[128]{};
if (!g_renderer->PlayerDetected())
{
g_api->UiText("Player: detecting...");
g_api->UiText(g_renderer->LastError());
return;
}
std::snprintf(line, sizeof(line), "Race ID: %u%s", g_renderer->Race(),
g_renderer->Race() == kBloodElfRace ? " (Blood Elf)" : "");
g_api->UiText(line);
std::snprintf(line, sizeof(line), "Gender ID: %u%s", g_renderer->Gender(),
g_renderer->Gender() == kFemaleGender ? " (Female)" : "");
g_api->UiText(line);
g_api->UiSeparator();
if (!g_renderer->Supported())
{
g_api->UiText("Prototype supports Blood Elf Female only.");
return;
}
g_api->UiText("Option: Head Decorations (WotLK fallback)");
for (const auto& choice : kHornsOption.choices)
{
std::snprintf(line, sizeof(line), "%s%s", choice.name,
g_renderer->CurrentChoice() == choice.id ? " [selected]" : "");
if (g_api->UiButton(line))
g_renderer->Apply(kHornsOption.id, choice.id);
}
g_api->UiSeparator();
g_api->UiText(g_renderer->LastError());
}
}
const WXL_PluginInfo* __cdecl WXL_Query(void)
{
static const WXL_PluginInfo info = {
sizeof(WXL_PluginInfo), WXL_API_VERSION, "MoonwellCustomization", 1, WXL_CLIENT_BUILD,
};
return &info;
}
int __cdecl WXL_Load(const WXL_Api* api)
{
using namespace moonwell::customization;
if (!api || api->apiVersion != WXL_API_VERSION ||
api->structSize < sizeof(WXL_Api) || !api->Subscribe || !api->UiAddPanel)
return 0;
g_api = api;
g_renderer = std::make_unique<CustomizationRenderer>(api);
api->Subscribe(uint32_t(ev::Event::OnWorldEnter), &OnWorldEnter, nullptr);
api->Subscribe(uint32_t(ev::Event::OnWorldLeave), &OnWorldLeave, nullptr);
api->Subscribe(uint32_t(ev::Event::OnUpdate), &OnUpdate, nullptr);
api->Subscribe(uint32_t(ev::Event::OnItemSlotChange), &OnItemSlotChange, nullptr);
api->Subscribe(uint32_t(ev::Event::OnItemSlotClear), &OnItemSlotClear, nullptr);
api->Subscribe(uint32_t(ev::Event::OnM2SkinFinalize), &OnSkinFinalize, nullptr);
api->Subscribe(uint32_t(ev::Event::OnBuildBonePalette), &OnBuildBonePalette, nullptr);
api->UiAddPanel("MoonWell Customization", &DrawPanel, nullptr);
api->Log(WXL_LOG_INFO, "MoonwellCustomization", "loaded");
return 1;
}
+26
View File
@@ -0,0 +1,26 @@
{
"repositoryPatches": [
"Data/patch-4.MPQ",
"Data/patch-Z.MPQ",
"Data/ruRU/patch-ruRU-4.MPQ",
"Data/ruRU/patch-ruRU-5.MPQ",
"Data/ruRU/patch-ruRU-Z.MPQ"
],
"graphicsPatches": [
"Data/patch-X.MPQ",
"Data/ruRU/backup-ruRU.MPQ",
"Data/ruRU/patch-ruRU-6.MPQ",
"Data/ruRU/patch-ruRU-A.mpq",
"Data/ruRU/patch-ruRU-B.mpq",
"Data/ruRU/patch-ruRU-E.mpq",
"Data/ruRU/patch-ruRU-H.MPQ",
"Data/ruRU/patch-ruRU-I.mpq",
"Data/ruRU/patch-ruRU-M.MPQ",
"Data/ruRU/patch-ruRU-S.mpq",
"Data/ruRU/patch-ruRU-T.mpq",
"Data/ruRU/patch-ruRU-U.mpq",
"Data/ruRU/patch-ruRU-W.mpq",
"Data/ruRU/patch-ruRU-X.MPQ",
"Data/ruRU/patch-ruRU-Y.MPQ"
]
}
+36
View File
@@ -0,0 +1,36 @@
#!/usr/bin/env python3
import json
from dataclasses import dataclass
from pathlib import Path
def normalized_path(path: str) -> str:
return path.replace("\\", "/").casefold()
@dataclass(frozen=True)
class PatchLayout:
repository_patches: frozenset[str]
graphics_patches: frozenset[str]
def is_repository_patch(self, path: str) -> bool:
return normalized_path(path) in self.repository_patches
def is_graphics_patch(self, path: str) -> bool:
return normalized_path(path) in self.graphics_patches
def is_external_graphics_patch(self, path: str) -> bool:
key = normalized_path(path)
return key in self.graphics_patches and key not in self.repository_patches
def load_patch_layout(path: Path | None = None) -> PatchLayout:
config_path = path or Path(__file__).resolve().with_name("patch-layout.json")
data = json.loads(config_path.read_text(encoding="utf-8"))
repository = frozenset(normalized_path(item) for item in data["repositoryPatches"])
graphics = frozenset(normalized_path(item) for item in data["graphicsPatches"])
return PatchLayout(repository_patches=repository, graphics_patches=graphics)
PATCH_LAYOUT = load_patch_layout()
+241
View File
@@ -0,0 +1,241 @@
$script:MoonWellExtensionNames = @(
'MoonWell',
'wxl-db2',
'wxl-fdid-moonwell',
'wxl-grasswind',
'wxl-modern-adt',
'wxl-modern-blp',
'wxl-modern-m2',
'wxl-modern-wmo',
'wxl-moonwell-storage-fallback',
'wxl-unit-outline'
)
$patchLayoutPath = Join-Path $PSScriptRoot 'patch-layout.json'
if (-not (Test-Path -LiteralPath $patchLayoutPath -PathType Leaf)) {
throw "Patch layout was not found: $patchLayoutPath"
}
$patchLayout = Get-Content -LiteralPath $patchLayoutPath -Raw -Encoding UTF8 | ConvertFrom-Json
$script:MoonWellRepositoryPatches = @($patchLayout.repositoryPatches)
$script:MoonWellGraphicsPatches = @($patchLayout.graphicsPatches)
function Get-MoonWellExtensionNames {
return @($script:MoonWellExtensionNames)
}
function Get-MoonWellRepositoryPatchPaths {
return @($script:MoonWellRepositoryPatches)
}
function Get-MoonWellGraphicsPatchPaths {
return @($script:MoonWellGraphicsPatches)
}
function Test-MoonWellRepositoryPatch {
param([Parameter(Mandatory)][string]$RelativePath)
foreach ($repositoryPatch in $script:MoonWellRepositoryPatches) {
if ($RelativePath.Replace('/', '\').Equals(
$repositoryPatch.Replace('/', '\'),
[System.StringComparison]::OrdinalIgnoreCase)) {
return $true
}
}
return $false
}
function Test-MoonWellGraphicsPatch {
param([Parameter(Mandatory)][string]$RelativePath)
foreach ($graphicsPatch in $script:MoonWellGraphicsPatches) {
if ($RelativePath.Replace('/', '\').Equals(
$graphicsPatch.Replace('/', '\'),
[System.StringComparison]::OrdinalIgnoreCase)) {
return $true
}
}
return $false
}
function Test-MoonWellPreservedDataPatch {
param([Parameter(Mandatory)][string]$RelativePath)
if (Test-MoonWellRepositoryPatch -RelativePath $RelativePath) {
return $false
}
return Test-MoonWellGraphicsPatch -RelativePath $RelativePath
}
function Assert-SafePackagePath {
param(
[Parameter(Mandatory)]
[string]$PackagePath,
[Parameter(Mandatory)]
[string]$RepositoryPath,
[Parameter()]
[string]$ClientPath
)
$packageRoot = [System.IO.Path]::GetFullPath($PackagePath).TrimEnd('\')
$repositoryRoot = [System.IO.Path]::GetFullPath($RepositoryPath).TrimEnd('\')
$pathRoot = [System.IO.Path]::GetPathRoot($packageRoot).TrimEnd('\')
if (-not $packageRoot -or $packageRoot -eq $pathRoot) {
throw "Refusing to use a filesystem root as package staging: $packageRoot"
}
if ($packageRoot.Equals($repositoryRoot, [System.StringComparison]::OrdinalIgnoreCase) -or
$repositoryRoot.StartsWith($packageRoot + '\', [System.StringComparison]::OrdinalIgnoreCase)) {
throw 'Package staging must not be the repository root or one of its ancestors.'
}
if (-not [string]::IsNullOrWhiteSpace($ClientPath)) {
$clientRoot = [System.IO.Path]::GetFullPath($ClientPath).TrimEnd('\')
$packageIsClientOrChild =
$packageRoot.Equals($clientRoot, [System.StringComparison]::OrdinalIgnoreCase) -or
$packageRoot.StartsWith($clientRoot + '\', [System.StringComparison]::OrdinalIgnoreCase)
$packageContainsClient =
$clientRoot.StartsWith($packageRoot + '\', [System.StringComparison]::OrdinalIgnoreCase)
if ($packageIsClientOrChild -or $packageContainsClient) {
throw 'Package staging must be separate from the installed client tree.'
}
}
}
function Get-RelativeFilePaths {
param([Parameter(Mandatory)][string]$Root)
if (-not (Test-Path -LiteralPath $Root -PathType Container)) {
return @()
}
$absoluteRoot = [System.IO.Path]::GetFullPath($Root).TrimEnd('\')
return @(
Get-ChildItem -LiteralPath $absoluteRoot -Recurse -Force -File |
ForEach-Object { $_.FullName.Substring($absoluteRoot.Length + 1) }
)
}
function Remove-EmptyMoonWellDirectories {
param([Parameter(Mandatory)][string]$Destination)
foreach ($relativeRoot in @('Data\Patch-WXL.MPQ', 'Extensions', 'Utils')) {
$managedRoot = Join-Path $Destination $relativeRoot
if (-not (Test-Path -LiteralPath $managedRoot -PathType Container)) {
continue
}
$directories = @(
Get-ChildItem -LiteralPath $managedRoot -Recurse -Force -Directory |
Sort-Object { $_.FullName.Length } -Descending
)
$directories += Get-Item -LiteralPath $managedRoot
foreach ($directory in $directories) {
if (-not @(Get-ChildItem -LiteralPath $directory.FullName -Force).Count) {
Remove-Item -LiteralPath $directory.FullName -Force
Write-Host "Removed empty managed directory: $($directory.FullName)"
}
}
}
}
function Reset-MoonWellPackageStaging {
param(
[Parameter(Mandatory)][string]$PackagePath,
[Parameter(Mandatory)][string]$RepositoryPath,
[Parameter(Mandatory)][string]$ClientPath
)
Assert-SafePackagePath `
-PackagePath $PackagePath `
-RepositoryPath $RepositoryPath `
-ClientPath $ClientPath
if (Test-Path -LiteralPath $PackagePath) {
Remove-Item -LiteralPath $PackagePath -Recurse -Force
}
New-Item -ItemType Directory -Path $PackagePath -Force | Out-Null
}
function Remove-MoonWellRuntimeGarbage {
param([Parameter(Mandatory)][string]$Destination)
if (-not (Test-Path -LiteralPath $Destination -PathType Container)) {
return
}
$allowedExtensions = @{}
foreach ($name in $script:MoonWellExtensionNames) {
$allowedExtensions[$name.ToLowerInvariant()] = $true
}
$extensionsRoot = Join-Path $Destination 'Extensions'
if (Test-Path -LiteralPath $extensionsRoot -PathType Container) {
foreach ($entry in Get-ChildItem -LiteralPath $extensionsRoot -Force) {
$isAllowedDirectory = $entry.PSIsContainer -and
$allowedExtensions.ContainsKey($entry.Name.ToLowerInvariant())
if (-not $isAllowedDirectory) {
Remove-Item -LiteralPath $entry.FullName -Recurse -Force
Write-Host "Removed unmanaged WarcraftXL extension artifact: $($entry.FullName)"
continue
}
foreach ($dll in Get-ChildItem -LiteralPath $entry.FullName -Force -File -Filter '*.dll') {
$expectedName = "$($entry.Name).dll"
if (-not $dll.Name.Equals($expectedName, [System.StringComparison]::OrdinalIgnoreCase)) {
Remove-Item -LiteralPath $dll.FullName -Force
Write-Host "Removed stale extension DLL: $($dll.FullName)"
}
}
}
}
foreach ($dll in Get-ChildItem -LiteralPath $Destination -Force -File -Filter 'WarcraftXL*.dll') {
if (-not $dll.Name.Equals('WarcraftXL.dll', [System.StringComparison]::OrdinalIgnoreCase)) {
Remove-Item -LiteralPath $dll.FullName -Force
Write-Host "Removed stale WarcraftXL DLL: $($dll.FullName)"
}
}
$utilsRoot = Join-Path $Destination 'Utils'
if (Test-Path -LiteralPath $utilsRoot -PathType Container) {
foreach ($legacyFile in Get-ChildItem -LiteralPath $utilsRoot -Force -File -Filter 'WarcraftXLHost*') {
Remove-Item -LiteralPath $legacyFile.FullName -Force
Write-Host "Removed obsolete WarcraftXL 1.0 host artifact: $($legacyFile.FullName)"
}
}
Remove-EmptyMoonWellDirectories -Destination $Destination
}
function Remove-StalePackageFilesFromClient {
param(
[Parameter(Mandatory)][string]$ClientPath,
[Parameter(Mandatory)][AllowEmptyCollection()][string[]]$PreviousFiles,
[Parameter(Mandatory)][AllowEmptyCollection()][string[]]$CurrentFiles
)
$current = @{}
foreach ($relativePath in $CurrentFiles) {
$current[$relativePath.ToLowerInvariant()] = $true
}
$clientRoot = [System.IO.Path]::GetFullPath($ClientPath).TrimEnd('\')
foreach ($relativePath in $PreviousFiles) {
if ($current.ContainsKey($relativePath.ToLowerInvariant()) -or
(Test-MoonWellPreservedDataPatch -RelativePath $relativePath)) {
continue
}
$target = [System.IO.Path]::GetFullPath((Join-Path $clientRoot $relativePath))
if (-not $target.StartsWith($clientRoot + '\', [System.StringComparison]::OrdinalIgnoreCase)) {
throw "Package inventory contains a path outside the client: $relativePath"
}
if (Test-Path -LiteralPath $target -PathType Leaf) {
Remove-Item -LiteralPath $target -Force
Write-Host "Removed stale packaged file from client: $target"
}
}
Remove-EmptyMoonWellDirectories -Destination $ClientPath
}
+1
View File
@@ -0,0 +1 @@
dvc[s3]==3.67.1
+30 -1
View File
@@ -9,6 +9,7 @@ $ErrorActionPreference = "Stop"
# --- Resolve project root (folder where script is located)
$ROOT = Split-Path -Parent $MyInvocation.MyCommand.Path
. (Join-Path $ROOT 'pipeline-layout.ps1')
# --- Load .env if WOW_HOME not already set
if (-not $env:WOW_HOME) {
@@ -80,6 +81,11 @@ $TOOL = Join-Path $ROOT "tool\target\release\tool.exe"
$RELOAD_SCRIPT = Join-Path $ROOT "reload_wow.bat"
$WXL_BUILD_SCRIPT = Join-Path $ROOT "build-warcraftxl.ps1"
Assert-SafePackagePath `
-PackagePath $DIST_DIR `
-RepositoryPath $ROOT `
-ClientPath $WOW_HOME
function Stop-WowRuntime {
param([Parameter(Mandatory=$true)][string]$ClientPath)
@@ -118,7 +124,14 @@ if (!(Test-Path $TOOL)) {
Pop-Location
}
# --- Build MPQ archives into dist/
# --- Build MPQ archives into a clean dist/
$previousPackageFiles = @(
Get-RelativeFilePaths -Root $DIST_DIR
)
Reset-MoonWellPackageStaging `
-PackagePath $DIST_DIR `
-RepositoryPath $ROOT `
-ClientPath $WOW_HOME
Write-Host "Building MPQ archives from src/ -> dist/..."
& $TOOL $SRC_DIR $DIST_DIR
if ($LASTEXITCODE -ne 0) {
@@ -145,6 +158,22 @@ if ($LASTEXITCODE -ne 0) {
# --- Sync dist/ -> WOW_HOME
Write-Host "Syncing dist/ -> WOW_HOME..."
$python = Get-Command python -ErrorAction SilentlyContinue
if (-not $python) {
Write-Error "Python is required for package validation."
exit 1
}
& $python.Source (Join-Path $ROOT 'validate_package.py') --dir $DIST_DIR
if ($LASTEXITCODE -ne 0) {
Write-Error "Package validation failed!"
exit 1
}
$currentPackageFiles = @(Get-RelativeFilePaths -Root $DIST_DIR)
Remove-StalePackageFilesFromClient `
-ClientPath $WOW_HOME `
-PreviousFiles $previousPackageFiles `
-CurrentFiles $currentPackageFiles
Remove-MoonWellRuntimeGarbage -Destination $WOW_HOME
robocopy $DIST_DIR $WOW_HOME /E /NFL /NDL
# robocopy exit codes 0-7 are success/warnings; 8+ are errors
if ($LASTEXITCODE -ge 8) {
@@ -0,0 +1,10 @@
## Interface: 30300
## Title: !!!ClassicAPI
## Notes: Blizzard Classic API Emulation
## Version: 1.1.64
## Author: Tsoukie
## DefaultState: Enabled
## X-MoonWell-System: 1
## X-Upstream-Commit: b3da3000bba23a2c31aa9c9b7c0232d5973789e6
Lib\Load.xml
Load.xml
@@ -0,0 +1,238 @@
--[[ $Id: CallbackHandler-1.0.lua 18 2014-10-16 02:52:20Z mikk $ ]]
local MAJOR, MINOR = "CallbackHandler-1.0", 7
local CallbackHandler = LibStub:NewLibrary(MAJOR, MINOR)
if not CallbackHandler then return end -- No upgrade needed
local meta = {__index = function(tbl, key) tbl[key] = {} return tbl[key] end}
-- Lua APIs
local tconcat = table.concat
local assert, error, loadstring = assert, error, loadstring
local setmetatable, rawset, rawget = setmetatable, rawset, rawget
local next, select, pairs, type, tostring = next, select, pairs, type, tostring
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: geterrorhandler
local xpcall = xpcall
local function errorhandler(err)
return geterrorhandler()(err)
end
local function CreateDispatcher(argCount)
local code = [[
local next, xpcall, eh = ...
local method, ARGS
local function call() method(ARGS) end
local function dispatch(handlers, ...)
local index
index, method = next(handlers)
if not method then return end
local OLD_ARGS = ARGS
ARGS = ...
repeat
xpcall(call, eh)
index, method = next(handlers, index)
until not method
ARGS = OLD_ARGS
end
return dispatch
]]
local ARGS, OLD_ARGS = {}, {}
for i = 1, argCount do ARGS[i], OLD_ARGS[i] = "arg"..i, "old_arg"..i end
code = code:gsub("OLD_ARGS", tconcat(OLD_ARGS, ", ")):gsub("ARGS", tconcat(ARGS, ", "))
return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(next, xpcall, errorhandler)
end
local Dispatchers = setmetatable({}, {__index=function(self, argCount)
local dispatcher = CreateDispatcher(argCount)
rawset(self, argCount, dispatcher)
return dispatcher
end})
--------------------------------------------------------------------------
-- CallbackHandler:New
--
-- target - target object to embed public APIs in
-- RegisterName - name of the callback registration API, default "RegisterCallback"
-- UnregisterName - name of the callback unregistration API, default "UnregisterCallback"
-- UnregisterAllName - name of the API to unregister all callbacks, default "UnregisterAllCallbacks". false == don't publish this API.
function CallbackHandler:New(target, RegisterName, UnregisterName, UnregisterAllName)
RegisterName = RegisterName or "RegisterCallback"
UnregisterName = UnregisterName or "UnregisterCallback"
if UnregisterAllName==nil then -- false is used to indicate "don't want this method"
UnregisterAllName = "UnregisterAllCallbacks"
end
-- we declare all objects and exported APIs inside this closure to quickly gain access
-- to e.g. function names, the "target" parameter, etc
-- Create the registry object
local events = setmetatable({}, meta)
local registry = { recurse=0, events=events }
-- registry:Fire() - fires the given event/message into the registry
function registry:Fire(eventname, ...)
if not rawget(events, eventname) or not next(events[eventname]) then return end
local oldrecurse = registry.recurse
registry.recurse = oldrecurse + 1
Dispatchers[select('#', ...) + 1](events[eventname], eventname, ...)
registry.recurse = oldrecurse
if registry.insertQueue and oldrecurse==0 then
-- Something in one of our callbacks wanted to register more callbacks; they got queued
for eventname,callbacks in pairs(registry.insertQueue) do
local first = not rawget(events, eventname) or not next(events[eventname]) -- test for empty before. not test for one member after. that one member may have been overwritten.
for self,func in pairs(callbacks) do
events[eventname][self] = func
-- fire OnUsed callback?
if first and registry.OnUsed then
registry.OnUsed(registry, target, eventname)
first = nil
end
end
end
registry.insertQueue = nil
end
end
-- Registration of a callback, handles:
-- self["method"], leads to self["method"](self, ...)
-- self with function ref, leads to functionref(...)
-- "addonId" (instead of self) with function ref, leads to functionref(...)
-- all with an optional arg, which, if present, gets passed as first argument (after self if present)
target[RegisterName] = function(self, eventname, method, ... --[[actually just a single arg]])
if type(eventname) ~= "string" then
error("Usage: "..RegisterName.."(eventname, method[, arg]): 'eventname' - string expected.", 2)
end
method = method or eventname
local first = not rawget(events, eventname) or not next(events[eventname]) -- test for empty before. not test for one member after. that one member may have been overwritten.
if type(method) ~= "string" and type(method) ~= "function" then
error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): 'methodname' - string or function expected.", 2)
end
local regfunc
if type(method) == "string" then
-- self["method"] calling style
if type(self) ~= "table" then
error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): self was not a table?", 2)
elseif self==target then
error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): do not use Library:"..RegisterName.."(), use your own 'self'", 2)
elseif type(self[method]) ~= "function" then
error("Usage: "..RegisterName.."(\"eventname\", \"methodname\"): 'methodname' - method '"..tostring(method).."' not found on self.", 2)
end
if select("#",...)>=1 then -- this is not the same as testing for arg==nil!
local arg=select(1,...)
regfunc = function(...) self[method](self,arg,...) end
else
regfunc = function(...) self[method](self,...) end
end
else
-- function ref with self=object or self="addonId" or self=thread
if type(self)~="table" and type(self)~="string" and type(self)~="thread" then
error("Usage: "..RegisterName.."(self or \"addonId\", eventname, method): 'self or addonId': table or string or thread expected.", 2)
end
if select("#",...)>=1 then -- this is not the same as testing for arg==nil!
local arg=select(1,...)
regfunc = function(...) method(arg,...) end
else
regfunc = method
end
end
if events[eventname][self] or registry.recurse<1 then
-- if registry.recurse<1 then
-- we're overwriting an existing entry, or not currently recursing. just set it.
events[eventname][self] = regfunc
-- fire OnUsed callback?
if registry.OnUsed and first then
registry.OnUsed(registry, target, eventname)
end
else
-- we're currently processing a callback in this registry, so delay the registration of this new entry!
-- yes, we're a bit wasteful on garbage, but this is a fringe case, so we're picking low implementation overhead over garbage efficiency
registry.insertQueue = registry.insertQueue or setmetatable({},meta)
registry.insertQueue[eventname][self] = regfunc
end
end
-- Unregister a callback
target[UnregisterName] = function(self, eventname)
if not self or self==target then
error("Usage: "..UnregisterName.."(eventname): bad 'self'", 2)
end
if type(eventname) ~= "string" then
error("Usage: "..UnregisterName.."(eventname): 'eventname' - string expected.", 2)
end
if rawget(events, eventname) and events[eventname][self] then
events[eventname][self] = nil
-- Fire OnUnused callback?
if registry.OnUnused and not next(events[eventname]) then
registry.OnUnused(registry, target, eventname)
end
end
if registry.insertQueue and rawget(registry.insertQueue, eventname) and registry.insertQueue[eventname][self] then
registry.insertQueue[eventname][self] = nil
end
end
-- OPTIONAL: Unregister all callbacks for given selfs/addonIds
if UnregisterAllName then
target[UnregisterAllName] = function(...)
if select("#",...)<1 then
error("Usage: "..UnregisterAllName.."([whatFor]): missing 'self' or \"addonId\" to unregister events for.", 2)
end
if select("#",...)==1 and ...==target then
error("Usage: "..UnregisterAllName.."([whatFor]): supply a meaningful 'self' or \"addonId\"", 2)
end
for i=1,select("#",...) do
local self = select(i,...)
if registry.insertQueue then
for eventname, callbacks in pairs(registry.insertQueue) do
if callbacks[self] then
callbacks[self] = nil
end
end
end
for eventname, callbacks in pairs(events) do
if callbacks[self] then
callbacks[self] = nil
-- Fire OnUnused callback?
if registry.OnUnused and not next(callbacks) then
registry.OnUnused(registry, target, eventname)
end
end
end
end
end
end
return registry
end
-- CallbackHandler purposefully does NOT do explicit embedding. Nor does it
-- try to upgrade old implicit embeds since the system is selfcontained and
-- relies on closures to work.
@@ -0,0 +1,4 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
<Script file="CallbackHandler-1.0.lua"/>
</Ui>
@@ -0,0 +1,51 @@
-- $Id: LibStub.lua 103 2014-10-16 03:02:50Z mikk $
-- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/addons/libstub/ for more info
-- LibStub is hereby placed in the Public Domain
-- Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke
local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 3 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS!
local LibStub = _G[LIBSTUB_MAJOR]
-- Check to see is this version of the stub is obsolete
if not LibStub or LibStub.minor < LIBSTUB_MINOR then
LibStub = LibStub or {libs = {}, minors = {} }
_G[LIBSTUB_MAJOR] = LibStub
LibStub.minor = LIBSTUB_MINOR
-- LibStub:NewLibrary(major, minor)
-- major (string) - the major version of the library
-- minor (string or number ) - the minor version of the library
--
-- returns nil if a newer or same version of the lib is already present
-- returns empty library object or old library object if upgrade is needed
function LibStub:NewLibrary(major, minor)
assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)")
minor = assert(tonumber(strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.")
local oldminor = self.minors[major]
if oldminor and oldminor >= minor then return nil end
self.minors[major], self.libs[major] = minor, self.libs[major] or {}
return self.libs[major], oldminor
end
-- LibStub:GetLibrary(major, [silent])
-- major (string) - the major version of the library
-- silent (boolean) - if true, library is optional, silently return nil if its not found
--
-- throws an error if the library can not be found (except silent is set)
-- returns the library object if found
function LibStub:GetLibrary(major, silent)
if not self.libs[major] and not silent then
error(("Cannot find a library instance of %q."):format(tostring(major)), 2)
end
return self.libs[major], self.minors[major]
end
-- LibStub:IterateLibraries()
--
-- Returns an iterator for the currently registered libraries
function LibStub:IterateLibraries()
return pairs(self.libs)
end
setmetatable(LibStub, { __call = LibStub.GetLibrary })
end
@@ -0,0 +1,523 @@
--
-- ChatThrottleLib by Mikk
--
-- Manages AddOn chat output to keep player from getting kicked off.
--
-- ChatThrottleLib:SendChatMessage/:SendAddonMessage functions that accept
-- a Priority ("BULK", "NORMAL", "ALERT") as well as prefix for SendChatMessage.
--
-- Priorities get an equal share of available bandwidth when fully loaded.
-- Communication channels are separated on extension+chattype+destination and
-- get round-robinned. (Destination only matters for whispers and channels,
-- obviously)
--
-- Will install hooks for SendChatMessage and SendAddonMessage to measure
-- bandwidth bypassing the library and use less bandwidth itself.
--
--
-- Fully embeddable library. Just copy this file into your addon directory,
-- add it to the .toc, and it's done.
--
-- Can run as a standalone addon also, but, really, just embed it! :-)
--
-- LICENSE: ChatThrottleLib is released into the Public Domain
--
local CTL_VERSION = 25
local _G = _G
if _G.ChatThrottleLib then
if _G.ChatThrottleLib.version >= CTL_VERSION then
-- There's already a newer (or same) version loaded. Buh-bye.
return
elseif not _G.ChatThrottleLib.securelyHooked then
print("ChatThrottleLib: Warning: There's an ANCIENT ChatThrottleLib.lua (pre-wow 2.0, <v16) in an addon somewhere. Get the addon updated or copy in a newer ChatThrottleLib.lua (>=v16) in it!")
-- ATTEMPT to unhook; this'll behave badly if someone else has hooked...
-- ... and if someone has securehooked, they can kiss that goodbye too... >.<
_G.SendChatMessage = _G.ChatThrottleLib.ORIG_SendChatMessage
if _G.ChatThrottleLib.ORIG_SendAddonMessage then
_G.SendAddonMessage = _G.ChatThrottleLib.ORIG_SendAddonMessage
end
end
_G.ChatThrottleLib.ORIG_SendChatMessage = nil
_G.ChatThrottleLib.ORIG_SendAddonMessage = nil
end
if not _G.ChatThrottleLib then
_G.ChatThrottleLib = {}
end
ChatThrottleLib = _G.ChatThrottleLib -- in case some addon does "local ChatThrottleLib" above us and we're copypasted (AceComm-2, sigh)
local ChatThrottleLib = _G.ChatThrottleLib
ChatThrottleLib.version = CTL_VERSION
------------------ TWEAKABLES -----------------
ChatThrottleLib.MAX_CPS = 800 -- 2000 seems to be safe if NOTHING ELSE is happening. let's call it 800.
ChatThrottleLib.MSG_OVERHEAD = 40 -- Guesstimate overhead for sending a message; source+dest+chattype+protocolstuff
ChatThrottleLib.BURST = 4000 -- WoW's server buffer seems to be about 32KB. 8KB should be safe, but seen disconnects on _some_ servers. Using 4KB now.
ChatThrottleLib.MIN_FPS = 20 -- Reduce output CPS to half (and don't burst) if FPS drops below this value
local setmetatable = setmetatable
local table_remove = table.remove
local tostring = tostring
local GetTime = GetTime
local math_min = math.min
local math_max = math.max
local next = next
local strlen = string.len
local GetFramerate = GetFramerate
local strlower = string.lower
local unpack,type,pairs,wipe = unpack,type,pairs,wipe
local UnitInRaid,GetNumPartyMembers = UnitInRaid,GetNumPartyMembers
-----------------------------------------------------------------------
-- Double-linked ring implementation
local Ring = {}
local RingMeta = { __index = Ring }
function Ring:New()
local ret = {}
setmetatable(ret, RingMeta)
return ret
end
function Ring:Add(obj) -- Append at the "far end" of the ring (aka just before the current position)
if self.pos then
obj.prev = self.pos.prev
obj.prev.next = obj
obj.next = self.pos
obj.next.prev = obj
else
obj.next = obj
obj.prev = obj
self.pos = obj
end
end
function Ring:Remove(obj)
obj.next.prev = obj.prev
obj.prev.next = obj.next
if self.pos == obj then
self.pos = obj.next
if self.pos == obj then
self.pos = nil
end
end
end
-----------------------------------------------------------------------
-- Recycling bin for pipes
-- A pipe is a plain integer-indexed queue of messages
-- Pipes normally live in Rings of pipes (3 rings total, one per priority)
ChatThrottleLib.PipeBin = nil -- pre-v19, drastically different
local PipeBin = setmetatable({}, {__mode="k"})
local function DelPipe(pipe)
for i = #pipe, 1, -1 do
pipe[i] = nil
end
pipe.prev = nil
pipe.next = nil
PipeBin[pipe] = true
end
local function NewPipe()
local pipe = next(PipeBin)
if pipe then
wipe(pipe)
PipeBin[pipe] = nil
return pipe
end
return {}
end
-----------------------------------------------------------------------
-- Recycling bin for messages
ChatThrottleLib.MsgBin = nil -- pre-v19, drastically different
local MsgBin = setmetatable({}, {__mode="k"})
local function DelMsg(msg)
msg[1] = nil
-- there's more parameters, but they're very repetetive so the string pool doesn't suffer really, and it's faster to just not delete them.
MsgBin[msg] = true
end
local function NewMsg()
local msg = next(MsgBin)
if msg then
MsgBin[msg] = nil
return msg
end
return {}
end
-----------------------------------------------------------------------
-- ChatThrottleLib:Init
-- Initialize queues, set up frame for OnUpdate, etc
function ChatThrottleLib:Init()
-- Set up queues
if not self.Prio then
self.Prio = {}
self.Prio["ALERT"] = { ByName = {}, Ring = Ring:New(), avail = 0 }
self.Prio["NORMAL"] = { ByName = {}, Ring = Ring:New(), avail = 0 }
self.Prio["BULK"] = { ByName = {}, Ring = Ring:New(), avail = 0 }
end
-- v4: total send counters per priority
for _, Prio in pairs(self.Prio) do
Prio.nTotalSent = Prio.nTotalSent or 0
end
if not self.avail then
self.avail = 0 -- v5
end
if not self.nTotalSent then
self.nTotalSent = 0 -- v5
end
-- Set up a frame to get OnUpdate events
if not self.Frame then
self.Frame = CreateFrame("Frame")
self.Frame:Hide()
end
self.Frame:SetScript("OnUpdate", self.OnUpdate)
self.Frame:SetScript("OnEvent", self.OnEvent) -- v11: Monitor P_E_W so we can throttle hard for a few seconds
self.Frame:RegisterEvent("PLAYER_ENTERING_WORLD")
self.OnUpdateDelay = 0
self.LastAvailUpdate = GetTime()
self.HardThrottlingBeginTime = GetTime() -- v11: Throttle hard for a few seconds after startup
-- Hook SendChatMessage and SendAddonMessage so we can measure unpiped traffic and avoid overloads (v7)
if not self.securelyHooked then
-- Use secure hooks as of v16. Old regular hook support yanked out in v21.
self.securelyHooked = true
--SendChatMessage
hooksecurefunc("SendChatMessage", function(...)
return ChatThrottleLib.Hook_SendChatMessage(...)
end)
--SendAddonMessage
hooksecurefunc("SendAddonMessage", function(...)
return ChatThrottleLib.Hook_SendAddonMessage(...)
end)
end
self.nBypass = 0
end
-----------------------------------------------------------------------
-- ChatThrottleLib.Hook_SendChatMessage / .Hook_SendAddonMessage
local bMyTraffic = false
function ChatThrottleLib.Hook_SendChatMessage(text, chattype, language, destination, ...)
if bMyTraffic then
return
end
local self = ChatThrottleLib
local size = strlen(tostring(text or "")) + strlen(tostring(destination or "")) + self.MSG_OVERHEAD
self.avail = self.avail - size
self.nBypass = self.nBypass + size -- just a statistic
end
function ChatThrottleLib.Hook_SendAddonMessage(prefix, text, chattype, destination, ...)
if bMyTraffic then
return
end
local self = ChatThrottleLib
local size = tostring(text or ""):len() + tostring(prefix or ""):len();
size = size + tostring(destination or ""):len() + self.MSG_OVERHEAD
self.avail = self.avail - size
self.nBypass = self.nBypass + size -- just a statistic
end
-----------------------------------------------------------------------
-- ChatThrottleLib:UpdateAvail
-- Update self.avail with how much bandwidth is currently available
function ChatThrottleLib:UpdateAvail()
local now = GetTime()
local MAX_CPS = self.MAX_CPS;
local newavail = MAX_CPS * (now - self.LastAvailUpdate)
local avail = self.avail
if now - self.HardThrottlingBeginTime < 5 then
-- First 5 seconds after startup/zoning: VERY hard clamping to avoid irritating the server rate limiter, it seems very cranky then
avail = math_min(avail + (newavail*0.1), MAX_CPS*0.5)
self.bChoking = true
elseif GetFramerate() < self.MIN_FPS then -- GetFramerate call takes ~0.002 secs
avail = math_min(MAX_CPS, avail + newavail*0.5)
self.bChoking = true -- just a statistic
else
avail = math_min(self.BURST, avail + newavail)
self.bChoking = false
end
avail = math_max(avail, 0-(MAX_CPS*2)) -- Can go negative when someone is eating bandwidth past the lib. but we refuse to stay silent for more than 2 seconds; if they can do it, we can.
self.avail = avail
self.LastAvailUpdate = now
return avail
end
-----------------------------------------------------------------------
-- Despooling logic
-- Reminder:
-- - We have 3 Priorities, each containing a "Ring" construct ...
-- - ... made up of N "Pipe"s (1 for each destination/pipename)
-- - and each pipe contains messages
function ChatThrottleLib:Despool(Prio)
local ring = Prio.Ring
while ring.pos and Prio.avail > ring.pos[1].nSize do
local msg = table_remove(ring.pos, 1)
if not ring.pos[1] then -- did we remove last msg in this pipe?
local pipe = Prio.Ring.pos
Prio.Ring:Remove(pipe)
Prio.ByName[pipe.name] = nil
DelPipe(pipe)
else
Prio.Ring.pos = Prio.Ring.pos.next
end
local didSend=false
local lowerDest = strlower(msg[3] or "")
if lowerDest == "raid" and not UnitInRaid("player") then
-- do nothing
elseif lowerDest == "party" and GetNumPartyMembers() == 0 then
-- do nothing
else
Prio.avail = Prio.avail - msg.nSize
bMyTraffic = true
msg.f(unpack(msg, 1, msg.n))
bMyTraffic = false
Prio.nTotalSent = Prio.nTotalSent + msg.nSize
DelMsg(msg)
didSend = true
end
-- notify caller of delivery (even if we didn't send it)
if msg.callbackFn then
msg.callbackFn (msg.callbackArg, didSend)
end
-- USER CALLBACK MAY ERROR
end
end
function ChatThrottleLib.OnEvent(this,event)
-- v11: We know that the rate limiter is touchy after login. Assume that it's touchy after zoning, too.
local self = ChatThrottleLib
if event == "PLAYER_ENTERING_WORLD" then
self.HardThrottlingBeginTime = GetTime() -- Throttle hard for a few seconds after zoning
self.avail = 0
end
end
function ChatThrottleLib.OnUpdate(this,delay)
local self = ChatThrottleLib
self.OnUpdateDelay = self.OnUpdateDelay + delay
if self.OnUpdateDelay < 0.08 then
return
end
self.OnUpdateDelay = 0
self:UpdateAvail()
if self.avail < 0 then
return -- argh. some bastard is spewing stuff past the lib. just bail early to save cpu.
end
-- See how many of our priorities have queued messages (we only have 3, don't worry about the loop)
local n = 0
for prioname,Prio in pairs(self.Prio) do
if Prio.Ring.pos or Prio.avail < 0 then
n = n + 1
end
end
-- Anything queued still?
if n<1 then
-- Nope. Move spillover bandwidth to global availability gauge and clear self.bQueueing
for prioname, Prio in pairs(self.Prio) do
self.avail = self.avail + Prio.avail
Prio.avail = 0
end
self.bQueueing = false
self.Frame:Hide()
return
end
-- There's stuff queued. Hand out available bandwidth to priorities as needed and despool their queues
local avail = self.avail/n
self.avail = 0
for prioname, Prio in pairs(self.Prio) do
if Prio.Ring.pos or Prio.avail < 0 then
Prio.avail = Prio.avail + avail
if Prio.Ring.pos and Prio.avail > Prio.Ring.pos[1].nSize then
self:Despool(Prio)
-- Note: We might not get here if the user-supplied callback function errors out! Take care!
end
end
end
end
-----------------------------------------------------------------------
-- Spooling logic
function ChatThrottleLib:Enqueue(prioname, pipename, msg)
local Prio = self.Prio[prioname]
local pipe = Prio.ByName[pipename]
if not pipe then
self.Frame:Show()
pipe = NewPipe()
pipe.name = pipename
Prio.ByName[pipename] = pipe
Prio.Ring:Add(pipe)
end
pipe[#pipe + 1] = msg
self.bQueueing = true
end
function ChatThrottleLib:SendChatMessage(prio, prefix, text, chattype, language, destination, queueName, callbackFn, callbackArg)
if not self or not prio or not prefix or not text or not self.Prio[prio] then
error('Usage: ChatThrottleLib:SendChatMessage("{BULK||NORMAL||ALERT}", "prefix", "text"[, "chattype"[, "language"[, "destination"]]]', 2)
end
if callbackFn and type(callbackFn)~="function" then
error('ChatThrottleLib:ChatMessage(): callbackFn: expected function, got '..type(callbackFn), 2)
end
local nSize = text:len()
if nSize>255 then
error("ChatThrottleLib:SendChatMessage(): message length cannot exceed 255 bytes", 2)
end
nSize = nSize + self.MSG_OVERHEAD
-- Check if there's room in the global available bandwidth gauge to send directly
if not self.bQueueing and nSize < self:UpdateAvail() then
self.avail = self.avail - nSize
bMyTraffic = true
_G.SendChatMessage(text, chattype, language, destination)
bMyTraffic = false
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize
if callbackFn then
callbackFn (callbackArg, true)
end
-- USER CALLBACK MAY ERROR
return
end
-- Message needs to be queued
local msg = NewMsg()
msg.f = _G.SendChatMessage
msg[1] = text
msg[2] = chattype or "SAY"
msg[3] = language
msg[4] = destination
msg.n = 4
msg.nSize = nSize
msg.callbackFn = callbackFn
msg.callbackArg = callbackArg
self:Enqueue(prio, queueName or (prefix..(chattype or "SAY")..(destination or "")), msg)
end
function ChatThrottleLib:SendAddonMessage(prio, prefix, text, chattype, target, queueName, callbackFn, callbackArg)
if not self or not prio or not prefix or not text or not chattype or not self.Prio[prio] then
error('Usage: ChatThrottleLib:SendAddonMessage("{BULK||NORMAL||ALERT}", "prefix", "text", "chattype"[, "target"])', 2)
end
if callbackFn and type(callbackFn)~="function" then
error('ChatThrottleLib:SendAddonMessage(): callbackFn: expected function, got '..type(callbackFn), 2)
end
local nSize = prefix:len() + 1 + text:len();
if nSize>255 then
error("ChatThrottleLib:SendAddonMessage(): prefix + message length cannot exceed 254 bytes", 2)
end
nSize = nSize + self.MSG_OVERHEAD;
-- Check if there's room in the global available bandwidth gauge to send directly
if not self.bQueueing and nSize < self:UpdateAvail() then
self.avail = self.avail - nSize
bMyTraffic = true
_G.SendAddonMessage(prefix, text, chattype, target)
bMyTraffic = false
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize
if callbackFn then
callbackFn (callbackArg, true)
end
-- USER CALLBACK MAY ERROR
return
end
-- Message needs to be queued
local msg = NewMsg()
msg.f = _G.SendAddonMessage
msg[1] = prefix
msg[2] = text
msg[3] = chattype
msg[4] = target
msg.n = (target~=nil) and 4 or 3;
msg.nSize = nSize
msg.callbackFn = callbackFn
msg.callbackArg = callbackArg
self:Enqueue(prio, queueName or (prefix..chattype..(target or "")), msg)
end
-----------------------------------------------------------------------
-- Get the ball rolling!
ChatThrottleLib:Init()
--[[ WoWBench debugging snippet
if(WOWB_VER) then
local function SayTimer()
print("SAY: "..GetTime().." "..arg1)
end
ChatThrottleLib.Frame:SetScript("OnEvent", SayTimer)
ChatThrottleLib.Frame:RegisterEvent("CHAT_MSG_SAY")
end
]]
@@ -0,0 +1,523 @@
--
-- ChatThrottleLib by Mikk
--
-- Manages AddOn chat output to keep player from getting kicked off.
--
-- ChatThrottleLib:SendChatMessage/:SendAddonMessage functions that accept
-- a Priority ("BULK", "NORMAL", "ALERT") as well as prefix for SendChatMessage.
--
-- Priorities get an equal share of available bandwidth when fully loaded.
-- Communication channels are separated on extension+chattype+destination and
-- get round-robinned. (Destination only matters for whispers and channels,
-- obviously)
--
-- Will install hooks for SendChatMessage and SendAddonMessage to measure
-- bandwidth bypassing the library and use less bandwidth itself.
--
--
-- Fully embeddable library. Just copy this file into your addon directory,
-- add it to the .toc, and it's done.
--
-- Can run as a standalone addon also, but, really, just embed it! :-)
--
-- LICENSE: ChatThrottleLib is released into the Public Domain
--
local CTL_VERSION = 25
local _G = _G
if _G.ChatThrottleLib then
if _G.ChatThrottleLib.version >= CTL_VERSION then
-- There's already a newer (or same) version loaded. Buh-bye.
return
elseif not _G.ChatThrottleLib.securelyHooked then
print("ChatThrottleLib: Warning: There's an ANCIENT ChatThrottleLib.lua (pre-wow 2.0, <v16) in an addon somewhere. Get the addon updated or copy in a newer ChatThrottleLib.lua (>=v16) in it!")
-- ATTEMPT to unhook; this'll behave badly if someone else has hooked...
-- ... and if someone has securehooked, they can kiss that goodbye too... >.<
_G.SendChatMessage = _G.ChatThrottleLib.ORIG_SendChatMessage
if _G.ChatThrottleLib.ORIG_SendAddonMessage then
_G.SendAddonMessage = _G.ChatThrottleLib.ORIG_SendAddonMessage
end
end
_G.ChatThrottleLib.ORIG_SendChatMessage = nil
_G.ChatThrottleLib.ORIG_SendAddonMessage = nil
end
if not _G.ChatThrottleLib then
_G.ChatThrottleLib = {}
end
ChatThrottleLib = _G.ChatThrottleLib -- in case some addon does "local ChatThrottleLib" above us and we're copypasted (AceComm-2, sigh)
local ChatThrottleLib = _G.ChatThrottleLib
ChatThrottleLib.version = CTL_VERSION
------------------ TWEAKABLES -----------------
ChatThrottleLib.MAX_CPS = 800 -- 2000 seems to be safe if NOTHING ELSE is happening. let's call it 800.
ChatThrottleLib.MSG_OVERHEAD = 40 -- Guesstimate overhead for sending a message; source+dest+chattype+protocolstuff
ChatThrottleLib.BURST = 4000 -- WoW's server buffer seems to be about 32KB. 8KB should be safe, but seen disconnects on _some_ servers. Using 4KB now.
ChatThrottleLib.MIN_FPS = 20 -- Reduce output CPS to half (and don't burst) if FPS drops below this value
local setmetatable = setmetatable
local table_remove = table.remove
local tostring = tostring
local GetTime = GetTime
local math_min = math.min
local math_max = math.max
local next = next
local strlen = string.len
local GetFramerate = GetFramerate
local strlower = string.lower
local unpack,type,pairs,wipe = unpack,type,pairs,wipe
local UnitInRaid,GetNumPartyMembers = UnitInRaid,GetNumPartyMembers
-----------------------------------------------------------------------
-- Double-linked ring implementation
local Ring = {}
local RingMeta = { __index = Ring }
function Ring:New()
local ret = {}
setmetatable(ret, RingMeta)
return ret
end
function Ring:Add(obj) -- Append at the "far end" of the ring (aka just before the current position)
if self.pos then
obj.prev = self.pos.prev
obj.prev.next = obj
obj.next = self.pos
obj.next.prev = obj
else
obj.next = obj
obj.prev = obj
self.pos = obj
end
end
function Ring:Remove(obj)
obj.next.prev = obj.prev
obj.prev.next = obj.next
if self.pos == obj then
self.pos = obj.next
if self.pos == obj then
self.pos = nil
end
end
end
-----------------------------------------------------------------------
-- Recycling bin for pipes
-- A pipe is a plain integer-indexed queue of messages
-- Pipes normally live in Rings of pipes (3 rings total, one per priority)
ChatThrottleLib.PipeBin = nil -- pre-v19, drastically different
local PipeBin = setmetatable({}, {__mode="k"})
local function DelPipe(pipe)
for i = #pipe, 1, -1 do
pipe[i] = nil
end
pipe.prev = nil
pipe.next = nil
PipeBin[pipe] = true
end
local function NewPipe()
local pipe = next(PipeBin)
if pipe then
wipe(pipe)
PipeBin[pipe] = nil
return pipe
end
return {}
end
-----------------------------------------------------------------------
-- Recycling bin for messages
ChatThrottleLib.MsgBin = nil -- pre-v19, drastically different
local MsgBin = setmetatable({}, {__mode="k"})
local function DelMsg(msg)
msg[1] = nil
-- there's more parameters, but they're very repetetive so the string pool doesn't suffer really, and it's faster to just not delete them.
MsgBin[msg] = true
end
local function NewMsg()
local msg = next(MsgBin)
if msg then
MsgBin[msg] = nil
return msg
end
return {}
end
-----------------------------------------------------------------------
-- ChatThrottleLib:Init
-- Initialize queues, set up frame for OnUpdate, etc
function ChatThrottleLib:Init()
-- Set up queues
if not self.Prio then
self.Prio = {}
self.Prio["ALERT"] = { ByName = {}, Ring = Ring:New(), avail = 0 }
self.Prio["NORMAL"] = { ByName = {}, Ring = Ring:New(), avail = 0 }
self.Prio["BULK"] = { ByName = {}, Ring = Ring:New(), avail = 0 }
end
-- v4: total send counters per priority
for _, Prio in pairs(self.Prio) do
Prio.nTotalSent = Prio.nTotalSent or 0
end
if not self.avail then
self.avail = 0 -- v5
end
if not self.nTotalSent then
self.nTotalSent = 0 -- v5
end
-- Set up a frame to get OnUpdate events
if not self.Frame then
self.Frame = CreateFrame("Frame")
self.Frame:Hide()
end
self.Frame:SetScript("OnUpdate", self.OnUpdate)
self.Frame:SetScript("OnEvent", self.OnEvent) -- v11: Monitor P_E_W so we can throttle hard for a few seconds
self.Frame:RegisterEvent("PLAYER_ENTERING_WORLD")
self.OnUpdateDelay = 0
self.LastAvailUpdate = GetTime()
self.HardThrottlingBeginTime = GetTime() -- v11: Throttle hard for a few seconds after startup
-- Hook SendChatMessage and SendAddonMessage so we can measure unpiped traffic and avoid overloads (v7)
if not self.securelyHooked then
-- Use secure hooks as of v16. Old regular hook support yanked out in v21.
self.securelyHooked = true
--SendChatMessage
hooksecurefunc("SendChatMessage", function(...)
return ChatThrottleLib.Hook_SendChatMessage(...)
end)
--SendAddonMessage
hooksecurefunc("SendAddonMessage", function(...)
return ChatThrottleLib.Hook_SendAddonMessage(...)
end)
end
self.nBypass = 0
end
-----------------------------------------------------------------------
-- ChatThrottleLib.Hook_SendChatMessage / .Hook_SendAddonMessage
local bMyTraffic = false
function ChatThrottleLib.Hook_SendChatMessage(text, chattype, language, destination, ...)
if bMyTraffic then
return
end
local self = ChatThrottleLib
local size = strlen(tostring(text or "")) + strlen(tostring(destination or "")) + self.MSG_OVERHEAD
self.avail = self.avail - size
self.nBypass = self.nBypass + size -- just a statistic
end
function ChatThrottleLib.Hook_SendAddonMessage(prefix, text, chattype, destination, ...)
if bMyTraffic then
return
end
local self = ChatThrottleLib
local size = tostring(text or ""):len() + tostring(prefix or ""):len();
size = size + tostring(destination or ""):len() + self.MSG_OVERHEAD
self.avail = self.avail - size
self.nBypass = self.nBypass + size -- just a statistic
end
-----------------------------------------------------------------------
-- ChatThrottleLib:UpdateAvail
-- Update self.avail with how much bandwidth is currently available
function ChatThrottleLib:UpdateAvail()
local now = GetTime()
local MAX_CPS = self.MAX_CPS;
local newavail = MAX_CPS * (now - self.LastAvailUpdate)
local avail = self.avail
if now - self.HardThrottlingBeginTime < 5 then
-- First 5 seconds after startup/zoning: VERY hard clamping to avoid irritating the server rate limiter, it seems very cranky then
avail = math_min(avail + (newavail*0.1), MAX_CPS*0.5)
self.bChoking = true
elseif GetFramerate() < self.MIN_FPS then -- GetFramerate call takes ~0.002 secs
avail = math_min(MAX_CPS, avail + newavail*0.5)
self.bChoking = true -- just a statistic
else
avail = math_min(self.BURST, avail + newavail)
self.bChoking = false
end
avail = math_max(avail, 0-(MAX_CPS*2)) -- Can go negative when someone is eating bandwidth past the lib. but we refuse to stay silent for more than 2 seconds; if they can do it, we can.
self.avail = avail
self.LastAvailUpdate = now
return avail
end
-----------------------------------------------------------------------
-- Despooling logic
-- Reminder:
-- - We have 3 Priorities, each containing a "Ring" construct ...
-- - ... made up of N "Pipe"s (1 for each destination/pipename)
-- - and each pipe contains messages
function ChatThrottleLib:Despool(Prio)
local ring = Prio.Ring
while ring.pos and Prio.avail > ring.pos[1].nSize do
local msg = table_remove(ring.pos, 1)
if not ring.pos[1] then -- did we remove last msg in this pipe?
local pipe = Prio.Ring.pos
Prio.Ring:Remove(pipe)
Prio.ByName[pipe.name] = nil
DelPipe(pipe)
else
Prio.Ring.pos = Prio.Ring.pos.next
end
local didSend=false
local lowerDest = strlower(msg[3] or "")
if lowerDest == "raid" and not UnitInRaid("player") then
-- do nothing
elseif lowerDest == "party" and GetNumPartyMembers() == 0 then
-- do nothing
else
Prio.avail = Prio.avail - msg.nSize
bMyTraffic = true
msg.f(unpack(msg, 1, msg.n))
bMyTraffic = false
Prio.nTotalSent = Prio.nTotalSent + msg.nSize
DelMsg(msg)
didSend = true
end
-- notify caller of delivery (even if we didn't send it)
if msg.callbackFn then
msg.callbackFn (msg.callbackArg, didSend)
end
-- USER CALLBACK MAY ERROR
end
end
function ChatThrottleLib.OnEvent(this,event)
-- v11: We know that the rate limiter is touchy after login. Assume that it's touchy after zoning, too.
local self = ChatThrottleLib
if event == "PLAYER_ENTERING_WORLD" then
self.HardThrottlingBeginTime = GetTime() -- Throttle hard for a few seconds after zoning
self.avail = 0
end
end
function ChatThrottleLib.OnUpdate(this,delay)
local self = ChatThrottleLib
self.OnUpdateDelay = self.OnUpdateDelay + delay
if self.OnUpdateDelay < 0.08 then
return
end
self.OnUpdateDelay = 0
self:UpdateAvail()
if self.avail < 0 then
return -- argh. some bastard is spewing stuff past the lib. just bail early to save cpu.
end
-- See how many of our priorities have queued messages (we only have 3, don't worry about the loop)
local n = 0
for prioname,Prio in pairs(self.Prio) do
if Prio.Ring.pos or Prio.avail < 0 then
n = n + 1
end
end
-- Anything queued still?
if n<1 then
-- Nope. Move spillover bandwidth to global availability gauge and clear self.bQueueing
for prioname, Prio in pairs(self.Prio) do
self.avail = self.avail + Prio.avail
Prio.avail = 0
end
self.bQueueing = false
self.Frame:Hide()
return
end
-- There's stuff queued. Hand out available bandwidth to priorities as needed and despool their queues
local avail = self.avail/n
self.avail = 0
for prioname, Prio in pairs(self.Prio) do
if Prio.Ring.pos or Prio.avail < 0 then
Prio.avail = Prio.avail + avail
if Prio.Ring.pos and Prio.avail > Prio.Ring.pos[1].nSize then
self:Despool(Prio)
-- Note: We might not get here if the user-supplied callback function errors out! Take care!
end
end
end
end
-----------------------------------------------------------------------
-- Spooling logic
function ChatThrottleLib:Enqueue(prioname, pipename, msg)
local Prio = self.Prio[prioname]
local pipe = Prio.ByName[pipename]
if not pipe then
self.Frame:Show()
pipe = NewPipe()
pipe.name = pipename
Prio.ByName[pipename] = pipe
Prio.Ring:Add(pipe)
end
pipe[#pipe + 1] = msg
self.bQueueing = true
end
function ChatThrottleLib:SendChatMessage(prio, prefix, text, chattype, language, destination, queueName, callbackFn, callbackArg)
if not self or not prio or not prefix or not text or not self.Prio[prio] then
error('Usage: ChatThrottleLib:SendChatMessage("{BULK||NORMAL||ALERT}", "prefix", "text"[, "chattype"[, "language"[, "destination"]]]', 2)
end
if callbackFn and type(callbackFn)~="function" then
error('ChatThrottleLib:ChatMessage(): callbackFn: expected function, got '..type(callbackFn), 2)
end
local nSize = text:len()
if nSize>255 then
error("ChatThrottleLib:SendChatMessage(): message length cannot exceed 255 bytes", 2)
end
nSize = nSize + self.MSG_OVERHEAD
-- Check if there's room in the global available bandwidth gauge to send directly
if not self.bQueueing and nSize < self:UpdateAvail() then
self.avail = self.avail - nSize
bMyTraffic = true
_G.SendChatMessage(text, chattype, language, destination)
bMyTraffic = false
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize
if callbackFn then
callbackFn (callbackArg, true)
end
-- USER CALLBACK MAY ERROR
return
end
-- Message needs to be queued
local msg = NewMsg()
msg.f = _G.SendChatMessage
msg[1] = text
msg[2] = chattype or "SAY"
msg[3] = language
msg[4] = destination
msg.n = 4
msg.nSize = nSize
msg.callbackFn = callbackFn
msg.callbackArg = callbackArg
self:Enqueue(prio, queueName or (prefix..(chattype or "SAY")..(destination or "")), msg)
end
function ChatThrottleLib:SendAddonMessage(prio, prefix, text, chattype, target, queueName, callbackFn, callbackArg)
if not self or not prio or not prefix or not text or not chattype or not self.Prio[prio] then
error('Usage: ChatThrottleLib:SendAddonMessage("{BULK||NORMAL||ALERT}", "prefix", "text", "chattype"[, "target"])', 2)
end
if callbackFn and type(callbackFn)~="function" then
error('ChatThrottleLib:SendAddonMessage(): callbackFn: expected function, got '..type(callbackFn), 2)
end
local nSize = prefix:len() + 1 + text:len();
if nSize>255 then
error("ChatThrottleLib:SendAddonMessage(): prefix + message length cannot exceed 254 bytes", 2)
end
nSize = nSize + self.MSG_OVERHEAD;
-- Check if there's room in the global available bandwidth gauge to send directly
if not self.bQueueing and nSize < self:UpdateAvail() then
self.avail = self.avail - nSize
bMyTraffic = true
_G.SendAddonMessage(prefix, text, chattype, target)
bMyTraffic = false
self.Prio[prio].nTotalSent = self.Prio[prio].nTotalSent + nSize
if callbackFn then
callbackFn (callbackArg, true)
end
-- USER CALLBACK MAY ERROR
return
end
-- Message needs to be queued
local msg = NewMsg()
msg.f = _G.SendAddonMessage
msg[1] = prefix
msg[2] = text
msg[3] = chattype
msg[4] = target
msg.n = (target~=nil) and 4 or 3;
msg.nSize = nSize
msg.callbackFn = callbackFn
msg.callbackArg = callbackArg
self:Enqueue(prio, queueName or (prefix..chattype..(target or "")), msg)
end
-----------------------------------------------------------------------
-- Get the ball rolling!
ChatThrottleLib:Init()
--[[ WoWBench debugging snippet
if(WOWB_VER) then
local function SayTimer()
print("SAY: "..GetTime().." "..arg1)
end
ChatThrottleLib.Frame:SetScript("OnEvent", SayTimer)
ChatThrottleLib.Frame:RegisterEvent("CHAT_MSG_SAY")
end
]]
@@ -0,0 +1,6 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
<Script file="ChatThrottleLib.lua" />
<Script file="LibHealComm-4.0.lua" />
</Ui>
@@ -0,0 +1,3 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/">
<Script file="ChatThrottleLib.lua" />
</Ui>
@@ -0,0 +1,58 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
<Script file="Util\Constants.lua" />
<Script file="Util\SoundKit.lua" />
<Script file="Util\C_TimerAugment.lua" />
<Script file="Util\EventHandler.lua" />
<Script file="Util\EventHandlerSupport.lua" />
<Script file="Util\Unit.lua" />
<Script file="Util\Cooldown.lua" />
<Script file="Util\Group.lua" />
<Script file="Util\Spell.lua" />
<Script file="Util\HealPrediction.lua" />
<Script file="Util\C_CreatureInfo.lua" />
<Script file="Util\C_FriendList.lua" />
<Script file="Util\C_IncomingSummon.lua" />
<Script file="Util\C_Map.lua" />
<Script file="Util\C_PvP.lua" />
<Script file="Util\C_Texture.lua" />
<Script file="Util\C_Talent.lua" />
<Script file="Util\C_VoiceChat.lua" />
<Script file="Util\C_NamePlate.lua" />
<Script file="Util\C_GossipInfo.lua" />
<Script file="Util\C_ChatInfo.lua" />
<Script file="Util\C_Spell.lua" />
<Script file="Util\C_Item.lua" />
<Script file="Util\C_UI.lua" />
<Script file="Util\C_NewItems.lua" />
<Script file="Util\Mixin.lua" />
<Script file="Util\Pools.lua" />
<Script file="Util\Color.lua" />
<Script file="Util\ColorUtil.lua" />
<Script file="Util\API.lua" />
<Script file="Util\TableUtil.lua" />
<Script file="Util\MathUtil.lua" />
<Script file="Util\EnumUtil.lua" />
<Script file="Util\Atlas.lua" />
<Script file="Util\SharedExtendedMethods.lua" />
<Script file="Util\PartyUtil.lua" />
<Script file="Util\PixelUtil.lua" />
<Script file="Util\AuraUtil.lua" />
<Script file="Util\Aura.lua" />
<Script file="Util\NineSlice.lua" />
<Script file="Util\TextureUtil.lua" />
<Script file="Util\SmoothStatusBar.lua" />
<Script file="Util\CallbackRegistry.lua" />
<Script file="Util\GlobalCallbackRegistry.lua" />
<Script file="Util\SpellUtil.lua" />
<Script file="Util\ItemUtil.lua" />
<Script file="Util\AddOnCompat.lua" />
<!-- Templates -->
<Include file="Templates\Load.xml" />
</Ui>
@@ -0,0 +1,455 @@
BackdropTemplateMixin = BackdropTemplateMixin or {}
BACKDROP_TOOLTIP_8_8_1111 = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true,
tileEdge = true,
tileSize = 8,
edgeSize = 8,
insets = { left = 1, right = 1, top = 1, bottom = 1 },
};
BACKDROP_TOOLTIP_8_12_1111 = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true,
tileEdge = true,
tileSize = 8,
edgeSize = 12,
insets = { left = 1, right = 1, top = 1, bottom = 1 },
};
BACKDROP_TOOLTIP_16_16_5555 = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true,
tileEdge = true,
tileSize = 16,
edgeSize = 16,
insets = { left = 5, right = 5, top = 5, bottom = 5 },
};
BACKDROP_TOOLTIP_12_12_4444 = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true,
tileEdge = true,
tileSize = 12,
edgeSize = 12,
insets = { left = 4, right = 4, top = 4, bottom = 4 },
};
BACKDROP_TOOLTIP_0_16 = {
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
edgeSize = 16,
tileEdge = true,
};
BACKDROP_TOOLTIP_0_12_0055 = {
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
edgeSize = 12,
tileEdge = true,
insets = { left = 0, right = 0, top = 5, bottom = 5 },
};
BACKDROP_TOOLTIP_0_16_5555 = {
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
edgeSize = 16,
tileEdge = true,
insets = { left = 5, right = 5, top = 5, bottom = 5 },
};
BACKDROP_ACHIEVEMENTS_0_64 = {
edgeFile = "Interface\\AchievementFrame\\UI-Achievement-WoodBorder",
edgeSize = 64,
tileEdge = true,
};
BACKDROP_ARENA_32_32 = {
bgFile = "Interface\\CharacterFrame\\UI-Party-Background",
edgeFile = "Interface\\ArenaEnemyFrame\\UI-Arena-Border",
tile = true,
tileEdge = true,
tileSize = 32,
edgeSize = 32,
insets = { left = 32, right = 32, top = 32, bottom = 32 },
};
BACKDROP_DIALOG_32_32 = {
bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
tile = true,
tileEdge = true,
tileSize = 32,
edgeSize = 32,
insets = { left = 11, right = 12, top = 12, bottom = 11 },
};
BACKDROP_GOLD_DIALOG_32_32 = {
bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background",
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Gold-Border",
tile = true,
tileEdge = true,
tileSize = 32,
edgeSize = 32,
insets = { left = 11, right = 12, top = 12, bottom = 11 },
};
BACKDROP_WATERMARK_DIALOG_0_16 = {
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-TestWatermark-Border",
tileEdge = true,
edgeSize = 16,
};
BACKDROP_SLIDER_8_8 = {
bgFile = "Interface\\Buttons\\UI-SliderBar-Background",
edgeFile = "Interface\\Buttons\\UI-SliderBar-Border",
tile = true,
tileEdge = true,
tileSize = 8,
edgeSize = 8,
insets = { left = 3, right = 3, top = 6, bottom = 6 },
};
BACKDROP_PARTY_32_32 = {
bgFile = "Interface\\CharacterFrame\\UI-Party-Background",
edgeFile = "Interface\\CharacterFrame\\UI-Party-Border",
tile = true,
tileEdge = true,
tileSize = 32,
edgeSize = 32,
insets = { left = 32, right = 32, top = 32, bottom = 32 },
};
BACKDROP_TOAST_12_12 = {
bgFile = "Interface\\FriendsFrame\\UI-Toast-Background",
edgeFile = "Interface\\FriendsFrame\\UI-Toast-Border",
tile = true,
tileEdge = true,
tileSize = 12,
edgeSize = 12,
insets = { left = 5, right = 5, top = 5, bottom = 5 },
};
BACKDROP_CALLOUT_GLOW_0_16 = {
edgeFile = "Interface\\TutorialFrame\\UI-TutorialFrame-CalloutGlow",
edgeSize = 16,
tileEdge = true,
};
BACKDROP_CALLOUT_GLOW_0_20 = {
edgeFile = "Interface\\TutorialFrame\\UI-TutorialFrame-CalloutGlow",
edgeSize = 20,
tileEdge = true,
};
BACKDROP_GLUE_TOOLTIP_16_16 = {
bgFile = "Interface\\Glues\\Common\\Glue-Tooltip-Background",
edgeFile = "Interface\\Glues\\Common\\Glue-Tooltip-Border",
tile = true,
tileEdge = true,
tileSize = 16,
edgeSize = 16,
insets = { left = 10, right = 5, top = 4, bottom = 9 },
};
BACKDROP_GLUE_TOOLTIP_0_16 = {
edgeFile = "Interface\\Glues\\Common\\Glue-Tooltip-Border",
tileEdge = true,
edgeSize = 16,
};
BACKDROP_MIXED_TOOLTIP_16_16 = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = "Interface\\Glues\\Common\\Glue-Tooltip-Border",
tile = true,
tileEdge = true,
tileSize = 16,
edgeSize = 16,
insets = { left = 10, right = 5, top = 4, bottom = 9 },
};
BACKDROP_TEXT_PANEL_0_16 = {
edgeFile = "Interface\\Glues\\Common\\TextPanel-Border",
tileEdge = true,
edgeSize = 16,
};
local coordStart = 0.0625;
local coordEnd = 1 - coordStart;
local textureUVs = { -- keys have to match pieceNames in nineSliceSetup table
TopLeftCorner = { setWidth = true, setHeight = true, ULx = 0.5078125, ULy = coordStart, LLx = 0.5078125, LLy = coordEnd, URx = 0.6171875, URy = coordStart, LRx = 0.6171875, LRy = coordEnd },
TopRightCorner = { setWidth = true, setHeight = true, ULx = 0.6328125, ULy = coordStart, LLx = 0.6328125, LLy = coordEnd, URx = 0.7421875, URy = coordStart, LRx = 0.7421875, LRy = coordEnd },
BottomLeftCorner = { setWidth = true, setHeight = true, ULx = 0.7578125, ULy = coordStart, LLx = 0.7578125, LLy = coordEnd, URx = 0.8671875, URy = coordStart, LRx = 0.8671875, LRy = coordEnd },
BottomRightCorner = { setWidth = true, setHeight = true, ULx = 0.8828125, ULy = coordStart, LLx = 0.8828125, LLy = coordEnd, URx = 0.9921875, URy = coordStart, LRx = 0.9921875, LRy = coordEnd },
TopEdge = { setHeight = true, ULx = 0.2578125, ULy = "repeatX", LLx = 0.3671875, LLy = "repeatX", URx = 0.2578125, URy = coordStart, LRx = 0.3671875, LRy = coordStart },
BottomEdge = { setHeight = true, ULx = 0.3828125, ULy = "repeatX", LLx = 0.4921875, LLy = "repeatX", URx = 0.3828125, URy = coordStart, LRx = 0.4921875, LRy = coordStart },
LeftEdge = { setWidth = true, ULx = 0.0078125, ULy = coordStart, LLx = 0.0078125, LLy = "repeatY", URx = 0.1171875, URy = coordStart, LRx = 0.1171875, LRy = "repeatY" },
RightEdge = { setWidth = true, ULx = 0.1328125, ULy = coordStart, LLx = 0.1328125, LLy = "repeatY", URx = 0.2421875, URy = coordStart, LRx = 0.2421875, LRy = "repeatY" },
Center = { ULx = 0, ULy = 0, LLx = 0, LLy = "repeatY", URx = "repeatX", URy = 0, LRx = "repeatX", LRy = "repeatY" },
};
local defaultEdgeSize = 39; -- the old default
function BackdropTemplateMixin:OnBackdropLoaded()
if self.backdropInfo then
-- check for invalid info
if not self.backdropInfo.edgeFile and not self.backdropInfo.bgFile then
self.backdropInfo = nil;
return;
end
self:ApplyBackdrop();
do
if self.backdropColor then
local r, g, b = 1, 1, 1;
r, g, b = self.backdropColor:GetRGB();
local a = self.backdropColorAlpha or 1;
self:SetBackdropColor(r, g, b, a);
end
end
do
if self.backdropBorderColor then
local r, g, b = 1, 1, 1;
r, g, b = self.backdropBorderColor:GetRGB();
local a = self.backdropBorderColorAlpha or 1;
self:SetBackdropBorderColor(r, g, b, a);
end
end
if self.backdropBorderBlendMode then
self:SetBorderBlendMode(self.backdropBorderBlendMode);
end
end
end
function BackdropTemplateMixin:OnBackdropSizeChanged()
if self.backdropInfo then
self:SetupTextureCoordinates();
end
end
function BackdropTemplateMixin:GetEdgeSize()
if self.backdropInfo.edgeSize and self.backdropInfo.edgeSize > 0 then
return self.backdropInfo.edgeSize;
else
return defaultEdgeSize;
end
end
local function GetBackdropCoordValue(coord, pieceSetup, repeatX, repeatY)
local value = pieceSetup[coord];
if value == "repeatX" then
return repeatX;
elseif value == "repeatY" then
return repeatY;
else
return value;
end
end
local function SetupBackdropTextureCoordinates(region, pieceSetup, repeatX, repeatY)
region:SetTexCoord( GetBackdropCoordValue("ULx", pieceSetup, repeatX, repeatY), GetBackdropCoordValue("ULy", pieceSetup, repeatX, repeatY),
GetBackdropCoordValue("LLx", pieceSetup, repeatX, repeatY), GetBackdropCoordValue("LLy", pieceSetup, repeatX, repeatY),
GetBackdropCoordValue("URx", pieceSetup, repeatX, repeatY), GetBackdropCoordValue("URy", pieceSetup, repeatX, repeatY),
GetBackdropCoordValue("LRx", pieceSetup, repeatX, repeatY), GetBackdropCoordValue("LRy", pieceSetup, repeatX, repeatY));
end
function BackdropTemplateMixin:SetupTextureCoordinates()
local width = self:GetWidth();
local height = self:GetHeight();
local effectiveScale = self:GetEffectiveScale();
local edgeSize = self:GetEdgeSize();
local edgeRepeatX = max(0, (width / edgeSize) * effectiveScale - 2 - coordStart);
local edgeRepeatY = max(0, (height / edgeSize) * effectiveScale - 2 - coordStart);
for pieceName, pieceSetup in pairs(textureUVs) do
local region = self[pieceName];
if region then
if pieceName == "Center" then
local repeatX = 1;
local repeatY = 1;
if self.backdropInfo.tile then
local divisor = self.backdropInfo.tileSize;
if not divisor or divisor == 0 then
divisor = edgeSize;
end
if divisor ~= 0 then
repeatX = (width / divisor) * effectiveScale;
repeatY = (height / divisor) * effectiveScale;
end
end
SetupBackdropTextureCoordinates(region, pieceSetup, repeatX, repeatY);
else
SetupBackdropTextureCoordinates(region, pieceSetup, edgeRepeatX, edgeRepeatY);
end
end
end
end
function BackdropTemplateMixin:SetupPieceVisuals(piece, setupInfo, pieceLayout)
local textureInfo = textureUVs[setupInfo.pieceName];
local tileVerts = false;
local file;
if setupInfo.pieceName == "Center" then
file = self.backdropInfo.bgFile;
tileVerts = self.backdropInfo.tile;
else
if self.backdropInfo.tileEdge ~= false then
tileVerts = true;
end
file = self.backdropInfo.edgeFile;
end
piece:SetTexture(file, tileVerts, tileVerts);
local cornerWidth = textureInfo.setWidth and self:GetEdgeSize() or 0;
local cornerHeight = textureInfo.setHeight and self:GetEdgeSize() or 0;
piece:SetSize(cornerWidth, cornerHeight);
end
function BackdropTemplateMixin:SetBorderBlendMode(blendMode)
if not self.backdropInfo then
return;
end
for pieceName in pairs(textureUVs) do
local region = self[pieceName];
if region and pieceName ~= "Center" then
region:SetBlendMode(blendMode);
end
end
end
function BackdropTemplateMixin:HasBackdropInfo(backdropInfo)
return self.backdropInfo == backdropInfo;
end
function BackdropTemplateMixin:ClearBackdrop()
if self.backdropInfo then
for pieceName in pairs(textureUVs) do
local region = self[pieceName];
if region then
region:SetTexture(nil);
end
end
self.backdropInfo = nil;
end
end
function BackdropTemplateMixin:ApplyBackdrop()
local x, y, x1, y1 = 0, 0, 0, 0;
if self.backdropInfo.bgFile then
local edgeSize = self:GetEdgeSize();
x = -edgeSize;
y = edgeSize;
x1 = edgeSize;
y1 = -edgeSize;
local insets = self.backdropInfo.insets;
if insets then
x = x + (insets.left or 0);
y = y - (insets.top or 0);
x1 = x1 - (insets.right or 0);
y1 = y1 + (insets.bottom or 0);
end
end
local layout = {
TopLeftCorner = { },
TopRightCorner = { },
BottomLeftCorner = { },
BottomRightCorner = { },
TopEdge = { },
BottomEdge = { },
LeftEdge = { },
RightEdge = { },
Center = { layer = "BACKGROUND", x = x, y = y, x1 = x1, y1 = y1 },
setupPieceVisualsFunction = BackdropTemplateMixin.SetupPieceVisuals,
};
NineSliceUtil.ApplyLayout(self, layout);
--self:SetBackdropColor(1, 1, 1, 1);
--self:SetBackdropBorderColor(1, 1, 1, 1);
self:SetupTextureCoordinates();
end
-- backwards compatibility API starts here
function BackdropTemplateMixin:SetBackdrop(backdropInfo)
if backdropInfo then
if self:HasBackdropInfo(backdropInfo) then
return;
end
if not backdropInfo.edgeFile and not backdropInfo.bgFile then
self:ClearBackdrop();
return;
end
self.backdropInfo = backdropInfo;
self:ApplyBackdrop();
else
self:ClearBackdrop();
end
end
function BackdropTemplateMixin:GetBackdrop()
if self.backdropInfo then
-- make a copy because it will be altered to match old API output
local backdropInfo = CopyTable(self.backdropInfo);
-- fill in defaults
if not backdropInfo.bgFile then
backdropInfo.bgFile = "";
end
if not backdropInfo.edgeFile then
backdropInfo.edgeFile = "";
end
if backdropInfo.tile == nil then
backdropInfo.tile = false;
end
if backdropInfo.tileSize == nil then
backdropInfo.tileSize = 0;
end
if backdropInfo.tileEdge == nil then
backdropInfo.tileEdge = true;
end
if not backdropInfo.edgeSize then
backdropInfo.edgeSize = self:GetEdgeSize();
end
if not backdropInfo.insets then
backdropInfo.insets = { };
end
if not backdropInfo.insets.left then
backdropInfo.insets.left = 0;
end
if not backdropInfo.insets.right then
backdropInfo.insets.right = 0;
end
if not backdropInfo.insets.top then
backdropInfo.insets.top = 0;
end
if not backdropInfo.insets.bottom then
backdropInfo.insets.bottom = 0;
end
return backdropInfo;
end
return nil;
end
function BackdropTemplateMixin:GetBackdropColor()
if not self.backdropInfo then
return;
end
if self.Center then
return self.Center:GetVertexColor();
end
end
function BackdropTemplateMixin:SetBackdropColor(r, g, b, a)
if not self.backdropInfo then
-- Ideally this would throw an error here but the old API just failed silently
return;
end
if self.Center then
self.Center:SetVertexColor(r, g, b, a or 1);
end
end
function BackdropTemplateMixin:GetBackdropBorderColor()
if not self.backdropInfo then
return
end
-- return the vertex color of any valid region
for pieceName in pairs(textureUVs) do
local region = self[pieceName];
if region and pieceName ~= "Center" then
return region:GetVertexColor();
end
end
end
function BackdropTemplateMixin:SetBackdropBorderColor(r, g, b, a)
if not self.backdropInfo then
-- Ideally this would throw an error here but the old API just failed silently
return;
end
for pieceName in pairs(textureUVs) do
local region = self[pieceName];
if region and pieceName ~= "Center" then
region:SetVertexColor(r, g, b, a or 1);
end
end
end
@@ -0,0 +1,15 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
<Script file="Backdrop.lua" />
<Frame name="BackdropTemplate" virtual="true">
<Scripts>
<OnLoad>
Mixin(self, BackdropTemplateMixin)
</OnLoad>
<OnSizeChanged>
self:OnBackdropLoaded()
self:OnBackdropSizeChanged()
</OnSizeChanged>
</Scripts>
</Frame>
</Ui>
@@ -0,0 +1,33 @@
-- Simplified Menu Display System
-- This is a basic system for displaying a menu from a structure table.
--
-- See UIDropDownMenu.lua for the menuList details.
--
-- Args:
-- menuList - menu table
-- menuFrame - the UI frame to populate
-- anchor - where to anchor the frame (e.g. CURSOR)
-- x - x offset
-- y - y offset
-- displayMode - border type
-- autoHideDelay - how long until the menu disappears
--
--
function C_EasyMenu(menuList, menuFrame, anchor, x, y, displayMode, autoHideDelay )
if ( displayMode == "MENU" ) then
menuFrame.displayMode = displayMode;
end
C_UIDropDownMenu_Initialize(menuFrame, EasyMenu_Initialize, displayMode, nil, menuList);
C_ToggleDropDownMenu(1, nil, menuFrame, anchor, x, y, menuList);
end
function C_EasyMenu_Initialize( frame, level, menuList )
for index = 1, #menuList do
local value = menuList[index]
if (value.text) then
value.index = index;
C_UIDropDownMenu_AddButton( value, level );
end
end
end
@@ -0,0 +1,371 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
<Button name="C_UIDropDownMenuButtonTemplate" virtual="true">
<Size x="100" y="16"/>
<Layers>
<Layer level="BACKGROUND">
<Texture name="$parentHighlight" file="Interface\QuestFrame\UI-QuestTitleHighlight" alphaMode="ADD" setAllPoints="true" hidden="true"/>
</Layer>
<Layer level="ARTWORK">
<Texture name="$parentCheck" file="Interface\Buttons\UI-CheckBox-Check">
<Size x="18" y="18"/>
<Anchors>
<Anchor point="LEFT">
<Offset x="0" y="0"/>
</Anchor>
</Anchors>
</Texture>
<Texture name="$parentIcon" hidden="true">
<Size>
<AbsDimension x="16" y="16"/>
</Size>
<Anchors>
<Anchor point="RIGHT">
<Offset x="0" y="0"/>
</Anchor>
</Anchors>
</Texture>
</Layer>
</Layers>
<Frames>
<Button name="$parentColorSwatch" hidden="true">
<Size>
<AbsDimension x="16" y="16"/>
</Size>
<Anchors>
<Anchor point="RIGHT">
<Offset>
<AbsDimension x="-6" y="0"/>
</Offset>
</Anchor>
</Anchors>
<Layers>
<Layer level="BACKGROUND">
<Texture name="$parentSwatchBg">
<Size>
<AbsDimension x="14" y="14"/>
</Size>
<Anchors>
<Anchor point="CENTER">
<Offset>
<AbsDimension x="0" y="0"/>
</Offset>
</Anchor>
</Anchors>
<Color r="1.0" g="1.0" b="1.0"/>
</Texture>
</Layer>
</Layers>
<Scripts>
<OnClick>
CloseMenus();
C_UIDropDownMenuButton_OpenColorPicker(self:GetParent());
</OnClick>
<OnEnter>
C_CloseDropDownMenus(self:GetParent():GetParent():GetID() + 1);
_G[self:GetName().."SwatchBg"]:SetVertexColor(NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b);
C_UIDropDownMenu_StopCounting(self:GetParent():GetParent());
</OnEnter>
<OnLeave>
_G[self:GetName().."SwatchBg"]:SetVertexColor(HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b);
C_UIDropDownMenu_StartCounting(self:GetParent():GetParent());
</OnLeave>
</Scripts>
<NormalTexture name="$parentNormalTexture" file="Interface\ChatFrame\ChatFrameColorSwatch"/>
</Button>
<Button name="$parentExpandArrow" hidden="true">
<Size>
<AbsDimension x="16" y="16"/>
</Size>
<Anchors>
<Anchor point="RIGHT">
<Offset>
<AbsDimension x="0" y="0"/>
</Offset>
</Anchor>
</Anchors>
<Scripts>
<OnClick>
C_ToggleDropDownMenu(self:GetParent():GetParent():GetID() + 1, self:GetParent().value, nil, nil, nil, nil, self:GetParent().menuList, self);
</OnClick>
<OnEnter>
local level = self:GetParent():GetParent():GetID() + 1;
local listFrame = _G["C_DropDownList"..level];
if ( not listFrame or not listFrame:IsShown() or select(2, listFrame:GetPoint()) ~= self ) then
C_ToggleDropDownMenu(level, self:GetParent().value, nil, nil, nil, nil, self:GetParent().menuList, self);
end
C_UIDropDownMenu_StopCounting(self:GetParent():GetParent());
</OnEnter>
<OnLeave>
C_UIDropDownMenu_StartCounting(self:GetParent():GetParent());
</OnLeave>
</Scripts>
<NormalTexture file="Interface\ChatFrame\ChatFrameExpandArrow"/>
</Button>
<Button name="$parentInvisibleButton" hidden="true">
<Anchors>
<Anchor point="TOPLEFT"/>
<Anchor point="BOTTOMLEFT"/>
<Anchor point="RIGHT" relativeTo="$parentColorSwatch" relativePoint="LEFT">
<Offset>
<AbsDimension x="0" y="0"/>
</Offset>
</Anchor>
</Anchors>
<Scripts>
<OnEnter>
C_UIDropDownMenu_StopCounting(self:GetParent():GetParent());
C_CloseDropDownMenus(self:GetParent():GetParent():GetID() + 1);
local parent = self:GetParent();
if ( parent.tooltipTitle and parent.tooltipWhileDisabled) then
if ( parent.tooltipOnButton ) then
GameTooltip:SetOwner(parent, "ANCHOR_RIGHT");
GameTooltip:AddLine(parent.tooltipTitle, 1.0, 1.0, 1.0);
GameTooltip:AddLine(parent.tooltipText);
GameTooltip:Show();
else
GameTooltip_AddNewbieTip(parent, parent.tooltipTitle, 1.0, 1.0, 1.0, parent.tooltipText, 1);
end
end
</OnEnter>
<OnLeave>
C_UIDropDownMenu_StartCounting(self:GetParent():GetParent());
GameTooltip:Hide();
</OnLeave>
</Scripts>
</Button>
</Frames>
<Scripts>
<OnLoad>
self:SetFrameLevel(2);
</OnLoad>
<OnClick>
C_UIDropDownMenuButton_OnClick(self, button, down);
</OnClick>
<OnEnter>
if ( self.hasArrow ) then
local level = self:GetParent():GetID() + 1;
local listFrame = _G["C_DropDownList"..level];
if ( not listFrame or not listFrame:IsShown() or select(2, listFrame:GetPoint()) ~= self ) then
C_ToggleDropDownMenu(self:GetParent():GetID() + 1, self.value, nil, nil, nil, nil, self.menuList, self);
end
else
C_CloseDropDownMenus(self:GetParent():GetID() + 1);
end
_G[self:GetName().."Highlight"]:Show();
C_UIDropDownMenu_StopCounting(self:GetParent());
if ( self.tooltipTitle ) then
if ( self.tooltipOnButton ) then
GameTooltip:SetOwner(self, "ANCHOR_RIGHT");
GameTooltip:AddLine(self.tooltipTitle, 1.0, 1.0, 1.0);
GameTooltip:AddLine(self.tooltipText);
GameTooltip:Show();
else
GameTooltip_AddNewbieTip(self, self.tooltipTitle, 1.0, 1.0, 1.0, self.tooltipText, 1);
end
end
</OnEnter>
<OnLeave>
_G[self:GetName().."Highlight"]:Hide();
C_UIDropDownMenu_StartCounting(self:GetParent());
GameTooltip:Hide();
</OnLeave>
</Scripts>
<ButtonText name="$parentNormalText">
<Anchors>
<Anchor point="LEFT">
<Offset x="-5" y="0"/>
</Anchor>
</Anchors>
</ButtonText>
<NormalFont style="GameFontHighlightSmallLeft"/>
<HighlightFont style="GameFontHighlightSmallLeft"/>
<DisabledFont style="GameFontDisableSmallLeft"/>
</Button>
<Button name="C_UIDropDownListTemplate" hidden="true" frameStrata="DIALOG" enableMouse="true" virtual="true">
<Frames>
<Frame name="$parentBackdrop" setAllPoints="true">
<Backdrop bgFile="Interface\DialogFrame\UI-DialogBox-Background-Dark" edgeFile="Interface\DialogFrame\UI-DialogBox-Border" tile="true">
<BackgroundInsets>
<AbsInset left="11" right="12" top="12" bottom="9"/>
</BackgroundInsets>
<TileSize>
<AbsValue val="32"/>
</TileSize>
<EdgeSize>
<AbsValue val="32"/>
</EdgeSize>
</Backdrop>
</Frame>
<Frame name="$parentMenuBackdrop" setAllPoints="true">
<Backdrop bgFile="Interface\Tooltips\UI-Tooltip-Background" edgeFile="Interface\Tooltips\UI-Tooltip-Border" tile="true">
<EdgeSize>
<AbsValue val="16"/>
</EdgeSize>
<TileSize>
<AbsValue val="16"/>
</TileSize>
<BackgroundInsets>
<AbsInset left="5" right="5" top="5" bottom="4"/>
</BackgroundInsets>
</Backdrop>
<Scripts>
<OnLoad>
self:SetBackdropBorderColor(TOOLTIP_DEFAULT_COLOR.r, TOOLTIP_DEFAULT_COLOR.g, TOOLTIP_DEFAULT_COLOR.b);
self:SetBackdropColor(TOOLTIP_DEFAULT_BACKGROUND_COLOR.r, TOOLTIP_DEFAULT_BACKGROUND_COLOR.g, TOOLTIP_DEFAULT_BACKGROUND_COLOR.b);
</OnLoad>
</Scripts>
</Frame>
<Button name="$parentButton1" inherits="C_UIDropDownMenuButtonTemplate" id="1"/>
<Button name="$parentButton2" inherits="C_UIDropDownMenuButtonTemplate" id="2"/>
<Button name="$parentButton3" inherits="C_UIDropDownMenuButtonTemplate" id="3"/>
<Button name="$parentButton4" inherits="C_UIDropDownMenuButtonTemplate" id="4"/>
<Button name="$parentButton5" inherits="C_UIDropDownMenuButtonTemplate" id="5"/>
<Button name="$parentButton6" inherits="C_UIDropDownMenuButtonTemplate" id="6"/>
<Button name="$parentButton7" inherits="C_UIDropDownMenuButtonTemplate" id="7"/>
<Button name="$parentButton8" inherits="C_UIDropDownMenuButtonTemplate" id="8"/>
</Frames>
<Scripts>
<OnClick>
self:Hide();
</OnClick>
<OnEnter>
C_UIDropDownMenu_StopCounting(self, motion);
</OnEnter>
<OnLeave>
C_UIDropDownMenu_StartCounting(self, motion);
</OnLeave>
<OnUpdate>
C_UIDropDownMenu_OnUpdate(self, elapsed);
</OnUpdate>
<OnShow>
for i=1, C_UIDROPDOWNMENU_MAXBUTTONS do
if (not self.noResize) then
_G[self:GetName().."Button"..i]:SetWidth(self.maxWidth);
end
end
if (not self.noResize) then
self:SetWidth(self.maxWidth+25);
end
self.showTime = nil;
if ( self:GetID() > 1 ) then
self.parent = _G["C_DropDownList"..(self:GetID() - 1)];
end
</OnShow>
<OnHide>
C_UIDropDownMenu_OnHide(self);
</OnHide>
</Scripts>
</Button>
<Frame name="C_UIDropDownMenuTemplate" virtual="true">
<Size>
<AbsDimension x="40" y="32"/>
</Size>
<Layers>
<Layer level="ARTWORK">
<Texture name="$parentLeft" file="Interface\Glues\CharacterCreate\CharacterCreate-LabelFrame">
<Size>
<AbsDimension x="25" y="64"/>
</Size>
<Anchors>
<Anchor point="TOPLEFT">
<Offset>
<AbsDimension x="0" y="17"/>
</Offset>
</Anchor>
</Anchors>
<TexCoords left="0" right="0.1953125" top="0" bottom="1"/>
</Texture>
<Texture name="$parentMiddle" file="Interface\Glues\CharacterCreate\CharacterCreate-LabelFrame">
<Size>
<AbsDimension x="115" y="64"/>
</Size>
<Anchors>
<Anchor point="LEFT" relativeTo="$parentLeft" relativePoint="RIGHT"/>
</Anchors>
<TexCoords left="0.1953125" right="0.8046875" top="0" bottom="1"/>
</Texture>
<Texture name="$parentRight" file="Interface\Glues\CharacterCreate\CharacterCreate-LabelFrame">
<Size>
<AbsDimension x="25" y="64"/>
</Size>
<Anchors>
<Anchor point="LEFT" relativeTo="$parentMiddle" relativePoint="RIGHT"/>
</Anchors>
<TexCoords left="0.8046875" right="1" top="0" bottom="1"/>
</Texture>
<FontString name="$parentText" inherits="GameFontHighlightSmall" justifyH="RIGHT">
<Size>
<AbsDimension x="0" y="10"/>
</Size>
<Anchors>
<Anchor point="RIGHT" relativeTo="$parentRight">
<Offset>
<AbsDimension x="-43" y="2"/>
</Offset>
</Anchor>
</Anchors>
</FontString>
</Layer>
</Layers>
<Frames>
<Button name="$parentButton">
<Size>
<AbsDimension x="24" y="24"/>
</Size>
<Anchors>
<Anchor point="TOPRIGHT" relativeTo="$parentRight">
<Offset>
<AbsDimension x="-16" y="-18"/>
</Offset>
</Anchor>
</Anchors>
<Scripts>
<OnClick>
C_ToggleDropDownMenu(nil, nil, self:GetParent());
PlaySound("igMainMenuOptionCheckBoxOn");
</OnClick>
</Scripts>
<NormalTexture name="$parentNormalTexture" file="Interface\ChatFrame\UI-ChatIcon-ScrollDown-Up">
<Size>
<AbsDimension x="24" y="24"/>
</Size>
<Anchors>
<Anchor point="RIGHT"/>
</Anchors>
</NormalTexture>
<PushedTexture name="$parentPushedTexture" file="Interface\ChatFrame\UI-ChatIcon-ScrollDown-Down">
<Size>
<AbsDimension x="24" y="24"/>
</Size>
<Anchors>
<Anchor point="RIGHT"/>
</Anchors>
</PushedTexture>
<DisabledTexture name="$parentDisabledTexture" file="Interface\ChatFrame\UI-ChatIcon-ScrollDown-Disabled">
<Size>
<AbsDimension x="24" y="24"/>
</Size>
<Anchors>
<Anchor point="RIGHT"/>
</Anchors>
</DisabledTexture>
<HighlightTexture name="$parentHighlightTexture" file="Interface\Buttons\UI-Common-MouseHilight" alphaMode="ADD">
<Size>
<AbsDimension x="24" y="24"/>
</Size>
<Anchors>
<Anchor point="RIGHT"/>
</Anchors>
</HighlightTexture>
</Button>
</Frames>
<Scripts>
<OnHide>
C_CloseDropDownMenus();
</OnHide>
</Scripts>
</Frame>
<Script file="C_UIDropDownMenu.lua" />
<Script file="C_EasyMenu.lua" />
</Ui>
@@ -0,0 +1,13 @@
local WIDTH, HEIGHT = 858, 660
local IOF = InterfaceOptionsFrame
IOF:SetPoint("CENTER", UIParent, "CENTER")
InterfaceOptionsFrameCategories:SetPoint("BOTTOMLEFT", IOF, "BOTTOMLEFT", 22, 50)
InterfaceOptionsFrameAddOns:SetPoint("BOTTOMLEFT", IOF, "BOTTOMLEFT", 22, 50)
IOF:SetSize(WIDTH, HEIGHT)
IOF:SetToplevel(true)
IOF:HookScript("OnShow", function()
IOF:SetSize(WIDTH, HEIGHT)
end)
@@ -0,0 +1,9 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
<Include file="XML_Helper.lua" />
<Include file="Backdrop.xml" />
<Include file="UIPanelTemplates.xml" />
<Include file="C_UIDropDownMenu.xml" />
<Script file="InterfaceOptions.lua" />
</Ui>
@@ -0,0 +1,50 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
<Button name="UIPanelButtonNoTooltipTemplate" virtual="true">
<Size x="40" y="22" />
<Layers>
<Layer level="BACKGROUND">
<Texture parentKey="Left" file="Interface\Buttons\UI-Panel-Button-Up">
<Size x="12" y="22" />
<Anchors>
<Anchor point="TOPLEFT" />
<Anchor point="BOTTOMLEFT" />
</Anchors>
<TexCoords left="0" right="0.09375" top="0" bottom="0.6875" />
</Texture>
<Texture parentKey="Right" file="Interface\Buttons\UI-Panel-Button-Up">
<Size x="12" y="22" />
<Anchors>
<Anchor point="TOPRIGHT" />
<Anchor point="BOTTOMRIGHT" />
</Anchors>
<TexCoords left="0.53125" right="0.625" top="0" bottom="0.6875" />
</Texture>
<Texture parentKey="Middle" file="Interface\Buttons\UI-Panel-Button-Up">
<Size x="12" y="22" />
<Anchors>
<Anchor point="TOPLEFT" relativeKey="$parent.Left" relativePoint="TOPRIGHT" />
<Anchor point="BOTTOMRIGHT" relativeKey="$parent.Right" relativePoint="BOTTOMLEFT" />
</Anchors>
<TexCoords left="0.09375" right="0.53125" top="0" bottom="0.6875" />
</Texture>
</Layer>
</Layers>
<Scripts>
<OnLoad function="UIPanelButton_OnLoad" />
<OnMouseDown function="UIPanelButton_OnMouseDown" />
<OnMouseUp function="UIPanelButton_OnMouseUp" />
<OnShow function="UIPanelButton_OnShow" />
<OnDisable function="UIPanelButton_OnDisable" />
<OnEnable function="UIPanelButton_OnEnable" />
</Scripts>
<ButtonText name="$parentText" parentKey="Text" />
<NormalFont style="GameFontNormal" />
<HighlightFont style="GameFontHighlight" />
<DisabledFont style="GameFontDisable" />
<HighlightTexture inherits="UIPanelButtonHighlightTexture" />
</Button>
</Ui>
@@ -0,0 +1,62 @@
--[[
Search Box Template
]]
function InputBoxInstructions_OnTextChanged(self)
self.Instructions:SetShown(self:GetText() == "")
end
function InputBoxInstructions_UpdateColorForEnabledState(self, color)
if color then
self:SetTextColor(color:GetRGBA());
end
end
function InputBoxInstructions_OnDisable(self)
InputBoxInstructions_UpdateColorForEnabledState(self, self.disabledColor);
end
function InputBoxInstructions_OnEnable(self)
InputBoxInstructions_UpdateColorForEnabledState(self, self.enabledColor);
end
function SearchBoxTemplate_OnLoad(self)
self.searchIcon:SetVertexColor(0.6, 0.6, 0.6);
self:SetTextInsets(16, 20, 0, 0);
self.Instructions:SetText(SEARCH);
self.Instructions:ClearAllPoints();
self.Instructions:SetPoint("TOPLEFT", self, "TOPLEFT", 16, 0);
self.Instructions:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", -20, 0);
end
function SearchBoxTemplate_OnEditFocusLost(self)
if ( self:GetText() == "" ) then
self.searchIcon:SetVertexColor(0.6, 0.6, 0.6);
self.clearButton:Hide();
end
end
function SearchBoxTemplate_OnEditFocusGained(self)
self.searchIcon:SetVertexColor(1.0, 1.0, 1.0);
self.clearButton:Show();
end
function SearchBoxTemplate_OnTextChanged(self)
if ( not self:HasFocus() and self:GetText() == "" ) then
self.searchIcon:SetVertexColor(0.6, 0.6, 0.6);
self.clearButton:Hide();
else
self.searchIcon:SetVertexColor(1.0, 1.0, 1.0);
self.clearButton:Show();
end
InputBoxInstructions_OnTextChanged(self);
end
function SearchBoxTemplateClearButton_OnClick(self)
--PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON);
local editBox = self:GetParent();
editBox:SetText("");
editBox:ClearFocus();
end
@@ -0,0 +1,312 @@
<Ui xmlns="http://www.blizzard.com/wow/ui/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.blizzard.com/wow/ui/
..\FrameXML\UI.xsd">
<Script file="SharedUIPanelTemplates.lua" />
<EditBox name="InputBoxInstructionsTemplate" inherits="InputBoxTemplate" virtual="true">
<!--KeyValues>
Optional
<KeyValue key="disabledColor" value="GRAY_FONT_COLOR" type="global"/>
<KeyValue key="enabledColor" value="HIGHLIGHT_FONT_COLOR" type="global"/>
</KeyValues-->
<Layers>
<Layer level="ARTWORK">
<FontString parentKey="Instructions" justifyH="LEFT" justifyV="MIDDLE" inherits="GameFontDisableSmall" setAllPoints="true">
<Color r="0.35" g="0.35" b="0.35"/>
</FontString>
</Layer>
</Layers>
<Scripts>
<OnTextChanged function="InputBoxInstructions_OnTextChanged"/>
<OnDisable function="InputBoxInstructions_OnDisable"/>
<OnEnable function="InputBoxInstructions_OnEnable"/>
</Scripts>
<FontString inherits="GameFontHighlightSmall"/>
</EditBox>
<EditBox name="SearchBoxTemplate" inherits="InputBoxInstructionsTemplate" autoFocus="false" virtual="true">
<Layers>
<Layer level="OVERLAY">
<Texture name="$parentSearchIcon" atlas="common-search-magnifyingglass" useAtlasSize="false" parentKey="searchIcon">
<Size x="10" y="10"/>
<Anchors>
<Anchor point="LEFT" x="1" y="-1"/>
</Anchors>
</Texture>
</Layer>
</Layers>
<Frames>
<Button name="$parentClearButton" parentKey="clearButton" hidden="true">
<Size x="17" y="17"/>
<Anchors>
<Anchor point="RIGHT" x="-3" y="0"/>
</Anchors>
<Layers>
<Layer level="ARTWORK">
<Texture atlas="common-search-clearbutton" useAtlasSize="false" alpha="0.5" parentKey="texture">
<Size x="10" y="10"/>
<Anchors>
<Anchor point="TOPLEFT" x="3" y="-3"/>
</Anchors>
</Texture>
</Layer>
</Layers>
<Scripts>
<OnEnter>
self.texture:SetAlpha(1.0);
</OnEnter>
<OnLeave>
self.texture:SetAlpha(0.5);
</OnLeave>
<OnMouseDown>
if self:IsEnabled() then
self.texture:SetPoint("TOPLEFT", self, "TOPLEFT", 4, -4);
end
</OnMouseDown>
<OnMouseUp>
self.texture:SetPoint("TOPLEFT", self, "TOPLEFT", 3, -3);
</OnMouseUp>
<OnClick function="SearchBoxTemplateClearButton_OnClick"/>
</Scripts>
</Button>
</Frames>
<Scripts>
<OnLoad function="SearchBoxTemplate_OnLoad"/>
<OnEscapePressed function="EditBox_ClearFocus"/>
<OnEnterPressed function="EditBox_ClearFocus"/>
<OnEditFocusLost function="SearchBoxTemplate_OnEditFocusLost"/>
<OnEditFocusGained function="SearchBoxTemplate_OnEditFocusGained"/>
<OnTextChanged function="SearchBoxTemplate_OnTextChanged"/>
</Scripts>
</EditBox>
<Slider name="HorizontalSliderTemplate" orientation="HORIZONTAL" enableMouse="true" virtual="true" inherits="BackdropTemplate">
<HitRectInsets>
<AbsInset left="0" right="0" top="-10" bottom="-10" />
</HitRectInsets>
<ThumbTexture parentKey="Thumb" name="$parentThumb" file="Interface\Buttons\UI-SliderBar-Button-Horizontal">
<Size x="32" y="32" />
</ThumbTexture>
<Scripts>
<OnLoad>
self.backdropInfo = _G["BACKDROP_SLIDER_8_8"]
</OnLoad>
</Scripts>
</Slider>
<Frame name="DialogBorderNoCenterTemplate" useParentLevel="true" frameLevel="15" setAllPoints="true" virtual="true">
<Scripts>
<OnLoad>
self.layoutType = "Dialog"
Mixin(self, NineSlicePanelMixin)
self:OnLoad()
</OnLoad>
</Scripts>
</Frame>
<Frame name="DialogBorderDarkTemplate" inherits="DialogBorderNoCenterTemplate" virtual="true">
<Layers>
<Layer level="BACKGROUND">
<!-- TODO: Convert this to atlas -->
<Texture parentKey="Bg" file="Interface\DialogFrame\UI-DialogBox-Background-Dark" horizTile="true" vertTile="true">
<Anchors>
<Anchor point="TOPLEFT" x="7" y="-7" />
<Anchor point="BOTTOMRIGHT" x="-7" y="7" />
</Anchors>
</Texture>
</Layer>
</Layers>
</Frame>
<Button name="UIPanelInfoButton" virtual="true">
<Size>
<AbsDimension x="16" y="16" />
</Size>
<Layers>
<Layer level="ARTWORK">
<Texture name="$parentTexture" file="Interface\FriendsFrame\InformationIcon" parentKey="texture">
<Anchors>
<Anchor point="TOPLEFT" />
</Anchors>
</Texture>
</Layer>
</Layers>
<Scripts>
<OnMouseDown>
self.texture:SetPoint("TOPLEFT", 1, -1);
</OnMouseDown>
<OnMouseUp>
self.texture:SetPoint("TOPLEFT", 0, 0);
</OnMouseUp>
</Scripts>
<HighlightTexture file="Interface\FriendsFrame\InformationIcon-Highlight" alphaMode="ADD">
<Anchors>
<Anchor point="TOPLEFT" relativeTo="$parentTexture" relativePoint="TOPLEFT" />
</Anchors>
<Color r="1" g="1" b="1" a="0.4" />
</HighlightTexture>
</Button>
<Button name="UIMenuButtonStretchTemplate" virtual="true">
<Size x="40" y="26" />
<Layers>
<Layer level="BORDER">
<Texture parentKey="TopLeft" name="$parentTopLeft" file="Interface\Buttons\UI-Silver-Button-Up">
<Size x="12" y="6" />
<Anchors>
<Anchor point="TOPLEFT" />
</Anchors>
<TexCoords left="0" right="0.09375" top="0" bottom="0.1875" />
</Texture>
<Texture parentKey="TopRight" name="$parentTopRight" file="Interface\Buttons\UI-Silver-Button-Up">
<Size x="12" y="6" />
<Anchors>
<Anchor point="TOPRIGHT" />
</Anchors>
<TexCoords left="0.53125" right="0.625" top="0" bottom="0.1875" />
</Texture>
<Texture parentKey="BottomLeft" name="$parentBottomLeft" file="Interface\Buttons\UI-Silver-Button-Up">
<Size x="12" y="6" />
<Anchors>
<Anchor point="BOTTOMLEFT" />
</Anchors>
<TexCoords left="0" right="0.09375" top="0.625" bottom="0.8125" />
</Texture>
<Texture parentKey="BottomRight" name="$parentBottomRight" file="Interface\Buttons\UI-Silver-Button-Up">
<Size x="12" y="6" />
<Anchors>
<Anchor point="BOTTOMRIGHT" />
</Anchors>
<TexCoords left="0.53125" right="0.625" top="0.625" bottom="0.8125" />
</Texture>
<Texture parentKey="TopMiddle" name="$parentTopMiddle" file="Interface\Buttons\UI-Silver-Button-Up">
<Size x="56" y="6" />
<Anchors>
<Anchor point="TOPLEFT" relativeTo="$parentTopLeft" relativePoint="TOPRIGHT" />
<Anchor point="BOTTOMRIGHT" relativeTo="$parentTopRight" relativePoint="BOTTOMLEFT" />
</Anchors>
<TexCoords left="0.09375" right="0.53125" top="0" bottom="0.1875" />
</Texture>
<Texture parentKey="MiddleLeft" name="$parentMiddleLeft" file="Interface\Buttons\UI-Silver-Button-Up">
<Size x="12" y="14" />
<Anchors>
<Anchor point="TOPRIGHT" relativeTo="$parentTopLeft" relativePoint="BOTTOMRIGHT" />
<Anchor point="BOTTOMLEFT" relativeTo="$parentBottomLeft" relativePoint="TOPLEFT" />
</Anchors>
<TexCoords left="0" right="0.09375" top="0.1875" bottom="0.625" />
</Texture>
<Texture parentKey="MiddleRight" name="$parentMiddleRight" file="Interface\Buttons\UI-Silver-Button-Up">
<Size x="12" y="14" />
<Anchors>
<Anchor point="TOPRIGHT" relativeTo="$parentTopRight" relativePoint="BOTTOMRIGHT" />
<Anchor point="BOTTOMLEFT" relativeTo="$parentBottomRight" relativePoint="TOPLEFT" />
</Anchors>
<TexCoords left="0.53125" right="0.625" top="0.1875" bottom="0.625" />
</Texture>
<Texture parentKey="BottomMiddle" name="$parentBottomMiddle" file="Interface\Buttons\UI-Silver-Button-Up">
<Size x="56" y="6" />
<Anchors>
<Anchor point="TOPLEFT" relativeTo="$parentBottomLeft" relativePoint="TOPRIGHT" />
<Anchor point="BOTTOMRIGHT" relativeTo="$parentBottomRight" relativePoint="BOTTOMLEFT" />
</Anchors>
<TexCoords left="0.09375" right="0.53125" top="0.625" bottom="0.8125" />
</Texture>
<Texture parentKey="MiddleMiddle" name="$parentMiddleMiddle" file="Interface\Buttons\UI-Silver-Button-Up">
<Size x="56" y="14" />
<Anchors>
<Anchor point="TOPLEFT" relativeTo="$parentTopLeft" relativePoint="BOTTOMRIGHT" />
<Anchor point="BOTTOMRIGHT" relativeTo="$parentBottomRight" relativePoint="TOPLEFT" />
</Anchors>
<TexCoords left="0.09375" right="0.53125" top="0.1875" bottom="0.625" />
</Texture>
</Layer>
</Layers>
<Scripts>
<OnMouseDown>
if self:IsEnabled() ~= 0 then
self.TopLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Down")
self.TopRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Down")
self.BottomLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Down")
self.BottomRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Down")
self.TopMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Down")
self.MiddleLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Down")
self.MiddleRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Down")
self.BottomMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Down")
self.MiddleMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Down")
if ( self.Icon ) then
if ( not self.Icon.oldPoint ) then
local point, relativeTo, relativePoint, x, y = self.Icon:GetPoint(1)
self.Icon.oldPoint = point
self.Icon.oldX = x
self.Icon.oldY = y
end
self.Icon:SetPoint(self.Icon.oldPoint, self.Icon.oldX + 1, self.Icon.oldY - 1)
end
end
</OnMouseDown>
<OnMouseUp>
if self:IsEnabled() ~= 0 then
self.TopLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.TopRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.BottomLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.BottomRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.TopMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.MiddleLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.MiddleRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.BottomMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.MiddleMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
if ( self.Icon ) then
self.Icon:SetPoint(self.Icon.oldPoint, self.Icon.oldX, self.Icon.oldY)
end
end
</OnMouseUp>
<OnShow>
if self:IsEnabled() ~= 0 then
-- we need to reset our textures just in case we were hidden before a mouse up fired
self.TopLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.TopRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.BottomLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.BottomRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.TopMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.MiddleLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.MiddleRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.BottomMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.MiddleMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
end
</OnShow>
<OnEnable>
self.TopLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.TopRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.BottomLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.BottomRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.TopMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.MiddleLeft:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.MiddleRight:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.BottomMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
self.MiddleMiddle:SetTexture("Interface\\Buttons\\UI-Silver-Button-Up")
</OnEnable>
<OnEnter>
if(self.tooltipText ~= nil) then
GameTooltip_AddNewbieTip(self, self.tooltipText, 1.0, 1.0, 1.0, self.newbieText)
end
</OnEnter>
<OnLeave>
if(self.tooltipText ~= nil) then
GameTooltip:Hide()
end
</OnLeave>
</Scripts>
<ButtonText parentKey="Text" name="$parentText">
<Anchors>
<Anchor point="CENTER" x="0" y="-1" />
</Anchors>
</ButtonText>
<NormalFont style="GameFontHighlightSmall" />
<HighlightFont style="GameFontHighlightSmall" />
<DisabledFont style="GameFontDisableSmall" />
<HighlightTexture file="Interface\Buttons\UI-Silver-Button-Highlight" alphaMode="ADD">
<TexCoords left="0" right="1.0" top="0.03" bottom="0.7175" />
</HighlightTexture>
</Button>
</Ui>
@@ -0,0 +1,79 @@
local function UIDropDownMenu_CreateUnChecked(object)
local uncheck = _G[object:GetName().."UnCheck"];
if ( uncheck ) then
return;
end
uncheck = object:CreateTexture("$parentUnCheck", "BORDER");
_G[object:GetName().."UnCheck"] = uncheck;
uncheck:SetSize(16, 16);
uncheck:SetPoint("Left");
end
hooksecurefunc("UIDropDownMenu_AddButton", function(info, level)
if ( not level ) then
level = 1;
end
local listFrame = _G["DropDownList"..level];
local index = listFrame and listFrame.numButtons or 1;
listFrame = listFrame or _G["DropDownList"..level];
local listFrameName = listFrame:GetName();
local button = _G[listFrameName.."Button"..index];
UIDropDownMenu_CreateUnChecked(button);
if ( not info.notCheckable ) then
local check = _G[listFrameName.."Button"..index.."Check"];
local uncheck = _G[listFrameName.."Button"..index.."UnCheck"];
if ( info.disabled ) then
check:SetDesaturated(true);
check:SetAlpha(0.5);
uncheck:SetDesaturated(true);
uncheck:SetAlpha(0.5);
else
check:SetDesaturated(false);
check:SetAlpha(1);
uncheck:SetDesaturated(false);
uncheck:SetAlpha(1);
end
if ( info.isRadio ) then
--check:SetTexCoord(0.0, 0.5, 0.5, 1.0);
check:SetTexCoord(0.25, 0.5, 0, 1);
check:SetTexture("Interface\\Buttons\\UI-RadioButton");
--uncheck:SetTexCoord(0.5, 1.0, 0.5, 1.0);
uncheck:SetTexCoord(0.75, 1, 0, 1);
uncheck:SetTexture("Interface\\Buttons\\UI-RadioButton");
else
check:SetTexCoord(0, 1, 0, 1);
check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check");
end
-- Checked can be a function now
local checked = info.checked;
if ( type(checked) == "function" ) then
checked = checked(button);
end
-- Show the check if checked
if ( checked ) then
button:LockHighlight();
check:Show();
uncheck:Hide();
else
button:UnlockHighlight();
check:Hide();
uncheck:Show();
end
else
_G[listFrameName.."Button"..index.."Check"]:Hide();
_G[listFrameName.."Button"..index.."UnCheck"]:Hide();
end
if ( not info.isRadio ) then
_G[listFrameName.."Button"..index.."UnCheck"]:Hide();
end
button.checked = info.checked;
end)
@@ -0,0 +1,398 @@
function SearchBoxTemplate_OnLoad(self)
self:SetText(SEARCH);
self:SetFontObject("GameFontDisable");
self.searchIcon:SetVertexColor(0.6, 0.6, 0.6);
self:SetTextInsets(16, 20, 0, 0);
end
function SearchBoxTemplate_OnEditFocusLost(self)
self:HighlightText(0, 0);
self:SetFontObject("GameFontDisable");
self.searchIcon:SetVertexColor(0.6, 0.6, 0.6);
if ( self:GetText() == "" or self:GetText() == SEARCH ) then
self:SetText(SEARCH);
self.clearButton:Hide();
end
end
function SerachBoxTemplate_OnEditFocusGained(self)
self:HighlightText();
self:SetFontObject("ChatFontSmall");
self.searchIcon:SetVertexColor(1.0, 1.0, 1.0);
if ( self:GetText() == SEARCH ) then
self:SetText("")
end
self.clearButton:Show();
end
ITEM_SEARCHBAR_LIST = {
"BagItemSearchBox",
"GuildItemSearchBox",
"VoidItemSearchBox",
"BankItemSearchBox",
};
function BagSearch_OnHide(self)
local allClosed = true;
for _,barName in pairs(ITEM_SEARCHBAR_LIST) do
local bar = _G[barName];
if bar and bar ~= self and bar:IsVisible() then
allClosed = false;
end
end
if ( allClosed ) then
self.clearButton:Click();
BagSearch_OnTextChanged(self);
end
end
function BagSearch_OnTextChanged(self, userChanged)
local text = self:GetText();
if ( text == SEARCH ) then
text = "";
end
SetItemSearch(text);
if (text ~= "") then
self.clearButton:Show();
else
self.clearButton:Hide();
end
end
function BagSearch_OnChar(self, text)
-- clear focus if the player is repeating keys (ie - trying to move)
-- TODO: move into base editbox code?
local MIN_REPEAT_CHARACTERS = 3
local searchString = self:GetText();
if (string.len(searchString) > MIN_REPEAT_CHARACTERS) then
local repeatChar = true;
for i=1, MIN_REPEAT_CHARACTERS, 1 do
if ( string.sub(searchString,(0-i), (0-i)) ~= string.sub(searchString,(-1-i),(-1-i)) ) then
repeatChar = false;
break;
end
end
if ( repeatChar ) then
self:ClearFocus();
end
end
end
function BagSearch_OnEditFocusGained(self)
SerachBoxTemplate_OnEditFocusGained(self);
for _,barName in pairs(ITEM_SEARCHBAR_LIST) do
local bar = _G[barName];
if bar and bar ~= self then
bar:SetText(SEARCH);
end
end
end
function BagSearch_OnEditFocusLost(self)
SerachBoxTemplate_OnEditFocusGained(self);
local search = self:GetText();
for _,barName in pairs(ITEM_SEARCHBAR_LIST) do
local bar = _G[barName];
if bar and bar ~= self then
bar:SetText(search);
end
end
end
-- Scrollframe functions
function ScrollBar_AdjustAnchors(scrollBar, topAdj, bottomAdj, xAdj)
-- assumes default anchoring of topleft-topright, bottomleft-bottomright
local topY = 0;
local bottomY = 0;
local point, parent, refPoint, x, y;
for i = 1, 2 do
point, parent, refPoint, x, y = scrollBar:GetPoint(i);
if ( point == "TOPLEFT" ) then
topY = y;
elseif ( point == "BOTTOMLEFT" ) then
bottomY = y;
end
end
xAdj = xAdj or 0;
topAdj = topAdj or 0;
bottomAdj = bottomAdj or 0;
scrollBar:SetPoint("TOPLEFT", parent, "TOPRIGHT", x + xAdj, topY + topAdj);
scrollBar:SetPoint("BOTTOMLEFT", parent, "BOTTOMRIGHT", x + xAdj, bottomY + bottomAdj);
end
-- Truncated Button code
function TruncatedButton_OnEnter(self)
local text = _G[self:GetName().."Text"];
if ( text:IsTruncated() ) then
GameTooltip:SetOwner(self, "ANCHOR_RIGHT");
GameTooltip:SetText(text:GetText());
GameTooltip:Show();
end
end
function TruncatedButton_OnLeave(self)
if ( GameTooltip:GetOwner() == self ) then
GameTooltip:Hide();
end
end
-- Magic Button code
function MagicButton_OnLoad(self)
local leftHandled = false;
local rightHandled = false;
-- Find out where this button is anchored and adjust positions/separators as necessary
for i=1, self:GetNumPoints() do
local point, relativeTo, relativePoint, offsetX, offsetY = self:GetPoint(i);
if (relativeTo:GetObjectType() == "Button" and (point == "TOPLEFT" or point == "LEFT")) then
if (offsetX == 0 and offsetY == 0) then
self:SetPoint(point, relativeTo, relativePoint, 1, 0);
end
if (relativeTo.RightSeparator) then
-- Modify separator to make it a Middle
self.LeftSeparator = relativeTo.RightSeparator;
else
-- Add a Middle separator
self.LeftSeparator = self:CreateTexture(self:GetName().."_LeftSeparator", "BORDER");
relativeTo.RightSeparator = self.LeftSeparator;
end
self.LeftSeparator:SetTexture("Interface\\AddOns\\!!!ClassicAPI\\Texture\\FrameGeneral\\UI-Frame");
self.LeftSeparator:SetTexCoord("0.00781250", "0.10937500", "0.75781250", "0.95312500");
self.LeftSeparator:SetWidth(13);
self.LeftSeparator:SetHeight(25);
self.LeftSeparator:SetPoint("TOPRIGHT", self, "TOPLEFT", 5, 1);
leftHandled = true;
elseif (relativeTo:GetObjectType() == "Button" and (point == "TOPRIGHT" or point == "RIGHT")) then
if (offsetX == 0 and offsetY == 0) then
self:SetPoint(point, relativeTo, relativePoint, -1, 0);
end
if (relativeTo.LeftSeparator) then
-- Modify separator to make it a Middle
self.RightSeparator = relativeTo.LeftSeparator;
else
-- Add a Middle separator
self.RightSeparator = self:CreateTexture(self:GetName().."_RightSeparator", "BORDER");
relativeTo.LeftSeparator = self.RightSeparator;
end
self.RightSeparator:SetTexture("Interface\\AddOns\\!!!ClassicAPI\\Texture\\FrameGeneral\\UI-Frame");
self.RightSeparator:SetTexCoord("0.00781250", "0.10937500", "0.75781250", "0.95312500");
self.RightSeparator:SetWidth(13);
self.RightSeparator:SetHeight(25);
self.RightSeparator:SetPoint("TOPLEFT", self, "TOPRIGHT", -5, 1);
rightHandled = true;
elseif (point == "BOTTOMLEFT") then
if (offsetX == 0 and offsetY == 0) then
self:SetPoint(point, relativeTo, relativePoint, 4, 4);
end
leftHandled = true;
elseif (point == "BOTTOMRIGHT") then
if (offsetX == 0 and offsetY == 0) then
self:SetPoint(point, relativeTo, relativePoint, -6, 4);
end
rightHandled = true;
elseif (point == "BOTTOM") then
if (offsetY == 0) then
self:SetPoint(point, relativeTo, relativePoint, 0, 4);
end
end
end
-- If this button didn't have a left anchor, add the left border texture
if (not leftHandled) then
if (not self.LeftSeparator) then
-- Add a Left border
self.LeftSeparator = self:CreateTexture(self:GetName().."_LeftSeparator", "BORDER");
self.LeftSeparator:SetTexture("Interface\\AddOns\\!!!ClassicAPI\\Texture\\FrameGeneral\\UI-Frame");
self.LeftSeparator:SetTexCoord("0.24218750", "0.32812500", "0.63281250", "0.82812500");
self.LeftSeparator:SetWidth(11);
self.LeftSeparator:SetHeight(25);
self.LeftSeparator:SetPoint("TOPRIGHT", self, "TOPLEFT", 6, 1);
end
end
-- If this button didn't have a right anchor, add the right border texture
if (not rightHandled) then
if (not self.RightSeparator) then
-- Add a Right border
self.RightSeparator = self:CreateTexture(self:GetName().."_RightSeparator", "BORDER");
self.RightSeparator:SetTexture("Interface\\AddOns\\!!!ClassicAPI\\Texture\\FrameGeneral\\UI-Frame");
self.RightSeparator:SetTexCoord("0.90625000", "0.99218750", "0.00781250", "0.20312500");
self.RightSeparator:SetWidth(11);
self.RightSeparator:SetHeight(25);
self.RightSeparator:SetPoint("TOPLEFT", self, "TOPRIGHT", -6, 1);
end
end
end
-- ButtonFrameTemplate code
function ButtonFrameTemplate_HideButtonBar(self)
if self.bottomInset then
self.bottomInset:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", PANEL_INSET_RIGHT_OFFSET, PANEL_INSET_BOTTOM_OFFSET);
else
_G[self:GetName() .. "Inset"]:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", PANEL_INSET_RIGHT_OFFSET, PANEL_INSET_BOTTOM_OFFSET);
end
_G[self:GetName() .. "BtnCornerLeft"]:Hide();
_G[self:GetName() .. "BtnCornerRight"]:Hide();
_G[self:GetName() .. "ButtonBottomBorder"]:Hide();
end
function ButtonFrameTemplate_ShowButtonBar(self)
if self.topInset then
self.topInset:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", PANEL_INSET_RIGHT_OFFSET, PANEL_INSET_BOTTOM_BUTTON_OFFSET);
else
_G[self:GetName() .. "Inset"]:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", PANEL_INSET_RIGHT_OFFSET, PANEL_INSET_BOTTOM_BUTTON_OFFSET);
end
_G[self:GetName() .. "BtnCornerLeft"]:Show();
_G[self:GetName() .. "BtnCornerRight"]:Show();
_G[self:GetName() .. "ButtonBottomBorder"]:Show();
end
function ButtonFrameTemplate_HideAttic(self)
if self.topInset then
self.topInset:SetPoint("TOPLEFT", self, "TOPLEFT", PANEL_INSET_LEFT_OFFSET, PANEL_INSET_TOP_OFFSET);
else
self.Inset:SetPoint("TOPLEFT", self, "TOPLEFT", PANEL_INSET_LEFT_OFFSET, PANEL_INSET_TOP_OFFSET);
end
self.TopTileStreaks:Hide();
end
function ButtonFrameTemplate_ShowAttic(self)
if self.topInset then
self.topInset:SetPoint("TOPLEFT", self, "TOPLEFT", PANEL_INSET_LEFT_OFFSET, PANEL_INSET_ATTIC_OFFSET);
else
self.Inset:SetPoint("TOPLEFT", self, "TOPLEFT", PANEL_INSET_LEFT_OFFSET, PANEL_INSET_ATTIC_OFFSET);
end
self.TopTileStreaks:Show();
end
function ButtonFrameTemplate_HidePortrait(self)
self.portrait:Hide();
self.portraitFrame:Hide();
self.topLeftCorner:Show();
self.topBorderBar:SetPoint("TOPLEFT", self.topLeftCorner, "TOPRIGHT", 0, 0);
self.leftBorderBar:SetPoint("TOPLEFT", self.topLeftCorner, "BOTTOMLEFT", 0, 0);
end
function ButtonFrameTemplate_ShowPortrait(self)
self.portrait:Show();
self.portraitFrame:Show();
self.topLeftCorner:Hide();
self.topBorderBar:SetPoint("TOPLEFT", self.portraitFrame, "TOPRIGHT", 0, -10);
self.leftBorderBar:SetPoint("TOPLEFT", self.portraitFrame, "BOTTOMLEFT", 8, 0);
end
-- SquareButton template code
SQUARE_BUTTON_TEXCOORDS = {
["UP"] = { 0.45312500, 0.64062500, 0.01562500, 0.20312500};
["DOWN"] = { 0.45312500, 0.64062500, 0.20312500, 0.01562500};
["LEFT"] = { 0.23437500, 0.42187500, 0.01562500, 0.20312500};
["RIGHT"] = { 0.42187500, 0.23437500, 0.01562500, 0.20312500};
["DELETE"] = { 0.01562500, 0.20312500, 0.01562500, 0.20312500};
};
function SquareButton_SetIcon(self, name)
local coords = SQUARE_BUTTON_TEXCOORDS[strupper(name)];
if (coords) then
self.icon:SetTexCoord(coords[1], coords[2], coords[3], coords[4]);
end
end
-- Cap progress bar
function CapProgressBar_SetNotches(capBar, count)
local barWidth = capBar:GetWidth();
local barName = capBar:GetName();
if ( capBar.notchCount and capBar.notchCount > count ) then
for i = count + 1, capBar.notchCount do
_G[barName.."Divider"..i]:Hide();
end
end
local notchWidth = barWidth / count;
for i=1, count - 1 do
local notch = _G[barName.."Divider"..i];
if ( not notch ) then
notch = capBar:CreateTexture(barName.."Divider"..i, "BORDER", "CapProgressBarDividerTemplate", -1);
end
notch:ClearAllPoints();
notch:SetPoint("LEFT", capBar, "LEFT", notchWidth * i - 2, 0);
end
capBar.notchCount = count;
end
function CapProgressBar_Update(capBar, cap1Quantity, cap1Limit, cap2Quantity, cap2Limit, totalQuantity, totalLimit, hasNoSharedStats)
if ( totalLimit == 0) then
return;
end
local barWidth = capBar:GetWidth();
local sizePerPoint = barWidth / totalLimit;
local progressWidth = totalQuantity * sizePerPoint;
local cap1Width, cap2Width;
if ( cap2Quantity and cap2Limit ) then
cap1Width = min(cap1Limit - cap1Quantity, cap2Limit - cap2Quantity) * sizePerPoint; --cap1 can't go past the cap2 LFG limit either.
cap2Width = (cap2Limit - cap2Quantity) * sizePerPoint - cap1Width;
else
cap1Width = (cap1Limit - cap1Quantity) * sizePerPoint;
cap2Width = 0;
end
--Don't let it go past the end.
progressWidth = min(progressWidth, barWidth);
cap1Width = min(cap1Width, barWidth - progressWidth);
cap2Width = min(cap2Width, barWidth - progressWidth - cap1Width);
capBar.progress:SetWidth(progressWidth);
capBar.cap1:SetWidth(cap1Width);
capBar.cap2:SetWidth(cap2Width);
local lastFrame, lastRelativePoint = capBar, "LEFT";
if ( progressWidth > 0 ) then
capBar.progress:Show();
capBar.progress:SetPoint("LEFT", lastFrame, lastRelativePoint, 0, 0);
lastFrame, lastRelativePoint = capBar.progress, "RIGHT";
else
capBar.progress:Hide();
end
if ( cap1Width > 0 and not hasNoSharedStats) then
capBar.cap1:Show();
capBar.cap1Marker:Show();
capBar.cap1:SetPoint("LEFT", lastFrame, lastRelativePoint, 0, 0);
lastFrame, lastRelativePoint = capBar.cap1, "RIGHT";
else
capBar.cap1:Hide();
capBar.cap1Marker:Hide();
end
if ( cap2Width > 0 and not hasNoSharedStats) then
capBar.cap2:Show();
capBar.cap2Marker:Show();
capBar.cap2:SetPoint("LEFT", lastFrame, lastRelativePoint, 0, 0);
lastFrame, lastRelativePoint = capBar.cap2, "RIGHT";
else
capBar.cap2:Hide();
capBar.cap2Marker:Hide();
end
end
@@ -0,0 +1,9 @@
function XML_NineSlice(Self, Layout)
Self.layoutType = Layout
Mixin(Self, NineSlicePanelMixin)
Self:OnLoad()
end
function XML_UseParentLevel(Self)
Self:SetFrameLevel(Self:GetParent():GetFrameLevel())
end

Some files were not shown because too many files have changed in this diff Show More