Skip to content

Изменение принципа работы моргания | Добавления привыкания к каплям Статиса#1058

Open
WardexOfficial wants to merge 2 commits into
space-sunrise:masterfrom
WardexOfficial:tweak/eyedroplets
Open

Изменение принципа работы моргания | Добавления привыкания к каплям Статиса#1058
WardexOfficial wants to merge 2 commits into
space-sunrise:masterfrom
WardexOfficial:tweak/eyedroplets

Conversation

@WardexOfficial

@WardexOfficial WardexOfficial commented Jun 14, 2026

Copy link
Copy Markdown
Collaborator

Краткое описание | Short description

Теперь к времени следующего моргания прибавляется значение BlinkingIntervalBonus для увеличения данного фактора.
Логика ReducedBlinkingSystem.cs теперь работает через BlinkingIntervalBonus, вместо изменения времени следующего моргания напрямую.

🆑 Wardex

  • add: Добавлено привыкание к капелям Статиса, которое влияет на получаемый от них эффект

Summary by CodeRabbit

  • Новые возможности
    • Добавлена механика переносимости эффектов на зрение с затуханием и вероятностным бонусом к интервалу мигания.
    • При достижении/превышении порога бонус на переносимость не применяется.
  • Исправления
    • Уточнена логика отката бонуса интервала мигания при выключении эффекта.
    • Исправлены расчёты времени следующего мигания с гарантией корректных (неотрицательных) значений.
  • Локализация
    • Добавлено новое предупреждение о привыкании глаз к эффектам.

@coderabbitai

coderabbitai Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

В систему моргания добавлена механика допуска (tolerance) для глазных капель. BlinkableComponent и ActiveReducedBlinkingUserComponent получают новые сетевые поля. При применении капель проверяется накопленный допуск: при превышении порога эффект блокируется с локализованным предупреждением, иначе бонус интервала масштабируется по коэффициенту эффективности. Допуск пассивно снижается со временем; при завершении эффекта бонус откатывается на сервере.

Changes

Система допуска к глазным каплям

Layer / File(s) Summary
Обновление контрактов данных компонентов
Content.Shared/_Scp/Blinking/BlinkableComponent.cs, Content.Shared/_Scp/Blinking/ReducedBlinking/ActiveReducedBlinkingUserComponent.cs
BlinkableComponent получает сетевые поля ReducedBlinkingTolerance (float, по умолчанию 0f) и BlinkingIntervalBonus (TimeSpan). В ActiveReducedBlinkingUserComponent поле BlinkingBonusDuration переименовано в BlinkingIntervalBonus с сохранением атрибутов DataField(required:true) и AutoNetworkedField.
Инициализация запросов и констант в SharedBlinkingSystem
Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs
Добавлены импорт namespace ReducedBlinking, константа ReducedBlinkingToleranceDecayPerSecond (0.05f), защищенное поле ActiveReducedBlinkingQuery для проверки наличия активного компонента эффекта и инициализация Query в методе Initialize.
Логика применения капель с проверкой допуска и масштабированием
Content.Shared/_Scp/Blinking/ReducedBlinking/ReducedBlinkingSystem.cs, Resources/Locale/ru-RU/_strings/_scp/blinking/blinking.ftl
Добавлен импорт и внедрение RandomPredictedSystem. Определены константы порога ToleranceReduceUseLimit и коэффициента MinReducedBlinkingEffectiveness. При EyeDropletsUsedDoAfterEvent проверяется допуск: при превышении порога выводится локализованное сообщение eye-droplets-tolerance-too-high, иначе вычисляется effectiveness, масштабируются тайминги, создаётся ActiveReducedBlinkingUserComponent, обновляются поля компонента и вызываются сброс состояния. Добавлен хелпер GetReducedBlinkingEffectiveness для нормализации коэффициента.
Пассивный распад допуска и исправление расчета задержки морганий
Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs
В Update добавлена логика затухания ReducedBlinkingTolerance на ReducedBlinkingToleranceDecayPerSecond * frameTime при отсутствии ActiveReducedBlinkingUserComponent, с отсечкой до 0 и вызовом DirtyField. В SetNextBlink введена переменная nextBlinkDelay, объединяющая interval, variance, BlinkingIntervalBonus и AdditionalBlinkingTime, с явным зажимом до TimeSpan.Zero.
Откат бонуса интервала на сервере
Content.Server/_Scp/Blinking/ReducedBlinking/ReducedBlinkingSystem.cs
Внедряется SharedBlinkingSystem. В OnUserShutdown BlinkingIntervalBonus уменьшается на значение из компонента с зажимом до TimeSpan.Zero, вызываются DirtyField и ResetBlink(predicted: false) для синхронизации состояния.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

🛠️ Есть C# 🛠️, 📚 Изменения: Локализация 📚

Poem

🐇 Глаза устали — капли кончились...
Допуск растёт, эффект уменьшился.
Но время идёт — допуск тает,
И кролик снова моргать начинает!
✨ Баланс найден, код сверкает ✨


Important

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

❌ Failed checks (1 error, 1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Ss14 Prototype ↔ Ftl Parity ❌ Error PR добавил новую строку локализации eye-droplets-tolerance-too-high в ru-RU, но не создал соответствующий файл en-US/_strings/_scp/blinking/blinking.ftl. Создать Resources/Locale/en-US/_strings/_scp/blinking/blinking.ftl с англоязычными версиями всех строк, включая eye-droplets-tolerance-too-high и другие eye-droplets-* ключи.
Docstring Coverage ⚠️ Warning Docstring coverage is 16.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Ss14 Prediction Safety ❓ Inconclusive No result was produced after verification. Marking as INCONCLUSIVE. Re-run the check or adjust instructions to produce a final result.
✅ Passed checks (7 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed Заголовок точно соответствует основным изменениям PR: рефакторинг системы моргания и добавление механики привыкания к каплям Статиса.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Ss14 Bridge Sync ✅ Passed Все 3 измененных файла в .agent/rules/ и 42 файла в .agent/skills/ имеют синхронизированные bridge файлы во всех требуемых директориях (.agents/, .claude/, .cursor/, .github/), и все ссылки на исто...
Ss14 C# Rules ✅ Passed Все изменённые файлы C# соответствуют правилам SS14: Component классы оканчиваются на "Component", EntitySystem классы оканчиваются на "System", приватные [Dependency] поля начинаются с "_", Event...
Ss14 Yaml/Ftl Rules ✅ Passed FTL файл соответствует всем требованиям SS14: новый ключ eye-droplets-tolerance-too-high использует kebab-case, не является сущностным ключом и содержит корректную русскую локализацию.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@666XxttimurkaxX666

Copy link
Copy Markdown
Contributor

это баф или дебаф 173?

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
Content.Shared/_Scp/Blinking/ReducedBlinking/ReducedBlinkingSystem.cs (1)

62-122: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Разбейте обработчик применения по цепочке OnEvent -> TryDo -> CanDo -> Do.

Сейчас в одном обработчике смешаны валидация, принятие решения и применение эффекта. Вынесите проверки (CanDo) и саму модификацию состояния (Do) в отдельные методы — так проще сопровождать и безопаснее расширять механику допуска.

Вариант минимального рефактора
- private void OnSuccess(Entity<ReducedBlinkingComponent> ent, ref EyeDropletsUsedDoAfterEvent args)
- {
-     // проверки + применение + сайд-эффекты
- }
+ private void OnSuccess(Entity<ReducedBlinkingComponent> ent, ref EyeDropletsUsedDoAfterEvent args)
+ {
+     TryApplyReducedBlinking(ent, ref args);
+ }
+
+ private bool TryApplyReducedBlinking(Entity<ReducedBlinkingComponent> ent, ref EyeDropletsUsedDoAfterEvent args)
+ {
+     if (!CanApplyReducedBlinking(ent, ref args, out var target, out var blinkable))
+         return false;
+
+     DoApplyReducedBlinking(ent, target, ref blinkable);
+     return true;
+ }

As per coding guidelines, enforce the interaction rule from .agent/rules/ss14-interaction-flow.md: OnEvent -> TryDo -> CanDo -> Do.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Content.Shared/_Scp/Blinking/ReducedBlinking/ReducedBlinkingSystem.cs` around
lines 62 - 122, Refactor the OnSuccess method in ReducedBlinkingSystem to follow
the OnEvent -> TryDo -> CanDo -> Do interaction flow pattern. Extract all the
validation checks (the conditions that return early with PopupPredicted calls)
into a new CanDo method that takes the necessary parameters and returns a
boolean indicating whether the operation can proceed. Extract all the state
modification logic (creating ActiveReducedBlinkingUserComponent, updating
blinkable properties, calling Dirty, ResetBlink, TryResetDelay, PlayPredicted,
and UsageCount decrement/QueueDel) into a new Do method. Create a TryDo method
that calls CanDo first and only calls Do if validation passes. Update OnSuccess
to simply call TryDo with the appropriate parameters, maintaining the event
handler's responsibility to route the event to the processing logic.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs`:
- Around line 28-31: The member declaration order in SharedBlinkingSystem.cs
does not follow the established convention. Move the constant
`ReducedBlinkingToleranceDecayPerSecond` to appear before the EntityQuery fields
`BlinkableQuery` and `ActiveReducedBlinkingQuery`. The correct member order for
System.cs files should be: dependencies, constants/static readonly, then runtime
cache/state. Ensure `ReducedBlinkingToleranceDecayPerSecond` is declared before
the EntityQuery runtime cache members.

In `@Resources/Locale/ru-RU/_strings/_scp/blinking/blinking.ftl`:
- Line 4: The localization key `eye-droplets-tolerance-too-high` is present only
in the Russian locale file but is missing from the English locale file. Without
this key in the English locale, the raw key identifier will be displayed instead
of translated text when the Russian localization is unavailable. Add the same
key `eye-droplets-tolerance-too-high` with an appropriate English translation to
the `Resources/Locale/en-US/_strings/_scp/blinking/blinking.ftl` file to provide
a fallback translation.

---

Outside diff comments:
In `@Content.Shared/_Scp/Blinking/ReducedBlinking/ReducedBlinkingSystem.cs`:
- Around line 62-122: Refactor the OnSuccess method in ReducedBlinkingSystem to
follow the OnEvent -> TryDo -> CanDo -> Do interaction flow pattern. Extract all
the validation checks (the conditions that return early with PopupPredicted
calls) into a new CanDo method that takes the necessary parameters and returns a
boolean indicating whether the operation can proceed. Extract all the state
modification logic (creating ActiveReducedBlinkingUserComponent, updating
blinkable properties, calling Dirty, ResetBlink, TryResetDelay, PlayPredicted,
and UsageCount decrement/QueueDel) into a new Do method. Create a TryDo method
that calls CanDo first and only calls Do if validation passes. Update OnSuccess
to simply call TryDo with the appropriate parameters, maintaining the event
handler's responsibility to route the event to the processing logic.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 6110f7a9-e6d1-48aa-a7f5-16dfb7802cf8

📥 Commits

Reviewing files that changed from the base of the PR and between 0ce6a7f and d3c387c.

📒 Files selected for processing (6)
  • Content.Server/_Scp/Blinking/ReducedBlinking/ReducedBlinkingSystem.cs
  • Content.Shared/_Scp/Blinking/BlinkableComponent.cs
  • Content.Shared/_Scp/Blinking/ReducedBlinking/ActiveReducedBlinkingUserComponent.cs
  • Content.Shared/_Scp/Blinking/ReducedBlinking/ReducedBlinkingSystem.cs
  • Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs
  • Resources/Locale/ru-RU/_strings/_scp/blinking/blinking.ftl

Comment thread Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs Outdated
Comment thread Resources/Locale/ru-RU/_strings/_scp/blinking/blinking.ftl
@WardexOfficial

Copy link
Copy Markdown
Collaborator Author

это баф или дебаф 173?

Это дебаф капель

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs (1)

119-130: ⚠️ Potential issue | 🟠 Major

Использование frameTime для изменения сетевого поля в предсказываемом коде создает рассинхронизацию.

Логика пассивного распада ReducedBlinkingTolerance (строки 123–126) выполняется в предсказываемом контексте (гейт IsFirstTimePredicted на строке 113 позволяет запускаться и на клиенте, и на сервере). Поскольку frameTime различается между клиентом и сервером из-за разных частот кадров, значение ReducedBlinkingTolerance будет расходиться между сторонами. Например, при 60 fps клиента и 30 fps сервера клиент и сервер будут уменьшать значение с разной скоростью, накапливая ошибку рассинхронизации.

Это противоречит логике обработчиков событий OnClosedEyes (строка 79) и OnOpenedEyes (строка 91), которые явно проверяют if (_net.IsServer) перед вызовом DirtyField. В Update логика должна следовать тому же паттерну.

Рекомендация: добавьте проверку if (_net.IsServer) перед блоком распада (строки 119–130), чтобы только сервер выполнял расчеты и отправлял обновленное значение клиентам.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs` around lines 119 - 130,
The passive decay logic for ReducedBlinkingTolerance in the SharedBlinkingSystem
is executing in a predictive context but using frameTime, which differs between
client and server due to different frame rates, causing desynchronization. To
fix this, add an `if (_net.IsServer)` check before the decay block that contains
the MathF.Max calculation and DirtyField call for ReducedBlinkingTolerance. This
ensures only the server performs the decay calculation and propagates the value
to clients, matching the same pattern used in the OnClosedEyes and OnOpenedEyes
event handlers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs`:
- Line 28: There is a TODO comment on line 16 about moving hardcoded values to
components, but the new constant ReducedBlinkingToleranceDecayPerSecond is being
added as a hardcoded value instead. To align with the stated goal and improve
flexibility, remove the hardcoded constant definition and add this value as a
[DataField] property in the BlinkableComponent class instead. This way the
blinking tolerance decay rate can be configured per component rather than being
a fixed system-wide constant.

---

Outside diff comments:
In `@Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs`:
- Around line 119-130: The passive decay logic for ReducedBlinkingTolerance in
the SharedBlinkingSystem is executing in a predictive context but using
frameTime, which differs between client and server due to different frame rates,
causing desynchronization. To fix this, add an `if (_net.IsServer)` check before
the decay block that contains the MathF.Max calculation and DirtyField call for
ReducedBlinkingTolerance. This ensures only the server performs the decay
calculation and propagates the value to clients, matching the same pattern used
in the OnClosedEyes and OnOpenedEyes event handlers.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2bf67ec7-6dc3-4b08-aacf-723a052dc9d1

📥 Commits

Reviewing files that changed from the base of the PR and between d3c387c and 182269d.

📒 Files selected for processing (1)
  • Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs

[Dependency] private readonly IGameTiming _timing = default!;
[Dependency] private readonly INetManager _net = default!;

private const float ReducedBlinkingToleranceDecayPerSecond = 0.05f;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick | 🔵 Trivial | 💤 Low value

Hardcoded константа при наличии TODO о переносе значений в компоненты.

На строке 16 есть TODO-комментарий "Анхардкод: Перенос значений в компоненты". Новая константа ReducedBlinkingToleranceDecayPerSecond добавлена как hardcoded значение в системе. Для будущей гибкости рассмотрите возможность переноса этого значения в BlinkableComponent как [DataField].

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@Content.Shared/_Scp/Blinking/SharedBlinkingSystem.cs` at line 28, There is a
TODO comment on line 16 about moving hardcoded values to components, but the new
constant ReducedBlinkingToleranceDecayPerSecond is being added as a hardcoded
value instead. To align with the stated goal and improve flexibility, remove the
hardcoded constant definition and add this value as a [DataField] property in
the BlinkableComponent class instead. This way the blinking tolerance decay rate
can be configured per component rather than being a fixed system-wide constant.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants