Skip to content

[ADD] Аллергии#2571

Open
Rorkh wants to merge 16 commits intoAdventureTimeSS14:masterfrom
Rorkh:allergies-feature
Open

[ADD] Аллергии#2571
Rorkh wants to merge 16 commits intoAdventureTimeSS14:masterfrom
Rorkh:allergies-feature

Conversation

@Rorkh
Copy link
Contributor

@Rorkh Rorkh commented Mar 2, 2026

Описание PR

Добавил систему аллергий. Пикнув трейт, добавляющий компонент AllergicComponent, существо может получить от Min до Max рандомных аллергий на ProtoId.

Возможные реагенты, на которых может быть аллергия, никак не ограничиваются - это элемент фана. С учетом их количества, скорее всего, игрок получит аллергию на некрозол, колу, черного русского, или еще какую-то фигню, поэтому этот трейт дает только -1 очко.

При употреблении реагента, на который имеется аллергия, существо также будет получать 0.5 урона, как если бы этот реагент имел !type:HealthChange эффект.

Наличие аллергии может быть выявлено с помощью медицинского сканера. Полный список аллергенов может быть выявлен с помощью тыка на игрока стерильной палочкой для сбора "биологического образца" и помещением этого образца в диагностировщик заболеваний. Пожужжав, он выдаст бумажку с списком аллергий, или с диагнозом, что их нет, если это исходит из образца.

Каждая стерильная палочка предполагается одноразовой, поэтому ей добавлено свойство накапливать список "аллергий" на себе - т.е если использовать ее на человеке с аллергией, она сохранит информацию об этих аллергиях, которые не будут очищены при следующем использовании, а только дополнены, если будет, чем.

Также было добавлен реагент ADTSanallergium, или же саналлергин, который способен избавить существо от аллергий. Для этого его нужно вколоть (минимум 10 ед.) вместе с реагентами, которые вызывают аллергию у существа, после чего аллергия на эти реагенты пропадет.

Этот MR нацелен только на добавление минимума для аллергий, поэтому тут не затронуты вопросы распространения аллергий и аллергического коллапса общества.

Если этот MR будет принят, я бы хотел заняться созданием какого-то антагониста нурглита нечистого, цель которого - сделать так, чтобы станция захлебнулась в говне потонула в болезнях.

Дополнение (последние правки)

Ввёл систему стака аллергии. Употребление вещества с аллергеном увеличивает его на значение StackGrow, и значение стака снижается само по себе каждые StackFadeRate (5) секунд

Когда значение стака >0, каждые от MinimumTimeTilNextShockEvent до MaximumTimeTilNextShockEvent (5, 10) секунд происходит "событие анафилактического шока". При событии анафилактического шока, выбирается один из прототипов allergicReaction, у которого threshold соотв. текущему значению стака, и применяются его эффекты.

Почему / Баланс

Дополнение (последние правки)

При тесте было замечено, что если ввести реагент аллергена в кол-ве 10 ед., то при его полном метаболизме стэк равняется ~7 единиц. Получается, для реакции, когда игрок начнет получать 3 airloss каждые 5-10 секунд, игроку надо употребить около 25 единиц аллергена (меньше кружки).

Возможно, слишком милосердно, и надо или повысить StackGrow еще на 0.2-0.3 ед., или повысить урон, я хз. Предлагайте.

Техническая информация

  • Изменения были протестированы на локальном сервере, и всё работает отлично.
  • PR закончен и требует просмотра изменений.

Медиа

Ща ща.

Чейнджлог

🆑 Rorkh

  • add: Трейт для аллергии и система аллергий

@github-actions github-actions bot added Status: Needs Review size/M Changes: UI Изменение интерфейса Changes: Localization Изменение локализации labels Mar 2, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 2, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

Добавлена система аллергий: новый сет компонентов и систем (AllergicComponent, AllergicSystem и связанные файлы) для генерации триггеров, учёта стека аллергии, событий шока и применения эффектов. Введён ByRef‑события AllergyTriggeredEvent/AllergyFadedEvent. Метаболизатор теперь поднимает GetReagentEffectsEvent для модификации эффектов. Добавлены эффекты PurgeAllergies и AdjustAllergicStack, реагент ADTSanallergium, трейт Allergic, DiseaseDiagnoserSystem и изменения в UI (аллергия в HealthAnalyzer) и ботанике (swab собирает триггеры).

Suggested labels

S: Untriaged

Suggested reviewers

  • Unlumy
  • Ratyyy
  • M1and1B
🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.42% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed Заголовок '[ADD] Аллергии' ясно и кратко описывает главное изменение PR - добавление системы аллергий.
Description check ✅ Passed Описание PR содержит детальное объяснение системы аллергий, её механики, баланса и технической информации, полностью соответствует изменениям в pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

🧹 Nitpick comments (3)
Content.Shared/ADT/Medical/DiseaseDiagnoserComponent.cs (1)

9-10: Рекомендуется добавить XML-документацию для класса

Для важных компонентов рекомендуется добавлять /// <summary> документацию, описывающую назначение компонента.

Предлагаемое дополнение
+/// <summary>
+/// Компонент для диагностического устройства болезней.
+/// Используется для анализа образцов и выявления аллергий.
+/// </summary>
 [RegisterComponent, NetworkedComponent, AutoGenerateComponentState]
 public sealed partial class DiseaseDiagnoserComponent : Component
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Shared/ADT/Medical/DiseaseDiagnoserComponent.cs` around lines 9 - 10,
Add an XML documentation summary for the DiseaseDiagnoserComponent class by
inserting a triple-slash comment (/// <summary>...</summary>) immediately above
the declaration of the public sealed partial class DiseaseDiagnoserComponent
(the class annotated with [RegisterComponent, NetworkedComponent,
AutoGenerateComponentState]) that briefly describes the component's purpose and
responsibilities.
Content.Shared/ADT/Body/Allergies/AlergicComponent.cs (1)

7-12: Добавьте /// summary для класса и Triggers.

Для ключевого компонента аллергий лучше закрыть документацию на уровне класса и основного поля.

📝 Предлагаемая правка
 [RegisterComponent, NetworkedComponent]
+/// <summary>
+/// Хранит данные об аллергиях сущности и диапазон их случайной генерации.
+/// </summary>
 public sealed partial class AllergicComponent : Component
 {
+    /// <summary>
+    /// Список реагентов, на которые у сущности аллергия.
+    /// </summary>
     [DataField]
     public List<ProtoId<ReagentPrototype>> Triggers = new();

As per coding guidelines: **/*.cs: «предлагай /// summary документацию к C# коду, к важным функциям или классам».

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Shared/ADT/Body/Allergies/AlergicComponent.cs` around lines 7 - 12,
Добавьте XML-документацию /// <summary> к самому классу AllergicComponent
(sealed partial class AllergicComponent : Component) и к основному полю Triggers
(DataField public List<ProtoId<ReagentPrototype>> Triggers), коротко описав
назначение компонента и что содержит Triggers (список реагентов/триггеров
аллергии); поместите комментарии непосредственно над объявлением класса и над
полем Triggers в соответствии с C# документационными шаблонами.
Content.Server/ADT/Medical/EntitySystems/DiseaseDiagnoserSystem.cs (1)

18-169: Добавьте /// <summary> для публичного API этого класса.

Для DiseaseDiagnoserSystem и его публичных методов (TryStart, Stop, GetReport, Finish, HasPower) стоит добавить XML-документацию — это упростит поддержку и чтение кода.

