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

[PORT] add reactive armore #615

Merged
merged 3 commits into from
Nov 22, 2024
Merged

[PORT] add reactive armore #615

merged 3 commits into from
Nov 22, 2024

Conversation

CrimeMoot
Copy link
Collaborator

@CrimeMoot CrimeMoot commented Nov 22, 2024

Реактивная броня. Телепортирует своего носителя до получение урона.

Summary by CodeRabbit

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

    • Добавлен компонент "Телепортация Урона", позволяющий телепортировать персонажей при получении урона.
    • Введён компонент "Реактивная Броня", который активируется при определённом уровне урона.
    • Добавлен новый предмет "Реактивная Броня" с описанием и функциональностью в локализации для русского языка.
    • Обновлены конфигурации шкафчиков, чтобы включить "Реактивную Броню" для директора исследований.
  • Исправления ошибок

    • Исправлена ошибка в пути к спрайту для "Реактивной Броне".

Copy link

coderabbitai bot commented Nov 22, 2024

Walkthrough

В данном запросе на изменение добавлены новые компоненты и системы, связанные с механикой телепортации при получении урона. Введены два компонента: DamageTeleportComponent и ReactiveArmorComponent, каждый из которых содержит параметры для настройки диапазона и типов урона. Также создана система DamageTeleportSystem, которая обрабатывает события, связанные с телепортацией. Кроме того, обновлены локализация и конфигурация предметов в игровых шкафчиках, а также добавлены новые текстуры для реактивной брони.

Changes

File Path Change Summary
Content.Shared/_Cats/Components/DamageTeleportComponent.cs Новый компонент DamageTeleportComponent с полями MinRange и MaxRange.
Content.Shared/_Cats/Components/ReactiveArmorComponent.cs Новый компонент ReactiveArmorComponent с полями MinRange, MaxRange, DamageTypes, DamageThreshold, AccumulatedDamage.
Content.Shared/_Cats/DamageTeleportSystem.cs Новый класс DamageTeleportSystem, обрабатывающий телепортацию при получении урона.
Resources/Locale/ru-RU/_Cats/entities/clothing/Outer.ftl Добавлен новый элемент локализации для "реактивная броня".
Resources/Prototypes/Catalog/Fills/Lockers/heads.yml Обновлены шкафчики с добавлением "ClothingOuterReactiveArmor" и уточнением их содержимого.
Resources/Prototypes/_SpaceCats/Entities/Clothing/OuterClothing/vests.yml Добавлено определение сущности "реактивная броня" с соответствующими компонентами.
Resources/Textures/_SpaceCats/Clothing/OuterClothing/reactive.rsi/meta.json Новый файл метаданных для текстур реактивной брони.

Possibly related PRs

  • Upstreams #580: Изменения в классе HealthChange, касающиеся применения урона, могут быть связаны с DamageTeleportComponent.
  • [PORT] disco floor #582: Добавление ReactiveArmorComponent с аналогичными полями MinRange и MaxRange указывает на связь с DamageTeleportComponent.
  • Upstreams #585: Модификации в BodyPartComponent касаются порогов урона и могут быть связаны с DamageTeleportComponent.
  • [PORT] Personale gun #588: Введение DNAGunLockerComponent и его взаимодействие с персонализацией оружия может быть связано с DamageTeleportComponent.
  • revert advanced prying #611: Удаление качества AdvancedPrying из инструментов может быть связано с механикой урона и взаимодействия в игре.

Suggested labels

Changes: Localization, Changes: Sprites, Changes: UI

🐰 В мире, где броня жжет,
Реактивный щит нас ждет.
При уроне — в миг, как в сказке,
Телепорт — вот чудо в маске!
Локализация — не зря,
Броня теперь в игре, ура! 🎉


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

github-actions bot commented Nov 22, 2024

RSI Diff Bot; head commit 7a1976a merging into 2377bc3
This PR makes changes to 1 or more RSIs. Here is a summary of all changes:

Resources/Textures/_SpaceCats/Clothing/OuterClothing/reactive.rsi

State Old New Status
equipped-OUTERCLOTHING Added
icon Added
inhand-left Added
inhand-right Added

