Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Fix] фиксы синхронизации системы лежания #936

Merged
merged 2 commits into from
Nov 23, 2024

Conversation

Rxup
Copy link
Owner

@Rxup Rxup commented Nov 23, 2024

🆑

  • fix: Улучшена визуализация переходов между состояниями стояния и лежания для сущностей.

Summary by CodeRabbit

Обновленные заметки о выпуске

  • Новые функции

    • Улучшена визуализация переходов между состояниями стояния и лежания для сущностей.
    • Добавлена поддержка управления состоянием с учетом времени и предсказания событий.
  • Исправления ошибок

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

    • Обновлены комментарии и форматирование в коде для улучшения читаемости.

Copy link
Contributor

coderabbitai bot commented Nov 23, 2024

Процесс

Внесены изменения в классы LayingDownSystem, SharedLayingDownSystem и StandingStateComponent, чтобы улучшить обработку состояний стояния и лежания. В LayingDownSystem добавлена подписка на событие OnChangeStanding, а метод OnChangeStanding теперь управляет вращением спрайта в зависимости от состояния. В SharedLayingDownSystem добавлена зависимость от IGameTiming, что изменяет управление событиями. В StandingStateComponent обновлены атрибуты для улучшения генерации состояния и доступа к свойству CurrentState.

Изменения

Файл Изменения
Content.Client/Backmen/Standing/LayingDownSystem.cs Добавлен метод OnChangeStanding для управления вращением спрайта. Обновлен метод OnChangeDraw для уточнения условий сброса глубины рисования.
Content.Shared/Backmen/Standing/SharedLayingDownSystem.cs Добавлена зависимость IGameTiming. Обновлен метод ToggleStanding для упрощения обработки событий. Обновлён метод TryStandUp для управления состоянием.
Content.Shared/Standing/StandingStateComponent.cs Изменён атрибут AutoGenerateComponentState на true. Добавлен атрибут ViewVariables(VVAccess.ReadWrite) к свойству CurrentState.

Стихотворение

В травках зелёных, под небом ясным,
Лежит кролик, мечтая о сказках.
Состояния смена — весёлый момент,
Встаёт он с радостью, как будто на свет.
Спрайты вращаются, как в танце весном,
В мире изменений — мы вместе, вдвоём! 🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between dbddd7d and fa818f1.

📒 Files selected for processing (1)
  • Content.Client/Backmen/Standing/LayingDownSystem.cs (2 hunks)
🔇 Additional comments (3)
Content.Client/Backmen/Standing/LayingDownSystem.cs (3)

32-32: Подписка на событие корректна!

Добавление подписки на событие AfterAutoHandleStateEvent для компонента StandingStateComponent выполнено правильно и соответствует общему паттерну системы.


70-73: Улучшение проверки DrawDepth одобрено!

Добавление дополнительного условия для проверки текущего значения DrawDepth является правильным решением, которое предотвращает ненужные сбросы значения.


39-59: 🛠️ Refactor suggestion

Требуются улучшения в обработке состояний!

Предыдущие замечания по коду всё ещё актуальны:

  1. Магические числа (270, 90) следует вынести в константы
  2. Необходима проверка на null для системы анимации
  3. Логика поворота может быть упрощена

Дополнительные замечания:

  1. Желательно добавить комментарии, объясняющие логику выбора углов поворота
  2. Рекомендуется добавить проверку на Deleted перед изменением компонентов

Предлагаемое решение:

+ /// <summary>
+ /// Углы поворота для состояния лежания
+ /// </summary>
+ private const float LAYING_DOWN_ANGLE = 270f;
+ private const float ALTERNATE_LAYING_ANGLE = 90f;

  private void OnChangeStanding(Entity<StandingStateComponent> ent, ref AfterAutoHandleStateEvent args)
  {
-     if(_animation.HasRunningAnimation(ent, "rotate"))
+     if(_animation?.HasRunningAnimation(ent, "rotate") ?? false)
          return;

+     if (Deleted(ent))
+         return;

      if (!TryComp<SpriteComponent>(ent, out var sprite))
      {
          return;
      }

      if (ent.Comp.Standing)
      {
          sprite.Rotation = Angle.Zero;
          return;
      }

-     if (sprite.Rotation != Angle.FromDegrees(270) && sprite.Rotation != Angle.FromDegrees(90))
+     if (sprite.Rotation != Angle.FromDegrees(LAYING_DOWN_ANGLE) && 
+         sprite.Rotation != Angle.FromDegrees(ALTERNATE_LAYING_ANGLE))
      {
-         sprite.Rotation = Angle.FromDegrees(270);
+         sprite.Rotation = Angle.FromDegrees(LAYING_DOWN_ANGLE);
      }
  }

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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

