Торговец снова становится призраком после выгрузки чанка

Баг со стрима: торговец, ставший чёрно-белым и полупрозрачным, наутро снова
обычный человек. Догадка была про обновление ассортимента - не подтвердилась, и
это стоит записать, потому что по часам лавки модель не трогает ВООБЩЕ ничего:
TraderData при сбросе переписывает только PrimaryInventory и lastInventoryUpdate,
а TraderArea.SetClosed ходит по блокам TraderOnOff - двери, замки, BlockLight,
динамик - и до сущности торговца не дотягивается.

Настоящая причина в EntityFactory.CreateEntityOperation.CompleteEntity:
`entity.entityId = ecd.id`, то есть сохранённый айди ВОССТАНАВЛИВАЕТСЯ. Торговцы
стримятся на подходе и точно так же выгружаются, когда игрок уходит на ночь.
Возвращается он - торговец собран заново: новый GameObject, новые рендереры,
ванильные материалы, ТОТ ЖЕ entityId. А в патче стоял HashSet<int> Ghosted -
"этот айди я уже обработал". Айди в наборе есть, свип проходит мимо, торговец
остаётся живым человеком до конца сессии. Отсюда и "на следующее утро": симптом
идёт не за часами лавки, а за чанком, в котором лавка стоит.

Ghosted стал Dictionary<int, GhostBody>, где GhostBody держит массив рендереров,
которые патч взял себе. IsIntact проверяет их: у Unity уничтоженный объект
сравнивается с null, так что подмена модели видна прямо, и та же проверка
бесплатно закрывает любую другую пересборку, не только выгрузку чанка.

Prune чистит Converted и TintedMaterials от уничтоженных объектов. Без него оба
списка росли бы на одного торговца за каждую пересборку, а Retint/Reapply ходили
бы по обломкам. Материал, выданный через renderer.materials, принадлежит
рендереру и умирает вместе с ним - одного прохода хватает на оба списка.

В лог добавлена строка "entity <id> came back with a new model" - ровно та,
которой не хватало, чтобы найти это за один заход вместо разбора в декомпиляторе.

Счётчик в necroghost переименован: со словарём он означает "торговцев под
присмотром сейчас", а не "id, которые когда-либо видели" - он теперь падает и
растёт.

Не проверено в игре: нужен заход к торговцу, выгрузка лавки и возвращение.

---

Traders go back to being ghosts after a chunk unload

Reported from the stream: a trader who had gone black-and-white and translucent
was an ordinary person again the next morning. The guess was the restock - it was
wrong, and that is worth recording, because nothing on the shop's clock touches
the model at all: TraderData's reset rewrites PrimaryInventory and
lastInventoryUpdate only, and TraderArea.SetClosed walks TraderOnOff blocks -
doors, locks, BlockLight, speaker - and never reaches the trader entity.

The real cause is in EntityFactory.CreateEntityOperation.CompleteEntity:
`entity.entityId = ecd.id`, so the saved id is RESTORED. Traders are streamed in
on approach and streamed out the same way when the player leaves for the night.
On return the trader is rebuilt from scratch - new GameObject, new renderers, the
game's own materials - carrying THE SAME entityId. The patch held a
HashSet<int> Ghosted, meaning "this id is done". The id was still in the set, the
sweep skipped him, and he stayed an ordinary person for the rest of the session.
Hence "the next morning": the symptom follows the chunk the shop sits in, not the
shop's clock.

Ghosted is now a Dictionary<int, GhostBody>, the value holding the renderers the
patch took over. IsIntact tests them: Unity's destroyed objects compare equal to
null, so a swapped model is directly visible, and the same check covers any other
rebuild for free.

Prune drops destroyed entries from Converted and TintedMaterials. Without it both
lists would grow by one trader's worth per rebuild and Retint/Reapply would be
walking the wreckage. A material assigned through renderer.materials is owned by
that renderer and dies with it, so one pass settles both.

A log line was added - "entity <id> came back with a new model" - the exact line
that was missing to find this in one visit rather than in a decompiler.

The necroghost counter was reworded: with a dictionary it means "traders held as
ghosts right now", not "ids ever seen" - it now falls as well as rises.

Not tested in game: needs a visit, a shop unload and a return.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MnwP2Dt1vk8bUPJ452EoVL
This commit is contained in:
AlexCube
2026-09-15 22:31:41 +03:00
co-authored by Claude Opus 5
parent 7172681353
commit 20af2bbe6c
4 changed files with 117 additions and 10 deletions
+7 -2
View File
@@ -148,7 +148,12 @@ namespace NecromancerTome
/// <summary>Current value plus what it actually reached, in both units, and which way the
/// body is being faded. The count is the half that answers "did it do anything": 0
/// materials means no trader has been converted yet - they stream in on approach - not
/// that the number was refused.</summary>
/// that the number was refused.
///
/// The trader count is "held as a ghost RIGHT NOW", not "seen this session": since the
/// 2026-09-15 fix, Ghosted is keyed by entity id but re-entered when a trader is rebuilt,
/// and a trader whose chunk has unloaded keeps his entry only until the next sweep finds
/// his model gone. So the number falls as well as rises, and that is correct.</summary>
public static void Report(string _prefix)
{
float alpha = GhostTraderPatch.GhostAlpha;
@@ -157,7 +162,7 @@ namespace NecromancerTome
_prefix + ": " + ((1f - alpha) * 100f).ToString("0.#") + "% transparent (alpha " +
alpha.ToString("0.###") + "), body mode " + GhostTraderPatch.BodyMode +
", applied to " + applied + " live material(s) across " +
GhostTraderPatch.Ghosted.Count + " trader(s) converted this session.");
GhostTraderPatch.Ghosted.Count + " trader(s) currently held as ghosts.");
}
/// <summary>Percent out of what the user typed. StringParsers is the game's own parser and
+109 -7
View File
@@ -67,6 +67,11 @@ namespace NecromancerTome
/// Polling with ModEvents.UnityUpdate - the same approach PetFollowPatch.cs already uses here -
/// avoids guessing at the right moment inside someone else's character pipeline. A trader with
/// no renderers yet is simply not marked done and is picked up on the next sweep.
///
/// The same tick is what puts a trader BACK once the game has rebuilt him - see Ghosted, and
/// the bug of 2026-09-15 that taught this file the difference between an entity id and a
/// model. A spawn hook would not have helped there either: the entity was never re-created as
/// far as its id is concerned.
/// </summary>
public static class GhostTraderPatch
{
@@ -135,6 +140,16 @@ namespace NecromancerTome
public Material[] Originals;
}
/// <summary>What one trader was actually given, kept so the sweep can ask "is he STILL a
/// ghost" instead of only "have I seen this id". The renderers are the answer: a trader
/// that streams out and back in is rebuilt from scratch - new GameObject, new renderers,
/// the game's own materials - while keeping the id he was saved under, so an id on its own
/// says nothing about the model standing there now. See the Ghosted comment.</summary>
public struct GhostBody
{
public Renderer[] Renderers;
}
/// <summary>Every renderer taken over, in the order it was found. Pruned of destroyed
/// renderers as they are walked; dropped wholesale when the world unloads.</summary>
public static readonly List<GhostRenderer> Converted = new List<GhostRenderer>();
@@ -192,8 +207,29 @@ namespace NecromancerTome
/// beyond doubt: 1 = solid, 0 = gone, exactly like an alpha.</summary>
public static readonly string[] FadeNameHints = { "_Fade" };
/// <summary>Entity ids already converted. Cleared when the world unloads.</summary>
public static readonly HashSet<int> Ghosted = new HashSet<int>();
/// <summary>Traders already converted, by entity id, WITH the renderers each was given.
/// Cleared when the world unloads.
///
/// THE VALUE IS NOT DECORATION - it is the fix for "the trader stopped being a ghost the
/// next morning" (2026-09-15). This was a HashSet of ids, and an id is not enough:
/// EntityFactory restores `entity.entityId = ecd.id` from the save, so a trader who is
/// streamed out while the player is away (they are streamed IN on approach in the first
/// place - see the class comment) comes back as a BRAND NEW GameObject carrying the SAME
/// id, with the game's own materials on it. The set still held the id, the sweep skipped
/// him, and he stayed an ordinary living person for the rest of the session.
///
/// It is NOT the restock, which was the first guess and is worth writing down as ruled
/// out: TraderData's reset rewrites PrimaryInventory and lastInventoryUpdate and touches
/// no renderer, and TraderArea.SetClosed - the whole open/close cycle - only works doors,
/// lights and speakers. Nothing on the shop's clock ever reaches the model. What does is
/// the chunk the shop sits in, which is why the symptom looks like it follows the morning:
/// the player is away for the night, the trader unloads with his chunk, and he is rebuilt
/// when they walk back.
///
/// Holding the renderers makes the question answerable: Unity's destroyed objects compare
/// equal to null, so a trader whose model is gone is visible as such, and the same check
/// covers any other rebuild of the model for free.</summary>
public static readonly Dictionary<int, GhostBody> Ghosted = new Dictionary<int, GhostBody>();
/// <summary>Source shader names already described in the log, so the probe says each
/// distinct thing once rather than once per trader per part.</summary>
@@ -252,21 +288,84 @@ namespace NecromancerTome
{
continue;
}
if (Ghosted.Contains(trader.entityId))
if (Ghosted.TryGetValue(trader.entityId, out GhostBody body))
{
if (IsIntact(body))
{
continue;
}
if (ApplyGreyscale(trader))
// His model was destroyed and rebuilt under him. Drop what is known about the
// old one before building the new, or Converted and TintedMaterials keep
// entries for renderers and materials that no longer exist.
Debug.Log("[NecromancerTome] GhostTraderPatch: entity " + trader.entityId +
" came back with a new model - ghosting him again");
Ghosted.Remove(trader.entityId);
Prune();
}
if (ApplyGreyscale(trader, out GhostBody fresh))
{
Ghosted.Add(trader.entityId);
Ghosted[trader.entityId] = fresh;
}
}
}
/// <summary>Is this trader still wearing what we put on him? False the moment any part of
/// the model we converted has been destroyed - which is what a stream-out and back in
/// looks like from here, and equally what any other rebuild of the model would look like.
///
/// Deliberately NOT "does he have renderers we have not converted": a trader gains and
/// loses renderers in normal play (a held item, worn equipment), and treating that as a
/// rebuild would re-run the conversion on renderers already carrying our materials - whose
/// sharedMaterials hand back OUR clones, so the "originals" kept for the next mode switch
/// would be re-shaded ones with no way back. The known gap that leaves is a part of the
/// model built AFTER the first sweep reached him: it stays in colour until he next
/// reloads. Nothing like that has been seen on the six traders.</summary>
public static bool IsIntact(GhostBody _body)
{
if (_body.Renderers == null || _body.Renderers.Length == 0)
{
return false;
}
foreach (Renderer renderer in _body.Renderers)
{
if (renderer == null)
{
return false;
}
}
return true;
}
/// <summary>Drops every entry whose Unity object the game has destroyed. Both lists are
/// session-long and keyed by nothing - without this they grow by one trader's worth of
/// renderers and materials every time a trader is rebuilt, and Retint/Reapply would be
/// walking the wreckage. A material assigned through renderer.materials is owned by that
/// renderer and dies with it, so one pass settles both.</summary>
public static void Prune()
{
for (int i = Converted.Count - 1; i >= 0; i--)
{
if (Converted[i].Renderer == null)
{
Converted.RemoveAt(i);
}
}
for (int i = TintedMaterials.Count - 1; i >= 0; i--)
{
if (TintedMaterials[i].Material == null)
{
TintedMaterials.RemoveAt(i);
}
}
}
/// <summary>False when there is nothing to work on yet (model not built), so the caller
/// leaves this trader unmarked and tries again on the next sweep.</summary>
public static bool ApplyGreyscale(EntityTrader _trader)
/// leaves this trader unmarked and tries again on the next sweep. On true, _body carries
/// the renderers taken over, which is how the next sweep tells this trader from a rebuilt
/// one standing under the same entity id.</summary>
public static bool ApplyGreyscale(EntityTrader _trader, out GhostBody _body)
{
_body = default(GhostBody);
Renderer[] renderers = _trader.GetComponentsInChildren<Renderer>(true);
if (renderers == null || renderers.Length == 0)
{
@@ -279,6 +378,7 @@ namespace NecromancerTome
int converted = 0;
int leversBefore = TintedMaterials.Count;
List<Renderer> taken = new List<Renderer>(renderers.Length);
foreach (Renderer renderer in renderers)
{
if (renderer == null || renderer is ParticleSystemRenderer)
@@ -293,11 +393,13 @@ namespace NecromancerTome
}
Converted.Add(new GhostRenderer { Renderer = renderer, Originals = sources });
taken.Add(renderer);
if (Convert(renderer, sources))
{
converted++;
}
}
_body.Renderers = taken.ToArray();
// The lever count is the half that answers "will the console command reach him":
// desaturation and opacity come from different properties, and the body had the first
Binary file not shown.
Binary file not shown.