RU/GTA:SA Resource Streaming

From Multi Theft Auto: Wiki
Revision as of 13:59, 27 May 2014 by TEDERIs (talk | contribs)
Jump to navigation Jump to search

Система GTA:SA Resource Streaming загружает данные из диска в игровую память. Она разделена на управление IMG контейнером, потоковым чтением ресурсов, преобразованием в игровые объекты, загрузка сектора COL/IPL и игровую логику. Она была создана для асинхронной загрузки ресурсов.

Известные типы ресурсов

Имя ID диапазон Описание
Модели (.DFF) 0-19999 Все игровые модели входят в эти ID. Внутренне этот диапазон дальше разделяется на подсекции объектов, автомобилей и педов.
Текстурные Словари (.TXD) 20000-24999 Содержит слоты текстурных словарей. Текстурные словари это контейнеры со всеми игровыми текстурами. Игра присваивает текстурные словари к моделям.
Секторы Столкновений (.COL) 25000-25255 Слоты хранят все загруженные секторы столкновений. Секторы столкновений это COLL контейнеры, которые могут ссылаться и простираться через внутриигровые границы (основано на зданиях, которые используют их).
IPL Секторы (.IPL) 25256-25510 Слоты содержат все загруженные IPL секторы. IPL секторы представлены бинарными .ipl файлами внутри .IMG контейнера. Игра загружает их внуть своих рамок только когда они будут необходимы.
Контейнеры Патчнодов (.DAT) 25511-25574 Патчноды выровнены на секторы 8*8 по 750*750 юнитам. Когда игра ссылаться на такой квадрат, она загружает связанные файлы патчнодов, которые нумерованы в соответствии с формулой (height * rowLen + rowIndex).
Блоки Анимаций (.IFP) 25575-25754 Блоки анимации содержат все последовательности анимаций. Модели могут ссылаться на анимационные блоки, поэтому они запрашивают их вместе.
Записи (.RRR) 25755-25819 Записи хранят предварительно записанные данные игровых движений. Эти игровые движения используются во время миссий когда вы гонитесь за кем-то или прицеливаетесь из окна пока друг ведет.

Описание

Управление IMG Контейнером

Во время инициализации движка, игра загружает файлы конфигурации, которые говорят ему какие .IMG контейнеры использовать. Когда Система стриминга инициализирована, она пытается загрузить зарегистрированные .IMG контейнеры. Каждый .IMG контейнер ссылается используя уникальный индекс внтури IMGFile массива. Игра держит открытыми хэндлы файлов .IMG контейнеров, так что она может всегда читать из них.

Когда .IMG контейнер будет загружен, каждый файл может представить новый ID ресурса внутри движка (структура CModelInfoSA). Модели получат ID путем сравнением их имен с .IDE записью. Если ничего не найдено, движок поддерживает небольшой кэш ресурса. Эти ресурсы еще могут быть загружены используя RequestSpecialModel. Текстурный Словарь получает новый ID. Имеется жесткий лимит в 5000 TXD. COLL и IPL секторы также получают новые ID основанные на порядке загрузки. Все остальные ресурсы поступают также, следую этим же принципам.

Внутренний CModelInfoSA массив представляет каждую запись ресурса в .IMG файлах. Движок поддерживает всего 26310 ресурсных ID.

Возможные состояния загрузки ресурса

Имя Описание
MODEL_UNAVAILABLE Ресурс не был загружен. Ни один из игровых ресурсов для этой записи не был загружен. Этот ресурс не используется ни одной из частей игрового движка.
MODEL_LOADED Этот ресурс был загружен Системой стриминга. Он готов быть использован игровым движком.
MODEL_LOADING Этот ресурс находится в очереди быть-загруженным. Он ожидает взятия Системой стриминга для чтения с диска.
MODEL_QUEUE Слайсер в настоящее время читает данные из диска для этого ресурса.
MODEL_RELOAD Этот ресурс в настоящее время загружается в сопрограмму. Данные которые с ним связаны слишком большие чтобы загрузить их сразу же.

Res loader sys.png

(Поточность) Чтение Ресурсов

Существует совершенно отдельная система просто для чтения порций данных с диска, известная как streaming runtime. Игра может создавать потоковые хэндлы для файлов на диске. При вызове функции ReadStream, будет сделан запрос на чтение данных из потокового хендла. Процесс чтения обеспечивается структурами syncSemaphore которые удерживают внутренние данные о процессе чтения (такие как хэндл файла или структуры OVERLAPPED). Вызов GetSyncSemaphoreStatus c индексом syncSemaphore в качестве аргумента будет возвращать статус запроса (т.е. чтение завершено). CancelSyncSemaphore останавливает любые асинхронные запросы.

Во время старта, система проверяет возможности системы. По умолчанию, поточность включена. Для проверки поддержки этого, предпринимается попытка чтения из GTA3.IMG используя перекрытый ВВОД/ВЫВОД. Система выберет наилучшую совместимую конфигурацию. На современных машинах, это значит поточность с перекрытым ВВОДОМ/ВЫВОДОМ. В случае худшего сценария, игра читает данные синхронно в одиночном потоке с остановкой выполнения игры, если данные читаются из медленного медиа-хранилища.

