<img src="icon.png" alt="ScrapSack" width="80">

# <span style="color: #cc0000;">SCRAP SACK</span>

![Lethal Company](https://img.shields.io/badge/Lethal%20Company-V81-cc0000?style=flat-square)
![BepInEx](https://img.shields.io/badge/BepInEx-5.4.21%2B-cc0000?style=flat-square)
![Version](https://img.shields.io/badge/version-1.1.3-cc0000?style=flat-square)
![License](https://img.shields.io/badge/license-MIT-cc0000?style=flat-square)

**Language / Язык:** [English](#english) · [Русский](#russian)

<a name="english"></a>
## <span style="color: #cc0000;">SCRAP SACK</span>

**Author:** <span style="color: #cc0000;">Solo00n</span>

A red belt bag sold in the terminal that holds loot instead of tools — and unlike a vanilla
bag, you carry the weight of everything inside it.

### <span style="color: #cc0000;">WHAT IT DOES</span>

- <strong style="color: #cc0000;">A new item in the shop</strong> — order <code>scrap
sack</code> from the terminal for 60 credits. It is a separate item, not a change to the bag
you already know.
- <strong style="color: #cc0000;">Scrap only</strong> — flashlights, the shotgun, keys and
every other tool are refused. One-handed loot by default; bulky two-handed loot can be
switched on. Bags never go in, not even one found as scrap.
- <strong style="color: #cc0000;">It weighs</strong> — every piece inside adds its weight
while you carry the sack. A vanilla belt bag is weightless, which makes it strictly better
than your hands; the sack trades that away.
- <strong style="color: #cc0000;">Red, not blue</strong> — the bag is recoloured by swapping
the red and blue channels of its textures, so the shape, seams, stitching and baked shadows
all survive the change.
- <strong style="color: #cc0000;">The vanilla belt bag is untouched</strong> — every patch
checks which bag it is looking at first, so vanilla bags behave exactly as vanilla and other
belt bag mods keep working.

### <span style="color: #cc0000;">HOW IT WORKS</span>

There is no Unity project and no AssetBundle. At startup the mod finds the vanilla belt bag
prefab in the NetworkManager's prefab list, clones it with its own <strong style="color:
#cc0000;">deterministic GlobalObjectIdHash</strong> — derived from the mod name, so every
client computes the same one — clones the <code>Item</code> asset alongside it, recolours the
clone's materials and registers the result as a shop item through LethalLib. The mesh,
animations, sounds and icon come along for free, and nothing about the vanilla item changes.

LethalLib marks the cloned template <code>HideAndDontSave</code> so it survives scene loads,
and Unity copies those flags onto every sack spawned from it — which would hide the sack from the
searches the game uses to clean up and save items. Each spawned sack drops the inherited flags, so
it is <strong style="color: #cc0000;">despawned at the end of the day, saved with the ship and
wiped when the crew is fired</strong>, exactly like a vanilla item.

The recolour is a <strong style="color: #cc0000;">red/blue channel swap</strong> rather than a
tint. Tinting red over a blue albedo multiplies towards black and gives a muddy maroon;
swapping the channels maps the blue exactly onto red and keeps every texture detail. Because
the game's textures are not CPU-readable, each one is copied through a RenderTexture on the
GPU before its pixels are rewritten.

### <span style="color: #cc0000;">MULTIPLAYER (HOST-AUTHORITATIVE)</span>

A bag that carries loot is worth cheating on, so the <strong style="color: #cc0000;">host
decides everything that could be an advantage</strong> and clients are given no say in it.

- <strong style="color: #cc0000;">The host's rules are sent on connect</strong> — capacity,
the scrap-only rule, the deny list, grab range and both weight settings travel to every client
in the handshake. Clients apply the host's values and ignore their own config, so editing the
file cannot buy you a bigger or lighter sack.
- <strong style="color: #cc0000;">Every add is validated server-side</strong> — capacity, what
counts as storable and the distance to the item are re-checked on the host when the client
asks to bag something, and refused there if they do not hold. A client that lies about any of
it is simply told no.
- <strong style="color: #cc0000;">Weight is synced rather than enforced</strong> —
<code>carryWeight</code> only exists on the machine that owns the player, so no server check
can reach it. That is exactly why the host's weight settings are sent instead of trusted
locally: without it, switching weight off in the config would turn the sack into a free,
weightless loot crate.
- <strong style="color: #cc0000;">Inert until the host confirms</strong> — a client's sack
behaviour stays off until the host says it has the mod, so a mismatched lobby degrades quietly
instead of desyncing.

> **Everyone needs the mod.** The sack is a network prefab, so a vanilla client cannot spawn
> it. This is unlike a pure tweak mod where only the host needs to be modded.

### <span style="color: #cc0000;">REQUIREMENTS</span>

- Lethal Company **V81**
- **BepInEx** 5.4.21 or newer
- **[LethalLib](https://thunderstore.io/c/lethal-company/p/Evaisa/LethalLib/)** — used to
register the shop item and the network prefab

### <span style="color: #cc0000;">INSTALLATION</span>

**Mod manager** — install through Thunderstore Mod Manager or r2modman; LethalLib comes with it.

**Manual**
1. Install **BepInEx 5** (BepInExPack for Lethal Company) and **LethalLib**.
2. Put <code>Iron.ScrapSack.dll</code> in <code>Lethal Company/BepInEx/plugins/</code>.
3. Launch once to generate <code>BepInEx/config/Iron.ScrapSack.cfg</code>.

### <span style="color: #cc0000;">CONFIGURATION</span>

<code>BepInEx/config/Iron.ScrapSack.cfg</code>

| Section | Key | Default | Meaning |
|---------|-----|---------|---------|
| General | `Enabled` | `true` | Master switch. |
| Shop | `Price` | `60` | Terminal price. Needs a game restart. |
| Shop | `Item Name` | `Scrap sack` | Terminal command and HUD name. Needs a restart. |
| Slots | `Capacity` | `4` | How many pieces fit. **Host's value is used.** |
| Slots | `Resize Inventory UI` | `true` | Rebuild the slot grid to match Capacity. |
| Slots | `Slots Per Row` | `4` | Columns in the rebuilt grid. |
| Items | `Allow Two-Handed Scrap` | `false` | Paintings and other bulky loot. **Host's value is used.** |
| Items | `Denied Items` | `Apparatus, Body` | Never fit, even though they are scrap. **Host's value is used.** |
| Weight | `Enabled` | `true` | Carry the weight of the contents. **Host's value is used.** |
| Weight | `Multiplier` | `1.0` | `0.5` = half weight, `0` = weightless. **Host's value is used.** |
| Appearance | `Recolor Mode` | `SwapRedBlue` | `SwapRedBlue` / `Tint` / `Off`. Needs a restart. |
| Appearance | `Tint Color` | `#C81E1E` | Used by `Tint` mode. Needs a restart. |
| Misc | `Grab Range` | `4` | Max reach when bagging. **Host's value is used.** |
| Misc | `Tooltips` | `true` | HUD tip when something is refused. |
| Misc | `Empty Bag Action` | `true` | Double-tap right-interact (E) dumps the sack. |
| Misc | `Empty Bag Double Tap Window` | `0.4` | Seconds the second press has to land in. |
| Host | `Enforce Capacity` | `true` | Server-side capacity check. |
| Host | `Enforce Restrictions` | `true` | Server-side scrap-only check. |
| Host | `Enforce Range` | `true` | Server-side grab-range check. |

The Apparatus is denied by default because bagging it interferes with leaving the facility.

### <span style="color: #cc0000;">INTEGRATIONS AND COMPATIBILITY</span>

- <strong style="color: #cc0000;">Other belt bag mods</strong> — a mod that patches
<code>BeltBagItem</code> patches the class, not the instance, so it sees the sack too. This mod
only ever acts on its own bag and hands everything else back. For the reverse direction,
<strong style="color: #cc0000;">ImprovedBeltBag 1.2.0+</strong> learned the same manners and
leaves the sack alone.
- <strong style="color: #cc0000;">The shared inventory panel</strong> — the slot grid is
returned to its original size whenever a different bag is opened, so two bag mods with
different capacities do not fight over it.
- <strong style="color: #cc0000;">Remnants and other mods that turn store items into scrap</strong>
— LethalLib builds those as copies with an <code>Item</code> and a prefab of their own, so a sack
found on a moon is not the object the shop sells. The sack prefab carries a marker that survives
the copy, and copies LethalLib registers are also recognised by the item they came from, so a
found sack behaves exactly like a bought one.

### <span style="color: #cc0000;">BUILD</span>

```
dotnet build -c Release
```

Or <code>.\build-package.ps1</code> to build and stage a Thunderstore zip in <code>dist/</code>.

### <span style="color: #cc0000;">CREDITS</span>

Built on [ImprovedBeltBag](https://github.com/Solo00n/ImprovedBeltBag). The server-side
enforcement and handshake patterns trace back to
[BagConfig](https://github.com/mattymatty97/LTC_BagConfig) by The Matty, MIT. Shop and network
prefab registration use [LethalLib](https://github.com/EvaisaDev/LethalLib) by Evaisa. See
[THIRD_PARTY_LICENSES.md](THIRD_PARTY_LICENSES.md).

---

<a name="russian"></a>
## <span style="color: #cc0000;">SCRAP SACK — Русское описание</span>

**Автор:** <span style="color: #cc0000;">Solo00n</span>

Красная поясная сумка, покупаемая в терминале. Носит лут вместо инструментов — и, в отличие от
ванильной, ты чувствуешь вес всего, что в неё сложил.

### <span style="color: #cc0000;">ЧТО ДЕЛАЕТ МОД</span>

- <strong style="color: #cc0000;">Новый предмет в магазине</strong> — заказывается в терминале
командой <code>scrap sack</code> за 60 кредитов. Это отдельный предмет, а не переделка
привычной сумки.
- <strong style="color: #cc0000;">Только скрап</strong> — фонарики, дробовик, ключи и прочие
инструменты не влезают. По умолчанию одноручный лут; двуручный включается в конфиге. Сумки не влезают никогда — даже найденные как скрап.
- <strong style="color: #cc0000;">Она весит</strong> — каждый предмет внутри добавляет свой вес,
пока ты несёшь сумку. Ванильная сумка невесома, из-за чего она строго лучше рук; эта сумка
меняет невесомость на вместимость.
- <strong style="color: #cc0000;">Красная, а не синяя</strong> — перекраска сделана обменом
красного и синего каналов текстур, поэтому форма, швы, строчка и запечённые тени полностью
сохраняются.
- <strong style="color: #cc0000;">Ванильная сумка не тронута</strong> — каждый патч сперва
проверяет, с какой сумкой имеет дело, так что ванильная ведёт себя ровно по-ванильному, а
другие моды на сумки продолжают работать.

### <span style="color: #cc0000;">КАК ЭТО РАБОТАЕТ</span>

Ни Unity-проекта, ни AssetBundle. При запуске мод находит ванильный префаб сумки в списке
сетевых префабов, клонирует его с собственным <strong style="color: #cc0000;">детерминированным
GlobalObjectIdHash</strong> — он выводится из имени мода, поэтому у всех клиентов получается
одинаковым, — клонирует рядом ассет <code>Item</code>, перекрашивает материалы клона и
регистрирует результат в магазине через LethalLib. Модель, анимации, звуки и иконка достаются
бесплатно, а ванильный предмет не меняется вообще.

LethalLib помечает клонированный шаблон флагами <code>HideAndDontSave</code>, чтобы он переживал
смену сцен, а Unity копирует эти флаги на каждую заспавненную из него сумку — и та становится
невидимой для поиска, которым игра убирает и сохраняет предметы. Каждая сумка при появлении
снимает унаследованные флаги, поэтому она <strong style="color: #cc0000;">удаляется в конце дня,
сохраняется вместе с кораблём и стирается при увольнении</strong> — ровно как ванильный предмет.

Перекраска — это <strong style="color: #cc0000;">обмен каналов R и B</strong>, а не тонирование.
Красный тон поверх синей текстуры умножается в сторону чёрного и даёт грязный бордовый; обмен
каналов кладёт синий точно на красный и сохраняет все детали. Текстуры игры недоступны для
чтения процессором, поэтому каждая сперва копируется через RenderTexture на видеокарте, и уже
копия переписывается попиксельно.

### <span style="color: #cc0000;">МУЛЬТИПЛЕЕР (HOST-AUTHORITATIVE)</span>

Сумку, которая носит лут, есть смысл читерить, поэтому <strong style="color: #cc0000;">всё, что
может дать преимущество, решает хост</strong>, а клиенту голоса не даётся.

- <strong style="color: #cc0000;">Правила хоста передаются при подключении</strong> —
вместимость, правило «только скрап», список запретов, дальность и обе настройки веса уходят
каждому клиенту в хендшейке. Клиент применяет значения хоста и игнорирует собственный конфиг,
так что правкой файла нельзя выдать себе сумку побольше или полегче.
- <strong style="color: #cc0000;">Каждое добавление проверяется на сервере</strong> —
вместимость, пригодность предмета и расстояние до него перепроверяются на хосте в момент, когда
клиент просит что-то положить, и отклоняются там же. Клиенту, который соврал, просто отвечают
отказом.
- <strong style="color: #cc0000;">Вес синхронизируется, а не проверяется</strong> —
<code>carryWeight</code> существует только на машине, которой принадлежит игрок, и серверная
проверка до него не дотянется. Именно поэтому настройки веса приходят от хоста, а не берутся
локально: иначе выключенный в конфиге вес превратил бы сумку в бесплатный невесомый ящик.
- <strong style="color: #cc0000;">Не работает без подтверждения хоста</strong> — поведение сумки
у клиента выключено, пока хост не сообщит, что мод у него есть. Несовпадающее лобби тихо
деградирует вместо рассинхрона.

> **Мод нужен всем.** Сумка — сетевой префаб, у ванильного клиента она просто не заспавнится.
> Это отличается от чистых твик-модов, где достаточно мода у хоста.

### <span style="color: #cc0000;">ТРЕБОВАНИЯ</span>

- Lethal Company **V81**
- **BepInEx** 5.4.21 или новее
- **[LethalLib](https://thunderstore.io/c/lethal-company/p/Evaisa/LethalLib/)** — регистрация
предмета в магазине и сетевого префаба

### <span style="color: #cc0000;">УСТАНОВКА</span>

**Через менеджер модов** — Thunderstore Mod Manager или r2modman; LethalLib подтянется сам.

**Вручную**
1. Установить **BepInEx 5** (BepInExPack для Lethal Company) и **LethalLib**.
2. Положить <code>Iron.ScrapSack.dll</code> в <code>Lethal Company/BepInEx/plugins/</code>.
3. Запустить игру один раз, чтобы создался <code>BepInEx/config/Iron.ScrapSack.cfg</code>.

### <span style="color: #cc0000;">НАСТРОЙКА</span>

<code>BepInEx/config/Iron.ScrapSack.cfg</code>

| Секция | Ключ | По умолчанию | Значение |
|--------|------|--------------|----------|
| General | `Enabled` | `true` | Общий выключатель. |
| Shop | `Price` | `60` | Цена в терминале. Нужен перезапуск игры. |
| Shop | `Item Name` | `Scrap sack` | Команда в терминале и имя в HUD. Нужен перезапуск. |
| Slots | `Capacity` | `4` | Сколько предметов влезает. **Берётся у хоста.** |
| Slots | `Resize Inventory UI` | `true` | Перестраивать сетку слотов под Capacity. |
| Slots | `Slots Per Row` | `4` | Столбцов в перестроенной сетке. |
| Items | `Allow Two-Handed Scrap` | `false` | Картины и прочий крупный лут. **Берётся у хоста.** |
| Items | `Denied Items` | `Apparatus, Body` | Не влезают, даже будучи скрапом. **Берётся у хоста.** |
| Weight | `Enabled` | `true` | Нести вес содержимого. **Берётся у хоста.** |
| Weight | `Multiplier` | `1.0` | `0.5` — половина веса, `0` — невесомо. **Берётся у хоста.** |
| Appearance | `Recolor Mode` | `SwapRedBlue` | `SwapRedBlue` / `Tint` / `Off`. Нужен перезапуск. |
| Appearance | `Tint Color` | `#C81E1E` | Для режима `Tint`. Нужен перезапуск. |
| Misc | `Grab Range` | `4` | Дальность подбора в сумку. **Берётся у хоста.** |
| Misc | `Tooltips` | `true` | Подсказка в HUD при отказе. |
| Misc | `Empty Bag Action` | `true` | Двойное нажатие E вываливает содержимое. |
| Misc | `Empty Bag Double Tap Window` | `0.4` | Секунд на второе нажатие. |
| Host | `Enforce Capacity` | `true` | Серверная проверка вместимости. |
| Host | `Enforce Restrictions` | `true` | Серверная проверка «только скрап». |
| Host | `Enforce Range` | `true` | Серверная проверка дальности. |

Apparatus запрещён по умолчанию, потому что в сумке он мешает уходу с завода.

### <span style="color: #cc0000;">СОВМЕСТИМОСТЬ</span>

- <strong style="color: #cc0000;">Другие моды на сумки</strong> — мод, патчащий
<code>BeltBagItem</code>, патчит класс, а не экземпляр, поэтому видит и нашу сумку. Этот мод
работает только со своей и отдаёт остальные обратно. В обратную сторону <strong style="color:
#cc0000;">ImprovedBeltBag 1.2.0+</strong> научился тому же и не трогает нашу.
- <strong style="color: #cc0000;">Общая панель инвентаря</strong> — сетка слотов возвращается к
исходному размеру при открытии любой другой сумки, поэтому два мода с разной вместимостью не
дерутся за неё.
- <strong style="color: #cc0000;">Remnants и другие моды, превращающие магазинные предметы в скрап</strong>
— LethalLib делает для них копии с собственными <code>Item</code> и префабом, поэтому найденная на
луне сумка — не тот объект, что продаёт магазин. На префабе сумки есть метка, которая переживает
копирование, а копии, зарегистрированные через LethalLib, распознаются и по предмету-источнику,
так что найденная сумка ведёт себя ровно как купленная.

### <span style="color: #cc0000;">СБОРКА</span>

```
dotnet build -c Release
```

Либо <code>.\build-package.ps1</code> — соберёт и упакует zip для Thunderstore в <code>dist/</code>.

### <span style="color: #cc0000;">АВТОРСТВО</span>

Построен на [ImprovedBeltBag](https://github.com/Solo00n/ImprovedBeltBag). Серверная валидация и
хендшейк восходят к [BagConfig](https://github.com/mattymatty97/LTC_BagConfig) от The Matty, MIT.
Регистрация в магазине и сетевого префаба — через
[LethalLib](https://github.com/EvaisaDev/LethalLib) от Evaisa. Подробности в
[THIRD_PARTY_LICENSES.md](THIRD_PARTY_LICENSES.md).
