Level with origin
This commit is contained in:
313
Extensions/olcPGEX_Graphics2D.h
Normal file
313
Extensions/olcPGEX_Graphics2D.h
Normal file
@@ -0,0 +1,313 @@
|
||||
/*
|
||||
olcPGEX_Graphics2D.h
|
||||
|
||||
+-------------------------------------------------------------+
|
||||
| OneLoneCoder Pixel Game Engine Extension |
|
||||
| Advanced 2D Rendering - v0.5 |
|
||||
+-------------------------------------------------------------+
|
||||
|
||||
What is this?
|
||||
~~~~~~~~~~~~~
|
||||
This is an extension to the olcPixelGameEngine, which provides
|
||||
advanced olc::Sprite manipulation and drawing routines. To use
|
||||
it, simply include this header file.
|
||||
|
||||
License (OLC-3)
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Copyright 2018 - 2019 OneLoneCoder.com
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions or derivations of source code must retain the above
|
||||
copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions or derivative works in binary form must reproduce
|
||||
the above copyright notice. This list of conditions and the following
|
||||
disclaimer must be reproduced in the documentation and/or other
|
||||
materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
Links
|
||||
~~~~~
|
||||
YouTube: https://www.youtube.com/javidx9
|
||||
Discord: https://discord.gg/WhwHUMV
|
||||
Twitter: https://www.twitter.com/javidx9
|
||||
Twitch: https://www.twitch.tv/javidx9
|
||||
GitHub: https://www.github.com/onelonecoder
|
||||
Homepage: https://www.onelonecoder.com
|
||||
|
||||
Author
|
||||
~~~~~~
|
||||
David Barr, aka javidx9, ©OneLoneCoder 2019
|
||||
*/
|
||||
|
||||
/*
|
||||
Matrices stored as [Column][Row] (i.e. x, y)
|
||||
|
||||
|C0R0 C1R0 C2R0| | x | | x'|
|
||||
|C0R1 C1R1 C2R1| * | y | = | y'|
|
||||
|C0R2 C1R2 C2R2| |1.0| | - |
|
||||
*/
|
||||
|
||||
|
||||
|
||||
#ifndef OLC_PGEX_GFX2D
|
||||
#define OLC_PGEX_GFX2D
|
||||
|
||||
#include <algorithm>
|
||||
#undef min
|
||||
#undef max
|
||||
|
||||
namespace olc
|
||||
{
|
||||
// Container class for Advanced 2D Drawing functions
|
||||
class GFX2D : public olc::PGEX
|
||||
{
|
||||
// A representation of an affine transform, used to rotate, scale, offset & shear space
|
||||
public:
|
||||
class Transform2D
|
||||
{
|
||||
public:
|
||||
Transform2D();
|
||||
|
||||
public:
|
||||
// Set this transformation to unity
|
||||
void Reset();
|
||||
// Append a rotation of fTheta radians to this transform
|
||||
void Rotate(float fTheta);
|
||||
// Append a translation (ox, oy) to this transform
|
||||
void Translate(float ox, float oy);
|
||||
// Append a scaling operation (sx, sy) to this transform
|
||||
void Scale(float sx, float sy);
|
||||
// Append a shear operation (sx, sy) to this transform
|
||||
void Shear(float sx, float sy);
|
||||
|
||||
void Perspective(float ox, float oy);
|
||||
// Calculate the Forward Transformation of the coordinate (in_x, in_y) -> (out_x, out_y)
|
||||
void Forward(float in_x, float in_y, float &out_x, float &out_y);
|
||||
// Calculate the Inverse Transformation of the coordinate (in_x, in_y) -> (out_x, out_y)
|
||||
void Backward(float in_x, float in_y, float &out_x, float &out_y);
|
||||
// Regenerate the Inverse Transformation
|
||||
void Invert();
|
||||
|
||||
private:
|
||||
void Multiply();
|
||||
float matrix[4][3][3];
|
||||
int nTargetMatrix;
|
||||
int nSourceMatrix;
|
||||
bool bDirty;
|
||||
};
|
||||
|
||||
public:
|
||||
// Draws a sprite with the transform applied
|
||||
static void DrawSprite(olc::Sprite *sprite, olc::GFX2D::Transform2D &transform);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
#ifdef OLC_PGEX_GRAPHICS2D
|
||||
#undef OLC_PGEX_GRAPHICS2D
|
||||
|
||||
namespace olc
|
||||
{
|
||||
void GFX2D::DrawSprite(olc::Sprite *sprite, olc::GFX2D::Transform2D &transform)
|
||||
{
|
||||
if (sprite == nullptr)
|
||||
return;
|
||||
|
||||
// Work out bounding rectangle of sprite
|
||||
float ex, ey;
|
||||
float sx, sy;
|
||||
float px, py;
|
||||
|
||||
transform.Forward(0.0f, 0.0f, sx, sy);
|
||||
px = sx; py = sy;
|
||||
sx = std::min(sx, px); sy = std::min(sy, py);
|
||||
ex = std::max(ex, px); ey = std::max(ey, py);
|
||||
|
||||
transform.Forward((float)sprite->width, (float)sprite->height, px, py);
|
||||
sx = std::min(sx, px); sy = std::min(sy, py);
|
||||
ex = std::max(ex, px); ey = std::max(ey, py);
|
||||
|
||||
transform.Forward(0.0f, (float)sprite->height, px, py);
|
||||
sx = std::min(sx, px); sy = std::min(sy, py);
|
||||
ex = std::max(ex, px); ey = std::max(ey, py);
|
||||
|
||||
transform.Forward((float)sprite->width, 0.0f, px, py);
|
||||
sx = std::min(sx, px); sy = std::min(sy, py);
|
||||
ex = std::max(ex, px); ey = std::max(ey, py);
|
||||
|
||||
// Perform inversion of transform if required
|
||||
transform.Invert();
|
||||
|
||||
if (ex < sx)
|
||||
std::swap(ex, sx);
|
||||
if (ey < sy)
|
||||
std::swap(ey, sy);
|
||||
|
||||
// Iterate through render space, and sample Sprite from suitable texel location
|
||||
for (float i = sx; i < ex; i++)
|
||||
{
|
||||
for (float j = sy; j < ey; j++)
|
||||
{
|
||||
float ox, oy;
|
||||
transform.Backward(i, j, ox, oy);
|
||||
pge->Draw((int32_t)i, (int32_t)j, sprite->GetPixel((int32_t)(ox+0.5f), (int32_t)(oy+0.5f)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
olc::GFX2D::Transform2D::Transform2D()
|
||||
{
|
||||
Reset();
|
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Reset()
|
||||
{
|
||||
nTargetMatrix = 0;
|
||||
nSourceMatrix = 1;
|
||||
bDirty = true;
|
||||
|
||||
// Columns Then Rows
|
||||
|
||||
// Matrices 0 & 1 are used as swaps in Transform accumulation
|
||||
matrix[0][0][0] = 1.0f; matrix[0][1][0] = 0.0f; matrix[0][2][0] = 0.0f;
|
||||
matrix[0][0][1] = 0.0f; matrix[0][1][1] = 1.0f; matrix[0][2][1] = 0.0f;
|
||||
matrix[0][0][2] = 0.0f; matrix[0][1][2] = 0.0f; matrix[0][2][2] = 1.0f;
|
||||
|
||||
matrix[1][0][0] = 1.0f; matrix[1][1][0] = 0.0f; matrix[1][2][0] = 0.0f;
|
||||
matrix[1][0][1] = 0.0f; matrix[1][1][1] = 1.0f; matrix[1][2][1] = 0.0f;
|
||||
matrix[1][0][2] = 0.0f; matrix[1][1][2] = 0.0f; matrix[1][2][2] = 1.0f;
|
||||
|
||||
// Matrix 2 is a cache matrix to hold the immediate transform operation
|
||||
// Matrix 3 is a cache matrix to hold the inverted transform
|
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Multiply()
|
||||
{
|
||||
for (int c = 0; c < 3; c++)
|
||||
{
|
||||
for (int r = 0; r < 3; r++)
|
||||
{
|
||||
matrix[nTargetMatrix][c][r] = matrix[2][0][r] * matrix[nSourceMatrix][c][0] +
|
||||
matrix[2][1][r] * matrix[nSourceMatrix][c][1] +
|
||||
matrix[2][2][r] * matrix[nSourceMatrix][c][2];
|
||||
}
|
||||
}
|
||||
|
||||
std::swap(nTargetMatrix, nSourceMatrix);
|
||||
bDirty = true; // Any transform multiply dirties the inversion
|
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Rotate(float fTheta)
|
||||
{
|
||||
// Construct Rotation Matrix
|
||||
matrix[2][0][0] = cosf(fTheta); matrix[2][1][0] = sinf(fTheta); matrix[2][2][0] = 0.0f;
|
||||
matrix[2][0][1] = -sinf(fTheta); matrix[2][1][1] = cosf(fTheta); matrix[2][2][1] = 0.0f;
|
||||
matrix[2][0][2] = 0.0f; matrix[2][1][2] = 0.0f; matrix[2][2][2] = 1.0f;
|
||||
Multiply();
|
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Scale(float sx, float sy)
|
||||
{
|
||||
// Construct Scale Matrix
|
||||
matrix[2][0][0] = sx; matrix[2][1][0] = 0.0f; matrix[2][2][0] = 0.0f;
|
||||
matrix[2][0][1] = 0.0f; matrix[2][1][1] = sy; matrix[2][2][1] = 0.0f;
|
||||
matrix[2][0][2] = 0.0f; matrix[2][1][2] = 0.0f; matrix[2][2][2] = 1.0f;
|
||||
Multiply();
|
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Shear(float sx, float sy)
|
||||
{
|
||||
// Construct Shear Matrix
|
||||
matrix[2][0][0] = 1.0f; matrix[2][1][0] = sx; matrix[2][2][0] = 0.0f;
|
||||
matrix[2][0][1] = sy; matrix[2][1][1] = 1.0f; matrix[2][2][1] = 0.0f;
|
||||
matrix[2][0][2] = 0.0f; matrix[2][1][2] = 0.0f; matrix[2][2][2] = 1.0f;
|
||||
Multiply();
|
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Translate(float ox, float oy)
|
||||
{
|
||||
// Construct Translate Matrix
|
||||
matrix[2][0][0] = 1.0f; matrix[2][1][0] = 0.0f; matrix[2][2][0] = ox;
|
||||
matrix[2][0][1] = 0.0f; matrix[2][1][1] = 1.0f; matrix[2][2][1] = oy;
|
||||
matrix[2][0][2] = 0.0f; matrix[2][1][2] = 0.0f; matrix[2][2][2] = 1.0f;
|
||||
Multiply();
|
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Perspective(float ox, float oy)
|
||||
{
|
||||
// Construct Translate Matrix
|
||||
matrix[2][0][0] = 1.0f; matrix[2][1][0] = 0.0f; matrix[2][2][0] = 0.0f;
|
||||
matrix[2][0][1] = 0.0f; matrix[2][1][1] = 1.0f; matrix[2][2][1] = 0.0f;
|
||||
matrix[2][0][2] = ox; matrix[2][1][2] = oy; matrix[2][2][2] = 1.0f;
|
||||
Multiply();
|
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Forward(float in_x, float in_y, float &out_x, float &out_y)
|
||||
{
|
||||
out_x = in_x * matrix[nSourceMatrix][0][0] + in_y * matrix[nSourceMatrix][1][0] + matrix[nSourceMatrix][2][0];
|
||||
out_y = in_x * matrix[nSourceMatrix][0][1] + in_y * matrix[nSourceMatrix][1][1] + matrix[nSourceMatrix][2][1];
|
||||
float out_z = in_x * matrix[nSourceMatrix][0][2] + in_y * matrix[nSourceMatrix][1][2] + matrix[nSourceMatrix][2][2];
|
||||
if (out_z != 0)
|
||||
{
|
||||
out_x /= out_z;
|
||||
out_y /= out_z;
|
||||
}
|
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Backward(float in_x, float in_y, float &out_x, float &out_y)
|
||||
{
|
||||
out_x = in_x * matrix[3][0][0] + in_y * matrix[3][1][0] + matrix[3][2][0];
|
||||
out_y = in_x * matrix[3][0][1] + in_y * matrix[3][1][1] + matrix[3][2][1];
|
||||
float out_z = in_x * matrix[3][0][2] + in_y * matrix[3][1][2] + matrix[3][2][2];
|
||||
if (out_z != 0)
|
||||
{
|
||||
out_x /= out_z;
|
||||
out_y /= out_z;
|
||||
}
|
||||
}
|
||||
|
||||
void olc::GFX2D::Transform2D::Invert()
|
||||
{
|
||||
if (bDirty) // Obviously costly so only do if needed
|
||||
{
|
||||
float det = matrix[nSourceMatrix][0][0] * (matrix[nSourceMatrix][1][1] * matrix[nSourceMatrix][2][2] - matrix[nSourceMatrix][1][2] * matrix[nSourceMatrix][2][1]) -
|
||||
matrix[nSourceMatrix][1][0] * (matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][2][2] - matrix[nSourceMatrix][2][1] * matrix[nSourceMatrix][0][2]) +
|
||||
matrix[nSourceMatrix][2][0] * (matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][1][2] - matrix[nSourceMatrix][1][1] * matrix[nSourceMatrix][0][2]);
|
||||
|
||||
float idet = 1.0f / det;
|
||||
matrix[3][0][0] = (matrix[nSourceMatrix][1][1] * matrix[nSourceMatrix][2][2] - matrix[nSourceMatrix][1][2] * matrix[nSourceMatrix][2][1]) * idet;
|
||||
matrix[3][1][0] = (matrix[nSourceMatrix][2][0] * matrix[nSourceMatrix][1][2] - matrix[nSourceMatrix][1][0] * matrix[nSourceMatrix][2][2]) * idet;
|
||||
matrix[3][2][0] = (matrix[nSourceMatrix][1][0] * matrix[nSourceMatrix][2][1] - matrix[nSourceMatrix][2][0] * matrix[nSourceMatrix][1][1]) * idet;
|
||||
matrix[3][0][1] = (matrix[nSourceMatrix][2][1] * matrix[nSourceMatrix][0][2] - matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][2][2]) * idet;
|
||||
matrix[3][1][1] = (matrix[nSourceMatrix][0][0] * matrix[nSourceMatrix][2][2] - matrix[nSourceMatrix][2][0] * matrix[nSourceMatrix][0][2]) * idet;
|
||||
matrix[3][2][1] = (matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][2][0] - matrix[nSourceMatrix][0][0] * matrix[nSourceMatrix][2][1]) * idet;
|
||||
matrix[3][0][2] = (matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][1][2] - matrix[nSourceMatrix][0][2] * matrix[nSourceMatrix][1][1]) * idet;
|
||||
matrix[3][1][2] = (matrix[nSourceMatrix][0][2] * matrix[nSourceMatrix][1][0] - matrix[nSourceMatrix][0][0] * matrix[nSourceMatrix][1][2]) * idet;
|
||||
matrix[3][2][2] = (matrix[nSourceMatrix][0][0] * matrix[nSourceMatrix][1][1] - matrix[nSourceMatrix][0][1] * matrix[nSourceMatrix][1][0]) * idet;
|
||||
bDirty = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
#endif
|
||||
1174
Extensions/olcPGEX_Graphics3D.h
Normal file
1174
Extensions/olcPGEX_Graphics3D.h
Normal file
File diff suppressed because it is too large
Load Diff
585
Extensions/olcPGEX_PopUpMenu.h
Normal file
585
Extensions/olcPGEX_PopUpMenu.h
Normal file
@@ -0,0 +1,585 @@
|
||||
/*
|
||||
olcPGEX_PopUp.h
|
||||
|
||||
+-------------------------------------------------------------+
|
||||
| OneLoneCoder Pixel Game Engine Extension |
|
||||
| Retro PopUp Menu 1.0 |
|
||||
+-------------------------------------------------------------+
|
||||
|
||||
What is this?
|
||||
~~~~~~~~~~~~~
|
||||
This is an extension to the olcPixelGameEngine, which provides
|
||||
a quick and easy to use, flexible, skinnable context pop-up
|
||||
menu system.
|
||||
|
||||
License (OLC-3)
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Copyright 2018 - 2020 OneLoneCoder.com
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions or derivations of source code must retain the above
|
||||
copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions or derivative works in binary form must reproduce
|
||||
the above copyright notice. This list of conditions and the following
|
||||
disclaimer must be reproduced in the documentation and/or other
|
||||
materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
Links
|
||||
~~~~~
|
||||
YouTube: https://www.youtube.com/javidx9
|
||||
Discord: https://discord.gg/WhwHUMV
|
||||
Twitter: https://www.twitter.com/javidx9
|
||||
Twitch: https://www.twitch.tv/javidx9
|
||||
GitHub: https://www.github.com/onelonecoder
|
||||
Homepage: https://www.onelonecoder.com
|
||||
|
||||
Author
|
||||
~~~~~~
|
||||
David Barr, aka javidx9, ©OneLoneCoder 2019, 2020
|
||||
*/
|
||||
|
||||
|
||||
/*
|
||||
Example
|
||||
~~~~~~~
|
||||
|
||||
#define OLC_PGEX_POPUPMENU
|
||||
#include "olcPGEX_PopUpMenu.h"
|
||||
|
||||
NOTE: Requires a 9-patch sprite, by default each patch is
|
||||
8x8 pixels, patches are as follows:
|
||||
|
||||
| PANEL TL | PANEL T | PANEL TR | SCROLL UP | CURSOR TL | CURSOR TR |
|
||||
| PANEL L | PANEL M | PANEL R | SUBMENU | CURSOR BL | CURSOR BR |
|
||||
| PANEL BL | PANEL B | PANEL BR | SCROLL DOWN | UNUSED | UNUSED |
|
||||
|
||||
You can find an example sprite here:
|
||||
https://github.com/OneLoneCoder/olcPixelGameEngine/blob/master/Videos/RetroMenu.png
|
||||
|
||||
Constructing A Menu
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
// Declaration (presumably inside class)
|
||||
olc::popup::Menu m;
|
||||
|
||||
// Construction (root menu is a 1x5 table)
|
||||
m.SetTable(1, 5);
|
||||
|
||||
// Add first item to root menu (A 1x5 submenu)
|
||||
m["Menu1"].SetTable(1, 5);
|
||||
|
||||
// Add items to first item
|
||||
m["Menu1"]["Item1"];
|
||||
m["Menu1"]["Item2"];
|
||||
|
||||
// Add a 4x3 submenu
|
||||
m["Menu1"]["Item3"].SetTable(4, 3);
|
||||
m["Menu1"]["Item3"]["Option1"];
|
||||
m["Menu1"]["Item3"]["Option2"];
|
||||
|
||||
// Set properties of specific item
|
||||
m["Menu1"]["Item3"]["Option3"].Enable(false);
|
||||
m["Menu1"]["Item3"]["Option4"];
|
||||
m["Menu1"]["Item3"]["Option5"];
|
||||
m["Menu1"]["Item4"];
|
||||
|
||||
// Add second item to root menu
|
||||
m["Menu2"].SetTable(3, 3);
|
||||
m["Menu2"]["Item1"];
|
||||
m["Menu2"]["Item2"].SetID(1001).Enable(true);
|
||||
m["Menu2"]["Item3"];
|
||||
|
||||
// Construct the menu structure
|
||||
m.Build();
|
||||
|
||||
|
||||
Displaying a Menu
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
||||
// Declaration of menu manager (presumably inside class)
|
||||
olc::popup::Manager man;
|
||||
|
||||
// Set the Menu object to the MenuManager (call once per pop)
|
||||
man.Open(&m);
|
||||
|
||||
// Draw Menu at position (30, 30), using "patch sprite"
|
||||
man.Draw(sprGFX, { 30,30 });
|
||||
|
||||
|
||||
Interacting with menu
|
||||
~~~~~~~~~~~~~~~~~~~~~
|
||||
|
||||
// Send key events to menu
|
||||
if (GetKey(olc::Key::UP).bPressed) man.OnUp();
|
||||
if (GetKey(olc::Key::DOWN).bPressed) man.OnDown();
|
||||
if (GetKey(olc::Key::LEFT).bPressed) man.OnLeft();
|
||||
if (GetKey(olc::Key::RIGHT).bPressed) man.OnRight();
|
||||
if (GetKey(olc::Key::Z).bPressed) man.OnBack();
|
||||
|
||||
// "Confirm/Action" Key does something, if it returns non-null
|
||||
// then a menu item has been selected. The specific item will
|
||||
// be returned
|
||||
olc::popup::Menu* command = nullptr;
|
||||
if (GetKey(olc::Key::SPACE).bPressed) command = man.OnConfirm();
|
||||
if (command != nullptr)
|
||||
{
|
||||
std::string sLastAction =
|
||||
"Selected: " + command->GetName() +
|
||||
" ID: " + std::to_string(command->GetID());
|
||||
|
||||
// Optionally close menu?
|
||||
man.Close();
|
||||
}
|
||||
|
||||
*/
|
||||
|
||||
#ifndef OLC_PGEX_POPUPMENU_H
|
||||
#define OLC_PGEX_POPUPMENU_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace olc
|
||||
{
|
||||
namespace popup
|
||||
{
|
||||
constexpr int32_t nPatch = 8;
|
||||
|
||||
class Menu
|
||||
{
|
||||
public:
|
||||
Menu();
|
||||
Menu(const std::string n);
|
||||
|
||||
Menu& SetTable(int32_t nColumns, int32_t nRows);
|
||||
Menu& SetID(int32_t id);
|
||||
Menu& Enable(bool b);
|
||||
|
||||
int32_t GetID();
|
||||
std::string& GetName();
|
||||
bool Enabled();
|
||||
bool HasChildren();
|
||||
olc::vi2d GetSize();
|
||||
olc::vi2d& GetCursorPosition();
|
||||
Menu& operator[](const std::string& name);
|
||||
void Build();
|
||||
void DrawSelf(olc::PixelGameEngine& pge, olc::Sprite* sprGFX, olc::vi2d vScreenOffset);
|
||||
void ClampCursor();
|
||||
void OnUp();
|
||||
void OnDown();
|
||||
void OnLeft();
|
||||
void OnRight();
|
||||
Menu* OnConfirm();
|
||||
Menu* GetSelectedItem();
|
||||
|
||||
protected:
|
||||
int32_t nID = -1;
|
||||
olc::vi2d vCellTable = { 1, 0 };
|
||||
std::unordered_map<std::string, size_t> itemPointer;
|
||||
std::vector<olc::popup::Menu> items;
|
||||
olc::vi2d vSizeInPatches = { 0, 0 };
|
||||
olc::vi2d vCellSize = { 0, 0 };
|
||||
olc::vi2d vCellPadding = { 2, 0 };
|
||||
olc::vi2d vCellCursor = { 0, 0 };
|
||||
int32_t nCursorItem = 0;
|
||||
int32_t nTopVisibleRow = 0;
|
||||
int32_t nTotalRows = 0;
|
||||
const olc::vi2d vPatchSize = { nPatch, nPatch };
|
||||
std::string sName;
|
||||
olc::vi2d vCursorPos = { 0, 0 };
|
||||
bool bEnabled = true;
|
||||
};
|
||||
|
||||
class Manager : public olc::PGEX
|
||||
{
|
||||
public:
|
||||
Manager();
|
||||
void Open(Menu* mo);
|
||||
void Close();
|
||||
void OnUp();
|
||||
void OnDown();
|
||||
void OnLeft();
|
||||
void OnRight();
|
||||
void OnBack();
|
||||
Menu* OnConfirm();
|
||||
void Draw(olc::Sprite* sprGFX, olc::vi2d vScreenOffset);
|
||||
|
||||
private:
|
||||
std::list<Menu*> panels;
|
||||
};
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
#ifdef OLC_PGEX_POPUPMENU
|
||||
#undef OLC_PGEX_POPUPMENU
|
||||
|
||||
namespace olc
|
||||
{
|
||||
namespace popup
|
||||
{
|
||||
Menu::Menu()
|
||||
{
|
||||
}
|
||||
|
||||
Menu::Menu(const std::string n)
|
||||
{
|
||||
sName = n;
|
||||
}
|
||||
|
||||
|
||||
Menu& Menu::SetTable(int32_t nColumns, int32_t nRows)
|
||||
{
|
||||
vCellTable = { nColumns, nRows };
|
||||
return *this;
|
||||
}
|
||||
|
||||
Menu& Menu::SetID(int32_t id)
|
||||
{
|
||||
nID = id;
|
||||
return *this;
|
||||
}
|
||||
|
||||
Menu& Menu::Enable(bool b)
|
||||
{
|
||||
bEnabled = b;
|
||||
return *this;
|
||||
}
|
||||
|
||||
int32_t Menu::GetID()
|
||||
{
|
||||
return nID;
|
||||
}
|
||||
|
||||
std::string& Menu::GetName()
|
||||
{
|
||||
return sName;
|
||||
}
|
||||
|
||||
bool Menu::Enabled()
|
||||
{
|
||||
return bEnabled;
|
||||
}
|
||||
|
||||
bool Menu::HasChildren()
|
||||
{
|
||||
return !items.empty();
|
||||
}
|
||||
|
||||
olc::vi2d Menu::GetSize()
|
||||
{
|
||||
return { int32_t(sName.size()), 1 };
|
||||
}
|
||||
|
||||
olc::vi2d& Menu::GetCursorPosition()
|
||||
{
|
||||
return vCursorPos;
|
||||
}
|
||||
|
||||
Menu& Menu::operator[](const std::string& name)
|
||||
{
|
||||
if (itemPointer.count(name) == 0)
|
||||
{
|
||||
itemPointer[name] = items.size();
|
||||
items.push_back(Menu(name));
|
||||
}
|
||||
|
||||
return items[itemPointer[name]];
|
||||
}
|
||||
|
||||
void Menu::Build()
|
||||
{
|
||||
// Recursively build all children, so they can determine their size, use
|
||||
// that size to indicate cell sizes if this object contains more than
|
||||
// one item
|
||||
for (auto& m : items)
|
||||
{
|
||||
if (m.HasChildren())
|
||||
{
|
||||
m.Build();
|
||||
}
|
||||
|
||||
// Longest child name determines cell width
|
||||
vCellSize.x = std::max(m.GetSize().x, vCellSize.x);
|
||||
vCellSize.y = std::max(m.GetSize().y, vCellSize.y);
|
||||
}
|
||||
|
||||
// Adjust size of this object (in patches) if it were rendered as a panel
|
||||
vSizeInPatches.x = vCellTable.x * vCellSize.x + (vCellTable.x - 1) * vCellPadding.x + 2;
|
||||
vSizeInPatches.y = vCellTable.y * vCellSize.y + (vCellTable.y - 1) * vCellPadding.y + 2;
|
||||
|
||||
// Calculate how many rows this item has to hold
|
||||
nTotalRows = (items.size() / vCellTable.x) + (((items.size() % vCellTable.x) > 0) ? 1 : 0);
|
||||
}
|
||||
|
||||
void Menu::DrawSelf(olc::PixelGameEngine& pge, olc::Sprite* sprGFX, olc::vi2d vScreenOffset)
|
||||
{
|
||||
// === Draw Panel
|
||||
|
||||
// Record current pixel mode user is using
|
||||
olc::Pixel::Mode currentPixelMode = pge.GetPixelMode();
|
||||
pge.SetPixelMode(olc::Pixel::MASK);
|
||||
|
||||
// Draw Panel & Border
|
||||
olc::vi2d vPatchPos = { 0,0 };
|
||||
for (vPatchPos.x = 0; vPatchPos.x < vSizeInPatches.x; vPatchPos.x++)
|
||||
{
|
||||
for (vPatchPos.y = 0; vPatchPos.y < vSizeInPatches.y; vPatchPos.y++)
|
||||
{
|
||||
// Determine position in screen space
|
||||
olc::vi2d vScreenLocation = vPatchPos * nPatch + vScreenOffset;
|
||||
|
||||
// Calculate which patch is needed
|
||||
olc::vi2d vSourcePatch = { 0, 0 };
|
||||
if (vPatchPos.x > 0) vSourcePatch.x = 1;
|
||||
if (vPatchPos.x == vSizeInPatches.x - 1) vSourcePatch.x = 2;
|
||||
if (vPatchPos.y > 0) vSourcePatch.y = 1;
|
||||
if (vPatchPos.y == vSizeInPatches.y - 1) vSourcePatch.y = 2;
|
||||
|
||||
// Draw Actual Patch
|
||||
pge.DrawPartialSprite(vScreenLocation, sprGFX, vSourcePatch * nPatch, vPatchSize);
|
||||
}
|
||||
}
|
||||
|
||||
// === Draw Panel Contents
|
||||
olc::vi2d vCell = { 0,0 };
|
||||
vPatchPos = { 1,1 };
|
||||
|
||||
// Work out visible items
|
||||
int32_t nTopLeftItem = nTopVisibleRow * vCellTable.x;
|
||||
int32_t nBottomRightItem = vCellTable.y * vCellTable.x + nTopLeftItem;
|
||||
|
||||
// Clamp to size of child item vector
|
||||
nBottomRightItem = std::min(int32_t(items.size()), nBottomRightItem);
|
||||
int32_t nVisibleItems = nBottomRightItem - nTopLeftItem;
|
||||
|
||||
// Draw Scroll Markers (if required)
|
||||
if (nTopVisibleRow > 0)
|
||||
{
|
||||
vPatchPos = { vSizeInPatches.x - 2, 0 };
|
||||
olc::vi2d vScreenLocation = vPatchPos * nPatch + vScreenOffset;
|
||||
olc::vi2d vSourcePatch = { 3, 0 };
|
||||
pge.DrawPartialSprite(vScreenLocation, sprGFX, vSourcePatch * nPatch, vPatchSize);
|
||||
}
|
||||
|
||||
if ((nTotalRows - nTopVisibleRow) > vCellTable.y)
|
||||
{
|
||||
vPatchPos = { vSizeInPatches.x - 2, vSizeInPatches.y - 1 };
|
||||
olc::vi2d vScreenLocation = vPatchPos * nPatch + vScreenOffset;
|
||||
olc::vi2d vSourcePatch = { 3, 2 };
|
||||
pge.DrawPartialSprite(vScreenLocation, sprGFX, vSourcePatch * nPatch, vPatchSize);
|
||||
}
|
||||
|
||||
// Draw Visible Items
|
||||
for (int32_t i = 0; i < nVisibleItems; i++)
|
||||
{
|
||||
// Cell location
|
||||
vCell.x = i % vCellTable.x;
|
||||
vCell.y = i / vCellTable.x;
|
||||
|
||||
// Patch location (including border offset and padding)
|
||||
vPatchPos.x = vCell.x * (vCellSize.x + vCellPadding.x) + 1;
|
||||
vPatchPos.y = vCell.y * (vCellSize.y + vCellPadding.y) + 1;
|
||||
|
||||
// Actual screen location in pixels
|
||||
olc::vi2d vScreenLocation = vPatchPos * nPatch + vScreenOffset;
|
||||
|
||||
// Display Item Header
|
||||
pge.DrawString(vScreenLocation, items[nTopLeftItem + i].sName, items[nTopLeftItem + i].bEnabled ? olc::WHITE : olc::DARK_GREY);
|
||||
|
||||
if (items[nTopLeftItem + i].HasChildren())
|
||||
{
|
||||
// Display Indicator that panel has a sub panel
|
||||
vPatchPos.x = vCell.x * (vCellSize.x + vCellPadding.x) + 1 + vCellSize.x;
|
||||
vPatchPos.y = vCell.y * (vCellSize.y + vCellPadding.y) + 1;
|
||||
olc::vi2d vSourcePatch = { 3, 1 };
|
||||
vScreenLocation = vPatchPos * nPatch + vScreenOffset;
|
||||
pge.DrawPartialSprite(vScreenLocation, sprGFX, vSourcePatch * nPatch, vPatchSize);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate cursor position in screen space in case system draws it
|
||||
vCursorPos.x = (vCellCursor.x * (vCellSize.x + vCellPadding.x)) * nPatch + vScreenOffset.x - nPatch;
|
||||
vCursorPos.y = ((vCellCursor.y - nTopVisibleRow) * (vCellSize.y + vCellPadding.y)) * nPatch + vScreenOffset.y + nPatch;
|
||||
}
|
||||
|
||||
void Menu::ClampCursor()
|
||||
{
|
||||
// Find item in children
|
||||
nCursorItem = vCellCursor.y * vCellTable.x + vCellCursor.x;
|
||||
|
||||
// Clamp Cursor
|
||||
if (nCursorItem >= int32_t(items.size()))
|
||||
{
|
||||
vCellCursor.y = (items.size() / vCellTable.x);
|
||||
vCellCursor.x = (items.size() % vCellTable.x) - 1;
|
||||
nCursorItem = items.size() - 1;
|
||||
}
|
||||
}
|
||||
|
||||
void Menu::OnUp()
|
||||
{
|
||||
vCellCursor.y--;
|
||||
if (vCellCursor.y < 0) vCellCursor.y = 0;
|
||||
|
||||
if (vCellCursor.y < nTopVisibleRow)
|
||||
{
|
||||
nTopVisibleRow--;
|
||||
if (nTopVisibleRow < 0) nTopVisibleRow = 0;
|
||||
}
|
||||
|
||||
ClampCursor();
|
||||
}
|
||||
|
||||
void Menu::OnDown()
|
||||
{
|
||||
vCellCursor.y++;
|
||||
if (vCellCursor.y == nTotalRows) vCellCursor.y = nTotalRows - 1;
|
||||
|
||||
if (vCellCursor.y > (nTopVisibleRow + vCellTable.y - 1))
|
||||
{
|
||||
nTopVisibleRow++;
|
||||
if (nTopVisibleRow > (nTotalRows - vCellTable.y))
|
||||
nTopVisibleRow = nTotalRows - vCellTable.y;
|
||||
}
|
||||
|
||||
ClampCursor();
|
||||
}
|
||||
|
||||
void Menu::OnLeft()
|
||||
{
|
||||
vCellCursor.x--;
|
||||
if (vCellCursor.x < 0) vCellCursor.x = 0;
|
||||
ClampCursor();
|
||||
}
|
||||
|
||||
void Menu::OnRight()
|
||||
{
|
||||
vCellCursor.x++;
|
||||
if (vCellCursor.x == vCellTable.x) vCellCursor.x = vCellTable.x - 1;
|
||||
ClampCursor();
|
||||
}
|
||||
|
||||
Menu* Menu::OnConfirm()
|
||||
{
|
||||
// Check if selected item has children
|
||||
if (items[nCursorItem].HasChildren())
|
||||
{
|
||||
return &items[nCursorItem];
|
||||
}
|
||||
else
|
||||
return this;
|
||||
}
|
||||
|
||||
Menu* Menu::GetSelectedItem()
|
||||
{
|
||||
return &items[nCursorItem];
|
||||
}
|
||||
|
||||
// =====================================================================
|
||||
|
||||
Manager::Manager()
|
||||
{
|
||||
}
|
||||
|
||||
void Manager::Open(Menu* mo)
|
||||
{
|
||||
Close();
|
||||
panels.push_back(mo);
|
||||
}
|
||||
|
||||
void Manager::Close()
|
||||
{
|
||||
panels.clear();
|
||||
}
|
||||
|
||||
void Manager::OnUp()
|
||||
{
|
||||
if (!panels.empty()) panels.back()->OnUp();
|
||||
}
|
||||
|
||||
void Manager::OnDown()
|
||||
{
|
||||
if (!panels.empty()) panels.back()->OnDown();
|
||||
}
|
||||
|
||||
void Manager::OnLeft()
|
||||
{
|
||||
if (!panels.empty()) panels.back()->OnLeft();
|
||||
}
|
||||
|
||||
void Manager::OnRight()
|
||||
{
|
||||
if (!panels.empty()) panels.back()->OnRight();
|
||||
}
|
||||
|
||||
void Manager::OnBack()
|
||||
{
|
||||
if (!panels.empty()) panels.pop_back();
|
||||
}
|
||||
|
||||
Menu* Manager::OnConfirm()
|
||||
{
|
||||
if (panels.empty()) return nullptr;
|
||||
|
||||
Menu* next = panels.back()->OnConfirm();
|
||||
if (next == panels.back())
|
||||
{
|
||||
if (panels.back()->GetSelectedItem()->Enabled())
|
||||
return panels.back()->GetSelectedItem();
|
||||
}
|
||||
else
|
||||
{
|
||||
if (next->Enabled())
|
||||
panels.push_back(next);
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void Manager::Draw(olc::Sprite* sprGFX, olc::vi2d vScreenOffset)
|
||||
{
|
||||
if (panels.empty()) return;
|
||||
|
||||
// Draw Visible Menu System
|
||||
for (auto& p : panels)
|
||||
{
|
||||
p->DrawSelf(*pge, sprGFX, vScreenOffset);
|
||||
vScreenOffset += {10, 10};
|
||||
}
|
||||
|
||||
// Draw Cursor
|
||||
olc::Pixel::Mode currentPixelMode = pge->GetPixelMode();
|
||||
pge->SetPixelMode(olc::Pixel::ALPHA);
|
||||
pge->DrawPartialSprite(panels.back()->GetCursorPosition(), sprGFX, olc::vi2d(4, 0) * nPatch, { nPatch * 2, nPatch * 2 });
|
||||
pge->SetPixelMode(currentPixelMode);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
#endif
|
||||
#endif
|
||||
892
Extensions/olcPGEX_Sound.h
Normal file
892
Extensions/olcPGEX_Sound.h
Normal file
@@ -0,0 +1,892 @@
|
||||
/*
|
||||
olcPGEX_Sound.h
|
||||
|
||||
+-------------------------------------------------------------+
|
||||
| OneLoneCoder Pixel Game Engine Extension |
|
||||
| Sound - v0.3 |
|
||||
+-------------------------------------------------------------+
|
||||
|
||||
What is this?
|
||||
~~~~~~~~~~~~~
|
||||
This is an extension to the olcPixelGameEngine, which provides
|
||||
sound generation and wave playing routines.
|
||||
|
||||
Special Thanks:
|
||||
~~~~~~~~~~~~~~~
|
||||
Slavka - For entire non-windows system back end!
|
||||
Gorbit99 - Testing, Bug Fixes
|
||||
Cyberdroid - Testing, Bug Fixes
|
||||
Dragoneye - Testing
|
||||
Puol - Testing
|
||||
|
||||
License (OLC-3)
|
||||
~~~~~~~~~~~~~~~
|
||||
|
||||
Copyright 2018 - 2019 OneLoneCoder.com
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions
|
||||
are met:
|
||||
|
||||
1. Redistributions or derivations of source code must retain the above
|
||||
copyright notice, this list of conditions and the following disclaimer.
|
||||
|
||||
2. Redistributions or derivative works in binary form must reproduce
|
||||
the above copyright notice. This list of conditions and the following
|
||||
disclaimer must be reproduced in the documentation and/or other
|
||||
materials provided with the distribution.
|
||||
|
||||
3. Neither the name of the copyright holder nor the names of its
|
||||
contributors may be used to endorse or promote products derived
|
||||
from this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
Links
|
||||
~~~~~
|
||||
YouTube: https://www.youtube.com/javidx9
|
||||
Discord: https://discord.gg/WhwHUMV
|
||||
Twitter: https://www.twitter.com/javidx9
|
||||
Twitch: https://www.twitch.tv/javidx9
|
||||
GitHub: https://www.github.com/onelonecoder
|
||||
Homepage: https://www.onelonecoder.com
|
||||
Patreon: https://www.patreon.com/javidx9
|
||||
|
||||
Author
|
||||
~~~~~~
|
||||
David Barr, aka javidx9, ©OneLoneCoder 2019
|
||||
*/
|
||||
|
||||
|
||||
#ifndef OLC_PGEX_SOUND_H
|
||||
#define OLC_PGEX_SOUND_H
|
||||
|
||||
#include <istream>
|
||||
#include <cstring>
|
||||
#include <climits>
|
||||
|
||||
#include <algorithm>
|
||||
#undef min
|
||||
#undef max
|
||||
|
||||
// Choose a default sound backend
|
||||
#if !defined(USE_ALSA) && !defined(USE_OPENAL) && !defined(USE_WINDOWS)
|
||||
#ifdef __linux__
|
||||
#define USE_ALSA
|
||||
#endif
|
||||
|
||||
#ifdef __EMSCRIPTEN__
|
||||
#define USE_OPENAL
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
#define USE_WINDOWS
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
#ifdef USE_ALSA
|
||||
#define ALSA_PCM_NEW_HW_PARAMS_API
|
||||
#include <alsa/asoundlib.h>
|
||||
#endif
|
||||
|
||||
#ifdef USE_OPENAL
|
||||
#include <AL/al.h>
|
||||
#include <AL/alc.h>
|
||||
#include <queue>
|
||||
#endif
|
||||
|
||||
#pragma pack(push, 1)
|
||||
typedef struct {
|
||||
uint16_t wFormatTag;
|
||||
uint16_t nChannels;
|
||||
uint32_t nSamplesPerSec;
|
||||
uint32_t nAvgBytesPerSec;
|
||||
uint16_t nBlockAlign;
|
||||
uint16_t wBitsPerSample;
|
||||
uint16_t cbSize;
|
||||
} OLC_WAVEFORMATEX;
|
||||
#pragma pack(pop)
|
||||
|
||||
namespace olc
|
||||
{
|
||||
// Container class for Advanced 2D Drawing functions
|
||||
class SOUND : public olc::PGEX
|
||||
{
|
||||
// A representation of an affine transform, used to rotate, scale, offset & shear space
|
||||
public:
|
||||
class AudioSample
|
||||
{
|
||||
public:
|
||||
AudioSample();
|
||||
AudioSample(std::string sWavFile, olc::ResourcePack *pack = nullptr);
|
||||
olc::rcode LoadFromFile(std::string sWavFile, olc::ResourcePack *pack = nullptr);
|
||||
|
||||
public:
|
||||
OLC_WAVEFORMATEX wavHeader;
|
||||
float *fSample = nullptr;
|
||||
long nSamples = 0;
|
||||
int nChannels = 0;
|
||||
bool bSampleValid = false;
|
||||
};
|
||||
|
||||
struct sCurrentlyPlayingSample
|
||||
{
|
||||
int nAudioSampleID = 0;
|
||||
long nSamplePosition = 0;
|
||||
bool bFinished = false;
|
||||
bool bLoop = false;
|
||||
bool bFlagForStop = false;
|
||||
};
|
||||
|
||||
static std::list<sCurrentlyPlayingSample> listActiveSamples;
|
||||
|
||||
public:
|
||||
static bool InitialiseAudio(unsigned int nSampleRate = 44100, unsigned int nChannels = 1, unsigned int nBlocks = 8, unsigned int nBlockSamples = 512);
|
||||
static bool DestroyAudio();
|
||||
static void SetUserSynthFunction(std::function<float(int, float, float)> func);
|
||||
static void SetUserFilterFunction(std::function<float(int, float, float)> func);
|
||||
|
||||
public:
|
||||
static int LoadAudioSample(std::string sWavFile, olc::ResourcePack *pack = nullptr);
|
||||
static void PlaySample(int id, bool bLoop = false);
|
||||
static void StopSample(int id);
|
||||
static void StopAll();
|
||||
static float GetMixerOutput(int nChannel, float fGlobalTime, float fTimeStep);
|
||||
|
||||
|
||||
private:
|
||||
#ifdef USE_WINDOWS // Windows specific sound management
|
||||
static void CALLBACK waveOutProc(HWAVEOUT hWaveOut, UINT uMsg, DWORD dwParam1, DWORD dwParam2);
|
||||
static unsigned int m_nSampleRate;
|
||||
static unsigned int m_nChannels;
|
||||
static unsigned int m_nBlockCount;
|
||||
static unsigned int m_nBlockSamples;
|
||||
static unsigned int m_nBlockCurrent;
|
||||
static short* m_pBlockMemory;
|
||||
static WAVEHDR *m_pWaveHeaders;
|
||||
static HWAVEOUT m_hwDevice;
|
||||
static std::atomic<unsigned int> m_nBlockFree;
|
||||
static std::condition_variable m_cvBlockNotZero;
|
||||
static std::mutex m_muxBlockNotZero;
|
||||
#endif
|
||||
|
||||
#ifdef USE_ALSA
|
||||
static snd_pcm_t *m_pPCM;
|
||||
static unsigned int m_nSampleRate;
|
||||
static unsigned int m_nChannels;
|
||||
static unsigned int m_nBlockSamples;
|
||||
static short* m_pBlockMemory;
|
||||
#endif
|
||||
|
||||
#ifdef USE_OPENAL
|
||||
static std::queue<ALuint> m_qAvailableBuffers;
|
||||
static ALuint *m_pBuffers;
|
||||
static ALuint m_nSource;
|
||||
static ALCdevice *m_pDevice;
|
||||
static ALCcontext *m_pContext;
|
||||
static unsigned int m_nSampleRate;
|
||||
static unsigned int m_nChannels;
|
||||
static unsigned int m_nBlockCount;
|
||||
static unsigned int m_nBlockSamples;
|
||||
static short* m_pBlockMemory;
|
||||
#endif
|
||||
|
||||
static void AudioThread();
|
||||
static std::thread m_AudioThread;
|
||||
static std::atomic<bool> m_bAudioThreadActive;
|
||||
static std::atomic<float> m_fGlobalTime;
|
||||
static std::function<float(int, float, float)> funcUserSynth;
|
||||
static std::function<float(int, float, float)> funcUserFilter;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
// Implementation, platform-independent
|
||||
|
||||
#ifdef OLC_PGEX_SOUND
|
||||
#undef OLC_PGEX_SOUND
|
||||
|
||||
namespace olc
|
||||
{
|
||||
SOUND::AudioSample::AudioSample()
|
||||
{ }
|
||||
|
||||
SOUND::AudioSample::AudioSample(std::string sWavFile, olc::ResourcePack *pack)
|
||||
{
|
||||
LoadFromFile(sWavFile, pack);
|
||||
}
|
||||
|
||||
olc::rcode SOUND::AudioSample::LoadFromFile(std::string sWavFile, olc::ResourcePack *pack)
|
||||
{
|
||||
auto ReadWave = [&](std::istream &is)
|
||||
{
|
||||
char dump[4];
|
||||
is.read(dump, sizeof(char) * 4); // Read "RIFF"
|
||||
if (strncmp(dump, "RIFF", 4) != 0) return olc::FAIL;
|
||||
is.read(dump, sizeof(char) * 4); // Not Interested
|
||||
is.read(dump, sizeof(char) * 4); // Read "WAVE"
|
||||
if (strncmp(dump, "WAVE", 4) != 0) return olc::FAIL;
|
||||
|
||||
// Read Wave description chunk
|
||||
is.read(dump, sizeof(char) * 4); // Read "fmt "
|
||||
unsigned int nHeaderSize = 0;
|
||||
is.read((char*)&nHeaderSize, sizeof(unsigned int)); // Not Interested
|
||||
is.read((char*)&wavHeader, nHeaderSize);// sizeof(WAVEFORMATEX)); // Read Wave Format Structure chunk
|
||||
// Note the -2, because the structure has 2 bytes to indicate its own size
|
||||
// which are not in the wav file
|
||||
|
||||
// Just check if wave format is compatible with olcPGE
|
||||
if (wavHeader.wBitsPerSample != 16 || wavHeader.nSamplesPerSec != 44100)
|
||||
return olc::FAIL;
|
||||
|
||||
// Search for audio data chunk
|
||||
uint32_t nChunksize = 0;
|
||||
is.read(dump, sizeof(char) * 4); // Read chunk header
|
||||
is.read((char*)&nChunksize, sizeof(uint32_t)); // Read chunk size
|
||||
while (strncmp(dump, "data", 4) != 0)
|
||||
{
|
||||
// Not audio data, so just skip it
|
||||
//std::fseek(f, nChunksize, SEEK_CUR);
|
||||
is.seekg(nChunksize, std::istream::cur);
|
||||
is.read(dump, sizeof(char) * 4);
|
||||
is.read((char*)&nChunksize, sizeof(uint32_t));
|
||||
}
|
||||
|
||||
// Finally got to data, so read it all in and convert to float samples
|
||||
nSamples = nChunksize / (wavHeader.nChannels * (wavHeader.wBitsPerSample >> 3));
|
||||
nChannels = wavHeader.nChannels;
|
||||
|
||||
// Create floating point buffer to hold audio sample
|
||||
fSample = new float[nSamples * nChannels];
|
||||
float *pSample = fSample;
|
||||
|
||||
// Read in audio data and normalise
|
||||
for (long i = 0; i < nSamples; i++)
|
||||
{
|
||||
for (int c = 0; c < nChannels; c++)
|
||||
{
|
||||
short s = 0;
|
||||
if (!is.eof())
|
||||
{
|
||||
is.read((char*)&s, sizeof(short));
|
||||
|
||||
*pSample = (float)s / (float)(SHRT_MAX);
|
||||
pSample++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// All done, flag sound as valid
|
||||
bSampleValid = true;
|
||||
return olc::OK;
|
||||
};
|
||||
|
||||
if (pack != nullptr)
|
||||
{
|
||||
olc::ResourcePack::sEntry entry = pack->GetStreamBuffer(sWavFile);
|
||||
std::istream is(&entry);
|
||||
return ReadWave(is);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Read from file
|
||||
std::ifstream ifs(sWavFile, std::ifstream::binary);
|
||||
if (ifs.is_open())
|
||||
{
|
||||
return ReadWave(ifs);
|
||||
}
|
||||
else
|
||||
return olc::FAIL;
|
||||
}
|
||||
}
|
||||
|
||||
// This vector holds all loaded sound samples in memory
|
||||
std::vector<olc::SOUND::AudioSample> vecAudioSamples;
|
||||
|
||||
// This structure represents a sound that is currently playing. It only
|
||||
// holds the sound ID and where this instance of it is up to for its
|
||||
// current playback
|
||||
|
||||
void SOUND::SetUserSynthFunction(std::function<float(int, float, float)> func)
|
||||
{
|
||||
funcUserSynth = func;
|
||||
}
|
||||
|
||||
void SOUND::SetUserFilterFunction(std::function<float(int, float, float)> func)
|
||||
{
|
||||
funcUserFilter = func;
|
||||
}
|
||||
|
||||
// Load a 16-bit WAVE file @ 44100Hz ONLY into memory. A sample ID
|
||||
// number is returned if successful, otherwise -1
|
||||
int SOUND::LoadAudioSample(std::string sWavFile, olc::ResourcePack *pack)
|
||||
{
|
||||
|
||||
olc::SOUND::AudioSample a(sWavFile, pack);
|
||||
if (a.bSampleValid)
|
||||
{
|
||||
vecAudioSamples.push_back(a);
|
||||
return (unsigned int)vecAudioSamples.size();
|
||||
}
|
||||
else
|
||||
return -1;
|
||||
}
|
||||
|
||||
// Add sample 'id' to the mixers sounds to play list
|
||||
void SOUND::PlaySample(int id, bool bLoop)
|
||||
{
|
||||
olc::SOUND::sCurrentlyPlayingSample a;
|
||||
a.nAudioSampleID = id;
|
||||
a.nSamplePosition = 0;
|
||||
a.bFinished = false;
|
||||
a.bFlagForStop = false;
|
||||
a.bLoop = bLoop;
|
||||
SOUND::listActiveSamples.push_back(a);
|
||||
}
|
||||
|
||||
void SOUND::StopSample(int id)
|
||||
{
|
||||
// Find first occurence of sample id
|
||||
auto s = std::find_if(listActiveSamples.begin(), listActiveSamples.end(), [&](const olc::SOUND::sCurrentlyPlayingSample &s) { return s.nAudioSampleID == id; });
|
||||
if (s != listActiveSamples.end())
|
||||
s->bFlagForStop = true;
|
||||
}
|
||||
|
||||
void SOUND::StopAll()
|
||||
{
|
||||
for (auto &s : listActiveSamples)
|
||||
{
|
||||
s.bFlagForStop = true;
|
||||
}
|
||||
}
|
||||
|
||||
float SOUND::GetMixerOutput(int nChannel, float fGlobalTime, float fTimeStep)
|
||||
{
|
||||
// Accumulate sample for this channel
|
||||
float fMixerSample = 0.0f;
|
||||
|
||||
for (auto &s : listActiveSamples)
|
||||
{
|
||||
if (m_bAudioThreadActive)
|
||||
{
|
||||
if (s.bFlagForStop)
|
||||
{
|
||||
s.bLoop = false;
|
||||
s.bFinished = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Calculate sample position
|
||||
s.nSamplePosition += roundf((float)vecAudioSamples[s.nAudioSampleID - 1].wavHeader.nSamplesPerSec * fTimeStep);
|
||||
|
||||
// If sample position is valid add to the mix
|
||||
if (s.nSamplePosition < vecAudioSamples[s.nAudioSampleID - 1].nSamples)
|
||||
fMixerSample += vecAudioSamples[s.nAudioSampleID - 1].fSample[(s.nSamplePosition * vecAudioSamples[s.nAudioSampleID - 1].nChannels) + nChannel];
|
||||
else
|
||||
{
|
||||
if (s.bLoop)
|
||||
{
|
||||
s.nSamplePosition = 0;
|
||||
}
|
||||
else
|
||||
s.bFinished = true; // Else sound has completed
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
// If sounds have completed then remove them
|
||||
listActiveSamples.remove_if([](const sCurrentlyPlayingSample &s) {return s.bFinished; });
|
||||
|
||||
// The users application might be generating sound, so grab that if it exists
|
||||
if (funcUserSynth != nullptr)
|
||||
fMixerSample += funcUserSynth(nChannel, fGlobalTime, fTimeStep);
|
||||
|
||||
// Return the sample via an optional user override to filter the sound
|
||||
if (funcUserFilter != nullptr)
|
||||
return funcUserFilter(nChannel, fGlobalTime, fMixerSample);
|
||||
else
|
||||
return fMixerSample;
|
||||
}
|
||||
|
||||
std::thread SOUND::m_AudioThread;
|
||||
std::atomic<bool> SOUND::m_bAudioThreadActive{ false };
|
||||
std::atomic<float> SOUND::m_fGlobalTime{ 0.0f };
|
||||
std::list<SOUND::sCurrentlyPlayingSample> SOUND::listActiveSamples;
|
||||
std::function<float(int, float, float)> SOUND::funcUserSynth = nullptr;
|
||||
std::function<float(int, float, float)> SOUND::funcUserFilter = nullptr;
|
||||
}
|
||||
|
||||
// Implementation, Windows-specific
|
||||
#ifdef USE_WINDOWS
|
||||
#pragma comment(lib, "winmm.lib")
|
||||
|
||||
namespace olc
|
||||
{
|
||||
bool SOUND::InitialiseAudio(unsigned int nSampleRate, unsigned int nChannels, unsigned int nBlocks, unsigned int nBlockSamples)
|
||||
{
|
||||
// Initialise Sound Engine
|
||||
m_bAudioThreadActive = false;
|
||||
m_nSampleRate = nSampleRate;
|
||||
m_nChannels = nChannels;
|
||||
m_nBlockCount = nBlocks;
|
||||
m_nBlockSamples = nBlockSamples;
|
||||
m_nBlockFree = m_nBlockCount;
|
||||
m_nBlockCurrent = 0;
|
||||
m_pBlockMemory = nullptr;
|
||||
m_pWaveHeaders = nullptr;
|
||||
|
||||
// Device is available
|
||||
WAVEFORMATEX waveFormat;
|
||||
waveFormat.wFormatTag = WAVE_FORMAT_PCM;
|
||||
waveFormat.nSamplesPerSec = m_nSampleRate;
|
||||
waveFormat.wBitsPerSample = sizeof(short) * 8;
|
||||
waveFormat.nChannels = m_nChannels;
|
||||
waveFormat.nBlockAlign = (waveFormat.wBitsPerSample / 8) * waveFormat.nChannels;
|
||||
waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
|
||||
waveFormat.cbSize = 0;
|
||||
|
||||
listActiveSamples.clear();
|
||||
|
||||
// Open Device if valid
|
||||
if (waveOutOpen(&m_hwDevice, WAVE_MAPPER, &waveFormat, (DWORD_PTR)SOUND::waveOutProc, (DWORD_PTR)0, CALLBACK_FUNCTION) != S_OK)
|
||||
return DestroyAudio();
|
||||
|
||||
// Allocate Wave|Block Memory
|
||||
m_pBlockMemory = new short[m_nBlockCount * m_nBlockSamples];
|
||||
if (m_pBlockMemory == nullptr)
|
||||
return DestroyAudio();
|
||||
ZeroMemory(m_pBlockMemory, sizeof(short) * m_nBlockCount * m_nBlockSamples);
|
||||
|
||||
m_pWaveHeaders = new WAVEHDR[m_nBlockCount];
|
||||
if (m_pWaveHeaders == nullptr)
|
||||
return DestroyAudio();
|
||||
ZeroMemory(m_pWaveHeaders, sizeof(WAVEHDR) * m_nBlockCount);
|
||||
|
||||
// Link headers to block memory
|
||||
for (unsigned int n = 0; n < m_nBlockCount; n++)
|
||||
{
|
||||
m_pWaveHeaders[n].dwBufferLength = m_nBlockSamples * sizeof(short);
|
||||
m_pWaveHeaders[n].lpData = (LPSTR)(m_pBlockMemory + (n * m_nBlockSamples));
|
||||
}
|
||||
|
||||
m_bAudioThreadActive = true;
|
||||
m_AudioThread = std::thread(&SOUND::AudioThread);
|
||||
|
||||
// Start the ball rolling with the sound delivery thread
|
||||
std::unique_lock<std::mutex> lm(m_muxBlockNotZero);
|
||||
m_cvBlockNotZero.notify_one();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Stop and clean up audio system
|
||||
bool SOUND::DestroyAudio()
|
||||
{
|
||||
m_bAudioThreadActive = false;
|
||||
m_AudioThread.join();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Handler for soundcard request for more data
|
||||
void CALLBACK SOUND::waveOutProc(HWAVEOUT hWaveOut, UINT uMsg, DWORD dwParam1, DWORD dwParam2)
|
||||
{
|
||||
if (uMsg != WOM_DONE) return;
|
||||
m_nBlockFree++;
|
||||
std::unique_lock<std::mutex> lm(m_muxBlockNotZero);
|
||||
m_cvBlockNotZero.notify_one();
|
||||
}
|
||||
|
||||
// Audio thread. This loop responds to requests from the soundcard to fill 'blocks'
|
||||
// with audio data. If no requests are available it goes dormant until the sound
|
||||
// card is ready for more data. The block is fille by the "user" in some manner
|
||||
// and then issued to the soundcard.
|
||||
void SOUND::AudioThread()
|
||||
{
|
||||
m_fGlobalTime = 0.0f;
|
||||
static float fTimeStep = 1.0f / (float)m_nSampleRate;
|
||||
|
||||
// Goofy hack to get maximum integer for a type at run-time
|
||||
short nMaxSample = (short)pow(2, (sizeof(short) * 8) - 1) - 1;
|
||||
float fMaxSample = (float)nMaxSample;
|
||||
short nPreviousSample = 0;
|
||||
|
||||
while (m_bAudioThreadActive)
|
||||
{
|
||||
// Wait for block to become available
|
||||
if (m_nBlockFree == 0)
|
||||
{
|
||||
std::unique_lock<std::mutex> lm(m_muxBlockNotZero);
|
||||
while (m_nBlockFree == 0) // sometimes, Windows signals incorrectly
|
||||
m_cvBlockNotZero.wait(lm);
|
||||
}
|
||||
|
||||
// Block is here, so use it
|
||||
m_nBlockFree--;
|
||||
|
||||
// Prepare block for processing
|
||||
if (m_pWaveHeaders[m_nBlockCurrent].dwFlags & WHDR_PREPARED)
|
||||
waveOutUnprepareHeader(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR));
|
||||
|
||||
short nNewSample = 0;
|
||||
int nCurrentBlock = m_nBlockCurrent * m_nBlockSamples;
|
||||
|
||||
auto clip = [](float fSample, float fMax)
|
||||
{
|
||||
if (fSample >= 0.0)
|
||||
return fmin(fSample, fMax);
|
||||
else
|
||||
return fmax(fSample, -fMax);
|
||||
};
|
||||
|
||||
for (unsigned int n = 0; n < m_nBlockSamples; n += m_nChannels)
|
||||
{
|
||||
// User Process
|
||||
for (unsigned int c = 0; c < m_nChannels; c++)
|
||||
{
|
||||
nNewSample = (short)(clip(GetMixerOutput(c, m_fGlobalTime, fTimeStep), 1.0) * fMaxSample);
|
||||
m_pBlockMemory[nCurrentBlock + n + c] = nNewSample;
|
||||
nPreviousSample = nNewSample;
|
||||
}
|
||||
|
||||
m_fGlobalTime = m_fGlobalTime + fTimeStep;
|
||||
}
|
||||
|
||||
// Send block to sound device
|
||||
waveOutPrepareHeader(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR));
|
||||
waveOutWrite(m_hwDevice, &m_pWaveHeaders[m_nBlockCurrent], sizeof(WAVEHDR));
|
||||
m_nBlockCurrent++;
|
||||
m_nBlockCurrent %= m_nBlockCount;
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int SOUND::m_nSampleRate = 0;
|
||||
unsigned int SOUND::m_nChannels = 0;
|
||||
unsigned int SOUND::m_nBlockCount = 0;
|
||||
unsigned int SOUND::m_nBlockSamples = 0;
|
||||
unsigned int SOUND::m_nBlockCurrent = 0;
|
||||
short* SOUND::m_pBlockMemory = nullptr;
|
||||
WAVEHDR *SOUND::m_pWaveHeaders = nullptr;
|
||||
HWAVEOUT SOUND::m_hwDevice;
|
||||
std::atomic<unsigned int> SOUND::m_nBlockFree = 0;
|
||||
std::condition_variable SOUND::m_cvBlockNotZero;
|
||||
std::mutex SOUND::m_muxBlockNotZero;
|
||||
}
|
||||
|
||||
#elif defined(USE_ALSA)
|
||||
|
||||
namespace olc
|
||||
{
|
||||
bool SOUND::InitialiseAudio(unsigned int nSampleRate, unsigned int nChannels, unsigned int nBlocks, unsigned int nBlockSamples)
|
||||
{
|
||||
// Initialise Sound Engine
|
||||
m_bAudioThreadActive = false;
|
||||
m_nSampleRate = nSampleRate;
|
||||
m_nChannels = nChannels;
|
||||
m_nBlockSamples = nBlockSamples;
|
||||
m_pBlockMemory = nullptr;
|
||||
|
||||
// Open PCM stream
|
||||
int rc = snd_pcm_open(&m_pPCM, "default", SND_PCM_STREAM_PLAYBACK, 0);
|
||||
if (rc < 0)
|
||||
return DestroyAudio();
|
||||
|
||||
|
||||
// Prepare the parameter structure and set default parameters
|
||||
snd_pcm_hw_params_t *params;
|
||||
snd_pcm_hw_params_alloca(¶ms);
|
||||
snd_pcm_hw_params_any(m_pPCM, params);
|
||||
|
||||
// Set other parameters
|
||||
snd_pcm_hw_params_set_format(m_pPCM, params, SND_PCM_FORMAT_S16_LE);
|
||||
snd_pcm_hw_params_set_rate(m_pPCM, params, m_nSampleRate, 0);
|
||||
snd_pcm_hw_params_set_channels(m_pPCM, params, m_nChannels);
|
||||
snd_pcm_hw_params_set_period_size(m_pPCM, params, m_nBlockSamples, 0);
|
||||
snd_pcm_hw_params_set_periods(m_pPCM, params, nBlocks, 0);
|
||||
|
||||
// Save these parameters
|
||||
rc = snd_pcm_hw_params(m_pPCM, params);
|
||||
if (rc < 0)
|
||||
return DestroyAudio();
|
||||
|
||||
listActiveSamples.clear();
|
||||
|
||||
// Allocate Wave|Block Memory
|
||||
m_pBlockMemory = new short[m_nBlockSamples];
|
||||
if (m_pBlockMemory == nullptr)
|
||||
return DestroyAudio();
|
||||
std::fill(m_pBlockMemory, m_pBlockMemory + m_nBlockSamples, 0);
|
||||
|
||||
// Unsure if really needed, helped prevent underrun on my setup
|
||||
snd_pcm_start(m_pPCM);
|
||||
for (unsigned int i = 0; i < nBlocks; i++)
|
||||
rc = snd_pcm_writei(m_pPCM, m_pBlockMemory, 512);
|
||||
|
||||
snd_pcm_start(m_pPCM);
|
||||
m_bAudioThreadActive = true;
|
||||
m_AudioThread = std::thread(&SOUND::AudioThread);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Stop and clean up audio system
|
||||
bool SOUND::DestroyAudio()
|
||||
{
|
||||
m_bAudioThreadActive = false;
|
||||
m_AudioThread.join();
|
||||
snd_pcm_drain(m_pPCM);
|
||||
snd_pcm_close(m_pPCM);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Audio thread. This loop responds to requests from the soundcard to fill 'blocks'
|
||||
// with audio data. If no requests are available it goes dormant until the sound
|
||||
// card is ready for more data. The block is fille by the "user" in some manner
|
||||
// and then issued to the soundcard.
|
||||
void SOUND::AudioThread()
|
||||
{
|
||||
m_fGlobalTime = 0.0f;
|
||||
static float fTimeStep = 1.0f / (float)m_nSampleRate;
|
||||
|
||||
// Goofy hack to get maximum integer for a type at run-time
|
||||
short nMaxSample = (short)pow(2, (sizeof(short) * 8) - 1) - 1;
|
||||
float fMaxSample = (float)nMaxSample;
|
||||
short nPreviousSample = 0;
|
||||
|
||||
while (m_bAudioThreadActive)
|
||||
{
|
||||
short nNewSample = 0;
|
||||
|
||||
auto clip = [](float fSample, float fMax)
|
||||
{
|
||||
if (fSample >= 0.0)
|
||||
return fmin(fSample, fMax);
|
||||
else
|
||||
return fmax(fSample, -fMax);
|
||||
};
|
||||
|
||||
for (unsigned int n = 0; n < m_nBlockSamples; n += m_nChannels)
|
||||
{
|
||||
// User Process
|
||||
for (unsigned int c = 0; c < m_nChannels; c++)
|
||||
{
|
||||
nNewSample = (short)(clip(GetMixerOutput(c, m_fGlobalTime, fTimeStep), 1.0) * fMaxSample);
|
||||
m_pBlockMemory[n + c] = nNewSample;
|
||||
nPreviousSample = nNewSample;
|
||||
}
|
||||
|
||||
m_fGlobalTime = m_fGlobalTime + fTimeStep;
|
||||
}
|
||||
|
||||
// Send block to sound device
|
||||
snd_pcm_uframes_t nLeft = m_nBlockSamples;
|
||||
short *pBlockPos = m_pBlockMemory;
|
||||
while (nLeft > 0)
|
||||
{
|
||||
int rc = snd_pcm_writei(m_pPCM, pBlockPos, nLeft);
|
||||
if (rc > 0)
|
||||
{
|
||||
pBlockPos += rc * m_nChannels;
|
||||
nLeft -= rc;
|
||||
}
|
||||
if (rc == -EAGAIN) continue;
|
||||
if (rc == -EPIPE) // an underrun occured, prepare the device for more data
|
||||
snd_pcm_prepare(m_pPCM);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
snd_pcm_t* SOUND::m_pPCM = nullptr;
|
||||
unsigned int SOUND::m_nSampleRate = 0;
|
||||
unsigned int SOUND::m_nChannels = 0;
|
||||
unsigned int SOUND::m_nBlockSamples = 0;
|
||||
short* SOUND::m_pBlockMemory = nullptr;
|
||||
}
|
||||
|
||||
#elif defined(USE_OPENAL)
|
||||
|
||||
namespace olc
|
||||
{
|
||||
bool SOUND::InitialiseAudio(unsigned int nSampleRate, unsigned int nChannels, unsigned int nBlocks, unsigned int nBlockSamples)
|
||||
{
|
||||
// Initialise Sound Engine
|
||||
m_bAudioThreadActive = false;
|
||||
m_nSampleRate = nSampleRate;
|
||||
m_nChannels = nChannels;
|
||||
m_nBlockCount = nBlocks;
|
||||
m_nBlockSamples = nBlockSamples;
|
||||
m_pBlockMemory = nullptr;
|
||||
|
||||
// Open the device and create the context
|
||||
m_pDevice = alcOpenDevice(NULL);
|
||||
if (m_pDevice)
|
||||
{
|
||||
m_pContext = alcCreateContext(m_pDevice, NULL);
|
||||
alcMakeContextCurrent(m_pContext);
|
||||
}
|
||||
else
|
||||
return DestroyAudio();
|
||||
|
||||
// Allocate memory for sound data
|
||||
alGetError();
|
||||
m_pBuffers = new ALuint[m_nBlockCount];
|
||||
alGenBuffers(m_nBlockCount, m_pBuffers);
|
||||
alGenSources(1, &m_nSource);
|
||||
|
||||
for (unsigned int i = 0; i < m_nBlockCount; i++)
|
||||
m_qAvailableBuffers.push(m_pBuffers[i]);
|
||||
|
||||
listActiveSamples.clear();
|
||||
|
||||
// Allocate Wave|Block Memory
|
||||
m_pBlockMemory = new short[m_nBlockSamples];
|
||||
if (m_pBlockMemory == nullptr)
|
||||
return DestroyAudio();
|
||||
std::fill(m_pBlockMemory, m_pBlockMemory + m_nBlockSamples, 0);
|
||||
|
||||
m_bAudioThreadActive = true;
|
||||
m_AudioThread = std::thread(&SOUND::AudioThread);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Stop and clean up audio system
|
||||
bool SOUND::DestroyAudio()
|
||||
{
|
||||
m_bAudioThreadActive = false;
|
||||
m_AudioThread.join();
|
||||
|
||||
alDeleteBuffers(m_nBlockCount, m_pBuffers);
|
||||
delete[] m_pBuffers;
|
||||
alDeleteSources(1, &m_nSource);
|
||||
|
||||
alcMakeContextCurrent(NULL);
|
||||
alcDestroyContext(m_pContext);
|
||||
alcCloseDevice(m_pDevice);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Audio thread. This loop responds to requests from the soundcard to fill 'blocks'
|
||||
// with audio data. If no requests are available it goes dormant until the sound
|
||||
// card is ready for more data. The block is fille by the "user" in some manner
|
||||
// and then issued to the soundcard.
|
||||
void SOUND::AudioThread()
|
||||
{
|
||||
m_fGlobalTime = 0.0f;
|
||||
static float fTimeStep = 1.0f / (float)m_nSampleRate;
|
||||
|
||||
// Goofy hack to get maximum integer for a type at run-time
|
||||
short nMaxSample = (short)pow(2, (sizeof(short) * 8) - 1) - 1;
|
||||
float fMaxSample = (float)nMaxSample;
|
||||
short nPreviousSample = 0;
|
||||
|
||||
std::vector<ALuint> vProcessed;
|
||||
|
||||
while (m_bAudioThreadActive)
|
||||
{
|
||||
ALint nState, nProcessed;
|
||||
alGetSourcei(m_nSource, AL_SOURCE_STATE, &nState);
|
||||
alGetSourcei(m_nSource, AL_BUFFERS_PROCESSED, &nProcessed);
|
||||
|
||||
// Add processed buffers to our queue
|
||||
vProcessed.resize(nProcessed);
|
||||
alSourceUnqueueBuffers(m_nSource, nProcessed, vProcessed.data());
|
||||
for (ALint nBuf : vProcessed) m_qAvailableBuffers.push(nBuf);
|
||||
|
||||
// Wait until there is a free buffer (ewww)
|
||||
if (m_qAvailableBuffers.empty()) continue;
|
||||
|
||||
short nNewSample = 0;
|
||||
|
||||
auto clip = [](float fSample, float fMax)
|
||||
{
|
||||
if (fSample >= 0.0)
|
||||
return fmin(fSample, fMax);
|
||||
else
|
||||
return fmax(fSample, -fMax);
|
||||
};
|
||||
|
||||
for (unsigned int n = 0; n < m_nBlockSamples; n += m_nChannels)
|
||||
{
|
||||
// User Process
|
||||
for (unsigned int c = 0; c < m_nChannels; c++)
|
||||
{
|
||||
nNewSample = (short)(clip(GetMixerOutput(c, m_fGlobalTime, fTimeStep), 1.0) * fMaxSample);
|
||||
m_pBlockMemory[n + c] = nNewSample;
|
||||
nPreviousSample = nNewSample;
|
||||
}
|
||||
|
||||
m_fGlobalTime = m_fGlobalTime + fTimeStep;
|
||||
}
|
||||
|
||||
// Fill OpenAL data buffer
|
||||
alBufferData(
|
||||
m_qAvailableBuffers.front(),
|
||||
m_nChannels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16,
|
||||
m_pBlockMemory,
|
||||
2 * m_nBlockSamples,
|
||||
m_nSampleRate
|
||||
);
|
||||
// Add it to the OpenAL queue
|
||||
alSourceQueueBuffers(m_nSource, 1, &m_qAvailableBuffers.front());
|
||||
// Remove it from ours
|
||||
m_qAvailableBuffers.pop();
|
||||
|
||||
// If it's not playing for some reason, change that
|
||||
if (nState != AL_PLAYING)
|
||||
alSourcePlay(m_nSource);
|
||||
}
|
||||
}
|
||||
|
||||
std::queue<ALuint> SOUND::m_qAvailableBuffers;
|
||||
ALuint *SOUND::m_pBuffers = nullptr;
|
||||
ALuint SOUND::m_nSource = 0;
|
||||
ALCdevice *SOUND::m_pDevice = nullptr;
|
||||
ALCcontext *SOUND::m_pContext = nullptr;
|
||||
unsigned int SOUND::m_nSampleRate = 0;
|
||||
unsigned int SOUND::m_nChannels = 0;
|
||||
unsigned int SOUND::m_nBlockCount = 0;
|
||||
unsigned int SOUND::m_nBlockSamples = 0;
|
||||
short* SOUND::m_pBlockMemory = nullptr;
|
||||
}
|
||||
|
||||
#else // Some other platform
|
||||
|
||||
namespace olc
|
||||
{
|
||||
bool SOUND::InitialiseAudio(unsigned int nSampleRate, unsigned int nChannels, unsigned int nBlocks, unsigned int nBlockSamples)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
// Stop and clean up audio system
|
||||
bool SOUND::DestroyAudio()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Audio thread. This loop responds to requests from the soundcard to fill 'blocks'
|
||||
// with audio data. If no requests are available it goes dormant until the sound
|
||||
// card is ready for more data. The block is fille by the "user" in some manner
|
||||
// and then issued to the soundcard.
|
||||
void SOUND::AudioThread()
|
||||
{ }
|
||||
}
|
||||
|
||||
#endif
|
||||
#endif
|
||||
#endif // OLC_PGEX_SOUND
|
||||
Reference in New Issue
Block a user