Conversion into Engine Objects

The Streaming system natively maintains two reading slicers. A reading slicer checks which requested data is close in an .IMG container and reads multiple data in one go. Using modification of the logic the engine can support an arbitrary number of slicers, that all share chunks inside of a reading buffer. The more slicers, the smaller the reading buffer section for each. If data that is read does not fit into a single slicer, the Streaming system waits for all smaller requests to finish and then reads that big data on the first slicer using the whole reading buffer. The reading buffer size is determined by the biggest resource inside any registered .IMG container.

There are 4 states that a slicer can be in: idle, buffering, loading and waiting. Idle slicers wait for requests that can occupy them. When slicers are buffering, they wait for their read requests to finish. Loading slicers wait until the game has loaded all game resources from them. Waiting is an exceptional status that is caused if a slicer is requested to push data for engine object conversion but the read requests have not finished yet.

Loading is the most interesting status. The slicers push the raw data into loader routines along with their model IDs. Using the model ID the engine knows what that raw data is supposed to represent. For instance, model id 1361 is a model resource that is stored in a .DFF file. The loader routines usually load data in one go. If data is found too big, it can be loaded across multiple slicer pulses (the slicer resides in loading status). Then the data is processed in coroutine fashion. Natively, only texture dictionaries that exceed a certain block count use this feature. Also, the engine has been optimized to assume that all data is loaded in two slicer pulses (max.).

Each slicer has its own syncSemaphore from the streaming runtime. The syncSemaphore index corresponds to the slicer index.

COL/IPL Sector Loading

The GTA:SA engine maps COLL and IPL sectors to world coordinate boundaries. When the streaming position (natively the player position) intersects with any sector, it will be requested to load. This activity is maintained in the Sectorizer template class. Every COLL and IPL sector is added into a quad tree to boost world area look-up. Sectors are allocated from a private data pool. Sectors have their own manager that specializes the Sectorizers activity (loading and unloading, pool index to model id conversion, sector marking logic).

Game Logic

When the camera is close to the ground, the Streaming system pulses game activity management. Game activity is pre-loading of event models and streaming of event zones. These features have been disabled in MTA, but are interesting if SP support is considered.

Multiplayer Support

MTA:SA sets high demands for the GTA:SA engine. The streaming system was meant to be the central location to load resources from. Hence, natively, the system does not expect interaction of outside sources, such as the MTA runtime.

To fix this problem, the entire system has to be understood and properly expanded. The RequestModel function and the FreeModel function are used to request resources for every game instance. By expanding the logic of these functions, MTA can offer custom resources to the game engine (i.e. models and collisions). Simple ASM hooks are insufficient, as the code requires heavy adjustments which need to be clear to every MTA developer. For instance, to prevent memory leaks and instability, the Streaming slicer activity and the loader queue have to be adjusted according to how MTA manipulates the resource status.

In MTA:Eir, the model support has been fixed by offering model resources on base model info request and preventing the deletion of custom collisions when COL sectors are being unloaded.

Ideas for Expansion

Natively, the loader does not operate with perfect efficiency. As stated above, the system mimicks coroutine behavior. If very big .DFF models are loaded, the Streaming system can cause FPS drops. The way texture containers are loaded is imperfect, even if their loading is split into two pulses. The theory is that the conversion of every texture into a game instance is a complex task. Natively, streaming is not dependant on timing of the load process. If it were, then the system could yield when a TXD container takes too long to load.

My proposal is that every slicer obtains a fiber in a MTA execution manager. Once per frame (and at all other plausible moments) all fibers will be pulsed, thus progressing resource loading. Since every fiber maintains its own runtime stack, complex code is avoided. When a certain quota of data is read from a RenderWare stream, the fiber's execution is yielded. Such a change in resource loading is going to smoothen the FPS of GTA:SA when traveling across the world.

Problem with such a proposal is that the RenderWare streaming functions are hooked by the network module.

Fibered Loading

This is a technique utilized in MTA:Eir to improve the performance of low-end computers. It generally smoothens the FPS count of the game by removing lag-spikes. In native GTA:SA, resources are mostly loaded in one go. Using fibered loading on the other hand, loading of resources depends on the time the Streaming system may take per frame. The time it may take is derived from the total execution time of last frame.

Imagine that a very big TXD container is stored inside of GTA3.IMG. Such resources take a relatively long time to be buffered into game memory and an initialization attempt during Streaming loading may cause a lagspike, since much data is processed at once. If fibered loading is enabled, a coroutine (a.k.a. fiber) is created for every resource loading slicer with its own execution stack. When the loader attempts to read resources from the buffer, the fiber executive manager checks whether the fiber has taken its time already. If so, it yields during the read process. Execution will continue next game frame.