🧹 Outside diff range and nitpick comments (2)
Content.Shared/Backmen/Standing/SharedLayingDownSystem.cs (2)

200-203: Оптимизация обработки сетевых событий

Проверка IsFirstTimePredicted предотвращает дублирование сетевых событий при синхронизации состояния между клиентом и сервером. Это важное изменение для корректной работы системы предсказания.

Убедитесь, что все остальные методы, вызывающие RaisePredictiveEvent, также проверяют IsFirstTimePredicted для консистентности поведения.


Line range hint 1-365: Общие рекомендации по улучшению кода

В целом изменения корректны и улучшают синхронизацию, но есть несколько моментов для рассмотрения:

  1. Рекомендуется добавить комментарии, объясняющие логику предсказания событий
  2. Стоит рассмотреть добавление логирования для отладки проблем с синхронизацией
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7a3d7a2 and dbddd7d.

📒 Files selected for processing (3)
  • Content.Client/Backmen/Standing/LayingDownSystem.cs (2 hunks)
  • Content.Shared/Backmen/Standing/SharedLayingDownSystem.cs (4 hunks)
  • Content.Shared/Standing/StandingStateComponent.cs (1 hunks)
🔇 Additional comments (7)
Content.Shared/Standing/StandingStateComponent.cs (2)

6-6: Правильное использование AutoGenerateComponentState!

Явное указание параметра true для автоматической генерации состояния улучшит синхронизацию между сервером и клиентом.


14-14: Проверьте корректность синхронизации состояний

Добавление ViewVariables с доступом на чтение и запись позволит отлаживать состояния в реальном времени. Рекомендуется проверить:

  • Корректную синхронизацию между сервером и клиентом
  • Правильное обновление состояния при переходах между Standing/Lying
✅ Verification successful

Based on the search results, I can see comprehensive evidence of proper synchronization between client and server for the StandingStateComponent:

  1. The component is properly networked with AutoNetworkedField
  2. Client-side LayingDownSystem subscribes to state changes via AfterAutoHandleStateEvent
  3. Server and shared systems properly handle state transitions
  4. Integration tests verify the state transitions

I can now provide the final response:

Синхронизация состояний реализована корректно

Проверка кодовой базы показала надёжную реализацию синхронизации:

  • Компонент корректно сетевой (AutoNetworkedField)
  • На клиенте есть обработчик изменений состояния (LayingDownSystem)
  • Имеются интеграционные тесты, проверяющие переходы состояний
  • ViewVariables не нарушает существующую логику синхронизации
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Проверка обработки состояний в связанных системах

# Поиск обработчиков событий изменения состояния
rg -A 5 "StandingStateComponent" --type cs

# Поиск связанных систем
ast-grep --pattern 'class $_ : ISystem {
  $$$
  StandingStateComponent
  $$$
}'

Length of output: 12870

Content.Client/Backmen/Standing/LayingDownSystem.cs (3)

25-25: Корректное добавление зависимости!

Зависимость SharedAppearanceSystem добавлена в соответствии с существующим паттерном инъекции зависимостей.


33-33: Подписка на событие добавлена корректно!

Подписка на AfterAutoHandleStateEvent для компонента StandingStateComponent правильно связана с обработчиком OnChangeStanding.


71-74: Улучшена логика проверки глубины отрисовки!

Добавленное условие корректно проверяет текущую глубину отрисовки перед её изменением, что предотвращает ненужные обновления состояния.

Content.Shared/Backmen/Standing/SharedLayingDownSystem.cs (2)

57-57: Добавлена зависимость IGameTiming для улучшения синхронизации

Добавление IGameTiming позволяет корректно обрабатывать предсказание событий между клиентом и сервером.


339-339: Улучшение синхронизации состояния

Добавление вызова Dirty после изменения CurrentState гарантирует, что изменение состояния будет корректно синхронизировано между клиентом и сервером.

Давайте проверим, что состояние корректно синхронизируется во всех случаях:

✅ Verification successful

Состояние корректно синхронизируется во всех случаях изменения