Edit: diff updated after 7a1976a

Copy link

@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: 11

🧹 Outside diff range and nitpick comments (7)
Content.Shared/_Cats/Components/DamageTeleportComponent.cs (1)

8-9: Добавьте XML-документацию для компонента

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

+/// <summary>
+/// Компонент, обеспечивающий телепортацию сущности при получении урона.
+/// </summary>
[RegisterComponent, Access(typeof(DamageTeleportSystem))]
public sealed partial class DamageTeleportComponent : Component
Resources/Prototypes/_SpaceCats/Entities/Clothing/OuterClothing/vests.yml (2)

4-5: Требуется более подробное описание

Текущее описание "Reactive armor" недостаточно информативно. Следует добавить информацию о механике телепортации при получении урона и других особенностях брони.

Предлагаю обновить описание:

- description: Reactive armor.
+ description: Продвинутая броня, оснащенная системой телепортации, которая активируется при получении урона. Обеспечивает хорошую защиту от различных типов повреждений.

28-28: Добавьте пустую строку в конец файла

Отсутствует пустая строка в конце файла, что может вызвать проблемы при обработке файла некоторыми инструментами.

Добавьте пустую строку в конец файла.

🧰 Tools
🪛 yamllint (1.29.0-1)

[error] 28-28: no new line character at the end of file

(new-line-at-end-of-file)

Content.Shared/_Cats/Components/ReactiveArmorComponent.cs (2)

23-28: Добавьте валидацию порога урона

Поле DamageThreshold должно быть положительным числом. Рекомендуется добавить атрибут для валидации значения.

 [DataField("damageThreshold", required: true)]
+[ViewVariables(VVAccess.ReadWrite)]
 public float DamageThreshold;

29-34: Исправьте документацию и добавьте валидацию накопленного урона

  1. В комментарии упоминается "artifact", что выглядит как ошибка копирования.
  2. Необходимо добавить проверку на отрицательные значения для AccumulatedDamage.
 /// <summary>
-/// How much damage has been accumulated on the artifact so far
+/// How much damage has been accumulated on the armor so far
 /// </summary>
 [DataField, ViewVariables(VVAccess.ReadWrite)]
-public float AccumulatedDamage = 0;
+public float AccumulatedDamage
+{
+    get => _accumulatedDamage;
+    set => _accumulatedDamage = Math.Max(0, value);
+}
+private float _accumulatedDamage = 0;
Content.Shared/_Cats/DamageTeleportSystem.cs (2)

1-21: Необходимо очистить неиспользуемые импорты

В файле присутствуют импорты, которые не используются в коде:

  • Content.Shared.Alert
  • Content.Shared.Gravity
  • Content.Shared.Standing
  • Robust.Shared.Player
  • Content.Shared.Mobs.Components
  • Content.Shared.Damage
  • Robust.Shared.Physics.Dynamics
  • Robust.Shared.Physics.Events

Также заголовок файла нестандартный и может быть улучшен.

-/// Maded by Gorox for Enterprise. See CLA
+// Copyright © 2024 Space Station 14 Team
+// Licensed under the Space Station 14 License

34-41: Рекомендуется реорганизация обработки событий

Все три обработчика событий выполняют идентичную логику телепортации. Рекомендуется выделить общую логику в отдельный метод.

+    private void HandleTeleport(EntityUid uid, DamageTeleportComponent component)
+    {
+        var xform = Transform(uid);
+        _transform.SetCoordinates(uid, xform, xform.Coordinates.Offset(
+            _random.NextVector2(component.MinRange, component.MaxRange)));
+    }
+
     public override void Initialize()
     {
         base.Initialize();
-        SubscribeLocalEvent<DamageTeleportComponent, AttackedEvent>(OnReactiveDamaged);
-        SubscribeLocalEvent<DamageTeleportComponent, ProjectileReflectAttemptEvent>(OnReactiveDamagedProjectile);
-        SubscribeLocalEvent<DamageTeleportComponent, HitScanReflectAttemptEvent>(OnReactiveDamagedHitscan);
+        SubscribeLocalEvent<DamageTeleportComponent, AttackedEvent>((uid, comp, args) => HandleTeleport(uid, comp));
+        SubscribeLocalEvent<DamageTeleportComponent, ProjectileReflectAttemptEvent>((uid, comp, args) => HandleTeleport(uid, comp));
+        SubscribeLocalEvent<DamageTeleportComponent, HitScanReflectAttemptEvent>((uid, comp, args) => HandleTeleport(uid, comp));
     }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 2377bc3 and 87a617c.