As per coding guidelines "и предлагай /// summary документацию к C# коду, к важным функциям или классам".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Medical/EntitySystems/DiseaseDiagnoserSystem.cs` around
lines 18 - 169, Add XML documentation comments (/// <summary> and where
appropriate <param> and <returns>) for the public class DiseaseDiagnoserSystem
and its public methods TryStart(Entity<DiseaseDiagnoserComponent>, EntityUid?),
Stop(Entity<DiseaseDiagnoserComponent>), GetReport(BotanySwabComponent),
Finish(Entity<DiseaseDiagnoserComponent>), and
HasPower(Entity<DiseaseDiagnoserComponent>). Each summary should concisely
describe the purpose of the class/method; include <param name="...">
descriptions for parameters and a <returns> for GetReport and HasPower
indicating what they return and any important semantics (e.g., side effects,
when methods no-op). Ensure the comments are placed immediately above the
class/method declarations.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Content.Server/ADT/Body/AllergicSystem.cs`:
- Around line 40-50: The code uses _random.Next(min, max) which excludes the
upper bound and then creates picked with possible duplicates, so allergiesCount
may be too small and picks non-unique; fix by using _random.Next(min, max + 1)
for inclusive Max (or otherwise ensure intended bounds) and generate unique
indices for picked (e.g. sample without replacement: build a sequence of
0..reagentsCount-1, shuffle or OrderBy(_ => _random.Next()) and
Take(allergiesCount, ensuring allergiesCount <= reagentsCount) or use a HashSet
loop to produce distinct picks) before iterating prototypes and using
picked.Contains(index) to populate allergies (refer to symbols: _random.Next,
allergiesCount, picked, reagentsCount,
_proto.EnumeratePrototypes<ReagentPrototype>(), allergies).

In `@Content.Server/ADT/Medical/EntitySystems/DiseaseDiagnoserSystem.cs`:
- Around line 134-136: The code reads container.ContainedEntities.First()
without checking for an empty container, which can throw if the container is
empty; before accessing the first entity (swabEnt) in the DiseaseDiagnoserSystem
(where swabEnt and TryComp<BotanySwabComponent> are used), guard by checking
that container != null and container.ContainedEntities has at least one element
(e.g., Any() or Count > 0) and return/skip processing if it's empty so you never
call First() on an empty collection and avoid the exception.

In `@Content.Server/Botany/Components/BotanySwabComponent.cs`:
- Around line 19-26: XML-документация для поля AllergicTriggers находится внутри
блока ADT-Tweak комментариев; вынеси строку с XML-подсказкой (/// <summary> ...
</summary>) и связанные XML-строки наружу, оставив блок ADT-Tweak только вокруг
объявления поля AllergicTriggers (и атрибута [DataField]) в классе
BotanySwabComponent, чтобы ADT-Tweak обрамлял только код, а не XML-документацию.

In `@Content.Server/Botany/Systems/BotanySwabSystem.cs`:
- Around line 111-117: Вместо присваивания ссылки на коллекцию allergic.Triggers
сохраните её копию, чтобы изменения в компоненте не мутировали swab: в коде
BotanySwabSystem при установке swab.AllergicTriggers (когда AllergicComponent
найден) создайте новый список из allergic.Triggers (например через ToList / new
List(...)) и присвойте его; оставьте также логику "snowball" в ветке
конкатенации, но убедитесь, что итоговый swab.AllergicTriggers — независимая
копия (Distinct().ToList()).

In `@Resources/Locale/ru-RU/ADT/allergies/allergies.ftl`:
- Around line 3-4: В строках с ключами botany-swab-unusable-plant и
botany-swab-unusable-bio исправьте опечатки в русских сообщениях: заменить
«непригода» на «непригодна» и «образов» на полное слово «образцов», т.е.
привести строки к корректным фразам типа «Палочка непригодна для сбора пыльцы.»
и «Палочка непригодна для взятия биологических образцов.».

In `@Resources/Locale/ru-RU/ADT/reagents/meta/medicine.ftl`:
- Line 59: Fix the typo in the localization entry reagent-desc-sanallergium by
replacing "имунной" with the correct spelling "иммунной" so the value reads:
"Используется для перманентного снижения иммунной реакции пациента к аллергенам
в крови."; update only the string value for reagent-desc-sanallergium in the
medicine.ftl file.