По результатам проверки кодовой базы видно, что после каждого изменения CurrentState в классах, связанных с системой Standing/LayingDown, всегда вызывается метод Dirty для синхронизации:

  • В SharedLayingDownSystem.cs после всех изменений standingState.CurrentState вызывается Dirty(uid, standingState)
  • В StandingStateSystem.cs также соблюдается этот паттерн
  • В StandingStateComponent.cs изменение происходит через свойство, которое правильно обрабатывается системой
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Проверяем все места, где изменяется CurrentState

# Поиск всех мест изменения CurrentState
ast-grep --pattern 'standingState.CurrentState = $_'

# Поиск вызовов Dirty после изменения состояния
rg -A 1 'CurrentState = ' 

Length of output: 5071

Comment on lines +40 to +60
private void OnChangeStanding(Entity<StandingStateComponent> ent, ref AfterAutoHandleStateEvent args)
{
if(_animation.HasRunningAnimation(ent, "rotate"))
return;

if (!TryComp<SpriteComponent>(ent, out var sprite))
{
return;
}

if (ent.Comp.Standing)
{
sprite.Rotation = Angle.Zero;
return;
}

if (sprite.Rotation != Angle.FromDegrees(270) && sprite.Rotation != Angle.FromDegrees(90))
{
sprite.Rotation = Angle.FromDegrees(270);
}
}
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 23, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Необходимы улучшения в обработке поворота спрайта!

Текущая реализация имеет несколько потенциальных улучшений:

  1. Отсутствует проверка на null для системы анимации
  2. Магические числа (270, 90) лучше вынести в константы
  3. Логика поворота может быть упрощена

Предлагаемые изменения:

+ private const float LAYING_DOWN_ANGLE = 270f;
+ private const float ALTERNATE_LAYING_ANGLE = 90f;

 private void OnChangeStanding(Entity<StandingStateComponent> ent, ref AfterAutoHandleStateEvent args)
 {
-    if(_animation.HasRunningAnimation(ent, "rotate"))
+    if(_animation?.HasRunningAnimation(ent, "rotate") ?? false)
         return;

     if (!TryComp<SpriteComponent>(ent, out var sprite))
     {
         return;
     }

     if (ent.Comp.Standing)
     {
         sprite.Rotation = Angle.Zero;
         return;
     }

-    if (sprite.Rotation != Angle.FromDegrees(270) && sprite.Rotation != Angle.FromDegrees(90))
+    if (sprite.Rotation != Angle.FromDegrees(LAYING_DOWN_ANGLE) && 
+        sprite.Rotation != Angle.FromDegrees(ALTERNATE_LAYING_ANGLE))
     {
-        sprite.Rotation = Angle.FromDegrees(270);
+        sprite.Rotation = Angle.FromDegrees(LAYING_DOWN_ANGLE);
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private void OnChangeStanding(Entity<StandingStateComponent> ent, ref AfterAutoHandleStateEvent args)
{
if(_animation.HasRunningAnimation(ent, "rotate"))
return;
if (!TryComp<SpriteComponent>(ent, out var sprite))
{
return;
}
if (ent.Comp.Standing)
{
sprite.Rotation = Angle.Zero;
return;
}
if (sprite.Rotation != Angle.FromDegrees(270) && sprite.Rotation != Angle.FromDegrees(90))
{
sprite.Rotation = Angle.FromDegrees(270);
}
}
private const float LAYING_DOWN_ANGLE = 270f;
private const float ALTERNATE_LAYING_ANGLE = 90f;
private void OnChangeStanding(Entity<StandingStateComponent> ent, ref AfterAutoHandleStateEvent args)
{
if(_animation?.HasRunningAnimation(ent, "rotate") ?? false)
return;
if (!TryComp<SpriteComponent>(ent, out var sprite))
{
return;
}
if (ent.Comp.Standing)
{
sprite.Rotation = Angle.Zero;
return;
}
if (sprite.Rotation != Angle.FromDegrees(LAYING_DOWN_ANGLE) &&
sprite.Rotation != Angle.FromDegrees(ALTERNATE_LAYING_ANGLE))
{
sprite.Rotation = Angle.FromDegrees(LAYING_DOWN_ANGLE);
}
}

Copy link
Contributor

Choose a reason for hiding this comment

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

Гуляш

Copy link
Contributor

Choose a reason for hiding this comment

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

@voko421: Понятно, спасибо за ваш ответ!

@Rxup Rxup merged commit bb3cc68 into master Nov 23, 2024
11 checks passed
@KayzelW KayzelW deleted the laydown-fix branch February 20, 2025 14:14
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