⛔ Files ignored due to path filters (4)
  • Resources/Textures/_SpaceCats/Clothing/OuterClothing/reactive.rsi/equipped-OUTERCLOTHING.png is excluded by !**/*.png
  • Resources/Textures/_SpaceCats/Clothing/OuterClothing/reactive.rsi/icon.png is excluded by !**/*.png
  • Resources/Textures/_SpaceCats/Clothing/OuterClothing/reactive.rsi/inhand-left.png is excluded by !**/*.png
  • Resources/Textures/_SpaceCats/Clothing/OuterClothing/reactive.rsi/inhand-right.png is excluded by !**/*.png
📒 Files selected for processing (7)
  • Content.Shared/_Cats/Components/DamageTeleportComponent.cs (1 hunks)
  • Content.Shared/_Cats/Components/ReactiveArmorComponent.cs (1 hunks)
  • Content.Shared/_Cats/DamageTeleportSystem.cs (1 hunks)
  • Resources/Locale/ru-RU/_Cats/entities/clothing/Outer.ftl (1 hunks)
  • Resources/Prototypes/Catalog/Fills/Lockers/heads.yml (1 hunks)
  • Resources/Prototypes/_SpaceCats/Entities/Clothing/OuterClothing/vests.yml (1 hunks)
  • Resources/Textures/_SpaceCats/Clothing/OuterClothing/reactive.rsi/meta.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • Resources/Textures/_SpaceCats/Clothing/OuterClothing/reactive.rsi/meta.json
🧰 Additional context used
🪛 GitHub Check: build (ubuntu-latest)
Content.Shared/_Cats/Components/ReactiveArmorComponent.cs

[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)


[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)

🪛 GitHub Check: YAML Linter
Content.Shared/_Cats/Components/ReactiveArmorComponent.cs

[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)


[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)

🪛 GitHub Check: Test Packaging
Content.Shared/_Cats/Components/ReactiveArmorComponent.cs

[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)


[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)

🪛 yamllint (1.29.0-1)
Resources/Prototypes/_SpaceCats/Entities/Clothing/OuterClothing/vests.yml

[error] 28-28: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (4)
Resources/Locale/ru-RU/_Cats/entities/clothing/Outer.ftl (1)

1-1: Перевод названия корректный!

Перевод "reactive armor" как "реактивная броня" выполнен правильно и соответствует игровой терминологии.

Content.Shared/_Cats/Components/DamageTeleportComponent.cs (1)

1-16: Проверить корректность размещения файла

Компонент находится в директории _Cats, что выглядит нестандартно для структуры проекта. Необходимо проверить, является ли это временным размещением при портировании.

✅ Verification successful

Let me gather more information about this _Cats directory and its purpose.


Размещение файла в директории _Cats является корректным

Анализ показал, что директория _Cats является специальным модулем проекта, содержащим множество связанных компонентов, систем и ресурсов. Это не временное размещение, а полноценная часть кодовой базы, включающая:

  • Компоненты и системы в Content.Shared/_Cats и Content.Server/_Cats
  • Локализации в Resources/Locale/{ru-RU,en-US}/_Cats
  • Аудио ресурсы в Resources/Audio/_Cats
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for other components in similar directory structure
echo "Checking for other components in _Cats directory:"
fd -e cs . | grep "_Cats/Components"

echo "Checking for standard component locations:"
fd -e cs . | grep "Components/" | grep -v "_Cats" | head -n 5

Length of output: 915


Script:

#!/bin/bash
# Check if there's any documentation or explanation about _Cats directory
echo "Checking for documentation mentioning _Cats:"
rg -i "_cats" "*.md"

echo -e "\nChecking for any other files in _Cats directory structure:"
fd . | grep "_Cats"

echo -e "\nChecking the git history of the _Cats directory:"
git log --oneline -- "*/_Cats/*" | head -n 5

Length of output: 10307

Resources/Prototypes/_SpaceCats/Entities/Clothing/OuterClothing/vests.yml (1)

13-21: Проверьте баланс защитных характеристик

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

Рекомендую пересмотреть коэффициенты защиты с учетом общего баланса игры.

Content.Shared/_Cats/Components/ReactiveArmorComponent.cs (1)

1-34: Проверьте интеграцию с системой урона

Компонент является частью механики телепортации при получении урона. Убедитесь, что:

  1. Система корректно подписана на события урона
  2. Обработка накопленного урона происходит атомарно
  3. Телепортация синхронизирована с сетевым кодом
🧰 Tools
🪛 GitHub Check: build (ubuntu-latest)

[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)


[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)

🪛 GitHub Check: YAML Linter

[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)


[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)

🪛 GitHub Check: Test Packaging

[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)


[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 8-8:
The type or namespace name 'ReactiveArmorSystem' could not be found (are you missing a using directive or an assembly reference?)

@@ -0,0 +1,2 @@
ent-ClothingOuterReactiveArmor = реактивная броня
.desc = Дорогая броня, с использованием блюспейс ядра. При получении повреждении телепортирует владельца на небольшое расстояние.
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Исправьте опечатку в слове "повреждении"

В описании допущена грамматическая ошибка.

Примените следующие изменения:

-    .desc = Дорогая броня, с использованием блюспейс ядра. При получении повреждении телепортирует владельца на небольшое расстояние.
+    .desc = Дорогая броня, с использованием блюспейс ядра. При получении повреждений телепортирует владельца на небольшое расстояние.
📝 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
.desc = Дорогая броня, с использованием блюспейс ядра. При получении повреждении телепортирует владельца на небольшое расстояние.
.desc = Дорогая броня, с использованием блюспейс ядра. При получении повреждений телепортирует владельца на небольшое расстояние.

Comment on lines +11 to +15
[DataField("minRandomRadius"), ViewVariables(VVAccess.ReadWrite)]
public float MinRange = 1.0f;

[DataField("maxRandomRadius"), ViewVariables(VVAccess.ReadWrite)]
public float MaxRange = 2.0f;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Требуются улучшения в определении полей

Обнаружено несколько проблем с полями компонента:

  1. Отсутствует проверка, что MaxRange > MinRange
  2. Имена в DataField атрибутах не соответствуют именам полей
  3. Отсутствует валидация допустимых значений
  4. Отсутствует XML-документация полей

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

+    /// <summary>
+    /// Минимальный радиус случайной телепортации в метрах.
+    /// </summary>
-    [DataField("minRandomRadius"), ViewVariables(VVAccess.ReadWrite)]
+    [DataField("minRange"), ViewVariables(VVAccess.ReadWrite)]
+    [DataField("validateRanges")]
     public float MinRange = 1.0f;

+    /// <summary>
+    /// Максимальный радиус случайной телепортации в метрах.
+    /// </summary>
-    [DataField("maxRandomRadius"), ViewVariables(VVAccess.ReadWrite)]
+    [DataField("maxRange"), ViewVariables(VVAccess.ReadWrite)]
+    [DataField("validateRanges")]
     public float MaxRange = 2.0f;

+    private void ValidateRanges()
+    {
+        if (MinRange < 0)
+            MinRange = 0;
+        if (MaxRange <= MinRange)
+            MaxRange = MinRange + 1.0f;
+    }

Committable suggestion skipped: line range outside the PR's diff.

@@ -0,0 +1,16 @@
/// Maded by Gorox for Enterprise. See CLA
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Необходимо привести заголовки файлов к стандартному виду проекта

Обнаружено, что все файлы в директории _Cats содержат нестандартный заголовок "Maded by Gorox for Enterprise. See CLA", в то время как остальные файлы проекта используют стандартный формат без указания авторства. Необходимо:

  • Удалить нестандартные заголовки CLA из следующих файлов:
    • Content.Shared/_Cats/Components/DamageTeleportComponent.cs
    • Content.Shared/_Cats/DamageTeleportSystem.cs
    • Content.Shared/_Cats/Components/ReactiveArmorComponent.cs

Файлы должны следовать общему стилю проекта, где используются только необходимые using-директивы без указания персонального авторства.

🔗 Analysis chain

Необходимо использовать стандартный заголовок лицензии

Текущий заголовок CLA не соответствует стандартному формату лицензирования проекта. Рекомендуется использовать стандартный заголовок лицензии, принятый в проекте.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the standard license header format used in the project
rg -l "^// <copyright" --type cs | head -n 1 | xargs cat | head -n 3

Length of output: 70


Script:

#!/bin/bash
# Let's check for common license header patterns in C# files
rg -l "^//.*[Cc]opyright|^//.*[Ll]icense|^//.*MIT|^//.*GPL|^//.*BSD" --type cs | head -n 5 | xargs -I {} sh -c 'echo "=== {} ==="; head -n 3 "{}"'

# Also check if there are other files with similar CLA mentions
rg -l "Gorox.*Enterprise|CLA" --type cs

Length of output: 354


Script:

#!/bin/bash
# Let's check the content of these files to see the pattern of CLA usage
echo "=== DamageTeleportSystem.cs ==="
head -n 3 Content.Shared/_Cats/DamageTeleportSystem.cs

echo -e "\n=== ReactiveArmorComponent.cs ==="
head -n 3 Content.Shared/_Cats/Components/ReactiveArmorComponent.cs

# Let's also check if there's a standard header pattern in other parts of the codebase
echo -e "\n=== Other C# files headers ==="
fd -e cs -E "_Cats" | head -n 5 | xargs -I {} sh -c 'echo "=== {} ==="; head -n 3 "{}"'

Length of output: 1509

Comment on lines +9 to +10
- type: Clothing
sprite: _SpaceCatsd/Clothing/OuterClothing/reactive.rsi
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Исправьте опечатку в пути к спрайту

В компоненте Clothing указан неверный путь к спрайту (_SpaceCatsd вместо _SpaceCats).

Примените следующие изменения:

- sprite: _SpaceCatsd/Clothing/OuterClothing/reactive.rsi
+ sprite: _SpaceCats/Clothing/OuterClothing/reactive.rsi
📝 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
- type: Clothing
sprite: _SpaceCatsd/Clothing/OuterClothing/reactive.rsi
- type: Clothing
sprite: _SpaceCats/Clothing/OuterClothing/reactive.rsi

Comment on lines +27 to +28
component:
- type: DamageTeleport
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Требуется конфигурация компонента DamageTeleport

Компонент DamageTeleport добавлен, но отсутствуют важные параметры, такие как MinRange и MaxRange для телепортации.

Добавьте необходимые параметры:

  - type: ClothingGrant
    component:
    - type: DamageTeleport
+      minRange: 2.0
+      maxRange: 7.0

Committable suggestion skipped: line range outside the PR's diff.

🧰 Tools
🪛 yamllint (1.29.0-1)

[error] 28-28: no new line character at the end of file

(new-line-at-end-of-file)

Comment on lines 17 to 22
/// <summary>
/// What damage types are accumulated for the trigger?
/// </summary>
[DataField("damageTypes", customTypeSerializer: typeof(PrototypeIdListSerializer<DamageTypePrototype>))]
public List<string>? DamageTypes;

Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Добавьте проверку на null для DamageTypes

Поле DamageTypes может быть null, но отсутствуют соответствующие проверки. Рекомендуется либо сделать поле non-nullable с пустым списком по умолчанию, либо добавить проверки.

-public List<string>? DamageTypes;
+[DataField("damageTypes", customTypeSerializer: typeof(PrototypeIdListSerializer<DamageTypePrototype>))]
+public List<string> DamageTypes = new();
📝 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
/// <summary>
/// What damage types are accumulated for the trigger?
/// </summary>
[DataField("damageTypes", customTypeSerializer: typeof(PrototypeIdListSerializer<DamageTypePrototype>))]
public List<string>? DamageTypes;
/// <summary>
/// What damage types are accumulated for the trigger?
/// </summary>
[DataField("damageTypes", customTypeSerializer: typeof(PrototypeIdListSerializer<DamageTypePrototype>))]
public List<string> DamageTypes = new();

Comment on lines 1 to 6
/// Maded by Gorox for Enterprise. See CLA
using Content.Shared.ReactiveArmor.Systems;
using Robust.Shared.Serialization.TypeSerializers.Implementations.Custom.Prototype.List;
using Content.Shared.Damage.Prototypes;

namespace Content.Shared.ReactiveArmor.Components;
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Подтверждено отсутствие ReactiveArmorSystem

Анализ кодовой базы показал, что компонент ReactiveArmorComponent.cs действительно является единственным файлом, связанным с реактивной броней, и система ReactiveArmorSystem отсутствует. Необходимо:

  • Создать файл ReactiveArmorSystem.cs в директории Content.Shared/_Cats/Systems/
  • Реализовать систему, наследующую ISystem
  • Обеспечить обработку логики реактивной брони
🔗 Analysis chain

Отсутствует реализация системы ReactiveArmorSystem

Компонент ссылается на Content.Shared.ReactiveArmor.Systems, но соответствующая система не найдена в сборке. Необходимо создать ReactiveArmorSystem.cs в директории Content.Shared/_Cats/Systems/.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Check if ReactiveArmorSystem exists
fd ReactiveArmorSystem.cs

Length of output: 27


Script:

#!/bin/bash
# Search for any files containing ReactiveArmor in their name
fd -t f ReactiveArmor

# Search for any references to ReactiveArmor namespace or system
rg -l "ReactiveArmor.(Systems|Components)"

# Check for any system implementations related to ReactiveArmor
ast-grep --pattern 'class $_ : ISystem {
  $$$
}'

Length of output: 236

🧰 Tools
🪛 GitHub Check: build (ubuntu-latest)

[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)

🪛 GitHub Check: YAML Linter

[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)

🪛 GitHub Check: Test Packaging

[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)


[failure] 2-2:
The type or namespace name 'Systems' does not exist in the namespace 'Content.Shared.ReactiveArmor' (are you missing an assembly reference?)

Comment on lines +26 to +32
[Dependency] private readonly INetManager _netManager = default!;
[Dependency] private readonly EntityLookupSystem _lookup = default!;
[Dependency] private readonly IRobustRandom _random = default!;
[Dependency] private readonly IGameTiming _gameTiming = default!;
[Dependency] private readonly SharedTransformSystem _transform = default!;
[Dependency] private readonly AlertsSystem _alerts = default!;
[Dependency] private readonly SharedTransformSystem _xform = default!;
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Требуется оптимизация зависимостей

В классе обнаружены следующие проблемы:

  1. Дублирование инъекции SharedTransformSystem (_transform и _xform)
  2. Неиспользуемая зависимость AlertsSystem
-    [Dependency] private readonly AlertsSystem _alerts = default!;
-    [Dependency] private readonly SharedTransformSystem _xform = default!;

Используйте единую ссылку на SharedTransformSystem.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +43 to +59
private void OnReactiveDamaged(EntityUid uid, DamageTeleportComponent component, ref AttackedEvent args)
{
var xform = Transform(uid);
_xform.SetCoordinates(uid, xform, xform.Coordinates.Offset(_random.NextVector2(component.MinRange, component.MaxRange)));
}

private void OnReactiveDamagedProjectile(EntityUid uid, DamageTeleportComponent component, ref ProjectileReflectAttemptEvent args)
{
var xform = Transform(uid);
_xform.SetCoordinates(uid, xform, xform.Coordinates.Offset(_random.NextVector2(component.MinRange, component.MaxRange)));
}

private void OnReactiveDamagedHitscan(EntityUid uid, DamageTeleportComponent component, ref HitScanReflectAttemptEvent args)
{
var xform = Transform(uid);
_xform.SetCoordinates(uid, xform, xform.Coordinates.Offset(_random.NextVector2(component.MinRange, component.MaxRange)));
}
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

⚠️ Potential issue

Based on the gathered information, I can now provide the final response:

Подтверждаю необходимость проверок безопасности телепортации

Анализ кодовой базы показывает, что другие системы телепортации (например, RandomTeleportArtifactSystem) также не имеют необходимых проверок безопасности. Это системная проблема, которая требует исправления.

Рекомендуемые изменения:

  • Добавить проверку коллизий через PhysicsComponent (CollisionLayer/CollisionMask)
  • Реализовать валидацию координат с использованием существующей системы CanAccess
  • Добавить обработку случаев неудачной телепортации с возвратом в исходную позицию

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

🔗 Analysis chain

Отсутствуют проверки безопасности телепортации

Текущая реализация телепортации может привести к следующим проблемам:

  1. Телепортация в недопустимые локации
  2. Отсутствие проверки коллизий
  3. Возможность застревания в стенах или других объектах

Рекомендуется:

  1. Добавить проверку валидности новых координат
  2. Реализовать обработку коллизий
  3. Добавить fallback механизм при неудачной телепортации

Let's gather more information about the teleportation implementations in the found files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Проверка наличия подобных механизмов безопасности в других системах телепортации

# Поиск других систем телепортации
rg -l "SetCoordinates.*Offset" --type cs

# Поиск примеров проверки координат
ast-grep --pattern 'if ($COND) { $$$; SetCoordinates($$$); }'

Length of output: 342


Script:

#!/bin/bash
# Check the implementation of other teleportation systems
rg -A 10 "SetCoordinates.*Offset" Content.Server/Xenoarchaeology/XenoArtifacts/Effects/Systems/RandomTeleportArtifactSystem.cs Content.Server/Disposal/Unit/EntitySystems/DisposableSystem.cs

# Look for any coordinate validation methods
rg "ValidateCoordinates|IsValidCoordinates|CanAccess" --type cs

# Check for any collision-related methods
rg "CheckCollision|HandleCollision|CollisionLayer" --type cs

Length of output: 33595

@@ -301,6 +301,7 @@
- id: FlatpackOracle # backmen
- id: FlatpackSophie # backmen
- id: AnomalyPinpointer # cats
- id: ClothingOuterReactiveArmor # cats
Copy link

Choose a reason for hiding this comment

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

💡 Codebase verification

Реактивная броня требует балансировки и документации

На основе проверки кодовой базы:

  • Броня имеет коэффициент сопротивления взрывам 0.65, что делает её достаточно мощной
  • Она доступна только в шкафчике директора исследований
  • Отсутствует подробная документация о механике работы

Рекомендации:

  • Добавить подробное описание механики работы брони в файл документации
  • Пересмотреть значение damageCoefficient с учётом баланса игры
  • Рассмотреть возможность добавления недостатков для компенсации сильной защиты
🔗 Analysis chain

Необходимо документировать возможности реактивной брони

Добавление реактивной брони в шкафчик директора исследований является значительным изменением с точки зрения игрового баланса. Рекомендуется:

  1. Добавить комментарий, описывающий возможности брони
  2. Проверить баланс относительно других глав станции
  3. Убедиться, что это соответствует роли директора исследований
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for documentation and configuration of reactive armor

# Look for reactive armor documentation
rg -l "ReactiveArmor" -g "*.md"

# Check reactive armor configuration
rg -l "ReactiveArmor" -g "*.yml"

Length of output: 191


Script:

#!/bin/bash
# Check the reactive armor configuration details
rg -A 10 "ReactiveArmor" Resources/Prototypes/_SpaceCats/Entities/Clothing/OuterClothing/vests.yml

# Check if there are any other head lockers with similar armor
rg -A 5 -B 5 "ClothingOuterReactiveArmor" Resources/Prototypes/Catalog/Fills/Lockers/heads.yml

# Look for any balance-related configurations or components
ast-grep --pattern 'id: ClothingOuterReactiveArmor
  parent: $_
  components:
    $$$'

Length of output: 975

@CrimeMoot CrimeMoot changed the title [PORT] add reactive [PORT] add reactive armore Nov 22, 2024
@CrimeMoot CrimeMoot merged commit e459607 into master Nov 22, 2024
13 checks passed
@CrimeMoot CrimeMoot deleted the Delay branch November 22, 2024 20:36
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.

1 participant