Исходный код osu

Обновлено: 05.07.2024

dev chat

A free-to-win rhythm game. Rhythm is just a click away!

The future of osu! and the beginning of an open era! Currently known by and released under the codename "lazer". As in sharper than cutting-edge.

This project is under heavy development, but is in a stable state. Users are encouraged to try it out and keep it installed alongside the stable osu! client. It will continue to evolve to the point of eventually replacing the existing stable client as an update.

IMPORTANT: Gameplay mechanics (and other features which you may have come to know and love) are in a constant state of flux. Game balance and final quality-of-life passes come at the end of development, preceded by experimentation and changes which may potentially reduce playability or usability. This is done in order to allow us to move forward as developers and designers more efficiently. If this offends you, please consider sticking to the stable releases of osu! (found on the website). We are not yet open to heated discussion over game mechanics and will not be using github as a forum for such discussions just yet.

We are accepting bug reports (please report with as much detail as possible and follow the existing issue templates). Feature requests are also welcome, but understand that our focus is on completing the game to feature parity before adding new features. A few resources are available as starting points to getting involved and understanding the project:

  • Detailed release changelogs are available on the official osu! site.
  • You can learn more about our approach to project management.
  • Read peppy's blog post exploring where the project is currently and the roadmap going forward.

If you are looking to install or test osu! without setting up a development environment, you can consume our binary releases. Handy links below will download the latest version for your operating system of choice:

Latest build:

  • The iOS testflight link may fill up (Apple has a hard limit of 10,000 users). We reset it occasionally when this happens. Please do not ask about this. Check back regularly for link resets or follow peppy on twitter for announcements of link resets.

If your platform is not listed above, there is still a chance you can manually build it by following the instructions below.

Developing a custom ruleset

osu! is designed to have extensible modular gameplay modes, called "rulesets". Building one of these allows a developer to harness the power of osu! for their own game style. To get started working on a ruleset, we have some templates available here.

You can see some examples of custom rulesets by visiting the custom ruleset directory.

Please make sure you have the following prerequisites:

Downloading the source code

Clone the repository:

To update the source code to the latest commit, run the following command inside the osu directory:

Build configurations for the recommended IDEs (listed above) are included. You should use the provided Build/Run functionality of your IDE to get things going. When testing or building new components, it's highly encouraged you use the VisualTests project/configuration. More information on this is provided below.

  • Visual Studio / Rider users should load the project via one of the platform-specific .slnf files, rather than the main .sln. This will allow access to template run configurations.

You can also build and run osu! from the command-line with a single command:

If you are not interested in debugging osu!, you can add -c Release to gain performance. In this case, you must replace Debug with Release in any commands mentioned in this document.

If the build fails, try to restore NuGet packages with dotnet restore .

Testing with resource/framework modifications

Sometimes it may be necessary to cross-test changes in osu-resources or osu-framework. This can be achieved by running some commands as documented on the osu-resources and osu-framework wiki pages.

Before committing your code, please run a code formatter. This can be achieved by running dotnet format in the command line, or using the Format code command in your IDE.

We have adopted some cross-platform, compiler integrated analyzers. They can provide warnings when you are editing, building inside IDE or from command line, as-if they are provided by the compiler itself.

JetBrains ReSharper InspectCode is also used for wider rule sets. You can run it from PowerShell with .\InspectCode.ps1 . Alternatively, you can install ReSharper or use Rider to get inline support in your IDE of choice.

When it comes to contributing to the project, the two main things you can do to help out are reporting issues and submitting pull requests. Based on past experiences, we have prepared a list of contributing guidelines that should hopefully ease you into our collaboration process and answer the most frequently-asked questions.

Note that while we already have certain standards in place, nothing is set in stone. If you have an issue with the way code is structured, with any libraries we are using, or with any processes involved with contributing, please bring it up. We welcome all feedback so we can make contributing to this project as painless as possible.

For those interested, we love to reward quality contributions via bounties, paid out via PayPal or osu!supporter tags. Don't hesitate to request a bounty for your work on this project.

osu!'s code and framework are licensed under the MIT licence. Please see the licence file for more information. tl;dr you can do whatever you want as long as you include the original copyright and license notice in any copy of the software/source.

Please note that this does not cover the usage of the "osu!" or "ppy" branding in any software, resources, advertising or promotion, as this is protected by trademark law.

Please also note that game resources are covered by a separate licence. Please see the ppy/osu-resources repository for clarifications.

Picture 1

Итого, для проверки игры на ошибки я использовал не тестовые проекты, содержащие 1507 файлов исходного кода и 110 тысяч строк. Однако результат меня отчасти порадовал, так как нашлось несколько интересных ошибок, о которых я спешу вам рассказать.

Заключение

В целом проект игры «osu!» порадовал небольшим числом ошибок. Тем не менее, я рекомендую разработчикам обратить внимание на обнаруженные проблемы. И пусть игра и далее радует своих поклонников.

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

Удачи и творческих успехов!

Ссылки


Если хотите поделиться этой статьей с англоязычной аудиторией, то прошу использовать ссылку на перевод: Sergey Khrenov. Play «osu!», but Watch Out for Bugs.

Ошибки

V3001 There are identical sub-expressions 'result == HitResult.Perfect' to the left and to the right of the '||' operator. DrawableHoldNote.cs 266


Хороший пример копипаст-ориентированного программирования. Шуточный термин, который недавно использовал (ввёл) мой коллега Валерий Комаров в своей статье "Топ 10 ошибок в проектах Java за 2019 год".

Итак, две идентичных проверки следуют одна за другой. Одна из проверок, скорее всего, должна содержать другую константу перечисления HitResult:


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

V3001 There are identical sub-expressions 'family != GetFamilyString(TournamentTypeface.Aquatico)' to the left and to the right of the '&&' operator. TournamentFont.cs 64


Возможно, в условии дважды по ошибке использована переменная family, но это не точно.

V3009 [CWE-393] It's odd that this method always returns one and the same value of 'false'. KeyCounterAction.cs 19


Метод всегда вернёт false. Для таких ошибок я обычно проверяю вызывающий код, так как там часто просто нигде не используют возвращаемое значение, тогда ошибки (кроме некрасивого стиля программирования) нет. В данном случае мне встретился такой код:


Как видим, результат, возвращаемый методом OnPressed, используется. И так как он всегда false, то и результат вызывающего OnPressed также будет всегда false. Думаю, следует лишний раз перепроверить этот код, так как высока вероятность ошибки.

Ещё одна подобная ошибка:

  • V3009 [CWE-393] It's odd that this method always returns one and the same value of 'false'. KeyCounterAction.cs 30


В условии оператора ?: с переменной val.NewValue работают небезопасно. Анализатор сделал такой вывод, так как далее в then-ветке для доступа к переменной используют безопасный вариант работы через оператор условного доступа val.NewValue?.Substring(. ).

Ещё одна подобная ошибка:

  • V3042 [CWE-476] Possible NullReferenceException. The '?.' and '.' operators are used for accessing members of the 'val.NewValue' object TournamentTeam.cs 48


Данный код менее однозначен, но я думаю, что ошибка тут всё же присутствует. Создают объект типа ActionableInfo. Поле Action инициализируют лямбдой, в теле которой небезопасно работают с потенциально нулевой ссылкой api. Анализатор посчитал такой паттерн ошибкой, так как далее при инициализации параметра Value с переменной api работают безопасно. Ошибку я назвал неоднозначной, потому что код лямбды предполагает отложенное выполнение и тогда, возможно, разработчик как-то гарантирует ненулевое значение ссылки api. Но это только предположение, так как тело лямбды не содержит никаких признаков безопасной работы со ссылкой (предварительных проверок, например).

V3066 [CWE-683] Possible incorrect order of arguments passed to 'Atan2' method: 'diff.X' and 'diff.Y'. SliderBall.cs 182


Анализатор заподозрил, что при работе с методом Atan2 класса Math разработчик перепутал порядок следования аргументов. Объявление Atan2:


Как видим, были переданы значения в обратном порядке. Не берусь судить, ошибка ли это, так как метод UpdateProgress содержит довольно много нетривиальных вычислений. Просто отмечу факт возможной проблемы в коде.

V3080 [CWE-476] Possible null dereference. Consider inspecting 'Beatmap'. WorkingBeatmap.cs 57


Анализатор указал на опасность доступа по нулевой ссылке Beatmap. Вот что она собой представляет:


Ну что же, анализатор прав.

V3083 [CWE-367] Unsafe invocation of event 'ObjectConverted', NullReferenceException is possible. Consider assigning event to a local variable before invoking it. BeatmapConverter.cs 82


Некритичная и довольно часто встречающаяся ошибка. Между проверкой события на равенство null и его инвокацией, от события могут отписаться, что приведет к падению программы.
Один из вариантов исправления:


V3095 [CWE-476] The 'columns' object was used before it was verified against null. Check lines: 141, 142. SquareGraph.cs 141


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

V3119 Calling overridden event 'OnNewResult' may lead to unpredictable behavior. Consider implementing event accessors explicitly or use 'sealed' keyword. DrawableRuleset.cs 256

Ещё одна подобная небезопасная конструкция в коде:

  • V3119 Calling an overridden event may lead to unpredictable behavior. Consider implementing event accessors explicitly or use 'sealed' keyword. DrawableRuleset.cs 257


Для лучшего понимания проблемы – приведу синтетический пример того, как сейчас работает код:


Ошибка была допущена вследствие того, что оператор "*" имеет более высокий приоритет, чем оператор "??". Исправленный вариант кода (добавлены скобки):

Ещё одна подобная ошибка в коде:

V3123 [CWE-783] Perhaps the '??' operator works in a different way than it was expected. Its priority is lower than priority of other operators in its left part. FramedReplayInputHandler.cs 103


Здесь, как и в предыдущем фрагменте кода, не учли приоритет операторов. Сейчас выражение, передаваемое в метод Math.Abs, вычисляется так:

V3142 [CWE-561] Unreachable code detected. It is possible that an error is present. DrawableHoldNote.cs 214


Анализатор утверждает, что код обработчика OnPressed, начиная со второго оператора if, является недостижимым. Это следует из предположения, что первое условие всегда истинно, то есть метод base.OnPressed всегда вернет false. Взглянем на метод base.OnPressed:


Переходим далее к методу UpdateResult:

Обратите внимание, реализация свойства Judged здесь не важна, так как из логики метода UpdateResult следует, что последний оператор return эквивалентен такому:


Таким образом, метод UpdateResult всегда вернет false, что и приведет к возникновению ошибки с недостижимым кодом в коде выше по стеку.

V3146 [CWE-476] Possible null dereference of 'ruleset'. The 'FirstOrDefault' can return default null value. APILegacyScoreInfo.cs 24


Анализатор считает небезопасным вызов ruleset.CreateInstance(). Переменная ruleset ранее получает значение в результате вызова GetRuleset:


Как видим, предупреждение анализатора обосновано, так как цепочка вызовов содержит FirstOrDefault, который может вернуть значение null.

Читайте также: