Децентрализация механик Scp939#981
Conversation
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: ASSERTIVE Plan: Pro Run ID: ⛔ Files ignored due to path filters (3)
📒 Files selected for processing (42)
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughКрупный рефакторинг, конвертирующий специфичные для SCP-939 системы видимости, сна и мимикрии в универсальные компоненты и системы. Удалены три основных SCP-939 сервер-клиентских системы; добавлены новые чистые компоненты (ScpOnSoundVisibility, ScpRememberPhrase, ScpHealOnSleep) с соответствующими системами для управления ими. Переработаны прототипы действий и конфигурация SCP-939 для использования новой архитектуры. ChangesМиграция видимости и HUD с SCP-939 на универсальную систему ScpOnSoundVisibility
Извлечение функциональности сна в универсальную систему ScpHealOnSleep
Добавление универсальной функциональности запоминания фраз
Добавление универсальной системы триггеров и масок
Sequence DiagramsequenceDiagram
participant Entity as Целевая сущность
participant Viewer as ScpOnSoundVisibilityViewer
participant System as ScpOnSoundVisibilitySystem
participant HudSys as ScpOnSoundVisibilityHudSystem
participant Overlay as SetAlphaOverlay
Entity->>System: В пределах VisibilityActivationRange
System->>System: UpdateVisibilityTargets()
System->>Entity: EnsureActiveVisibility()
activate Entity
Entity->>Entity: ActiveScpOnSoundVisibilityComponent создан
Entity->>Entity: HideTime, MinValue, MaxValue синхронизированы
deactivate Entity
loop Каждый UPDATE
HudSys->>Entity: Проверить событие OnMove/OnCollide
alt Событие действия (столкновение, движение)
Entity->>HudSys: VisibilityAcc сброшен в InitialVisibilityAcc
else Нет события
HudSys->>HudSys: Incrementally увеличить VisibilityAcc
end
HudSys->>HudSys: GetVisibility(ent) вычислить
HudSys->>Viewer: Проверить PoorEyesight
alt PoorEyesight активен
HudSys->>HudSys: Применить модификатор видимости [MinValue, MaxValue]
end
Overlay->>HudSys: GetVisibility(ent) для целевой альфы
Overlay->>Overlay: SetAlphaOverlay: обновить спрайт-альфу
end
Viewer->>System: AfterFlashedEvent
System->>System: PoorEyesight = true, PoorEyesightTimeStart = now
System->>System: ActiveScpPoorEyesightComponent создан
loop Истечение
System->>System: Проверить elapsed > PoorEyesightTime
alt Истекло
System->>System: PoorEyesight = false, удалить ActiveScpPoorEyesightComponent
end
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Poem
Important Pre-merge checks failedPlease resolve all errors before merging. Addressing warnings is optional. ❌ Failed checks (4 errors, 1 warning)
✅ Passed checks (5 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Warning Review ran into problems🔥 ProblemsGit: Failed to clone repository. Please run the Tip 💬 Introducing Slack Agent: The best way for teams to turn conversations into code.Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
Built for teams:
One agent for your entire SDLC. Right inside Slack. 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 16
🤖 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.Client/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityHudSystem.cs`:
- Line 277: Текст TODO в классе ScpOnSoundVisibilityHudSystem (файл
ScpOnSoundVisibilityHudSystem.cs) нужно вынести в трекер задач и заменить в коде
краткой пометкой с идентификатором issue: создайте issue/bug/feature в вашей
системе (описать: "Переделать визуализацию как статус-эффект и добавить его в
панель статус-эффектов"), получите его номер/ссылку и замените TODO-комментарий
на комментарий вида "TODO: see ISSUE-1234" (или аналог с URL), чтобы задача была
отслеживаема; оставьте в issue детали UX-изменения и ожидаемое поведение для
методов и UI, чтобы потом реализовать изменения в ScpOnSoundVisibilityHudSystem.
In
`@Content.Client/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityHudSystem.Overlay.cs`:
- Around line 23-26: При отключении локального игрока в методе OnPlayerDetached
нужно не только сбрасывать поле _viewerComponent, но и явно удалить все активные
оверлеи: вызовите RemoveOverlays() (или эквивалентный метод очистки) до того,
как присвоите _viewerComponent = null; это гарантирует, что визуальные элементы
удаляются и не остаются активными после детача.
In `@Content.Client/_Scp/Other/ScpSleep/ScpSleepVisualizer.cs`:
- Line 8: Класс в файле ScpSleepVisualizer.cs объявлен как Scp939Visualizer;
переименуйте класс Scp939Visualizer в ScpSleepVisualizer (класс:
Scp939Visualizer, базовый: VisualizerSystem<ScpSleepComponent>) и обновите все
ссылочные использования/именования в проекте, чтобы соответствовать новому имени
ScpSleepVisualizer.
- Around line 20-25: The UpdateSprite method currently declares optional
parameters spriteComponent and mobStateComponent but immediately overwrites them
with TryComp calls; either remove these optional parameters from the
UpdateSprite signature (so only uid and appearanceComponent remain) and keep the
TryComp lookups inside, or change the body to use the Resolve pattern to respect
callers' supplied components (use Resolve(uid, ref spriteComponent, ref
mobStateComponent) or the project's equivalent) before falling back to TryComp;
update references to SpriteComponent, MobStateComponent, TryComp, and the
_spriteSystem.LayerMapTryGet((uid, spriteComponent), ScpSleepLayers.Base, ...)
call accordingly to ensure you pass the resolved variables into LayerMapTryGet.
In
`@Content.Server/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilitySystem.cs`:
- Around line 74-80: OnMobStartup сейчас всегда добавляет
EnsureComp<ScpOnSoundVisibilityComponent> всем мобам (кроме тех с
ScpOnSoundVisibilityViewerComponent), что создаёт лишние компоненты на большом
количестве NPC; исправьте это, добавив предикат перед вызовом EnsureComp:
например, только если у сущности уже есть маркер интереса
(HasComp<ScpOnSoundVisibilityInterestComponent>(ent)), или если сущность
является игроком/активным юнитом (проверка по компоненту/флагу типа
PlayerComponent/ActiveAiComponent), либо перенесите конфигурацию в
Singleton/SharedResource и вообще не добавляйте компонент всем. Обновите функцию
OnMobStartup, заменив бесконтрольный
EnsureComp<ScpOnSoundVisibilityComponent>(ent) на условный вызов с описанными
проверками или уберите добавление и читайте конфиг из единого места.
- Around line 166-167: Remove the redundant call to
_visibilityCandidates.Clear() at the end of the method in
ScpOnSoundVisibilitySystem since _visibilityCandidates is already cleared inside
the processing loop (the earlier Clear). Locate the method in the
ScpOnSoundVisibilitySystem class where both _visibilityCandidates.Clear() and
_visibilityRemovalQueue.Clear() are called and delete only the trailing
_visibilityCandidates.Clear() call, leaving _visibilityRemovalQueue.Clear()
as-is.
In `@Content.Server/_Scp/Other/ScpReleaseGas/ScpReleaseGasSystem.cs`:
- Around line 28-34: В методе OnGasAction при обнаружении маски через
_scpMask.TryGetScpMask вы делаете ранний return после _scpMask.TryCreatePopup,
но не устанавливаете флаг обработки события; исправьте это, перед возвратом
установить args.Handled = true на объекте ScpReleaseGasActionEvent, чтобы
пометить событие как обработанное и предотвратить дальнейшую обработку другими
системами.
- Line 7: Namespace declaration is incorrect for this file; change the namespace
from Content.Server._Scp.Scp939 to match the folder hierarchy (e.g.,
Content.Server._Scp.Other.ScpReleaseGas) so the ScpReleaseGasSystem class and
any related types live in the correct namespace and follow project conventions.
- Around line 23-26: The component event handler OnInit in ScpReleaseGasSystem
is declared public but should be private by SS14 convention; change the method
signature from public void OnInit(Entity<ScpReleaseGasComponent> ent, ref
ComponentInit args) to private void OnInit(Entity<ScpReleaseGasComponent> ent,
ref ComponentInit args) (leave the body unchanged, still calling
_actionsSystem.AddAction(ent, ent.Comp.ActionProto)) so the handler remains
functional but uses the correct access level.
- Around line 19-21: В компоненте ScpReleaseGasComponent вы подписываете
действие в Initialize() через обработчик OnInit (ComponentInit) но не удаляете
его при уничтожении, что ведёт к orphaned actions; добавьте подписку на
ComponentShutdown в Initialize() и реализуйте обработчик (например OnShutdown)
который найдёт и удалит ранее зарегистрированное действие для
ScpReleaseGasComponent (тот же идентификатор/тип, что используете в
OnInit/OnGasAction) — убрать действие из ActionSystem/Owner или вызвать
соответствующий метод удаления, чтобы гарантировать очистку при
ComponentShutdown.
In `@Content.Server/_Scp/Other/ScpRememberPhrase/ScpRememberPhraseSystem.cs`:
- Around line 84-88: The current removal picks a random key via
_random.Pick(rememberEnt.Comp.RememberedMessages.Keys) which iterates keys and
then Remove does another lookup; to optimize, change the component storage to
maintain a parallel List<TKey> (e.g., RememberedMessageKeys) alongside the
Dictionary RememberedMessages and use _random.Next(0,
RememberedMessageKeys.Count) to pick an index then get the key by index and
remove by key from the Dictionary and RemoveAt from the List; ensure all places
that add or remove entries (where RememberedMessages is modified) also update
RememberedMessageKeys so the two stay in sync and use the new index-based
removal in the block currently using _random.Pick.
- Line 70: The GetEntitiesInRange call uses a hardcoded radius (16f); add a
DataField to ScpRememberPhraseComponent: [DataField] public float ListenRange =
16f; then replace the literal 16f in the _entityLookup.GetEntitiesInRange(...)
invocation with the component's ListenRange (i.e., use rememberSet.ListenRange
or the ScpRememberPhraseComponent instance associated with ent) so the radius is
configurable via prototypes.
In `@Content.Server/_Scp/Other/ScpSleep/ScpSleepSystem.cs`:
- Around line 56-69: The method OnSleepChanged currently uses magic numbers 20
and 1 to set bloodstreamComponent.BloodRefreshAmount; add two DataField
properties to ScpSleepComponent (e.g., public float SleepingBloodRefreshAmount =
20f; public float DefaultBloodRefreshAmount = 1f;) and then update
OnSleepChanged to read those fields from the entity's ScpSleepComponent instance
instead of the hardcoded literals (use the component on the same entity to set
bloodstreamComponent.BloodRefreshAmount to SleepingBloodRefreshAmount when
args.FellAsleep is true and to DefaultBloodRefreshAmount otherwise, then call
Dirty as before).
In
`@Content.Shared/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityViewerComponent.cs`:
- Line 17: The inline comment on the public field PoorEyesightTime in
ScpOnSoundVisibilityViewerComponent.cs is in Russian ("// Секунды"); change it
to English by replacing it with "// Seconds" so it matches the project's English
comment standards and clearly documents the unit for PoorEyesightTime.
In `@Content.Shared/_Scp/Other/ScpReleaseGas/ScpReleaseGasComponent.cs`:
- Around line 9-10: Класс ScpReleaseGasComponent помечен атрибутом
[NetworkedComponent], но в нём нет полей с [AutoNetworkedField]; либо удалите
атрибут [NetworkedComponent] из объявления класса ScpReleaseGasComponent, либо
добавьте необходимые сетевые поля, пометив их [AutoNetworkedField] (и настроив
идентификаторы/версии), чтобы отражать реальную потребность в синхронизации.
In `@Content.Shared/_Scp/Other/ScpRememberPhrase/ScpRememberPhraseComponent.cs`:
- Around line 8-22: The ScpRememberPhraseComponent is incorrectly marked with
[NetworkedComponent] even though its state (notably the RememberedMessages
dictionary) is server-only; remove the [NetworkedComponent] attribute from the
ScpRememberPhraseComponent declaration so the component is not
network-synchronized and remains server-side only, leaving other attributes
(e.g., [RegisterComponent]) and fields (ActionProto, MaxRememberedMessages,
RememberedMessages) unchanged.
🪄 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: d3590131-6c0a-42a0-ba4b-e76554c419c3
⛔ Files ignored due to path filters (3)
Resources/Textures/_Scp/Actions/scp-actions.rsi/mimic.pngis excluded by!**/*.pngResources/Textures/_Scp/Actions/scp-actions.rsi/sleep.pngis excluded by!**/*.pngResources/Textures/_Scp/Actions/scp-actions.rsi/smaug.pngis excluded by!**/*.png
📒 Files selected for processing (35)
Content.Client/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityHudSystem.Overlay.csContent.Client/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityHudSystem.csContent.Client/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityResetAlphaOverlay.csContent.Client/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilitySetAlphaOverlay.csContent.Client/_Scp/Other/ScpSleep/ScpSleepVisualizer.csContent.Client/_Scp/Scp939/Scp939HudSystem.Visibility.csContent.Client/_Scp/Scp939/Scp939HudSystem.csContent.Client/_Scp/Scp939/Scp939Visualizer.csContent.Server/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilitySystem.csContent.Server/_Scp/Other/ScpReleaseGas/ScpReleaseGasSystem.csContent.Server/_Scp/Other/ScpRememberPhrase/ScpRememberPhraseSystem.csContent.Server/_Scp/Other/ScpSleep/ScpSleepSystem.csContent.Server/_Scp/Research/Artifacts/Effects/_ScpSpecific/Scp939/Sleep/ArtifactScp939SleepSystem.csContent.Server/_Scp/Scp939/Scp939System.Actions.csContent.Server/_Scp/Scp939/Scp939System.Visibility.csContent.Server/_Scp/Scp939/Scp939System.csContent.Shared/_Scp/Other/ScpOnSoundVisibility/ActiveScpOnSoundVisibilityComponent.csContent.Shared/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityComponent.csContent.Shared/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityProtectionComponent.csContent.Shared/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityViewerComponent.csContent.Shared/_Scp/Other/ScpReleaseGas/ScpReleaseGasActionEvent.csContent.Shared/_Scp/Other/ScpReleaseGas/ScpReleaseGasComponent.csContent.Shared/_Scp/Other/ScpRememberPhrase/ScpRememberPhraseActionEvent.csContent.Shared/_Scp/Other/ScpRememberPhrase/ScpRememberPhraseComponent.csContent.Shared/_Scp/Other/ScpSleep/ScpSleepActionEvent.csContent.Shared/_Scp/Other/ScpSleep/ScpSleepComponent.csContent.Shared/_Scp/Other/ScpSleep/SharedScpSleepData.csContent.Shared/_Scp/Scp939/ActiveScp939VisibilityComponent.csContent.Shared/_Scp/Scp939/Protection/Scp939ProtectionComponent.csContent.Shared/_Scp/Scp939/Scp939Component.csContent.Shared/_Scp/Scp939/SharedScp939Data.csResources/Prototypes/_Scp/Actions/scp939.ymlResources/Prototypes/_Scp/Actions/scp_actions.ymlResources/Prototypes/_Scp/Entities/Mobs/Player/Scp/Main/scp939.ymlResources/Textures/_Scp/Actions/scp-actions.rsi/meta.json
💤 Files with no reviewable changes (8)
- Content.Shared/_Scp/Scp939/ActiveScp939VisibilityComponent.cs
- Content.Client/_Scp/Scp939/Scp939Visualizer.cs
- Content.Shared/_Scp/Scp939/SharedScp939Data.cs
- Content.Server/_Scp/Scp939/Scp939System.Actions.cs
- Content.Client/_Scp/Scp939/Scp939HudSystem.cs
- Content.Server/_Scp/Scp939/Scp939System.cs
- Content.Client/_Scp/Scp939/Scp939HudSystem.Visibility.cs
- Content.Server/_Scp/Scp939/Scp939System.Visibility.cs
|
Пока не доделал пусть будет в драфте |
|
Также выдели 173 в отдельный ПР для удобства ревью. Начни только с 939, потому что я уверен тут будет много замечаний и будет тяжело ориентироваться |
|
В принципе готово для ревью |
|
Нужно будет не забыть изменить ключи локализации, где они содержат в себе "939" |
|
@ThereDrD0 готово к ревью |
|
Ммм, забей, я не тот компонент указал для акшиона, мдэ |
|
@ThereDrD0 |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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/_Scp/Other/ScpHealOnSleep/ScpHealOnSleepSystem.cs`:
- Around line 92-96: Сделайте операцию атомарной: либо сначала попытайтесь
добавить эффект сна, а только потом вызвать _sleeping.TrySleeping(owner) (т.е.
поменяйте порядок вызовов и вызвать TryAddStatusEffectDuration(ent,
ent.Comp.StatusEffect, hibernationDuration) перед
_sleeping.TrySleeping(ent.Owner)), либо если порядок нужен таким как сейчас —
реализуйте откат: если _statusEffects.TryAddStatusEffectDuration(...) вернул
false, отменяйте состояние сна вызовом соответствующего метода
отмены/пробуждения у _sleeping (например _sleeping.TryWake(ent.Owner) или
эквивалент), чтобы не оставить полукачественное состояние; обновите логирование
и тесты для покрытия обоих путей.
In
`@Content.Server/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilitySystem.cs`:
- Around line 91-127: Сейчас _visibilityActiveTargets собирает объединение целей
всех ScpOnSoundVisibilityViewerComponent и вешает глобальный
ActiveScpOnSoundVisibilityComponent, из‑за чего видимость делится между
зрителями; нужно менять это на per‑viewer логику: вместо добавления всех целей в
общий _visibilityActiveTargets и массового EnsureActiveVisibility,
фильтровать/вешать компонент в контексте конкретного viewer — то есть внутри
цикла по scpQuery для каждого viewer пройти по _visibilityCandidates и вызывать
EnsureActiveVisibility только для тех target, которые проходят локальную
проверку (или хранить временную коллекцию targetsForViewer и потом привязывать
ActiveScpOnSoundVisibilityComponent с учётом viewer id), не используя глобальное
объединение; используйте имена ScpOnSoundVisibilityViewerComponent,
_visibilityCandidates, _visibilityActiveTargets, EnsureActiveVisibility и
ActiveScpOnSoundVisibilityComponent чтобы найти и заменить текущую глобальную
логику на per‑viewer фильтрацию/привязку.
In `@Content.Server/_Scp/Other/ScpRememberPhrase/ScpRememberPhraseSystem.cs`:
- Around line 57-68: Сохраните текущий голос перед подменой и восстановите его
после отправки сообщения: в блоке где вызывается TryComp<TTSComponent> возьмите
оригинальный voice (например originalVoice = ttsComponent.VoicePrototypeId),
присвойте messagePair.TtsVoice, вызовите _chat.TrySendInGameICMessage(...),
затем верните ttsComponent.VoicePrototypeId = originalVoice и пометьте компонент
как изменённый через Dirty(ent, ttsComponent) — это гарантирует, что временная
подмена голоса на TTSComponent не останется после отправки.
In `@Content.Shared/_Scp/Other/ScpHealOnSleep/ScpHealOnSleepComponent.cs`:
- Around line 10-11: The ScpHealOnSleepComponent is marked with
[NetworkedComponent] but has no [AutoNetworkedField] nor
[AutoGenerateComponentState], indicating it’s a server-only component; remove
the [NetworkedComponent] attribute from the ScpHealOnSleepComponent declaration
(leave [RegisterComponent] and the class ScpHealOnSleepComponent as-is) so it is
not treated as networked, or alternatively if it actually needs networking add
[AutoGenerateComponentState] and mark mutable fields with [AutoNetworkedField];
prefer removing [NetworkedComponent] here if clients never read or update its
fields.
🪄 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: a17e8596-1c38-4f68-8c6b-69da6eee5e18
📒 Files selected for processing (16)
Content.Client/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityHudSystem.csContent.Server/_Scp/Other/ScpHealOnSleep/ScpHealOnSleepSystem.csContent.Server/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilitySystem.csContent.Server/_Scp/Other/ScpReleaseGas/ScpReleaseGasSystem.csContent.Server/_Scp/Other/ScpRememberPhrase/ScpRememberPhraseSystem.csContent.Server/_Scp/Research/Artifacts/Effects/_ScpSpecific/Scp939/Sleep/ArtifactScp939SleepSystem.csContent.Shared/_Scp/Other/Events/ScpSystemsEvents.csContent.Shared/_Scp/Other/ScpHealOnSleep/ScpHealOnSleepComponent.csContent.Shared/_Scp/Other/ScpHealOnSleep/SharedScpHealOnSleepData.csContent.Shared/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityComponent.csContent.Shared/_Scp/Other/ScpOnSoundVisibility/ScpOnSoundVisibilityViewerComponent.csContent.Shared/_Scp/Other/ScpReleaseGas/ScpReleaseGasComponent.csContent.Shared/_Scp/Other/ScpRememberPhrase/ScpRememberPhraseComponent.csResources/Prototypes/Entities/Mobs/base.ymlResources/Prototypes/_Scp/Actions/scp_actions.ymlResources/Prototypes/_Scp/Entities/Mobs/Player/Scp/Main/scp939.yml
Ты должен его сделать |
There was a problem hiding this comment.
Actionable comments posted: 4
🤖 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/_Scp/Other/ScpReleaseGas/ScpReleaseGasSystem.cs`:
- Around line 18-36: The handler OnAttemptTriggerEvent is subscribed to
ScpReleaseGasComponent (bearer) but AttemptTriggerEvent is raised on the action
entity (see ScpTriggerOnActionSystem.OnAction()), so the subscription will never
fire and the handler body is empty; change the subscription to listen on the
action entity created in OnMapInit (ent.Comp.ActionEnt) — e.g. subscribe to
AttemptTriggerEvent for the action entity when you call _actionsSystem.AddAction
and remove that subscription on OnShutdown (or forward the AttemptTriggerEvent
from the action entity to the bearer in ScpTriggerOnActionSystem.OnAction());
then implement the gas release logic inside OnAttemptTriggerEvent using the
bearer component (ScpReleaseGasComponent) fields. Ensure you reference and
update ActionEnt when subscribing/unsubscribing so the correct entity receives
AttemptTriggerEvent.
In `@Content.Shared/_Scp/Trigger/ScpTriggerOnAction/ScpTriggerOnActionSystem.cs`:
- Around line 34-46: В методе OnTriggerAttempt используйте активатора из
события: замените вызовы _scpMask.TryGetScpMask(ent, out var scpMask) и
_scpMask.TryCreatePopup(ent, scpMask) на проверку и popup с использованием
args.User (AttemptTriggerEvent.User) вместо ent, и пометьте args.Cancelled =
true когда маска сработала; в методе OnAction замените второй аргумент
_trigger.Trigger(ent, ent, ent.Comp.KeyOut) на активатора (тот же объект, что и
в AttemptTriggerEvent) — если ScpActionTriggerAttemptEvent не содержит поля
пользователя, расширьте событие (или добавьте поле/механизм передачи) чтобы
передавать инициатора и используйте его в _trigger.Trigger; обновите
соответствующие места, где создаётся и шлётся ScpActionTriggerAttemptEvent,
чтобы включать пользователя.
In `@Content.Shared/Actions/SharedActionsSystem.cs`:
- Around line 302-308: Переместите вызов хука ScpActionTriggerAttemptEvent так,
чтобы он выполнялся после стандартной валидации (проверок Enabled, cooldown,
вызовов ActionAttempt и ActionValidate) и вызывался на сущности действия, а не
на user: удалите текущую отправку RaiseLocalEvent(user, ref checkEv) до
валидации и добавьте RaiseLocalEvent(actionEntity, ref checkEv) после блоков,
содержащих Enabled, cooldown, ActionAttempt и ActionValidate; убедитесь, что
обработчики ScpTriggerOnActionComponent подписываются на событие на
action-сущности и что метод по-прежнему проверяет checkEv.Cancelled и корректно
прерывает выполнение при отмене.
In `@Resources/Prototypes/_Scp/Entities/Mobs/Player/Scp/Main/scp939.yml`:
- Around line 71-74: В файле указан реагент с кириллическим ID "АМН-С227", но в
других местах используются латинские варианты "AMH-C227" и "amhc227"; замените
все вхождения латинских форм на единый кириллический идентификатор "АМН-С227" по
всему репозиторию (включая записи в ignore_list и ключи/значения локализации),
убедитесь, что поля ReagentId и smokePrototype (и любые локализованные ключи)
теперь используют ровно "АМН-С227", и сделайте поисковую замену по всему
коду/локалям с проверкой кодировки/энкодинга файлов, чтобы не ввести смешанные
символы.
🪄 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: 950ba50a-1ded-4ebb-a560-af8069be3087
📒 Files selected for processing (9)
Content.Server/_Scp/Other/ScpHealOnSleep/ScpHealOnSleepComponent.csContent.Server/_Scp/Other/ScpReleaseGas/ScpReleaseGasSystem.csContent.Shared/Actions/SharedActionsSystem.csContent.Shared/_Scp/Other/Events/ScpTriggerEvents.csContent.Shared/_Scp/Other/ScpReleaseGas/ScpReleaseGasComponent.csContent.Shared/_Scp/Trigger/ScpTriggerOnAction/ScpTriggerOnActionComponent.csContent.Shared/_Scp/Trigger/ScpTriggerOnAction/ScpTriggerOnActionSystem.csResources/Prototypes/_Scp/Actions/scp_actions.ymlResources/Prototypes/_Scp/Entities/Mobs/Player/Scp/Main/scp939.yml
There was a problem hiding this comment.
Actionable comments posted: 5
♻️ Duplicate comments (1)
Content.Shared/_Scp/Trigger/ScpTriggerOnAction/ScpTriggerOnActionSystem.cs (1)
16-18:⚠️ Potential issue | 🟠 Major | ⚡ Quick winПередавайте в триггер реального исполнителя action-события.
_trigger.Trigger(ent, ent, args.KeyOut)всегда подставляет самого носителя компонента какuserи затирает контекст активатора. Любая триггер-логика, завязанная на инициатора, здесь получит неверную сущность.#!/bin/bash # Проверить, какое поле InstantActionEvent несет исполнителя, # и подтвердить сигнатуру TriggerSystem.Trigger. rg -n -C3 'class InstantActionEvent|record InstantActionEvent|struct InstantActionEvent|\b(Performer|User)\b' --type cs Content.Shared Robust.Shared rg -n -C3 'public .* Trigger\s*\(' --type cs Content.Shared/Trigger/Systems/TriggerSystem.csОжидаемый результат: найти поле исполнителя в
InstantActionEventи передавать именно его вторым аргументом в_trigger.Trigger(...).🤖 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/Trigger/ScpTriggerOnAction/ScpTriggerOnActionSystem.cs` around lines 16 - 18, OnAction in ScpTriggerOnActionSystem currently calls _trigger.Trigger(ent, ent, args.KeyOut) which incorrectly uses the component holder as the action performer; change the second argument to the real performer from the action event (inspect ScpTriggerOnActionEvent / underlying InstantActionEvent for the performer field named e.g. Performer or User) and pass that entity as the user to _trigger.Trigger(...) instead of ent so trigger logic receives the true initiator.
🤖 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/Other/Events/ScpTriggerEvents.cs`:
- Around line 7-8: Поле KeyOut должно быть обязательным и не-null: в объявлении
поля `KeyOut` в классе (в файле ScpTriggerEvents.cs) уберите
nullable-модификатор и пометьте DataField как обязательное (например через
параметр required либо аналогичный атрибут в вашем кодогенераторе), либо
инициализируйте поле безопасным значением (например пустой строкой или
`default!`) чтобы подавить предупреждение; это гарантирует раннюю ошибку при
отсутствующем или опечатанном YAML-поле и совместимо с обработчиком, который
передаёт `KeyOut` в `TriggerSystem`.
In `@Content.Shared/_Scp/ScpMask/ScpMaskChekerComponent.cs`:
- Around line 1-10: The file name has a typo: rename the file from
ScpMaskChekerComponent.cs to ScpMaskCheckerComponent.cs so it matches the public
class ScpMaskCheckerComponent; after renaming, update any references/imports or
project file entries if present (e.g., in solution/project or build scripts) to
the new file name to keep IDE navigation and SS14 naming conventions consistent.
- Around line 5-9: Класс ScpMaskCheckerComponent помечен как
[NetworkedComponent], но поле BlockTriggers не помечено для авто-сериализации;
добавьте атрибут [AutoGenerateComponentState] на класс ScpMaskCheckerComponent и
атрибут [AutoNetworkedField] на поле BlockTriggers (указывая при необходимости
порядковый id), чтобы состояние BlockTriggers сериализовалось и отправлялось
клиентам для корректного предсказания AttemptTriggerEvent.
In `@Content.Shared/_Scp/ScpMask/ScpMaskSystem.Checker.cs`:
- Around line 12-23: В методе OnAttemptTrigger найден лишний завершающий
оператор return в конце блока if; удалите последний "return;" (внутри ветки, где
успешно найден маск — после вызова TryCreatePopup(ent, scpMask) и установки
args.Cancelled = true) поскольку метод и так завершается, оставив только вызов
TryCreatePopup и присвоение args.Cancelled = true; убедитесь, что логика с
проверкой ent.Comp.BlockTriggers, вызовом TryGetScpMask и установкой
args.Cancelled остаётся без изменений.
In `@Resources/Prototypes/_Scp/Actions/scp_actions.yml`:
- Around line 1-38: The three new entity prototypes RememberPhraseAction,
ScpSmokeAction, and ScpSleepAction were added as concrete, player-facing
prototypes but lack matching localization keys; either add corresponding
ent-<PrototypeId> localization entries for each ID in the touched locale files
(e.g., ent-RememberPhraseAction, ent-ScpSmokeAction, ent-ScpSleepAction with
name/description strings) or change each prototype to be non-concrete by adding
abstract: true to RememberPhraseAction, ScpSmokeAction, and ScpSleepAction so
they are only base prototypes.
---
Duplicate comments:
In `@Content.Shared/_Scp/Trigger/ScpTriggerOnAction/ScpTriggerOnActionSystem.cs`:
- Around line 16-18: OnAction in ScpTriggerOnActionSystem currently calls
_trigger.Trigger(ent, ent, args.KeyOut) which incorrectly uses the component
holder as the action performer; change the second argument to the real performer
from the action event (inspect ScpTriggerOnActionEvent / underlying
InstantActionEvent for the performer field named e.g. Performer or User) and
pass that entity as the user to _trigger.Trigger(...) instead of ent so trigger
logic receives the true initiator.
🪄 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: 586944ba-8a0b-439e-93d2-e83515d99768
📒 Files selected for processing (9)
Content.Shared/_Scp/Other/Events/ScpTriggerEvents.csContent.Shared/_Scp/ScpMask/ScpMaskChekerComponent.csContent.Shared/_Scp/ScpMask/ScpMaskSystem.Checker.csContent.Shared/_Scp/ScpMask/ScpMaskSystem.csContent.Shared/_Scp/Trigger/ScpTriggerOnAction/ScpTriggerOnActionListenerComponent.csContent.Shared/_Scp/Trigger/ScpTriggerOnAction/ScpTriggerOnActionSystem.csResources/Prototypes/_Scp/Actions/scp939.ymlResources/Prototypes/_Scp/Actions/scp_actions.ymlResources/Prototypes/_Scp/Entities/Mobs/Player/Scp/Main/scp939.yml
|
Этот PR содержит конфликты, пожалуйста, разрешите их, прежде чем мы сможем его оценить. |
|
@coderabbitai сделай ревью |
🧩 Analysis chain🏁 Script executed: Length of output: 24026
Общий итогРефакторинг выполнен качественно: старые системы ( 🔴 Критично1. Несоответствие ключа локализации
|
"желательно обсудить с @ThereDrD0 на предмет нагрузки." |
|
Tip For best results, initiate chat on the files or code changes.
Критичные пункты (ключ локализации |
|
Tip For best results, initiate chat on the files or code changes.
(=^ ◡ ^=) ✏️ Learnings added
|
|
как писать кролику |
упоминаешь его и пишешь |
Краткое описание | Short description
Разбитие механик Scp939 на раздельные системы.
TODO
Summary by CodeRabbit
Обновления функциональности
Новые возможности
Переработка