In `@Resources/Prototypes/ADT/Traits/disabilities.yml`:
- Around line 91-93: The trait uses the wrong key name "component" so the system
won't emit the expected AllergicComponent; change the key from "component" to
"components" in this trait (the block containing "- type: Allergic" and "cost:
-1") so the trait exposes the AllergicComponent as intended.

---

Nitpick comments:
In `@Content.Server/ADT/Medical/EntitySystems/DiseaseDiagnoserSystem.cs`:
- Around line 18-169: Add XML documentation comments (/// <summary> and where
appropriate <param> and <returns>) for the public class DiseaseDiagnoserSystem
and its public methods TryStart(Entity<DiseaseDiagnoserComponent>, EntityUid?),
Stop(Entity<DiseaseDiagnoserComponent>), GetReport(BotanySwabComponent),
Finish(Entity<DiseaseDiagnoserComponent>), and
HasPower(Entity<DiseaseDiagnoserComponent>). Each summary should concisely
describe the purpose of the class/method; include <param name="...">
descriptions for parameters and a <returns> for GetReport and HasPower
indicating what they return and any important semantics (e.g., side effects,
when methods no-op). Ensure the comments are placed immediately above the
class/method declarations.

In `@Content.Shared/ADT/Body/Allergies/AlergicComponent.cs`:
- Around line 7-12: Добавьте XML-документацию /// <summary> к самому классу
AllergicComponent (sealed partial class AllergicComponent : Component) и к
основному полю Triggers (DataField public List<ProtoId<ReagentPrototype>>
Triggers), коротко описав назначение компонента и что содержит Triggers (список
реагентов/триггеров аллергии); поместите комментарии непосредственно над
объявлением класса и над полем Triggers в соответствии с C# документационными
шаблонами.

In `@Content.Shared/ADT/Medical/DiseaseDiagnoserComponent.cs`:
- Around line 9-10: Add an XML documentation summary for the
DiseaseDiagnoserComponent class by inserting a triple-slash comment (///
<summary>...</summary>) immediately above the declaration of the public sealed
partial class DiseaseDiagnoserComponent (the class annotated with
[RegisterComponent, NetworkedComponent, AutoGenerateComponentState]) that
briefly describes the component's purpose and responsibilities.

ℹ️ Review info

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5b770ed and fde50c2.

📒 Files selected for processing (18)
  • Content.Client/HealthAnalyzer/UI/HealthAnalyzerWindow.xaml
  • Content.Client/HealthAnalyzer/UI/HealthAnalyzerWindow.xaml.cs
  • Content.Server/ADT/Body/AllergicSystem.cs
  • Content.Server/ADT/Medical/EntitySystems/DiseaseDiagnoserSystem.cs
  • Content.Server/Body/Systems/MetabolizerSystem.cs
  • Content.Server/Botany/Components/BotanySwabComponent.cs
  • Content.Server/Botany/Systems/BotanySwabSystem.cs
  • Content.Shared/ADT/Body/Allergies/AlergicComponent.cs
  • Content.Shared/ADT/EntityEffects/PurgeAllergies.cs
  • Content.Shared/ADT/Medical/DiseaseDiagnoserComponent.cs
  • Resources/Locale/ru-RU/ADT/allergies/allergies.ftl
  • Resources/Locale/ru-RU/ADT/guidebook/chemistry/effects.ftl
  • Resources/Locale/ru-RU/ADT/reagents/meta/medicine.ftl
  • Resources/Locale/ru-RU/ADT/traits/disabilities.ftl
  • Resources/Prototypes/ADT/Reagents/medicine.yml
  • Resources/Prototypes/ADT/Recipes/Reactions/medicine.yml
  • Resources/Prototypes/ADT/Traits/disabilities.yml
  • Resources/Prototypes/Entities/Structures/Machines/Medical/disease_diagnoser.yml

@Rorkh
Copy link
Contributor Author

Rorkh commented Mar 2, 2026

Ёмаё

@github-actions
Copy link
Contributor

github-actions bot commented Mar 2, 2026

This pull request has conflicts, please resolve those before we can evaluate the pull request.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
Content.Server/ADT/Medical/EntitySystems/DiseaseDiagnoserSystem.cs (1)

18-171: Добавьте /// <summary> для класса и публичных методов системы.

Для нового важного server-side API это улучшит поддержку и читаемость.

As per coding guidelines: «и предлагай /// summary документацию к C# коду, к важным функциям или классам».

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Medical/EntitySystems/DiseaseDiagnoserSystem.cs` around
lines 18 - 171, Add XML documentation comments (/// <summary> ... </summary>)
for the DiseaseDiagnoserSystem class and its public API methods to satisfy
coding guidelines: document the purpose of the class and each public method
(Initialize, TryStart, Stop, GetReport, Finish, Update, HasPower) and briefly
describe important parameters/return values (e.g., entity, user,
BotanySwabComponent return string) so readers and tooling can understand the
server-side API.
Content.Server/ADT/Body/AllergicSystem.cs (1)

13-81: Добавьте /// <summary> для AllergicSystem и ключевых методов.

Это повысит понятность новой игровой механики в поддержке.

As per coding guidelines: «и предлагай /// summary документацию к C# коду, к важным функциям или классам».

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.cs` around lines 13 - 81, Add XML
documentation summaries for the AllergicSystem class and its key methods:
provide a /// <summary> for the AllergicSystem class explaining it handles
reagent-triggered allergy effects, a summary for GetRandomAllergies describing
it returns a randomized list of reagent prototype IDs between min and max, and
brief <param> and <returns> tags; add summaries for OnInit (initializes
component.Triggers using GetRandomAllergies) and OnGetReagentEffects (applies
allergy damage effect when reagent matches component.Triggers), mentioning
important parameters (uid, component, ev) and the effect produced. Ensure the
docs are included above the declarations of AllergicSystem, GetRandomAllergies,
OnInit, and OnGetReagentEffects.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Content.Server/Botany/Systems/BotanySwabSystem.cs`:
- Line 132: The method signature change for OnDoAfter in class BotanySwabSystem
needs the ADT marker on the signature itself; add a comment like "// ADT-Tweak:
<brief reason>" immediately above (or on the same line as) the modified
signature of private void OnDoAfter(EntityUid uid, BotanySwabComponent swab,
DoAfterEvent args) so the ADT marker covers the signature rather than only the
inner block, keeping the marker style consistent with other C# ADT comments in
the repository.

---

Nitpick comments:
In `@Content.Server/ADT/Body/AllergicSystem.cs`:
- Around line 13-81: Add XML documentation summaries for the AllergicSystem
class and its key methods: provide a /// <summary> for the AllergicSystem class
explaining it handles reagent-triggered allergy effects, a summary for
GetRandomAllergies describing it returns a randomized list of reagent prototype
IDs between min and max, and brief <param> and <returns> tags; add summaries for
OnInit (initializes component.Triggers using GetRandomAllergies) and
OnGetReagentEffects (applies allergy damage effect when reagent matches
component.Triggers), mentioning important parameters (uid, component, ev) and
the effect produced. Ensure the docs are included above the declarations of
AllergicSystem, GetRandomAllergies, OnInit, and OnGetReagentEffects.

In `@Content.Server/ADT/Medical/EntitySystems/DiseaseDiagnoserSystem.cs`:
- Around line 18-171: Add XML documentation comments (/// <summary> ...
</summary>) for the DiseaseDiagnoserSystem class and its public API methods to
satisfy coding guidelines: document the purpose of the class and each public
method (Initialize, TryStart, Stop, GetReport, Finish, Update, HasPower) and
briefly describe important parameters/return values (e.g., entity, user,
BotanySwabComponent return string) so readers and tooling can understand the
server-side API.

ℹ️ Review info

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fde50c2 and 45fb046.

📒 Files selected for processing (9)
  • Content.Server/ADT/Body/AllergicSystem.cs
  • Content.Server/ADT/Medical/EntitySystems/DiseaseDiagnoserSystem.cs
  • Content.Server/Botany/Components/BotanySwabComponent.cs
  • Content.Server/Botany/Systems/BotanySwabSystem.cs
  • Resources/Locale/ru-RU/ADT/allergies/allergies.ftl
  • Resources/Locale/ru-RU/ADT/reagents/meta/medicine.ftl
  • Resources/Prototypes/ADT/Reagents/medicine.yml
  • Resources/Prototypes/ADT/Recipes/Reactions/medicine.yml
  • Resources/Prototypes/ADT/Traits/disabilities.yml
🚧 Files skipped from review as they are similar to previous changes (3)
  • Resources/Locale/ru-RU/ADT/reagents/meta/medicine.ftl
  • Resources/Prototypes/ADT/Reagents/medicine.yml
  • Content.Server/Botany/Components/BotanySwabComponent.cs

@HyperB1
Copy link
Contributor

HyperB1 commented Mar 3, 2026

По идее эффектом от аллергии должна быть тряска/кашель/удушение (человек временно прекращает дышать, как при захвате-удушении, эффект аккумулируется с кол-вом аллергена), анафилактический шок в общем, а останавливать его должны антигистаминные препараты в виде дифенгидрамина и эпинефрина. Простое отравление без визуальных проявлений и иммунной реакции - это просто несварение.

@Rorkh
Copy link
Contributor Author

Rorkh commented Mar 3, 2026

По идее эффектом от аллергии должна быть тряска/кашель/удушение (человек временно прекращает дышать, как при захвате-удушении, эффект аккумулируется с кол-вом аллергена), анафилактический шок в общем, а останавливать его должны антигистаминные препараты в виде дифенгидрамина и эпинефрина. Простое отравление без визуальных проявлений и иммунной реакции - это просто несварение.

Окей. Доработаю

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

🧹 Nitpick comments (7)
Content.Server/ADT/Body/AllergicSystem.Shock.cs (2)

62-62: Используйте .Length вместо .Count() для массива.

Effects — это массив EntityEffect[], для которого .Length эффективнее, чем LINQ-метод .Count().

♻️ Предлагаемое исправление
-            EntityEffect effect = picked.Effects[_random.Next(0, picked.Effects.Count())];
+            EntityEffect effect = picked.Effects[_random.Next(0, picked.Effects.Length)];
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs` at line 62, The code selects
a random effect using picked.Effects.Count(), but Effects is an EntityEffect[]
array so replace the LINQ call with the array property: use
picked.Effects.Length when calling _random.Next (e.g., _random.Next(0,
picked.Effects.Length)) to avoid the overhead of Count(); update the line that
assigns EntityEffect effect to reference picked.Effects.Length instead of
.Count().

22-26: Упростите условие в ShockOnTrigger.

Проверка if (!allergic.InShock) избыточна — присвоение true идемпотентно.

♻️ Предлагаемое исправление
     private void ShockOnTrigger(EntityUid uid, AllergicComponent allergic, ref AllergyTriggeredEvent ev)
     {
-        if (!allergic.InShock)
-            allergic.InShock = true;
+        allergic.InShock = true;
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs` around lines 22 - 26, Remove
the redundant conditional in ShockOnTrigger: instead of checking if
(!allergic.InShock) before setting it, directly set allergic.InShock = true
inside ShockOnTrigger (the assignment is idempotent). Update the ShockOnTrigger
method (which takes EntityUid uid, AllergicComponent allergic, ref
AllergyTriggeredEvent ev) to remove the if-check and perform the direct
assignment.
Content.Server/ADT/Body/AllergicSystem.cs (2)

55-55: Неуместное сообщение в отладочном логе.

Log.Debug("We got some nasty shit inside!") содержит ненормативную лексику. Рекомендуется заменить на более профессиональное сообщение.

♻️ Предлагаемое исправление
-        Log.Debug("We got some nasty shit inside!");
+        Log.Debug($"Allergy triggered for reagent: {ev.Reagent.Prototype}");
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.cs` at line 55, Replace the
unprofessional debug message in AllergicSystem (the Log.Debug call currently
saying "We got some nasty shit inside!") with a concise, professional log
string; locate the Log.Debug invocation inside the AllergicSystem class/method
and change it to a neutral message such as "Allergen detected in system" or
similar that conveys the same meaning without profanity, preserving log level
and surrounding logic.

14-17: Рекомендуется добавить XML-документацию для класса AllergicSystem.

Класс является основной системой управления аллергиями, но не имеет документации.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.cs` around lines 14 - 17, Добавьте
XML‑документацию для класса AllergicSystem: над объявлением public sealed
partial class AllergicSystem : EntitySystem добавьте <summary> с кратким
описанием роли системы (управление аллергиями и реакциями), упомяните ключевые
зависимости/поля (_random, _proto) и любые заметные детали поведения или
взаимодействия; при необходимости добавьте <remarks> для более подробных деталей
о жизненном цикле/обработчиках внутри класса.
Content.Server/ADT/Body/AllergicSystem.Stacks.cs (2)

1-4: Неиспользуемые директивы using.

Следующие using не используются в этом файле и могут быть удалены:

  • System.Linq
  • Content.Shared.Chemistry.Reagent
  • Robust.Shared.Prototypes
♻️ Предлагаемое исправление
-using System.Linq;
 using Content.Shared.ADT.Body.Allergies;
-using Content.Shared.Chemistry.Reagent;
-using Robust.Shared.Prototypes;

 namespace Content.Server.ADT.Body;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.Stacks.cs` around lines 1 - 4, Remove
the unused using directives to clean up imports: delete System.Linq,
Content.Shared.Chemistry.Reagent, and Robust.Shared.Prototypes from the top of
AllergicSystem.Stacks.cs so only required namespaces (e.g.,
Content.Shared.ADT.Body.Allergies) remain; verify that no symbols from those
namespaces are referenced in methods or classes (e.g., any code in this file
referencing LINQ, Reagent, or Prototype APIs) before committing.

12-16: Неиспользуемый параметр ev в IncrementStackOnTrigger.

Параметр ref AllergyTriggeredEvent ev передаётся, но не используется в методе. Если в будущем планируется использовать информацию о реагенте из события, это корректно. Иначе рассмотрите удаление параметра.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.Stacks.cs` around lines 12 - 16,
Параметр ref AllergyTriggeredEvent ev в методе IncrementStackOnTrigger не
используется — удалите его из сигнатуры IncrementStackOnTrigger (и из всех мест,
где этот метод передаётся/подписывается), либо если планируется использовать
данные события, используйте ev внутри метода (например для проверки реагента)
вместо удалённого параметра; проверьте также соответствие делегатов/обработчиков
событий и сохраните вызов AdjustAllergyStack(uid, allergic.StackGrow, allergic)
как есть.
Content.Shared/ADT/Body/Allergies/Prototypes/AllergicReactionPrototype.cs (1)

6-17: Рекомендуется добавить XML-документацию для класса.

Класс AllergicReactionPrototype является публичным прототипом, но не имеет документации. Рекомендуется добавить /// <summary> для описания назначения класса и его полей.

📝 Предлагаемая документация
+/// <summary>
+/// Прототип аллергической реакции, определяющий эффекты и порог срабатывания.
+/// </summary>
 [Prototype("allergicReaction")]
 public sealed partial class AllergicReactionPrototype : IPrototype
 {
     [IdDataField]
     public string ID { get; private set; } = default!;

+    /// <summary>
+    /// Эффекты, применяемые при срабатывании реакции.
+    /// </summary>
     [DataField("effects")]
     public EntityEffect[] Effects = default!;

+    /// <summary>
+    /// Порог стэка аллергии для активации реакции.
+    /// </summary>
     [DataField]
     public float StackThreshold;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Shared/ADT/Body/Allergies/Prototypes/AllergicReactionPrototype.cs`
around lines 6 - 17, Add XML summary documentation to the public prototype and
its public members: add a /// <summary> describing the purpose of the
AllergicReactionPrototype class, and /// <summary> (and optional <remarks> or
<example> if useful) for the ID property, Effects field, and StackThreshold
field; ensure the comments sit immediately above the declarations for
AllergicReactionPrototype, ID, Effects, and StackThreshold so IDEs and generated
docs pick them up.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Content.Server/ADT/Body/AllergicEvents.cs`:
- Around line 9-16: The AllergyTriggeredEvent.Reagent field is left default
because AllergicSystem creates the event without setting the reagent before
calling RaiseLocalEvent; update the code in AllergicSystem where
AllergyTriggeredEvent triggered = new(); and RaiseLocalEvent(uid, ref
triggered); to populate the Reagent field (e.g., create the event with
AllergyTriggeredEvent triggered = new() { Reagent = theReagentId } or assign
triggered.Reagent = theReagentId before calling RaiseLocalEvent) so the Reagent
value is passed to listeners.

In `@Content.Server/ADT/Body/AllergicSystem.cs`:
- Around line 19-20: The field _allergyDamageGroup is declared with the wrong
prototype type: change its type from ProtoId<DamageGroupPrototype> to
ProtoId<DamageTypePrototype> and initialize it with "Poison" as a
DamageTypePrototype; update any code that treats _allergyDamageGroup as a damage
group (notably the usage near _allergyDamageTypeProto where the code
indexes/queries a DamageTypePrototype by _allergyDamageGroup) to instead use the
correct DamageType prototype id or resolve a DamageGroup from the DamageType if
that was intended (adjust code referencing _allergyDamageGroup and
_allergyDamageTypeProto so the types match, e.g., use
ProtoId<DamageTypePrototype> for the id variable and look up DamageTypePrototype
by that id).

In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs`:
- Around line 49-50: The timer check is inverted so effects never run; replace
the guard that currently reads "if (_timing.CurTime > allergic.NextShockEvent)
return;" with a check that returns while time has not yet arrived, e.g. use
"_timing.CurTime < allergic.NextShockEvent" (or "_timing.CurTime <=" depending
on desired equality semantics) so the shock effects in the AllergicSystem
(referencing allergic.NextShockEvent and _timing.CurTime) execute when CurTime
reaches or exceeds NextShockEvent.

In `@Content.Shared/ADT/Body/Allergies/AlergicComponent.cs`:
- Around line 7-8: The file name contains a typo: rename the source file from
AlergicComponent.cs to AllergicComponent.cs to match the public sealed partial
class AllergicComponent definition; update any project/solution entries and any
references/usings that import AlergicComponent.cs so they point to
AllergicComponent.cs (ensuring the class symbol AllergicComponent remains
unchanged), and run a build to verify there are no remaining references to the
old filename.

In `@Resources/Prototypes/ADT/Medical/allergy.yml`:
- Around line 1-6: The YAML uses the key "threshold" but the C# prototype
property is declared as [DataField] public float StackThreshold in
AllergicReactionPrototype.cs (which maps to "stackThreshold" in YAML by
convention), so change the YAML to use "stackThreshold: 5" (or alternatively add
an explicit name to the DataField attribute on StackThreshold), ensuring the key
matches the DataField name used by AllergicReactionPrototype.cs for the
allergicReaction/mildAllergicReaction entry.

---

Nitpick comments:
In `@Content.Server/ADT/Body/AllergicSystem.cs`:
- Line 55: Replace the unprofessional debug message in AllergicSystem (the
Log.Debug call currently saying "We got some nasty shit inside!") with a
concise, professional log string; locate the Log.Debug invocation inside the
AllergicSystem class/method and change it to a neutral message such as "Allergen
detected in system" or similar that conveys the same meaning without profanity,
preserving log level and surrounding logic.
- Around line 14-17: Добавьте XML‑документацию для класса AllergicSystem: над
объявлением public sealed partial class AllergicSystem : EntitySystem добавьте
<summary> с кратким описанием роли системы (управление аллергиями и реакциями),
упомяните ключевые зависимости/поля (_random, _proto) и любые заметные детали
поведения или взаимодействия; при необходимости добавьте <remarks> для более
подробных деталей о жизненном цикле/обработчиках внутри класса.

In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs`:
- Line 62: The code selects a random effect using picked.Effects.Count(), but
Effects is an EntityEffect[] array so replace the LINQ call with the array
property: use picked.Effects.Length when calling _random.Next (e.g.,
_random.Next(0, picked.Effects.Length)) to avoid the overhead of Count(); update
the line that assigns EntityEffect effect to reference picked.Effects.Length
instead of .Count().
- Around line 22-26: Remove the redundant conditional in ShockOnTrigger: instead
of checking if (!allergic.InShock) before setting it, directly set
allergic.InShock = true inside ShockOnTrigger (the assignment is idempotent).
Update the ShockOnTrigger method (which takes EntityUid uid, AllergicComponent
allergic, ref AllergyTriggeredEvent ev) to remove the if-check and perform the
direct assignment.

In `@Content.Server/ADT/Body/AllergicSystem.Stacks.cs`:
- Around line 1-4: Remove the unused using directives to clean up imports:
delete System.Linq, Content.Shared.Chemistry.Reagent, and
Robust.Shared.Prototypes from the top of AllergicSystem.Stacks.cs so only
required namespaces (e.g., Content.Shared.ADT.Body.Allergies) remain; verify
that no symbols from those namespaces are referenced in methods or classes
(e.g., any code in this file referencing LINQ, Reagent, or Prototype APIs)
before committing.
- Around line 12-16: Параметр ref AllergyTriggeredEvent ev в методе
IncrementStackOnTrigger не используется — удалите его из сигнатуры
IncrementStackOnTrigger (и из всех мест, где этот метод
передаётся/подписывается), либо если планируется использовать данные события,
используйте ev внутри метода (например для проверки реагента) вместо удалённого
параметра; проверьте также соответствие делегатов/обработчиков событий и
сохраните вызов AdjustAllergyStack(uid, allergic.StackGrow, allergic) как есть.

In `@Content.Shared/ADT/Body/Allergies/Prototypes/AllergicReactionPrototype.cs`:
- Around line 6-17: Add XML summary documentation to the public prototype and
its public members: add a /// <summary> describing the purpose of the
AllergicReactionPrototype class, and /// <summary> (and optional <remarks> or
<example> if useful) for the ID property, Effects field, and StackThreshold
field; ensure the comments sit immediately above the declarations for
AllergicReactionPrototype, ID, Effects, and StackThreshold so IDEs and generated
docs pick them up.

ℹ️ Review info

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 45fb046 and bcb05c5.

📒 Files selected for processing (7)
  • Content.Server/ADT/Body/AllergicEvents.cs
  • Content.Server/ADT/Body/AllergicSystem.Shock.cs
  • Content.Server/ADT/Body/AllergicSystem.Stacks.cs
  • Content.Server/ADT/Body/AllergicSystem.cs
  • Content.Shared/ADT/Body/Allergies/AlergicComponent.cs
  • Content.Shared/ADT/Body/Allergies/Prototypes/AllergicReactionPrototype.cs
  • Resources/Prototypes/ADT/Medical/allergy.yml

@Rorkh
Copy link
Contributor Author

Rorkh commented Mar 3, 2026

WIP

@Rorkh Rorkh changed the title [ADD] Аллергии [ADD] [WIP] Аллергии Mar 3, 2026
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (10)
Content.Shared/ADT/Body/Allergies/AllergicComponent.cs (1)

66-72: Лишняя пустая строка.

Между summary и атрибутом ViewVariables есть лишняя пустая строка (строка 69).

🧹 Предлагаемое исправление
     /// <summary>
     /// Значение роста стака при метаболизме аллергена.
     /// </summary>
-
     [ViewVariables(VVAccess.ReadWrite)]
     [DataField]
     public float StackGrow = 0.5f;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Shared/ADT/Body/Allergies/AllergicComponent.cs` around lines 66 - 72,
Remove the extra blank line between the XML summary comment and the
ViewVariables attribute for the StackGrow field in AllergicComponent.cs; place
[ViewVariables(VVAccess.ReadWrite)] immediately after the summary so the
attribute is directly attached to the public float StackGrow = 0.5f declaration.
Content.Server/ADT/Body/AllergicEvents.cs (2)

6-16: Добавьте русскоязычную документацию для консистентности.

XML-комментарии на английском, тогда как в AllergicComponent.cs используется русский язык. Рекомендуется привести к единому стилю.

📝 Предлагаемое исправление
 /// <summary>
-/// When allergy triggered by allergens in bloodstream.
+/// Событие срабатывания аллергии при наличии аллергенов в кровотоке.
 /// </summary>
 [ByRefEvent]
 public struct AllergyTriggeredEvent;

 /// <summary>
-/// When allergy stack has faded to zero.
+/// Событие затухания стака аллергии до нуля.
 /// </summary>
 [ByRefEvent]
 public struct AllergyFadedEvent;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicEvents.cs` around lines 6 - 16, Добавьте
русскоязычные XML-комментарии для структур AllergyTriggeredEvent и
AllergyFadedEvent, чтобы привести документацию к единому стилю с
AllergicComponent.cs; замените или дополните существующие английские комментарии
строками на русском, поясняющими смысл событий (аллергия сработала при наличии
аллергенов в кровотоке для AllergyTriggeredEvent и очистка/затухание эффекта
аллергии до нуля для AllergyFadedEvent), сохранив атрибут [ByRefEvent] и формат
XML-комментариев (/// <summary>...</summary>).

1-2: Удалите неиспользуемые директивы using.

Импорты Content.Shared.Chemistry.Reagent и Robust.Shared.Prototypes не используются в этом файле, так как структуры событий пусты.

🧹 Предлагаемое исправление
-using Content.Shared.Chemistry.Reagent;
-using Robust.Shared.Prototypes;
-
 namespace Content.Server.ADT.Body;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicEvents.cs` around lines 1 - 2, Удалите
неиспользуемые директивы using из файла: уберите строки with
Content.Shared.Chemistry.Reagent и Robust.Shared.Prototypes — они не
используются в этом файле, так как объявленные структуры событий пусты; оставьте
только необходимые using для типов, реально применяемых в AllergicEvents.cs.
Content.Server/ADT/Body/AllergicSystem.Shock.cs (2)

56-56: Используйте .Length вместо .Count() для массива.

Effects — это массив, поэтому .Length эффективнее, чем LINQ-метод .Count().

🧹 Предлагаемое исправление
-            EntityEffect effect = picked.Effects[_random.Next(0, picked.Effects.Count())];
+            EntityEffect effect = picked.Effects[_random.Next(0, picked.Effects.Length)];
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs` at line 56, В методе где
выбирается эффект из picked.Effects (строка с EntityEffect effect =
picked.Effects[_random.Next(0, picked.Effects.Count())];) замените вызов LINQ
.Count() на свойство массива .Length, т.е. использовать picked.Effects.Length
внутри _random.Next, чтобы избегать ненужного вызова LINQ для массива и
сохранить ту же семантику выбора случайного индекса.

8-62: Добавьте XML-документацию для публичных и важных методов.

Методы InitializeShock, UpdateShock и другие не имеют XML-документации.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs` around lines 8 - 62, Add XML
documentation comments to the AllergicSystem class and its public/important
methods: add a <summary> for the class and for InitializeShock, UpdateShock,
Unshock, and AssignNextShockTiming describing their behavior; include <param>
tags for parameters (e.g., uid, allergic, ev) and any remarks about timing or
side-effects (e.g., sets allergic.NextShockEvent, subscribes events, applies
effects); keep comments concise and in English/Russian per project convention
and place them immediately above the corresponding declarations (class
AllergicSystem, methods InitializeShock, UpdateShock, Unshock,
AssignNextShockTiming).
Content.Server/ADT/Body/AllergicSystem.Stacks.cs (2)

21-39: Потенциальный дрейф таймера при отставании.

На строке 38 используется allergic.NextStackFade + allergic.StackFadeRate, что может привести к накоплению отставания, если система обновляется с задержкой. Рекомендуется использовать _timing.CurTime + allergic.StackFadeRate для более предсказуемого поведения.

⏱️ Предлагаемое исправление
-        allergic.NextStackFade = allergic.NextStackFade + allergic.StackFadeRate;
+        allergic.NextStackFade = _timing.CurTime + allergic.StackFadeRate;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.Stacks.cs` around lines 21 - 39, In
UpdateStack, avoid accumulating timer drift by replacing the relative update
allergic.NextStackFade = allergic.NextStackFade + allergic.StackFadeRate with
setting it based on the current time; compute allergic.NextStackFade =
_timing.CurTime + allergic.StackFadeRate so the next fade is scheduled from the
present time rather than from the possibly delayed previous NextStackFade (refer
to UpdateStack, allergic.NextStackFade, allergic.StackFadeRate, and
_timing.CurTime).

1-4: Удалите неиспользуемые директивы using.

Импорты System.Linq, Content.Shared.Chemistry.Reagent и Robust.Shared.Prototypes не используются в этом файле.

🧹 Предлагаемое исправление
-using System.Linq;
 using Content.Shared.ADT.Body.Allergies;
-using Content.Shared.Chemistry.Reagent;
-using Robust.Shared.Prototypes;

 namespace Content.Server.ADT.Body;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.Stacks.cs` around lines 1 - 4, Удалите
неиспользуемые директивы using в файле: уберите строки с using System.Linq,
using Content.Shared.Chemistry.Reagent и using Robust.Shared.Prototypes, оставив
только реально используемые пространства имен (например using
Content.Shared.ADT.Body.Allergies). После удаления выполните сборку или
запустите анализатор (IDE) чтобы убедиться, что больше нет неиспользуемых
импортов.
Content.Server/ADT/Body/AllergicSystem.cs (2)

36-39: Обработчики событий могут быть приватными.

Методы OnInit и OnGetReagentEffects используются только как обработчики событий и могут быть объявлены как private вместо public.

🧹 Предлагаемое исправление
-    public void OnInit(EntityUid uid, AllergicComponent component, ComponentInit args)
+    private void OnInit(EntityUid uid, AllergicComponent component, ComponentInit args)
     {
         component.Triggers = GetRandomAllergies(component.Min, component.Max);
     }

-    public void OnGetReagentEffects(EntityUid uid, AllergicComponent component, ref GetReagentEffectsEvent ev)
+    private void OnGetReagentEffects(EntityUid uid, AllergicComponent component, ref GetReagentEffectsEvent ev)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.cs` around lines 36 - 39, Change the
event-handler methods OnInit and OnGetReagentEffects in the AllergicSystem to be
private instead of public; locate the method declarations for OnInit(EntityUid
uid, AllergicComponent component, ComponentInit args) and
OnGetReagentEffects(...) and update their visibility to private so they remain
accessible to the event wiring but are not exposed publicly, ensuring any event
subscriptions or calls in the same class still match the renamed signatures.

14-105: Добавьте XML-документацию для класса и ключевых методов.

Системе не хватает XML-документации. Рекомендуется добавить описание для класса и метода GetRandomAllergies.

📝 Пример документации
 namespace Content.Server.ADT.Body;

+/// <summary>
+/// Система управления аллергическими реакциями сущностей.
+/// Обрабатывает назначение случайных аллергенов, срабатывание реакций и применение эффектов.
+/// </summary>
 public sealed partial class AllergicSystem : EntitySystem
 {
+    /// <summary>
+    /// Генерирует случайный список аллергенов из доступных реагентов.
+    /// </summary>
+    /// <param name="min">Минимальное количество аллергенов.</param>
+    /// <param name="max">Максимальное количество аллергенов.</param>
+    /// <returns>Список идентификаторов прототипов реагентов-аллергенов.</returns>
     private List<ProtoId<ReagentPrototype>> GetRandomAllergies(int min, int max)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.cs` around lines 14 - 105, Add XML
documentation to the AllergicSystem class and its GetRandomAllergies method: add
a <summary> on the AllergicSystem explaining its responsibility (managing
allergic reaction triggers/effects), and on GetRandomAllergies include
<summary>, <param name="min">, <param name="max"> describing the bounds, and
<returns> explaining it returns a list of ProtoId<ReagentPrototype> representing
the randomly selected allergy reagents; keep descriptions concise and mention
how clamping/random selection works. Also ensure any public-facing methods
referenced by documentation (e.g., Initialize or Update if you document them
later) have appropriate XML comments for consistency.
Content.Shared/ADT/Body/Allergies/Prototypes/AllergicReactionPrototype.cs (1)

6-17: Добавьте XML-документацию и рассмотрите безопасность полей.

Классу не хватает XML-документации. Также поле Effects может быть null, если не указано в YAML, что может вызвать NullReferenceException при использовании в AllergicSystem.Shock.cs.

📝 Предлагаемые улучшения
+/// <summary>
+/// Прототип аллергической реакции, определяющий эффекты и порог срабатывания.
+/// </summary>
 [Prototype("allergicReaction")]
 public sealed partial class AllergicReactionPrototype : IPrototype
 {
     [IdDataField]
     public string ID { get; private set; } = default!;

-    [DataField("effects")]
-    public EntityEffect[] Effects = default!;
+    [DataField("effects", required: true)]
+    public EntityEffect[] Effects = default!;

     [DataField("threshold", required: true)]
     public float StackThreshold;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Shared/ADT/Body/Allergies/Prototypes/AllergicReactionPrototype.cs`
around lines 6 - 17, Add XML documentation to the AllergicReactionPrototype
class and its public members (ID, Effects, StackThreshold) and make Effects
non-nullable at runtime by giving it a safe default (e.g., initialize to an
empty array) or mark the DataField as required; update the definition of
AllergicReactionPrototype (class name + members ID, Effects, StackThreshold) so
AllergicSystem.Shock.cs cannot get a null Effects array at runtime and callers
can rely on a non-null, possibly empty, EntityEffect[].
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs`:
- Around line 46-52: Цикл в InitializeShock выбирает последнюю подходящую
реакцию из _reactions, что даёт непредсказуемый результат; нужно выбрать реакцию
с наибольшим StackThreshold, не превышающим allergic.AllergyStack. Исправьте код
в InitializeShock/блоке, где используется AllergicReactionPrototype picked:
вместо простого перебора без порядка либо отсортируйте _reactions по
StackThreshold по возрастанию/убыванию и возьмите последний/первый подходящий
элемент, либо при перечислении сравнивайте и обновляйте picked только если
reaction.StackThreshold > picked.StackThreshold и reaction.StackThreshold <=
allergic.AllergyStack; обеспечьте, чтобы выбранная реакция была максимальной по
порогу.

---

Nitpick comments:
In `@Content.Server/ADT/Body/AllergicEvents.cs`:
- Around line 6-16: Добавьте русскоязычные XML-комментарии для структур
AllergyTriggeredEvent и AllergyFadedEvent, чтобы привести документацию к единому
стилю с AllergicComponent.cs; замените или дополните существующие английские
комментарии строками на русском, поясняющими смысл событий (аллергия сработала
при наличии аллергенов в кровотоке для AllergyTriggeredEvent и очистка/затухание
эффекта аллергии до нуля для AllergyFadedEvent), сохранив атрибут [ByRefEvent] и
формат XML-комментариев (/// <summary>...</summary>).
- Around line 1-2: Удалите неиспользуемые директивы using из файла: уберите
строки with Content.Shared.Chemistry.Reagent и Robust.Shared.Prototypes — они не
используются в этом файле, так как объявленные структуры событий пусты; оставьте
только необходимые using для типов, реально применяемых в AllergicEvents.cs.

In `@Content.Server/ADT/Body/AllergicSystem.cs`:
- Around line 36-39: Change the event-handler methods OnInit and
OnGetReagentEffects in the AllergicSystem to be private instead of public;
locate the method declarations for OnInit(EntityUid uid, AllergicComponent
component, ComponentInit args) and OnGetReagentEffects(...) and update their
visibility to private so they remain accessible to the event wiring but are not
exposed publicly, ensuring any event subscriptions or calls in the same class
still match the renamed signatures.
- Around line 14-105: Add XML documentation to the AllergicSystem class and its
GetRandomAllergies method: add a <summary> on the AllergicSystem explaining its
responsibility (managing allergic reaction triggers/effects), and on
GetRandomAllergies include <summary>, <param name="min">, <param name="max">
describing the bounds, and <returns> explaining it returns a list of
ProtoId<ReagentPrototype> representing the randomly selected allergy reagents;
keep descriptions concise and mention how clamping/random selection works. Also
ensure any public-facing methods referenced by documentation (e.g., Initialize
or Update if you document them later) have appropriate XML comments for
consistency.

In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs`:
- Line 56: В методе где выбирается эффект из picked.Effects (строка с
EntityEffect effect = picked.Effects[_random.Next(0, picked.Effects.Count())];)
замените вызов LINQ .Count() на свойство массива .Length, т.е. использовать
picked.Effects.Length внутри _random.Next, чтобы избегать ненужного вызова LINQ
для массива и сохранить ту же семантику выбора случайного индекса.
- Around line 8-62: Add XML documentation comments to the AllergicSystem class
and its public/important methods: add a <summary> for the class and for
InitializeShock, UpdateShock, Unshock, and AssignNextShockTiming describing
their behavior; include <param> tags for parameters (e.g., uid, allergic, ev)
and any remarks about timing or side-effects (e.g., sets
allergic.NextShockEvent, subscribes events, applies effects); keep comments
concise and in English/Russian per project convention and place them immediately
above the corresponding declarations (class AllergicSystem, methods
InitializeShock, UpdateShock, Unshock, AssignNextShockTiming).

In `@Content.Server/ADT/Body/AllergicSystem.Stacks.cs`:
- Around line 21-39: In UpdateStack, avoid accumulating timer drift by replacing
the relative update allergic.NextStackFade = allergic.NextStackFade +
allergic.StackFadeRate with setting it based on the current time; compute
allergic.NextStackFade = _timing.CurTime + allergic.StackFadeRate so the next
fade is scheduled from the present time rather than from the possibly delayed
previous NextStackFade (refer to UpdateStack, allergic.NextStackFade,
allergic.StackFadeRate, and _timing.CurTime).
- Around line 1-4: Удалите неиспользуемые директивы using в файле: уберите
строки с using System.Linq, using Content.Shared.Chemistry.Reagent и using
Robust.Shared.Prototypes, оставив только реально используемые пространства имен
(например using Content.Shared.ADT.Body.Allergies). После удаления выполните
сборку или запустите анализатор (IDE) чтобы убедиться, что больше нет
неиспользуемых импортов.

In `@Content.Shared/ADT/Body/Allergies/AllergicComponent.cs`:
- Around line 66-72: Remove the extra blank line between the XML summary comment
and the ViewVariables attribute for the StackGrow field in AllergicComponent.cs;
place [ViewVariables(VVAccess.ReadWrite)] immediately after the summary so the
attribute is directly attached to the public float StackGrow = 0.5f declaration.

In `@Content.Shared/ADT/Body/Allergies/Prototypes/AllergicReactionPrototype.cs`:
- Around line 6-17: Add XML documentation to the AllergicReactionPrototype class
and its public members (ID, Effects, StackThreshold) and make Effects
non-nullable at runtime by giving it a safe default (e.g., initialize to an
empty array) or mark the DataField as required; update the definition of
AllergicReactionPrototype (class name + members ID, Effects, StackThreshold) so
AllergicSystem.Shock.cs cannot get a null Effects array at runtime and callers
can rely on a non-null, possibly empty, EntityEffect[].

ℹ️ Review info

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bcb05c5 and 2d8fc6e.

📒 Files selected for processing (6)
  • Content.Server/ADT/Body/AllergicEvents.cs
  • Content.Server/ADT/Body/AllergicSystem.Shock.cs
  • Content.Server/ADT/Body/AllergicSystem.Stacks.cs
  • Content.Server/ADT/Body/AllergicSystem.cs
  • Content.Shared/ADT/Body/Allergies/AllergicComponent.cs
  • Content.Shared/ADT/Body/Allergies/Prototypes/AllergicReactionPrototype.cs

@github-actions
Copy link
Contributor

This pull request has conflicts, please resolve those before we can evaluate the pull request.

@Rorkh Rorkh changed the title [ADD] [WIP] Аллергии [ADD] Аллергии Mar 14, 2026
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
Content.Shared/ADT/Body/Allergies/AllergicComponent.cs (2)

66-72: Лишняя пустая строка между summary и атрибутом.

На строке 69 есть лишняя пустая строка между закрывающим тегом </summary> и атрибутом [ViewVariables].

🧹 Предлагаемое исправление форматирования
     /// <summary>
     /// Значение роста стака при метаболизме аллергена.
     /// </summary>
-
     [ViewVariables(VVAccess.ReadWrite)]
     [DataField]
     public float StackGrow = 0.5f;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Shared/ADT/Body/Allergies/AllergicComponent.cs` around lines 66 - 72,
The XML summary comment for the StackGrow field in AllergicComponent has an
extra blank line before the [ViewVariables] attribute; remove the empty line so
the closing </summary> tag is immediately followed by the
[ViewVariables(VVAccess.ReadWrite)] attribute above the public float StackGrow =
0.5f declaration to restore proper formatting.

7-11: Добавьте документацию для класса и поля Triggers.

Класс и поле Triggers не имеют XML-документации, в отличие от остальных полей компонента.

📝 Предлагаемое добавление документации
 namespace Content.Shared.ADT.Body.Allergies;

+/// <summary>
+/// Компонент, отвечающий за хранение данных об аллергии сущности:
+/// триггеры (аллергены), стак аллергической реакции и параметры шока.
+/// </summary>
 [RegisterComponent, NetworkedComponent]
 public sealed partial class AllergicComponent : Component
 {
+    /// <summary>
+    /// Список реагентов-аллергенов, на которые у сущности есть аллергия.
+    /// </summary>
     [DataField]
     public List<ProtoId<ReagentPrototype>> Triggers = new();
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Shared/ADT/Body/Allergies/AllergicComponent.cs` around lines 7 - 11,
Add XML documentation for the AllergicComponent class and its Triggers field:
add a /// <summary> on the AllergicComponent type describing that this component
marks entities that react allergically and what behavior it controls, and add a
/// <summary> on the Triggers field explaining that it is a list of
ProtoId<ReagentPrototype> that will trigger the allergy (optionally note
semantics like whether any or all reagents trigger, and expected format). Ensure
the docs match the style of other components in the codebase and reference the
AllergicComponent class and Triggers field names.
Content.Server/ADT/Body/AllergicSystem.Shock.cs (1)

16-65: Рекомендуется добавить XML-документацию к публичным методам.

Методы InitializeShock и UpdateShock не имеют XML-документации. Для важных методов системы рекомендуется добавить краткое описание.

📝 Предлагаемое добавление документации
+    /// <summary>
+    /// Инициализирует подсистему шока: подписывается на события и загружает прототипы реакций.
+    /// </summary>
     public void InitializeShock()
     {
         SubscribeLocalEvent<AllergicComponent, AllergyFadedEvent>(Unshock);
         _reactions = _proto.EnumeratePrototypes<AllergicReactionPrototype>()
             .OrderBy(r => r.StackThreshold)
             .ToList();
     }
+    /// <summary>
+    /// Обновляет состояние шока: проверяет таймер и применяет эффекты реакции при необходимости.
+    /// </summary>
     private void UpdateShock(EntityUid uid, AllergicComponent allergic)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs` around lines 16 - 65, Add
XML documentation comments to the public methods InitializeShock() and
UpdateShock(EntityUid uid, AllergicComponent allergic): add a <summary>
describing the purpose of each method, include <param name="uid"> and <param
name="allergic"> for UpdateShock explaining the entity and component parameters,
and note side-effects (e.g., scheduling shock events or applying effects) so
callers understand behavior; ensure the doc comments are placed immediately
above the method signatures (InitializeShock and UpdateShock) and follow the
project's XML doc style.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs`:
- Around line 1-5: Порядок директив using в AllergicSystem.Shock.cs нарушен —
переместите "using System.Linq;" так, чтобы оно шло после "using
Robust.Shared.Timing;" (сохранив остальные импорты в текущем виде) чтобы все
using-ы были в алфавитном порядке; отредактируйте блок using в начале файла
соответствующим образом.

---

Nitpick comments:
In `@Content.Server/ADT/Body/AllergicSystem.Shock.cs`:
- Around line 16-65: Add XML documentation comments to the public methods
InitializeShock() and UpdateShock(EntityUid uid, AllergicComponent allergic):
add a <summary> describing the purpose of each method, include <param
name="uid"> and <param name="allergic"> for UpdateShock explaining the entity
and component parameters, and note side-effects (e.g., scheduling shock events
or applying effects) so callers understand behavior; ensure the doc comments are
placed immediately above the method signatures (InitializeShock and UpdateShock)
and follow the project's XML doc style.

In `@Content.Shared/ADT/Body/Allergies/AllergicComponent.cs`:
- Around line 66-72: The XML summary comment for the StackGrow field in
AllergicComponent has an extra blank line before the [ViewVariables] attribute;
remove the empty line so the closing </summary> tag is immediately followed by
the [ViewVariables(VVAccess.ReadWrite)] attribute above the public float
StackGrow = 0.5f declaration to restore proper formatting.
- Around line 7-11: Add XML documentation for the AllergicComponent class and
its Triggers field: add a /// <summary> on the AllergicComponent type describing
that this component marks entities that react allergically and what behavior it
controls, and add a /// <summary> on the Triggers field explaining that it is a
list of ProtoId<ReagentPrototype> that will trigger the allergy (optionally note
semantics like whether any or all reagents trigger, and expected format). Ensure
the docs match the style of other components in the codebase and reference the
AllergicComponent class and Triggers field names.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 2d6e495d-0cd5-46b1-bbfd-671eca0e8ced

📥 Commits

Reviewing files that changed from the base of the PR and between 2d8fc6e and ef57367.

📒 Files selected for processing (6)
  • Content.Server/ADT/Body/AllergicSystem.Shock.cs
  • Content.Server/ADT/EntityEffects/AdjustAllergicStackEffectSystem.cs
  • Content.Shared/ADT/Body/Allergies/AllergicComponent.cs
  • Content.Shared/ADT/Body/Allergies/Prototypes/AllergicReactionPrototype.cs
  • Content.Shared/ADT/EntityEffects/AdjustAllergicStack.cs
  • Resources/Locale/ru-RU/ADT/guidebook/chemistry/effects.ftl
🚧 Files skipped from review as they are similar to previous changes (1)
  • Content.Shared/ADT/Body/Allergies/Prototypes/AllergicReactionPrototype.cs

@Rorkh
Copy link
Contributor Author

Rorkh commented Mar 14, 2026

Больше не WIP. Как понял, в тестах физика фейлится, я тут ни при чем.

@Rorkh
Copy link
Contributor Author

Rorkh commented Mar 14, 2026

Дополнил описание

Copy link
Collaborator

@Schrodinger71 Schrodinger71 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Чейнжлог ни особо информативен

Просто написано add: Алергия, и что где как что с этого можно понять куда она добавлена?

Copy link
Collaborator

@Schrodinger71 Schrodinger71 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ну в теории всё ок

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Changes: Localization Изменение локализации Changes: UI Изменение интерфейса size/M Status: Needs Review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants