diff --git a/articles/getting_started/1_setting_up_your_development_environment_unix.md b/articles/getting_started/1_setting_up_your_development_environment_unix.md index ff7ee2d..39e5ca0 100644 --- a/articles/getting_started/1_setting_up_your_development_environment_unix.md +++ b/articles/getting_started/1_setting_up_your_development_environment_unix.md @@ -1,15 +1,11 @@ --- title: Setting up your development environment for macOS and Linux -description: A step-by-step guide for setting up your development environment on macOS and Linux. +description: This section provides a step-by-step guide for setting up your development environment on macOS and Linux. --- -# Setting up your development environment for macOS and Linux - -This section provides a step-by-step guide for setting up your development environment on macOS and Linux. - The only development environment that MonoGame officially supports on Linux is [Visual Studio Code](https://code.visualstudio.com/). -## Install .NET 6 SDK +## Install .NET 8 SDK - .NET SDK at: [https://dotnet.microsoft.com/en-us/download](https://dotnet.microsoft.com/en-us/download) - If you are intending to target mobile platforms, make sure that you have the corresponding workload installed @@ -34,6 +30,7 @@ code --install-extension ms-dotnettools.csharp ``` If you want, you can also install the C# Dev Kit extensions, which are not open source: + ```sh code --install-extension ms-dotnettools.csdevkit code --install-extension ms-dotnettools.dotnet-maui diff --git a/articles/getting_started/1_setting_up_your_development_environment_vscode.md b/articles/getting_started/1_setting_up_your_development_environment_vscode.md index 04ba4fb..af59200 100644 --- a/articles/getting_started/1_setting_up_your_development_environment_vscode.md +++ b/articles/getting_started/1_setting_up_your_development_environment_vscode.md @@ -3,8 +3,6 @@ title: Setting up your development environment for VSCode description: A step-by-step guide for setting up your development environment using VSCode --- -# Setting up your development environment for VSCode - This is a guide on setting up your development environment for creating games with MonoGame using Visual Studio Code. By following this guide, you will learn how to install the necessary .NET SDK for developing C# applications, set up MonoGame C# templates for new projects, and configure Visual Studio Code with recommended extensions for C# development. By the end, you'll be fully equipped to start creating games with MonoGame using Visual Studio code. > [!NOTE] @@ -13,15 +11,17 @@ This is a guide on setting up your development environment for creating games wi > [Visual Studio for Mac will be discontinued](https://devblogs.microsoft.com/visualstudio/visual-studio-for-mac-retirement-announcement/) by Microsoft in August 2024. At that time, [Visual Studio Code](https://code.visualstudio.com/) will be the only development environment supported by MonoGame on macOS. ## Install .NET 8 SDK + To develop with C#, you will need to install the .NET SDK. At the time of this writing, the current version is .NET 8.0. You can follow the instructions below based your operating system to install the .NET 8.0 SDK > [!NOTE] > The current version of MonoGame (3.8.1.303) targets .NET 6.0. Regardless you can, and it is recommended to, use .NET 8.0. The only requirement for having .NET 6.0 installed is if you are developing extensions for the MGCB Editor. -# [Windows](#tab/windows) +### [Windows](#tab/windows) + 1. Navigate to [https://dotnet.microsoft.com/en-us/download](https://dotnet.microsoft.com/en-us/download) -![Download .NET For Windows](./images/1_setting_up_your_development_environment/vscode/windows/download-dotnet.png) + ![Download .NET For Windows](./images/1_setting_up_your_development_environment/vscode/windows/download-dotnet.png) 2. Click the **.NET SDK x64** download button to download. This will take you to the download page where the **dotnet-sdk-8.x.yyy-win-x64.exe** will download. 3. When the download completes, run the **dotnet-sdk-8.x.yyy-win-x64.exe** installer and complete the steps to install .NET on your machine. @@ -29,59 +29,61 @@ To develop with C#, you will need to install the .NET SDK. At the time of this ![Verify Installation](./images/1_setting_up_your_development_environment/vscode/windows/verify-install.png) -# [macOS](#tab/macos) +### [macOS](#tab/macos) + 1. Navigate to [https://dotnet.microsoft.com/en-us/download](https://dotnet.microsoft.com/en-us/download) -![Download .NET For Mac](./images/1_setting_up_your_development_environment/vscode/mac/download-dotnet.png) + ![Download .NET For Mac](./images/1_setting_up_your_development_environment/vscode/mac/download-dotnet.png) 2. Download the .NET SDK x64-(Intel) Installer -> [!NOTE] -> For the time being, MonoGame requires that you install the **.NET SDK x64-(Intel)** version of the .NET SDK even if you are running on an Apple Silicon (M1/M2) Mac. For Apple Silicon Macs, it also requires that [Rosetta](https://support.apple.com/en-us/HT211861) is enabled. + > [!NOTE] + > For the time being, MonoGame requires that you install the **.NET SDK x64-(Intel)** version of the .NET SDK even if you are running on an Apple Silicon (M1/M2) Mac. For Apple Silicon Macs, it also requires that [Rosetta](https://support.apple.com/en-us/HT211861) is enabled. 3. Once the installation **.pkg** file finishes downloading, run it and follow the prompts to install the .NET SDK -![Install .NET For Mac](./images/1_setting_up_your_development_environment/vscode/mac/install-dotnet.png) + ![Install .NET For Mac](./images/1_setting_up_your_development_environment/vscode/mac/install-dotnet.png) 4. Once the installation is complete, open a new terminal window and run the command `dotnet` to verify the installation was successful. ![Verify Installation](./images/1_setting_up_your_development_environment/vscode/mac/verify-install.png) -# [Linux](#tab/linux) +### [Linux](#tab/linux) + 1. Open a new **Terminal** window. 2. Enter the following command in the terminal to download the **dotnet-install.sh** -```sh -wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh -``` + ```sh + wget https://dot.net/v1/dotnet-install.sh -O dotnet-install.sh + ``` 3. Grant permission for the script to execute by entering the following command in the terminal: -```sh -chmod +x ./dotnet-install.sh -``` + ```sh + chmod +x ./dotnet-install.sh + ``` 4. Run the script to install the .NET 8 SDK by entering the following command in the terminal: -```sh -./dotnet-install.sh -``` + ```sh + ./dotnet-install.sh + ``` -![.NET Install Script](./images/1_setting_up_your_development_environment/vscode/linux/dotnet-install-script.png) + ![.NET Install Script](./images/1_setting_up_your_development_environment/vscode/linux/dotnet-install-script.png) 5. You will now need to setup your environment variables so that the `dotnet` command is recognized. To do this, open the file `~/.bashrc` in a text editor and add the following lines to the end of the file. -```sh -export DOTNET_ROOT=$HOME/.dotnet -export PATH=$PATH:$DOTNET_ROOT:$DOTNET_ROOT/tools -``` + ```sh + export DOTNET_ROOT=$HOME/.dotnet + export PATH=$PATH:$DOTNET_ROOT:$DOTNET_ROOT/tools + ``` -![Add Environment Variables](./images/1_setting_up_your_development_environment/vscode/linux/add-environment-variables.png) + ![Add Environment Variables](./images/1_setting_up_your_development_environment/vscode/linux/add-environment-variables.png) 6. Save and close the file, close any open terminal windows, then open a new terminal window so the new environment variables are registered. 7. Enter the `dotnet` command to validate that the .NET 8 SDK is now installed. -![Verify Installation](./images/1_setting_up_your_development_environment/vscode/linux/verify-install.png) + ![Verify Installation](./images/1_setting_up_your_development_environment/vscode/linux/verify-install.png) --- @@ -94,40 +96,43 @@ export PATH=$PATH:$DOTNET_ROOT:$DOTNET_ROOT/tools > ``` ## Install MonoGame Templates + The .NET SDK installation provides the default C# project templates but does not include the MonoGame templates. These templates must be installed manually. 1. Open a new terminal window (**Command Prompt** on Windows). -```sh -dotnet new install MonoGame.Templates.CSharp -``` - -![Install MonoGame Templates](./images/1_setting_up_your_development_environment/vscode/install-templates.png) + ```sh + dotnet new install MonoGame.Templates.CSharp + ``` + ![Install MonoGame Templates](./images/1_setting_up_your_development_environment/vscode/install-templates.png) -> [!NOTE] -> When installing the templates, an error message may appear regarding the UWP template failing to install. This error can be safely ignored, as the UWP templates are deprecated and will be removed in a future MonoGame release. + > [!NOTE] + > When installing the templates, an error message may appear regarding the UWP template failing to install. This error can be safely ignored, as the UWP templates are deprecated and will be removed in a future MonoGame release. ## Install Visual Studio Code -# [Windows](#tab/windows) +### [Windows](#tab/windows) + 1. Open your web browser and navigate to [https://code.visualstudio.com/](https://code.visualstudio.com/). -![Download VSCode](./images/1_setting_up_your_development_environment/vscode/windows/download-vscode.png) + ![Download VSCode](./images/1_setting_up_your_development_environment/vscode/windows/download-vscode.png) 2. Click the **Download for Windows** button. This will redirect you to the download page where the installer will automatically download. 3. When the download completes, run the installer and complete the steps to install Visual Studio Code. -# [macOS](#tab/macos) +### [macOS](#tab/macos) + 1. Open your web browser and navigate to [https://code.visualstudio.com/](https://code.visualstudio.com/). -![Download VSCode](./images/1_setting_up_your_development_environment/vscode/mac/download-vscode.png) + ![Download VSCode](./images/1_setting_up_your_development_environment/vscode/mac/download-vscode.png) 2. Click the **Download Mac Universal** button. This will redirect you to the page where the application archive (.zip) file will begin downloading. 3. Extract the contents of the VSCode archive that downloaded by double-clicking it inside a Finder window. This will extract the **Visual Studio Code.app** file. 4. Drag the **Visual Studio Code.app** file into the **Applications** folder, making it available in the macOS Launchpad. -# [Linux](#tab/linux) +### [Linux](#tab/linux) + The recommended method for installing Visual Studio Code in Linux is to use Snap. This is supported by most Linux distributions. - [Snap Package](https://code.visualstudio.com/docs/setup/linux#_snap) @@ -143,12 +148,13 @@ There are also individual guides below based on your Linux distribution if you d --- ## Install Visual Studio Code C# Extensions + To transform Visual Studio Code from a simple text editor into a powerful development environment for C# projects, you must install the Visual Studio Code C# extension. This extension enhances the editor by providing syntax highlighting, code analysis, IntelliSense, and other features that significantly improve the development experience and productivity when working with C#. 1. Open Visual Studio Code. 2. Click the **Extensions** icon in the **Activity Bar** on the left. -![Click Extensions](./images/1_setting_up_your_development_environment/vscode/click-extensions.png) + ![Click Extensions](./images/1_setting_up_your_development_environment/vscode/click-extensions.png) 3. In the **Search Box** type `C#`. 4. Click **Install** for the **C# Dev Kit** extension. Installing this will also install the base **C#** extension. @@ -158,15 +164,18 @@ To transform Visual Studio Code from a simple text editor into a powerful develo --- ## Setup Wine For Effect Compilation - MacOS/Linux Only + Effect (shader) compilation requires access to DirectX. This means it will not work natively on macOS and Linux systems, but it can be used through [Wine](https://www.winehq.org/). -# [Windows](#tab/windows) +### [Windows](#tab/windows) + > [!NOTE] > Windows users do not require an additional setup for effect compilation and can skip this section. -# [macOS](#tab/macos) -MonoGame -MonoGame provides a setup script that can be executed to setup the Wine environment for Effect (shader) compilation. However, this script has the following prerequisites that must first be setup +### [macOS](#tab/macos) + +MonoGame provides a setup script that can be executed to setup the Wine environment for Effect (shader) compilation. However, this script has the following prerequisites that must first be setup: + - **curl** must be installed - **p7zip** must be installed - **wine-stable** must be installed. @@ -176,13 +185,13 @@ These can be installed using **brew**. 1. Open a terminal window. 2. Enter the following command: -```sh -brew install p7zip curl -brew install --cask wine-stable -``` + ```sh + brew install p7zip curl + brew install --cask wine-stable + ``` -> [!CAUTION] -> It is recommended that you use `wine-stable` and not `wine-staging`. + > [!CAUTION] + > It is recommended that you use `wine-stable` and not `wine-staging`. 3. Now that the prerequisites are installed, download the [mgfxc_wine_setup.sh](https://monogame.net/downloads/net6_mgfxc_wine_setup.sh) script and execute it by entering the following command in the terminal: @@ -192,8 +201,10 @@ wget -qO- https://monogame.net/downloads/net6_mgfxc_wine_setup.sh | bash This will create new directory called `.winemonogame` in your home directory. If you ever wish to undo the setup this script performed, just simply delete that directory. -# [Linux](#tab/linux) -MonoGame provides a setup script that can be executed to setup the Wine environment for Effect (shader) compilation. However, this script has the following prerequisites that must first be setup +### [Linux](#tab/linux) + +MonoGame provides a setup script that can be executed to setup the Wine environment for Effect (shader) compilation. However, this script has the following prerequisites that must first be setup: + - **curl** must be installed - **p7zip** must be installed - **wine64** must be installed. @@ -203,42 +214,42 @@ For Debian-based distributions like Ubuntu, you can perform the following: 1. Open a terminal window 2. Enter the following command -```sh -sudo apt install curl p7zip-full wine64 -``` + ```sh + sudo apt install curl p7zip-full wine64 + ``` -> [!TIP] -> If you receive an error stating that either of the packages do not have an install candidate, you may need to enable the universe apt repository. To do this, enter the following commands in the terminal -> -> ```sh -> sudo add-apt-repository universe -> sudo apt update -> ``` -> -> Then try installing the packages again. + > [!TIP] + > If you receive an error stating that either of the packages do not have an install candidate, you may need to enable the universe apt repository. To do this, enter the following commands in the terminal + > + > ```sh + > sudo add-apt-repository universe + > sudo apt update + > ``` + > + > Then try installing the packages again. -> [!CAUTION] -> If you plan to install Wine using the `winehq-*` package instead, it is recommended that you use the `winehq-stable` package and not `-staging`. + > [!CAUTION] + > If you plan to install Wine using the `winehq-*` package instead, it is recommended that you use the `winehq-stable` package and not `-staging`. 3. Now that the prerequisites are installed, download the [mgfxc_wine_setup.sh](https://monogame.net/downloads/net6_mgfxc_wine_setup.sh) script and execute it by entering the following command in the terminal: -```sh -wget -qO- https://monogame.net/downloads/net6_mgfxc_wine_setup.sh | bash -``` + ```sh + wget -qO- https://monogame.net/downloads/net6_mgfxc_wine_setup.sh | bash + ``` This will create new directory called `.winemonogame` in your home directory. If you ever wish to undo the setup this script performed, just simply delete that directory. - --- ## Apple Silicon Known Issues + There is currently a two known issue when building content on an Apple Silicon (M1/M2) Mac: 1. **Building Textures**: An exception occurs stating that the **freeimage** lib could not be found. 2. **Building SpriteFonts**: An exception occurs stating that the **freetype** lib could not be found. 3. **Building Models**: An exception occurs starting that the **assimp** lib could not be found. -These issue occur due to needing compiled versions of these libs for the M1/M2 architecture. [There is currently work being done to resolve this](https://github.com/MonoGame/MonoGame/issues/8124), however in the meantime you can use the following workaround that has been provided by community members. +These issue occur due to needing compiled versions of these libs for the M1/M2 architecture. [There is currently work being done to resolve this](https://github.com/MonoGame/MonoGame/issues/8124), however in the meantime, you can use the following workaround that has been provided by community members. 1. Download and install the x64 version of [.NET 6](https://dotnet.microsoft.com/en-us/download/dotnet/6.0). This will place an x64 version of .NET 6 in a `/usr/local/share/dotnet/x64` directory. NOTE: It MUST be the x64 version in order for this to work. This will allow the x64 native libraries that the MonoGame Content Pipeline uses to function on the Apple Silicon device. @@ -246,15 +257,15 @@ Currently it also needs to be .NET 6 for the 3.8.1 Release of MonoGame. 2. Open your .csproj and add the following lines to the first `` section. -```xml -/usr/local/share/dotnet/x64/dotnet -``` + ```xml + /usr/local/share/dotnet/x64/dotnet + ``` 3. (Alternative) The directory above is not in the path. But we do not want the system to be confused on which .NET is should be using. So rather thatn putting the x64 verison in the path we should instead create a symlink named `dotnet64`. -```sh -sudo ln -s /usr/local/share/dotnet/x64/dotnet /usr/local/share/dotnet/dotnet64 -``` + ```sh + sudo ln -s /usr/local/share/dotnet/x64/dotnet /usr/local/share/dotnet/dotnet64 + ``` We can then use this value as the value for `DotnetCommand` @@ -263,4 +274,5 @@ We can then use this value as the value for `DotnetCommand` ``` ## Conclusion + By following this guide, you have successfully set up your development environment for game development with MonoGame using Visual Studio Code. You've installed the .NET SDK, added MonoGame project templates, and configured Visual Studio Code with the necessary C# extensions. Now, you're ready to start creating your games! [Continue to the next section to create your first project and begin development](2_creating_a_new_project_netcore.md). diff --git a/articles/getting_started/1_setting_up_your_development_environment_windows.md b/articles/getting_started/1_setting_up_your_development_environment_windows.md index a8841db..ae83b91 100644 --- a/articles/getting_started/1_setting_up_your_development_environment_windows.md +++ b/articles/getting_started/1_setting_up_your_development_environment_windows.md @@ -1,12 +1,8 @@ --- title: Setting up your development environment for Windows -description: A step-by-step guide for setting up your development environment on Windows. +description: This section provides a step-by-step guide for setting up your development environment on Windows. --- -# Setting up your development environment for Windows - -This section provides a step-by-step guide for setting up your development environment on Windows. - MonoGame can work with most .NET compatible tools, but we recommend [Visual Studio 2022](https://visualstudio.microsoft.com/vs/) Alternatively, you can use [JetBrains Rider](https://www.jetbrains.com/rider/) or [Visual Studio Code](https://code.visualstudio.com/). @@ -37,21 +33,21 @@ To create new MonoGame projects from within Visual Studio 2022, you will need to 1. Launch Visual Studio 2022 2. Select **Continue without code**. This will launch Visual Studio without any project or solution opened. -![Visual Studio Launcher Continue Without Code](images/1_continue_without_code.png) + ![Visual Studio Launcher Continue Without Code](images/1_continue_without_code.png) 3. Click "*Extensions -> Manage Extensions* in the Visual Studio 2022 menu bar. This will open the Manage Extensions dialog window. -![Extensions -> Manage Extensions Menu Selection](images/1_visual_studio_extension_menu.png) + ![Extensions -> Manage Extensions Menu Selection](images/1_visual_studio_extension_menu.png) 4. Use the search box in the top-right corner of the Manage Extensions dialog window to search for **MonoGame**, then click the **MonoGame Framework C# project templates** extension as shown below and download it to install it. -![Visual Studio Extension Manager](images/1_visual_studio_extension_manager.png) + ![Visual Studio Extension Manager](images/1_visual_studio_extension_manager.png) 5. After it is downloaded, an alert will appear at the bottom of the Manage Extensions window that states "Your changes will be scheduled. The modifications will begin when all Microsoft Visual Studio windows are closed." Click the **Close** button, then close Visual Studio 2022. 6. After closing Visual Studio 2022, a VSIX Installer window will open confirming that you want to install the **MonoGame Framework C# project templates** extension. Click the **Modify** button to accept the install. -![VSIX Installer Window](images/1_vsix_installer_window.png) + ![VSIX Installer Window](images/1_vsix_installer_window.png) You now have the MonoGame templates installed and are ready to create new projects. @@ -59,9 +55,9 @@ You now have the MonoGame templates installed and are ready to create new projec ## [Alternative] Install the .NET 6 SDK (compatible with JetBrains Rider and Visual Studio Code) -If you prefer to use JetBrains Rider or Visual Studio Code, and after installing either of them, you will also need to [install the .NET 6 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/6.0). +If you prefer to use JetBrains Rider or Visual Studio Code, and after installing either of them, you will also need to [install the .NET 8 SDK](https://dotnet.microsoft.com/en-us/download/dotnet/8.0). -Once the .NET 6 SDK is installed, you can open a Command Prompt and install the MonoGame templates by typing the following command: +Once the .NET 8 SDK is installed, you can open a Command Prompt and install the MonoGame templates by typing the following command: ```sh dotnet new --install MonoGame.Templates.CSharp diff --git a/articles/getting_started/2_creating_a_new_project_netcore.md b/articles/getting_started/2_creating_a_new_project_netcore.md index 48e1973..c0464e1 100644 --- a/articles/getting_started/2_creating_a_new_project_netcore.md +++ b/articles/getting_started/2_creating_a_new_project_netcore.md @@ -1,14 +1,14 @@ --- -title: Creating a new project +title: .NET CLI (JetBrains Rider or Visual Studio Code) description: A step-by-step guide for creating a new project using JetBrains Rider or Visual Studio Code. --- -# .NET CLI (JetBrains Rider or Visual Studio Code) - This guide will walk you through building a starter game with MonoGame using only the command line/terminal on your operating system and a lightweight coding tool of your choice (such as [Visual Studio Code](https://code.visualstudio.com/) or [JetBrains Rider](https://www.jetbrains.com/rider/)). -> It is assumed that you have already properly installed the .NET 6 SDK and MonoGame. +> [!NOTE] +> It is assumed that you have already properly installed the .NET 8 SDK and MonoGame. +> [!IMPORTANT] > Be aware that for iOS/iPadOS and Android, development might be limited when using the .NET CLI. Many of the development features for those targets are exclusive to Visual Studio 2022. ## Create a MonoGame Project @@ -23,13 +23,13 @@ You can now create new MonoGame projects. To do that: For example: -``` +```cli dotnet new mgdesktopgl -o MyGame ``` > To know which platform identifier (short name) to use for your project, please refer to [Target Platforms](./platforms.md), or type the following command into the command prompt to list the installed templates and their corresponding short names: -> -> ``` +> +> ```cli > dotnet new -l > ``` diff --git a/articles/getting_started/2_creating_a_new_project_vs.md b/articles/getting_started/2_creating_a_new_project_vs.md index 6ff0cd8..85160a3 100644 --- a/articles/getting_started/2_creating_a_new_project_vs.md +++ b/articles/getting_started/2_creating_a_new_project_vs.md @@ -1,12 +1,11 @@ --- -title: Creating a new project +title: Creating a Project with Visual Studio 2022 description: A step-by-step guide for creating a new project using Visual Studio --- -# Creating a Project with Visual Studio 2022 - This guide will walk you through building a starter game with MonoGame using Windows and Visual Studio 2022. +> [!NOTE] > It is assumed that you have already properly installed Visual Studio 2022 and MonoGame. Start Visual Studio 2022 and select **New Project...** in the upper left corner. diff --git a/articles/getting_started/3_understanding_the_code.md b/articles/getting_started/3_understanding_the_code.md index f100096..2ba8750 100644 --- a/articles/getting_started/3_understanding_the_code.md +++ b/articles/getting_started/3_understanding_the_code.md @@ -1,12 +1,9 @@ --- title: Understanding the Code -description: A look at the code that is generated after creating a new project. +description: This tutorial will go over the code that is generated when you start a blank project. --- -# Understanding the Code - -This tutorial will go over the code that is generated when you start a blank project. - +> [!NOTE] > For help with creating a project, please look at the Creating a New Project section of the [Getting Started guide](index.md). Within the **Game.cs** class file, which is the core of any MonoGame project, you will find several critical sections necessary for your game to run: diff --git a/articles/getting_started/4_adding_content.md b/articles/getting_started/4_adding_content.md index f85a30b..a8ae205 100644 --- a/articles/getting_started/4_adding_content.md +++ b/articles/getting_started/4_adding_content.md @@ -1,12 +1,9 @@ --- title: Adding Content -description: Learn how to add content such as images or sounds to your game. +description: This tutorial will go over adding content such as images or sounds to your game. --- -# Adding Content - -This tutorial will go over adding content such as images or sounds to your game. - +> [!NOTE] > For help with creating a project, please look at the [Creating a New Project](index.md) section of the Getting Started guide. ## MonoGame Content Builder Tool (MGCB Editor) diff --git a/articles/getting_started/5_adding_basic_code.md b/articles/getting_started/5_adding_basic_code.md index 36550b9..d035913 100644 --- a/articles/getting_started/5_adding_basic_code.md +++ b/articles/getting_started/5_adding_basic_code.md @@ -1,11 +1,10 @@ --- title: Adding Basic Code -description: Learn how to add basic logic to your game. +description: This tutorial will go over adding basic logic to your game --- -# Adding Basic Code - -This tutorial will go over adding basic logic to your game, continuing from where [Adding Content](4_adding_content.md) left off. +> [!NOTE] +> this tutorial continues from where [4. Adding Content](4_adding_content.md) left off. --- @@ -133,14 +132,14 @@ Find the **Update** method in the Game1.cs class file and add: if(Joystick.LastConnectedIndex == 0) { JoystickState jstate = Joystick.GetState(PlayerIndex.One); - + float updatedBallSpeed = ballSpeed * (float)gameTime.ElapsedGameTime.TotalSeconds; - + if (jstate.Axes[1] < 0) { ballPosition.Y -= updatedBallSpeed; } - else if (jstate.Axes[1] > 0) + else if (jstate.Axes[1] > 0) { ballPosition.Y += updatedBallSpeed; } diff --git a/articles/getting_started/index.md b/articles/getting_started/index.md index 3341927..e735023 100644 --- a/articles/getting_started/index.md +++ b/articles/getting_started/index.md @@ -1,12 +1,8 @@ --- title: Getting Started -description: Get started creating games with MonoGame. +description: This section walks you through the basics of MonoGame, and helps you to create your first game. --- -# Getting Started - -This section walks you through the basics of MonoGame, and helps you to create your first game. - First, select the operating system and toolset you will be working with to create your first MonoGame project, then continue reading to understand the basic layout of a MonoGame project. By the end of this tutorial set, you will have a working project to build for your target platform and will be ready to tackle your next steps. diff --git a/articles/getting_started/packaging_games.md b/articles/getting_started/packaging_games.md index a832f00..26763ce 100644 --- a/articles/getting_started/packaging_games.md +++ b/articles/getting_started/packaging_games.md @@ -3,10 +3,6 @@ title: Package games for distribution description: How to package your game for distribution. --- -# Package games for distribution - -Once your game is ready to be published, it is recommended that you package it properly for consumption by players. - ## Desktop games To publish desktop games, it is recommended that you build your project as a [self-contained](https://docs.microsoft.com/en-us/dotnet/core/deploying/#publish-self-contained) .NET application. As such, your game will require absolutely no external dependencies and should run out-of-the-box as-is. @@ -35,14 +31,14 @@ We recommend using the .tar.gz archiving format to preserve the execution permis From the .NET CLI: -``` +```cli dotnet publish -c Release -r osx-x64 /p:PublishReadyToRun=false /p:TieredCompilation=false --self-contained dotnet publish -c Release -r osx-arm64 /p:PublishReadyToRun=false /p:TieredCompilation=false --self-contained ``` We recommend that you distribute your game as an [application bundle](https://developer.apple.com/library/archive/documentation/CoreFoundation/Conceptual/CFBundles/BundleTypes/BundleTypes.html). Application bundles are directories with the following file structure: -``` +```text YourGame.app                    (this is your root folder)     - Contents         - Resources @@ -56,6 +52,7 @@ YourGame.app                    (this is your root folder) ``` The contents of the entry point script: + ```sh #!/bin/bash @@ -67,7 +64,7 @@ else fi ``` -The Info.plist file is a standard macOS file containing metadata about your game. Here's an example file with required and recommended values set: +The `Info.plist` file is a standard macOS file containing metadata about your game. Here is an example file with required and recommended values set: ```xml diff --git a/articles/getting_started/platforms.md b/articles/getting_started/platforms.md index 30a566b..0d8bf60 100644 --- a/articles/getting_started/platforms.md +++ b/articles/getting_started/platforms.md @@ -3,16 +3,14 @@ title: Supported Platforms description: Platforms that MonoGame supports building games for. --- - -# Supported Platforms - MonoGame supports building games for the following **systems**: | **Desktop PCs** | **Mobiles** | **Gaming consoles*** | | --------------------------- | -------------------------- | ------------------------------------------------------------------------------ | | Windows
macOS
Linux | iOS
iPadOS
Android | Xbox
PlayStation 4
PlayStation 5
Nintendo Switch
Google Stadia | -**Gaming consoles are restricted to registered developers and are not publicly available nor publicly documented. To get access to those platforms, please contact your console account manager(s). MonoGame documentation for closed platforms is available in their respective repositories.* +> [!IMPORTANT] +> **Gaming consoles are restricted to registered developers and are not publicly available nor publicly documented. To get access to those platforms, please contact your console account manager(s). MonoGame documentation for closed platforms is available in their respective repositories.* ## Understanding MonoGame's platform types @@ -26,7 +24,6 @@ Below is a list of public platforms with their corresponding NuGet package, the - [WindowsDX](#windowsdx) - [DesktopGL](#desktopgl) -- [Windows Universal](#windowsuniversal) - [Android](#android) - [iOS](#ios) @@ -68,28 +65,6 @@ You can target Windows 8.1 (and up), macOS Catalina 10.15 (and up), and Linux wi DesktopGL currently does not have a `VideoPlayer` implementation. -### WindowsUniversal - -| **Supported Systems** | **NuGet Package** | **Template ID** | -| ------------------------------------ | ----------------------------------- | --------------------------------------------------- | -| Windows 10, Xbox (UWP-only, not XDK) | MonoGame.Framework.WindowsUniversal | mguwpcore (core app, no xaml), mguwpxaml (xaml app) | - -The WindowsUniversal platform runs on [Universal Windows Platform (UWP)](https://docs.microsoft.com/en-us/windows/uwp/get-started/universal-application-platform-guide). - -WindowsUniversal uses **DirectX** for graphics, and XAudio for audio just like the WindowsDX platform. - -UWP comes in two flavors, each with its own project template: - -- **XAML app template**: an app in which your game will be hosted within an XAML page. This can be useful if you wish to offer a more complex UWP experience with multiple pages or XAML controls. - -- **Core app template**: a raw app without any XAML, more straightforward if you don't need XAML controls. - -This platform is meant to publish games on the **Windows Store**, for both **Windows** and **Xbox** (through the [Xbox Live Creators Program](https://www.xbox.com/en-US/developers/creators-program)). - -Note that UWP games running on Xbox get [restricted access](https://docs.microsoft.com/en-us/windows/uwp/xbox-apps/system-resource-allocation) to the console capabilities. To unlock those restrictions, MonoGame has a dedicated Xbox platform for registered [ID@Xbox](https://www.xbox.com/en-US/Developers/id) developers targeting the XDK (this platform is private and requires you to contact your ID@Xbox manager). - -Building for UWP requires the Windows SDK version 19041 or better to be installed. - ### Android | **Supported Systems** | **NuGet Package** | **Template ID** | @@ -135,5 +110,3 @@ A project template to create a [shared project](https://docs.microsoft.com/en-us **Template ID**: mgpipeline A project template for writing custom logic for handling content and building it into XNB files. - -# diff --git a/articles/getting_started/preparing_for_consoles.md b/articles/getting_started/preparing_for_consoles.md index 36e2fd6..fc7f328 100644 --- a/articles/getting_started/preparing_for_consoles.md +++ b/articles/getting_started/preparing_for_consoles.md @@ -1,12 +1,8 @@ --- title: Preparing for consoles -description: How to get your game ready to run on consoles. +description: If you would like to port your game to consoles, there are some best practices to follow if you want to avoid running into issues while porting. --- -# Preparing for consoles - -If you would like to port your game to consoles, there are some best practices to follow if you want to avoid running into issues while porting. - MonoGame for gaming consoles uses a dedicated .NET runtime that is not maintained by Microsoft. Therefore, a 100% accuracy and reliability is not guaranteed. Moreover, the console runtime makes use of `ahead-of-time` native compilation (AOT), which means that some .NET features will not, and cannot work on consoles. This article explains the most common pitfalls and suggested guidelines to optimize your chances of having a smoother porting experience. @@ -27,7 +23,7 @@ To publish with AOT: - Add `true` to your `.csproj`. - Then run `dotnet publish` from the command-line/terminal. -This will nativily compile your game in a fashion similar to consoles. The output executable will be in your output folder, within a sub-folder nammed `publish`. +This will natively compile your game in a fashion similar to consoles. The output executable will be in your output folder, within a sub-folder named `publish`. From there, you can try running this executable. If it does not start or crashes later on, you likely are using reflection or another unsupported feature in a AOT runtime. @@ -41,7 +37,7 @@ It should show you on which C# lines it crashed. It is important to note that you should test every aspect of your game, and not just if it starts. Run through all the menus/screens, scene transitions and gameplay. -Another way to make sure that everything is safe is to enable `true` in your `.csproj`, and then **rebuild** (not just build) your game and check the build output for AOT warnings. Those warnings will tell you which parts of your code might trigger crashes or unexecpted results when running on AOT compilation. You should seek to resolve all of them. +Another way to make sure that everything is safe is to enable `true` in your `.csproj`, and then **rebuild** (not just build) your game and check the build output for AOT warnings. Those warnings will tell you which parts of your code might trigger crashes or unexpected results when running on AOT compilation. You should seek to resolve all of them. ## No runtime compilation / IL emit @@ -61,7 +57,7 @@ It is advised to choose very carefully the libraries that you are using when por The best way to make sure if they will work, is to search if they are **"AOT-compatible"**, or try to compile with the `true` setting in your `.csproj` and check if there are any warnings related to those libraries. -For example, here are some parsing libraries known for their compliance with AOT compilation and good handling of memrory: +For example, here are some parsing libraries known for their compliance with AOT compilation and good handling of memory: - [TurboXML](https://github.com/xoofx/TurboXml) - [TinyJSON](https://github.com/zanders3/json) @@ -88,7 +84,7 @@ Even though your game has good performance on PC and does not show stutters, you The garbage collector is slower on consoles and if your game generates a lot of garbage memory, there will be visible stutters. -To verify that your game is not too garbage-prone, you can run Visual Studio's Perfomance Profiler (`Debug/Performance Profiler...`) and check the **".NET Object Allocation Tracking"** tool. +To verify that your game is not too garbage-prone, you can run Visual Studio's Performance Profiler (`Debug/Performance Profiler...`) and check the **".NET Object Allocation Tracking"** tool. From there, you can check which parts of your code generate garbage and you can pinpoint where to optimize. @@ -103,7 +99,7 @@ In order to avoid garbage, here are some best practices: ## Do not rely on system calls -If your game calls directly to system functions, like kernel, win32 or unix commands, you might want to get rid of them. +If your game calls directly to system functions, like kernel, win32 or Unix commands, you might want to get rid of them. ## Consider I/O to be asynchronous @@ -116,4 +112,3 @@ If you consider all your I/O and system operations as asynchronous, you will lik ## Suggestions If you have other tips or suggestions when building for consoles, then let the MonoGame team know by raising an issue and we will improve this article even further over time. - diff --git a/articles/getting_to_know/howto/audio/HowTo_ChangePitchAndVolume.md b/articles/getting_to_know/howto/audio/HowTo_ChangePitchAndVolume.md new file mode 100644 index 0000000..f70be56 --- /dev/null +++ b/articles/getting_to_know/howto/audio/HowTo_ChangePitchAndVolume.md @@ -0,0 +1,140 @@ +--- +title: How to adjust Pitch and Volume +description: Demonstrates how to manipulate the pitch and volume of sound effects as they play. +requireMSLicense: true +--- + +## Overview + +In this example, you will walk through the basics of dynamic sounds, using the more advanced [SoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance) cl;ass over the basic [SoundEffect.Play](xref:Microsoft.Xna.Framework.Audio.SoundEffect.Play) method used in [Playing a Sound](HowTo_PlayASound.md). + +## Using SoundEffectInstance + +The **[SoundEffect.Play](xref:Microsoft.Xna.Framework.Audio.SoundEffect.Play)** method allows you to specify the pitch and volume of a sound to play. However, after you call **[Play](xref:Microsoft.Xna.Framework.Audio.SoundEffect.Play)** you cannot modify the sound. + +Using **[SoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance)** for a given **[SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect)**, allows you to change the **pitch** and **volume** of a sound at any time during playback. + +> [!NOTE] +> The pitch of a sound changes the frequency of the sound, which in turn changes the speed of the sound. The volume of a sound changes the amplitude of the sound, which in turn changes the loudness of the sound. + +## Requirements + +This sample uses a sound file named [tx0_fire1.wav](files/tx0_fire1.wav), which you can download from [this link here](files/tx0_fire1.wav). (save-as) +But you can use your own if you wish. + +## Change Pitch and Volume of Sound + +1. Declare a **[SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect)** and a [Stream](http://msdn.microsoft.com/en-us/library/system.io.stream.aspx) file by using the method shown in [Playing a Sound](HowTo_PlayASound.md). In addition to the method described in [Playing a Sound](HowTo_PlayASound.md), declare a **[SoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance)** and a **Sound Effect** field member. We also create two float fields for **pitch** and **volume** to store the pitch and volume of the sound effect and assign initial values to them. + + ```csharp + // place these usings at the top of the file + using System.IO; + using Microsoft.Xna.Framework; + using Microsoft.Xna.Framework.Audio; + using Microsoft.Xna.Framework.Graphics; + using Microsoft.Xna.Framework.Input; + + // place these fields at the top of the class + private SoundEffect soundEffect; + private SoundEffectInstance soundEffectInstance; + private float pitch = 0.75f; + private float volume = 0.5f; + ``` + + > [!NOTE] + > Usings are declared at the top of the file to ensure that the necessary namespaces are available to the class. The fields are declared at the top of the class to ensure that they are accessible to all methods in the class. + +2. In the [Game.LoadContent](xref:Microsoft.Xna.Framework.Game.LoadContent) method, set the **SoundEffectInstance** object to the return value of [SoundEffect.CreateInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffect.CreateInstance). + +3. In the **[Game.LoadContent](xref:Microsoft.Xna.Framework.Game.LoadContent)** method, set the **SoundEffectInstance** object to the return value of **[SoundEffect.CreateInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffect.CreateInstance)**. We also optionally define a variable **soundFile** to store the location of the sound file being used with the **[TitleContainer.OpenStream](xref:Microsoft.Xna.Framework.TitleContainer#Microsoft_Xna_Framework_TitleContainer_OpenStream_System_String_)** method, which is accessed with the **using** keyword, and include a field member variable called **soundEffect**, to hold the stream. + + ```csharp + using Stream soundfile = TitleContainer.OpenStream(@"Content\tx0_fire1.wav"); + soundEffect = SoundEffect.FromStream(soundfile); + soundEffectInstance = soundEffect.CreateInstance(); + ``` + + >[IMPORTANT] + > As we need the raw wav file and not a compressed version to access its stream, make sure to set the 'Build Action' in the MGCB tool to 'COPY' + > ![Copy build action](./images/set_wav_to_copy.png) + +4. Adjust the sound to the desired level using the [SoundEffectInstance.Pitch](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance.Pitch) and [SoundEffectInstance.Volume](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance.Volume) properties. + + ```csharp + // Pitch takes values from -1 to 1 + soundEffectInstance.Pitch = pitch; + + // Volume only takes values from 0 to 1 + soundEffectInstance.Volume = volume; + ``` + +5. Play the sound using [SoundEffectInstance.Stop](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance.Play). + + ```csharp + // Play Sound + soundEffectInstance.Play(); + ``` + + > [!NOTE] + > An instance will play once, to loop the sound, you can use the **[SoundEffectInstance.IsLooped](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance.IsLooped)** property to set the sound to loop. Also note that the sound will not repeat until the sound has finished playing. You can utilise the **[SoundEffectInstance.State](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance.State)** property to check if the sound is playing, paused or stopped. Use the **[SoundEffectInstance.Stop](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance.Stop)** method to stop the sound. + +## An Extended Example + + 1. Below the **[Game.Draw](xref:Microsoft.Xna.Framework.Game#Microsoft_Xna_Framework_Game_Draw_Microsoft_Xna_Framework_GameTime_)** method, create a new method called **IsKeyPressed**, which will check if a specified key is pressed and return a boolean value of true if it has been pressed. + + ```csharp + private bool IsKeyPressed(Keys key) + { + return Keyboard.GetState().IsKeyDown(key); + } + ``` + + 2. In the **[Game.Update](xref:Microsoft.Xna.Framework.Game#Microsoft_Xna_Framework_Game_Update_Microsoft_Xna_Framework_GameTime_)** method, we will add a check to see if the **Space** key is pressed and adjust the pitch and volume of the sound effect accordingly. The pitch and volume values are adjusted by +0.1f each time the **Space key** is pressed. The pitch values are clamped to a minimum value of -1.0f and a maximum value of 1.0f, and the volume values are then clamped to a minimum value of 0f and a maximum value of 1.0f. This is done to ensure that the pitch and volume values are within valid ranges. + + ```csharp + // Check if the SpaceKey is pressed and play the instance + if (IsKeyPressed(Keys.Space)) + { + pitch += 0.1f; + volume += 0.1f; + pitch = MathHelper.Clamp(pitch, -1.0f, 1.0f); + volume = MathHelper.Clamp(volume, 0f, 1.0f); + soundEffectInstance.Pitch = pitch; + soundEffectInstance.Volume = volume; + soundEffectInstance.Play(); + } + ``` + + > [!NOTE] + > The **MathHelper.Clamp** method is used to ensure that the pitch and volume values are within the valid range. The pitch value is clamped between -1 and 1, while the volume value is clamped between 0 and 1. + + > [!IMPORTANT] + > The check for the keypress does not prevent the call to the method repeating so any value entered may peak the value in a single key press. To prevent this, you can add a delay to the key press check, or use a boolean value to check if the key has been pressed and released. + +## See Also + +* [Playing a Sound](HowTo_PlayASound.md) + + Demonstrates how to play a simple sound by using [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect). + +* [Looping a Sound](HowTo_LoopASound.md) + + Demonstrates how to loop a sound. + +* [Stream data from a Wav](HowTo_StreamDataFromWav.md) + + Demonstrates how to load a wav file through a file stream. + +* [Creating and Playing Sounds](../../whatis/WhatIs_Audio.md) + + Provides overviews about audio technology, and presents predefined scenarios to demonstrate how to use audio. + +## Reference + +* [SoundEffect Class](xref:Microsoft.Xna.Framework.Audio.SoundEffect) + + Provides a loaded sound resource. + +* [SoundEffectInstance Class](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance) + + Provides a single playing, paused, or stopped instance of a [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect) sound. diff --git a/articles/getting_to_know/howto/audio/HowTo_LoopASound.md b/articles/getting_to_know/howto/audio/HowTo_LoopASound.md new file mode 100644 index 0000000..29d0aa9 --- /dev/null +++ b/articles/getting_to_know/howto/audio/HowTo_LoopASound.md @@ -0,0 +1,61 @@ +--- +title: How to loop Sounds +description: This section demonstrates how to loop a sound. +requireMSLicense: true +--- + +## Overview + +In this example we will go over the basics of how to make sound effects loop rather than the default play once. + +## Simple Sound Looping + +Not much extra code is needed to continuously loop a sound file in your game. Since the [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect) class does not provide looping support, you will need to allocate a [SoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance) object. The following procedure builds on the sample code provided in the [Playing a Sound](HowTo_PlayASound.md) topic. + +### To loop a sound + +1. Follow the instructions show in [Playing a Sound](HowTo_PlayASound.md) topic. + +2. Declare a [SoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance) object to hold an instance of the sound file. + + ```csharp + private SoundEffectInstance soundEffectInstance; + ``` + +3. To be able to loop a sound you will need to declare a [SoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance) object, and set it to the return value of [SoundEffect.CreateInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffect.CreateInstance). add this after loading the sound file in the `LoadContent` method. + + ```csharp + soundEffectInstance = soundEffect.CreateInstance(); + ``` + +4. Set [SoundEffectInstance.IsLooped](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance#Microsoft_Xna_Framework_Audio_SoundEffectInstance_IsLooped) to **true** which will cause the sound effect to play forever or until you stop it or close the game. + + ```csharp + soundEffectInstance.IsLooped = true; + ``` + +5. Play the sound instance (removing the old soundEffect.Play() call). + + ```csharp + // Play the sound effect instance + soundEffectInstance.Play(); + ``` + +> [!NOTE] +> Obviously you would not normally call `play` in the `LoadContent` method, we just use here as an example. + +## See Also + +* [Playing a Sound](HowTo_PlayASound.md) + + Demonstrates how to play a simple sound by using [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect). + +## Reference + +* [SoundEffect Class](xref:Microsoft.Xna.Framework.Audio.SoundEffect) + + Provides a loaded sound resource. + +* [SoundEffectInstance Class](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance) + + Provides a single playing, paused, or stopped instance of a [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect) sound. diff --git a/articles/getting_to_know/howto/audio/HowTo_Microphone.md b/articles/getting_to_know/howto/audio/HowTo_Microphone.md new file mode 100644 index 0000000..04d9172 --- /dev/null +++ b/articles/getting_to_know/howto/audio/HowTo_Microphone.md @@ -0,0 +1,44 @@ +--- +title: How to work with Microphones +description: This topic provides basic information about microphone usage in games. +requireMSLicense: true +--- + +## Supported Microphone Devices + +The Microphone API is only implemented on OpenAL based platforms at this time. This includes iOS/Android and Desktop projects using DesktopGL. + +## Capabilities of the Microphone API + +The MonoGame Microphone API has the following functionality: + +* Captures the audio stream from a microphone. +* Submits and controls a stream of audio buffers for playback using the [DynamicSoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) object. +* Plays back audio. + +## Microphone API Process Workflow + +The Microphone API behaves like a simple audio recorder with a configurable capture buffer. It has been designed with the following development process workflow: + +1. Select the microphone connected to the device. +2. Configure the microphone's capture buffer size. +3. Control the recording using standard transport controls (Start and Stop). +4. Retrieve the captured audio using the [GetData](xref:Microsoft.Xna.Framework.Audio.Microphone) method. + +Also, you can use the **BufferReady** event handler of the [Microphone](xref:Microsoft.Xna.Framework.Audio.Microphone) class if you want to be notified when the audio capture buffer is ready to be processed. + +## See Also + +* [Creating and Playing Sounds](../../whatis/WhatIs_Audio.md) + + Provides overviews about audio technology, and presents predefined scenarios to demonstrate how to use audio. + +## Reference + +* [DynamicSoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) + + Provides properties, methods, and events for play back of the audio buffer. + +* [Microphone](xref:Microsoft.Xna.Framework.Audio.Microphone) + + Provides properties, methods, and fields and events for capturing audio data with microphones. diff --git a/articles/getting_to_know/howto/audio/HowTo_PlayASong.md b/articles/getting_to_know/howto/audio/HowTo_PlayASong.md new file mode 100644 index 0000000..e959612 --- /dev/null +++ b/articles/getting_to_know/howto/audio/HowTo_PlayASong.md @@ -0,0 +1,72 @@ +--- +title: How to play a Song / music +description: Demonstrates how to play a song from a media library. +requireMSLicense: true +--- + +## Overview + +In this example we will demonstrate the ability to load a media file such as an MP3, OGG or WMA file. + +The [MediaPlayer](xref:Microsoft.Xna.Framework.Media.MediaPlayer) class manages long running music or media. Will start audio playback when using the [Play](xref:Microsoft.Xna.Framework.Media.MediaPlayer#Microsoft_Xna_Framework_Media_MediaPlayer_Play_Microsoft_Xna_Framework_Media_Song_) method. If the user currently is playing a different song, the [Stop](xref:Microsoft.Xna.Framework.Media.MediaPlayer#Microsoft_Xna_Framework_Media_MediaPlayer_Stop) method can be used to stop the current song. + +> [!NOTE] +> Only one song can be played at any time using the MediaPlayer. + +## Requirements + +This sample uses a mp3 file named [rock_loop_stereo.mp3](https://github.com/MonoGame/MonoGame/raw/develop/Tests/Assets/Audio/rock_loop_stereo.mp3), which you can download from [this link here](https://github.com/MonoGame/MonoGame/raw/develop/Tests/Assets/Audio/rock_loop_stereo.mp3). (save-as) +But you can use your own if you wish. + +## To add a music file to your project + +1. Open your MonoGame game in your editor of choice. + +2. Open the `Content.mgcb` file by either double-clicking on it, or right-clicking and selecting `Open in MGCB editor". (depending on your editor) + +3. Click **Add** in the menu bar, and then click **Existing Item**. (alternatively, use the icon for the same task in the editor) + +4. Navigate to the music (mp3) file you want to add, and then select it. + +> The selected audio file is inserted into your project. By default, it is processed by the Content Pipeline as a [Song](xref:Microsoft.Xna.Framework.Media.Song) + +## To play a song + +The following demonstrates how to play a song from the media file in the content project. + +1. Declare a [Song](xref:Microsoft.Xna.Framework.Media.Song) parameter as a reference for the media file to load. + + ```csharp + private Song song; + ``` + +2. Load the media file using [Content.Load](xref:Microsoft.Xna.Framework.Content.ContentManager) in the 'LoadContent' method. + + ```csharp + song = Content.Load("rock_loop_stereo"); + ``` + +3. Check if the [MediaPlayer](xref:Microsoft.Xna.Framework.Media.MediaPlayer) is currently playing (or has a paused track), and then call "Stop" if needed. As soon as the [MediaPlayer](xref:Microsoft.Xna.Framework.Media.MediaPlayer) is ready, play the music. + + ```csharp + // check the current state of the MediaPlayer. + if(MediaPlayer.State != MediaState.Stopped) + { + MediaPlayer.Stop(); // stop current audio playback if playing or paused. + } + + // Play the selected song reference. + MediaPlayer.Play(song); + ``` + +## See Also + +* [Media Overview](../../whatis/WhatIs_Audio.md) + + Provides a high-level overview about the capabilities—such as playing music and video and accessing pictures—of the Media API in MonoGame. + +## Reference + +* [MediaPlayer Class](xref:Microsoft.Xna.Framework.Media.MediaPlayer) + + Provides methods and properties to play, pause, resume, and stop songs. **MediaPlayer** also exposes shuffle, repeat, volume, play position, and visualization capabilities. diff --git a/articles/getting_to_know/howto/audio/HowTo_PlayASound.md b/articles/getting_to_know/howto/audio/HowTo_PlayASound.md new file mode 100644 index 0000000..963605a --- /dev/null +++ b/articles/getting_to_know/howto/audio/HowTo_PlayASound.md @@ -0,0 +1,67 @@ +--- +title: How to play a Sound(effect) +description: This topic demonstrates how to play a simple sound by using SoundEffect. +requireMSLicense: true +--- + +## Overview + +In this example we will take our first steps into audio nirvana and play a simple one-time-only [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect). + +## Requirements + +This sample uses a sound file named [tx0_fire1.wav](./files/tx0_fire1.wav), which you can download from [this link here](./files/tx0_fire1.wav). (save-as) +But you can use your own if you wish. + +## To add a sound file to your project + +1. Open your MonoGame game in your editor of choice. + +2. Open the `Content.mgcb` file by either double-clicking on it, or right-clicking and selecting `Open in MGCB editor". (depending on your editor) + +3. Click **Add** in the menu bar, and then click **Existing Item**. (alternatively, use the icon for the same task in the editor) + +4. Navigate to the sound file you want to add, and then select it. + +> The selected audio file is inserted into your project. By default, it is processed by the Content Pipeline, and built wave files are accessed automatically when the game is built. + +### To play a simple sound + +1. Declare a [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect) object to hold the sound file. + + ```csharp + // Audio objects + SoundEffect soundEffect; + ``` + +2. Load the sound file using [Content.Load](xref:Microsoft.Xna.Framework.Content.ContentManager) in the 'LoadContent' method. + + ```csharp + soundEffect = Content.Load("tx0_fire1"); + ``` + +3. Play the sound. + + ```csharp + // Play the sound + soundEffect.Play(); + ``` + +> [!NOTE] +> Obviously you would not normally call `play` in the `LoadContent` method, we just use here as an example. + +## See Also + +* [Looping a Sound](HowTo_LoopASound.md) + + Demonstrates how to loop a sound. + +## Reference + +* [SoundEffect Class](xref:Microsoft.Xna.Framework.Audio.SoundEffect) + + Provides a loaded sound resource. + +* [SoundEffectInstance Class](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance) + + Provides a single playing, paused, or stopped instance of a [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect) sound. diff --git a/articles/getting_to_know/howto/audio/HowTo_Record_Microphone.md b/articles/getting_to_know/howto/audio/HowTo_Record_Microphone.md new file mode 100644 index 0000000..9aca1fa --- /dev/null +++ b/articles/getting_to_know/howto/audio/HowTo_Record_Microphone.md @@ -0,0 +1,145 @@ +--- +title: How to record Sound with a Microphone +description: This topic demonstrates the basics of recording audio using a microphone. +requireMSLicense: true +--- + +## Overview + +The following procedure shows the bare basics of using the microphone to record audio. In practice, you will want to use UI elements (such as buttons) to start and stop audio recording. + +As handling microphone audio can become quite complex, this tutorial is split into two halves: + +* Part 1 walks through the required code in order to record audio from the default microphone and then stop recording. +* Part 2 is a more in-depth sample which also processes the recorded audio and plays it back to you. + +## Part 1, Guide to recording audio from the microphone + +1. Get the device's default microphone by using [Microphone.Default](xref:Microsoft.Xna.Framework.Audio.Microphone). + + ```csharp + Microphone activeMicrophone; + + activeMicrophone = Microphone.Default; + if (activeMicrophone != null) + { + + } + else + { + // No microphone is attached to the device + } + ``` + +2. Set the size (duration) of the Microphone buffer and wire up the event to handle the data as it becomes available. THen declare a buffer array to hold the audio data from these settings. + + ```csharp + // Set the capture buffer size for low latency. + // Microphone will call the game back when it has captured at least that much audio data. + activeMicrophone.BufferDuration = TimeSpan.FromMilliseconds(100); + + // Subscribe to the event that's raised when the capture buffer is filled. + activeMicrophone.BufferReady += BufferReady; + + // We will put the mic samples in this buffer. We only want to allocate it once. + micSamples = new byte[activeMicrophone.GetSampleSizeInBytes(activeMicrophone.BufferDuration)]; + ``` + +3. The `Buffer Ready` handler can then process the prepared microphone data for storage, transmission or playback, getting the sample data from the Microphone and storing it in the prepared buffer array (micSamples). + + ```csharp + /// + /// This is called each time a microphone buffer has been filled. + /// + void BufferReady(object sender, EventArgs e) + { + try + { + // Copy the captured audio data into the pre-allocated array. + int sampleDataSize = activeMicrophone.GetData(micSamples); + } + catch (NoMicrophoneConnectedException) + { + // Microphone was disconnected - let the user know. + } + } + ``` + +4. Begin recording audio, calling method [Microphone.Start](xref:Microsoft.Xna.Framework.Audio.Microphone). + + ```csharp + private void StartRecording() + { + // Can't start a microphone that doesn't exist. + if (activeMicrophone == null) { return; } + + try + { + activeMicrophone.Start(); + } + catch (NoMicrophoneConnectedException) + { + // Microphone was disconnected - let the user know. + } + } + ``` + +5. While the microphone is recording, [Microphone.GetData (Byte\[\], Int32, Int32)](xref:Microsoft.Xna.Framework.Audio.Microphone) is called in the aforementioned `BufferReady` handler as the audio data becomes available. + + ```csharp + int sampleDataSize = activeMicrophone.GetData(micSamples); + ``` + +6. When you are finished recording, set the microphone state to stopped by calling method [Stop](xref:Microsoft.Xna.Framework.Audio.Microphone). + + ```csharp + private void StopRecording() + { + // Can't stop a microphone that doesn't exist. + if (activeMicrophone == null) { return; } + + try + { + // Stop the microphone + activeMicrophone.Stop(); + } + catch (NoMicrophoneConnectedException) + { + UpdateMicrophoneStatus(); + } + } + ``` + +## Part 2, Full example of outputting the microphone to audio + +As promised, the following is a fully working sample that: + +* Starts recording and outputting audio from the active microphone when "space is pressed". +* Stops recording when "P" is pressed. +* Adds an "Extension method" to determine if a Microphone is connected. +* A "PickFirstConnectedMicrophone" method to choose a specific microphone. Can be modified so you can switch mic's +* An "InitializeMicrophone" method to initialize and setup the microphone, updated to work in "Update" so it can continually monitor the Mic connection. + +Enjoy, all code commented where applicable for reference. + +[!code-csharp[](files/microphonesample.cs)] + +## See Also + +* [Working with Microphones](HowTo_Microphone.md) + + Provides basic information about microphone usage in games. + +* [HowTo_StreamDataFromWav](HowTo_StreamDataFromWav.md) + + a sample demonstrating the uses of the [DynamicSoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) + +## Reference + +* [Microphone](xref:Microsoft.Xna.Framework.Audio.Microphone) + + Provides properties, methods, and fields and events for capturing audio data with microphones. + +* [DynamicSoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) + + Provides properties, methods, and events for play back of the audio buffer. diff --git a/articles/getting_to_know/howto/audio/HowTo_StreamDataFromWav.md b/articles/getting_to_know/howto/audio/HowTo_StreamDataFromWav.md new file mode 100644 index 0000000..adc5091 --- /dev/null +++ b/articles/getting_to_know/howto/audio/HowTo_StreamDataFromWav.md @@ -0,0 +1,152 @@ +--- +title: How to stream Data from a WAV File +description: This topic describes how to stream an audio file using DynamicSoundEffectInstance. +requireMSLicense: true +--- + +## Overview + +In this example we will demonstrate the uses of the [DynamicSoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) which is an advanced method for strictly controlling what audio data is going to be played. + +One approach is to tightly control the memory being used for playing audio, rather than loading an entire track into memory, you only need to load a sufficient amount to play audio for the current frame or frames. Very useful when every bit of memory data counts. + +Another approach (Which was used in the [Nokia AlphaLabs Experiment - Vequencer](https://martincaine.com/xna/introducing_vequencer_an_alphalabscc_experiment)) enables you to dynamically compose audio at runtime, especially useful when you want to control pacing and the number of instruments playing. But buyer beware, it can be tricky to get this right. (but awesome when it works) + +## Requirements + +This sample uses a sound file named [rock_loop_mono.wav](https://github.com/MonoGame/MonoGame/raw/develop/Tests/Assets/Audio/rock_loop_mono.wav), which you can download from [this link here](https://github.com/MonoGame/MonoGame/raw/develop/Tests/Assets/Audio/rock_loop_mono.wav). (save-as) +But you can use your own if you wish. + +## Opening a wave file for streaming + +1. Create global variables to hold the [DynamicSoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance), position, count, and data. + + ```csharp + DynamicSoundEffectInstance dynamicSound; + int position; + int count; + byte[] byteArray; + ``` + +2. In the [Game.LoadContent](xref:Microsoft.Xna.Framework.Game.LoadContent) method of your game, open the audio data using [TitleContainer.OpenStream](xref:Microsoft.Xna.Framework.TitleContainer). + + ```csharp + System.IO.Stream waveFileStream = TitleContainer.OpenStream(@"Content\rock_loop_mono.wav"); + ``` + +3. Create a new binary reader to read from the audio stream. + + ```csharp + BinaryReader reader = new BinaryReader(waveFileStream); + ``` + +4. Read the wave file header from the buffer. + + ```csharp + int chunkID = reader.ReadInt32(); + int fileSize = reader.ReadInt32(); + int riffType = reader.ReadInt32(); + int fmtID = reader.ReadInt32(); + int fmtSize = reader.ReadInt32(); + int fmtCode = reader.ReadInt16(); + int channels = reader.ReadInt16(); + int sampleRate = reader.ReadInt32(); + int fmtAvgBPS = reader.ReadInt32(); + int fmtBlockAlign = reader.ReadInt16(); + int bitDepth = reader.ReadInt16(); + + if (fmtSize == 18) + { + // Read any extra values + int fmtExtraSize = reader.ReadInt16(); + reader.ReadBytes(fmtExtraSize); + } + + int dataID = reader.ReadInt32(); + int dataSize = reader.ReadInt32(); + ``` + +5. Store the audio data of the wave file to a byte array. + + ```csharp + byteArray = reader.ReadBytes(dataSize); + ``` + +6. Create the new dynamic sound effect instance using the sample rate and channel information extracted from the sound file. + + ```csharp + dynamicSound = new DynamicSoundEffectInstance(sampleRate, (AudioChannels)channels); + ``` + +7. Store the size of the audio buffer that is needed in the count variable, etting data in 100 ms chunks. + + ```csharp + count = dynamicSound.GetSampleSizeInBytes(TimeSpan.FromMilliseconds(100)); + ``` + +8. Set up the dynamic sound effect's "buffer needed" event handler, so audio data is only read when it needs more data. + + ```csharp + dynamicSound.BufferNeeded += new EventHandler(DynamicSound_BufferNeeded); + ``` + +9. Implement the buffer needed event handler after the `LoadContent` method. + + ```csharp + void DynamicSound_BufferNeeded(object sender, EventArgs e) + { + dynamicSound.SubmitBuffer(byteArray, position, count / 2); + dynamicSound.SubmitBuffer(byteArray, position + count / 2, count / 2); + + position += count; + if (position + count > byteArray.Length) + { + position = 0; + } + } + ``` + +10. Below the **[Game.Draw](xref:Microsoft.Xna.Framework.Game#Microsoft_Xna_Framework_Game_Draw_Microsoft_Xna_Framework_GameTime_)** method, create a new method called **IsKeyPressed**, which will check if a specified key is pressed and return a boolean value of true if it has been pressed. + + ```csharp + private bool IsKeyPressed(Keys key) + { + return Keyboard.GetState().IsKeyDown(key); + } + ``` + +11. Use the controller buttons to play and stop the sound stream in the `Update` method. + + ```csharp + // Pressing the spacebar will start the DynamicSoundEffectInstance playing + if (IsKeyPressed(Keys.Space)) + { + dynamicSound.Play(); + } + + // Pressing "P" will stop the audio playing. + if (IsKeyPressed(Keys.P)) + { + dynamicSound.Pause(); + } + ``` + +## See Also + +* [Playing a Sound](HowTo_PlayASound.md) + + Demonstrates how to play a simple sound by using [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect). + +## Reference + +* [DynamicSoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) + + Provides properties, methods, and events for play back of the audio buffer. + +* [BufferNeeded](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) + + Event that occurs when the number of audio capture buffers awaiting playback is less than or equal to two. + +* [OpenStream](xref:Microsoft.Xna.Framework.TitleContainer) + + Returns a stream to an existing file in the default title storage location. diff --git a/articles/getting_to_know/howto/audio/files/microphonesample.cs b/articles/getting_to_know/howto/audio/files/microphonesample.cs new file mode 100644 index 0000000..20193de --- /dev/null +++ b/articles/getting_to_know/howto/audio/files/microphonesample.cs @@ -0,0 +1,254 @@ +using System; +using Microsoft.Xna.Framework; +using Microsoft.Xna.Framework.Audio; +using Microsoft.Xna.Framework.Graphics; +using Microsoft.Xna.Framework.Input; + +namespace MonoGameMicrophoneExample; + +public class Game1 : Game +{ + private GraphicsDeviceManager graphics; + private SpriteBatch spriteBatch; + SpriteFont font; + // The most recent microphone samples. + byte[] micSamples; + // DynamicSoundEffectInstance is used to playback the captured audio after processing it for echo. + DynamicSoundEffectInstance dynamicSound; + // Microphone used for recording. + Microphone activeMicrophone; + // Used to communicate the microphone status to the user. + string microphoneStatus = string.Empty; + const string instructions = @"Press 'Space' to start and 'P' to stop recording"; + +#region MonoGame Boilerplate + public Game1() + { + graphics = new GraphicsDeviceManager(this); + Content.RootDirectory = "Content"; + IsMouseVisible = true; + } + + protected override void Initialize() + { + // TODO: Add your initialization logic here + + base.Initialize(); + } + + protected override void LoadContent() + { + spriteBatch = new SpriteBatch(GraphicsDevice); + + // Make sure to create a SpriteFont in the Content project and set its build action to "Content". + font = Content.Load("File"); + } + + + protected override void Update(GameTime gameTime) + { + if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) + Exit(); + + // Constantly check for a good microphone to start recording. + InitializeMicrophone(); + + // Check and update microphone status. + UpdateMicrophoneStatus(); + + if (IsKeyPressed(Keys.Space)) + { + StartRecording(); + } + if (IsKeyPressed(Keys.P)) + { + StopRecording(); + } + + base.Update(gameTime); + } + + + protected override void Draw(GameTime gameTime) + { + GraphicsDevice.Clear(Color.CornflowerBlue); + + // TODO: Add your drawing code here + spriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend); + spriteBatch.DrawString(font, instructions, new Vector2(10f, 20f), Color.White); + spriteBatch.DrawString(font, microphoneStatus, new Vector2(10f, 50f), Color.White); + spriteBatch.End(); + base.Draw(gameTime); + } +#endregion MonoGame Boilerplate + +#region Input Handling + private bool IsKeyPressed(Keys key) + { + return Keyboard.GetState().IsKeyDown(key); + } + + private void StartRecording() + { + // Can't start a microphone that doesn't exist. + if (activeMicrophone == null) { return; } + + try + { + activeMicrophone.Start(); + } + catch (NoMicrophoneConnectedException) + { + UpdateMicrophoneStatus(); + } + } + + private void StopRecording() + { + // Can't stop a microphone that doesn't exist. + if (activeMicrophone == null) { return; } + + try + { + // Stop the microphone + activeMicrophone.Stop(); + } + catch (NoMicrophoneConnectedException) + { + UpdateMicrophoneStatus(); + } + } +#endregion Input Handling + +#region Microphone Handling + /// + /// Keep track of the microphone status to communicate to the user. + /// + private void UpdateMicrophoneStatus() + { + // We don't have any microphones connected to the system. + if (activeMicrophone == null) + { + microphoneStatus = "Waiting for microphone connection..."; + } + else + { + try + { + // Update the status - if the microphone gets disconnected this will throw + microphoneStatus = string.Format("{0} is {1}", activeMicrophone.Name, activeMicrophone.State); + } + catch (NoMicrophoneConnectedException) + { + // Microphone got disconnected - Let's ask the user to reconnect it. + microphoneStatus = string.Format("Please reconnect {0}", activeMicrophone.Name); + } + } + } + + /// + /// This is called each time a microphone buffer has been filled. + /// + void BufferReady(object sender, EventArgs e) + { + try + { + // Copy the captured audio data into the pre-allocated array. + int sampleDataSize = activeMicrophone.GetData(micSamples); + + // Process the captured audio for playback + dynamicSound.SubmitBuffer(micSamples, 0, sampleDataSize); + } + catch (NoMicrophoneConnectedException) + { + // Microphone was disconnected - let the user know. + UpdateMicrophoneStatus(); + } + } + + /// + /// Look for a good microphone to start recording. + /// + /// + private Microphone PickFirstConnectedMicrophone() + { + // Let's pick the default microphone if it's ready. + if (Microphone.Default != null && Microphone.Default.IsConnected()) + { + return Microphone.Default; + } + + // Default microphone seems to be disconnected so look for another microphone that we can use. + // And if the default was null then the list will be empty and we'll skip the search. + foreach (Microphone microphone in Microphone.All) + { + if (microphone.IsConnected()) + { + return microphone; + } + } + + // There are no microphones hooked up to the system! + return null; + } + + /// + /// Finds a good microphone to use and sets up everything to start recording and playback. + /// Once a microphone is selected the game uses it throughout its lifetime. + /// If it gets disconnected it will tell the user to reconnect it. + /// + private void InitializeMicrophone() + { + // We already have a microphone, skip out early. + if (activeMicrophone != null) { return; } + + try + { + // Find the first microphone that's ready to rock. + activeMicrophone = PickFirstConnectedMicrophone(); + if (activeMicrophone != null) + { + // Set the capture buffer size for kow latency. + // Microphone will call the game back when it has captured at least that much audio data. + activeMicrophone.BufferDuration = TimeSpan.FromMilliseconds(100); + // Subscribe to the event that's raised when the capture buffer is filled. + activeMicrophone.BufferReady += BufferReady; + // We will put the mic samples in this buffer. We only want to allocate it once. + micSamples = new byte[activeMicrophone.GetSampleSizeInBytes(activeMicrophone.BufferDuration)]; + + // Create a DynamicSoundEffectInstance in the right format to playback the captured audio. + dynamicSound = new DynamicSoundEffectInstance(activeMicrophone.SampleRate, AudioChannels.Mono); + dynamicSound.Play(); + } + } + catch (NoMicrophoneConnectedException) + { + // Uh oh, the microphone was disconnected in the middle of initialization. + // Let's clean up everything so we can look for another microphone again on the next update. + activeMicrophone.BufferReady -= BufferReady; + activeMicrophone = null; + } + } +#endregion Microphone Handling +} + +#region Helper Microphone Extension Method +public static class MicrophoneExtensions +{ + // Provides a simple method to check if a microphone is connected. + // There is no guarantee that the microphone will not get disconnected at any time. + // This method helps in simplifying the microphone enumeration code. + public static bool IsConnected(this Microphone microphone) + { + try + { + MicrophoneState state = microphone.State; + return true; + } + catch (NoMicrophoneConnectedException) + { + return false; + } + } +} +#endregion Helper Microphone Extension Method \ No newline at end of file diff --git a/articles/getting_to_know/howto/audio/files/tx0_fire1.wav b/articles/getting_to_know/howto/audio/files/tx0_fire1.wav new file mode 100644 index 0000000..935e9c5 Binary files /dev/null and b/articles/getting_to_know/howto/audio/files/tx0_fire1.wav differ diff --git a/articles/getting_to_know/howto/audio/images/set_wav_to_copy.png b/articles/getting_to_know/howto/audio/images/set_wav_to_copy.png new file mode 100644 index 0000000..3a42a37 Binary files /dev/null and b/articles/getting_to_know/howto/audio/images/set_wav_to_copy.png differ diff --git a/articles/getting_to_know/howto/audio/index.md b/articles/getting_to_know/howto/audio/index.md new file mode 100644 index 0000000..80c53a4 --- /dev/null +++ b/articles/getting_to_know/howto/audio/index.md @@ -0,0 +1,39 @@ +--- +title: How To tasks for Audio +description: A series of articles to answer common questions related to audio operation! +requireMSLicense: true +--- + +## In This Section + +No game is truly complete without sound, whether is is a melodious background track, one off sound effects or even recapturing the players voice through a microphone. Without sound games lack depth (although also remember for accessibility, some hear sounds through audio description!, make sure to be inclusive.) + +The following articles showcase some of the best ways to get sound out of your game: + +* [Playing a Sound](HowTo_PlayASound.md) + + Demonstrates how to play a simple sound by using [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect). + +* [Looping a Sound](HowTo_LoopASound.md) + + Demonstrates how to loop a sound. + +* [Adjusting Pitch and Volume](HowTo_ChangePitchAndVolume.md) + + Demonstrates how to change pitch and volume of a playing sound. + +* [Playing a Song](HowTo_PlayASong.md) + + Demonstrates how to play a song from a media file. + +* [Streaming Data from a WAV File](HowTo_StreamDataFromWav.md) + + Demonstrates how to stream audio from a wave (.wav) file. + +* [Accessing Microphone devices](HowTo_Microphone.md) + + Topics that provide guidance on writing code to support access to microphones for MonoGame. + +* [Recording Sound with a Microphone](HowTo_Record_Microphone.md) + + Demonstrates the basics of recording audio using a microphone attached to a device. diff --git a/articles/getting_to_know/howto/audio/toc.yml b/articles/getting_to_know/howto/audio/toc.yml new file mode 100644 index 0000000..68bd170 --- /dev/null +++ b/articles/getting_to_know/howto/audio/toc.yml @@ -0,0 +1,18 @@ +- name: <- Back + href: ../index.md +- name: Introduction + href: index.md +- name: How to Play a sound + href: HowTo_PlayASound.md +- name: How to Loop a sound + href: HowTo_LoopASound.md +- name: How to Play a song + href: HowTo_PlayASong.md +- name: How to Change Pitch And Volume + href: HowTo_ChangePitchAndVolume.md +- name: How to Stream Data From a Wav + href: HowTo_StreamDataFromWav.md +- name: Microphone basics + href: HowTo_Microphone.md +- name: How to Record the Microphone + href: HowTo_Record_Microphone.md \ No newline at end of file diff --git a/articles/getting_to_know/howto/content_pipeline/index.md b/articles/getting_to_know/howto/content_pipeline/index.md new file mode 100644 index 0000000..0e5cd60 --- /dev/null +++ b/articles/getting_to_know/howto/content_pipeline/index.md @@ -0,0 +1,7 @@ +--- +title: How To articles for the Content Pipeline +description: A series of articles to answer common questions related to Content Pipeline operation! +requireMSLicense: true +--- + +## Coming soon \ No newline at end of file diff --git a/articles/getting_to_know/howto/content_pipeline/toc.yml b/articles/getting_to_know/howto/content_pipeline/toc.yml new file mode 100644 index 0000000..bd892b8 --- /dev/null +++ b/articles/getting_to_know/howto/content_pipeline/toc.yml @@ -0,0 +1,2 @@ +- name: <- Back + href: ../index.md \ No newline at end of file diff --git a/articles/getting_to_know/howto/graphics/index.md b/articles/getting_to_know/howto/graphics/index.md new file mode 100644 index 0000000..4744c00 --- /dev/null +++ b/articles/getting_to_know/howto/graphics/index.md @@ -0,0 +1,7 @@ +--- +title: How to articles for the Graphics pipeline +description: These articles provide a details on how to use the Graphics API in MonoGame. +requireMSLicense: true +--- + +## Coming soon \ No newline at end of file diff --git a/articles/getting_to_know/howto/graphics/toc.yml b/articles/getting_to_know/howto/graphics/toc.yml new file mode 100644 index 0000000..bd892b8 --- /dev/null +++ b/articles/getting_to_know/howto/graphics/toc.yml @@ -0,0 +1,2 @@ +- name: <- Back + href: ../index.md \ No newline at end of file diff --git a/articles/getting_to_know/howto/index.md b/articles/getting_to_know/howto/index.md new file mode 100644 index 0000000..059fb27 --- /dev/null +++ b/articles/getting_to_know/howto/index.md @@ -0,0 +1,50 @@ +--- +title: How To Articles for MonoGame +description: These articles provide a brief introduction into performing some basic tasks in MonoGame. +requireMSLicense: true +--- + +## In This Section + +Ever wondered how to do a specific thing quickly, or just try to recall how an operation or function is meant to be implemented, these "How To" guides are quick and short tutorials on how to use each of the features of the MonoGame Framework. + +> [!NOTE] +> These guides are not meant to be a replacement for "full on" tutorials, they are intended as short cuts to relevant information only. + +This section is broken down into 3 distinct categories: + +* [Core concepts](#core-concepts) +* [Game Operations](#game-operations) +* [Guidance](#guidance) + +### Core concepts + +This section details the core concepts to understand how MonoGame projects fit together. + +* [Audio](./audio/index.md) + + A set of articles detailing how to use or implement specific audio features of MonoGame. + +* [Content Pipeline](./content_pipeline/index.md) + + Guides on how to use the Content Pipeline and the MGCB tool for getting content into your MonoGame projects. + +* [Graphics](./graphics/index.md) + + Detailed tutorials on specific graphics features and operations. + +* [Input](./input/index.md) + + Tutorials on how to get the most out of specific inputs from MonoGame while running on platforms. + +### Game Operations + +This section details some of the operational aspects of running a MonoGame game. + +Coming Soon + +### Guidance + +This section contains articles to help make your MonoGame project successful. + +Coming Soon diff --git a/articles/getting_to_know/howto/input/index.md b/articles/getting_to_know/howto/input/index.md new file mode 100644 index 0000000..2a7c73b --- /dev/null +++ b/articles/getting_to_know/howto/input/index.md @@ -0,0 +1,7 @@ +--- +title: Working with Input +description: This section provides topics that demonstrate how to write code that managed input in your MonoGame project for keyboard, mouse, gamepad and touch. +requireMSLicense: true +--- + +## Coming soon \ No newline at end of file diff --git a/articles/getting_to_know/howto/input/toc.yml b/articles/getting_to_know/howto/input/toc.yml new file mode 100644 index 0000000..bd892b8 --- /dev/null +++ b/articles/getting_to_know/howto/input/toc.yml @@ -0,0 +1,2 @@ +- name: <- Back + href: ../index.md \ No newline at end of file diff --git a/articles/getting_to_know/howto/toc.yml b/articles/getting_to_know/howto/toc.yml new file mode 100644 index 0000000..0d05dd1 --- /dev/null +++ b/articles/getting_to_know/howto/toc.yml @@ -0,0 +1,12 @@ +- name: <- Back + href: ../index.md +- name: Introduction + href: index.md +- name: Audio + href: audio/ +- name: Content Pipeline + href: content_pipeline/ +- name: Graphics + href: graphics/ +- name: Input + href: input/ \ No newline at end of file diff --git a/articles/getting_to_know/index.md b/articles/getting_to_know/index.md new file mode 100644 index 0000000..9b0dbe6 --- /dev/null +++ b/articles/getting_to_know/index.md @@ -0,0 +1,26 @@ +--- +title: Welcome to the MonoGame documentation hub +description: The one stop shop for answers to those questions raised by the community about MonoGame +--- + +This new and improved documentation area aims to bridge the gaps in the understanding of the MonoGame Framework, covering all aspects of the features of MonoGame with some support from the original XNA documentation graciously donated by Microsoft. + +Please check back regularly for updates and more details on the evolution of the MonoGame Framework and its API. + +## In This Section + +### [What Is articles](whatis/index.md) + +Provides simple definitions for most of the central concepts maintained by the MonoGame Framework. + +The aim with this documentation section to to answer those most basic of questions, what is this thing and what is it for? Ultimately, these guides are here to help peel back the curtains as to what each feature of the MonoGame framework is for. + +### [How To articles](howto/index.md) + +Short guides for everything you wanted to know about how to do game development with MonoGame, divided up in to simple articles for each activity. + +These guides are here to give shortcuts to specific questions, like how to draw an image or how do I get input from a device. They are not a replacement for the full featured tutorials that MonoGame is investing in, but there to get to to an answer for how to do specific things quicker. + +## Online Resources + +[Check out the full API documentation here](~/api/index.md) diff --git a/articles/getting_to_know/toc.yml b/articles/getting_to_know/toc.yml new file mode 100644 index 0000000..d0f3c65 --- /dev/null +++ b/articles/getting_to_know/toc.yml @@ -0,0 +1,30 @@ +- name: Introduction + href: index.md +- name: What is + href: whatis/ + items: + - name: Audio + href: whatis/WhatIs_Audio.md + - name: Content Pipeline + href: whatis/content_pipeline/ + - name: Graphics + href: whatis/graphics/ + - name: The Game Loop + href: whatis/WhatIs_TheGameLoop.md + - name: Input + href: whatis/WhatIs_Input.md + - name: Vector / Matrix / Quaternions + href: whatis/WhatIs_VectorMatrixQuat.md + - name: MonoGame Class Library + href: whatis/WhatIs_MonoGame_Class_Library.md +- name: How To + href: howto/ + items: + - name: Audio + href: howto/audio/ + - name: Content Pipeline + href: howto/content_pipeline/ + - name: Graphics + href: howto/graphics/ + - name: Input + href: howto/input/ diff --git a/articles/getting_to_know/whatis/WhatIs_Audio.md b/articles/getting_to_know/whatis/WhatIs_Audio.md new file mode 100644 index 0000000..81feb5a --- /dev/null +++ b/articles/getting_to_know/whatis/WhatIs_Audio.md @@ -0,0 +1,68 @@ +--- +title: Sounds Overview +description: An overview of how the MonoGame Framework provides audio playback through several core audio classes. +requireMSLicense: true +--- + +If your game is to use a few sound files, then the [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect), [SoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance), and [DynamicSoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) classes will provide everything you need to play and stream audio during gameplay. + +## Simple Audio Playback + +The simplest way to play sounds for background music or sound effects is to use [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect) and [SoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance). Source audio files are added like any other game asset to the project. For example code, see [Playing a Sound](../howto/audio/HowTo_PlayASound.md), [Looping a Sound](../howto/audio/HowTo_LoopASound.md), and [Adjusting Pitch and Volume](../howto/audio/HowTo_ChangePitchAndVolume.md). For background music, see [Playing a Song](../howto/audio/HowTo_PlayASong.md). + +## Accessing the Audio Buffer + +Developers can use [DynamicSoundEffectInstance](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) for direct access to an audio buffer. By accessing the audio buffer, developers can manipulate sound, break up large sound files into smaller data chunks, and stream sound. For example code, see [Streaming Data from a WAV File](../howto/audio/HowTo_StreamDataFromWav.md). + +## 3D Audio + +The [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect) class provides the ability to place audio in a 3D space. By creating [AudioEmitter](xref:Microsoft.Xna.Framework.Audio.AudioEmitter) and [AudioListener](xref:Microsoft.Xna.Framework.Audio.AudioListener) objects, the API can position a sound in 3D, and can change the 3D position of a sound during playback. Once you create and initialize [AudioEmitter](xref:Microsoft.Xna.Framework.Audio.AudioEmitter) and [AudioListener](xref:Microsoft.Xna.Framework.Audio.AudioListener), call [SoundEffectInstance.Apply3D](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance). + +## Audio Constraints + +When working with multiple platforms using MonoGame, there are a few constraints around audio that you will need to keep in mind and cater for, namely: + +* Mobile platforms have a maximum of 32 sounds playing simultaneously. +* Desktop platforms have a maximum of 256 sounds playing simultaneously. +* Consoles and other platforms have their own constraints, please look at the console sdk documentation for more information, + +> [!IMPORTANT] +> An [InstancePlayLimitException](xref:Microsoft.Xna.Framework.Audio.InstancePlayLimitException) exception is thrown if this limit is exceeded. + +## Audio Buffer Format + +The `byte[]` buffer format used as a parameter for the [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect) constructor, [Microphone.GetData](xref:Microsoft.Xna.Framework.Audio.Microphone) method, and [DynamicSoundEffectInstance.SubmitBuffer](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) method is PCM wave data. Additionally, the PCM format is interleaved and in little-endian. + +The audio format has the following constraints: + +* The audio channels can be mono (1) or stereo (2). +* The PCM wave file must have 16-bits per sample. +* The sample rate must be between 8,000 Hz and 48,000 Hz. +* The interleaving for stereo data is left channel to right channel. + +## Songs as Background Music + +Access to the media library, combined with the ability to use playlists, allows games to create interesting background scores that can change with gameplay. Songs can be played directly from the media library, or can be imported by using the Content Pipeline. For more information, see [Playing a Song](../howto/audio/HowTo_PlayASong.md). + +## Concepts + +> [!IMPORTANT] +> How to articles to follow. + +## Reference + +* [SoundEffect Class](xref:Microsoft.Xna.Framework.Audio.SoundEffect) + + Provides a loaded sound resource. + +* [SoundEffectInstance Class](xref:Microsoft.Xna.Framework.Audio.SoundEffectInstance) + + Provides a single playing, paused, or stopped instance of a [SoundEffect](xref:Microsoft.Xna.Framework.Audio.SoundEffect) sound. + +* [DynamicSoundEffectInstance Class](xref:Microsoft.Xna.Framework.Audio.DynamicSoundEffectInstance) + + Provides properties, methods, and events for play back of the audio buffer. + +* [Song Class](xref:Microsoft.Xna.Framework.Media.Song) + + Provides access to a song in the song library. diff --git a/articles/getting_to_know/whatis/WhatIs_Input.md b/articles/getting_to_know/whatis/WhatIs_Input.md new file mode 100644 index 0000000..b5e7649 --- /dev/null +++ b/articles/getting_to_know/whatis/WhatIs_Input.md @@ -0,0 +1,20 @@ +--- +title: Overview of User Input and Input Devices +description: Input is a general term referring to the process of receiving actions from the user. +requireMSLicense: true +--- + +Input is a general term referring to the process of receiving actions from the user. In MonoGame, the [Microsoft.Xna.Framework.Input](xref:Microsoft.Xna.Framework.Input) namespace provides support for most input devices. + +Methods related to input devices unavailable on the platform your game is running on are always available to your code. For example, you can access all [GamePad](xref:Microsoft.Xna.Framework.Input.GamePad) methods on Mobile, but they will not return valid information (unless a GamePad is connected). Although using these methods will not cause exceptions or build errors in your code, they will silently fail when run. + +Physical keyboards may or may not be present on mobile devices; you should not rely on the presence of a physical keyboard. For text input, you should use a software input panel (SIP), which will work on all devices, including those with physical keyboards. + +If the mobile device does have access to a physical keyboard, the same methods used for keyboards on desktop can be used, given a few caveats. + +For multi-touch devices, you can use the raw touch data provided by the [TouchPanel](xref:Microsoft.Xna.Framework.Input.Touch.TouchPanel) class, but you can also use MonoGame's support for predefined gestures if your input fits one of the supported gesture types. For information about working with raw multi-touch input, see [Working with Touch Input](). For information about gesture support, see [Detecting Gestures on a Multi-touch Screen](). + +The microphone on mobile can be used to capture audio that can be used in your game. For more information, see [Recording Sounds with Microphones](). + +> [!IMPORTANT] +> How to articles to follow. \ No newline at end of file diff --git a/articles/getting_to_know/whatis/WhatIs_MonoGame_Class_Library.md b/articles/getting_to_know/whatis/WhatIs_MonoGame_Class_Library.md new file mode 100644 index 0000000..2d7723e --- /dev/null +++ b/articles/getting_to_know/whatis/WhatIs_MonoGame_Class_Library.md @@ -0,0 +1,53 @@ +--- +title: MonoGame Framework Class Library +description: MonoGame Framework Class Library Reference +requireMSLicense: true +--- + +The MonoGame Framework class library is a library of classes, interfaces, and value types that are included in MonoGame Game Studio. This library provides access to MonoGame Framework functionality and is designed to be the foundation on which MonoGame Game Studio applications, components, and controls are built. + +## Namespaces + +- [Microsoft.Xna.Framework](xref:Microsoft.Xna.Framework) + + Provides commonly needed game classes such as timers and game loops. + +- [Microsoft.Xna.Framework.Audio](xref:Microsoft.Xna.Framework.Audio) + + Contains low-level application programming interface (API) methods that can load and manipulate content files to play audio. + +- [Microsoft.Xna.Framework.Content](xref:Microsoft.Xna.Framework.Content) + + Contains the run-time components of the Content Pipeline. + +- [Microsoft.Xna.Framework.Design](xref:Microsoft.Xna.Framework.Design) + + Provides a unified way of converting types of values to other types. + +- [Microsoft.Xna.Framework.Graphics](xref:Microsoft.Xna.Framework.Graphics) + + Contains low-level application programming interface (API) methods that take advantage of hardware acceleration capabilities to display 3D objects. + +- [Microsoft.Xna.Framework.Graphics.PackedVector](xref:Microsoft.Xna.Framework.Graphics.PackedVector) + + Represents data types with components that are not multiples of 8 bits. + +- [Microsoft.Xna.Framework.Input](xref:Microsoft.Xna.Framework.Input) + + Contains classes to receive input from keyboard, mouse, and GamePad devices. + +- [Microsoft.Xna.Framework.Input.Touch](xref:Microsoft.Xna.Framework.Input.Touch) + + Contains classes that enable access to touch-based input on devices that support it. + +- [Microsoft.Xna.Framework.Media](xref:Microsoft.Xna.Framework.Media) + + Contains classes to enumerate, play, and view songs, albums, playlists, and pictures. + +- Microsoft.Xna.Framework.Utilities + + Contains classes that provide additional support for working with MonoGame. + +- Microsoft.Xna.Framework.Utilities.Deflate + + Contains classes that provide additional support for compression with MonoGame. diff --git a/articles/getting_to_know/whatis/WhatIs_TheGameLoop.md b/articles/getting_to_know/whatis/WhatIs_TheGameLoop.md new file mode 100644 index 0000000..0b6c162 --- /dev/null +++ b/articles/getting_to_know/whatis/WhatIs_TheGameLoop.md @@ -0,0 +1,96 @@ +--- +title: What is the Game Loop +description: There is a specific order of operations related to how a MonoGame project runs. +requireMSLicense: true +--- + +The MonoGame Framework [Game](xref:Microsoft.Xna.Framework.Game) class implements a game loop, which provides not only the window which displays your game, but also provides overloadable methods that your game implements to facilitate communication between your game and the operating system. This topic provides an overview of the basic functionality provided by the game loop. + +* [Making a New Game](#making-a-new-game) +* [Game Loop Timing](#game-loop-timing) +* [Game Components](#game-components) +* [Game Services](#game-services) +* [Game Components Consuming Game Services](#game-components-consuming-game-services) + +![The MonoGame "Game" Loop](./images/MGExecution.png) + +## Making a New Game + +The first step in creating a new game is to make a class that derives from [Game](xref:Microsoft.Xna.Framework.Game). The new class needs to override the following methods: + +* Initialize - which is the method is responsible for game setup before the first frame of the game. +* Update - which is the method is responsible for handling game logic. +* Draw - which is the method responsible for drawing content to the screen. + +## Game Loop Timing + +A [Game](xref:Microsoft.Xna.Framework.Game) is either fixed step or variable step, defaulting to fixed step. The type of step determines how often [Update](xref:Microsoft.Xna.Framework.Game) will be called and affects how you need to represent time-based procedures such as movement and animation. + +### Fixed-Step Game Loops + +A fixed-step [Game](xref:Microsoft.Xna.Framework.Game) tries to call its **Update** method on the fixed interval specified in **TargetElapsedTime**. Setting **Game.IsFixedTimeStep** to **true** causes a [Game](xref:Microsoft.Xna.Framework.Game) to use a fixed-step game loop. A new MonoGame project uses a fixed-step game loop with a default **TargetElapsedTime** of 1/60th of a second. + +In a fixed-step game loop, [Game](xref:Microsoft.Xna.Framework.Game) calls **Update** once the **TargetElapsedTime** has elapsed. After **Update** is called, if it is not time to call **Update** again, the [Game](xref:Microsoft.Xna.Framework.Game) calls **Draw**. After **Draw** is called, if it is not time to call **Update** again, [Game](xref:Microsoft.Xna.Framework.Game) idles until it is time to call **UpdateS**. + +If **Update** takes too long to process, [Game](xref:Microsoft.Xna.Framework.Game) sets **IsRunningSlowly** to **true** and calls **Update** again, without calling **Draw** in between. When an update runs longer than the **TargetElapsedTime**, [Game](xref:Microsoft.Xna.Framework.Game) responds by calling **Update** extra times and dropping the frames associated with those updates to catch up. This ensures that **Update** will have been called the expected number of times when the game loop catches up from a slowdown. You can check the value of **IsRunningSlowly** in your **Update** if you want to detect dropped frames and shorten your **Update** processing to compensate. You can reset the elapsed times by calling **ResetElapsedTime**. + +When your game pauses in the debugger, [Game](xref:Microsoft.Xna.Framework.Game) will not make extra calls to **Update** when the game resumes. + +### Variable-Step Game Loops + +A variable-step game calls its **Update** and **Draw** methods in a continuous loop without regard to the [TargetElapsedTime](xref:Microsoft.Xna.Framework.Game). Setting [Game.IsFixedTimeStep](xref:Microsoft.Xna.Framework.Game) to **false** causes a [Game](xref:Microsoft.Xna.Framework.Game) to use a variable-step game loop. + +### Animation and Timing + +For operations that require precise timing, such as animation, the type of game loop your game uses (fixed-step or variable-step) is important. + +Using a fixed step allows game logic to use the **TargetElapsedTime** as its basic unit of time and assume that **Update** will be called at that interval. Using a variable step requires the game logic and animation code to be based on **ElapsedGameTime** to ensure smooth gameplay. Because the **Update** method is called immediately after the previous frame is drawn, the time between calls to **Update** can vary. Without taking the time between calls into account, the game would seem to speed up and slow down. The time elapsed between calls to the **Update** method is available in the **Update** method's _gameTime_ parameter. You can reset the elapsed times by calling **ResetElapsedTime**. + +When using a variable-step game loop, you should express rates—such as the distance a sprite moves—in game units per millisecond (ms). The amount a sprite moves in any given update can then be calculated as the rate of the sprite times the elapsed time. Using this approach to calculate the distance the sprite moved ensures that the sprite will move consistently if the speed of the game or computer varies. + +## Game Components + +Game components provide a modular way of adding functionality to a game. You create a game component by deriving the new component either from the + +* [GameComponent](xref:Microsoft.Xna.Framework.GameComponent) class, or +* [DrawableGameComponent](xref:Microsoft.Xna.Framework.DrawableGameComponent) class if the component loads and draws graphics content. + +You then add game logic and rendering code to the game component by overriding the following methods: + +* **GameComponent.Update** +* **GameComponent.Initialize** + +Additionally, if you derive from the `DrawableGameComponent` class, you will additionally be able to override: + +* **DrawableGameComponent.Draw** + +A game component is registered with a game by passing the component to `Game.Components.Add`. A registered component will have its `initialize`, `update`, and `draw` methods called from the `Game.Initialize`, `Game.Update`, and `Game.Draw` methods, respectively. + +## Game Services + +Game services are a mechanism for maintaining loose coupling between objects that need to interact with each other. Services work through a mediator—in this case, [Game.Services](xref:Microsoft.Xna.Framework.Game.Services). Service providers register with [Game.Services](xref:Microsoft.Xna.Framework.Game.Services), and service consumers request services from [Game.Services](xref:Microsoft.Xna.Framework.Game.Services). This arrangement allows an object that requires a service to request the service without knowing the name of the service provider. + +Game services are defined by a unique interface. A class specifies the services it provides by implementing interfaces and registering the services with [Game.Services](xref:Microsoft.Xna.Framework.Game.Services). A service is registered by calling **Game.Services.AddService** specifying the type of service being implemented and a reference to the object providing the service. For example, to register an object that provides a service represented by the interface IMyService, you would use the following code. + +```csharp + Services.AddService( typeof( IMyService ), myobject ); +``` + +Once a service is registered, the object providing the service can be retrieved by **Game.Services.GetService** and specifying the desired service. For example, to retrieve [IGraphicsDeviceService](xref:Microsoft.Xna.Framework.Graphics.IGraphicsDeviceService), you would use the following code. + +```csharp + IGraphicsDeviceService graphicsservice = (IGraphicsDeviceService)Services.GetService( typeof(IGraphicsDeviceService) ); +``` + +## Game Components Consuming Game Services + +The [GameComponent](xref:Microsoft.Xna.Framework.GameComponent) class provides the [Game](xref:Microsoft.Xna.Framework.GameComponent.Game) property so a [GameComponent](xref:Microsoft.Xna.Framework.GameComponent) can determine what [Game](xref:Microsoft.Xna.Framework.Game) it is attached to. With the [Game](xref:Microsoft.Xna.Framework.GameComponent.Game) property, a [GameComponent](xref:Microsoft.Xna.Framework.GameComponent) can call [Game.Services.GetService](xref:Microsoft.Xna.Framework.GameServiceContainer) to find a provider of a particular service. For example, a [GameComponent](xref:Microsoft.Xna.Framework.GameComponent) would find the [IGraphicsDeviceService](xref:Microsoft.Xna.Framework.Graphics.IGraphicsDeviceService) provider by using the following code. + +```csharp + IGraphicsDeviceService graphicsservice = (IGraphicsDeviceService)Game.Services.GetService( typeof( IGraphicsDeviceService ) ); +``` + +## Related articles + +> [!IMPORTANT] +> How to articles to follow. diff --git a/articles/getting_to_know/whatis/WhatIs_VectorMatrixQuat.md b/articles/getting_to_know/whatis/WhatIs_VectorMatrixQuat.md new file mode 100644 index 0000000..b4d8aa8 --- /dev/null +++ b/articles/getting_to_know/whatis/WhatIs_VectorMatrixQuat.md @@ -0,0 +1,63 @@ +--- +title: What are Vectors, Matrices, and Quaternions? +description: What are What are Vectors, Matrices, and Quaternions definitions for MonoGame! +requireMSLicense: true +--- + +The MonoGame Framework Math Libraries are in the [Microsoft.Xna.Framework](xref:Microsoft.Xna.Framework) namespace alongside a number of additional types that deal with The MonoGame Framework Application model. + +* [Coordinate system](#coordinate-system) +* [Mathematical Constants and Scalar Manipulation](#mathematical-constants-and-scalar-manipulation) +* [Basic Geometric Types](#basic-geometric-types) +* [Precision and Performance](#precision-and-performance) + +## Coordinate system + +The MonoGame Framework uses a right-handed coordinate system, with the positive z-axis pointing toward the observer when the positive x-axis is pointing to the right, and the positive y-axis is pointing up. + +## Mathematical Constants and Scalar Manipulation + +The MonoGame Framework provides the [MathHelper Members](xref:Microsoft.Xna.Framework.MathHelper) class for manipulating scalar values and retrieving some common mathematical constants. This includes methods such as the `ToDegrees` and `ToRadians` utility methods for converting between degrees and radians. + +## Basic Geometric Types + +The MonoGame Framework Math library has multiple basic geometric types for manipulating objects in 2D or 3D space. Each geometric type has a number of mathematical operations that are supported for the type. + +### Vectors + +The MonoGame Framework provides the [Vector2](xref:Microsoft.Xna.Framework.Vector2), [Vector3](xref:Microsoft.Xna.Framework.Vector3), and [Vector4](xref:Microsoft.Xna.Framework.Vector4) classes for representing and manipulating vectors. A vector typically is used to represent a direction and magnitude. In The MonoGame Framework, however, it also could be used to store a coordinate or other data type with the same storage requirements. + +Each vector class has methods for performing standard vector operations such as: + +* [Dot product](/api/Microsoft.Xna.Framework.Vector3.html#Microsoft_Xna_Framework_Vector3_Dot_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Vector3_) +* [Cross product](/api/Microsoft.Xna.Framework.Vector3.html#Microsoft_Xna_Framework_Vector3_Cross_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Vector3_) +* [Normalization](/api/Microsoft.Xna.Framework.Vector3.html#Microsoft_Xna_Framework_Vector3_Normalize) +* [Transformation](/api/Microsoft.Xna.Framework.Vector3.html#Microsoft_Xna_Framework_Vector3_Transform_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Matrix_) +* [Linear](/api/Microsoft.Xna.Framework.Vector3.html#Microsoft_Xna_Framework_Vector3_Lerp_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Vector3_System_Single_), [Cubic](/api/Microsoft.Xna.Framework.Vector3.html#Microsoft_Xna_Framework_Vector3_SmoothStep_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Vector3_System_Single_), [Catmull-Rom](/api/Microsoft.Xna.Framework.Vector3.html#Microsoft_Xna_Framework_Vector3_CatmullRom_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Vector3_System_Single_), or [Hermite spline](/api/Microsoft.Xna.Framework.Vector3.html#Microsoft_Xna_Framework_Vector3_Hermite_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Vector3_Microsoft_Xna_Framework_Vector3_System_Single_) interpolation. + +### Matrices + +The MonoGame Framework provides the [Matrix](xref:Microsoft.Xna.Framework.Matrix) class for transformation of geometry. The [Matrix](xref:Microsoft.Xna.Framework.Matrix) class uses row major order to address matrices, which means that the row is specified before the column when describing an element of a two-dimensional matrix. The [Matrix](xref:Microsoft.Xna.Framework.Matrix) class provides methods for performing standard matrix operations such as calculating the `determinate` or `inverse` of a matrix. There also are helper methods for creating scale, rotation, and translation matrices. + +### Quaternions + +The MonoGame Framework provides the [Quaternion](xref:Microsoft.Xna.Framework.Quaternion) structure to calculate the efficient rotation of a vector by a specified angle. + +### Curves + +The [Curve](xref:Microsoft.Xna.Framework.Curve) class represents a Hermite curve for interpolating varying positions at different times without having to explicitly define each position. The curve is defined by a collection of [CurveKey](xref:Microsoft.Xna.Framework.CurveKey) points representing each varying position at different times. This class can be used not only for spatial motion, but also to represent any response that changes over time. + +### Bounding Volumes + +The MonoGame Framework provides the [BoundingBox](xref:Microsoft.Xna.Framework.BoundingBox), [BoundingFrustum](xref:Microsoft.Xna.Framework.BoundingFrustum), [BoundingSphere](xref:Microsoft.Xna.Framework.BoundingSphere), [Plane](xref:Microsoft.Xna.Framework.Plane), and [Ray](xref:Microsoft.Xna.Framework.Ray) classes for representing simplified versions of geometry for the purpose of efficient collision and hit testing. These classes have methods for checking for intersection and containment with each other. + +## Precision and Performance + +The MonoGame Framework Math libraries are single-precision. This means that the primitives and operations contained in this library use 32-bit floating-point numbers to achieve a balance between precision and efficiency when performing large numbers of calculations. + +A 32-bit floating-point number ranges from `–3.402823e38` to `+3.402823e38`. The 32 bits store the sign, mantissa, and exponent of the number that yields seven digits of floating-point precision. + + [!NOTE] +> Some numbers—for example π, 1/3, or the square root of two—can be approximated only with seven digits of precision, so be aware of rounding errors when using a binary representation of a floating-point number. + +For more information about single-precision numbers, see the documentation for the [Single](http://msdn.microsoft.com/en-us/library/system.single.aspx) data type. diff --git a/articles/getting_to_know/whatis/content_pipeline/index.md b/articles/getting_to_know/whatis/content_pipeline/index.md new file mode 100644 index 0000000..ee4ddfe --- /dev/null +++ b/articles/getting_to_know/whatis/content_pipeline/index.md @@ -0,0 +1,7 @@ +--- +title: What is the Content pipeline? +description: The topics in this section describe how to add and load content such as textures, meshes, sounds, and data in your game. +requireMSLicense: true +--- + +## Coming soon \ No newline at end of file diff --git a/articles/getting_to_know/whatis/content_pipeline/toc.yml b/articles/getting_to_know/whatis/content_pipeline/toc.yml new file mode 100644 index 0000000..bd892b8 --- /dev/null +++ b/articles/getting_to_know/whatis/content_pipeline/toc.yml @@ -0,0 +1,2 @@ +- name: <- Back + href: ../index.md \ No newline at end of file diff --git a/articles/getting_to_know/whatis/graphics/index.md b/articles/getting_to_know/whatis/graphics/index.md new file mode 100644 index 0000000..d931c64 --- /dev/null +++ b/articles/getting_to_know/whatis/graphics/index.md @@ -0,0 +1,7 @@ +--- +title: What are Graphics? +description: The basics of the graphics architecture for MonoGame! +requireMSLicense: true +--- + +## Coming soon \ No newline at end of file diff --git a/articles/getting_to_know/whatis/graphics/toc.yml b/articles/getting_to_know/whatis/graphics/toc.yml new file mode 100644 index 0000000..bd892b8 --- /dev/null +++ b/articles/getting_to_know/whatis/graphics/toc.yml @@ -0,0 +1,2 @@ +- name: <- Back + href: ../index.md \ No newline at end of file diff --git a/articles/getting_to_know/whatis/images/MGExecution.png b/articles/getting_to_know/whatis/images/MGExecution.png new file mode 100644 index 0000000..6f04808 Binary files /dev/null and b/articles/getting_to_know/whatis/images/MGExecution.png differ diff --git a/articles/getting_to_know/whatis/index.md b/articles/getting_to_know/whatis/index.md new file mode 100644 index 0000000..a8bf67c --- /dev/null +++ b/articles/getting_to_know/whatis/index.md @@ -0,0 +1,60 @@ +--- +title: What Is Articles for MonoGame +description: A series of articles to answer common questions related to MonoGame operation! +requireMSLicense: true +--- + +## In This Section + +Ever wondered why a specific feature exists and what it is supposed to do? The following articles go into detail as to what each of the major components of the MonoGame Framework do and how best to make use of them. + +Where applicable, these articles also cross-reference with the "[How-To](../howto/index.md)" articles for the use of these features. + +> [!NOTE] +> These guides are not meant to be a replacement for "full on" tutorials, they are intended as short cuts to relevant information only. + +This section is broken down into 3 distinct categories: + +* [Detailed sections](#detailed-sections) +* [Game Operations](#game-operations) +* [References](#references) + +### Detailed sections + +Due the complexity of the Content and Graphics pipelines, the information is broken up into smaller pieces for easier understanding: + +* [What Is the Content Pipeline?](content_pipeline/index.md) + + An overview of how the MonoGame Framework provides content management and loading for games. + +* [What Is the Graphics Pipeline?](graphics/index.md) + + An overview of how the MonoGame Framework provides graphical support for games. + +### Game Operations + +This section details some general aspects of the operation of a MonoGame Framework game. + +* [What Is Audio?](WhatIs_Audio.md) + + An overview of how the MonoGame Framework provides audio playback through several core audio classes. + +* [What Is Input?](WhatIs_Input.md) + + An overview of how the MonoGame Framework provides input management for games. + +* [What Is the GameLoop?](WhatIs_TheGameLoop.md) + + A viewport is a 2D rectangle that defines the size of the rendering surface onto which a 3D scene is projected. + +* [What are Vectors, Matrices, and Quaternions?](WhatIs_VectorMatrixQuat.md) + + Presents an overview of the math-related functionality provided by the MonoGame Framework. + +## See Also + +### References + +* [What Is MonoGame Class Library](WhatIs_MonoGame_Class_Library.md) + + An overview of the MonoGame Class Library reference, containing all the API calls available to the MonoGame Framework. diff --git a/articles/getting_to_know/whatis/toc.yml b/articles/getting_to_know/whatis/toc.yml new file mode 100644 index 0000000..80e1ad2 --- /dev/null +++ b/articles/getting_to_know/whatis/toc.yml @@ -0,0 +1,18 @@ +- name: <- Back + href: ../index.md +- name: Introduction + href: index.md +- name: Content Pipeline + href: content_pipeline/ +- name: Graphics + href: graphics/ +- name: Audio + href: WhatIs_Audio.md +- name: Input + href: WhatIs_Input.md +- name: The Game Loop + href: WhatIs_TheGameLoop.md +- name: Vector / Matrix / Quaternions + href: WhatIs_VectorMatrixQuat.md +- name: MonoGame Class Library + href: WhatIs_VectorMatrixQuat.md diff --git a/articles/toc.yml b/articles/toc.yml index 4071903..efa25c5 100644 --- a/articles/toc.yml +++ b/articles/toc.yml @@ -1,5 +1,5 @@ - name: Introduction - href: index.md + href: - name: Roadmap href: roadmap.md - name: What's New @@ -7,7 +7,7 @@ - name: Getting Started items: - name: Introduction - href: getting_started/index.md + href: getting_started/ - name: Supported platforms href: getting_started/platforms.md - name: 1. Setting up your development environment @@ -37,7 +37,7 @@ - name: Tools items: - name: Introduction - href: getting_started/tools/index.md + href: getting_started/tools/ - name: MGCB href: getting_started/tools/mgcb.md - name: MGCB Editor @@ -58,6 +58,37 @@ href: getting_started/content_pipeline/adding_ttf_fonts.md - name: Localization href: getting_started/content_pipeline/localization.md +- name: Getting to know MonoGame + href: getting_to_know/ + items: + - name: What is + href: getting_to_know/whatis/ + items: + - name: Audio + href: getting_to_know/whatis/WhatIs_Audio.md + - name: Content Pipeline + href: getting_to_know/whatis/content_pipeline/ + - name: Graphics + href: getting_to_know/whatis/graphics/ + - name: Input + href: getting_to_know/whatis/WhatIs_Input.md + - name: The Game Loop + href: getting_to_know/whatis/WhatIs_TheGameLoop.md + - name: Vector / Matrix / Quaternions + href: getting_to_know/whatis/WhatIs_VectorMatrixQuat.md + - name: MonoGame Class Library + href: getting_to_know/whatis/WhatIs_MonoGame_Class_Library.md + - name: How to + href: getting_to_know/howto/ + items: + - name: Audio + href: getting_to_know/howto/audio/ + - name: Content Pipeline + href: getting_to_know/howto/content_pipeline/ + - name: Graphics + href: getting_to_know/howto/graphics/ + - name: Input + href: getting_to_know/howto/input/ - name: Migration items: - name: Migrating from XNA @@ -73,4 +104,4 @@ - name: Help and Support href: help_and_support.md - name: Contributing to documentation - href: contributing.md \ No newline at end of file + href: contributing.md diff --git a/docfx.json b/docfx.json index a96e10b..ba76ca2 100644 --- a/docfx.json +++ b/docfx.json @@ -48,6 +48,7 @@ { "files": [ "**/images/**", + "**/files/**", "CNAME" ] }