mirror of
https://github.com/RetroDECK/ES-DE.git
synced 2025-01-29 19:55:37 +00:00
Formatted the es-core source tree using clang-format.
This commit is contained in:
parent
af5e32e121
commit
23fdc00044
|
@ -12,7 +12,7 @@
|
|||
#include <string>
|
||||
|
||||
enum AsyncHandleStatus {
|
||||
ASYNC_IN_PROGRESS,
|
||||
ASYNC_IN_PROGRESS, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
ASYNC_ERROR,
|
||||
ASYNC_DONE
|
||||
};
|
||||
|
@ -21,17 +21,24 @@ enum AsyncHandleStatus {
|
|||
class AsyncHandle
|
||||
{
|
||||
public:
|
||||
AsyncHandle() : mStatus(ASYNC_IN_PROGRESS) {};
|
||||
virtual ~AsyncHandle() {};
|
||||
AsyncHandle()
|
||||
: mStatus(ASYNC_IN_PROGRESS)
|
||||
{
|
||||
}
|
||||
virtual ~AsyncHandle() {}
|
||||
|
||||
virtual void update() = 0;
|
||||
|
||||
// Update and return the latest status.
|
||||
inline AsyncHandleStatus status() { update(); return mStatus; }
|
||||
AsyncHandleStatus status()
|
||||
{
|
||||
update();
|
||||
return mStatus;
|
||||
}
|
||||
|
||||
// User-friendly string of our current status.
|
||||
// Will return error message if status() == SEARCH_ERROR.
|
||||
inline std::string getStatusString()
|
||||
std::string getStatusString()
|
||||
{
|
||||
switch (mStatus) {
|
||||
case ASYNC_IN_PROGRESS:
|
||||
|
@ -46,8 +53,12 @@ public:
|
|||
}
|
||||
|
||||
protected:
|
||||
inline void setStatus(AsyncHandleStatus status) { mStatus = status; }
|
||||
inline void setError(const std::string& error) { setStatus(ASYNC_ERROR); mError = error; }
|
||||
void setStatus(AsyncHandleStatus status) { mStatus = status; }
|
||||
void setError(const std::string& error)
|
||||
{
|
||||
setStatus(ASYNC_ERROR);
|
||||
mError = error;
|
||||
}
|
||||
|
||||
std::string mError;
|
||||
AsyncHandleStatus mStatus;
|
||||
|
|
|
@ -19,17 +19,20 @@ std::vector<std::shared_ptr<Sound>> AudioManager::sSoundVector;
|
|||
SDL_AudioDeviceID AudioManager::sAudioDevice = 0;
|
||||
SDL_AudioSpec AudioManager::sAudioFormat;
|
||||
SDL_AudioStream* AudioManager::sConversionStream;
|
||||
|
||||
bool AudioManager::sMuteStream = false;
|
||||
bool AudioManager::sHasAudioDevice = true;
|
||||
bool AudioManager::mIsClearingStream = false;
|
||||
|
||||
AudioManager::AudioManager()
|
||||
{
|
||||
// Init on construction.
|
||||
init();
|
||||
}
|
||||
|
||||
AudioManager::~AudioManager()
|
||||
{
|
||||
// Deinit on destruction.
|
||||
deinit();
|
||||
}
|
||||
|
||||
|
@ -74,7 +77,7 @@ void AudioManager::init()
|
|||
}
|
||||
|
||||
sAudioDevice = SDL_OpenAudioDevice(0, 0, &sRequestedAudioFormat, &sAudioFormat,
|
||||
SDL_AUDIO_ALLOW_ANY_CHANGE);
|
||||
SDL_AUDIO_ALLOW_ANY_CHANGE);
|
||||
|
||||
if (sAudioDevice == 0) {
|
||||
LOG(LogError) << "Unable to open audio device: " << SDL_GetError();
|
||||
|
@ -82,29 +85,30 @@ void AudioManager::init()
|
|||
}
|
||||
|
||||
if (sAudioFormat.freq != sRequestedAudioFormat.freq) {
|
||||
LOG(LogDebug) << "AudioManager::init(): Requested sample rate " <<
|
||||
std::to_string(sRequestedAudioFormat.freq) << " could not be "
|
||||
"set, obtained " << std::to_string(sAudioFormat.freq);
|
||||
LOG(LogDebug) << "AudioManager::init(): Requested sample rate "
|
||||
<< std::to_string(sRequestedAudioFormat.freq)
|
||||
<< " could not be set, obtained " << std::to_string(sAudioFormat.freq);
|
||||
}
|
||||
if (sAudioFormat.format != sRequestedAudioFormat.format) {
|
||||
LOG(LogDebug) << "AudioManager::init(): Requested format " <<
|
||||
std::to_string(sRequestedAudioFormat.format) << " could not be "
|
||||
"set, obtained " << std::to_string(sAudioFormat.format);
|
||||
LOG(LogDebug) << "AudioManager::init(): Requested format "
|
||||
<< std::to_string(sRequestedAudioFormat.format)
|
||||
<< " could not be set, obtained " << std::to_string(sAudioFormat.format);
|
||||
}
|
||||
if (sAudioFormat.channels != sRequestedAudioFormat.channels) {
|
||||
LOG(LogDebug) << "AudioManager::init(): Requested channel count " <<
|
||||
std::to_string(sRequestedAudioFormat.channels) << " could not be "
|
||||
"set, obtained " << std::to_string(sAudioFormat.channels);
|
||||
LOG(LogDebug) << "AudioManager::init(): Requested channel count "
|
||||
<< std::to_string(sRequestedAudioFormat.channels)
|
||||
<< " could not be set, obtained " << std::to_string(sAudioFormat.channels);
|
||||
}
|
||||
#if defined(_WIN64) || defined(__APPLE__)
|
||||
#if defined(_WIN64) || defined(__APPLE__)
|
||||
// Beats me why the buffer size is not divided by the channel count on some operating systems.
|
||||
if (sAudioFormat.samples != sRequestedAudioFormat.samples) {
|
||||
#else
|
||||
#else
|
||||
if (sAudioFormat.samples != sRequestedAudioFormat.samples / sRequestedAudioFormat.channels) {
|
||||
#endif
|
||||
LOG(LogDebug) << "AudioManager::init(): Requested sample buffer size " <<
|
||||
std::to_string(sRequestedAudioFormat.samples / sRequestedAudioFormat.channels) <<
|
||||
" could not be set, obtained " << std::to_string(sAudioFormat.samples);
|
||||
#endif
|
||||
LOG(LogDebug) << "AudioManager::init(): Requested sample buffer size "
|
||||
<< std::to_string(sRequestedAudioFormat.samples /
|
||||
sRequestedAudioFormat.channels)
|
||||
<< " could not be set, obtained " << std::to_string(sAudioFormat.samples);
|
||||
}
|
||||
|
||||
// Just in case someone changed the es_settings.xml file manually to invalid values.
|
||||
|
@ -126,7 +130,7 @@ void AudioManager::deinit()
|
|||
// user on some operating systems such as macOS, and it's annoying to have a crash at the
|
||||
// end of debugging session. So we'll simply disable the function until it has been properly
|
||||
// fixed in the SDL library.
|
||||
// SDL_FreeAudioStream(sConversionStream);
|
||||
// SDL_FreeAudioStream(sConversionStream);
|
||||
|
||||
SDL_CloseAudio();
|
||||
SDL_QuitSubSystem(SDL_INIT_AUDIO);
|
||||
|
@ -153,9 +157,9 @@ void AudioManager::mixAudio(void* /*unused*/, Uint8* stream, int len)
|
|||
restLength = len;
|
||||
}
|
||||
// Mix sample into stream.
|
||||
SDL_MixAudioFormat(stream, &(sound->getData()[sound->getPosition()]),
|
||||
sAudioFormat.format, restLength, static_cast<int>(Settings::getInstance()->
|
||||
getInt("SoundVolumeNavigation") * 1.28f));
|
||||
SDL_MixAudioFormat(
|
||||
stream, &(sound->getData()[sound->getPosition()]), sAudioFormat.format, restLength,
|
||||
static_cast<int>(Settings::getInstance()->getInt("SoundVolumeNavigation") * 1.28f));
|
||||
if (sound->getPosition() + restLength < sound->getLength()) {
|
||||
// Sample hasn't ended yet.
|
||||
stillPlaying = true;
|
||||
|
@ -191,8 +195,8 @@ void AudioManager::mixAudio(void* /*unused*/, Uint8* stream, int len)
|
|||
|
||||
std::vector<Uint8> converted(chunkLength);
|
||||
|
||||
int processedLength = SDL_AudioStreamGet(sConversionStream,
|
||||
static_cast<void*>(&converted.at(0)), chunkLength);
|
||||
int processedLength =
|
||||
SDL_AudioStreamGet(sConversionStream, static_cast<void*>(&converted.at(0)), chunkLength);
|
||||
|
||||
if (processedLength < 0) {
|
||||
LOG(LogError) << "AudioManager::mixAudio(): Couldn't convert sound chunk:";
|
||||
|
@ -201,9 +205,9 @@ void AudioManager::mixAudio(void* /*unused*/, Uint8* stream, int len)
|
|||
}
|
||||
|
||||
// Enable only when needed, as this generates a lot of debug output.
|
||||
// LOG(LogDebug) << "AudioManager::mixAudio(): chunkLength "
|
||||
// "/ processedLength / streamLength: " << chunkLength << " / " <<
|
||||
// " / " << processedLength << " / " << streamLength;
|
||||
// LOG(LogDebug) << "AudioManager::mixAudio(): chunkLength "
|
||||
// "/ processedLength / streamLength: " << chunkLength << " / " <<
|
||||
// " / " << processedLength << " / " << streamLength;
|
||||
|
||||
// This mute flag is used to make sure that the audio buffer already sent to the
|
||||
// stream is not played when the video player has been stopped. Otherwise there would
|
||||
|
@ -213,8 +217,9 @@ void AudioManager::mixAudio(void* /*unused*/, Uint8* stream, int len)
|
|||
SDL_MixAudioFormat(stream, &converted.at(0), sAudioFormat.format, processedLength, 0);
|
||||
}
|
||||
else {
|
||||
SDL_MixAudioFormat(stream, &converted.at(0), sAudioFormat.format, processedLength,
|
||||
static_cast<int>(Settings::getInstance()->getInt("SoundVolumeVideos") * 1.28f));
|
||||
SDL_MixAudioFormat(
|
||||
stream, &converted.at(0), sAudioFormat.format, processedLength,
|
||||
static_cast<int>(Settings::getInstance()->getInt("SoundVolumeVideos") * 1.28f));
|
||||
}
|
||||
|
||||
// If nothing is playing, pause the device until there is more audio to output.
|
||||
|
@ -224,6 +229,7 @@ void AudioManager::mixAudio(void* /*unused*/, Uint8* stream, int len)
|
|||
|
||||
void AudioManager::registerSound(std::shared_ptr<Sound>& sound)
|
||||
{
|
||||
// Add sound to sound vector.
|
||||
sSoundVector.push_back(sound);
|
||||
}
|
||||
|
||||
|
@ -267,7 +273,7 @@ void AudioManager::setupAudioStream(int sampleRate)
|
|||
|
||||
// Used for streaming audio from videos.
|
||||
sConversionStream = SDL_NewAudioStream(AUDIO_F32, 2, sampleRate, sAudioFormat.format,
|
||||
sAudioFormat.channels, sAudioFormat.freq);
|
||||
sAudioFormat.channels, sAudioFormat.freq);
|
||||
if (sConversionStream == nullptr) {
|
||||
LOG(LogError) << "Failed to create audio conversion stream:";
|
||||
LOG(LogError) << SDL_GetError();
|
||||
|
@ -298,7 +304,7 @@ void AudioManager::clearStream()
|
|||
// The SDL_AudioStreamClear() function is unstable and causes random crashes, so
|
||||
// we have to implement a workaround instead where SDL_AudioStreamGet() is used
|
||||
// to empty the stream.
|
||||
// SDL_AudioStreamClear(sConversionStream);
|
||||
// SDL_AudioStreamClear(sConversionStream);
|
||||
|
||||
mIsClearingStream = true;
|
||||
|
||||
|
@ -307,8 +313,8 @@ void AudioManager::clearStream()
|
|||
|
||||
while ((streamSize = SDL_AudioStreamAvailable(sConversionStream)) > 0) {
|
||||
std::vector<Uint8> readBuffer(length);
|
||||
int processedLength = SDL_AudioStreamGet(sConversionStream,
|
||||
static_cast<void*>(&readBuffer.at(0)), length);
|
||||
int processedLength =
|
||||
SDL_AudioStreamGet(sConversionStream, static_cast<void*>(&readBuffer.at(0)), length);
|
||||
if (processedLength <= 0) {
|
||||
break;
|
||||
}
|
||||
|
|
|
@ -33,11 +33,12 @@ extern int SDL_USER_CECBUTTONUP;
|
|||
CECInput* CECInput::sInstance = nullptr;
|
||||
|
||||
#if defined(HAVE_LIBCEC)
|
||||
static void onAlert(void* /*cbParam*/, const CEC::libcec_alert type,
|
||||
const CEC::libcec_parameter param)
|
||||
static void onAlert(void* /*cbParam*/,
|
||||
const CEC::libcec_alert type,
|
||||
const CEC::libcec_parameter param)
|
||||
{
|
||||
LOG(LogDebug) << "CECInput::onAlert type: " << CECInput::getAlertTypeString(type) <<
|
||||
" parameter: " << reinterpret_cast<char*>(param.paramData);
|
||||
LOG(LogDebug) << "CECInput::onAlert type: " << CECInput::getAlertTypeString(type)
|
||||
<< " parameter: " << reinterpret_cast<char*>(param.paramData);
|
||||
}
|
||||
|
||||
static void onCommand(void* /*cbParam*/, const CEC::cec_command* command)
|
||||
|
@ -50,7 +51,7 @@ static void onKeyPress(void* /*cbParam*/, const CEC::cec_keypress* key)
|
|||
LOG(LogDebug) << "CECInput::onKeyPress keycode: " << CECInput::getKeyCodeString(key->keycode);
|
||||
|
||||
SDL_Event event;
|
||||
event.type = (key->duration > 0) ? SDL_USER_CECBUTTONUP : SDL_USER_CECBUTTONDOWN;
|
||||
event.type = (key->duration > 0) ? SDL_USER_CECBUTTONUP : SDL_USER_CECBUTTONDOWN;
|
||||
event.user.code = key->keycode;
|
||||
SDL_PushEvent(&event);
|
||||
}
|
||||
|
@ -93,14 +94,15 @@ void CECInput::deinit()
|
|||
}
|
||||
}
|
||||
|
||||
CECInput::CECInput() : mlibCEC(nullptr)
|
||||
CECInput::CECInput()
|
||||
: mlibCEC(nullptr)
|
||||
{
|
||||
#if defined(HAVE_LIBCEC)
|
||||
#if defined(_RPI_)
|
||||
#if defined(HAVE_LIBCEC)
|
||||
#if defined(_RPI_)
|
||||
// Restart vchi tv and CEC in case we just came back from another app using CEC (like Kodi).
|
||||
vchi_tv_and_cec_deinit();
|
||||
vchi_tv_and_cec_init();
|
||||
#endif // _RPI_
|
||||
#endif // _RPI_
|
||||
|
||||
CEC::ICECCallbacks callbacks;
|
||||
CEC::libcec_configuration config;
|
||||
|
@ -136,8 +138,8 @@ CECInput::CECInput() : mlibCEC(nullptr)
|
|||
}
|
||||
|
||||
for (int i = 0; i < numAdapters; i++)
|
||||
LOG(LogDebug) << "CEC adapter: " << i << " path: " << adapters[i].strComPath <<
|
||||
" name: " << adapters[i].strComName;
|
||||
LOG(LogDebug) << "CEC adapter: " << i << " path: " << adapters[i].strComPath
|
||||
<< " name: " << adapters[i].strComName;
|
||||
|
||||
if (!mlibCEC->Open(adapters[0].strComName)) {
|
||||
LOG(LogError) << "CECInput::mAdapter->Open failed";
|
||||
|
@ -145,28 +147,29 @@ CECInput::CECInput() : mlibCEC(nullptr)
|
|||
mlibCEC = nullptr;
|
||||
return;
|
||||
}
|
||||
#endif // HAVE_LIBCEC
|
||||
#endif // HAVE_LIBCEC
|
||||
}
|
||||
|
||||
CECInput::~CECInput()
|
||||
{
|
||||
|
||||
#if defined(HAVE_LIBCEC)
|
||||
#if defined(HAVE_LIBCEC)
|
||||
if (mlibCEC) {
|
||||
mlibCEC->Close();
|
||||
UnloadLibCec(mlibCEC);
|
||||
mlibCEC = nullptr;
|
||||
}
|
||||
|
||||
#if defined(_RPI_)
|
||||
#if defined(_RPI_)
|
||||
// Deinit vchi tv and CEC in case we are going to launch another app using CEC (like Kodi).
|
||||
vchi_tv_and_cec_deinit();
|
||||
#endif // _RPI_
|
||||
#endif // HAVE_LIBCEC
|
||||
#endif // _RPI_
|
||||
#endif // HAVE_LIBCEC
|
||||
}
|
||||
|
||||
std::string CECInput::getAlertTypeString(const unsigned int _type)
|
||||
{
|
||||
// clang-format off
|
||||
switch (_type) {
|
||||
#if defined(HAVE_LIBCEC)
|
||||
case CEC::CEC_ALERT_SERVICE_DEVICE: { return "Service-Device"; } break;
|
||||
|
@ -180,10 +183,12 @@ std::string CECInput::getAlertTypeString(const unsigned int _type)
|
|||
#endif // HAVE_LIBCEC
|
||||
default: { return "Unknown"; } break;
|
||||
}
|
||||
// clang-format on
|
||||
}
|
||||
|
||||
std::string CECInput::getOpCodeString(const unsigned int _opCode)
|
||||
{
|
||||
// clang-format off
|
||||
switch (_opCode) {
|
||||
#if defined(HAVE_LIBCEC)
|
||||
case CEC::CEC_OPCODE_ACTIVE_SOURCE: { return "Active-Source"; } break;
|
||||
|
@ -261,10 +266,12 @@ std::string CECInput::getOpCodeString(const unsigned int _opCode)
|
|||
#endif // HAVE_LIBCEC
|
||||
default: { return "Unknown"; } break;
|
||||
}
|
||||
// clang-format on
|
||||
}
|
||||
|
||||
std::string CECInput::getKeyCodeString(const unsigned int _keyCode)
|
||||
{
|
||||
// clang-format off
|
||||
switch (_keyCode) {
|
||||
#if defined(HAVE_LIBCEC)
|
||||
case CEC::CEC_USER_CONTROL_CODE_SELECT: { return "Select"; } break;
|
||||
|
@ -358,5 +365,6 @@ std::string CECInput::getKeyCodeString(const unsigned int _keyCode)
|
|||
case 0:
|
||||
#endif // HAVE_LIBCEC
|
||||
default: { return "Unknown"; } break;
|
||||
// clang-format off
|
||||
}
|
||||
}
|
|
@ -11,7 +11,10 @@
|
|||
|
||||
#include <string>
|
||||
|
||||
namespace CEC { class ICECAdapter; }
|
||||
namespace CEC
|
||||
{
|
||||
class ICECAdapter;
|
||||
}
|
||||
|
||||
class CECInput
|
||||
{
|
||||
|
@ -23,7 +26,7 @@ public:
|
|||
static std::string getKeyCodeString(const unsigned int _keyCode);
|
||||
|
||||
private:
|
||||
CECInput();
|
||||
CECInput();
|
||||
~CECInput();
|
||||
|
||||
static CECInput* sInstance;
|
||||
|
|
|
@ -8,31 +8,30 @@
|
|||
|
||||
#include "GuiComponent.h"
|
||||
|
||||
#include "animations/Animation.h"
|
||||
#include "animations/AnimationController.h"
|
||||
#include "renderers/Renderer.h"
|
||||
#include "Log.h"
|
||||
#include "ThemeData.h"
|
||||
#include "Window.h"
|
||||
#include "animations/Animation.h"
|
||||
#include "renderers/Renderer.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
GuiComponent::GuiComponent(Window* window)
|
||||
: mWindow(window),
|
||||
mParent(nullptr),
|
||||
mColor(0),
|
||||
mColorShift(0),
|
||||
mColorShiftEnd(0),
|
||||
mOpacity(255),
|
||||
mSaturation(1.0),
|
||||
mPosition(Vector3f::Zero()),
|
||||
mOrigin(Vector2f::Zero()),
|
||||
mRotationOrigin(0.5, 0.5),
|
||||
mSize(Vector2f::Zero()),
|
||||
mTransform(Transform4x4f::Identity()),
|
||||
mIsProcessing(false),
|
||||
mVisible(true),
|
||||
mEnabled(true)
|
||||
: mWindow(window)
|
||||
, mParent(nullptr)
|
||||
, mColor(0)
|
||||
, mColorShift(0)
|
||||
, mColorShiftEnd(0)
|
||||
, mOpacity(255)
|
||||
, mSaturation(1.0f)
|
||||
, mPosition(Vector3f::Zero())
|
||||
, mOrigin(Vector2f::Zero())
|
||||
, mRotationOrigin(0.5f, 0.5f)
|
||||
, mSize(Vector2f::Zero())
|
||||
, mTransform(Transform4x4f::Identity())
|
||||
, mIsProcessing(false)
|
||||
, mVisible(true)
|
||||
, mEnabled(true)
|
||||
{
|
||||
for (unsigned char i = 0; i < MAX_ANIMATIONS; i++)
|
||||
mAnimationMap[i] = nullptr;
|
||||
|
@ -94,105 +93,30 @@ void GuiComponent::renderChildren(const Transform4x4f& transform) const
|
|||
getChild(i)->render(transform);
|
||||
}
|
||||
|
||||
Vector3f GuiComponent::getPosition() const
|
||||
{
|
||||
return mPosition;
|
||||
}
|
||||
|
||||
void GuiComponent::setPosition(float x, float y, float z)
|
||||
{
|
||||
mPosition = Vector3f(x, y, z);
|
||||
onPositionChanged();
|
||||
}
|
||||
|
||||
Vector2f GuiComponent::getOrigin() const
|
||||
{
|
||||
return mOrigin;
|
||||
}
|
||||
|
||||
void GuiComponent::setOrigin(float x, float y)
|
||||
{
|
||||
mOrigin = Vector2f(x, y);
|
||||
onOriginChanged();
|
||||
}
|
||||
|
||||
Vector2f GuiComponent::getRotationOrigin() const
|
||||
{
|
||||
return mRotationOrigin;
|
||||
}
|
||||
|
||||
void GuiComponent::setRotationOrigin(float x, float y)
|
||||
{
|
||||
mRotationOrigin = Vector2f(x, y);
|
||||
}
|
||||
|
||||
Vector2f GuiComponent::getSize() const
|
||||
{
|
||||
return mSize;
|
||||
}
|
||||
|
||||
void GuiComponent::setSize(float w, float h)
|
||||
{
|
||||
mSize = Vector2f(w, h);
|
||||
onSizeChanged();
|
||||
}
|
||||
|
||||
float GuiComponent::getRotation() const
|
||||
{
|
||||
return mRotation;
|
||||
}
|
||||
|
||||
void GuiComponent::setRotation(float rotation)
|
||||
{
|
||||
mRotation = rotation;
|
||||
}
|
||||
|
||||
float GuiComponent::getScale() const
|
||||
{
|
||||
return mScale;
|
||||
}
|
||||
|
||||
void GuiComponent::setScale(float scale)
|
||||
{
|
||||
mScale = scale;
|
||||
}
|
||||
|
||||
float GuiComponent::getZIndex() const
|
||||
{
|
||||
return mZIndex;
|
||||
}
|
||||
|
||||
void GuiComponent::setZIndex(float z)
|
||||
{
|
||||
mZIndex = z;
|
||||
}
|
||||
|
||||
float GuiComponent::getDefaultZIndex() const
|
||||
{
|
||||
return mDefaultZIndex;
|
||||
}
|
||||
|
||||
void GuiComponent::setDefaultZIndex(float z)
|
||||
{
|
||||
mDefaultZIndex = z;
|
||||
}
|
||||
|
||||
bool GuiComponent::isVisible() const
|
||||
{
|
||||
return mVisible;
|
||||
}
|
||||
void GuiComponent::setVisible(bool visible)
|
||||
{
|
||||
mVisible = visible;
|
||||
}
|
||||
|
||||
Vector2f GuiComponent::getCenter() const
|
||||
{
|
||||
return Vector2f(mPosition.x() - (getSize().x() * mOrigin.x()) + getSize().x() / 2,
|
||||
mPosition.y() - (getSize().y() * mOrigin.y()) + getSize().y() / 2);
|
||||
return Vector2f(mPosition.x() - (getSize().x() * mOrigin.x()) + getSize().x() / 2.0f,
|
||||
mPosition.y() - (getSize().y() * mOrigin.y()) + getSize().y() / 2.0f);
|
||||
}
|
||||
|
||||
// Children stuff.
|
||||
void GuiComponent::addChild(GuiComponent* cmp)
|
||||
{
|
||||
mChildren.push_back(cmp);
|
||||
|
@ -222,11 +146,6 @@ void GuiComponent::removeChild(GuiComponent* cmp)
|
|||
}
|
||||
}
|
||||
|
||||
void GuiComponent::clearChildren()
|
||||
{
|
||||
mChildren.clear();
|
||||
}
|
||||
|
||||
void GuiComponent::sortChildren()
|
||||
{
|
||||
std::stable_sort(mChildren.begin(), mChildren.end(), [](GuiComponent* a, GuiComponent* b) {
|
||||
|
@ -234,15 +153,10 @@ void GuiComponent::sortChildren()
|
|||
});
|
||||
}
|
||||
|
||||
unsigned int GuiComponent::getChildCount() const
|
||||
{
|
||||
return static_cast<int>(mChildren.size());
|
||||
}
|
||||
|
||||
int GuiComponent::getChildIndex() const
|
||||
{
|
||||
std::vector<GuiComponent*>::iterator it =
|
||||
std::find(getParent()->mChildren.begin(), getParent()->mChildren.end(), this);
|
||||
std::find(getParent()->mChildren.begin(), getParent()->mChildren.end(), this);
|
||||
|
||||
if (it != getParent()->mChildren.end())
|
||||
return static_cast<int>(std::distance(getParent()->mChildren.begin(), it));
|
||||
|
@ -250,26 +164,6 @@ int GuiComponent::getChildIndex() const
|
|||
return -1;
|
||||
}
|
||||
|
||||
GuiComponent* GuiComponent::getChild(unsigned int i) const
|
||||
{
|
||||
return mChildren.at(i);
|
||||
}
|
||||
|
||||
void GuiComponent::setParent(GuiComponent* parent)
|
||||
{
|
||||
mParent = parent;
|
||||
}
|
||||
|
||||
GuiComponent* GuiComponent::getParent() const
|
||||
{
|
||||
return mParent;
|
||||
}
|
||||
|
||||
unsigned char GuiComponent::getOpacity() const
|
||||
{
|
||||
return mOpacity;
|
||||
}
|
||||
|
||||
void GuiComponent::setOpacity(unsigned char opacity)
|
||||
{
|
||||
mOpacity = opacity;
|
||||
|
@ -277,92 +171,47 @@ void GuiComponent::setOpacity(unsigned char opacity)
|
|||
(*it)->setOpacity(opacity);
|
||||
}
|
||||
|
||||
unsigned int GuiComponent::getColor() const
|
||||
{
|
||||
return mColor;
|
||||
}
|
||||
|
||||
unsigned int GuiComponent::getColorShift() const
|
||||
{
|
||||
return mColorShift;
|
||||
}
|
||||
|
||||
void GuiComponent::setColor(unsigned int color)
|
||||
{
|
||||
mColor = color;
|
||||
mColorOpacity = mColor & 0x000000FF;
|
||||
}
|
||||
|
||||
float GuiComponent::getSaturation() const
|
||||
{
|
||||
return static_cast<float>(mColor);
|
||||
}
|
||||
|
||||
void GuiComponent::setSaturation(float saturation)
|
||||
{
|
||||
mSaturation = saturation;
|
||||
}
|
||||
|
||||
void GuiComponent::setColorShift(unsigned int color)
|
||||
{
|
||||
mColorShift = color;
|
||||
mColorShiftEnd = color;
|
||||
}
|
||||
|
||||
const Transform4x4f& GuiComponent::getTransform()
|
||||
{
|
||||
mTransform = Transform4x4f::Identity();
|
||||
mTransform.translate(mPosition);
|
||||
if (mScale != 1.0)
|
||||
|
||||
if (mScale != 1.0f)
|
||||
mTransform.scale(mScale);
|
||||
if (mRotation != 0.0) {
|
||||
|
||||
if (mRotation != 0.0f) {
|
||||
// Calculate offset as difference between origin and rotation origin.
|
||||
Vector2f rotationSize = getRotationSize();
|
||||
float xOff = (mOrigin.x() - mRotationOrigin.x()) * rotationSize.x();
|
||||
float yOff = (mOrigin.y() - mRotationOrigin.y()) * rotationSize.y();
|
||||
|
||||
// Transform to offset point.
|
||||
if (xOff != 0.0 || yOff != 0.0)
|
||||
mTransform.translate(Vector3f(xOff * -1, yOff * -1, 0.0f));
|
||||
if (xOff != 0.0f || yOff != 0.0f)
|
||||
mTransform.translate(Vector3f(xOff * -1.0f, yOff * -1.0f, 0.0f));
|
||||
|
||||
// Apply rotation transform.
|
||||
mTransform.rotateZ(mRotation);
|
||||
|
||||
// Transform back to original point.
|
||||
if (xOff != 0.0 || yOff != 0.0)
|
||||
if (xOff != 0.0f || yOff != 0.0f)
|
||||
mTransform.translate(Vector3f(xOff, yOff, 0.0f));
|
||||
}
|
||||
mTransform.translate(Vector3f(mOrigin.x() * mSize.x() * -1,
|
||||
mOrigin.y() * mSize.y() * -1, 0.0f));
|
||||
mTransform.translate(
|
||||
Vector3f(mOrigin.x() * mSize.x() * -1.0f, mOrigin.y() * mSize.y() * -1.0f, 0.0f));
|
||||
return mTransform;
|
||||
}
|
||||
|
||||
std::string GuiComponent::getValue() const
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
void GuiComponent::setValue(const std::string& /*value*/)
|
||||
{
|
||||
}
|
||||
|
||||
std::string GuiComponent::getHiddenValue() const
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
void GuiComponent::setHiddenValue(const std::string& /*value*/)
|
||||
{
|
||||
}
|
||||
|
||||
void GuiComponent::textInput(const std::string& text)
|
||||
{
|
||||
for (auto iter = mChildren.cbegin(); iter != mChildren.cend(); iter++)
|
||||
(*iter)->textInput(text);
|
||||
}
|
||||
|
||||
void GuiComponent::setAnimation(Animation* anim, int delay,
|
||||
std::function<void()> finishedCallback, bool reverse, unsigned char slot)
|
||||
void GuiComponent::setAnimation(Animation* anim,
|
||||
int delay,
|
||||
std::function<void()> finishedCallback,
|
||||
bool reverse,
|
||||
unsigned char slot)
|
||||
{
|
||||
assert(slot < MAX_ANIMATIONS);
|
||||
|
||||
|
@ -447,29 +296,14 @@ void GuiComponent::cancelAllAnimations()
|
|||
cancelAnimation(i);
|
||||
}
|
||||
|
||||
bool GuiComponent::isAnimationPlaying(unsigned char slot) const
|
||||
{
|
||||
return mAnimationMap[slot] != nullptr;
|
||||
}
|
||||
|
||||
bool GuiComponent::isAnimationReversed(unsigned char slot) const
|
||||
{
|
||||
assert(mAnimationMap[slot] != nullptr);
|
||||
return mAnimationMap[slot]->isReversed();
|
||||
}
|
||||
|
||||
int GuiComponent::getAnimationTime(unsigned char slot) const
|
||||
{
|
||||
assert(mAnimationMap[slot] != nullptr);
|
||||
return mAnimationMap[slot]->getTime();
|
||||
}
|
||||
|
||||
void GuiComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& element, unsigned int properties)
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties)
|
||||
{
|
||||
Vector2f scale = getParent() ? getParent()->getSize()
|
||||
: Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
Vector2f scale = getParent() ? getParent()->getSize() :
|
||||
Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
|
||||
const ThemeData::ThemeElement* elem = theme->getElement(view, element, "");
|
||||
if (!elem)
|
||||
|
@ -484,9 +318,9 @@ void GuiComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
if (properties & ThemeFlags::SIZE && elem->has("size"))
|
||||
setSize(elem->get<Vector2f>("size") * scale);
|
||||
|
||||
// Position + size also implies origin
|
||||
if ((properties & ORIGIN || (properties & POSITION &&
|
||||
properties & ThemeFlags::SIZE)) && elem->has("origin")) {
|
||||
// Position + size also implies origin.
|
||||
if ((properties & ORIGIN || (properties & POSITION && properties & ThemeFlags::SIZE)) &&
|
||||
elem->has("origin")) {
|
||||
setOrigin(elem->get<Vector2f>("origin"));
|
||||
}
|
||||
|
||||
|
@ -521,16 +355,6 @@ void GuiComponent::updateHelpPrompts()
|
|||
mWindow->setHelpPrompts(prompts, getHelpStyle());
|
||||
}
|
||||
|
||||
HelpStyle GuiComponent::getHelpStyle()
|
||||
{
|
||||
return HelpStyle();
|
||||
}
|
||||
|
||||
bool GuiComponent::isProcessing() const
|
||||
{
|
||||
return mIsProcessing;
|
||||
}
|
||||
|
||||
void GuiComponent::onShow()
|
||||
{
|
||||
for (unsigned int i = 0; i < getChildCount(); i++)
|
||||
|
|
|
@ -9,11 +9,12 @@
|
|||
#ifndef ES_CORE_GUI_COMPONENT_H
|
||||
#define ES_CORE_GUI_COMPONENT_H
|
||||
|
||||
#include "math/Misc.h"
|
||||
#include "math/Transform4x4f.h"
|
||||
#include "HelpPrompt.h"
|
||||
#include "HelpStyle.h"
|
||||
#include "InputConfig.h"
|
||||
#include "animations/AnimationController.h"
|
||||
#include "math/Misc.h"
|
||||
#include "math/Transform4x4f.h"
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
|
@ -65,72 +66,84 @@ public:
|
|||
// 4. Tell your children to render, based on your component's transform - renderChildren(t).
|
||||
virtual void render(const Transform4x4f& parentTrans);
|
||||
|
||||
Vector3f getPosition() const;
|
||||
inline void setPosition(const Vector3f& offset)
|
||||
{ setPosition(offset.x(), offset.y(), offset.z()); }
|
||||
Vector3f getPosition() const { return mPosition; }
|
||||
void setPosition(const Vector3f& offset) { setPosition(offset.x(), offset.y(), offset.z()); }
|
||||
void setPosition(float x, float y, float z = 0.0f);
|
||||
virtual void onPositionChanged() {};
|
||||
virtual void onPositionChanged() {}
|
||||
|
||||
Vector2f getOrigin() const { return mOrigin; }
|
||||
// Sets the origin as a percentage of this image.
|
||||
// (e.g. (0, 0) is top left, (0.5, 0.5) is the center.)
|
||||
Vector2f getOrigin() const;
|
||||
void setOrigin(float originX, float originY);
|
||||
inline void setOrigin(Vector2f origin) { setOrigin(origin.x(), origin.y()); }
|
||||
virtual void onOriginChanged() {};
|
||||
void setOrigin(Vector2f origin) { setOrigin(origin.x(), origin.y()); }
|
||||
virtual void onOriginChanged() {}
|
||||
|
||||
Vector2f getRotationOrigin() const { return mRotationOrigin; }
|
||||
// Sets the rotation origin as a percentage of this image.
|
||||
// (e.g. (0, 0) is top left, (0.5, 0.5) is the center.)
|
||||
Vector2f getRotationOrigin() const;
|
||||
void setRotationOrigin(float originX, float originY);
|
||||
inline void setRotationOrigin(Vector2f origin)
|
||||
{ setRotationOrigin(origin.x(), origin.y()); }
|
||||
void setRotationOrigin(float originX, float originY)
|
||||
{
|
||||
mRotationOrigin = Vector2f(originX, originY);
|
||||
}
|
||||
void setRotationOrigin(Vector2f origin) { setRotationOrigin(origin.x(), origin.y()); }
|
||||
|
||||
virtual Vector2f getSize() const;
|
||||
inline void setSize(const Vector2f& size) { setSize(size.x(), size.y()); }
|
||||
virtual Vector2f getSize() const { return mSize; }
|
||||
void setSize(const Vector2f& size) { setSize(size.x(), size.y()); }
|
||||
void setSize(float w, float h);
|
||||
virtual void setResize(float width, float height) {};
|
||||
virtual void onSizeChanged() {};
|
||||
virtual void setResize(float width, float height) {}
|
||||
virtual void onSizeChanged() {}
|
||||
|
||||
virtual Vector2f getRotationSize() const { return getSize(); };
|
||||
virtual Vector2f getRotationSize() const { return getSize(); }
|
||||
float getRotation() const { return mRotation; }
|
||||
void setRotation(float rotation) { mRotation = rotation; }
|
||||
void setRotationDegrees(float rotation)
|
||||
{
|
||||
setRotation(static_cast<float>(ES_DEG_TO_RAD(rotation)));
|
||||
}
|
||||
|
||||
float getRotation() const;
|
||||
void setRotation(float rotation);
|
||||
inline void setRotationDegrees(float rotation) {
|
||||
setRotation(static_cast<float>(ES_DEG_TO_RAD(rotation))); }
|
||||
float getScale() const { return mScale; }
|
||||
void setScale(float scale) { mScale = scale; }
|
||||
|
||||
float getScale() const;
|
||||
void setScale(float scale);
|
||||
float getZIndex() const { return mZIndex; }
|
||||
void setZIndex(float zIndex) { mZIndex = zIndex; }
|
||||
|
||||
float getZIndex() const;
|
||||
void setZIndex(float zIndex);
|
||||
float getDefaultZIndex() const { return mDefaultZIndex; }
|
||||
void setDefaultZIndex(float zIndex) { mDefaultZIndex = zIndex; }
|
||||
|
||||
float getDefaultZIndex() const;
|
||||
void setDefaultZIndex(float zIndex);
|
||||
|
||||
bool isVisible() const;
|
||||
void setVisible(bool visible);
|
||||
bool isVisible() const { return mVisible; }
|
||||
void setVisible(bool visible) { mVisible = visible; }
|
||||
|
||||
// Returns the center point of the image (takes origin into account).
|
||||
Vector2f getCenter() const;
|
||||
|
||||
void setParent(GuiComponent* parent);
|
||||
GuiComponent* getParent() const;
|
||||
void setParent(GuiComponent* parent) { mParent = parent; }
|
||||
GuiComponent* getParent() const { return mParent; }
|
||||
|
||||
void addChild(GuiComponent* cmp);
|
||||
void removeChild(GuiComponent* cmp);
|
||||
void clearChildren();
|
||||
void clearChildren() { mChildren.clear(); }
|
||||
void sortChildren();
|
||||
unsigned int getChildCount() const;
|
||||
unsigned int getChildCount() const { return static_cast<int>(mChildren.size()); }
|
||||
int getChildIndex() const;
|
||||
GuiComponent* getChild(unsigned int i) const;
|
||||
GuiComponent* getChild(unsigned int i) const { return mChildren.at(i); }
|
||||
|
||||
// Animation will be automatically deleted when it completes or is stopped.
|
||||
bool isAnimationPlaying(unsigned char slot) const;
|
||||
bool isAnimationReversed(unsigned char slot) const;
|
||||
int getAnimationTime(unsigned char slot) const;
|
||||
void setAnimation(Animation* animation, int delay = 0,
|
||||
std::function<void()> finishedCallback = nullptr,
|
||||
bool reverse = false, unsigned char slot = 0);
|
||||
bool isAnimationPlaying(unsigned char slot) const { return mAnimationMap[slot] != nullptr; }
|
||||
bool isAnimationReversed(unsigned char slot) const
|
||||
{
|
||||
assert(mAnimationMap[slot] != nullptr);
|
||||
return mAnimationMap[slot]->isReversed();
|
||||
}
|
||||
int getAnimationTime(unsigned char slot) const
|
||||
{
|
||||
assert(mAnimationMap[slot] != nullptr);
|
||||
return mAnimationMap[slot]->getTime();
|
||||
}
|
||||
void setAnimation(Animation* animation,
|
||||
int delay = 0,
|
||||
std::function<void()> finishedCallback = nullptr,
|
||||
bool reverse = false,
|
||||
unsigned char slot = 0);
|
||||
bool stopAnimation(unsigned char slot);
|
||||
// Like stopAnimation, but doesn't call finishedCallback - only removes the animation, leaving
|
||||
// things in their current state. Returns true if successful (an animation was in this slot).
|
||||
|
@ -143,45 +156,53 @@ public:
|
|||
void stopAllAnimations();
|
||||
void cancelAllAnimations();
|
||||
|
||||
virtual bool isListScrolling() { return false; };
|
||||
virtual void stopListScrolling() {};
|
||||
virtual unsigned char getOpacity() const;
|
||||
virtual bool isListScrolling() { return false; }
|
||||
virtual void stopListScrolling() {}
|
||||
virtual unsigned char getOpacity() const { return mOpacity; }
|
||||
virtual void setOpacity(unsigned char opacity);
|
||||
virtual unsigned int getColor() const;
|
||||
virtual unsigned int getColorShift() const;
|
||||
virtual void setColor(unsigned int color);
|
||||
virtual float getSaturation() const;
|
||||
virtual void setSaturation(float saturation);
|
||||
virtual void setColorShift(unsigned int color);
|
||||
virtual void setOriginalColor(unsigned int color) { mColorOriginalValue = color; };
|
||||
virtual void setChangedColor(unsigned int color) { mColorChangedValue = color; };
|
||||
virtual unsigned int getColor() const { return mColor; }
|
||||
virtual unsigned int getColorShift() const { return mColorShift; }
|
||||
virtual void setColor(unsigned int color)
|
||||
{
|
||||
mColor = color;
|
||||
mColorOpacity = mColor & 0x000000FF;
|
||||
}
|
||||
virtual float getSaturation() const { return static_cast<float>(mColor); }
|
||||
virtual void setSaturation(float saturation) { mSaturation = saturation; }
|
||||
virtual void setColorShift(unsigned int color)
|
||||
{
|
||||
mColorShift = color;
|
||||
mColorShiftEnd = color;
|
||||
}
|
||||
virtual void setOriginalColor(unsigned int color) { mColorOriginalValue = color; }
|
||||
virtual void setChangedColor(unsigned int color) { mColorChangedValue = color; }
|
||||
|
||||
// These functions are used to enable and disable options in menus, i.e. switches and similar.
|
||||
virtual bool getEnabled() { return mEnabled; };
|
||||
virtual void setEnabled(bool state) { mEnabled = state; };
|
||||
virtual bool getEnabled() { return mEnabled; }
|
||||
virtual void setEnabled(bool state) { mEnabled = state; }
|
||||
|
||||
virtual std::shared_ptr<Font> getFont() const { return nullptr; };
|
||||
virtual std::shared_ptr<Font> getFont() const { return nullptr; }
|
||||
|
||||
const Transform4x4f& getTransform();
|
||||
|
||||
virtual std::string getValue() const;
|
||||
virtual void setValue(const std::string& value);
|
||||
virtual std::string getValue() const { return ""; }
|
||||
virtual void setValue(const std::string& value) {}
|
||||
|
||||
virtual std::string getHiddenValue() const;
|
||||
virtual void setHiddenValue(const std::string& value);
|
||||
virtual std::string getHiddenValue() const { return ""; }
|
||||
virtual void setHiddenValue(const std::string& value) {}
|
||||
|
||||
// Used to set the parameters for ScrollableContainer.
|
||||
virtual void setScrollParameters(float, float, int) {};
|
||||
virtual void setScrollParameters(float, float, int) {}
|
||||
|
||||
virtual void onFocusGained() {};
|
||||
virtual void onFocusLost() {};
|
||||
virtual void onFocusGained() {}
|
||||
virtual void onFocusLost() {}
|
||||
|
||||
virtual void onShow();
|
||||
virtual void onHide();
|
||||
virtual void onStopVideo();
|
||||
virtual void onPauseVideo();
|
||||
virtual void onUnpauseVideo();
|
||||
virtual bool isVideoPaused() { return false; };
|
||||
virtual bool isVideoPaused() { return false; }
|
||||
|
||||
virtual void onScreensaverActivate();
|
||||
virtual void onScreensaverDeactivate();
|
||||
|
@ -192,18 +213,20 @@ public:
|
|||
// Default implementation just handles <pos> and <size> tags as normalized float pairs.
|
||||
// You probably want to keep this behavior for any derived classes as well as add your own.
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& element, unsigned int properties);
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties);
|
||||
|
||||
// Returns a list of help prompts.
|
||||
virtual std::vector<HelpPrompt> getHelpPrompts() { return std::vector<HelpPrompt>(); };
|
||||
virtual std::vector<HelpPrompt> getHelpPrompts() { return std::vector<HelpPrompt>(); }
|
||||
|
||||
// Called whenever help prompts change.
|
||||
void updateHelpPrompts();
|
||||
|
||||
virtual HelpStyle getHelpStyle();
|
||||
virtual HelpStyle getHelpStyle() { return HelpStyle(); }
|
||||
|
||||
// Returns true if the component is busy doing background processing (e.g. HTTP downloads).
|
||||
bool isProcessing() const;
|
||||
bool isProcessing() const { return mIsProcessing; }
|
||||
|
||||
const static unsigned char MAX_ANIMATIONS = 4;
|
||||
|
||||
|
|
|
@ -31,9 +31,9 @@ void HelpStyle::applyTheme(const std::shared_ptr<ThemeData>& theme, const std::s
|
|||
return;
|
||||
|
||||
if (elem->has("pos"))
|
||||
position = elem->get<Vector2f>("pos") *
|
||||
Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
position =
|
||||
elem->get<Vector2f>("pos") * Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
|
||||
if (elem->has("origin"))
|
||||
origin = elem->get<Vector2f>("origin");
|
||||
|
|
|
@ -10,21 +10,21 @@
|
|||
|
||||
#include "HttpReq.h"
|
||||
|
||||
#include "Log.h"
|
||||
#include "resources/ResourceManager.h"
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "Log.h"
|
||||
|
||||
#include <assert.h>
|
||||
|
||||
CURLM* HttpReq::s_multi_handle;
|
||||
std::map<CURL*, HttpReq*> HttpReq::s_requests;
|
||||
|
||||
std::string HttpReq::urlEncode(const std::string &s)
|
||||
std::string HttpReq::urlEncode(const std::string& s)
|
||||
{
|
||||
const std::string unreserved =
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
|
||||
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~";
|
||||
|
||||
std::string escaped="";
|
||||
std::string escaped = "";
|
||||
for (size_t i = 0; i < s.length(); i++) {
|
||||
if (unreserved.find_first_of(s[i]) != std::string::npos) {
|
||||
escaped.push_back(s[i]);
|
||||
|
@ -43,11 +43,13 @@ bool HttpReq::isUrl(const std::string& str)
|
|||
{
|
||||
// The worst guess.
|
||||
return (!str.empty() && !Utils::FileSystem::exists(str) &&
|
||||
(str.find("http://") != std::string::npos || str.find("https://") !=
|
||||
std::string::npos || str.find("www.") != std::string::npos));
|
||||
(str.find("http://") != std::string::npos ||
|
||||
str.find("https://") != std::string::npos || str.find("www.") != std::string::npos));
|
||||
}
|
||||
|
||||
HttpReq::HttpReq(const std::string& url) : mStatus(REQ_IN_PROGRESS), mHandle(nullptr)
|
||||
HttpReq::HttpReq(const std::string& url)
|
||||
: mStatus(REQ_IN_PROGRESS)
|
||||
, mHandle(nullptr)
|
||||
{
|
||||
// The multi-handle is cleaned up via a call from GuiScraperSearch after the scraping
|
||||
// has been completed for a game, meaning the handle is valid for all cURL requests
|
||||
|
@ -57,14 +59,16 @@ HttpReq::HttpReq(const std::string& url) : mStatus(REQ_IN_PROGRESS), mHandle(nul
|
|||
|
||||
mHandle = curl_easy_init();
|
||||
|
||||
#if defined(_WIN64)
|
||||
// On Windows, use the bundled cURL TLS/SSL certificates (which actually come from the
|
||||
// Mozilla project). There is a possibility to use the OS provided Schannel certificates
|
||||
// but I haven't been able to get this to work and it also seems to be problematic on
|
||||
// older Windows versions.
|
||||
#if defined(_WIN64)
|
||||
curl_easy_setopt(mHandle, CURLOPT_CAINFO, ResourceManager::getInstance()->
|
||||
getResourcePath(":/certificates/curl-ca-bundle.crt").c_str());
|
||||
#endif
|
||||
curl_easy_setopt(mHandle, CURLOPT_CAINFO,
|
||||
ResourceManager::getInstance()
|
||||
->getResourcePath(":/certificates/curl-ca-bundle.crt")
|
||||
.c_str());
|
||||
#endif
|
||||
|
||||
if (mHandle == nullptr) {
|
||||
mStatus = REQ_IO_ERROR;
|
||||
|
@ -140,8 +144,8 @@ HttpReq::~HttpReq()
|
|||
CURLMcode merr = curl_multi_remove_handle(s_multi_handle, mHandle);
|
||||
|
||||
if (merr != CURLM_OK) {
|
||||
LOG(LogError) << "Error removing curl_easy handle from curl_multi: " <<
|
||||
curl_multi_strerror(merr);
|
||||
LOG(LogError) << "Error removing curl_easy handle from curl_multi: "
|
||||
<< curl_multi_strerror(merr);
|
||||
}
|
||||
|
||||
curl_easy_cleanup(mHandle);
|
||||
|
@ -194,16 +198,6 @@ std::string HttpReq::getContent() const
|
|||
return mContent.str();
|
||||
}
|
||||
|
||||
void HttpReq::onError(const std::string& msg)
|
||||
{
|
||||
mErrorMsg = msg;
|
||||
}
|
||||
|
||||
std::string HttpReq::getErrorMsg()
|
||||
{
|
||||
return mErrorMsg;
|
||||
}
|
||||
|
||||
// Used as a curl callback.
|
||||
// size = size of an element, nmemb = number of elements.
|
||||
// Return value is number of elements successfully read.
|
||||
|
|
|
@ -43,6 +43,7 @@ public:
|
|||
~HttpReq();
|
||||
|
||||
enum Status {
|
||||
// clang-format off
|
||||
REQ_IN_PROGRESS, // Request is in progress.
|
||||
REQ_SUCCESS, // Request completed successfully, get it with getContent().
|
||||
REQ_IO_ERROR, // Some error happened, get it with getErrorMsg().
|
||||
|
@ -50,13 +51,14 @@ public:
|
|||
REQ_BAD_STATUS_CODE, // Some invalid HTTP response status code happened (non-200).
|
||||
REQ_INVALID_RESPONSE, // The HTTP response was invalid.
|
||||
REQ_UNDEFINED_ERROR
|
||||
// clang-format on
|
||||
};
|
||||
|
||||
Status status(); // Process any received data and return the status afterwards.
|
||||
std::string getErrorMsg();
|
||||
std::string getErrorMsg() { return mErrorMsg; }
|
||||
std::string getContent() const; // mStatus must be REQ_SUCCESS.
|
||||
|
||||
static std::string urlEncode(const std::string &s);
|
||||
static std::string urlEncode(const std::string& s);
|
||||
static bool isUrl(const std::string& s);
|
||||
|
||||
static void cleanupCurlMulti()
|
||||
|
@ -65,11 +67,11 @@ public:
|
|||
curl_multi_cleanup(s_multi_handle);
|
||||
s_multi_handle = nullptr;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private:
|
||||
static size_t write_content(void* buff, size_t size, size_t nmemb, void* req_ptr);
|
||||
void onError(const std::string& msg);
|
||||
void onError(const std::string& msg) { mErrorMsg = msg; }
|
||||
|
||||
// God dammit libcurl why can't you have some way to check the status of an
|
||||
// individual handle why do I have to handle ALL messages at once.
|
||||
|
|
|
@ -14,7 +14,9 @@
|
|||
#include <string.h>
|
||||
|
||||
std::vector<unsigned char> ImageIO::loadFromMemoryRGBA32(const unsigned char* data,
|
||||
const size_t size, size_t& width, size_t& height)
|
||||
const size_t size,
|
||||
size_t& width,
|
||||
size_t& height)
|
||||
{
|
||||
std::vector<unsigned char> rawData;
|
||||
width = 0;
|
||||
|
@ -44,8 +46,7 @@ std::vector<unsigned char> ImageIO::loadFromMemoryRGBA32(const unsigned char* da
|
|||
// This is necessary, because width*height*bpp might not be == pitch.
|
||||
unsigned char* tempData = new unsigned char[width * height * 4];
|
||||
for (size_t i = 0; i < height; i++) {
|
||||
const BYTE* scanLine =
|
||||
FreeImage_GetScanLine(fiBitmap, static_cast<int>(i));
|
||||
const BYTE* scanLine = FreeImage_GetScanLine(fiBitmap, static_cast<int>(i));
|
||||
memcpy(tempData + (i * width * 4), scanLine, width * 4);
|
||||
}
|
||||
// Convert from BGRA to RGBA.
|
||||
|
@ -69,8 +70,8 @@ std::vector<unsigned char> ImageIO::loadFromMemoryRGBA32(const unsigned char* da
|
|||
}
|
||||
}
|
||||
else {
|
||||
LOG(LogError) << "Couldn't load image, file is missing or the file type is " <<
|
||||
(format == FIF_UNKNOWN ? "unknown" : "unsupported");
|
||||
LOG(LogError) << "Couldn't load image, file is missing or the file type is "
|
||||
<< (format == FIF_UNKNOWN ? "unknown" : "unsupported");
|
||||
}
|
||||
// Free fiMemory again.
|
||||
FreeImage_CloseMemory(fiMemory);
|
||||
|
|
|
@ -16,7 +16,9 @@ class ImageIO
|
|||
{
|
||||
public:
|
||||
static std::vector<unsigned char> loadFromMemoryRGBA32(const unsigned char* data,
|
||||
const size_t size, size_t& width, size_t& height);
|
||||
const size_t size,
|
||||
size_t& width,
|
||||
size_t& height);
|
||||
static void flipPixelsVert(unsigned char* imagePx, const size_t& width, const size_t& height);
|
||||
};
|
||||
|
||||
|
|
|
@ -12,13 +12,10 @@
|
|||
|
||||
#include <pugixml.hpp>
|
||||
|
||||
InputConfig::InputConfig(
|
||||
int deviceId,
|
||||
const std::string& deviceName,
|
||||
const std::string& deviceGUID)
|
||||
: mDeviceId(deviceId),
|
||||
mDeviceName(deviceName),
|
||||
mDeviceGUID(deviceGUID)
|
||||
InputConfig::InputConfig(int deviceId, const std::string& deviceName, const std::string& deviceGUID)
|
||||
: mDeviceId(deviceId)
|
||||
, mDeviceName(deviceName)
|
||||
, mDeviceGUID(deviceGUID)
|
||||
{
|
||||
}
|
||||
|
||||
|
@ -59,16 +56,6 @@ std::string InputConfig::toLower(std::string str)
|
|||
return str;
|
||||
}
|
||||
|
||||
void InputConfig::clear()
|
||||
{
|
||||
mNameMap.clear();
|
||||
}
|
||||
|
||||
bool InputConfig::isConfigured()
|
||||
{
|
||||
return mNameMap.size() > 0;
|
||||
}
|
||||
|
||||
void InputConfig::mapInput(const std::string& name, Input input)
|
||||
{
|
||||
mNameMap[toLower(name)] = input;
|
||||
|
@ -100,19 +87,19 @@ bool InputConfig::isMappedLike(const std::string& name, Input input)
|
|||
{
|
||||
if (name == "left") {
|
||||
return isMappedTo("left", input) || isMappedTo("leftthumbstickleft", input) ||
|
||||
isMappedTo("rightthumbstickleft", input);
|
||||
isMappedTo("rightthumbstickleft", input);
|
||||
}
|
||||
else if (name == "right") {
|
||||
return isMappedTo("right", input) || isMappedTo("leftthumbstickright", input) ||
|
||||
isMappedTo("rightthumbstickright", input);
|
||||
isMappedTo("rightthumbstickright", input);
|
||||
}
|
||||
else if (name == "up") {
|
||||
return isMappedTo("up", input) || isMappedTo("leftthumbstickup", input) ||
|
||||
isMappedTo("rightthumbstickup", input);
|
||||
isMappedTo("rightthumbstickup", input);
|
||||
}
|
||||
else if (name == "down") {
|
||||
return isMappedTo("down", input) || isMappedTo("leftthumbstickdown", input) ||
|
||||
isMappedTo("rightthumbstickdown", input);
|
||||
isMappedTo("rightthumbstickdown", input);
|
||||
}
|
||||
else if (name == "leftshoulder") {
|
||||
return isMappedTo("leftshoulder", input) || isMappedTo("pageup", input);
|
||||
|
@ -182,8 +169,8 @@ void InputConfig::loadFromXML(pugi::xml_node& node)
|
|||
InputType typeEnum = stringToInputType(type);
|
||||
|
||||
if (typeEnum == TYPE_COUNT) {
|
||||
LOG(LogError) << "InputConfig load error - input of type \"" << type <<
|
||||
"\" is invalid! Skipping input \"" << name << "\".\n";
|
||||
LOG(LogError) << "InputConfig load error - input of type \"" << type
|
||||
<< "\" is invalid! Skipping input \"" << name << "\".\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
|
@ -191,8 +178,7 @@ void InputConfig::loadFromXML(pugi::xml_node& node)
|
|||
int value = input.attribute("value").as_int();
|
||||
|
||||
if (value == 0) {
|
||||
LOG(LogWarning) << "InputConfig value is 0 for " <<
|
||||
type << " " << id << "!\n";
|
||||
LOG(LogWarning) << "InputConfig value is 0 for " << type << " " << id << "!\n";
|
||||
}
|
||||
|
||||
mNameMap[toLower(name)] = Input(mDeviceId, typeEnum, id, value, true);
|
||||
|
|
|
@ -9,18 +9,18 @@
|
|||
#ifndef ES_CORE_INPUT_CONFIG_H
|
||||
#define ES_CORE_INPUT_CONFIG_H
|
||||
|
||||
#include <CECInput.h>
|
||||
#include <SDL2/SDL_joystick.h>
|
||||
#include <SDL2/SDL_keyboard.h>
|
||||
#include <CECInput.h>
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
#define DEVICE_KEYBOARD -1
|
||||
#define DEVICE_CEC -2
|
||||
#define DEVICE_CEC -2
|
||||
|
||||
enum InputType {
|
||||
TYPE_AXIS,
|
||||
TYPE_AXIS, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
TYPE_BUTTON,
|
||||
TYPE_KEY,
|
||||
TYPE_CEC_BUTTON,
|
||||
|
@ -32,8 +32,7 @@ namespace pugi
|
|||
class xml_node;
|
||||
}
|
||||
|
||||
struct Input
|
||||
{
|
||||
struct Input {
|
||||
public:
|
||||
int device;
|
||||
InputType type;
|
||||
|
@ -50,23 +49,16 @@ public:
|
|||
type = TYPE_COUNT;
|
||||
}
|
||||
|
||||
Input(
|
||||
int dev,
|
||||
InputType t,
|
||||
int i,
|
||||
int val,
|
||||
bool conf)
|
||||
: device(dev),
|
||||
type(t),id(i),
|
||||
value(val),
|
||||
configured(conf)
|
||||
Input(int dev, InputType t, int i, int val, bool conf)
|
||||
: device(dev)
|
||||
, type(t)
|
||||
, id(i)
|
||||
, value(val)
|
||||
, configured(conf)
|
||||
{
|
||||
}
|
||||
|
||||
std::string getCECButtonName(int keycode)
|
||||
{
|
||||
return CECInput::getKeyCodeString(keycode);
|
||||
}
|
||||
std::string getCECButtonName(int keycode) { return CECInput::getKeyCodeString(keycode); }
|
||||
|
||||
std::string string()
|
||||
{
|
||||
|
@ -113,8 +105,8 @@ public:
|
|||
InputType stringToInputType(const std::string& type);
|
||||
std::string toLower(std::string str);
|
||||
|
||||
void clear();
|
||||
bool isConfigured();
|
||||
void clear() { mNameMap.clear(); }
|
||||
bool isConfigured() { return mNameMap.size() > 0; }
|
||||
|
||||
void mapInput(const std::string& name, Input input);
|
||||
void unmapInput(const std::string& name); // Unmap all Inputs mapped to this name.
|
||||
|
@ -134,9 +126,9 @@ public:
|
|||
void loadFromXML(pugi::xml_node& root);
|
||||
void writeToXML(pugi::xml_node& parent);
|
||||
|
||||
inline int getDeviceId() const { return mDeviceId; };
|
||||
inline const std::string& getDeviceName() { return mDeviceName; }
|
||||
inline const std::string& getDeviceGUIDString() { return mDeviceGUID; }
|
||||
int getDeviceId() const { return mDeviceId; }
|
||||
const std::string& getDeviceName() { return mDeviceName; }
|
||||
const std::string& getDeviceGUIDString() { return mDeviceGUID; }
|
||||
|
||||
private:
|
||||
std::map<std::string, Input> mNameMap;
|
||||
|
|
|
@ -10,14 +10,14 @@
|
|||
|
||||
#include "InputManager.h"
|
||||
|
||||
#include "resources/ResourceManager.h"
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "CECInput.h"
|
||||
#include "Log.h"
|
||||
#include "Platform.h"
|
||||
#include "Scripting.h"
|
||||
#include "Window.h"
|
||||
#include "resources/ResourceManager.h"
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "utils/StringUtil.h"
|
||||
|
||||
#include <iostream>
|
||||
#include <pugixml.hpp>
|
||||
|
@ -30,12 +30,14 @@ int SDL_USER_CECBUTTONUP = -1;
|
|||
|
||||
InputManager* InputManager::sInstance = nullptr;
|
||||
|
||||
InputManager::InputManager() : mKeyboardInputConfig(nullptr)
|
||||
InputManager::InputManager()
|
||||
: mKeyboardInputConfig(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
InputManager::~InputManager()
|
||||
{
|
||||
// Deinit when destroyed.
|
||||
deinit();
|
||||
}
|
||||
|
||||
|
@ -66,8 +68,8 @@ void InputManager::init()
|
|||
mConfigFileExists = true;
|
||||
}
|
||||
|
||||
mKeyboardInputConfig = std::make_unique<InputConfig>(DEVICE_KEYBOARD,
|
||||
"Keyboard", KEYBOARD_GUID_STRING);
|
||||
mKeyboardInputConfig =
|
||||
std::make_unique<InputConfig>(DEVICE_KEYBOARD, "Keyboard", KEYBOARD_GUID_STRING);
|
||||
|
||||
bool customConfig = loadInputConfig(mKeyboardInputConfig.get());
|
||||
|
||||
|
@ -84,18 +86,18 @@ void InputManager::init()
|
|||
// the bundled mapping is incorrect, or the SDL version is a bit older, it makes sense to be
|
||||
// able to customize this. If a controller GUID is present in the mappings file that is
|
||||
// already present inside SDL, the custom mapping will overwrite the bundled one.
|
||||
std::string mappingsFile = Utils::FileSystem::getHomePath() +
|
||||
"/.emulationstation/" + "es_controller_mappings.cfg";
|
||||
std::string mappingsFile =
|
||||
Utils::FileSystem::getHomePath() + "/.emulationstation/" + "es_controller_mappings.cfg";
|
||||
|
||||
if (!Utils::FileSystem::exists(mappingsFile))
|
||||
mappingsFile = ResourceManager::getInstance()->
|
||||
getResourcePath(":/controllers/es_controller_mappings.cfg");
|
||||
mappingsFile = ResourceManager::getInstance()->getResourcePath(
|
||||
":/controllers/es_controller_mappings.cfg");
|
||||
|
||||
int controllerMappings = SDL_GameControllerAddMappingsFromFile(mappingsFile.c_str());
|
||||
|
||||
if (controllerMappings != -1 && controllerMappings != 0) {
|
||||
LOG(LogInfo) << "Loaded " << controllerMappings << " controller " <<
|
||||
(controllerMappings == 1 ? "mapping" : "mappings");
|
||||
LOG(LogInfo) << "Loaded " << controllerMappings << " controller "
|
||||
<< (controllerMappings == 1 ? "mapping" : "mappings");
|
||||
}
|
||||
|
||||
int numJoysticks = SDL_NumJoysticks();
|
||||
|
@ -150,18 +152,20 @@ void InputManager::writeDeviceConfig(InputConfig* config)
|
|||
std::string path = getConfigPath();
|
||||
|
||||
LOG(LogDebug) << "InputManager::writeDeviceConfig(): "
|
||||
"Saving input configuration file to \"" << path << "\"";
|
||||
"Saving input configuration file to \""
|
||||
<< path << "\"";
|
||||
|
||||
pugi::xml_document doc;
|
||||
|
||||
if (Utils::FileSystem::exists(path)) {
|
||||
// Merge files.
|
||||
#if defined(_WIN64)
|
||||
|
||||
#if defined(_WIN64)
|
||||
pugi::xml_parse_result result =
|
||||
doc.load_file(Utils::String::stringToWideString(path).c_str());
|
||||
#else
|
||||
doc.load_file(Utils::String::stringToWideString(path).c_str());
|
||||
#else
|
||||
pugi::xml_parse_result result = doc.load_file(path.c_str());
|
||||
#endif
|
||||
#endif
|
||||
if (!result) {
|
||||
LOG(LogError) << "Couldn't parse input configuration file: " << result.description();
|
||||
}
|
||||
|
@ -172,8 +176,8 @@ void InputManager::writeDeviceConfig(InputConfig* config)
|
|||
// If inputAction @type=onfinish is set, let doOnFinish command take care of
|
||||
// creating input configuration. We just put the input configuration into a
|
||||
// temporary input config file.
|
||||
pugi::xml_node actionnode = root.find_child_by_attribute("inputAction",
|
||||
"type", "onfinish");
|
||||
pugi::xml_node actionnode =
|
||||
root.find_child_by_attribute("inputAction", "type", "onfinish");
|
||||
if (actionnode) {
|
||||
path = getTemporaryConfigPath();
|
||||
doc.reset();
|
||||
|
@ -181,12 +185,12 @@ void InputManager::writeDeviceConfig(InputConfig* config)
|
|||
root.append_copy(actionnode);
|
||||
}
|
||||
else {
|
||||
pugi::xml_node oldEntry = root.find_child_by_attribute("inputConfig",
|
||||
"deviceGUID", config->getDeviceGUIDString().c_str());
|
||||
pugi::xml_node oldEntry = root.find_child_by_attribute(
|
||||
"inputConfig", "deviceGUID", config->getDeviceGUIDString().c_str());
|
||||
if (oldEntry)
|
||||
root.remove_child(oldEntry);
|
||||
oldEntry = root.find_child_by_attribute("inputConfig", "deviceName",
|
||||
config->getDeviceName().c_str());
|
||||
config->getDeviceName().c_str());
|
||||
if (oldEntry)
|
||||
root.remove_child(oldEntry);
|
||||
}
|
||||
|
@ -200,11 +204,11 @@ void InputManager::writeDeviceConfig(InputConfig* config)
|
|||
|
||||
config->writeToXML(root);
|
||||
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
doc.save_file(Utils::String::stringToWideString(path).c_str());
|
||||
#else
|
||||
#else
|
||||
doc.save_file(path.c_str());
|
||||
#endif
|
||||
#endif
|
||||
|
||||
Scripting::fireEvent("config-changed");
|
||||
Scripting::fireEvent("controls-changed");
|
||||
|
@ -222,12 +226,12 @@ void InputManager::doOnFinish()
|
|||
pugi::xml_document doc;
|
||||
|
||||
if (Utils::FileSystem::exists(path)) {
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
pugi::xml_parse_result result =
|
||||
doc.load_file(Utils::String::stringToWideString(path).c_str());
|
||||
#else
|
||||
doc.load_file(Utils::String::stringToWideString(path).c_str());
|
||||
#else
|
||||
pugi::xml_parse_result result = doc.load_file(path.c_str());
|
||||
#endif
|
||||
#endif
|
||||
|
||||
if (!result) {
|
||||
LOG(LogError) << "Couldn't parse input configuration file: " << result.description();
|
||||
|
@ -238,18 +242,18 @@ void InputManager::doOnFinish()
|
|||
root = root.find_child_by_attribute("inputAction", "type", "onfinish");
|
||||
if (root) {
|
||||
for (pugi::xml_node command = root.child("command"); command;
|
||||
command = command.next_sibling("command")) {
|
||||
command = command.next_sibling("command")) {
|
||||
std::string tocall = command.text().get();
|
||||
|
||||
LOG(LogInfo) << " " << tocall;
|
||||
std::cout << "==============================================\n"
|
||||
"input config finish command:\n";
|
||||
"input config finish command:\n";
|
||||
int exitCode = runSystemCommand(tocall);
|
||||
std::cout << "==============================================\n";
|
||||
|
||||
if (exitCode != 0) {
|
||||
LOG(LogWarning) << "...launch terminated with nonzero exit code " <<
|
||||
exitCode << "!";
|
||||
LOG(LogWarning) << "...launch terminated with nonzero exit code "
|
||||
<< exitCode << "!";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -298,11 +302,11 @@ int InputManager::getButtonCountByDevice(SDL_JoystickID id)
|
|||
if (id == DEVICE_KEYBOARD)
|
||||
return -1;
|
||||
else if (id == DEVICE_CEC)
|
||||
#if defined(HAVE_CECLIB)
|
||||
#if defined(HAVE_CECLIB)
|
||||
return CEC::CEC_USER_CONTROL_CODE_MAX;
|
||||
#else
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
#endif
|
||||
else
|
||||
return SDL_JoystickNumButtons(mJoysticks[id]);
|
||||
}
|
||||
|
@ -343,10 +347,10 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window)
|
|||
|
||||
switch (event.type) {
|
||||
case SDL_CONTROLLERAXISMOTION: {
|
||||
// Whether to only accept input from the first controller.
|
||||
if (Settings::getInstance()->getBool("InputOnlyFirstController"))
|
||||
if (mInputConfigs.begin()->first != event.cdevice.which)
|
||||
return false;
|
||||
// Whether to only accept input from the first controller.
|
||||
if (Settings::getInstance()->getBool("InputOnlyFirstController"))
|
||||
if (mInputConfigs.begin()->first != event.cdevice.which)
|
||||
return false;
|
||||
|
||||
// This is needed for a situation which sometimes occur when a game is launched,
|
||||
// some axis input is generated and then the controller is disconnected before
|
||||
|
@ -363,14 +367,17 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window)
|
|||
int deadzone = 0;
|
||||
|
||||
if (event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERLEFT ||
|
||||
event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT)
|
||||
event.caxis.axis == SDL_CONTROLLER_AXIS_TRIGGERRIGHT) {
|
||||
deadzone = DEADZONE_TRIGGERS;
|
||||
else
|
||||
}
|
||||
else {
|
||||
deadzone = DEADZONE_THUMBSTICKS;
|
||||
}
|
||||
|
||||
// Check if the input value switched boundaries.
|
||||
if ((abs(axisValue) > deadzone) != (abs(mPrevAxisValues[
|
||||
std::make_pair(event.caxis.which, event.caxis.axis)]) > deadzone)) {
|
||||
if ((abs(axisValue) > deadzone) !=
|
||||
(abs(mPrevAxisValues[std::make_pair(event.caxis.which, event.caxis.axis)]) >
|
||||
deadzone)) {
|
||||
int normValue;
|
||||
if (abs(axisValue) <= deadzone) {
|
||||
normValue = 0;
|
||||
|
@ -382,8 +389,9 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window)
|
|||
normValue = -1;
|
||||
}
|
||||
|
||||
window->input(getInputConfigByDevice(event.caxis.which), Input(event.caxis.which,
|
||||
TYPE_AXIS, event.caxis.axis, normValue, false));
|
||||
window->input(
|
||||
getInputConfigByDevice(event.caxis.which),
|
||||
Input(event.caxis.which, TYPE_AXIS, event.caxis.axis, normValue, false));
|
||||
causedEvent = true;
|
||||
}
|
||||
|
||||
|
@ -393,26 +401,27 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window)
|
|||
case SDL_CONTROLLERBUTTONDOWN: {
|
||||
}
|
||||
case SDL_CONTROLLERBUTTONUP: {
|
||||
// Whether to only accept input from the first controller.
|
||||
if (Settings::getInstance()->getBool("InputOnlyFirstController"))
|
||||
if (mInputConfigs.begin()->first != event.cdevice.which)
|
||||
return false;
|
||||
// Whether to only accept input from the first controller.
|
||||
if (Settings::getInstance()->getBool("InputOnlyFirstController"))
|
||||
if (mInputConfigs.begin()->first != event.cdevice.which)
|
||||
return false;
|
||||
|
||||
// The event filtering below is required as some controllers send button presses
|
||||
// starting with the state 0 when using the D-pad. I consider this invalid behaviour
|
||||
// and the more popular controllers such as those from Microsoft and Sony do not show
|
||||
// this strange behavior.
|
||||
int buttonState = mPrevButtonValues[
|
||||
std::make_pair(event.cbutton.which, event.cbutton.button)];
|
||||
int buttonState =
|
||||
mPrevButtonValues[std::make_pair(event.cbutton.which, event.cbutton.button)];
|
||||
|
||||
if ((buttonState == -1 || buttonState == 0) && event.cbutton.state == 0)
|
||||
return false;
|
||||
|
||||
mPrevButtonValues[std::make_pair(event.cbutton.which, event.cbutton.button)] =
|
||||
event.cbutton.state;
|
||||
event.cbutton.state;
|
||||
|
||||
window->input(getInputConfigByDevice(event.cbutton.which), Input(event.cbutton.which,
|
||||
TYPE_BUTTON, event.cbutton.button, event.cbutton.state == SDL_PRESSED, false));
|
||||
window->input(getInputConfigByDevice(event.cbutton.which),
|
||||
Input(event.cbutton.which, TYPE_BUTTON, event.cbutton.button,
|
||||
event.cbutton.state == SDL_PRESSED, false));
|
||||
|
||||
return true;
|
||||
}
|
||||
|
@ -430,13 +439,13 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window)
|
|||
return false;
|
||||
}
|
||||
|
||||
window->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD,
|
||||
TYPE_KEY, event.key.keysym.sym, 1, false));
|
||||
window->input(getInputConfigByDevice(DEVICE_KEYBOARD),
|
||||
Input(DEVICE_KEYBOARD, TYPE_KEY, event.key.keysym.sym, 1, false));
|
||||
return true;
|
||||
}
|
||||
case SDL_KEYUP: {
|
||||
window->input(getInputConfigByDevice(DEVICE_KEYBOARD), Input(DEVICE_KEYBOARD,
|
||||
TYPE_KEY, event.key.keysym.sym, 0, false));
|
||||
window->input(getInputConfigByDevice(DEVICE_KEYBOARD),
|
||||
Input(DEVICE_KEYBOARD, TYPE_KEY, event.key.keysym.sym, 0, false));
|
||||
return true;
|
||||
}
|
||||
case SDL_TEXTINPUT: {
|
||||
|
@ -454,21 +463,17 @@ bool InputManager::parseEvent(const SDL_Event& event, Window* window)
|
|||
}
|
||||
|
||||
if ((event.type == static_cast<unsigned int>(SDL_USER_CECBUTTONDOWN)) ||
|
||||
(event.type == static_cast<unsigned int>(SDL_USER_CECBUTTONUP))) {
|
||||
window->input(getInputConfigByDevice(DEVICE_CEC), Input(DEVICE_CEC,
|
||||
TYPE_CEC_BUTTON, event.user.code, event.type ==
|
||||
static_cast<unsigned int>(SDL_USER_CECBUTTONDOWN), false));
|
||||
(event.type == static_cast<unsigned int>(SDL_USER_CECBUTTONUP))) {
|
||||
window->input(getInputConfigByDevice(DEVICE_CEC),
|
||||
Input(DEVICE_CEC, TYPE_CEC_BUTTON, event.user.code,
|
||||
event.type == static_cast<unsigned int>(SDL_USER_CECBUTTONDOWN),
|
||||
false));
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool InputManager::initialized() const
|
||||
{
|
||||
return mKeyboardInputConfig != nullptr;
|
||||
}
|
||||
|
||||
bool InputManager::loadInputConfig(InputConfig* config)
|
||||
{
|
||||
if (!mConfigFileExists)
|
||||
|
@ -477,11 +482,11 @@ bool InputManager::loadInputConfig(InputConfig* config)
|
|||
std::string path = getConfigPath();
|
||||
|
||||
pugi::xml_document doc;
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
pugi::xml_parse_result res = doc.load_file(Utils::String::stringToWideString(path).c_str());
|
||||
#else
|
||||
#else
|
||||
pugi::xml_parse_result res = doc.load_file(path.c_str());
|
||||
#endif
|
||||
#endif
|
||||
|
||||
if (!res) {
|
||||
LOG(LogError) << "Couldn't parse the input configuration file: " << res.description();
|
||||
|
@ -492,16 +497,16 @@ bool InputManager::loadInputConfig(InputConfig* config)
|
|||
if (!root)
|
||||
return false;
|
||||
|
||||
pugi::xml_node configNode = root.find_child_by_attribute("inputConfig",
|
||||
"deviceGUID", config->getDeviceGUIDString().c_str());
|
||||
pugi::xml_node configNode = root.find_child_by_attribute("inputConfig", "deviceGUID",
|
||||
config->getDeviceGUIDString().c_str());
|
||||
|
||||
// Enabling this will match an entry in es_input.xml based on the device name if there
|
||||
// was no GUID match. This is probably not a good idea as many controllers share the same
|
||||
// name even though the GUID differ and potentially the button configuration could be
|
||||
// different between them. Keeping the code for now though.
|
||||
// if (!configNode)
|
||||
// configNode = root.find_child_by_attribute("inputConfig",
|
||||
// "deviceName", config->getDeviceName().c_str());
|
||||
// if (!configNode)
|
||||
// configNode = root.find_child_by_attribute("inputConfig",
|
||||
// "deviceName", config->getDeviceName().c_str());
|
||||
|
||||
// With the move to the SDL GameController API the button layout changed quite a lot, so
|
||||
// es_input.xml files generated using the old API will end up with a completely unusable
|
||||
|
@ -535,11 +540,11 @@ void InputManager::loadDefaultKBConfig()
|
|||
cfg->mapInput("A", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_RETURN, 1, true));
|
||||
cfg->mapInput("B", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_BACKSPACE, 1, true));
|
||||
cfg->mapInput("X", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_DELETE, 1, true));
|
||||
#if defined(__APPLE__)
|
||||
#if defined(__APPLE__)
|
||||
cfg->mapInput("Y", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_PRINTSCREEN, 1, true));
|
||||
#else
|
||||
#else
|
||||
cfg->mapInput("Y", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_INSERT, 1, true));
|
||||
#endif
|
||||
#endif
|
||||
cfg->mapInput("Start", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_ESCAPE, 1, true));
|
||||
cfg->mapInput("Back", Input(DEVICE_KEYBOARD, TYPE_KEY, SDLK_F1, 1, true));
|
||||
|
||||
|
@ -559,6 +564,7 @@ void InputManager::loadDefaultControllerConfig(SDL_JoystickID deviceIndex)
|
|||
if (cfg->isConfigured())
|
||||
return;
|
||||
|
||||
// clang-format off
|
||||
cfg->mapInput("Up", Input(deviceIndex, TYPE_BUTTON, SDL_CONTROLLER_BUTTON_DPAD_UP, 1, true));
|
||||
cfg->mapInput("Down", Input(deviceIndex, TYPE_BUTTON, SDL_CONTROLLER_BUTTON_DPAD_DOWN, 1, true));
|
||||
cfg->mapInput("Left", Input(deviceIndex, TYPE_BUTTON, SDL_CONTROLLER_BUTTON_DPAD_LEFT, 1, true));
|
||||
|
@ -583,6 +589,7 @@ void InputManager::loadDefaultControllerConfig(SDL_JoystickID deviceIndex)
|
|||
cfg->mapInput("RightThumbstickLeft", Input(deviceIndex, TYPE_AXIS, SDL_CONTROLLER_AXIS_RIGHTX, -1, true));
|
||||
cfg->mapInput("RightThumbstickRight", Input(deviceIndex, TYPE_AXIS, SDL_CONTROLLER_AXIS_RIGHTX, 1, true));
|
||||
cfg->mapInput("RightThumbstickClick", Input(deviceIndex, TYPE_BUTTON, SDL_CONTROLLER_BUTTON_RIGHTSTICK, 1, true));
|
||||
// clang-format on
|
||||
}
|
||||
|
||||
void InputManager::addControllerByDeviceIndex(int deviceIndex)
|
||||
|
@ -599,21 +606,21 @@ void InputManager::addControllerByDeviceIndex(int deviceIndex)
|
|||
char guid[65];
|
||||
SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joy), guid, 65);
|
||||
|
||||
mInputConfigs[joyID] = std::make_unique<InputConfig>(
|
||||
joyID, SDL_GameControllerName(mControllers[joyID]), guid);
|
||||
mInputConfigs[joyID] =
|
||||
std::make_unique<InputConfig>(joyID, SDL_GameControllerName(mControllers[joyID]), guid);
|
||||
|
||||
bool customConfig = loadInputConfig(mInputConfigs[joyID].get());
|
||||
|
||||
if (customConfig) {
|
||||
LOG(LogInfo) << "Added controller with custom configuration: \"" <<
|
||||
SDL_GameControllerName(mControllers[joyID]) << "\" (GUID: " << guid <<
|
||||
", instance ID: " << joyID << ", device index: " << deviceIndex << ")";
|
||||
LOG(LogInfo) << "Added controller with custom configuration: \""
|
||||
<< SDL_GameControllerName(mControllers[joyID]) << "\" (GUID: " << guid
|
||||
<< ", instance ID: " << joyID << ", device index: " << deviceIndex << ")";
|
||||
}
|
||||
else {
|
||||
loadDefaultControllerConfig(joyID);
|
||||
LOG(LogInfo) << "Added controller with default configuration: \"" <<
|
||||
SDL_GameControllerName(mControllers[joyID]) << "\" (GUID: " << guid <<
|
||||
", instance ID: " << joyID << ", device index: " << deviceIndex << ")";
|
||||
LOG(LogInfo) << "Added controller with default configuration: \""
|
||||
<< SDL_GameControllerName(mControllers[joyID]) << "\" (GUID: " << guid
|
||||
<< ", instance ID: " << joyID << ", device index: " << deviceIndex << ")";
|
||||
}
|
||||
|
||||
int numAxes = SDL_JoystickNumAxes(joy);
|
||||
|
@ -634,8 +641,8 @@ void InputManager::removeControllerByJoystickID(SDL_JoystickID joyID)
|
|||
SDL_Joystick* joy = SDL_JoystickFromInstanceID(joyID);
|
||||
SDL_JoystickGetGUIDString(SDL_JoystickGetGUID(joy), guid, 65);
|
||||
|
||||
LOG(LogInfo) << "Removed controller \"" << SDL_GameControllerName(mControllers[joyID]) <<
|
||||
"\" (GUID: " << guid << ", instance ID: " << joyID << ")";
|
||||
LOG(LogInfo) << "Removed controller \"" << SDL_GameControllerName(mControllers[joyID])
|
||||
<< "\" (GUID: " << guid << ", instance ID: " << joyID << ")";
|
||||
|
||||
// Delete mPrevAxisValues for the device.
|
||||
int axisEntries = static_cast<int>(mPrevAxisValues.size());
|
||||
|
|
|
@ -55,7 +55,7 @@ public:
|
|||
int getNumJoysticks() { return static_cast<int>(mJoysticks.size()); }
|
||||
|
||||
private:
|
||||
bool initialized() const;
|
||||
bool initialized() const { return mKeyboardInputConfig != nullptr; }
|
||||
|
||||
bool loadInputConfig(InputConfig* config);
|
||||
void loadDefaultKBConfig();
|
||||
|
|
|
@ -8,32 +8,16 @@
|
|||
|
||||
#include "Log.h"
|
||||
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Platform.h"
|
||||
#include "utils/StringUtil.h"
|
||||
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
|
||||
LogLevel Log::reportingLevel = LogInfo;
|
||||
std::ofstream file;
|
||||
|
||||
LogLevel Log::getReportingLevel()
|
||||
{
|
||||
return reportingLevel;
|
||||
}
|
||||
|
||||
std::string Log::getLogPath()
|
||||
{
|
||||
return Utils::FileSystem::getHomePath() + "/.emulationstation/es_log.txt";
|
||||
}
|
||||
|
||||
void Log::setReportingLevel(LogLevel level)
|
||||
{
|
||||
reportingLevel = level;
|
||||
}
|
||||
|
||||
void Log::init()
|
||||
{
|
||||
Utils::FileSystem::removeFile(getLogPath() + ".bak");
|
||||
|
@ -44,24 +28,24 @@ void Log::init()
|
|||
|
||||
void Log::open()
|
||||
{
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
file.open(Utils::String::stringToWideString(getLogPath()).c_str());
|
||||
#else
|
||||
#else
|
||||
file.open(getLogPath().c_str());
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
std::ostringstream& Log::get(LogLevel level)
|
||||
{
|
||||
time_t t = time(nullptr);
|
||||
struct tm tm;
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
// Of course Windows does not follow standards and puts the parameters the other way
|
||||
// around compared to POSIX.
|
||||
localtime_s(&tm, &t);
|
||||
#else
|
||||
#else
|
||||
localtime_r(&t, &tm);
|
||||
#endif
|
||||
#endif
|
||||
os << std::put_time(&tm, "%b %d %T ") << logLevelMap[level] << ":\t";
|
||||
messageLevel = level;
|
||||
|
||||
|
@ -70,6 +54,7 @@ std::ostringstream& Log::get(LogLevel level)
|
|||
|
||||
void Log::flush()
|
||||
{
|
||||
// This runs on application exit.
|
||||
file.flush();
|
||||
}
|
||||
|
||||
|
@ -85,8 +70,8 @@ Log::~Log()
|
|||
|
||||
if (!file.is_open()) {
|
||||
// Not open yet, print to stdout.
|
||||
std::cerr << "ERROR - tried to write to log file before it was open! "
|
||||
"The following won't be logged:\n";
|
||||
std::cerr << "Error: Tried to write to log file before it was open, "
|
||||
"the following won't be logged:\n";
|
||||
std::cerr << os.str();
|
||||
return;
|
||||
}
|
||||
|
|
|
@ -9,15 +9,19 @@
|
|||
#ifndef ES_CORE_LOG_H
|
||||
#define ES_CORE_LOG_H
|
||||
|
||||
#include "utils/FileSystemUtil.h"
|
||||
|
||||
#include <map>
|
||||
#include <sstream>
|
||||
|
||||
#define LOG(level) \
|
||||
if (level > Log::getReportingLevel()); \
|
||||
else Log().get(level)
|
||||
#define LOG(level) \
|
||||
if (level > Log::getReportingLevel()) \
|
||||
; \
|
||||
else \
|
||||
Log().get(level)
|
||||
|
||||
enum LogLevel {
|
||||
LogError,
|
||||
LogError, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
LogWarning,
|
||||
LogInfo,
|
||||
LogDebug
|
||||
|
@ -29,10 +33,12 @@ public:
|
|||
~Log();
|
||||
std::ostringstream& get(LogLevel level = LogInfo);
|
||||
|
||||
static LogLevel getReportingLevel();
|
||||
static void setReportingLevel(LogLevel level);
|
||||
|
||||
static std::string getLogPath();
|
||||
static LogLevel getReportingLevel() { return reportingLevel; }
|
||||
static void setReportingLevel(LogLevel level) { reportingLevel = level; }
|
||||
static std::string getLogPath()
|
||||
{
|
||||
return Utils::FileSystem::getHomePath() + "/.emulationstation/es_log.txt";
|
||||
}
|
||||
|
||||
static void flush();
|
||||
static void init();
|
||||
|
@ -43,11 +49,11 @@ protected:
|
|||
std::ostringstream os;
|
||||
|
||||
private:
|
||||
std::map<LogLevel, std::string> logLevelMap {
|
||||
{ LogError, "Error" },
|
||||
{ LogWarning, "Warn" },
|
||||
{ LogInfo, "Info" },
|
||||
{ LogDebug, "Debug" }
|
||||
std::map<LogLevel, std::string> logLevelMap { // Log level indicators.
|
||||
{ LogError, "Error" },
|
||||
{ LogWarning, "Warn" },
|
||||
{ LogInfo, "Info" },
|
||||
{ LogDebug, "Debug" }
|
||||
};
|
||||
|
||||
static LogLevel reportingLevel;
|
||||
|
|
|
@ -11,10 +11,10 @@
|
|||
|
||||
#include "MameNames.h"
|
||||
|
||||
#include "Log.h"
|
||||
#include "resources/ResourceManager.h"
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Log.h"
|
||||
|
||||
#include <pugixml.hpp>
|
||||
#include <string.h>
|
||||
|
@ -53,25 +53,23 @@ MameNames::MameNames()
|
|||
LOG(LogInfo) << "Parsing MAME names file \"" << xmlpath << "\"...";
|
||||
|
||||
pugi::xml_document doc;
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
pugi::xml_parse_result result =
|
||||
doc.load_file(Utils::String::stringToWideString(xmlpath).c_str());
|
||||
#else
|
||||
doc.load_file(Utils::String::stringToWideString(xmlpath).c_str());
|
||||
#else
|
||||
pugi::xml_parse_result result = doc.load_file(xmlpath.c_str());
|
||||
#endif
|
||||
#endif
|
||||
|
||||
if (!result) {
|
||||
LOG(LogError) << "Error parsing MAME names file \"" << xmlpath << "\": "
|
||||
<< result.description();
|
||||
LOG(LogError) << "Error parsing MAME names file \"" << xmlpath
|
||||
<< "\": " << result.description();
|
||||
return;
|
||||
}
|
||||
|
||||
for (pugi::xml_node gameNode = doc.child("game");
|
||||
gameNode; gameNode = gameNode.next_sibling("game")) {
|
||||
NamePair namePair = {
|
||||
gameNode.child("mamename").text().get(),
|
||||
gameNode.child("realname").text().get()
|
||||
};
|
||||
for (pugi::xml_node gameNode = doc.child("game"); gameNode;
|
||||
gameNode = gameNode.next_sibling("game")) {
|
||||
NamePair namePair = { gameNode.child("mamename").text().get(),
|
||||
gameNode.child("realname").text().get() };
|
||||
mNamePairs.push_back(namePair);
|
||||
}
|
||||
|
||||
|
@ -83,20 +81,20 @@ MameNames::MameNames()
|
|||
|
||||
LOG(LogInfo) << "Parsing MAME BIOSes file \"" << xmlpath << "\"...";
|
||||
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
result = doc.load_file(Utils::String::stringToWideString(xmlpath).c_str());
|
||||
#else
|
||||
#else
|
||||
result = doc.load_file(xmlpath.c_str());
|
||||
#endif
|
||||
#endif
|
||||
|
||||
if (!result) {
|
||||
LOG(LogError) << "Error parsing MAME BIOSes file \"" << xmlpath << "\": "
|
||||
<< result.description();
|
||||
LOG(LogError) << "Error parsing MAME BIOSes file \"" << xmlpath
|
||||
<< "\": " << result.description();
|
||||
return;
|
||||
}
|
||||
|
||||
for (pugi::xml_node biosNode = doc.child("bios");
|
||||
biosNode; biosNode = biosNode.next_sibling("bios")) {
|
||||
for (pugi::xml_node biosNode = doc.child("bios"); biosNode;
|
||||
biosNode = biosNode.next_sibling("bios")) {
|
||||
std::string bios = biosNode.text().get();
|
||||
mMameBioses.push_back(bios);
|
||||
}
|
||||
|
@ -109,29 +107,25 @@ MameNames::MameNames()
|
|||
|
||||
LOG(LogInfo) << "Parsing MAME devices file \"" << xmlpath << "\"...";
|
||||
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
result = doc.load_file(Utils::String::stringToWideString(xmlpath).c_str());
|
||||
#else
|
||||
#else
|
||||
result = doc.load_file(xmlpath.c_str());
|
||||
#endif
|
||||
#endif
|
||||
|
||||
if (!result) {
|
||||
LOG(LogError) << "Error parsing MAME devices file \"" << xmlpath << "\": "
|
||||
<< result.description();
|
||||
LOG(LogError) << "Error parsing MAME devices file \"" << xmlpath
|
||||
<< "\": " << result.description();
|
||||
return;
|
||||
}
|
||||
|
||||
for (pugi::xml_node deviceNode = doc.child("device");
|
||||
deviceNode; deviceNode = deviceNode.next_sibling("device")) {
|
||||
for (pugi::xml_node deviceNode = doc.child("device"); deviceNode;
|
||||
deviceNode = deviceNode.next_sibling("device")) {
|
||||
std::string device = deviceNode.text().get();
|
||||
mMameDevices.push_back(device);
|
||||
}
|
||||
}
|
||||
|
||||
MameNames::~MameNames()
|
||||
{
|
||||
}
|
||||
|
||||
std::string MameNames::getRealName(const std::string& _mameName)
|
||||
{
|
||||
size_t start = 0;
|
||||
|
@ -158,17 +152,6 @@ std::string MameNames::getCleanName(const std::string& _mameName)
|
|||
return cleanName;
|
||||
}
|
||||
|
||||
const bool MameNames::isBios(const std::string& _biosName)
|
||||
{
|
||||
return MameNames::find(mMameBioses, _biosName);
|
||||
}
|
||||
|
||||
const bool MameNames::isDevice(const std::string& _deviceName)
|
||||
{
|
||||
return MameNames::find(mMameDevices, _deviceName);
|
||||
|
||||
}
|
||||
|
||||
const bool MameNames::find(std::vector<std::string> devices, const std::string& name)
|
||||
{
|
||||
size_t start = 0;
|
||||
|
|
|
@ -24,8 +24,14 @@ public:
|
|||
static MameNames* getInstance();
|
||||
std::string getRealName(const std::string& _mameName);
|
||||
std::string getCleanName(const std::string& _mameName);
|
||||
const bool isBios(const std::string& _biosName);
|
||||
const bool isDevice(const std::string& _deviceName);
|
||||
const bool isBios(const std::string& _biosName)
|
||||
{
|
||||
return MameNames::find(mMameBioses, _biosName);
|
||||
}
|
||||
const bool isDevice(const std::string& _deviceName)
|
||||
{
|
||||
return MameNames::find(mMameDevices, _deviceName);
|
||||
}
|
||||
|
||||
private:
|
||||
struct NamePair {
|
||||
|
@ -35,8 +41,8 @@ private:
|
|||
|
||||
typedef std::vector<NamePair> namePairVector;
|
||||
|
||||
MameNames();
|
||||
~MameNames();
|
||||
MameNames();
|
||||
~MameNames() {}
|
||||
|
||||
static MameNames* sInstance;
|
||||
|
||||
|
|
|
@ -8,12 +8,12 @@
|
|||
|
||||
#include "Platform.h"
|
||||
|
||||
#include "renderers/Renderer.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "AudioManager.h"
|
||||
#include "Log.h"
|
||||
#include "MameNames.h"
|
||||
#include "Settings.h"
|
||||
#include "renderers/Renderer.h"
|
||||
#include "utils/StringUtil.h"
|
||||
|
||||
#include <SDL2/SDL_events.h>
|
||||
|
||||
|
@ -52,36 +52,36 @@ int runPoweroffCommand()
|
|||
|
||||
int runSystemCommand(const std::string& cmd_utf8)
|
||||
{
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
// On Windows we use _wsystem to support non-ASCII paths
|
||||
// which requires converting from UTF-8 to a wstring.
|
||||
std::wstring wchar_str = Utils::String::stringToWideString(cmd_utf8);
|
||||
return _wsystem(wchar_str.c_str());
|
||||
#else
|
||||
#else
|
||||
return system(cmd_utf8.c_str());
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
int runSystemCommand(const std::wstring& cmd_utf16)
|
||||
{
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
return _wsystem(cmd_utf16.c_str());
|
||||
#else
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
int launchGameUnix(const std::string& cmd_utf8, bool runInBackground)
|
||||
{
|
||||
#if defined(__unix__) || defined (__APPLE__)
|
||||
#if defined(__unix__) || defined(__APPLE__)
|
||||
std::string command = std::string(cmd_utf8) + " 2>&1 &";
|
||||
|
||||
// Launching games while keeping ES-DE running in the background is very crude as for
|
||||
// instance no output from the command is captured and no real error handling is
|
||||
// implemented. It should therefore only be used when absolutely necessary.
|
||||
if (runInBackground) {
|
||||
LOG(LogDebug) << "Platform::launchGameUnix(): Launching game while keeping ES-DE "
|
||||
"running in the background, no command output will be written to the log file";
|
||||
LOG(LogDebug) << "Platform::launchGameUnix(): Launching game while keeping ES-DE running "
|
||||
"in the background, no command output will be written to the log file";
|
||||
return system(command.c_str());
|
||||
}
|
||||
|
||||
|
@ -106,12 +106,11 @@ int launchGameUnix(const std::string& cmd_utf8, bool runInBackground)
|
|||
// Remove any trailing newline from the command output.
|
||||
if (commandOutput.size()) {
|
||||
if (commandOutput.back() == '\n')
|
||||
commandOutput.pop_back();
|
||||
commandOutput.pop_back();
|
||||
}
|
||||
|
||||
if (returnValue) {
|
||||
LOG(LogError) << "launchGameUnix - return value " <<
|
||||
std::to_string(returnValue) + ":";
|
||||
LOG(LogError) << "launchGameUnix - return value " << std::to_string(returnValue) + ":";
|
||||
if (commandOutput.size())
|
||||
LOG(LogError) << commandOutput;
|
||||
else
|
||||
|
@ -124,14 +123,14 @@ int launchGameUnix(const std::string& cmd_utf8, bool runInBackground)
|
|||
|
||||
return returnValue;
|
||||
|
||||
#else // __unix__
|
||||
#else // __unix__
|
||||
return 0;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
int launchGameWindows(const std::wstring& cmd_utf16, bool runInBackground)
|
||||
{
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
STARTUPINFOW si {};
|
||||
PROCESS_INFORMATION pi;
|
||||
|
||||
|
@ -139,17 +138,19 @@ int launchGameWindows(const std::wstring& cmd_utf16, bool runInBackground)
|
|||
bool processReturnValue = true;
|
||||
DWORD errorCode = 0;
|
||||
|
||||
// clang-format off
|
||||
processReturnValue = CreateProcessW(
|
||||
nullptr, // No application name (use command line).
|
||||
const_cast<wchar_t*>(cmd_utf16.c_str()), // Command line.
|
||||
nullptr, // Process attributes.
|
||||
nullptr, // Thread attributes.
|
||||
FALSE, // Handles inheritance.
|
||||
0, // Creation flags.
|
||||
nullptr, // Use parent's environment block.
|
||||
nullptr, // Use parent's starting directory.
|
||||
&si, // Pointer to the STARTUPINFOW structure.
|
||||
&pi); // Pointer to the PROCESS_INFORMATION structure.
|
||||
nullptr, // No application name (use command line).
|
||||
const_cast<wchar_t*>(cmd_utf16.c_str()), // Command line.
|
||||
nullptr, // Process attributes.
|
||||
nullptr, // Thread attributes.
|
||||
FALSE, // Handles inheritance.
|
||||
0, // Creation flags.
|
||||
nullptr, // Use parent's environment block.
|
||||
nullptr, // Use parent's starting directory.
|
||||
&si, // Pointer to the STARTUPINFOW structure.
|
||||
&pi); // Pointer to the PROCESS_INFORMATION structure.
|
||||
// clang-format on
|
||||
|
||||
if (!runInBackground) {
|
||||
if (Settings::getInstance()->getBool("LaunchWorkaround")) {
|
||||
|
@ -169,9 +170,9 @@ int launchGameWindows(const std::wstring& cmd_utf16, bool runInBackground)
|
|||
if (!processReturnValue) {
|
||||
LPWSTR pBuffer = nullptr;
|
||||
|
||||
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
|
||||
nullptr, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||
reinterpret_cast<LPWSTR>(&pBuffer), 0, nullptr);
|
||||
FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER, nullptr,
|
||||
GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||
reinterpret_cast<LPWSTR>(&pBuffer), 0, nullptr);
|
||||
|
||||
errorCode = GetLastError();
|
||||
|
||||
|
@ -186,8 +187,8 @@ int launchGameWindows(const std::wstring& cmd_utf16, bool runInBackground)
|
|||
}
|
||||
}
|
||||
|
||||
LOG(LogError) << "launchGameWindows - system error code " <<
|
||||
errorCode << ": " << errorMessage;
|
||||
LOG(LogError) << "launchGameWindows - system error code " << errorCode << ": "
|
||||
<< errorMessage;
|
||||
}
|
||||
|
||||
// Close process and thread handles.
|
||||
|
@ -196,40 +197,40 @@ int launchGameWindows(const std::wstring& cmd_utf16, bool runInBackground)
|
|||
|
||||
return errorCode;
|
||||
|
||||
#else // _WIN64
|
||||
#else // _WIN64
|
||||
return 0;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
unsigned int getTaskbarState()
|
||||
{
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
APPBARDATA barData;
|
||||
barData.cbSize = sizeof(APPBARDATA);
|
||||
return static_cast<UINT>(SHAppBarMessage(ABM_GETSTATE, &barData));
|
||||
#else
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
void hideTaskbar()
|
||||
{
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
APPBARDATA barData;
|
||||
barData.cbSize = sizeof(APPBARDATA);
|
||||
barData.lParam = ABS_AUTOHIDE;
|
||||
SHAppBarMessage(ABM_SETSTATE, &barData);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
void revertTaskbarState(unsigned int& state)
|
||||
{
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
APPBARDATA barData;
|
||||
barData.cbSize = sizeof(APPBARDATA);
|
||||
barData.lParam = state;
|
||||
SHAppBarMessage(ABM_SETSTATE, &barData);
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
QuitMode quitMode = QuitMode::QUIT;
|
||||
|
@ -264,7 +265,7 @@ void touch(const std::string& filename)
|
|||
if (fp != nullptr)
|
||||
fclose(fp);
|
||||
#else
|
||||
int fd = open(filename.c_str(), O_CREAT|O_WRONLY, 0644);
|
||||
int fd = open(filename.c_str(), O_CREAT | O_WRONLY, 0644);
|
||||
if (fd >= 0)
|
||||
close(fd);
|
||||
#endif
|
||||
|
@ -273,15 +274,18 @@ void touch(const std::string& filename)
|
|||
void processQuitMode()
|
||||
{
|
||||
switch (quitMode) {
|
||||
case QuitMode::REBOOT:
|
||||
LOG(LogInfo) << "Rebooting system";
|
||||
runRebootCommand();
|
||||
break;
|
||||
case QuitMode::POWEROFF:
|
||||
LOG(LogInfo) << "Powering off system";
|
||||
runPoweroffCommand();
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
case QuitMode::REBOOT: {
|
||||
LOG(LogInfo) << "Rebooting system";
|
||||
runRebootCommand();
|
||||
break;
|
||||
}
|
||||
case QuitMode::POWEROFF: {
|
||||
LOG(LogInfo) << "Powering off system";
|
||||
runPoweroffCommand();
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
@ -12,11 +12,12 @@
|
|||
#include <string>
|
||||
|
||||
#if defined(_WIN64)
|
||||
#include <winsock2.h>
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
enum QuitMode {
|
||||
QUIT = 0,
|
||||
QUIT = 0, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
REBOOT = 1,
|
||||
POWEROFF = 2
|
||||
};
|
||||
|
@ -35,6 +36,7 @@ void revertTaskbarState(unsigned int& state);
|
|||
|
||||
// Clean, normal shutdown.
|
||||
int quitES(QuitMode mode = QuitMode::QUIT);
|
||||
|
||||
// Immediately shut down the application as cleanly as possible.
|
||||
void emergencyShutdown();
|
||||
void processQuitMode();
|
||||
|
|
|
@ -14,20 +14,20 @@
|
|||
|
||||
#include "Scripting.h"
|
||||
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "Log.h"
|
||||
#include "Platform.h"
|
||||
#include "Settings.h"
|
||||
#include "utils/FileSystemUtil.h"
|
||||
|
||||
namespace Scripting
|
||||
{
|
||||
void fireEvent(const std::string& eventName, const std::string& arg1, const std::string& arg2)
|
||||
{
|
||||
void fireEvent(const std::string& eventName, const std::string& arg1, const std::string& arg2)
|
||||
{
|
||||
if (!Settings::getInstance()->getBool("CustomEventScripts"))
|
||||
return;
|
||||
|
||||
LOG(LogDebug) << "Scripting::fireEvent(): " << eventName << " \"" << arg1 <<
|
||||
"\" \"" << arg2 << "\"";
|
||||
LOG(LogDebug) << "Scripting::fireEvent(): " << eventName << " \"" << arg1 << "\" \"" << arg2
|
||||
<< "\"";
|
||||
|
||||
std::list<std::string> scriptDirList;
|
||||
std::string scriptDir;
|
||||
|
@ -38,10 +38,10 @@ namespace Scripting
|
|||
scriptDirList.push_back(scriptDir);
|
||||
|
||||
for (std::list<std::string>::const_iterator dirIt = scriptDirList.cbegin();
|
||||
dirIt != scriptDirList.cend(); dirIt++) {
|
||||
dirIt != scriptDirList.cend(); dirIt++) {
|
||||
std::list<std::string> scripts = Utils::FileSystem::getDirContent(*dirIt);
|
||||
for (std::list<std::string>::const_iterator it = scripts.cbegin();
|
||||
it != scripts.cend(); it++) {
|
||||
for (std::list<std::string>::const_iterator it = scripts.cbegin(); // Line break.
|
||||
it != scripts.cend(); it++) {
|
||||
std::string arg1Quotation;
|
||||
std::string arg2Quotation;
|
||||
// Add quotation marks around the arguments as long as these are not already
|
||||
|
@ -51,10 +51,10 @@ namespace Scripting
|
|||
if (arg2.front() != '\"')
|
||||
arg2Quotation = "\"";
|
||||
std::string script = *it + " " + arg1Quotation + arg1 + arg1Quotation + " " +
|
||||
arg2Quotation + arg2 + arg2Quotation;
|
||||
arg2Quotation + arg2 + arg2Quotation;
|
||||
LOG(LogDebug) << "Executing: " << script;
|
||||
runSystemCommand(script);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} // namespace Scripting
|
||||
|
|
|
@ -20,7 +20,8 @@
|
|||
namespace Scripting
|
||||
{
|
||||
void fireEvent(const std::string& eventName,
|
||||
const std::string& arg1="", const std::string& arg2="");
|
||||
const std::string& arg1 = "",
|
||||
const std::string& arg2 = "");
|
||||
}
|
||||
|
||||
#endif //ES_CORE_SCRIPTING_H
|
||||
#endif // ES_CORE_SCRIPTING_H
|
||||
|
|
|
@ -9,11 +9,11 @@
|
|||
|
||||
#include "Settings.h"
|
||||
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Log.h"
|
||||
#include "Platform.h"
|
||||
#include "Scripting.h"
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "utils/StringUtil.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <pugixml.hpp>
|
||||
|
@ -25,7 +25,9 @@ Settings* Settings::sInstance = nullptr;
|
|||
// the in-program settings menu. Most can be set using command-line arguments,
|
||||
// but some are debug flags that are either hardcoded or set by internal debug
|
||||
// functions.
|
||||
std::vector<std::string> settings_dont_save {
|
||||
std::vector<std::string> settingsSkipSaving
|
||||
{
|
||||
// clang-format off
|
||||
// These options can be set using command-line arguments:
|
||||
"WindowWidth", // Set via --resolution [width] [height]
|
||||
"WindowHeight", // set via --resolution [width] [height]
|
||||
|
@ -55,6 +57,7 @@ std::vector<std::string> settings_dont_save {
|
|||
"DebugImage",
|
||||
"SplashScreenProgress",
|
||||
"ScraperFilter"
|
||||
// clang-format on
|
||||
};
|
||||
|
||||
Settings::Settings()
|
||||
|
@ -174,9 +177,8 @@ void Settings::setDefaults()
|
|||
mBoolMap["ScreensaverSlideshowScanlines"] = { true, true };
|
||||
mBoolMap["ScreensaverSlideshowCustomImages"] = { false, false };
|
||||
mBoolMap["ScreensaverSlideshowRecurse"] = { false, false };
|
||||
mStringMap["ScreensaverSlideshowImageDir"] = {
|
||||
"~/.emulationstation/slideshow/custom_images",
|
||||
"~/.emulationstation/slideshow/custom_images" };
|
||||
mStringMap["ScreensaverSlideshowImageDir"] = { "~/.emulationstation/slideshow/custom_images",
|
||||
"~/.emulationstation/slideshow/custom_images" };
|
||||
|
||||
// UI settings -> screensaver settings -> video screensaver settings.
|
||||
mIntMap["ScreensaverSwapVideoTimeout"] = { 0, 0 };
|
||||
|
@ -185,6 +187,7 @@ void Settings::setDefaults()
|
|||
mBoolMap["ScreensaverVideoScanlines"] = { true, true };
|
||||
mBoolMap["ScreensaverVideoBlur"] = { false, false };
|
||||
|
||||
#if defined(_RPI_)
|
||||
// Sound settings.
|
||||
// The ALSA Audio Card and Audio Device selection code is disabled at the moment.
|
||||
// As PulseAudio controls the sound devices for the desktop environment, it doesn't
|
||||
|
@ -193,7 +196,6 @@ void Settings::setDefaults()
|
|||
// settings could be added later on, if needed.
|
||||
// The code is still active for Raspberry Pi though as I'm not sure if this is
|
||||
// useful for that device.
|
||||
#if defined(_RPI_)
|
||||
mStringMap["AudioCard"] = { "default", "default" };
|
||||
// Audio out device for volume control.
|
||||
//#endif
|
||||
|
@ -201,9 +203,8 @@ void Settings::setDefaults()
|
|||
mStringMap["AudioDevice"] = { "PCM", "PCM" };
|
||||
// Audio out device for Video playback using OMX player.
|
||||
mStringMap["OMXAudioDev"] = { "both", "both" };
|
||||
//#else
|
||||
// mStringMap["AudioDevice"] = { "Master", "Master" };
|
||||
#endif
|
||||
#endif
|
||||
|
||||
mIntMap["SoundVolumeNavigation"] = { 80, 80 };
|
||||
mIntMap["SoundVolumeVideos"] = { 100, 100 };
|
||||
mBoolMap["GamelistVideoAudio"] = { true, true };
|
||||
|
@ -223,32 +224,32 @@ void Settings::setDefaults()
|
|||
mBoolMap["UseCustomCollectionsSystem"] = { true, true };
|
||||
mBoolMap["CollectionShowSystemInfo"] = { true, true };
|
||||
|
||||
// Other settings.
|
||||
#if defined(_RPI_)
|
||||
// Other settings.
|
||||
#if defined(_RPI_)
|
||||
mIntMap["MaxVRAM"] = { 80, 80 };
|
||||
#else
|
||||
#else
|
||||
mIntMap["MaxVRAM"] = { 256, 256 };
|
||||
#endif
|
||||
#endif
|
||||
mIntMap["DisplayIndex"] = { 1, 1 };
|
||||
#if defined (__unix__)
|
||||
#if defined(__unix__)
|
||||
mStringMap["FullscreenMode"] = { "normal", "normal" };
|
||||
#endif
|
||||
#if defined(BUILD_VLC_PLAYER)
|
||||
#endif
|
||||
#if defined(BUILD_VLC_PLAYER)
|
||||
mStringMap["VideoPlayer"] = { "ffmpeg", "ffmpeg" };
|
||||
#endif
|
||||
#if defined(_RPI_)
|
||||
#endif
|
||||
#if defined(_RPI_)
|
||||
mBoolMap["VideoOmxPlayer"] = { false, false };
|
||||
// We're defaulting to OMX Player for full screen video on the Pi.
|
||||
mBoolMap["ScreensaverOmxPlayer"] = { true, true };
|
||||
#endif
|
||||
#endif
|
||||
mStringMap["SaveGamelistsMode"] = { "always", "always" };
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
mBoolMap["HideTaskbar"] = { false, false };
|
||||
#endif
|
||||
#endif
|
||||
mBoolMap["RunInBackground"] = { false, false };
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
mBoolMap["LaunchWorkaround"] = { true, true };
|
||||
#endif
|
||||
#endif
|
||||
mStringMap["MediaDirectory"] = { "", "" };
|
||||
mBoolMap["VideoUpscaleFrameRate"] = { false, false };
|
||||
mBoolMap["LaunchCommandOverride"] = { true, true };
|
||||
|
@ -256,15 +257,15 @@ void Settings::setDefaults()
|
|||
mBoolMap["ShowHiddenGames"] = { true, true };
|
||||
mBoolMap["CustomEventScripts"] = { false, false };
|
||||
mBoolMap["ParseGamelistOnly"] = { false, false };
|
||||
#if defined(__unix__)
|
||||
#if defined(__unix__)
|
||||
mBoolMap["DisableComposition"] = { true, true };
|
||||
#endif
|
||||
#endif
|
||||
mBoolMap["DisplayGPUStatistics"] = { false, false };
|
||||
// macOS requires root privileges to reboot and power off so it doesn't make much
|
||||
// sense to enable this setting and menu entry for that operating system.
|
||||
#if !defined(__APPLE__)
|
||||
// macOS requires root privileges to reboot and power off so it doesn't make much
|
||||
// sense to enable this setting and menu entry for that operating system.
|
||||
#if !defined(__APPLE__)
|
||||
mBoolMap["ShowQuitMenu"] = { false, false };
|
||||
#endif
|
||||
#endif
|
||||
|
||||
//
|
||||
// Settings configured via command-line arguments.
|
||||
|
@ -278,18 +279,18 @@ void Settings::setDefaults()
|
|||
mBoolMap["IgnoreGamelist"] = { false, false };
|
||||
mBoolMap["SplashScreen"] = { true, true };
|
||||
mBoolMap["VSync"] = { true, true };
|
||||
#if !defined(_WIN64)
|
||||
#if !defined(_WIN64)
|
||||
mBoolMap["Windowed"] = { false, false };
|
||||
#endif
|
||||
mIntMap["WindowWidth"] = { 0, 0 };
|
||||
mIntMap["WindowHeight"] = { 0, 0 };
|
||||
mIntMap["ScreenWidth"] = { 0, 0 };
|
||||
#endif
|
||||
mIntMap["WindowWidth"] = { 0, 0 };
|
||||
mIntMap["WindowHeight"] = { 0, 0 };
|
||||
mIntMap["ScreenWidth"] = { 0, 0 };
|
||||
|
||||
// Undocumented options.
|
||||
mIntMap["ScreenHeight"] = { 0, 0 };
|
||||
mIntMap["ScreenHeight"] = { 0, 0 };
|
||||
mIntMap["ScreenOffsetX"] = { 0, 0 };
|
||||
mIntMap["ScreenOffsetY"] = { 0, 0 };
|
||||
mIntMap["ScreenRotate"] = { 0, 0 };
|
||||
mIntMap["ScreenRotate"] = { 0, 0 };
|
||||
|
||||
//
|
||||
// Settings that can be changed in es_settings.xml
|
||||
|
@ -317,9 +318,10 @@ void saveMap(pugi::xml_document& doc, std::map<K, V>& map, const std::string& ty
|
|||
{
|
||||
for (auto iter = map.cbegin(); iter != map.cend(); iter++) {
|
||||
// Key is on the "don't save" list, so don't save it.
|
||||
if (std::find(settings_dont_save.cbegin(), settings_dont_save.cend(),
|
||||
iter->first) != settings_dont_save.cend())
|
||||
if (std::find(settingsSkipSaving.cbegin(), settingsSkipSaving.cend(), iter->first) !=
|
||||
settingsSkipSaving.cend()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
pugi::xml_node node = doc.append_child(type.c_str());
|
||||
node.append_attribute("name").set_value(iter->first.c_str());
|
||||
|
@ -330,8 +332,8 @@ void saveMap(pugi::xml_document& doc, std::map<K, V>& map, const std::string& ty
|
|||
void Settings::saveFile()
|
||||
{
|
||||
LOG(LogDebug) << "Settings::saveFile(): Saving settings to es_settings.xml";
|
||||
const std::string path = Utils::FileSystem::getHomePath() +
|
||||
"/.emulationstation/es_settings.xml";
|
||||
const std::string path =
|
||||
Utils::FileSystem::getHomePath() + "/.emulationstation/es_settings.xml";
|
||||
|
||||
pugi::xml_document doc;
|
||||
|
||||
|
@ -345,11 +347,11 @@ void Settings::saveFile()
|
|||
node.append_attribute("value").set_value(iter->second.second.c_str());
|
||||
}
|
||||
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
doc.save_file(Utils::String::stringToWideString(path).c_str());
|
||||
#else
|
||||
#else
|
||||
doc.save_file(path.c_str());
|
||||
#endif
|
||||
#endif
|
||||
|
||||
Scripting::fireEvent("config-changed");
|
||||
Scripting::fireEvent("settings-changed");
|
||||
|
@ -358,11 +360,11 @@ void Settings::saveFile()
|
|||
void Settings::loadFile()
|
||||
{
|
||||
// Prior to ES-DE v1.1, the configuration file had the .cfg suffix instead of .xml
|
||||
const std::string legacyConfigFile = Utils::FileSystem::getHomePath() +
|
||||
"/.emulationstation/es_settings.cfg";
|
||||
const std::string legacyConfigFile =
|
||||
Utils::FileSystem::getHomePath() + "/.emulationstation/es_settings.cfg";
|
||||
|
||||
const std::string configFile = Utils::FileSystem::getHomePath() +
|
||||
"/.emulationstation/es_settings.xml";
|
||||
const std::string configFile =
|
||||
Utils::FileSystem::getHomePath() + "/.emulationstation/es_settings.xml";
|
||||
|
||||
if (Utils::FileSystem::exists(legacyConfigFile) && !Utils::FileSystem::exists(configFile))
|
||||
Utils::FileSystem::copyFile(legacyConfigFile, configFile, false);
|
||||
|
@ -371,12 +373,12 @@ void Settings::loadFile()
|
|||
return;
|
||||
|
||||
pugi::xml_document doc;
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
pugi::xml_parse_result result =
|
||||
doc.load_file(Utils::String::stringToWideString(configFile).c_str());
|
||||
#else
|
||||
doc.load_file(Utils::String::stringToWideString(configFile).c_str());
|
||||
#else
|
||||
pugi::xml_parse_result result = doc.load_file(configFile.c_str());
|
||||
#endif
|
||||
#endif
|
||||
if (!result) {
|
||||
LOG(LogError) << "Could not parse the es_settings.xml file\n " << result.description();
|
||||
return;
|
||||
|
@ -392,37 +394,37 @@ void Settings::loadFile()
|
|||
setString(node.attribute("name").as_string(), node.attribute("value").as_string());
|
||||
}
|
||||
|
||||
// Print a warning message if the setting we're trying to get doesn't already exist in
|
||||
// the map. Then return the value in the map.
|
||||
#define SETTINGS_GETSET(type, mapName, getFunction, getDefaultFunction, setFunction) \
|
||||
type Settings::getFunction(const std::string& name) \
|
||||
{ \
|
||||
if (mapName.find(name) == mapName.cend()) { \
|
||||
LOG(LogError) << "Tried to use unset setting " << name; \
|
||||
} \
|
||||
return mapName[name].second; \
|
||||
} \
|
||||
type Settings::getDefaultFunction(const std::string& name) \
|
||||
{ \
|
||||
if (mapName.find(name) == mapName.cend()) { \
|
||||
LOG(LogError) << "Tried to use unset setting " << name; \
|
||||
} \
|
||||
return mapName[name].first; \
|
||||
} \
|
||||
bool Settings::setFunction(const std::string& name, type value) \
|
||||
{ \
|
||||
if (mapName.count(name) == 0 || mapName[name].second != value) { \
|
||||
mapName[name].second = value; \
|
||||
\
|
||||
if (std::find(settings_dont_save.cbegin(), settings_dont_save.cend(), name) \
|
||||
== settings_dont_save.cend()) \
|
||||
mWasChanged = true; \
|
||||
\
|
||||
return true; \
|
||||
} \
|
||||
return false; \
|
||||
}
|
||||
// Macro to create the get and set functions for the various data types
|
||||
#define SETTINGS_GETSET(type, mapName, getFunction, getDefaultFunction, setFunction) \
|
||||
type Settings::getFunction(const std::string& name) \
|
||||
{ \
|
||||
if (mapName.find(name) == mapName.cend()) { \
|
||||
LOG(LogError) << "Tried to use unset setting " << name; \
|
||||
} \
|
||||
return mapName[name].second; \
|
||||
} \
|
||||
type Settings::getDefaultFunction(const std::string& name) \
|
||||
{ \
|
||||
if (mapName.find(name) == mapName.cend()) { \
|
||||
LOG(LogError) << "Tried to use unset setting " << name; \
|
||||
} \
|
||||
return mapName[name].first; \
|
||||
} \
|
||||
bool Settings::setFunction(const std::string& name, type value) \
|
||||
{ \
|
||||
if (mapName.count(name) == 0 || mapName[name].second != value) { \
|
||||
mapName[name].second = value; \
|
||||
\
|
||||
if (std::find(settingsSkipSaving.cbegin(), settingsSkipSaving.cend(), name) == \
|
||||
settingsSkipSaving.cend()) \
|
||||
mWasChanged = true; \
|
||||
\
|
||||
return true; \
|
||||
} \
|
||||
return false; \
|
||||
}
|
||||
|
||||
// Parameters for the macro defined above.
|
||||
SETTINGS_GETSET(bool, mBoolMap, getBool, getDefaultBool, setBool);
|
||||
SETTINGS_GETSET(int, mIntMap, getInt, getDefaultInt, setInt);
|
||||
SETTINGS_GETSET(float, mFloatMap, getFloat, getDefaultFloat, setFloat);
|
||||
|
|
|
@ -9,11 +9,11 @@
|
|||
|
||||
#include "Sound.h"
|
||||
|
||||
#include "resources/ResourceManager.h"
|
||||
#include "AudioManager.h"
|
||||
#include "Log.h"
|
||||
#include "Settings.h"
|
||||
#include "ThemeData.h"
|
||||
#include "resources/ResourceManager.h"
|
||||
|
||||
NavigationSounds* NavigationSounds::sInstance = nullptr;
|
||||
|
||||
|
@ -32,11 +32,12 @@ std::shared_ptr<Sound> Sound::get(const std::string& path)
|
|||
}
|
||||
|
||||
std::shared_ptr<Sound> Sound::getFromTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& element)
|
||||
const std::string& view,
|
||||
const std::string& element)
|
||||
{
|
||||
if (!theme) {
|
||||
LOG(LogDebug) << "Sound::getFromTheme(): Using fallback sound file for \""
|
||||
<< element << "\"";
|
||||
LOG(LogDebug) << "Sound::getFromTheme(): Using fallback sound file for \"" << element
|
||||
<< "\"";
|
||||
return get(ResourceManager::getInstance()->getResourcePath(":/sounds/" + element + ".wav"));
|
||||
}
|
||||
|
||||
|
@ -44,7 +45,7 @@ std::shared_ptr<Sound> Sound::getFromTheme(const std::shared_ptr<ThemeData>& the
|
|||
|
||||
const ThemeData::ThemeElement* elem = theme->getElement(view, element, "sound");
|
||||
if (!elem || !elem->has("path")) {
|
||||
LOG(LogDebug) << "Sound::getFromTheme(): " << "Tag not found, using fallback sound file";
|
||||
LOG(LogDebug) << "Sound::getFromTheme(): Tag not found, using fallback sound file";
|
||||
return get(ResourceManager::getInstance()->getResourcePath(":/sounds/" + element + ".wav"));
|
||||
}
|
||||
|
||||
|
@ -52,20 +53,15 @@ std::shared_ptr<Sound> Sound::getFromTheme(const std::shared_ptr<ThemeData>& the
|
|||
return get(elem->get<std::string>("path"));
|
||||
}
|
||||
|
||||
Sound::Sound(
|
||||
const std::string& path)
|
||||
: mSampleData(nullptr),
|
||||
mSamplePos(0),
|
||||
mSampleLength(0),
|
||||
playing(false)
|
||||
Sound::Sound(const std::string& path)
|
||||
: mSampleData(nullptr)
|
||||
, mSamplePos(0)
|
||||
, mSampleLength(0)
|
||||
, playing(false)
|
||||
{
|
||||
loadFile(path);
|
||||
}
|
||||
|
||||
Sound::~Sound()
|
||||
{
|
||||
}
|
||||
|
||||
void Sound::loadFile(const std::string& path)
|
||||
{
|
||||
mPath = path;
|
||||
|
@ -91,9 +87,9 @@ void Sound::init()
|
|||
}
|
||||
|
||||
// Convert sound file to the format required by ES-DE.
|
||||
SDL_AudioStream *conversionStream = SDL_NewAudioStream(wave.format, wave.channels, wave.freq,
|
||||
AudioManager::sAudioFormat.format, AudioManager::sAudioFormat.channels,
|
||||
AudioManager::sAudioFormat.freq);
|
||||
SDL_AudioStream* conversionStream =
|
||||
SDL_NewAudioStream(wave.format, wave.channels, wave.freq, AudioManager::sAudioFormat.format,
|
||||
AudioManager::sAudioFormat.channels, AudioManager::sAudioFormat.freq);
|
||||
|
||||
if (conversionStream == nullptr) {
|
||||
LOG(LogError) << "Failed to create sample conversion stream:";
|
||||
|
@ -169,11 +165,6 @@ void Sound::play()
|
|||
AudioManager::getInstance()->play();
|
||||
}
|
||||
|
||||
bool Sound::isPlaying() const
|
||||
{
|
||||
return playing;
|
||||
}
|
||||
|
||||
void Sound::stop()
|
||||
{
|
||||
// Flag our sample as not playing and rewind its position.
|
||||
|
@ -183,16 +174,6 @@ void Sound::stop()
|
|||
SDL_UnlockAudioDevice(AudioManager::sAudioDevice);
|
||||
}
|
||||
|
||||
const Uint8* Sound::getData() const
|
||||
{
|
||||
return mSampleData;
|
||||
}
|
||||
|
||||
Uint32 Sound::getPosition() const
|
||||
{
|
||||
return mSamplePos;
|
||||
}
|
||||
|
||||
void Sound::setPosition(Uint32 newPosition)
|
||||
{
|
||||
mSamplePos = newPosition;
|
||||
|
@ -203,11 +184,6 @@ void Sound::setPosition(Uint32 newPosition)
|
|||
}
|
||||
}
|
||||
|
||||
Uint32 Sound::getLength() const
|
||||
{
|
||||
return mSampleLength;
|
||||
}
|
||||
|
||||
NavigationSounds* NavigationSounds::getInstance()
|
||||
{
|
||||
if (sInstance == nullptr)
|
||||
|
@ -234,11 +210,12 @@ void NavigationSounds::loadThemeNavigationSounds(const std::shared_ptr<ThemeData
|
|||
{
|
||||
if (theme) {
|
||||
LOG(LogDebug) << "NavigationSounds::loadThemeNavigationSounds(): "
|
||||
"Theme set includes navigation sound support, loading custom sounds";
|
||||
"Theme set includes navigation sound support, loading custom sounds";
|
||||
}
|
||||
else {
|
||||
LOG(LogDebug) << "NavigationSounds::loadThemeNavigationSounds(): "
|
||||
"Theme set does not include navigation sound support, using fallback sounds";
|
||||
LOG(LogDebug)
|
||||
<< "NavigationSounds::loadThemeNavigationSounds(): "
|
||||
"Theme set does not include navigation sound support, using fallback sounds";
|
||||
}
|
||||
|
||||
navigationSounds.push_back(std::move(Sound::getFromTheme(theme, "all", "systembrowse")));
|
||||
|
|
|
@ -22,7 +22,7 @@ class ThemeData;
|
|||
class Sound
|
||||
{
|
||||
public:
|
||||
~Sound();
|
||||
~Sound() {}
|
||||
|
||||
void init();
|
||||
void deinit();
|
||||
|
@ -30,17 +30,18 @@ public:
|
|||
void loadFile(const std::string& path);
|
||||
|
||||
void play();
|
||||
bool isPlaying() const;
|
||||
bool isPlaying() const { return playing; }
|
||||
void stop();
|
||||
|
||||
const Uint8* getData() const;
|
||||
Uint32 getPosition() const;
|
||||
const Uint8* getData() const { return mSampleData; }
|
||||
Uint32 getPosition() const { return mSamplePos; }
|
||||
void setPosition(Uint32 newPosition);
|
||||
Uint32 getLength() const;
|
||||
Uint32 getLength() const { return mSampleLength; }
|
||||
|
||||
static std::shared_ptr<Sound> get(const std::string& path);
|
||||
static std::shared_ptr<Sound> getFromTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& elem);
|
||||
const std::string& view,
|
||||
const std::string& elem);
|
||||
|
||||
private:
|
||||
Sound(const std::string& path = "");
|
||||
|
|
|
@ -10,190 +10,190 @@
|
|||
|
||||
#include "ThemeData.h"
|
||||
|
||||
#include "Log.h"
|
||||
#include "Platform.h"
|
||||
#include "Settings.h"
|
||||
#include "components/ImageComponent.h"
|
||||
#include "components/TextComponent.h"
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Log.h"
|
||||
#include "Platform.h"
|
||||
#include "Settings.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <pugixml.hpp>
|
||||
|
||||
std::vector<std::string> ThemeData::sSupportedViews {
|
||||
{ "all" }, { "system" }, { "basic" }, { "detailed" }, { "grid" }, { "video" } };
|
||||
std::vector<std::string> ThemeData::sSupportedViews { { "all" }, { "system" }, { "basic" },
|
||||
{ "detailed" }, { "grid" }, { "video" } };
|
||||
std::vector<std::string> ThemeData::sSupportedFeatures {
|
||||
{ "navigationsounds" }, { "video" }, { "carousel" }, { "z-index" }, { "visible" } };
|
||||
|
||||
std::map<std::string, std::map<std::string,
|
||||
ThemeData::ElementPropertyType>> ThemeData::sElementMap {
|
||||
{ "image", {
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "maxSize", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "rotation", FLOAT },
|
||||
{ "rotationOrigin", NORMALIZED_PAIR },
|
||||
{ "path", PATH },
|
||||
{ "default", PATH },
|
||||
{ "tile", BOOLEAN },
|
||||
{ "color", COLOR },
|
||||
{ "colorEnd", COLOR },
|
||||
{ "gradientType", STRING },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "imagegrid", {
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "margin", NORMALIZED_PAIR },
|
||||
{ "padding", NORMALIZED_RECT },
|
||||
{ "autoLayout", NORMALIZED_PAIR },
|
||||
{ "autoLayoutSelectedZoom", FLOAT },
|
||||
{ "gameImage", PATH },
|
||||
{ "folderImage", PATH },
|
||||
{ "imageSource", STRING },
|
||||
{ "scrollDirection", STRING },
|
||||
{ "centerSelection", BOOLEAN },
|
||||
{ "scrollLoop", BOOLEAN },
|
||||
{ "animate", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "gridtile", {
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "padding", NORMALIZED_PAIR },
|
||||
{ "imageColor", COLOR },
|
||||
{ "backgroundImage", PATH },
|
||||
{ "backgroundCornerSize", NORMALIZED_PAIR },
|
||||
{ "backgroundColor", COLOR },
|
||||
{ "backgroundCenterColor", COLOR },
|
||||
{ "backgroundEdgeColor", COLOR } } },
|
||||
{ "text", {
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "rotation", FLOAT },
|
||||
{ "rotationOrigin", NORMALIZED_PAIR },
|
||||
{ "text", STRING },
|
||||
{ "backgroundColor", COLOR },
|
||||
{ "fontPath", PATH },
|
||||
{ "fontSize", FLOAT },
|
||||
{ "color", COLOR },
|
||||
{ "alignment", STRING },
|
||||
{ "forceUppercase", BOOLEAN },
|
||||
{ "lineSpacing", FLOAT },
|
||||
{ "value", STRING },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "textlist", {
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "selectorHeight", FLOAT },
|
||||
{ "selectorOffsetY", FLOAT },
|
||||
{ "selectorColor", COLOR },
|
||||
{ "selectorColorEnd", COLOR },
|
||||
{ "selectorGradientType", STRING },
|
||||
{ "selectorImagePath", PATH },
|
||||
{ "selectorImageTile", BOOLEAN },
|
||||
{ "selectedColor", COLOR },
|
||||
{ "primaryColor", COLOR },
|
||||
{ "secondaryColor", COLOR },
|
||||
{ "fontPath", PATH },
|
||||
{ "fontSize", FLOAT },
|
||||
{ "scrollSound", PATH }, // Need to keep this for backward compatibility with old themes.
|
||||
{ "alignment", STRING },
|
||||
{ "horizontalMargin", FLOAT },
|
||||
{ "forceUppercase", BOOLEAN },
|
||||
{ "lineSpacing", FLOAT },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "container", {
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "ninepatch", {
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "path", PATH },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "datetime", {
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "rotation", FLOAT },
|
||||
{ "rotationOrigin", NORMALIZED_PAIR },
|
||||
{ "backgroundColor", COLOR },
|
||||
{ "fontPath", PATH },
|
||||
{ "fontSize", FLOAT },
|
||||
{ "color", COLOR },
|
||||
{ "alignment", STRING },
|
||||
{ "forceUppercase", BOOLEAN },
|
||||
{ "lineSpacing", FLOAT },
|
||||
{ "value", STRING },
|
||||
{ "format", STRING },
|
||||
{ "displayRelative", BOOLEAN },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "rating", {
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "rotation", FLOAT },
|
||||
{ "rotationOrigin", NORMALIZED_PAIR },
|
||||
{ "color", COLOR },
|
||||
{ "filledPath", PATH },
|
||||
{ "unfilledPath", PATH },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "sound", {
|
||||
{ "path", PATH } } },
|
||||
{ "helpsystem", {
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "textColor", COLOR },
|
||||
{ "iconColor", COLOR },
|
||||
{ "fontPath", PATH },
|
||||
{ "fontSize", FLOAT } } },
|
||||
{ "navigationsounds", {
|
||||
{ "systembrowseSound", PATH },
|
||||
{ "quicksysselectSound", PATH },
|
||||
{ "selectSound", PATH },
|
||||
{ "backSound", PATH },
|
||||
{ "scrollSound", PATH },
|
||||
{ "favoriteSound", PATH },
|
||||
{ "launchSound", PATH } } },
|
||||
{ "video", {
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "maxSize", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "rotation", FLOAT },
|
||||
{ "rotationOrigin", NORMALIZED_PAIR },
|
||||
{ "default", PATH },
|
||||
{ "delay", FLOAT },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT },
|
||||
{ "showSnapshotNoVideo", BOOLEAN },
|
||||
{ "showSnapshotDelay", BOOLEAN } } },
|
||||
{ "carousel", {
|
||||
{ "type", STRING },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "color", COLOR },
|
||||
{ "colorEnd", COLOR },
|
||||
{ "gradientType", STRING },
|
||||
{ "logoScale", FLOAT },
|
||||
{ "logoRotation", FLOAT },
|
||||
{ "logoRotationOrigin", NORMALIZED_PAIR },
|
||||
{ "logoSize", NORMALIZED_PAIR },
|
||||
{ "logoAlignment", STRING },
|
||||
{ "maxLogoCount", FLOAT },
|
||||
{ "zIndex", FLOAT } } }
|
||||
{ "navigationsounds" }, { "video" }, { "carousel" }, { "z-index" }, { "visible" }
|
||||
};
|
||||
|
||||
std::map<std::string, std::map<std::string, ThemeData::ElementPropertyType>>
|
||||
ThemeData::sElementMap {
|
||||
{ "image",
|
||||
{ { "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "maxSize", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "rotation", FLOAT },
|
||||
{ "rotationOrigin", NORMALIZED_PAIR },
|
||||
{ "path", PATH },
|
||||
{ "default", PATH },
|
||||
{ "tile", BOOLEAN },
|
||||
{ "color", COLOR },
|
||||
{ "colorEnd", COLOR },
|
||||
{ "gradientType", STRING },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "imagegrid",
|
||||
{ { "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "margin", NORMALIZED_PAIR },
|
||||
{ "padding", NORMALIZED_RECT },
|
||||
{ "autoLayout", NORMALIZED_PAIR },
|
||||
{ "autoLayoutSelectedZoom", FLOAT },
|
||||
{ "gameImage", PATH },
|
||||
{ "folderImage", PATH },
|
||||
{ "imageSource", STRING },
|
||||
{ "scrollDirection", STRING },
|
||||
{ "centerSelection", BOOLEAN },
|
||||
{ "scrollLoop", BOOLEAN },
|
||||
{ "animate", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "gridtile",
|
||||
{ { "size", NORMALIZED_PAIR },
|
||||
{ "padding", NORMALIZED_PAIR },
|
||||
{ "imageColor", COLOR },
|
||||
{ "backgroundImage", PATH },
|
||||
{ "backgroundCornerSize", NORMALIZED_PAIR },
|
||||
{ "backgroundColor", COLOR },
|
||||
{ "backgroundCenterColor", COLOR },
|
||||
{ "backgroundEdgeColor", COLOR } } },
|
||||
{ "text",
|
||||
{ { "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "rotation", FLOAT },
|
||||
{ "rotationOrigin", NORMALIZED_PAIR },
|
||||
{ "text", STRING },
|
||||
{ "backgroundColor", COLOR },
|
||||
{ "fontPath", PATH },
|
||||
{ "fontSize", FLOAT },
|
||||
{ "color", COLOR },
|
||||
{ "alignment", STRING },
|
||||
{ "forceUppercase", BOOLEAN },
|
||||
{ "lineSpacing", FLOAT },
|
||||
{ "value", STRING },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "textlist",
|
||||
{ { "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "selectorHeight", FLOAT },
|
||||
{ "selectorOffsetY", FLOAT },
|
||||
{ "selectorColor", COLOR },
|
||||
{ "selectorColorEnd", COLOR },
|
||||
{ "selectorGradientType", STRING },
|
||||
{ "selectorImagePath", PATH },
|
||||
{ "selectorImageTile", BOOLEAN },
|
||||
{ "selectedColor", COLOR },
|
||||
{ "primaryColor", COLOR },
|
||||
{ "secondaryColor", COLOR },
|
||||
{ "fontPath", PATH },
|
||||
{ "fontSize", FLOAT },
|
||||
{ "scrollSound", PATH }, // For backward compatibility with old themes.
|
||||
{ "alignment", STRING },
|
||||
{ "horizontalMargin", FLOAT },
|
||||
{ "forceUppercase", BOOLEAN },
|
||||
{ "lineSpacing", FLOAT },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "container",
|
||||
{ { "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "ninepatch",
|
||||
{ { "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "path", PATH },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "datetime",
|
||||
{ { "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "rotation", FLOAT },
|
||||
{ "rotationOrigin", NORMALIZED_PAIR },
|
||||
{ "backgroundColor", COLOR },
|
||||
{ "fontPath", PATH },
|
||||
{ "fontSize", FLOAT },
|
||||
{ "color", COLOR },
|
||||
{ "alignment", STRING },
|
||||
{ "forceUppercase", BOOLEAN },
|
||||
{ "lineSpacing", FLOAT },
|
||||
{ "value", STRING },
|
||||
{ "format", STRING },
|
||||
{ "displayRelative", BOOLEAN },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "rating",
|
||||
{ { "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "rotation", FLOAT },
|
||||
{ "rotationOrigin", NORMALIZED_PAIR },
|
||||
{ "color", COLOR },
|
||||
{ "filledPath", PATH },
|
||||
{ "unfilledPath", PATH },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT } } },
|
||||
{ "sound", { { "path", PATH } } },
|
||||
{ "helpsystem",
|
||||
{ { "pos", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "textColor", COLOR },
|
||||
{ "iconColor", COLOR },
|
||||
{ "fontPath", PATH },
|
||||
{ "fontSize", FLOAT } } },
|
||||
{ "navigationsounds",
|
||||
{ { "systembrowseSound", PATH },
|
||||
{ "quicksysselectSound", PATH },
|
||||
{ "selectSound", PATH },
|
||||
{ "backSound", PATH },
|
||||
{ "scrollSound", PATH },
|
||||
{ "favoriteSound", PATH },
|
||||
{ "launchSound", PATH } } },
|
||||
{ "video",
|
||||
{ { "pos", NORMALIZED_PAIR },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "maxSize", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "rotation", FLOAT },
|
||||
{ "rotationOrigin", NORMALIZED_PAIR },
|
||||
{ "default", PATH },
|
||||
{ "delay", FLOAT },
|
||||
{ "visible", BOOLEAN },
|
||||
{ "zIndex", FLOAT },
|
||||
{ "showSnapshotNoVideo", BOOLEAN },
|
||||
{ "showSnapshotDelay", BOOLEAN } } },
|
||||
{ "carousel",
|
||||
{ { "type", STRING },
|
||||
{ "size", NORMALIZED_PAIR },
|
||||
{ "pos", NORMALIZED_PAIR },
|
||||
{ "origin", NORMALIZED_PAIR },
|
||||
{ "color", COLOR },
|
||||
{ "colorEnd", COLOR },
|
||||
{ "gradientType", STRING },
|
||||
{ "logoScale", FLOAT },
|
||||
{ "logoRotation", FLOAT },
|
||||
{ "logoRotationOrigin", NORMALIZED_PAIR },
|
||||
{ "logoSize", NORMALIZED_PAIR },
|
||||
{ "logoAlignment", STRING },
|
||||
{ "maxLogoCount", FLOAT },
|
||||
{ "zIndex", FLOAT } } }
|
||||
};
|
||||
|
||||
#define MINIMUM_THEME_FORMAT_VERSION 3
|
||||
#define CURRENT_THEME_FORMAT_VERSION 6
|
||||
|
||||
|
@ -241,6 +241,7 @@ std::string resolvePlaceholders(const std::string& in)
|
|||
|
||||
ThemeData::ThemeData()
|
||||
{
|
||||
// The version will be loaded from the theme file.
|
||||
mVersion = 0;
|
||||
}
|
||||
|
||||
|
@ -261,11 +262,11 @@ void ThemeData::loadFile(std::map<std::string, std::string> sysDataMap, const st
|
|||
mVariables.insert(sysDataMap.cbegin(), sysDataMap.cend());
|
||||
|
||||
pugi::xml_document doc;
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
pugi::xml_parse_result res = doc.load_file(Utils::String::stringToWideString(path).c_str());
|
||||
#else
|
||||
#else
|
||||
pugi::xml_parse_result res = doc.load_file(path.c_str());
|
||||
#endif
|
||||
#endif
|
||||
if (!res)
|
||||
throw error << "XML parsing error: \n " << res.description();
|
||||
|
||||
|
@ -276,13 +277,13 @@ void ThemeData::loadFile(std::map<std::string, std::string> sysDataMap, const st
|
|||
// parse version
|
||||
mVersion = root.child("formatVersion").text().as_float(-404);
|
||||
if (mVersion == -404)
|
||||
throw error << "<formatVersion> tag missing!\n It's either out of date or you need "
|
||||
"to add <formatVersion>" << CURRENT_THEME_FORMAT_VERSION <<
|
||||
"</formatVersion> inside your <theme> tag.";
|
||||
throw error << "<formatVersion> tag missing\n "
|
||||
"It's either out of date or you need to add <formatVersion>"
|
||||
<< CURRENT_THEME_FORMAT_VERSION << "</formatVersion> inside your <theme> tag.";
|
||||
|
||||
if (mVersion < MINIMUM_THEME_FORMAT_VERSION)
|
||||
throw error << "Theme uses format version " << mVersion <<
|
||||
". Minimum supported version is " << MINIMUM_THEME_FORMAT_VERSION << ".";
|
||||
throw error << "Theme uses format version " << mVersion << ". Minimum supported version is "
|
||||
<< MINIMUM_THEME_FORMAT_VERSION << ".";
|
||||
|
||||
parseVariables(root);
|
||||
parseIncludes(root);
|
||||
|
@ -299,19 +300,18 @@ void ThemeData::parseIncludes(const pugi::xml_node& root)
|
|||
std::string relPath = resolvePlaceholders(node.text().as_string());
|
||||
std::string path = Utils::FileSystem::resolveRelativePath(relPath, mPaths.back(), true);
|
||||
if (!ResourceManager::getInstance()->fileExists(path))
|
||||
throw error << " -> \"" << relPath <<
|
||||
"\" not found (resolved to \"" << path << "\")";
|
||||
throw error << " -> \"" << relPath << "\" not found (resolved to \"" << path << "\")";
|
||||
error << " -> \"" << relPath << "\"";
|
||||
|
||||
mPaths.push_back(path);
|
||||
|
||||
pugi::xml_document includeDoc;
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
pugi::xml_parse_result result =
|
||||
includeDoc.load_file(Utils::String::stringToWideString(path).c_str());
|
||||
#else
|
||||
includeDoc.load_file(Utils::String::stringToWideString(path).c_str());
|
||||
#else
|
||||
pugi::xml_parse_result result = includeDoc.load_file(path.c_str());
|
||||
#endif
|
||||
#endif
|
||||
if (!result)
|
||||
throw error << ": Error parsing file: " << result.description();
|
||||
|
||||
|
@ -339,9 +339,10 @@ void ThemeData::parseFeatures(const pugi::xml_node& root)
|
|||
|
||||
const std::string supportedAttr = node.attribute("supported").as_string();
|
||||
|
||||
if (std::find(sSupportedFeatures.cbegin(), sSupportedFeatures.cend(),
|
||||
supportedAttr) != sSupportedFeatures.cend())
|
||||
if (std::find(sSupportedFeatures.cbegin(), sSupportedFeatures.cend(), supportedAttr) !=
|
||||
sSupportedFeatures.cend()) {
|
||||
parseViews(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -384,10 +385,11 @@ void ThemeData::parseViews(const pugi::xml_node& root)
|
|||
prevOff = nameAttr.find_first_not_of(delim, off);
|
||||
off = nameAttr.find_first_of(delim, prevOff);
|
||||
|
||||
if (std::find(sSupportedViews.cbegin(), sSupportedViews.cend(),
|
||||
viewKey) != sSupportedViews.cend()) {
|
||||
ThemeView& view = mViews.insert(std::pair<std::string,
|
||||
ThemeView>(viewKey, ThemeView())).first->second;
|
||||
if (std::find(sSupportedViews.cbegin(), sSupportedViews.cend(), viewKey) !=
|
||||
sSupportedViews.cend()) {
|
||||
ThemeView& view =
|
||||
mViews.insert(std::pair<std::string, ThemeView>(viewKey, ThemeView()))
|
||||
.first->second;
|
||||
parseView(node, view);
|
||||
}
|
||||
}
|
||||
|
@ -416,19 +418,21 @@ void ThemeData::parseView(const pugi::xml_node& root, ThemeView& view)
|
|||
prevOff = nameAttr.find_first_not_of(delim, off);
|
||||
off = nameAttr.find_first_of(delim, prevOff);
|
||||
|
||||
parseElement(node, elemTypeIt->second,
|
||||
view.elements.insert(std::pair<std::string,
|
||||
ThemeElement>(elemKey, ThemeElement())).first->second);
|
||||
parseElement(
|
||||
node, elemTypeIt->second,
|
||||
view.elements.insert(std::pair<std::string, ThemeElement>(elemKey, ThemeElement()))
|
||||
.first->second);
|
||||
|
||||
if (std::find(view.orderedKeys.cbegin(), view.orderedKeys.cend(),
|
||||
elemKey) == view.orderedKeys.cend())
|
||||
if (std::find(view.orderedKeys.cbegin(), view.orderedKeys.cend(), elemKey) ==
|
||||
view.orderedKeys.cend())
|
||||
view.orderedKeys.push_back(elemKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void ThemeData::parseElement(const pugi::xml_node& root,
|
||||
const std::map<std::string, ElementPropertyType>& typeMap, ThemeElement& element)
|
||||
const std::map<std::string, ElementPropertyType>& typeMap,
|
||||
ThemeElement& element)
|
||||
{
|
||||
ThemeException error;
|
||||
error.setFiles(mPaths);
|
||||
|
@ -439,85 +443,88 @@ void ThemeData::parseElement(const pugi::xml_node& root,
|
|||
for (pugi::xml_node node = root.first_child(); node; node = node.next_sibling()) {
|
||||
auto typeIt = typeMap.find(node.name());
|
||||
if (typeIt == typeMap.cend())
|
||||
throw error << ": Unknown property type \"" << node.name() <<
|
||||
"\" (for element of type " << root.name() << ")";
|
||||
throw error << ": Unknown property type \"" << node.name() << "\" (for element of type "
|
||||
<< root.name() << ")";
|
||||
|
||||
std::string str = resolvePlaceholders(node.text().as_string());
|
||||
|
||||
switch (typeIt->second) {
|
||||
case NORMALIZED_RECT: {
|
||||
Vector4f val;
|
||||
case NORMALIZED_RECT: {
|
||||
Vector4f val;
|
||||
|
||||
auto splits = Utils::String::delimitedStringToVector(str, " ");
|
||||
if (splits.size() == 2) {
|
||||
val = Vector4f(static_cast<float>(atof(splits.at(0).c_str())),
|
||||
static_cast<float>(atof(splits.at(1).c_str())),
|
||||
static_cast<float>(atof(splits.at(0).c_str())),
|
||||
static_cast<float>(atof(splits.at(1).c_str())));
|
||||
auto splits = Utils::String::delimitedStringToVector(str, " ");
|
||||
if (splits.size() == 2) {
|
||||
val = Vector4f(static_cast<float>(atof(splits.at(0).c_str())),
|
||||
static_cast<float>(atof(splits.at(1).c_str())),
|
||||
static_cast<float>(atof(splits.at(0).c_str())),
|
||||
static_cast<float>(atof(splits.at(1).c_str())));
|
||||
}
|
||||
else if (splits.size() == 4) {
|
||||
val = Vector4f(static_cast<float>(atof(splits.at(0).c_str())),
|
||||
static_cast<float>(atof(splits.at(1).c_str())),
|
||||
static_cast<float>(atof(splits.at(2).c_str())),
|
||||
static_cast<float>(atof(splits.at(3).c_str())));
|
||||
}
|
||||
|
||||
element.properties[node.name()] = val;
|
||||
break;
|
||||
}
|
||||
else if (splits.size() == 4) {
|
||||
val = Vector4f(static_cast<float>(atof(splits.at(0).c_str())),
|
||||
static_cast<float>(atof(splits.at(1).c_str())),
|
||||
static_cast<float>(atof(splits.at(2).c_str())),
|
||||
static_cast<float>(atof(splits.at(3).c_str())));
|
||||
case NORMALIZED_PAIR: {
|
||||
size_t divider = str.find(' ');
|
||||
if (divider == std::string::npos)
|
||||
throw error << "invalid normalized pair (property \"" << node.name()
|
||||
<< "\", value \"" << str.c_str() << "\")";
|
||||
|
||||
std::string first = str.substr(0, divider);
|
||||
std::string second = str.substr(divider, std::string::npos);
|
||||
|
||||
Vector2f val(static_cast<float>(atof(first.c_str())),
|
||||
static_cast<float>(atof(second.c_str())));
|
||||
|
||||
element.properties[node.name()] = val;
|
||||
break;
|
||||
}
|
||||
|
||||
element.properties[node.name()] = val;
|
||||
break;
|
||||
}
|
||||
case NORMALIZED_PAIR: {
|
||||
size_t divider = str.find(' ');
|
||||
if (divider == std::string::npos)
|
||||
throw error << "invalid normalized pair (property \"" << node.name() <<
|
||||
"\", value \"" << str.c_str() << "\")";
|
||||
|
||||
std::string first = str.substr(0, divider);
|
||||
std::string second = str.substr(divider, std::string::npos);
|
||||
|
||||
Vector2f val(static_cast<float>(atof(first.c_str())),
|
||||
static_cast<float>(atof(second.c_str())));
|
||||
|
||||
element.properties[node.name()] = val;
|
||||
break;
|
||||
}
|
||||
case STRING: {
|
||||
element.properties[node.name()] = str;
|
||||
break;
|
||||
}
|
||||
case PATH: {
|
||||
std::string path = Utils::FileSystem::resolveRelativePath(str, mPaths.back(), true);
|
||||
if (!ResourceManager::getInstance()->fileExists(path)) {
|
||||
std::stringstream ss;
|
||||
// "From theme yadda yadda, included file yadda yadda.
|
||||
LOG(LogWarning) << error.msg << ":";
|
||||
LOG(LogWarning) << "Could not find file \"" << node.text().get() << "\" " <<
|
||||
((node.text().get() != path) ? "which resolves to \"" + path + "\"" : "");
|
||||
case STRING: {
|
||||
element.properties[node.name()] = str;
|
||||
break;
|
||||
}
|
||||
element.properties[node.name()] = path;
|
||||
break;
|
||||
}
|
||||
case COLOR: {
|
||||
element.properties[node.name()] = getHexColor(str);
|
||||
break;
|
||||
}
|
||||
case FLOAT: {
|
||||
float floatVal = static_cast<float>(strtod(str.c_str(), 0));
|
||||
element.properties[node.name()] = floatVal;
|
||||
break;
|
||||
}
|
||||
case BOOLEAN: {
|
||||
// Only look at first char.
|
||||
char first = str[0];
|
||||
// 1*, t* (true), T* (True), y* (yes), Y* (YES)
|
||||
bool boolVal = (first == '1' || first == 't' || first == 'T' ||
|
||||
first == 'y' || first == 'Y');
|
||||
case PATH: {
|
||||
std::string path = Utils::FileSystem::resolveRelativePath(str, mPaths.back(), true);
|
||||
if (!ResourceManager::getInstance()->fileExists(path)) {
|
||||
std::stringstream ss;
|
||||
// "From theme yadda yadda, included file yadda yadda.
|
||||
LOG(LogWarning) << error.msg << ":";
|
||||
LOG(LogWarning)
|
||||
<< "Could not find file \"" << node.text().get() << "\" "
|
||||
<< ((node.text().get() != path) ? "which resolves to \"" + path + "\"" :
|
||||
"");
|
||||
}
|
||||
element.properties[node.name()] = path;
|
||||
break;
|
||||
}
|
||||
case COLOR: {
|
||||
element.properties[node.name()] = getHexColor(str);
|
||||
break;
|
||||
}
|
||||
case FLOAT: {
|
||||
float floatVal = static_cast<float>(strtod(str.c_str(), 0));
|
||||
element.properties[node.name()] = floatVal;
|
||||
break;
|
||||
}
|
||||
case BOOLEAN: {
|
||||
// Only look at first char.
|
||||
char first = str[0];
|
||||
// 1*, t* (true), T* (True), y* (yes), Y* (YES)
|
||||
bool boolVal =
|
||||
(first == '1' || first == 't' || first == 'T' || first == 'y' || first == 'Y');
|
||||
|
||||
element.properties[node.name()] = boolVal;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
throw error << "Unknown ElementPropertyType for \"" <<
|
||||
root.attribute("name").as_string() << "\", property " << node.name();
|
||||
element.properties[node.name()] = boolVal;
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
throw error << "Unknown ElementPropertyType for \""
|
||||
<< root.attribute("name").as_string() << "\", property " << node.name();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -529,7 +536,8 @@ bool ThemeData::hasView(const std::string& view)
|
|||
}
|
||||
|
||||
const ThemeData::ThemeElement* ThemeData::getElement(const std::string& view,
|
||||
const std::string& element, const std::string& expectedType) const
|
||||
const std::string& element,
|
||||
const std::string& expectedType) const
|
||||
{
|
||||
auto viewIt = mViews.find(view);
|
||||
if (viewIt == mViews.cend())
|
||||
|
@ -540,9 +548,9 @@ const ThemeData::ThemeElement* ThemeData::getElement(const std::string& view,
|
|||
return nullptr;
|
||||
|
||||
if (elemIt->second.type != expectedType && !expectedType.empty()) {
|
||||
LOG(LogWarning) << " requested mismatched theme type for [" <<
|
||||
view << "." << element << "] - expected \""
|
||||
<< expectedType << "\", got \"" << elemIt->second.type << "\"";
|
||||
LOG(LogWarning) << " requested mismatched theme type for [" << view << "." << element
|
||||
<< "] - expected \"" << expectedType << "\", got \"" << elemIt->second.type
|
||||
<< "\"";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
|
@ -555,14 +563,14 @@ const std::shared_ptr<ThemeData>& ThemeData::getDefault()
|
|||
if (theme == nullptr) {
|
||||
theme = std::shared_ptr<ThemeData>(new ThemeData());
|
||||
|
||||
const std::string path = Utils::FileSystem::getHomePath() +
|
||||
"/.emulationstation/es_theme_default.xml";
|
||||
const std::string path =
|
||||
Utils::FileSystem::getHomePath() + "/.emulationstation/es_theme_default.xml";
|
||||
if (Utils::FileSystem::exists(path)) {
|
||||
try {
|
||||
std::map<std::string, std::string> emptyMap;
|
||||
theme->loadFile(emptyMap, path);
|
||||
}
|
||||
catch(ThemeException& e) {
|
||||
catch (ThemeException& e) {
|
||||
LOG(LogError) << e.what();
|
||||
theme = std::shared_ptr<ThemeData>(new ThemeData()); // Reset to empty.
|
||||
}
|
||||
|
@ -573,7 +581,8 @@ const std::shared_ptr<ThemeData>& ThemeData::getDefault()
|
|||
}
|
||||
|
||||
std::vector<GuiComponent*> ThemeData::makeExtras(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, Window* window)
|
||||
const std::string& view,
|
||||
Window* window)
|
||||
{
|
||||
std::vector<GuiComponent*> comps;
|
||||
|
||||
|
@ -581,8 +590,8 @@ std::vector<GuiComponent*> ThemeData::makeExtras(const std::shared_ptr<ThemeData
|
|||
if (viewIt == theme->mViews.cend())
|
||||
return comps;
|
||||
|
||||
for (auto it = viewIt->second.orderedKeys.cbegin();
|
||||
it != viewIt->second.orderedKeys.cend(); it++) {
|
||||
for (auto it = viewIt->second.orderedKeys.cbegin(); // Line break.
|
||||
it != viewIt->second.orderedKeys.cend(); it++) {
|
||||
ThemeElement& elem = viewIt->second.elements.at(*it);
|
||||
if (elem.extra) {
|
||||
GuiComponent* comp = nullptr;
|
||||
|
@ -608,19 +617,20 @@ std::map<std::string, ThemeSet> ThemeData::getThemeSets()
|
|||
std::map<std::string, ThemeSet> sets;
|
||||
|
||||
// Check for themes first under the home directory, then under the data installation
|
||||
// directory (Unix only) and last under the ES executable directory.
|
||||
#if defined(__unix__) || defined(__APPLE__)
|
||||
// directory (Unix only) and last under the ES-DE binary directory.
|
||||
|
||||
#if defined(__unix__) || defined(__APPLE__)
|
||||
static const size_t pathCount = 3;
|
||||
#else
|
||||
#else
|
||||
static const size_t pathCount = 2;
|
||||
#endif
|
||||
#endif
|
||||
std::string paths[pathCount] = {
|
||||
Utils::FileSystem::getExePath() + "/themes",
|
||||
#if defined(__APPLE__)
|
||||
#if defined(__APPLE__)
|
||||
Utils::FileSystem::getExePath() + "/../Resources/themes",
|
||||
#elif defined(__unix__)
|
||||
#elif defined(__unix__)
|
||||
Utils::FileSystem::getProgramDataPath() + "/themes",
|
||||
#endif
|
||||
#endif
|
||||
Utils::FileSystem::getHomePath() + "/.emulationstation/themes"
|
||||
};
|
||||
|
||||
|
@ -631,9 +641,9 @@ std::map<std::string, ThemeSet> ThemeData::getThemeSets()
|
|||
Utils::FileSystem::stringList dirContent = Utils::FileSystem::getDirContent(paths[i]);
|
||||
|
||||
for (Utils::FileSystem::stringList::const_iterator it = dirContent.cbegin();
|
||||
it != dirContent.cend(); it++) {
|
||||
it != dirContent.cend(); it++) {
|
||||
if (Utils::FileSystem::isDirectory(*it)) {
|
||||
ThemeSet set = {*it};
|
||||
ThemeSet set = { *it };
|
||||
sets[set.getName()] = set;
|
||||
}
|
||||
}
|
||||
|
@ -650,9 +660,9 @@ std::string ThemeData::getThemeFromCurrentSet(const std::string& system)
|
|||
return "";
|
||||
|
||||
std::map<std::string, ThemeSet>::const_iterator set =
|
||||
themeSets.find(Settings::getInstance()->getString("ThemeSet"));
|
||||
themeSets.find(Settings::getInstance()->getString("ThemeSet"));
|
||||
if (set == themeSets.cend()) {
|
||||
// Currently selected theme set is missing, so just pick the first available set.
|
||||
// Currently configured theme set is missing, so just pick the first available set.
|
||||
set = themeSets.cbegin();
|
||||
Settings::getInstance()->setString("ThemeSet", set->first);
|
||||
}
|
||||
|
|
|
@ -21,10 +21,12 @@
|
|||
#include <sstream>
|
||||
#include <vector>
|
||||
|
||||
namespace pugi { class xml_node; }
|
||||
namespace pugi
|
||||
{
|
||||
class xml_node;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
class TextListComponent;
|
||||
template <typename T> class TextListComponent;
|
||||
|
||||
class GuiComponent;
|
||||
class ImageComponent;
|
||||
|
@ -63,10 +65,9 @@ public:
|
|||
|
||||
virtual const char* what() const throw() { return msg.c_str(); }
|
||||
|
||||
template<typename T>
|
||||
friend ThemeException& operator<<(ThemeException& e, T msg);
|
||||
template <typename T> friend ThemeException& operator<<(ThemeException& e, T msg);
|
||||
|
||||
inline void setFiles(const std::deque<std::string>& deque)
|
||||
void setFiles(const std::deque<std::string>& deque)
|
||||
{
|
||||
*this << "From theme \"" << deque.front() << "\"";
|
||||
for (auto it = deque.cbegin() + 1; it != deque.cend(); it++)
|
||||
|
@ -74,8 +75,7 @@ public:
|
|||
}
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
ThemeException& operator<<(ThemeException& e, T appendMsg)
|
||||
template <typename T> ThemeException& operator<<(ThemeException& e, T appendMsg)
|
||||
{
|
||||
std::stringstream ss;
|
||||
ss << e.msg << appendMsg;
|
||||
|
@ -83,13 +83,14 @@ ThemeException& operator<<(ThemeException& e, T appendMsg)
|
|||
return e;
|
||||
}
|
||||
|
||||
struct ThemeSet
|
||||
{
|
||||
struct ThemeSet {
|
||||
std::string path;
|
||||
|
||||
inline std::string getName() const { return Utils::FileSystem::getStem(path); }
|
||||
inline std::string getThemePath(const std::string& system) const
|
||||
{ return path + "/" + system + "/theme.xml"; }
|
||||
std::string getName() const { return Utils::FileSystem::getStem(path); }
|
||||
std::string getThemePath(const std::string& system) const
|
||||
{
|
||||
return path + "/" + system + "/theme.xml";
|
||||
}
|
||||
};
|
||||
|
||||
class ThemeData
|
||||
|
@ -124,8 +125,7 @@ public:
|
|||
|
||||
std::map<std::string, Property> properties;
|
||||
|
||||
template<typename T>
|
||||
const T get(const std::string& prop) const
|
||||
template <typename T> const T get(const std::string& prop) const
|
||||
{
|
||||
if (std::is_same<T, Vector2f>::value)
|
||||
return *(const T*)&properties.at(prop).v;
|
||||
|
@ -142,8 +142,10 @@ public:
|
|||
return T();
|
||||
}
|
||||
|
||||
inline bool has(const std::string& prop) const
|
||||
{ return (properties.find(prop) != properties.cend()); }
|
||||
bool has(const std::string& prop) const
|
||||
{
|
||||
return (properties.find(prop) != properties.cend());
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
|
@ -173,11 +175,13 @@ public:
|
|||
bool hasView(const std::string& view);
|
||||
|
||||
// If expectedType is an empty string, will do no type checking.
|
||||
const ThemeElement* getElement(const std::string& view, const std::string& element,
|
||||
const std::string& expectedType) const;
|
||||
const ThemeElement* getElement(const std::string& view,
|
||||
const std::string& element,
|
||||
const std::string& expectedType) const;
|
||||
|
||||
static std::vector<GuiComponent*> makeExtras(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, Window* window);
|
||||
const std::string& view,
|
||||
Window* window);
|
||||
|
||||
static const std::shared_ptr<ThemeData>& getDefault();
|
||||
|
||||
|
@ -198,7 +202,8 @@ private:
|
|||
void parseViews(const pugi::xml_node& themeRoot);
|
||||
void parseView(const pugi::xml_node& viewNode, ThemeView& view);
|
||||
void parseElement(const pugi::xml_node& elementNode,
|
||||
const std::map<std::string, ElementPropertyType>& typeMap, ThemeElement& element);
|
||||
const std::map<std::string, ElementPropertyType>& typeMap,
|
||||
ThemeElement& element);
|
||||
|
||||
std::map<std::string, ThemeView> mViews;
|
||||
};
|
||||
|
|
|
@ -14,40 +14,41 @@
|
|||
#if defined(BUILD_VLC_PLAYER)
|
||||
#include "components/VideoVlcComponent.h"
|
||||
#endif
|
||||
#include "resources/Font.h"
|
||||
#include "AudioManager.h"
|
||||
#include "InputManager.h"
|
||||
#include "Log.h"
|
||||
#include "Scripting.h"
|
||||
#include "Sound.h"
|
||||
#include "resources/Font.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <iomanip>
|
||||
|
||||
#define CLOCK_BACKGROUND_CREATION false
|
||||
|
||||
Window::Window()
|
||||
: mScreensaver(nullptr),
|
||||
mMediaViewer(nullptr),
|
||||
mLaunchScreen(nullptr),
|
||||
mInfoPopup(nullptr),
|
||||
mNormalizeNextUpdate(false),
|
||||
mFrameTimeElapsed(0),
|
||||
mFrameCountElapsed(0),
|
||||
mAverageDeltaTime(10),
|
||||
mAllowSleep(true),
|
||||
mSleeping(false),
|
||||
mTimeSinceLastInput(0),
|
||||
mRenderScreensaver(false),
|
||||
mRenderMediaViewer(false),
|
||||
mRenderLaunchScreen(false),
|
||||
mGameLaunchedState(false),
|
||||
mAllowTextScrolling(true),
|
||||
mCachedBackground(false),
|
||||
mInvalidatedCachedBackground(false),
|
||||
mVideoPlayerCount(0),
|
||||
mTopOpacity(0),
|
||||
mTopScale(0.5),
|
||||
mListScrollOpacity(0),
|
||||
mChangedThemeSet(false)
|
||||
: mScreensaver(nullptr)
|
||||
, mMediaViewer(nullptr)
|
||||
, mLaunchScreen(nullptr)
|
||||
, mInfoPopup(nullptr)
|
||||
, mNormalizeNextUpdate(false)
|
||||
, mFrameTimeElapsed(0)
|
||||
, mFrameCountElapsed(0)
|
||||
, mAverageDeltaTime(10)
|
||||
, mAllowSleep(true)
|
||||
, mSleeping(false)
|
||||
, mTimeSinceLastInput(0)
|
||||
, mRenderScreensaver(false)
|
||||
, mRenderMediaViewer(false)
|
||||
, mRenderLaunchScreen(false)
|
||||
, mGameLaunchedState(false)
|
||||
, mAllowTextScrolling(true)
|
||||
, mCachedBackground(false)
|
||||
, mInvalidatedCachedBackground(false)
|
||||
, mVideoPlayerCount(0)
|
||||
, mTopOpacity(0)
|
||||
, mTopScale(0.5)
|
||||
, mListScrollOpacity(0)
|
||||
, mChangedThemeSet(false)
|
||||
{
|
||||
mHelp = new HelpComponent(this);
|
||||
mBackgroundOverlay = new ImageComponent(this);
|
||||
|
@ -122,7 +123,7 @@ bool Window::init()
|
|||
|
||||
mBackgroundOverlay->setImage(":/graphics/screen_gradient.png");
|
||||
mBackgroundOverlay->setResize(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
|
||||
mListScrollFont = Font::get(FONT_SIZE_LARGE);
|
||||
|
||||
|
@ -141,9 +142,9 @@ void Window::deinit()
|
|||
|
||||
InputManager::getInstance()->deinit();
|
||||
ResourceManager::getInstance()->unloadAll();
|
||||
#if defined(BUILD_VLC_PLAYER)
|
||||
#if defined(BUILD_VLC_PLAYER)
|
||||
VideoVlcComponent::deinit();
|
||||
#endif
|
||||
#endif
|
||||
Renderer::deinit();
|
||||
}
|
||||
|
||||
|
@ -154,8 +155,9 @@ void Window::input(InputConfig* config, Input input)
|
|||
// The DebugSkipInputLogging option has to be set manually in es_settings.xml as
|
||||
// it does not have any settings menu entry.
|
||||
if (Settings::getInstance()->getBool("Debug") &&
|
||||
!Settings::getInstance()->getBool("DebugSkipInputLogging"))
|
||||
!Settings::getInstance()->getBool("DebugSkipInputLogging")) {
|
||||
logInput(config, input);
|
||||
}
|
||||
|
||||
if (mMediaViewer && mRenderMediaViewer) {
|
||||
if (config->isMappedLike("right", input) && input.value != 0)
|
||||
|
@ -177,17 +179,17 @@ void Window::input(InputConfig* config, Input input)
|
|||
|
||||
if (mScreensaver) {
|
||||
if (mScreensaver->isScreensaverActive() &&
|
||||
Settings::getInstance()->getBool("ScreensaverControls") &&
|
||||
((Settings::getInstance()->getString("ScreensaverType") == "video") ||
|
||||
(Settings::getInstance()->getString("ScreensaverType") == "slideshow"))) {
|
||||
Settings::getInstance()->getBool("ScreensaverControls") &&
|
||||
((Settings::getInstance()->getString("ScreensaverType") == "video") ||
|
||||
(Settings::getInstance()->getString("ScreensaverType") == "slideshow"))) {
|
||||
bool customImageSlideshow = false;
|
||||
if (Settings::getInstance()->getString("ScreensaverType") == "slideshow" &&
|
||||
Settings::getInstance()->getBool("ScreensaverSlideshowCustomImages"))
|
||||
Settings::getInstance()->getBool("ScreensaverSlideshowCustomImages"))
|
||||
customImageSlideshow = true;
|
||||
|
||||
if ((customImageSlideshow || mScreensaver->getCurrentGame() != nullptr) &&
|
||||
(config->isMappedTo("a", input) || config->isMappedTo("y", input) ||
|
||||
config->isMappedLike("left", input) || config->isMappedLike("right", input))) {
|
||||
(config->isMappedTo("a", input) || config->isMappedTo("y", input) ||
|
||||
config->isMappedLike("left", input) || config->isMappedLike("right", input))) {
|
||||
// Left or right browses to the next video or image.
|
||||
if (config->isMappedLike("left", input) || config->isMappedLike("right", input)) {
|
||||
if (input.value != 0) {
|
||||
|
@ -230,22 +232,22 @@ void Window::input(InputConfig* config, Input input)
|
|||
}
|
||||
|
||||
if (config->getDeviceId() == DEVICE_KEYBOARD && input.value && input.id == SDLK_g &&
|
||||
SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) {
|
||||
SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) {
|
||||
// Toggle debug grid with Ctrl-G.
|
||||
Settings::getInstance()->setBool("DebugGrid",
|
||||
!Settings::getInstance()->getBool("DebugGrid"));
|
||||
!Settings::getInstance()->getBool("DebugGrid"));
|
||||
}
|
||||
else if (config->getDeviceId() == DEVICE_KEYBOARD && input.value && input.id == SDLK_t &&
|
||||
SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) {
|
||||
SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) {
|
||||
// Toggle TextComponent debug view with Ctrl-T.
|
||||
Settings::getInstance()->setBool("DebugText",
|
||||
!Settings::getInstance()->getBool("DebugText"));
|
||||
!Settings::getInstance()->getBool("DebugText"));
|
||||
}
|
||||
else if (config->getDeviceId() == DEVICE_KEYBOARD && input.value && input.id == SDLK_i &&
|
||||
SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) {
|
||||
SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool("Debug")) {
|
||||
// Toggle ImageComponent debug view with Ctrl-I.
|
||||
Settings::getInstance()->setBool("DebugImage",
|
||||
!Settings::getInstance()->getBool("DebugImage"));
|
||||
!Settings::getInstance()->getBool("DebugImage"));
|
||||
}
|
||||
else {
|
||||
if (peekGui())
|
||||
|
@ -270,8 +272,8 @@ void Window::logInput(InputConfig* config, Input input)
|
|||
mapname += ", ";
|
||||
}
|
||||
|
||||
LOG(LogDebug) << "Window::logInput(" << config->getDeviceName() << "): " <<
|
||||
input.string() << ", isMappedTo=" << mapname << "value=" << input.value;
|
||||
LOG(LogDebug) << "Window::logInput(" << config->getDeviceName() << "): " << input.string()
|
||||
<< ", isMappedTo=" << mapname << "value=" << input.value;
|
||||
}
|
||||
|
||||
void Window::update(int deltaTime)
|
||||
|
@ -292,12 +294,13 @@ void Window::update(int deltaTime)
|
|||
std::stringstream ss;
|
||||
|
||||
// FPS.
|
||||
ss << std::fixed << std::setprecision(1) <<
|
||||
(1000.0f * static_cast<float>(mFrameCountElapsed) /
|
||||
static_cast<float>(mFrameTimeElapsed)) << " FPS (";
|
||||
ss << std::fixed << std::setprecision(2) <<
|
||||
(static_cast<float>(mFrameTimeElapsed) /
|
||||
static_cast<float>(mFrameCountElapsed)) << " ms)";
|
||||
ss << std::fixed << std::setprecision(1)
|
||||
<< (1000.0f * static_cast<float>(mFrameCountElapsed) /
|
||||
static_cast<float>(mFrameTimeElapsed))
|
||||
<< " FPS (";
|
||||
ss << std::fixed << std::setprecision(2)
|
||||
<< (static_cast<float>(mFrameTimeElapsed) / static_cast<float>(mFrameCountElapsed))
|
||||
<< " ms)";
|
||||
|
||||
// The following calculations are not accurate, and the font calculation is completely
|
||||
// broken. For now, still report the figures as it's somehow useful to locate memory
|
||||
|
@ -307,12 +310,12 @@ void Window::update(int deltaTime)
|
|||
float textureTotalUsageMiB = TextureResource::getTotalTextureSize() / 1024.0f / 1024.0f;
|
||||
float fontVramUsageMiB = Font::getTotalMemUsage() / 1024.0f / 1024.0f;
|
||||
|
||||
ss << "\nFont VRAM: " << fontVramUsageMiB << " MiB\nTexture VRAM: " <<
|
||||
textureVramUsageMiB << " MiB\nMax Texture VRAM: " <<
|
||||
textureTotalUsageMiB << " MiB";
|
||||
mFrameDataText = std::unique_ptr<TextCache>
|
||||
(mDefaultFonts.at(0)->buildTextCache(ss.str(), Renderer::getScreenWidth() *
|
||||
0.02f, Renderer::getScreenHeight() * 0.02f, 0xFF00FFFF, 1.3f));
|
||||
ss << "\nFont VRAM: " << fontVramUsageMiB
|
||||
<< " MiB\nTexture VRAM: " << textureVramUsageMiB
|
||||
<< " MiB\nMax Texture VRAM: " << textureTotalUsageMiB << " MiB";
|
||||
mFrameDataText = std::unique_ptr<TextCache>(mDefaultFonts.at(0)->buildTextCache(
|
||||
ss.str(), Renderer::getScreenWidth() * 0.02f, Renderer::getScreenHeight() * 0.02f,
|
||||
0xFF00FFFF, 1.3f));
|
||||
}
|
||||
|
||||
mFrameTimeElapsed = 0;
|
||||
|
@ -368,27 +371,29 @@ void Window::render()
|
|||
else if (mRenderScreensaver && mScreensaver->isFallbackScreensaver())
|
||||
renderBottom = true;
|
||||
else if (mRenderScreensaver &&
|
||||
Settings::getInstance()->getString("ScreensaverType") == "video")
|
||||
Settings::getInstance()->getString("ScreensaverType") == "video")
|
||||
renderBottom = false;
|
||||
else if (mRenderScreensaver &&
|
||||
Settings::getInstance()->getString("ScreensaverType") == "slideshow")
|
||||
Settings::getInstance()->getString("ScreensaverType") == "slideshow")
|
||||
renderBottom = false;
|
||||
|
||||
if (renderBottom)
|
||||
bottom->render(transform);
|
||||
|
||||
if (bottom != top || mRenderLaunchScreen) {
|
||||
#if defined(USE_OPENGL_21)
|
||||
#if defined(USE_OPENGL_21)
|
||||
if (!mCachedBackground) {
|
||||
// Generate a cache texture of the shaded background when opening the menu, which
|
||||
// will remain valid until the menu is closed. This is way faster than having to
|
||||
// render the shaders for every frame.
|
||||
// const auto backgroundStartTime = std::chrono::system_clock::now();
|
||||
#if (CLOCK_BACKGROUND_CREATION)
|
||||
const auto backgroundStartTime = std::chrono::system_clock::now();
|
||||
#endif
|
||||
|
||||
std::shared_ptr<TextureResource> mPostprocessedBackground;
|
||||
mPostprocessedBackground = TextureResource::get("");
|
||||
unsigned char* processedTexture = new unsigned char[Renderer::getScreenWidth() *
|
||||
Renderer::getScreenHeight() * 4];
|
||||
unsigned char* processedTexture =
|
||||
new unsigned char[Renderer::getScreenWidth() * Renderer::getScreenHeight() * 4];
|
||||
|
||||
// Defocus the background using multiple passes of gaussian blur, with the number
|
||||
// of iterations relative to the screen resolution.
|
||||
|
@ -396,7 +401,7 @@ void Window::render()
|
|||
|
||||
if (Settings::getInstance()->getBool("MenuBlurBackground")) {
|
||||
float heightModifier = Renderer::getScreenHeightModifier();
|
||||
|
||||
// clang-format off
|
||||
if (heightModifier < 1)
|
||||
backgroundParameters.blurPasses = 2; // Below 1080
|
||||
else if (heightModifier >= 4)
|
||||
|
@ -411,23 +416,25 @@ void Window::render()
|
|||
backgroundParameters.blurPasses = 3; // 1440
|
||||
else if (heightModifier >= 1)
|
||||
backgroundParameters.blurPasses = 2; // 1080
|
||||
// clang-format on
|
||||
|
||||
// Also dim the background slightly.
|
||||
backgroundParameters.fragmentDimValue = 0.60f;
|
||||
|
||||
Renderer::shaderPostprocessing(Renderer::SHADER_BLUR_HORIZONTAL |
|
||||
Renderer::SHADER_BLUR_VERTICAL | Renderer::SHADER_DIM,
|
||||
backgroundParameters, processedTexture);
|
||||
Renderer::SHADER_BLUR_VERTICAL |
|
||||
Renderer::SHADER_DIM,
|
||||
backgroundParameters, processedTexture);
|
||||
}
|
||||
else {
|
||||
// Dim the background slightly.
|
||||
backgroundParameters.fragmentDimValue = 0.60f;
|
||||
Renderer::shaderPostprocessing(
|
||||
Renderer::SHADER_DIM, backgroundParameters, processedTexture);
|
||||
Renderer::shaderPostprocessing(Renderer::SHADER_DIM, backgroundParameters,
|
||||
processedTexture);
|
||||
}
|
||||
|
||||
mPostprocessedBackground->initFromPixels(processedTexture,
|
||||
Renderer::getScreenWidth(), Renderer::getScreenHeight());
|
||||
mPostprocessedBackground->initFromPixels(
|
||||
processedTexture, Renderer::getScreenWidth(), Renderer::getScreenHeight());
|
||||
|
||||
mBackgroundOverlay->setImage(mPostprocessedBackground);
|
||||
|
||||
|
@ -444,10 +451,14 @@ void Window::render()
|
|||
delete[] processedTexture;
|
||||
mCachedBackground = true;
|
||||
|
||||
// const auto backgroundEndTime = std::chrono::system_clock::now();
|
||||
// LOG(LogDebug) << "Window::render(): Time to create cached background: " <<
|
||||
// std::chrono::duration_cast<std::chrono::milliseconds>
|
||||
// (backgroundEndTime - backgroundStartTime).count() << " ms";
|
||||
#if (CLOCK_BACKGROUND_CREATION)
|
||||
const auto backgroundEndTime = std::chrono::system_clock::now();
|
||||
LOG(LogDebug) << "Window::render(): Time to create cached background: "
|
||||
<< std::chrono::duration_cast<std::chrono::milliseconds>(
|
||||
backgroundEndTime - backgroundStartTime)
|
||||
.count()
|
||||
<< " ms";
|
||||
#endif
|
||||
}
|
||||
// Fade in the cached background if the menu opening effect has been set to scale-up.
|
||||
if (Settings::getInstance()->getString("MenuOpeningEffect") == "scale-up") {
|
||||
|
@ -455,7 +466,7 @@ void Window::render()
|
|||
if (mBackgroundOverlayOpacity < 255)
|
||||
mBackgroundOverlayOpacity = Math::clamp(mBackgroundOverlayOpacity + 30, 0, 255);
|
||||
}
|
||||
#endif
|
||||
#endif // USE_OPENGL_21
|
||||
|
||||
mBackgroundOverlay->render(transform);
|
||||
|
||||
|
@ -464,8 +475,8 @@ void Window::render()
|
|||
if (mTopScale < 1.0f) {
|
||||
mTopScale = Math::clamp(mTopScale + 0.07f, 0.0f, 1.0f);
|
||||
Vector2f topCenter = top->getCenter();
|
||||
top->setOrigin({0.5, 0.5});
|
||||
top->setPosition({topCenter.x(), topCenter.y(), 0});
|
||||
top->setOrigin({ 0.5f, 0.5f });
|
||||
top->setPosition({ topCenter.x(), topCenter.y(), 0.0f });
|
||||
top->setScale(mTopScale);
|
||||
}
|
||||
}
|
||||
|
@ -476,7 +487,7 @@ void Window::render()
|
|||
else {
|
||||
mCachedBackground = false;
|
||||
mTopOpacity = 0;
|
||||
mTopScale = 0.5;
|
||||
mTopScale = 0.5f;
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -484,15 +495,15 @@ void Window::render()
|
|||
if (mListScrollOpacity != 0) {
|
||||
Renderer::setMatrix(Transform4x4f::Identity());
|
||||
Renderer::drawRect(0.0f, 0.0f, static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()),
|
||||
0x00000000 | mListScrollOpacity, 0x00000000 | mListScrollOpacity);
|
||||
static_cast<float>(Renderer::getScreenHeight()),
|
||||
0x00000000 | mListScrollOpacity, 0x00000000 | mListScrollOpacity);
|
||||
|
||||
Vector2f offset = mListScrollFont->sizeText(mListScrollText);
|
||||
offset[0] = (Renderer::getScreenWidth() - offset.x()) * 0.5f;
|
||||
offset[1] = (Renderer::getScreenHeight() - offset.y()) * 0.5f;
|
||||
|
||||
TextCache* cache = mListScrollFont->buildTextCache(mListScrollText,
|
||||
offset.x(), offset.y(), 0xFFFFFF00 | mListScrollOpacity);
|
||||
TextCache* cache = mListScrollFont->buildTextCache(mListScrollText, offset.x(), offset.y(),
|
||||
0xFFFFFF00 | mListScrollOpacity);
|
||||
mListScrollFont->renderTextCache(cache);
|
||||
delete cache;
|
||||
}
|
||||
|
@ -501,7 +512,7 @@ void Window::render()
|
|||
mHelp->render(transform);
|
||||
|
||||
unsigned int screensaverTimer =
|
||||
static_cast<unsigned int>(Settings::getInstance()->getInt("ScreensaverTimer"));
|
||||
static_cast<unsigned int>(Settings::getInstance()->getInt("ScreensaverTimer"));
|
||||
if (mTimeSinceLastInput >= screensaverTimer && screensaverTimer != 0) {
|
||||
// If the media viewer is running or if a menu is open, reset the screensaver timer so
|
||||
// that the screensaver won't start.
|
||||
|
@ -549,17 +560,17 @@ void Window::renderLoadingScreen(std::string text)
|
|||
Transform4x4f trans = Transform4x4f::Identity();
|
||||
Renderer::setMatrix(trans);
|
||||
Renderer::drawRect(0.0f, 0.0f, static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()), 0x000000FF, 0x000000FF);
|
||||
static_cast<float>(Renderer::getScreenHeight()), 0x000000FF, 0x000000FF);
|
||||
|
||||
ImageComponent splash(this, true);
|
||||
splash.setResize(Renderer::getScreenWidth() * 0.6f, 0.0f);
|
||||
splash.setImage(":/graphics/splash.svg");
|
||||
splash.setPosition((Renderer::getScreenWidth() - splash.getSize().x()) / 2,
|
||||
(Renderer::getScreenHeight() - splash.getSize().y()) / 2 * 0.6f);
|
||||
splash.setPosition((Renderer::getScreenWidth() - splash.getSize().x()) / 2.0f,
|
||||
(Renderer::getScreenHeight() - splash.getSize().y()) / 2.0f * 0.6f);
|
||||
splash.render(trans);
|
||||
|
||||
auto& font = mDefaultFonts.at(1);
|
||||
TextCache* cache = font->buildTextCache(text, 0, 0, 0x656565FF);
|
||||
TextCache* cache = font->buildTextCache(text, 0.0f, 0.0f, 0x656565FF);
|
||||
|
||||
float x = std::round((Renderer::getScreenWidth() - cache->metrics.size.x()) / 2.0f);
|
||||
float y = std::round(Renderer::getScreenHeight() * 0.835f);
|
||||
|
@ -602,20 +613,17 @@ void Window::setHelpPrompts(const std::vector<HelpPrompt>& prompts, const HelpSt
|
|||
|
||||
// Can we combine? (dpad only).
|
||||
if ((it->first == "up/down" &&
|
||||
addPrompts.at(mappedTo->second).first != "left/right") ||
|
||||
(it->first == "left/right" &&
|
||||
addPrompts.at(mappedTo->second).first != "up/down")) {
|
||||
// Yes!
|
||||
addPrompts.at(mappedTo->second).first != "left/right") ||
|
||||
(it->first == "left/right" &&
|
||||
addPrompts.at(mappedTo->second).first != "up/down")) {
|
||||
// Yes.
|
||||
addPrompts.at(mappedTo->second).first = "up/down/left/right";
|
||||
// Don't need to add this to addPrompts since we just merged.
|
||||
}
|
||||
else {
|
||||
// No, we can't combine!
|
||||
addPrompts.push_back(*it);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// No, it hasn't!
|
||||
mappedToSeenMap.emplace(it->second, static_cast<int>(addPrompts.size()));
|
||||
addPrompts.push_back(*it);
|
||||
}
|
||||
|
@ -624,29 +632,31 @@ void Window::setHelpPrompts(const std::vector<HelpPrompt>& prompts, const HelpSt
|
|||
|
||||
// Sort prompts so it goes [dpad_all] [dpad_u/d] [dpad_l/r] [a/b/x/y/l/r] [start/back].
|
||||
std::sort(addPrompts.begin(), addPrompts.end(),
|
||||
[](const HelpPrompt& a, const HelpPrompt& b) -> bool {
|
||||
[](const HelpPrompt& a, const HelpPrompt& b) -> bool {
|
||||
static const std::vector<std::string> map = { "up/down/left/right",
|
||||
"up/down",
|
||||
"left/right",
|
||||
"a",
|
||||
"b",
|
||||
"x",
|
||||
"y",
|
||||
"l",
|
||||
"r",
|
||||
"start",
|
||||
"back" };
|
||||
int i = 0;
|
||||
int aVal = 0;
|
||||
int bVal = 0;
|
||||
while (i < map.size()) {
|
||||
if (a.first == map[i])
|
||||
aVal = i;
|
||||
if (b.first == map[i])
|
||||
bVal = i;
|
||||
i++;
|
||||
}
|
||||
|
||||
static const std::vector<std::string> map = {
|
||||
"up/down/left/right",
|
||||
"up/down",
|
||||
"left/right",
|
||||
"a", "b", "x", "y", "l", "r",
|
||||
"start", "back"
|
||||
};
|
||||
|
||||
int i = 0;
|
||||
int aVal = 0;
|
||||
int bVal = 0;
|
||||
while (i < map.size()) {
|
||||
if (a.first == map[i])
|
||||
aVal = i;
|
||||
if (b.first == map[i])
|
||||
bVal = i;
|
||||
i++;
|
||||
}
|
||||
|
||||
return aVal > bVal;
|
||||
});
|
||||
return aVal > bVal;
|
||||
});
|
||||
|
||||
mHelp->setPrompts(addPrompts);
|
||||
}
|
||||
|
@ -789,18 +799,8 @@ void Window::invalidateCachedBackground()
|
|||
mInvalidatedCachedBackground = true;
|
||||
}
|
||||
|
||||
void Window::onSleep()
|
||||
{
|
||||
Scripting::fireEvent("sleep");
|
||||
}
|
||||
|
||||
void Window::onWake()
|
||||
{
|
||||
Scripting::fireEvent("wake");
|
||||
}
|
||||
|
||||
bool Window::isProcessing()
|
||||
{
|
||||
return count_if (mGuiStack.cbegin(), mGuiStack.cend(), [](GuiComponent* c) {
|
||||
return c->isProcessing(); }) > 0;
|
||||
return count_if(mGuiStack.cbegin(), mGuiStack.cend(),
|
||||
[](GuiComponent* c) { return c->isProcessing(); }) > 0;
|
||||
}
|
||||
|
|
|
@ -10,10 +10,11 @@
|
|||
#ifndef ES_CORE_WINDOW_H
|
||||
#define ES_CORE_WINDOW_H
|
||||
|
||||
#include "resources/TextureResource.h"
|
||||
#include "HelpPrompt.h"
|
||||
#include "InputConfig.h"
|
||||
#include "Scripting.h"
|
||||
#include "Settings.h"
|
||||
#include "resources/TextureResource.h"
|
||||
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
|
@ -78,7 +79,7 @@ public:
|
|||
public:
|
||||
virtual void render(const Transform4x4f& parentTrans) = 0;
|
||||
virtual void stop() = 0;
|
||||
virtual ~InfoPopup() {};
|
||||
virtual ~InfoPopup() {}
|
||||
};
|
||||
|
||||
Window();
|
||||
|
@ -87,7 +88,7 @@ public:
|
|||
void pushGui(GuiComponent* gui);
|
||||
void removeGui(GuiComponent* gui);
|
||||
GuiComponent* peekGui();
|
||||
inline int getGuiStackSize() { return static_cast<int>(mGuiStack.size()); }
|
||||
int getGuiStackSize() { return static_cast<int>(mGuiStack.size()); }
|
||||
|
||||
bool init();
|
||||
void deinit();
|
||||
|
@ -102,7 +103,7 @@ public:
|
|||
|
||||
bool getAllowSleep() { return mAllowSleep; }
|
||||
void setAllowSleep(bool sleep) { mAllowSleep = sleep; }
|
||||
inline bool isSleeping() const { return mSleeping; }
|
||||
bool isSleeping() const { return mSleeping; }
|
||||
|
||||
void renderLoadingScreen(std::string text);
|
||||
// The list scroll overlay is triggered from IList when the highest scrolling tier is reached.
|
||||
|
@ -148,8 +149,8 @@ public:
|
|||
bool getChangedThemeSet() { return mChangedThemeSet; }
|
||||
|
||||
private:
|
||||
void onSleep();
|
||||
void onWake();
|
||||
void onSleep() { Scripting::fireEvent("sleep"); }
|
||||
void onWake() { Scripting::fireEvent("wake"); }
|
||||
|
||||
// Returns true if at least one component on the stack is processing.
|
||||
bool isProcessing();
|
||||
|
|
|
@ -12,7 +12,7 @@
|
|||
class Animation
|
||||
{
|
||||
public:
|
||||
virtual ~Animation() {};
|
||||
virtual ~Animation() {}
|
||||
virtual int getDuration() const = 0;
|
||||
virtual void apply(float t) = 0;
|
||||
};
|
||||
|
|
|
@ -10,16 +10,15 @@
|
|||
|
||||
#include "animations/Animation.h"
|
||||
|
||||
AnimationController::AnimationController(
|
||||
Animation* anim,
|
||||
int delay,
|
||||
std::function<void()> finishedCallback,
|
||||
bool reverse)
|
||||
: mAnimation(anim),
|
||||
mFinishedCallback(finishedCallback),
|
||||
mReverse(reverse),
|
||||
mTime(-delay),
|
||||
mDelay(delay)
|
||||
AnimationController::AnimationController(Animation* anim,
|
||||
int delay,
|
||||
std::function<void()> finishedCallback,
|
||||
bool reverse)
|
||||
: mAnimation(anim)
|
||||
, mFinishedCallback(finishedCallback)
|
||||
, mReverse(reverse)
|
||||
, mTime(-delay)
|
||||
, mDelay(delay)
|
||||
{
|
||||
}
|
||||
|
||||
|
|
|
@ -17,20 +17,22 @@ class AnimationController
|
|||
{
|
||||
public:
|
||||
// Takes ownership of anim (will delete in destructor).
|
||||
AnimationController(Animation* anim, int delay = 0,
|
||||
std::function<void()> finishedCallback = nullptr, bool reverse = false);
|
||||
AnimationController(Animation* anim,
|
||||
int delay = 0,
|
||||
std::function<void()> finishedCallback = nullptr,
|
||||
bool reverse = false);
|
||||
virtual ~AnimationController();
|
||||
|
||||
// Returns true if the animation is complete.
|
||||
bool update(int deltaTime);
|
||||
|
||||
inline bool isReversed() const { return mReverse; }
|
||||
inline int getTime() const { return mTime; }
|
||||
inline int getDelay() const { return mDelay; }
|
||||
inline const std::function<void()>& getFinishedCallback() const { return mFinishedCallback; }
|
||||
inline Animation* getAnimation() const { return mAnimation; }
|
||||
bool isReversed() const { return mReverse; }
|
||||
int getTime() const { return mTime; }
|
||||
int getDelay() const { return mDelay; }
|
||||
const std::function<void()>& getFinishedCallback() const { return mFinishedCallback; }
|
||||
Animation* getAnimation() const { return mAnimation; }
|
||||
|
||||
inline void removeFinishedCallback() { mFinishedCallback = nullptr; }
|
||||
void removeFinishedCallback() { mFinishedCallback = nullptr; }
|
||||
|
||||
private:
|
||||
Animation* mAnimation;
|
||||
|
|
|
@ -19,16 +19,15 @@ class LambdaAnimation : public Animation
|
|||
{
|
||||
public:
|
||||
LambdaAnimation(const std::function<void(float t)>& func, int duration)
|
||||
: mFunction(func), mDuration(duration) {}
|
||||
: mFunction(func)
|
||||
, mDuration(duration)
|
||||
{
|
||||
}
|
||||
|
||||
virtual ~LambdaAnimation() = default;
|
||||
|
||||
int getDuration() const override { return mDuration; }
|
||||
|
||||
void apply(float t) override
|
||||
{
|
||||
mFunction(t);
|
||||
}
|
||||
void apply(float t) override { mFunction(t); }
|
||||
|
||||
private:
|
||||
std::function<void(float t)> mFunction;
|
||||
|
|
|
@ -8,12 +8,13 @@
|
|||
|
||||
#include "components/AnimatedImageComponent.h"
|
||||
|
||||
#include "Log.h"
|
||||
#include "components/ImageComponent.h"
|
||||
#include "resources/ResourceManager.h"
|
||||
#include "Log.h"
|
||||
|
||||
AnimatedImageComponent::AnimatedImageComponent(Window* window)
|
||||
: GuiComponent(window), mEnabled(false)
|
||||
: GuiComponent(window)
|
||||
, mEnabled(false)
|
||||
{
|
||||
}
|
||||
|
||||
|
@ -25,9 +26,9 @@ void AnimatedImageComponent::load(const AnimationDef* def)
|
|||
|
||||
for (size_t i = 0; i < def->frameCount; i++) {
|
||||
if (def->frames[i].path != "" &&
|
||||
!ResourceManager::getInstance()->fileExists(def->frames[i].path)) {
|
||||
LOG(LogError) << "Missing animation frame " << i <<
|
||||
" (\"" << def->frames[i].path << "\")";
|
||||
!ResourceManager::getInstance()->fileExists(def->frames[i].path)) {
|
||||
LOG(LogError) << "Missing animation frame " << i << " (\"" << def->frames[i].path
|
||||
<< "\")";
|
||||
continue;
|
||||
}
|
||||
|
||||
|
|
|
@ -14,21 +14,23 @@
|
|||
|
||||
// Animation definition.
|
||||
AnimationFrame BUSY_ANIMATION_FRAMES[] = {
|
||||
{":/graphics/busy_0.svg", 300},
|
||||
{":/graphics/busy_1.svg", 300},
|
||||
{":/graphics/busy_2.svg", 300},
|
||||
{":/graphics/busy_3.svg", 300},
|
||||
{ ":/graphics/busy_0.svg", 300 },
|
||||
{ ":/graphics/busy_1.svg", 300 },
|
||||
{ ":/graphics/busy_2.svg", 300 },
|
||||
{ ":/graphics/busy_3.svg", 300 },
|
||||
};
|
||||
|
||||
const AnimationDef BUSY_ANIMATION_DEF = { BUSY_ANIMATION_FRAMES, 4, true };
|
||||
|
||||
BusyComponent::BusyComponent(Window* window): GuiComponent(window),
|
||||
mBackground(window, ":/graphics/frame.png"), mGrid(window, Vector2i(5, 3))
|
||||
BusyComponent::BusyComponent(Window* window)
|
||||
: GuiComponent(window)
|
||||
, mBackground(window, ":/graphics/frame.png")
|
||||
, mGrid(window, Vector2i(5, 3))
|
||||
{
|
||||
mAnimation = std::make_shared<AnimatedImageComponent>(mWindow);
|
||||
mAnimation->load(&BUSY_ANIMATION_DEF);
|
||||
mText = std::make_shared<TextComponent>(mWindow, "WORKING...",
|
||||
Font::get(FONT_SIZE_MEDIUM), 0x777777FF);
|
||||
mText = std::make_shared<TextComponent>(mWindow, "WORKING...", Font::get(FONT_SIZE_MEDIUM),
|
||||
0x777777FF);
|
||||
|
||||
// Col 0 = animation, col 1 = spacer, col 2 = text.
|
||||
mGrid.setEntry(mAnimation, Vector2i(1, 1), false, true);
|
||||
|
@ -57,13 +59,13 @@ void BusyComponent::onSizeChanged()
|
|||
mGrid.setRowHeightPerc(1, textHeight / mSize.y());
|
||||
|
||||
mBackground.setCornerSize({ 16.0f * Renderer::getScreenWidthModifier(),
|
||||
16.0f * Renderer::getScreenHeightModifier() });
|
||||
mBackground.fitTo(Vector2f(mGrid.getColWidth(1) + mGrid.getColWidth(2) +
|
||||
mGrid.getColWidth(3), textHeight + (2 * Renderer::getScreenHeightModifier())),
|
||||
mAnimation->getPosition(), Vector2f(0, 0));
|
||||
16.0f * Renderer::getScreenHeightModifier() });
|
||||
mBackground.fitTo(Vector2f(mGrid.getColWidth(1) + mGrid.getColWidth(2) + mGrid.getColWidth(3),
|
||||
textHeight + (2.0f * Renderer::getScreenHeightModifier())),
|
||||
mAnimation->getPosition(), Vector2f(0, 0));
|
||||
}
|
||||
|
||||
void BusyComponent::reset()
|
||||
{
|
||||
//mAnimation->reset();
|
||||
// mAnimation->reset();
|
||||
}
|
||||
|
|
|
@ -9,9 +9,9 @@
|
|||
#ifndef ES_CORE_COMPONENTS_BUSY_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_BUSY_COMPONENT_H
|
||||
|
||||
#include "GuiComponent.h"
|
||||
#include "components/ComponentGrid.h"
|
||||
#include "components/NinePatchComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
|
||||
class AnimatedImageComponent;
|
||||
class TextComponent;
|
||||
|
|
|
@ -8,20 +8,21 @@
|
|||
|
||||
#include "components/ButtonComponent.h"
|
||||
|
||||
#include "Settings.h"
|
||||
#include "resources/Font.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Settings.h"
|
||||
|
||||
ButtonComponent::ButtonComponent(
|
||||
Window* window, const std::string& text,
|
||||
const std::string& helpText,
|
||||
const std::function<void()>& func)
|
||||
: GuiComponent(window),
|
||||
mBox(window, ":/graphics/button.svg"),
|
||||
mFont(Font::get(FONT_SIZE_MEDIUM)),
|
||||
mFocused(false),
|
||||
mEnabled(true),
|
||||
mTextColorFocused(0xFFFFFFFF), mTextColorUnfocused(0x777777FF)
|
||||
ButtonComponent::ButtonComponent(Window* window,
|
||||
const std::string& text,
|
||||
const std::string& helpText,
|
||||
const std::function<void()>& func)
|
||||
: GuiComponent(window)
|
||||
, mBox(window, ":/graphics/button.svg")
|
||||
, mFont(Font::get(FONT_SIZE_MEDIUM))
|
||||
, mFocused(false)
|
||||
, mEnabled(true)
|
||||
, mTextColorFocused(0xFFFFFFFF)
|
||||
, mTextColorUnfocused(0x777777FF)
|
||||
{
|
||||
setPressedFunc(func);
|
||||
setText(text, helpText);
|
||||
|
@ -30,12 +31,8 @@ ButtonComponent::ButtonComponent(
|
|||
|
||||
void ButtonComponent::onSizeChanged()
|
||||
{
|
||||
mBox.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
|
||||
}
|
||||
|
||||
void ButtonComponent::setPressedFunc(std::function<void()> f)
|
||||
{
|
||||
mPressedFunc = f;
|
||||
// Fit to mBox.
|
||||
mBox.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f));
|
||||
}
|
||||
|
||||
bool ButtonComponent::input(InputConfig* config, Input input)
|
||||
|
@ -56,9 +53,10 @@ void ButtonComponent::setText(const std::string& text, const std::string& helpTe
|
|||
|
||||
mTextCache = std::unique_ptr<TextCache>(mFont->buildTextCache(mText, 0, 0, getCurTextColor()));
|
||||
|
||||
float minWidth = mFont->sizeText("DELETE").x() + (12 * Renderer::getScreenWidthModifier());
|
||||
setSize(std::max(mTextCache->metrics.size.x() + (12 * Renderer::getScreenWidthModifier()),
|
||||
minWidth), mTextCache->metrics.size.y());
|
||||
float minWidth = mFont->sizeText("DELETE").x() + (12.0f * Renderer::getScreenWidthModifier());
|
||||
setSize(std::max(mTextCache->metrics.size.x() + (12.0f * Renderer::getScreenWidthModifier()),
|
||||
minWidth),
|
||||
mTextCache->metrics.size.y());
|
||||
|
||||
updateHelpPrompts();
|
||||
}
|
||||
|
@ -103,14 +101,14 @@ void ButtonComponent::render(const Transform4x4f& parentTrans)
|
|||
|
||||
if (mTextCache) {
|
||||
Vector3f centerOffset((mSize.x() - mTextCache->metrics.size.x()) / 2.0f,
|
||||
(mSize.y() - mTextCache->metrics.size.y()) / 2.0f, 0);
|
||||
(mSize.y() - mTextCache->metrics.size.y()) / 2.0f, 0);
|
||||
trans = trans.translate(centerOffset);
|
||||
|
||||
if (Settings::getInstance()->getBool("DebugText")) {
|
||||
Renderer::drawRect(centerOffset.x(), 0.0f, mTextCache->metrics.size.x(),
|
||||
mSize.y(), 0x00000033, 0x00000033);
|
||||
Renderer::drawRect(mBox.getPosition().x(), 0.0f, mBox.getSize().x(),
|
||||
mSize.y(), 0x0000FF33, 0x0000FF33);
|
||||
Renderer::drawRect(centerOffset.x(), 0.0f, mTextCache->metrics.size.x(), mSize.y(),
|
||||
0x00000033, 0x00000033);
|
||||
Renderer::drawRect(mBox.getPosition().x(), 0.0f, mBox.getSize().x(), mSize.y(),
|
||||
0x0000FF33, 0x0000FF33);
|
||||
}
|
||||
|
||||
Renderer::setMatrix(trans);
|
||||
|
|
|
@ -9,18 +9,20 @@
|
|||
#ifndef ES_CORE_COMPONENTS_BUTTON_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_BUTTON_COMPONENT_H
|
||||
|
||||
#include "components/NinePatchComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
#include "components/NinePatchComponent.h"
|
||||
|
||||
class TextCache;
|
||||
|
||||
class ButtonComponent : public GuiComponent
|
||||
{
|
||||
public:
|
||||
ButtonComponent(Window* window, const std::string& text = "",
|
||||
const std::string& helpText = "", const std::function<void()>& func = nullptr);
|
||||
ButtonComponent(Window* window,
|
||||
const std::string& text = "",
|
||||
const std::string& helpText = "",
|
||||
const std::function<void()>& func = nullptr);
|
||||
|
||||
void setPressedFunc(std::function<void()> f);
|
||||
void setPressedFunc(std::function<void()> f) { mPressedFunc = f; }
|
||||
void setEnabled(bool state) override;
|
||||
|
||||
bool input(InputConfig* config, Input input) override;
|
||||
|
@ -28,8 +30,8 @@ public:
|
|||
|
||||
void setText(const std::string& text, const std::string& helpText);
|
||||
|
||||
inline const std::string& getText() const { return mText; };
|
||||
inline const std::function<void()>& getPressedFunc() const { return mPressedFunc; };
|
||||
const std::string& getText() const { return mText; }
|
||||
const std::function<void()>& getPressedFunc() const { return mPressedFunc; }
|
||||
|
||||
void onSizeChanged() override;
|
||||
void onFocusGained() override;
|
||||
|
|
|
@ -12,12 +12,10 @@
|
|||
|
||||
using namespace GridFlags;
|
||||
|
||||
ComponentGrid::ComponentGrid(
|
||||
Window* window,
|
||||
const Vector2i& gridDimensions)
|
||||
: GuiComponent(window),
|
||||
mGridSize(gridDimensions),
|
||||
mCursor(0, 0)
|
||||
ComponentGrid::ComponentGrid(Window* window, const Vector2i& gridDimensions)
|
||||
: GuiComponent(window)
|
||||
, mGridSize(gridDimensions)
|
||||
, mCursor(0, 0)
|
||||
{
|
||||
assert(gridDimensions.x() > 0 && gridDimensions.y() > 0);
|
||||
|
||||
|
@ -25,6 +23,7 @@ ComponentGrid::ComponentGrid(
|
|||
|
||||
mColWidths = new float[gridDimensions.x()];
|
||||
mRowHeights = new float[gridDimensions.y()];
|
||||
|
||||
for (int x = 0; x < gridDimensions.x(); x++)
|
||||
mColWidths[x] = 0;
|
||||
for (int y = 0; y < gridDimensions.y(); y++)
|
||||
|
@ -90,14 +89,13 @@ void ComponentGrid::setRowHeightPerc(int row, float height, bool update)
|
|||
onSizeChanged();
|
||||
}
|
||||
|
||||
void ComponentGrid::setEntry(
|
||||
const std::shared_ptr<GuiComponent>& comp,
|
||||
const Vector2i& pos,
|
||||
bool canFocus,
|
||||
bool resize,
|
||||
const Vector2i& size,
|
||||
unsigned int border,
|
||||
GridFlags::UpdateType updateType)
|
||||
void ComponentGrid::setEntry(const std::shared_ptr<GuiComponent>& comp,
|
||||
const Vector2i& pos,
|
||||
bool canFocus,
|
||||
bool resize,
|
||||
const Vector2i& size,
|
||||
unsigned int border,
|
||||
GridFlags::UpdateType updateType)
|
||||
{
|
||||
assert(pos.x() >= 0 && pos.x() < mGridSize.x() && pos.y() >= 0 && pos.y() < mGridSize.y());
|
||||
assert(comp != nullptr);
|
||||
|
@ -294,14 +292,14 @@ bool ComponentGrid::moveCursor(Vector2i dir)
|
|||
Vector2i searchAxis(dir.x() == 0, dir.y() == 0);
|
||||
|
||||
while (mCursor.x() >= 0 && mCursor.y() >= 0 && mCursor.x() < mGridSize.x() &&
|
||||
mCursor.y() < mGridSize.y()) {
|
||||
mCursor.y() < mGridSize.y()) {
|
||||
mCursor = mCursor + dir;
|
||||
Vector2i curDirPos = mCursor;
|
||||
const GridEntry* cursorEntry;
|
||||
|
||||
// Spread out on search axis+
|
||||
while (mCursor.x() < mGridSize.x() && mCursor.y() < mGridSize.y()
|
||||
&& mCursor.x() >= 0 && mCursor.y() >= 0) {
|
||||
while (mCursor.x() < mGridSize.x() && mCursor.y() < mGridSize.y() && mCursor.x() >= 0 &&
|
||||
mCursor.y() >= 0) {
|
||||
cursorEntry = getCellAt(mCursor);
|
||||
if (cursorEntry && cursorEntry->canFocus && cursorEntry != currentCursorEntry) {
|
||||
onCursorMoved(origCursor, mCursor);
|
||||
|
@ -312,8 +310,8 @@ bool ComponentGrid::moveCursor(Vector2i dir)
|
|||
|
||||
// Now again on search axis-
|
||||
mCursor = curDirPos;
|
||||
while (mCursor.x() >= 0 && mCursor.y() >= 0
|
||||
&& mCursor.x() < mGridSize.x() && mCursor.y() < mGridSize.y()) {
|
||||
while (mCursor.x() >= 0 && mCursor.y() >= 0 && mCursor.x() < mGridSize.x() &&
|
||||
mCursor.y() < mGridSize.y()) {
|
||||
cursorEntry = getCellAt(mCursor);
|
||||
|
||||
if (cursorEntry && cursorEntry->canFocus && cursorEntry != currentCursorEntry) {
|
||||
|
@ -356,8 +354,9 @@ void ComponentGrid::update(int deltaTime)
|
|||
const GridEntry* cursorEntry = getCellAt(mCursor);
|
||||
for (auto it = mCells.cbegin(); it != mCells.cend(); it++) {
|
||||
if (it->updateType == UPDATE_ALWAYS ||
|
||||
(it->updateType == UPDATE_WHEN_SELECTED && cursorEntry == &(*it)))
|
||||
(it->updateType == UPDATE_WHEN_SELECTED && cursorEntry == &(*it))) {
|
||||
it->component->update(deltaTime);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -371,7 +370,7 @@ void ComponentGrid::render(const Transform4x4f& parentTrans)
|
|||
for (size_t i = 0; i < mSeparators.size(); i++) {
|
||||
Renderer::setMatrix(trans);
|
||||
Renderer::drawRect(mSeparators[i][0], mSeparators[i][1], mSeparators[i][2],
|
||||
mSeparators[i][3], 0xC6C7C6FF, 0xC6C7C6FF);
|
||||
mSeparators[i][3], 0xC6C7C6FF, 0xC6C7C6FF);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -9,14 +9,14 @@
|
|||
#ifndef ES_CORE_COMPONENTS_COMPONENT_GRID_H
|
||||
#define ES_CORE_COMPONENTS_COMPONENT_GRID_H
|
||||
|
||||
#include "GuiComponent.h"
|
||||
#include "math/Vector2i.h"
|
||||
#include "renderers/Renderer.h"
|
||||
#include "GuiComponent.h"
|
||||
|
||||
namespace GridFlags
|
||||
{
|
||||
enum UpdateType {
|
||||
UPDATE_ALWAYS,
|
||||
UPDATE_ALWAYS, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
UPDATE_WHEN_SELECTED,
|
||||
UPDATE_NEVER
|
||||
};
|
||||
|
@ -28,7 +28,7 @@ namespace GridFlags
|
|||
BORDER_LEFT = 4,
|
||||
BORDER_RIGHT = 8
|
||||
};
|
||||
};
|
||||
}; // namespace GridFlags
|
||||
|
||||
// Provides basic layout of components in an X*Y grid.
|
||||
class ComponentGrid : public GuiComponent
|
||||
|
@ -39,14 +39,13 @@ public:
|
|||
|
||||
bool removeEntry(const std::shared_ptr<GuiComponent>& comp);
|
||||
|
||||
void setEntry(
|
||||
const std::shared_ptr<GuiComponent>& comp,
|
||||
const Vector2i& pos,
|
||||
bool canFocus,
|
||||
bool resize = true,
|
||||
const Vector2i& size = Vector2i(1, 1),
|
||||
unsigned int border = GridFlags::BORDER_NONE,
|
||||
GridFlags::UpdateType updateType = GridFlags::UPDATE_ALWAYS);
|
||||
void setEntry(const std::shared_ptr<GuiComponent>& comp,
|
||||
const Vector2i& pos,
|
||||
bool canFocus,
|
||||
bool resize = true,
|
||||
const Vector2i& size = Vector2i(1, 1),
|
||||
unsigned int border = GridFlags::BORDER_NONE,
|
||||
GridFlags::UpdateType updateType = GridFlags::UPDATE_ALWAYS);
|
||||
|
||||
void textInput(const std::string& text) override;
|
||||
bool input(InputConfig* config, Input input) override;
|
||||
|
@ -69,7 +68,7 @@ public:
|
|||
bool moveCursor(Vector2i dir);
|
||||
void setCursorTo(const std::shared_ptr<GuiComponent>& comp);
|
||||
|
||||
inline std::shared_ptr<GuiComponent> getSelectedComponent()
|
||||
std::shared_ptr<GuiComponent> getSelectedComponent()
|
||||
{
|
||||
const GridEntry* e = getCellAt(mCursor);
|
||||
if (e)
|
||||
|
@ -95,28 +94,24 @@ private:
|
|||
GridFlags::UpdateType updateType;
|
||||
unsigned int border;
|
||||
|
||||
GridEntry(
|
||||
const Vector2i& p = Vector2i::Zero(),
|
||||
const Vector2i& d = Vector2i::Zero(),
|
||||
const std::shared_ptr<GuiComponent>& cmp = nullptr,
|
||||
bool f = false,
|
||||
bool r = true,
|
||||
GridFlags::UpdateType u = GridFlags::UPDATE_ALWAYS,
|
||||
unsigned int b =
|
||||
GridFlags::BORDER_NONE)
|
||||
: pos(p),
|
||||
dim(d),
|
||||
component(cmp),
|
||||
canFocus(f),
|
||||
resize(r),
|
||||
updateType(u),
|
||||
border(b)
|
||||
{};
|
||||
|
||||
operator bool() const
|
||||
GridEntry(const Vector2i& p = Vector2i::Zero(),
|
||||
const Vector2i& d = Vector2i::Zero(),
|
||||
const std::shared_ptr<GuiComponent>& cmp = nullptr,
|
||||
bool f = false,
|
||||
bool r = true,
|
||||
GridFlags::UpdateType u = GridFlags::UPDATE_ALWAYS,
|
||||
unsigned int b = GridFlags::BORDER_NONE)
|
||||
: pos(p)
|
||||
, dim(d)
|
||||
, component(cmp)
|
||||
, canFocus(f)
|
||||
, resize(r)
|
||||
, updateType(u)
|
||||
, border(b)
|
||||
{
|
||||
return component != nullptr;
|
||||
}
|
||||
|
||||
operator bool() const { return component != nullptr; }
|
||||
};
|
||||
|
||||
// Update position and size.
|
||||
|
@ -125,9 +120,7 @@ private:
|
|||
|
||||
void onCursorMoved(Vector2i from, Vector2i to);
|
||||
const GridEntry* getCellAt(int x, int y) const;
|
||||
|
||||
inline const GridEntry* getCellAt(const Vector2i& pos) const
|
||||
{ return getCellAt(pos.x(), pos.y()); }
|
||||
const GridEntry* getCellAt(const Vector2i& pos) const { return getCellAt(pos.x(), pos.y()); }
|
||||
|
||||
std::vector<std::vector<float>> mSeparators;
|
||||
Vector2i mGridSize;
|
||||
|
|
|
@ -10,14 +10,14 @@
|
|||
|
||||
#define TOTAL_HORIZONTAL_PADDING_PX 20.0f
|
||||
|
||||
ComponentList::ComponentList(Window* window) : IList<ComponentListRow,
|
||||
void*>(window, LIST_SCROLL_STYLE_SLOW, LIST_NEVER_LOOP)
|
||||
ComponentList::ComponentList(Window* window)
|
||||
: IList<ComponentListRow, void*>(window, LIST_SCROLL_STYLE_SLOW, LIST_NEVER_LOOP)
|
||||
{
|
||||
// Adjust the padding relative to the aspect ratio and screen resolution to make it look
|
||||
// coherent regardless of screen type. The 1.778 aspect ratio value is the 16:9 reference.
|
||||
float aspectValue = 1.778f / Renderer::getScreenAspectRatio();
|
||||
mHorizontalPadding = TOTAL_HORIZONTAL_PADDING_PX * aspectValue *
|
||||
Renderer::getScreenWidthModifier();
|
||||
mHorizontalPadding =
|
||||
TOTAL_HORIZONTAL_PADDING_PX * aspectValue * Renderer::getScreenWidthModifier();
|
||||
|
||||
mSelectorBarOffset = 0.0f;
|
||||
mCameraOffset = 0.0f;
|
||||
|
@ -34,7 +34,7 @@ void ComponentList::addRow(const ComponentListRow& row, bool setCursorHere)
|
|||
this->add(e);
|
||||
|
||||
for (auto it = mEntries.back().data.elements.cbegin();
|
||||
it != mEntries.back().data.elements.cend(); it++)
|
||||
it != mEntries.back().data.elements.cend(); it++)
|
||||
addChild(it->component.get());
|
||||
|
||||
updateElementSize(mEntries.back().data);
|
||||
|
@ -56,16 +56,6 @@ void ComponentList::onSizeChanged()
|
|||
updateCameraOffset();
|
||||
}
|
||||
|
||||
void ComponentList::onFocusLost()
|
||||
{
|
||||
mFocused = false;
|
||||
}
|
||||
|
||||
void ComponentList::onFocusGained()
|
||||
{
|
||||
mFocused = true;
|
||||
}
|
||||
|
||||
bool ComponentList::input(InputConfig* config, Input input)
|
||||
{
|
||||
if (size() == 0)
|
||||
|
@ -122,7 +112,7 @@ void ComponentList::update(int deltaTime)
|
|||
if (size()) {
|
||||
// Update our currently selected row.
|
||||
for (auto it = mEntries.at(mCursor).data.elements.cbegin();
|
||||
it != mEntries.at(mCursor).data.elements.cend(); it++)
|
||||
it != mEntries.at(mCursor).data.elements.cend(); it++)
|
||||
it->component->update(deltaTime);
|
||||
}
|
||||
}
|
||||
|
@ -156,8 +146,8 @@ void ComponentList::updateCameraOffset()
|
|||
// Move the camera to scroll.
|
||||
const float totalHeight = getTotalRowHeight();
|
||||
if (totalHeight > mSize.y()) {
|
||||
float target = mSelectorBarOffset +
|
||||
getRowHeight(mEntries.at(mCursor).data) / 2.0f - (mSize.y() / 2.0f);
|
||||
float target = mSelectorBarOffset + getRowHeight(mEntries.at(mCursor).data) / 2.0f -
|
||||
(mSize.y() / 2.0f);
|
||||
|
||||
// Clamp the camera to prevent a fraction of a row from being displayed.
|
||||
mCameraOffset = 0.0f;
|
||||
|
@ -187,9 +177,10 @@ void ComponentList::render(const Transform4x4f& parentTrans)
|
|||
// Clip everything to be inside our bounds.
|
||||
Vector3f dim(mSize.x(), mSize.y(), 0.0f);
|
||||
dim = trans * dim - trans.translation();
|
||||
Renderer::pushClipRect(Vector2i(static_cast<int>(std::round(trans.translation().x())),
|
||||
static_cast<int>(std::round(trans.translation().y()))), Vector2i(static_cast<int>(
|
||||
std::round(dim.x())), static_cast<int>(std::round(dim.y()))));
|
||||
Renderer::pushClipRect(
|
||||
Vector2i(static_cast<int>(std::round(trans.translation().x())),
|
||||
static_cast<int>(std::round(trans.translation().y()))),
|
||||
Vector2i(static_cast<int>(std::round(dim.x())), static_cast<int>(std::round(dim.y()))));
|
||||
|
||||
// Scroll the camera.
|
||||
trans.translate(Vector3f(0.0f, -std::round(mCameraOffset), 0.0f));
|
||||
|
@ -205,7 +196,7 @@ void ComponentList::render(const Transform4x4f& parentTrans)
|
|||
// For the row where the cursor is at, we want to remove any hue from the
|
||||
// font or image before inverting, as it would otherwise lead to an ugly
|
||||
// inverted color (e.g. red inverting to a green hue).
|
||||
if (i == mCursor && it->component->getValue() != "" ) {
|
||||
if (i == mCursor && it->component->getValue() != "") {
|
||||
// Check if we're dealing with text or an image component.
|
||||
bool isTextComponent = true;
|
||||
unsigned int origColor = it->component->getColor();
|
||||
|
@ -260,13 +251,13 @@ void ComponentList::render(const Transform4x4f& parentTrans)
|
|||
const float selectedRowHeight = getRowHeight(mEntries.at(mCursor).data);
|
||||
|
||||
if (opacity == 1) {
|
||||
Renderer::drawRect(0.0f, mSelectorBarOffset, mSize.x(),
|
||||
selectedRowHeight, 0xFFFFFFFF, 0xFFFFFFFF, false, opacity, trans,
|
||||
Renderer::Blend::ONE_MINUS_DST_COLOR, Renderer::Blend::ZERO);
|
||||
Renderer::drawRect(0.0f, mSelectorBarOffset, mSize.x(), selectedRowHeight, 0xFFFFFFFF,
|
||||
0xFFFFFFFF, false, opacity, trans,
|
||||
Renderer::Blend::ONE_MINUS_DST_COLOR, Renderer::Blend::ZERO);
|
||||
|
||||
Renderer::drawRect(0.0f, mSelectorBarOffset, mSize.x(),
|
||||
selectedRowHeight, 0x777777FF, 0x777777FF, false, opacity, trans,
|
||||
Renderer::Blend::ONE, Renderer::Blend::ONE);
|
||||
Renderer::drawRect(0.0f, mSelectorBarOffset, mSize.x(), selectedRowHeight, 0x777777FF,
|
||||
0x777777FF, false, opacity, trans, Renderer::Blend::ONE,
|
||||
Renderer::Blend::ONE);
|
||||
}
|
||||
|
||||
for (auto it = drawAfterCursor.cbegin(); it != drawAfterCursor.cend(); it++)
|
||||
|
@ -281,12 +272,12 @@ void ComponentList::render(const Transform4x4f& parentTrans)
|
|||
float y = 0;
|
||||
for (unsigned int i = 0; i < mEntries.size(); i++) {
|
||||
Renderer::drawRect(0.0f, y, mSize.x(), 1.0f * Renderer::getScreenHeightModifier(),
|
||||
0xC6C7C6FF, 0xC6C7C6FF, false, opacity, trans);
|
||||
0xC6C7C6FF, 0xC6C7C6FF, false, opacity, trans);
|
||||
y += getRowHeight(mEntries.at(i).data);
|
||||
}
|
||||
|
||||
Renderer::drawRect(0.0f, y, mSize.x(), 1.0f * Renderer::getScreenHeightModifier(),
|
||||
0xC6C7C6FF, 0xC6C7C6FF, false, opacity, trans);
|
||||
Renderer::drawRect(0.0f, y, mSize.x(), 1.0f * Renderer::getScreenHeightModifier(), 0xC6C7C6FF,
|
||||
0xC6C7C6FF, false, opacity, trans);
|
||||
Renderer::popClipRect();
|
||||
}
|
||||
|
||||
|
@ -362,7 +353,7 @@ std::vector<HelpPrompt> ComponentList::getHelpPrompts()
|
|||
return std::vector<HelpPrompt>();
|
||||
|
||||
std::vector<HelpPrompt> prompts =
|
||||
mEntries.at(mCursor).data.elements.back().component->getHelpPrompts();
|
||||
mEntries.at(mCursor).data.elements.back().component->getHelpPrompts();
|
||||
|
||||
if (size() > 1) {
|
||||
bool addMovePrompt = true;
|
||||
|
|
|
@ -12,21 +12,21 @@
|
|||
#include "IList.h"
|
||||
|
||||
struct ComponentListElement {
|
||||
ComponentListElement(
|
||||
const std::shared_ptr<GuiComponent>& cmp = nullptr,
|
||||
bool resize_w = true,
|
||||
bool inv = true)
|
||||
: component(cmp),
|
||||
resize_width(resize_w),
|
||||
invert_when_selected(inv) {};
|
||||
ComponentListElement(const std::shared_ptr<GuiComponent>& cmp = nullptr,
|
||||
bool resize_w = true,
|
||||
bool inv = true)
|
||||
: component(cmp)
|
||||
, resize_width(resize_w)
|
||||
, invert_when_selected(inv)
|
||||
{
|
||||
}
|
||||
|
||||
std::shared_ptr<GuiComponent> component;
|
||||
bool resize_width;
|
||||
bool invert_when_selected;
|
||||
};
|
||||
|
||||
struct ComponentListRow
|
||||
{
|
||||
struct ComponentListRow {
|
||||
std::vector<ComponentListElement> elements;
|
||||
|
||||
// The input handler is called when the user enters any input while this row is
|
||||
|
@ -36,14 +36,15 @@ struct ComponentListRow
|
|||
// to forward the input to the rightmost element in the currently selected row.
|
||||
std::function<bool(InputConfig*, Input)> input_handler;
|
||||
|
||||
inline void addElement(const std::shared_ptr<GuiComponent>& component,
|
||||
bool resize_width, bool invert_when_selected = true)
|
||||
void addElement(const std::shared_ptr<GuiComponent>& component,
|
||||
bool resize_width,
|
||||
bool invert_when_selected = true)
|
||||
{
|
||||
elements.push_back(ComponentListElement(component, resize_width, invert_when_selected));
|
||||
}
|
||||
|
||||
// Utility function for making an input handler for "when the users presses A on this, do func".
|
||||
inline void makeAcceptInputHandler(const std::function<void()>& func)
|
||||
void makeAcceptInputHandler(const std::function<void()>& func)
|
||||
{
|
||||
input_handler = [func](InputConfig* config, Input input) -> bool {
|
||||
if (config->isMappedTo("a", input) && input.value != 0) {
|
||||
|
@ -69,19 +70,23 @@ public:
|
|||
virtual std::vector<HelpPrompt> getHelpPrompts() override;
|
||||
|
||||
void onSizeChanged() override;
|
||||
void onFocusGained() override;
|
||||
void onFocusLost() override;
|
||||
void onFocusGained() override { mFocused = true; }
|
||||
void onFocusLost() override { mFocused = false; }
|
||||
|
||||
bool moveCursor(int amt);
|
||||
inline int getCursorId() const { return mCursor; }
|
||||
int getCursorId() const { return mCursor; }
|
||||
|
||||
float getTotalRowHeight() const;
|
||||
inline float getRowHeight(int row) const { return getRowHeight(mEntries.at(row).data); }
|
||||
float getRowHeight(int row) const { return getRowHeight(mEntries.at(row).data); }
|
||||
|
||||
inline void setCursorChangedCallback(const std::function<void(CursorState state)>& callback)
|
||||
{ mCursorChangedCallback = callback; };
|
||||
inline const std::function<void(CursorState state)>& getCursorChangedCallback() const
|
||||
{ return mCursorChangedCallback; };
|
||||
void setCursorChangedCallback(const std::function<void(CursorState state)>& callback)
|
||||
{
|
||||
mCursorChangedCallback = callback;
|
||||
}
|
||||
const std::function<void(CursorState state)>& getCursorChangedCallback() const
|
||||
{
|
||||
return mCursorChangedCallback;
|
||||
}
|
||||
|
||||
protected:
|
||||
void onCursorChanged(const CursorState& state) override;
|
||||
|
|
|
@ -10,28 +10,28 @@
|
|||
|
||||
#include "components/DateTimeComponent.h"
|
||||
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Log.h"
|
||||
#include "Settings.h"
|
||||
#include "utils/StringUtil.h"
|
||||
|
||||
DateTimeComponent::DateTimeComponent(Window* window)
|
||||
: TextComponent(window), mDisplayRelative(false)
|
||||
: TextComponent(window)
|
||||
, mDisplayRelative(false)
|
||||
{
|
||||
// ISO 8601 date format.
|
||||
setFormat("%Y-%m-%d");
|
||||
}
|
||||
|
||||
DateTimeComponent::DateTimeComponent(
|
||||
Window* window,
|
||||
const std::string& text,
|
||||
const std::shared_ptr<Font>& font,
|
||||
unsigned int color,
|
||||
Alignment align,
|
||||
Vector3f pos,
|
||||
Vector2f size,
|
||||
unsigned int bgcolor)
|
||||
: TextComponent(window, text, font, color, align, pos, size, bgcolor),
|
||||
mDisplayRelative(false)
|
||||
DateTimeComponent::DateTimeComponent(Window* window,
|
||||
const std::string& text,
|
||||
const std::shared_ptr<Font>& font,
|
||||
unsigned int color,
|
||||
Alignment align,
|
||||
Vector3f pos,
|
||||
Vector2f size,
|
||||
unsigned int bgcolor)
|
||||
: TextComponent(window, text, font, color, align, pos, size, bgcolor)
|
||||
, mDisplayRelative(false)
|
||||
{
|
||||
// ISO 8601 date format.
|
||||
setFormat("%Y-%m-%d");
|
||||
|
@ -45,6 +45,7 @@ void DateTimeComponent::setValue(const std::string& val)
|
|||
|
||||
std::string DateTimeComponent::getValue() const
|
||||
{
|
||||
// Return time value as a string.
|
||||
return mTime;
|
||||
}
|
||||
|
||||
|
@ -79,17 +80,17 @@ std::string DateTimeComponent::getDisplayString() const
|
|||
std::string buf;
|
||||
|
||||
if (dur.getDays() > 0)
|
||||
buf = std::to_string(dur.getDays()) + " day" +
|
||||
(dur.getDays() > 1 ? "s" : "") + " ago";
|
||||
buf = std::to_string(dur.getDays()) + " day" + // Line break.
|
||||
(dur.getDays() > 1 ? "s" : "") + " ago";
|
||||
else if (dur.getHours() > 0)
|
||||
buf = std::to_string(dur.getHours()) + " hour" +
|
||||
(dur.getHours() > 1 ? "s" : "") + " ago";
|
||||
buf = std::to_string(dur.getHours()) + " hour" + // Line break.
|
||||
(dur.getHours() > 1 ? "s" : "") + " ago";
|
||||
else if (dur.getMinutes() > 0)
|
||||
buf = std::to_string(dur.getMinutes()) + " minute" +
|
||||
(dur.getMinutes() > 1 ? "s" : "") + " ago";
|
||||
buf = std::to_string(dur.getMinutes()) + " minute" + // Line break.
|
||||
(dur.getMinutes() > 1 ? "s" : "") + " ago";
|
||||
else
|
||||
buf = std::to_string(dur.getSeconds()) + " second" +
|
||||
(dur.getSeconds() > 1 || dur.getSeconds() == 0 ? "s" : "") + " ago";
|
||||
buf = std::to_string(dur.getSeconds()) + " second" + // Line break.
|
||||
(dur.getSeconds() > 1 || dur.getSeconds() == 0 ? "s" : "") + " ago";
|
||||
|
||||
return std::string(buf);
|
||||
}
|
||||
|
@ -106,7 +107,9 @@ void DateTimeComponent::render(const Transform4x4f& parentTrans)
|
|||
}
|
||||
|
||||
void DateTimeComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& element, unsigned int properties)
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties)
|
||||
{
|
||||
GuiComponent::applyTheme(theme, view, element, properties);
|
||||
|
||||
|
@ -140,7 +143,7 @@ void DateTimeComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
else if (str == "right")
|
||||
setHorizontalAlignment(ALIGN_RIGHT);
|
||||
else
|
||||
LOG(LogError) << "Unknown text alignment string: " << str;
|
||||
LOG(LogError) << "Unknown text alignment string: " << str;
|
||||
}
|
||||
|
||||
if (properties & FORCE_UPPERCASE && elem->has("forceUppercase"))
|
||||
|
|
|
@ -11,8 +11,8 @@
|
|||
#ifndef ES_CORE_COMPONENTS_DATE_TIME_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_DATE_TIME_COMPONENT_H
|
||||
|
||||
#include "utils/TimeUtil.h"
|
||||
#include "TextComponent.h"
|
||||
#include "utils/TimeUtil.h"
|
||||
|
||||
class ThemeData;
|
||||
|
||||
|
@ -21,15 +21,14 @@ class DateTimeComponent : public TextComponent
|
|||
{
|
||||
public:
|
||||
DateTimeComponent(Window* window);
|
||||
DateTimeComponent(
|
||||
Window* window,
|
||||
const std::string& text,
|
||||
const std::shared_ptr<Font>& font,
|
||||
unsigned int color = 0x000000FF,
|
||||
Alignment align = ALIGN_LEFT,
|
||||
Vector3f pos = Vector3f::Zero(),
|
||||
Vector2f size = Vector2f::Zero(),
|
||||
unsigned int bgcolor = 0x00000000);
|
||||
DateTimeComponent(Window* window,
|
||||
const std::string& text,
|
||||
const std::shared_ptr<Font>& font,
|
||||
unsigned int color = 0x000000FF,
|
||||
Alignment align = ALIGN_LEFT,
|
||||
Vector3f pos = Vector3f::Zero(),
|
||||
Vector2f size = Vector2f::Zero(),
|
||||
unsigned int bgcolor = 0x00000000);
|
||||
|
||||
void render(const Transform4x4f& parentTrans) override;
|
||||
|
||||
|
@ -39,8 +38,10 @@ public:
|
|||
void setFormat(const std::string& format);
|
||||
void setDisplayRelative(bool displayRelative);
|
||||
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties) override;
|
||||
|
||||
protected:
|
||||
void onTextChanged() override;
|
||||
|
|
|
@ -8,24 +8,21 @@
|
|||
|
||||
#include "components/DateTimeEditComponent.h"
|
||||
|
||||
#include "Settings.h"
|
||||
#include "resources/Font.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Settings.h"
|
||||
|
||||
DateTimeEditComponent::DateTimeEditComponent(
|
||||
Window* window,
|
||||
bool alignRight,
|
||||
DisplayMode dispMode)
|
||||
: GuiComponent(window),
|
||||
mEditing(false),
|
||||
mEditIndex(0),
|
||||
mDisplayMode(dispMode),
|
||||
mRelativeUpdateAccumulator(0),
|
||||
mColor(0x777777FF),
|
||||
mFont(Font::get(FONT_SIZE_SMALL, FONT_PATH_LIGHT)),
|
||||
mUppercase(false),
|
||||
mAutoSize(true),
|
||||
mAlignRight(alignRight)
|
||||
DateTimeEditComponent::DateTimeEditComponent(Window* window, bool alignRight, DisplayMode dispMode)
|
||||
: GuiComponent(window)
|
||||
, mEditing(false)
|
||||
, mEditIndex(0)
|
||||
, mDisplayMode(dispMode)
|
||||
, mRelativeUpdateAccumulator(0)
|
||||
, mColor(0x777777FF)
|
||||
, mFont(Font::get(FONT_SIZE_SMALL, FONT_PATH_LIGHT))
|
||||
, mUppercase(false)
|
||||
, mAutoSize(true)
|
||||
, mAlignRight(alignRight)
|
||||
{
|
||||
updateTextCache();
|
||||
}
|
||||
|
@ -68,8 +65,9 @@ bool DateTimeEditComponent::input(InputConfig* config, Input input)
|
|||
if (mEditing) {
|
||||
|
||||
if (config->isMappedLike("lefttrigger", input) ||
|
||||
config->isMappedLike("righttrigger", input))
|
||||
config->isMappedLike("righttrigger", input)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (config->isMappedTo("b", input)) {
|
||||
mEditing = false;
|
||||
|
@ -101,23 +99,21 @@ bool DateTimeEditComponent::input(InputConfig* config, Input input)
|
|||
new_tm.tm_mon = 0;
|
||||
else if (new_tm.tm_mon < 0)
|
||||
new_tm.tm_mon = 11;
|
||||
|
||||
}
|
||||
else if (mEditIndex == 2) {
|
||||
const int days_in_month =
|
||||
Utils::Time::daysInMonth(new_tm.tm_year + 1900, new_tm.tm_mon + 1);
|
||||
Utils::Time::daysInMonth(new_tm.tm_year + 1900, new_tm.tm_mon + 1);
|
||||
new_tm.tm_mday += incDir;
|
||||
|
||||
if (new_tm.tm_mday > days_in_month)
|
||||
new_tm.tm_mday = 1;
|
||||
else if (new_tm.tm_mday < 1)
|
||||
new_tm.tm_mday = days_in_month;
|
||||
|
||||
}
|
||||
|
||||
// Validate day.
|
||||
const int days_in_month =
|
||||
Utils::Time::daysInMonth(new_tm.tm_year + 1900, new_tm.tm_mon + 1);
|
||||
Utils::Time::daysInMonth(new_tm.tm_year + 1900, new_tm.tm_mon + 1);
|
||||
if (new_tm.tm_mday > days_in_month)
|
||||
new_tm.tm_mday = days_in_month;
|
||||
|
||||
|
@ -185,11 +181,11 @@ void DateTimeEditComponent::render(const Transform4x4f& parentTrans)
|
|||
if (Settings::getInstance()->getBool("DebugText")) {
|
||||
Renderer::setMatrix(trans);
|
||||
if (mTextCache->metrics.size.x() > 0) {
|
||||
Renderer::drawRect(0.0f, 0.0f - off.y(),
|
||||
mSize.x() - off.x(), mSize.y(), 0x0000FF33, 0x0000FF33);
|
||||
Renderer::drawRect(0.0f, 0.0f - off.y(), mSize.x() - off.x(), mSize.y(), 0x0000FF33,
|
||||
0x0000FF33);
|
||||
}
|
||||
Renderer::drawRect(0.0f, 0.0f, mTextCache->metrics.size.x(),
|
||||
mTextCache->metrics.size.y(), 0x00000033, 0x00000033);
|
||||
mTextCache->metrics.size.y(), 0x00000033, 0x00000033);
|
||||
}
|
||||
|
||||
mTextCache->setColor((mColor & 0xFFFFFF00) | getOpacity());
|
||||
|
@ -198,8 +194,8 @@ void DateTimeEditComponent::render(const Transform4x4f& parentTrans)
|
|||
if (mEditing) {
|
||||
if (mEditIndex >= 0 && static_cast<unsigned int>(mEditIndex) < mCursorBoxes.size())
|
||||
Renderer::drawRect(mCursorBoxes[mEditIndex][0], mCursorBoxes[mEditIndex][1],
|
||||
mCursorBoxes[mEditIndex][2], mCursorBoxes[mEditIndex][3],
|
||||
0x00000022, 0x00000022);
|
||||
mCursorBoxes[mEditIndex][2], mCursorBoxes[mEditIndex][3],
|
||||
0x00000022, 0x00000022);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -211,41 +207,24 @@ void DateTimeEditComponent::setValue(const std::string& val)
|
|||
updateTextCache();
|
||||
}
|
||||
|
||||
std::string DateTimeEditComponent::getValue() const
|
||||
{
|
||||
return mTime;
|
||||
}
|
||||
|
||||
DateTimeEditComponent::DisplayMode DateTimeEditComponent::getCurrentDisplayMode() const
|
||||
{
|
||||
// if (mEditing) {
|
||||
// if (mDisplayMode == DISP_RELATIVE_TO_NOW) {
|
||||
// // TODO: if time component == 00:00:00, return DISP_DATE, else return DISP_DATE_TIME.
|
||||
// return DISP_DATE;
|
||||
// }
|
||||
// }
|
||||
|
||||
return mDisplayMode;
|
||||
}
|
||||
|
||||
std::string DateTimeEditComponent::getDisplayString(DisplayMode mode) const
|
||||
{
|
||||
// ISO 8601 date format.
|
||||
std::string fmt;
|
||||
switch (mode) {
|
||||
case DISP_DATE: {
|
||||
if (mTime.getTime() == 0)
|
||||
return "unknown";
|
||||
fmt = "%Y-%m-%d";
|
||||
break;
|
||||
}
|
||||
case DISP_DATE_TIME: {
|
||||
if (mTime.getTime() == 0)
|
||||
return "unknown";
|
||||
fmt = "%Y-%m-%d %H:%M:%S";
|
||||
break;
|
||||
}
|
||||
case DISP_RELATIVE_TO_NOW: {
|
||||
case DISP_DATE: {
|
||||
if (mTime.getTime() == 0)
|
||||
return "unknown";
|
||||
fmt = "%Y-%m-%d";
|
||||
break;
|
||||
}
|
||||
case DISP_DATE_TIME: {
|
||||
if (mTime.getTime() == 0)
|
||||
return "unknown";
|
||||
fmt = "%Y-%m-%d %H:%M:%S";
|
||||
break;
|
||||
}
|
||||
case DISP_RELATIVE_TO_NOW: {
|
||||
// Relative time.
|
||||
if (mTime.getTime() == 0)
|
||||
return "never";
|
||||
|
@ -256,21 +235,22 @@ std::string DateTimeEditComponent::getDisplayString(DisplayMode mode) const
|
|||
std::string buf;
|
||||
|
||||
if (dur.getDays() > 0)
|
||||
buf = std::to_string(dur.getDays()) + " day" +
|
||||
(dur.getDays() > 1 ? "s" : "") + " ago";
|
||||
buf = std::to_string(dur.getDays()) + // Line break.
|
||||
" day" + (dur.getDays() > 1 ? "s" : "") + " ago";
|
||||
else if (dur.getHours() > 0)
|
||||
buf = std::to_string(dur.getHours()) + " hour" +
|
||||
(dur.getHours() > 1 ? "s" : "") + " ago";
|
||||
buf = std::to_string(dur.getHours()) + // Line break.
|
||||
" hour" + (dur.getHours() > 1 ? "s" : "") + " ago";
|
||||
else if (dur.getMinutes() > 0)
|
||||
buf = std::to_string(dur.getMinutes()) + " minute" +
|
||||
(dur.getMinutes() > 1 ? "s" : "") + " ago";
|
||||
buf = std::to_string(dur.getMinutes()) + // Line break.
|
||||
" minute" + (dur.getMinutes() > 1 ? "s" : "") + " ago";
|
||||
else
|
||||
buf = std::to_string(dur.getSeconds()) + " second" +
|
||||
(dur.getSeconds() > 1 || dur.getSeconds() == 0 ? "s" : "") + " ago";
|
||||
buf = std::to_string(dur.getSeconds()) + // Line break.
|
||||
" second" + (dur.getSeconds() > 1 || dur.getSeconds() == 0 ? "s" : "") +
|
||||
" ago";
|
||||
|
||||
return std::string(buf);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
return Utils::Time::timeToString(mTime, fmt);
|
||||
|
@ -296,16 +276,16 @@ void DateTimeEditComponent::updateTextCache()
|
|||
dispString = "";
|
||||
}
|
||||
else {
|
||||
dispString = mUppercase ? Utils::String::toUpper(getDisplayString(mode)) :
|
||||
getDisplayString(mode);
|
||||
dispString =
|
||||
mUppercase ? Utils::String::toUpper(getDisplayString(mode)) : getDisplayString(mode);
|
||||
}
|
||||
std::shared_ptr<Font> font = getFont();
|
||||
mTextCache = std::unique_ptr<TextCache>(font->buildTextCache(dispString, 0, 0, mColor));
|
||||
|
||||
if (mAutoSize) {
|
||||
mSize = mTextCache->metrics.size;
|
||||
|
||||
mAutoSize = false;
|
||||
|
||||
if (getParent())
|
||||
getParent()->onSizeChanged();
|
||||
}
|
||||
|
@ -367,7 +347,9 @@ void DateTimeEditComponent::setUppercase(bool uppercase)
|
|||
}
|
||||
|
||||
void DateTimeEditComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& element, unsigned int properties)
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties)
|
||||
{
|
||||
const ThemeData::ThemeElement* elem = theme->getElement(view, element, "datetime");
|
||||
|
||||
|
|
|
@ -9,8 +9,8 @@
|
|||
#ifndef ES_CORE_COMPONENTS_DATE_TIME_EDIT_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_DATE_TIME_EDIT_COMPONENT_H
|
||||
|
||||
#include "utils/TimeUtil.h"
|
||||
#include "GuiComponent.h"
|
||||
#include "utils/TimeUtil.h"
|
||||
|
||||
class TextCache;
|
||||
|
||||
|
@ -18,21 +18,22 @@ class TextCache;
|
|||
class DateTimeEditComponent : public GuiComponent
|
||||
{
|
||||
public:
|
||||
enum DisplayMode{
|
||||
DISP_DATE,
|
||||
enum DisplayMode {
|
||||
DISP_DATE, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
DISP_DATE_TIME,
|
||||
DISP_RELATIVE_TO_NOW
|
||||
};
|
||||
|
||||
DateTimeEditComponent(Window* window, bool alignRight = false,
|
||||
DisplayMode dispMode = DISP_DATE);
|
||||
DateTimeEditComponent(Window* window,
|
||||
bool alignRight = false,
|
||||
DisplayMode dispMode = DISP_DATE);
|
||||
|
||||
void setValue(const std::string& val) override;
|
||||
std::string getValue() const override;
|
||||
std::string getValue() const override { return mTime; }
|
||||
|
||||
bool input(InputConfig* config, Input input) override;
|
||||
void update(int deltaTime) override;
|
||||
unsigned int getColor() const override { return mColor; };
|
||||
unsigned int getColor() const override { return mColor; }
|
||||
void render(const Transform4x4f& parentTrans) override;
|
||||
void onSizeChanged() override;
|
||||
|
||||
|
@ -45,19 +46,21 @@ public:
|
|||
// The initial value is DISP_DATE.
|
||||
void setDisplayMode(DisplayMode mode);
|
||||
|
||||
// Text color.
|
||||
// Text color.
|
||||
void setColor(unsigned int color) override;
|
||||
// Font to use. Default is Font::get(FONT_SIZE_MEDIUM).
|
||||
|
||||
void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; };
|
||||
void setChangedColor(unsigned int color) override { mColorChangedValue = color; };
|
||||
void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; }
|
||||
void setChangedColor(unsigned int color) override { mColorChangedValue = color; }
|
||||
|
||||
void setFont(std::shared_ptr<Font> font);
|
||||
// Force text to be uppercase when in DISP_RELATIVE_TO_NOW mode.
|
||||
void setUppercase(bool uppercase);
|
||||
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties) override;
|
||||
|
||||
virtual std::vector<HelpPrompt> getHelpPrompts() override;
|
||||
|
||||
|
@ -65,7 +68,7 @@ private:
|
|||
std::shared_ptr<Font> getFont() const override;
|
||||
|
||||
std::string getDisplayString(DisplayMode mode) const;
|
||||
DisplayMode getCurrentDisplayMode() const;
|
||||
DisplayMode getCurrentDisplayMode() const { return mDisplayMode; }
|
||||
|
||||
void updateTextCache();
|
||||
|
||||
|
|
|
@ -8,16 +8,17 @@
|
|||
|
||||
#include "GridTileComponent.h"
|
||||
|
||||
#include "ThemeData.h"
|
||||
#include "animations/LambdaAnimation.h"
|
||||
#include "resources/TextureResource.h"
|
||||
#include "ThemeData.h"
|
||||
|
||||
GridTileComponent::GridTileComponent(Window* window) :
|
||||
GuiComponent(window), mBackground(window, ":/graphics/frame.png")
|
||||
GridTileComponent::GridTileComponent(Window* window)
|
||||
: GuiComponent(window)
|
||||
, mBackground(window, ":/graphics/frame.png")
|
||||
{
|
||||
mDefaultProperties.mSize = getDefaultTileSize();
|
||||
mDefaultProperties.mPadding = Vector2f(16.0f * Renderer::getScreenWidthModifier(),
|
||||
16.0f * Renderer::getScreenHeightModifier());
|
||||
16.0f * Renderer::getScreenHeightModifier());
|
||||
mDefaultProperties.mImageColor = 0xAAAAAABB;
|
||||
// Attempting to use frame.svg instead causes quite severe performance problems.
|
||||
mDefaultProperties.mBackgroundImage = ":/graphics/frame.png";
|
||||
|
@ -76,7 +77,7 @@ void GridTileComponent::update(int deltaTime)
|
|||
void applyThemeToProperties(const ThemeData::ThemeElement* elem, GridTileProperties* properties)
|
||||
{
|
||||
Vector2f screen = Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
|
||||
if (elem->has("size"))
|
||||
properties->mSize = elem->get<Vector2f>("size") * screen;
|
||||
|
@ -106,10 +107,12 @@ void applyThemeToProperties(const ThemeData::ThemeElement* elem, GridTilePropert
|
|||
}
|
||||
|
||||
void GridTileComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& /*element*/, unsigned int /*properties*/)
|
||||
const std::string& view,
|
||||
const std::string& /*element*/,
|
||||
unsigned int /*properties*/)
|
||||
{
|
||||
Vector2f screen = Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
|
||||
// Apply theme to the default gridtile.
|
||||
const ThemeData::ThemeElement* elem = theme->getElement(view, "default", "gridtile");
|
||||
|
@ -133,26 +136,23 @@ void GridTileComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
Vector2f GridTileComponent::getDefaultTileSize()
|
||||
{
|
||||
Vector2f screen = Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
|
||||
return screen * 0.22f;
|
||||
}
|
||||
|
||||
Vector2f GridTileComponent::getSelectedTileSize() const
|
||||
{
|
||||
// Return the tile size.
|
||||
return mDefaultProperties.mSize * 1.2f;
|
||||
}
|
||||
|
||||
bool GridTileComponent::isSelected() const
|
||||
{
|
||||
// Return whether the tile is selected.
|
||||
return mSelected;
|
||||
}
|
||||
|
||||
void GridTileComponent::reset()
|
||||
{
|
||||
setImage("");
|
||||
}
|
||||
|
||||
void GridTileComponent::setImage(const std::string& path)
|
||||
{
|
||||
mImage->setImage(path);
|
||||
|
@ -169,8 +169,10 @@ void GridTileComponent::setImage(const std::shared_ptr<TextureResource>& texture
|
|||
resize();
|
||||
}
|
||||
|
||||
void GridTileComponent::setSelected(
|
||||
bool selected, bool allowAnimation, Vector3f* pPosition, bool force)
|
||||
void GridTileComponent::setSelected(bool selected,
|
||||
bool allowAnimation,
|
||||
Vector3f* pPosition,
|
||||
bool force)
|
||||
{
|
||||
if (mSelected == selected && !force)
|
||||
return;
|
||||
|
@ -191,15 +193,18 @@ void GridTileComponent::setSelected(
|
|||
|
||||
auto func = [this](float t) {
|
||||
t -= 1; // Cubic ease out.
|
||||
float pct = Math::lerp(0, 1, t*t*t + 1);
|
||||
float pct = Math::lerp(0, 1, t * t * t + 1);
|
||||
this->setSelectedZoom(pct);
|
||||
};
|
||||
|
||||
cancelAnimation(3);
|
||||
setAnimation(new LambdaAnimation(func, 250), 0, [this] {
|
||||
this->setSelectedZoom(1);
|
||||
mAnimPosition = Vector3f(0, 0, 0);
|
||||
}, false, 3);
|
||||
setAnimation(
|
||||
new LambdaAnimation(func, 250), 0,
|
||||
[this] {
|
||||
this->setSelectedZoom(1);
|
||||
mAnimPosition = Vector3f(0, 0, 0);
|
||||
},
|
||||
false, 3);
|
||||
}
|
||||
}
|
||||
else {
|
||||
|
@ -213,15 +218,14 @@ void GridTileComponent::setSelected(
|
|||
this->setSelectedZoom(1);
|
||||
|
||||
auto func = [this](float t) {
|
||||
t -= 1; // Cubic ease out.
|
||||
float pct = Math::lerp(0, 1, t*t*t + 1);
|
||||
t -= 1.0f; // Cubic ease out.
|
||||
float pct = Math::lerp(0, 1, t * t * t + 1.0f);
|
||||
this->setSelectedZoom(1.0f - pct);
|
||||
};
|
||||
|
||||
cancelAnimation(3);
|
||||
setAnimation(new LambdaAnimation(func, 250), 0, [this] {
|
||||
this->setSelectedZoom(0);
|
||||
}, false, 3);
|
||||
setAnimation(
|
||||
new LambdaAnimation(func, 250), 0, [this] { this->setSelectedZoom(0); }, false, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -235,10 +239,7 @@ void GridTileComponent::setSelectedZoom(float percent)
|
|||
resize();
|
||||
}
|
||||
|
||||
void GridTileComponent::setVisible(bool visible)
|
||||
{
|
||||
mVisible = visible;
|
||||
}
|
||||
void GridTileComponent::setVisible(bool visible) { mVisible = visible; }
|
||||
|
||||
void GridTileComponent::resize()
|
||||
{
|
||||
|
@ -278,30 +279,31 @@ void GridTileComponent::calcCurrentProperties()
|
|||
if (mSelectedZoomPercent != 0.0f && mSelectedZoomPercent != 1.0f) {
|
||||
if (mDefaultProperties.mSize != mSelectedProperties.mSize)
|
||||
mCurrentProperties.mSize = mDefaultProperties.mSize * zoomPercentInverse +
|
||||
mSelectedProperties.mSize * mSelectedZoomPercent;
|
||||
mSelectedProperties.mSize * mSelectedZoomPercent;
|
||||
|
||||
if (mDefaultProperties.mPadding != mSelectedProperties.mPadding)
|
||||
mCurrentProperties.mPadding = mDefaultProperties.mPadding * zoomPercentInverse +
|
||||
mSelectedProperties.mPadding * mSelectedZoomPercent;
|
||||
mSelectedProperties.mPadding * mSelectedZoomPercent;
|
||||
|
||||
if (mDefaultProperties.mImageColor != mSelectedProperties.mImageColor)
|
||||
mCurrentProperties.mImageColor = mixColors(mDefaultProperties.mImageColor,
|
||||
mSelectedProperties.mImageColor, mSelectedZoomPercent);
|
||||
mCurrentProperties.mImageColor =
|
||||
mixColors(mDefaultProperties.mImageColor, mSelectedProperties.mImageColor,
|
||||
mSelectedZoomPercent);
|
||||
|
||||
if (mDefaultProperties.mBackgroundCornerSize != mSelectedProperties.mBackgroundCornerSize)
|
||||
mCurrentProperties.mBackgroundCornerSize = mDefaultProperties.mBackgroundCornerSize *
|
||||
zoomPercentInverse + mSelectedProperties.mBackgroundCornerSize *
|
||||
mSelectedZoomPercent;
|
||||
mCurrentProperties.mBackgroundCornerSize =
|
||||
mDefaultProperties.mBackgroundCornerSize * zoomPercentInverse +
|
||||
mSelectedProperties.mBackgroundCornerSize * mSelectedZoomPercent;
|
||||
|
||||
if (mDefaultProperties.mBackgroundCenterColor != mSelectedProperties.mBackgroundCenterColor)
|
||||
mCurrentProperties.mBackgroundCenterColor =
|
||||
mixColors(mDefaultProperties.mBackgroundCenterColor,
|
||||
mSelectedProperties.mBackgroundCenterColor, mSelectedZoomPercent);
|
||||
mixColors(mDefaultProperties.mBackgroundCenterColor,
|
||||
mSelectedProperties.mBackgroundCenterColor, mSelectedZoomPercent);
|
||||
|
||||
if (mDefaultProperties.mBackgroundEdgeColor != mSelectedProperties.mBackgroundEdgeColor)
|
||||
mCurrentProperties.mBackgroundEdgeColor =
|
||||
mixColors(mDefaultProperties.mBackgroundEdgeColor,
|
||||
mSelectedProperties.mBackgroundEdgeColor, mSelectedZoomPercent);
|
||||
mixColors(mDefaultProperties.mBackgroundEdgeColor,
|
||||
mSelectedProperties.mBackgroundEdgeColor, mSelectedZoomPercent);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -28,8 +28,10 @@ public:
|
|||
GridTileComponent(Window* window);
|
||||
|
||||
void render(const Transform4x4f& parentTrans) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties) override;
|
||||
|
||||
// Made this a static function because the ImageGridComponent needs to know the default tile
|
||||
// max size to calculate the grid dimension before it instantiates the GridTileComponents.
|
||||
|
@ -37,12 +39,14 @@ public:
|
|||
Vector2f getSelectedTileSize() const;
|
||||
bool isSelected() const;
|
||||
|
||||
void reset();
|
||||
void reset() { setImage(""); }
|
||||
|
||||
void setImage(const std::string& path);
|
||||
void setImage(const std::shared_ptr<TextureResource>& texture);
|
||||
void setSelected(bool selected, bool allowAnimation = true,
|
||||
Vector3f* pPosition = nullptr, bool force=false);
|
||||
void setSelected(bool selected,
|
||||
bool allowAnimation = true,
|
||||
Vector3f* pPosition = nullptr,
|
||||
bool force = false);
|
||||
void setVisible(bool visible);
|
||||
|
||||
void forceSize(Vector2f size, float selectedZoom);
|
||||
|
|
|
@ -8,20 +8,21 @@
|
|||
|
||||
#include "components/HelpComponent.h"
|
||||
|
||||
#include "Log.h"
|
||||
#include "Settings.h"
|
||||
#include "components/ComponentGrid.h"
|
||||
#include "components/ImageComponent.h"
|
||||
#include "components/TextComponent.h"
|
||||
#include "resources/TextureResource.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Log.h"
|
||||
#include "Settings.h"
|
||||
|
||||
#define ICON_TEXT_SPACING 8 // Space between [icon] and [text] (px).
|
||||
#define ENTRY_SPACING 16 // Space between [text] and next [icon] (px).
|
||||
|
||||
static std::map<std::string, std::string> sIconPathMap {};
|
||||
|
||||
HelpComponent::HelpComponent(Window* window) : GuiComponent(window)
|
||||
HelpComponent::HelpComponent(Window* window)
|
||||
: GuiComponent(window)
|
||||
{
|
||||
assignIcons();
|
||||
}
|
||||
|
@ -113,7 +114,7 @@ void HelpComponent::updateGrid()
|
|||
std::shared_ptr<Font>& font = mStyle.font;
|
||||
|
||||
mGrid = std::make_shared<ComponentGrid>(mWindow,
|
||||
Vector2i(static_cast<int>(mPrompts.size()) * 4, 1));
|
||||
Vector2i(static_cast<int>(mPrompts.size()) * 4, 1));
|
||||
|
||||
// [icon] [spacer1] [text] [spacer2]
|
||||
|
||||
|
@ -130,12 +131,12 @@ void HelpComponent::updateGrid()
|
|||
icon->setResize(0, height);
|
||||
icons.push_back(icon);
|
||||
|
||||
auto lbl = std::make_shared<TextComponent>(mWindow,
|
||||
Utils::String::toUpper(it->second), font, mStyle.textColor);
|
||||
auto lbl = std::make_shared<TextComponent>(mWindow, Utils::String::toUpper(it->second),
|
||||
font, mStyle.textColor);
|
||||
labels.push_back(lbl);
|
||||
|
||||
width += icon->getSize().x() + lbl->getSize().x() +
|
||||
((ICON_TEXT_SPACING + ENTRY_SPACING) * Renderer::getScreenWidthModifier());
|
||||
((ICON_TEXT_SPACING + ENTRY_SPACING) * Renderer::getScreenWidthModifier());
|
||||
}
|
||||
|
||||
mGrid->setSize(width, height);
|
||||
|
@ -143,8 +144,8 @@ void HelpComponent::updateGrid()
|
|||
for (unsigned int i = 0; i < icons.size(); i++) {
|
||||
const int col = i * 4;
|
||||
mGrid->setColWidthPerc(col, icons.at(i)->getSize().x() / width);
|
||||
mGrid->setColWidthPerc(col + 1, (ICON_TEXT_SPACING *
|
||||
Renderer::getScreenWidthModifier()) / width);
|
||||
mGrid->setColWidthPerc(col + 1,
|
||||
(ICON_TEXT_SPACING * Renderer::getScreenWidthModifier()) / width);
|
||||
mGrid->setColWidthPerc(col + 2, labels.at(i)->getSize().x() / width);
|
||||
|
||||
mGrid->setEntry(icons.at(i), Vector2i(col, 0), false, false);
|
||||
|
@ -167,13 +168,13 @@ std::shared_ptr<TextureResource> HelpComponent::getIconTexture(const char* name)
|
|||
return nullptr;
|
||||
}
|
||||
if (!ResourceManager::getInstance()->fileExists(pathLookup->second)) {
|
||||
LOG(LogError) << "Couldn't load help icon \"" << name <<
|
||||
"\" as the file \"" << pathLookup->second << "\" is missing";
|
||||
LOG(LogError) << "Couldn't load help icon \"" << name << "\" as the file \""
|
||||
<< pathLookup->second << "\" is missing";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::shared_ptr<TextureResource> tex =
|
||||
TextureResource::get(pathLookup->second, false, false, false);
|
||||
TextureResource::get(pathLookup->second, false, false, false);
|
||||
mIconCache[std::string(name)] = tex;
|
||||
return tex;
|
||||
}
|
||||
|
|
|
@ -9,17 +9,17 @@
|
|||
#ifndef ES_CORE_COMPONENTS_ILIST_H
|
||||
#define ES_CORE_COMPONENTS_ILIST_H
|
||||
|
||||
#include "Window.h"
|
||||
#include "components/ImageComponent.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Window.h"
|
||||
|
||||
enum CursorState {
|
||||
CURSOR_STOPPED,
|
||||
CURSOR_STOPPED, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
CURSOR_SCROLLING
|
||||
};
|
||||
|
||||
enum ListLoopType {
|
||||
LIST_ALWAYS_LOOP,
|
||||
LIST_ALWAYS_LOOP, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
LIST_PAUSE_AT_END,
|
||||
LIST_NEVER_LOOP
|
||||
};
|
||||
|
@ -35,10 +35,11 @@ struct ScrollTierList {
|
|||
};
|
||||
|
||||
// Default scroll tiers.
|
||||
// clang-format off
|
||||
const ScrollTier QUICK_SCROLL_TIERS[] = {
|
||||
{500, 500},
|
||||
{1200, 114},
|
||||
{0, 16}
|
||||
{ 500, 500 },
|
||||
{ 1200, 114 },
|
||||
{ 0, 16 }
|
||||
};
|
||||
const ScrollTierList LIST_SCROLL_STYLE_QUICK = {
|
||||
3,
|
||||
|
@ -46,17 +47,17 @@ const ScrollTierList LIST_SCROLL_STYLE_QUICK = {
|
|||
};
|
||||
|
||||
const ScrollTier SLOW_SCROLL_TIERS[] = {
|
||||
{500, 500},
|
||||
{0, 200}
|
||||
{ 500, 500 },
|
||||
{ 0, 200 }
|
||||
};
|
||||
|
||||
const ScrollTierList LIST_SCROLL_STYLE_SLOW = {
|
||||
2,
|
||||
SLOW_SCROLL_TIERS
|
||||
};
|
||||
// clang-format on
|
||||
|
||||
template <typename EntryData, typename UserData>
|
||||
class IList : public GuiComponent
|
||||
template <typename EntryData, typename UserData> class IList : public GuiComponent
|
||||
{
|
||||
public:
|
||||
struct Entry {
|
||||
|
@ -82,14 +83,13 @@ protected:
|
|||
Window* mWindow;
|
||||
|
||||
public:
|
||||
IList(
|
||||
Window* window,
|
||||
const ScrollTierList& tierList = LIST_SCROLL_STYLE_QUICK,
|
||||
const ListLoopType& loopType = LIST_PAUSE_AT_END)
|
||||
: GuiComponent(window),
|
||||
mTierList(tierList),
|
||||
mLoopType(loopType),
|
||||
mWindow(window)
|
||||
IList(Window* window,
|
||||
const ScrollTierList& tierList = LIST_SCROLL_STYLE_QUICK,
|
||||
const ListLoopType& loopType = LIST_PAUSE_AT_END)
|
||||
: GuiComponent(window)
|
||||
, mTierList(tierList)
|
||||
, mLoopType(loopType)
|
||||
, mWindow(window)
|
||||
{
|
||||
mCursor = 0;
|
||||
mScrollTier = 0;
|
||||
|
@ -101,15 +101,9 @@ public:
|
|||
mTitleOverlayColor = 0xFFFFFF00;
|
||||
}
|
||||
|
||||
bool isScrolling() const
|
||||
{
|
||||
return (mScrollVelocity != 0 && mScrollTier > 0);
|
||||
}
|
||||
bool isScrolling() const { return (mScrollVelocity != 0 && mScrollTier > 0); }
|
||||
|
||||
int getScrollingVelocity()
|
||||
{
|
||||
return mScrollVelocity;
|
||||
}
|
||||
int getScrollingVelocity() { return mScrollVelocity; }
|
||||
|
||||
void stopScrolling()
|
||||
{
|
||||
|
@ -128,43 +122,43 @@ public:
|
|||
onCursorChanged(CURSOR_STOPPED);
|
||||
}
|
||||
|
||||
inline const std::string& getSelectedName()
|
||||
const std::string& getSelectedName()
|
||||
{
|
||||
assert(size() > 0);
|
||||
return mEntries.at(mCursor).name;
|
||||
}
|
||||
|
||||
inline const UserData& getSelected() const
|
||||
const UserData& getSelected() const
|
||||
{
|
||||
assert(size() > 0);
|
||||
return mEntries.at(mCursor).object;
|
||||
}
|
||||
|
||||
inline const UserData& getNext() const
|
||||
const UserData& getNext() const
|
||||
{
|
||||
// If there is a next entry, then return it, otherwise return the current entry.
|
||||
if (mCursor + 1 < mEntries.size())
|
||||
return mEntries.at(mCursor+1).object;
|
||||
return mEntries.at(mCursor + 1).object;
|
||||
else
|
||||
return mEntries.at(mCursor).object;
|
||||
}
|
||||
|
||||
inline const UserData& getPrevious() const
|
||||
const UserData& getPrevious() const
|
||||
{
|
||||
// If there is a previous entry, then return it, otherwise return the current entry.
|
||||
if (mCursor != 0)
|
||||
return mEntries.at(mCursor-1).object;
|
||||
return mEntries.at(mCursor - 1).object;
|
||||
else
|
||||
return mEntries.at(mCursor).object;
|
||||
}
|
||||
|
||||
inline const UserData& getFirst() const
|
||||
const UserData& getFirst() const
|
||||
{
|
||||
assert(size() > 0);
|
||||
return mEntries.front().object;
|
||||
}
|
||||
|
||||
inline const UserData& getLast() const
|
||||
const UserData& getLast() const
|
||||
{
|
||||
assert(size() > 0);
|
||||
return mEntries.back().object;
|
||||
|
@ -192,10 +186,7 @@ public:
|
|||
}
|
||||
|
||||
// Entry management.
|
||||
void add(const Entry& e)
|
||||
{
|
||||
mEntries.push_back(e);
|
||||
}
|
||||
void add(const Entry& e) { mEntries.push_back(e); }
|
||||
|
||||
bool remove(const UserData& obj)
|
||||
{
|
||||
|
@ -209,10 +200,7 @@ public:
|
|||
return false;
|
||||
}
|
||||
|
||||
inline int size() const
|
||||
{
|
||||
return static_cast<int>(mEntries.size());
|
||||
}
|
||||
int size() const { return static_cast<int>(mEntries.size()); }
|
||||
|
||||
protected:
|
||||
void remove(typename std::vector<Entry>::const_iterator& it)
|
||||
|
@ -241,7 +229,6 @@ protected:
|
|||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool listInput(int velocity) // A velocity of 0 = stop scrolling.
|
||||
{
|
||||
mScrollVelocity = velocity;
|
||||
|
@ -284,8 +271,8 @@ protected:
|
|||
}
|
||||
|
||||
// Should we go to the next scrolling tier?
|
||||
while (mScrollTier < mTierList.count - 1 && mScrollTierAccumulator >=
|
||||
mTierList.tiers[mScrollTier].length) {
|
||||
while (mScrollTier < mTierList.count - 1 &&
|
||||
mScrollTierAccumulator >= mTierList.tiers[mScrollTier].length) {
|
||||
mScrollTierAccumulator -= mTierList.tiers[mScrollTier].length;
|
||||
mScrollTier++;
|
||||
}
|
||||
|
@ -314,11 +301,11 @@ protected:
|
|||
favoritesSorting = Settings::getInstance()->getBool("FavoritesFirst");
|
||||
|
||||
if (favoritesSorting && getSelected()->getFavorite()) {
|
||||
#if defined(_MSC_VER) // MSVC compiler.
|
||||
#if defined(_MSC_VER) // MSVC compiler.
|
||||
titleIndex = Utils::String::wideStringToString(L"\uF005");
|
||||
#else
|
||||
#else
|
||||
titleIndex = "\uF005";
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
else {
|
||||
titleIndex = getSelected()->getName();
|
||||
|
|
|
@ -8,11 +8,11 @@
|
|||
|
||||
#include "components/ImageComponent.h"
|
||||
|
||||
#include "resources/TextureResource.h"
|
||||
#include "utils/CImgUtil.h"
|
||||
#include "Log.h"
|
||||
#include "Settings.h"
|
||||
#include "ThemeData.h"
|
||||
#include "resources/TextureResource.h"
|
||||
#include "utils/CImgUtil.h"
|
||||
|
||||
Vector2i ImageComponent::getTextureSize() const
|
||||
{
|
||||
|
@ -27,34 +27,27 @@ Vector2f ImageComponent::getSize() const
|
|||
return GuiComponent::getSize() * (mBottomRightCrop - mTopLeftCrop);
|
||||
}
|
||||
|
||||
ImageComponent::ImageComponent(
|
||||
Window* window,
|
||||
bool forceLoad,
|
||||
bool dynamic)
|
||||
: GuiComponent(window),
|
||||
mTargetIsMax(false),
|
||||
mTargetIsMin(false),
|
||||
mFlipX(false),
|
||||
mFlipY(false),
|
||||
mTargetSize(0, 0),
|
||||
mColorShift(0xFFFFFFFF),
|
||||
mColorShiftEnd(0xFFFFFFFF),
|
||||
mColorGradientHorizontal(true),
|
||||
mForceLoad(forceLoad),
|
||||
mDynamic(dynamic),
|
||||
mFadeOpacity(0),
|
||||
mFading(false),
|
||||
mRotateByTargetSize(false),
|
||||
mTopLeftCrop(0.0f, 0.0f),
|
||||
mBottomRightCrop(1.0f, 1.0f)
|
||||
ImageComponent::ImageComponent(Window* window, bool forceLoad, bool dynamic)
|
||||
: GuiComponent(window)
|
||||
, mTargetIsMax(false)
|
||||
, mTargetIsMin(false)
|
||||
, mFlipX(false)
|
||||
, mFlipY(false)
|
||||
, mTargetSize(0, 0)
|
||||
, mColorShift(0xFFFFFFFF)
|
||||
, mColorShiftEnd(0xFFFFFFFF)
|
||||
, mColorGradientHorizontal(true)
|
||||
, mForceLoad(forceLoad)
|
||||
, mDynamic(dynamic)
|
||||
, mFadeOpacity(0)
|
||||
, mFading(false)
|
||||
, mRotateByTargetSize(false)
|
||||
, mTopLeftCrop(0.0f, 0.0f)
|
||||
, mBottomRightCrop(1.0f, 1.0f)
|
||||
{
|
||||
updateColors();
|
||||
}
|
||||
|
||||
ImageComponent::~ImageComponent()
|
||||
{
|
||||
}
|
||||
|
||||
void ImageComponent::resize()
|
||||
{
|
||||
if (!mTexture)
|
||||
|
@ -91,8 +84,8 @@ void ImageComponent::resize()
|
|||
mSize[1] = floorf(mSize[1] * resizeScale.y());
|
||||
// For SVG rasterization, always calculate width from rounded height (see comment
|
||||
// above). We need to make sure we're not creating an image larger than max size.
|
||||
mSize[0] = std::min((mSize[1] / textureSize.y()) * textureSize.x(),
|
||||
mTargetSize.x());
|
||||
mSize[0] =
|
||||
std::min((mSize[1] / textureSize.y()) * textureSize.x(), mTargetSize.x());
|
||||
}
|
||||
}
|
||||
else if (mTargetIsMin) {
|
||||
|
@ -118,7 +111,6 @@ void ImageComponent::resize()
|
|||
// above). We need to make sure we're not creating an image smaller than min size.
|
||||
mSize[1] = std::max(floorf(mSize[1]), mTargetSize.y());
|
||||
mSize[0] = std::max((mSize[1] / textureSize.y()) * textureSize.x(), mTargetSize.x());
|
||||
|
||||
}
|
||||
else {
|
||||
// If both components are set, we just stretch.
|
||||
|
@ -147,16 +139,6 @@ void ImageComponent::resize()
|
|||
onSizeChanged();
|
||||
}
|
||||
|
||||
void ImageComponent::onSizeChanged()
|
||||
{
|
||||
updateVertices();
|
||||
}
|
||||
|
||||
void ImageComponent::setDefaultImage(std::string path)
|
||||
{
|
||||
mDefaultPath = path;
|
||||
}
|
||||
|
||||
void ImageComponent::setImage(std::string path, bool tile)
|
||||
{
|
||||
// Always load bundled graphic resources statically, unless mForceLoad has been set.
|
||||
|
@ -218,16 +200,6 @@ void ImageComponent::setMinSize(float width, float height)
|
|||
resize();
|
||||
}
|
||||
|
||||
Vector2f ImageComponent::getRotationSize() const
|
||||
{
|
||||
return mRotateByTargetSize ? mTargetSize : mSize;
|
||||
}
|
||||
|
||||
void ImageComponent::setRotateByTargetSize(bool rotate)
|
||||
{
|
||||
mRotateByTargetSize = rotate;
|
||||
}
|
||||
|
||||
void ImageComponent::cropLeft(float percent)
|
||||
{
|
||||
assert(percent >= 0.0f && percent <= 1.0f);
|
||||
|
@ -262,6 +234,7 @@ void ImageComponent::crop(float left, float top, float right, float bot)
|
|||
|
||||
void ImageComponent::uncrop()
|
||||
{
|
||||
// Remove any applied crop.
|
||||
crop(0, 0, 0, 0);
|
||||
}
|
||||
|
||||
|
@ -375,10 +348,12 @@ void ImageComponent::updateVertices()
|
|||
const float px = mTexture->isTiled() ? mSize.x() / getTextureSize().x() : 1.0f;
|
||||
const float py = mTexture->isTiled() ? mSize.y() / getTextureSize().y() : 1.0f;
|
||||
|
||||
// clang-format off
|
||||
mVertices[0] = { { topLeft.x(), topLeft.y() }, { mTopLeftCrop.x(), py - mTopLeftCrop.y() }, 0 };
|
||||
mVertices[1] = { { topLeft.x(), bottomRight.y() }, { mTopLeftCrop.x(), 1.0f - mBottomRightCrop.y() }, 0 };
|
||||
mVertices[2] = { { bottomRight.x(), topLeft.y() }, { mBottomRightCrop.x() * px, py - mTopLeftCrop.y() }, 0 };
|
||||
mVertices[3] = { { bottomRight.x(), bottomRight.y() }, { mBottomRightCrop.x() * px, 1.0f - mBottomRightCrop.y() }, 0 };
|
||||
// clang-format on
|
||||
|
||||
updateColors();
|
||||
|
||||
|
@ -400,10 +375,11 @@ void ImageComponent::updateVertices()
|
|||
void ImageComponent::updateColors()
|
||||
{
|
||||
const float opacity = (mOpacity * (mFading ? mFadeOpacity / 255.0f : 1.0f)) / 255.0f;
|
||||
const unsigned int color = Renderer::convertRGBAToABGR((mColorShift & 0xFFFFFF00) |
|
||||
static_cast<unsigned char>((mColorShift & 0xFF) * opacity));
|
||||
const unsigned int colorEnd = Renderer::convertRGBAToABGR((mColorShiftEnd & 0xFFFFFF00) |
|
||||
static_cast<unsigned char>((mColorShiftEnd & 0xFF) * opacity));
|
||||
const unsigned int color = Renderer::convertRGBAToABGR(
|
||||
(mColorShift & 0xFFFFFF00) | static_cast<unsigned char>((mColorShift & 0xFF) * opacity));
|
||||
const unsigned int colorEnd =
|
||||
Renderer::convertRGBAToABGR((mColorShiftEnd & 0xFFFFFF00) |
|
||||
static_cast<unsigned char>((mColorShiftEnd & 0xFF) * opacity));
|
||||
|
||||
mVertices[0].col = color;
|
||||
mVertices[1].col = mColorGradientHorizontal ? colorEnd : color;
|
||||
|
@ -423,7 +399,7 @@ void ImageComponent::render(const Transform4x4f& parentTrans)
|
|||
if (Settings::getInstance()->getBool("DebugImage")) {
|
||||
Vector2f targetSizePos = (mTargetSize - mSize) * mOrigin * -1;
|
||||
Renderer::drawRect(targetSizePos.x(), targetSizePos.y(), mTargetSize.x(),
|
||||
mTargetSize.y(), 0xFF000033, 0xFF000033);
|
||||
mTargetSize.y(), 0xFF000033, 0xFF000033);
|
||||
Renderer::drawRect(0.0f, 0.0f, mSize.x(), mSize.y(), 0xFF000033, 0xFF000033);
|
||||
}
|
||||
// An image with zero size would normally indicate a corrupt image file.
|
||||
|
@ -433,12 +409,12 @@ void ImageComponent::render(const Transform4x4f& parentTrans)
|
|||
// texture is bound in this case but we want to handle a fade so it doesn't just
|
||||
// 'jump' in when it finally loads.
|
||||
fadeIn(mTexture->bind());
|
||||
#if defined(USE_OPENGL_21)
|
||||
#if defined(USE_OPENGL_21)
|
||||
if (mSaturation < 1.0) {
|
||||
mVertices[0].shaders = Renderer::SHADER_DESATURATE;
|
||||
mVertices[0].saturation = mSaturation;
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
Renderer::drawTriangleStrips(&mVertices[0], 4, trans);
|
||||
}
|
||||
else {
|
||||
|
@ -448,8 +424,8 @@ void ImageComponent::render(const Transform4x4f& parentTrans)
|
|||
else {
|
||||
std::string textureFilePath = mTexture->getTextureFilePath();
|
||||
if (textureFilePath != "") {
|
||||
LOG(LogError) << "Image texture for file \"" << textureFilePath <<
|
||||
"\" has zero size";
|
||||
LOG(LogError) << "Image texture for file \"" << textureFilePath
|
||||
<< "\" has zero size";
|
||||
}
|
||||
else {
|
||||
LOG(LogError) << "Image texture has zero size";
|
||||
|
@ -492,26 +468,24 @@ void ImageComponent::fadeIn(bool textureLoaded)
|
|||
}
|
||||
}
|
||||
|
||||
bool ImageComponent::hasImage()
|
||||
{
|
||||
return (bool)mTexture;
|
||||
}
|
||||
|
||||
void ImageComponent::applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties)
|
||||
void ImageComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties)
|
||||
{
|
||||
using namespace ThemeFlags;
|
||||
|
||||
GuiComponent::applyTheme(theme, view, element, (properties ^ ThemeFlags::SIZE) |
|
||||
((properties & (ThemeFlags::SIZE | POSITION)) ? ORIGIN : 0));
|
||||
GuiComponent::applyTheme(theme, view, element,
|
||||
(properties ^ ThemeFlags::SIZE) |
|
||||
((properties & (ThemeFlags::SIZE | POSITION)) ? ORIGIN : 0));
|
||||
|
||||
const ThemeData::ThemeElement* elem = theme->getElement(view, element, "image");
|
||||
if (!elem)
|
||||
return;
|
||||
|
||||
Vector2f scale = getParent() ? getParent()->getSize() :
|
||||
Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
|
||||
if (properties & ThemeFlags::SIZE) {
|
||||
if (elem->has("size"))
|
||||
|
@ -536,8 +510,8 @@ void ImageComponent::applyTheme(const std::shared_ptr<ThemeData>& theme, const s
|
|||
if (elem->has("colorEnd"))
|
||||
setColorShiftEnd(elem->get<unsigned int>("colorEnd"));
|
||||
if (elem->has("gradientType"))
|
||||
setColorGradientHorizontal(!(elem->
|
||||
get<std::string>("gradientType").compare("horizontal")));
|
||||
setColorGradientHorizontal(
|
||||
!(elem->get<std::string>("gradientType").compare("horizontal")));
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -9,9 +9,9 @@
|
|||
#ifndef ES_CORE_COMPONENTS_IMAGE_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_IMAGE_COMPONENT_H
|
||||
|
||||
#include "GuiComponent.h"
|
||||
#include "math/Vector2i.h"
|
||||
#include "renderers/Renderer.h"
|
||||
#include "GuiComponent.h"
|
||||
|
||||
class TextureResource;
|
||||
|
||||
|
@ -19,9 +19,9 @@ class ImageComponent : public GuiComponent
|
|||
{
|
||||
public:
|
||||
ImageComponent(Window* window, bool forceLoad = false, bool dynamic = true);
|
||||
virtual ~ImageComponent();
|
||||
virtual ~ImageComponent() {}
|
||||
|
||||
void setDefaultImage(std::string path);
|
||||
void setDefaultImage(std::string path) { mDefaultPath = path; }
|
||||
|
||||
// Loads the image at the given filepath. Will tile if tile is true (retrieves texture
|
||||
// as tiling, creates vertices accordingly).
|
||||
|
@ -31,7 +31,7 @@ public:
|
|||
// Use an already existing texture.
|
||||
void setImage(const std::shared_ptr<TextureResource>& texture);
|
||||
|
||||
void onSizeChanged() override;
|
||||
void onSizeChanged() override { updateVertices(); }
|
||||
|
||||
// Resize the image to fit this size. If one axis is zero, scale that axis to maintain
|
||||
// aspect ratio. If both are non-zero, potentially break the aspect ratio. If both are
|
||||
|
@ -39,18 +39,18 @@ public:
|
|||
// Can be set before or after an image is loaded.
|
||||
// setMaxSize() and setResize() are mutually exclusive.
|
||||
void setResize(float width, float height) override;
|
||||
inline void setResize(const Vector2f& size) { setResize(size.x(), size.y()); }
|
||||
void setResize(const Vector2f& size) { setResize(size.x(), size.y()); }
|
||||
|
||||
// Resize the image to be as large as possible but fit within a box of this size.
|
||||
// Can be set before or after an image is loaded.
|
||||
// Never breaks the aspect ratio. setMaxSize() and setResize() are mutually exclusive.
|
||||
void setMaxSize(float width, float height);
|
||||
inline void setMaxSize(const Vector2f& size) { setMaxSize(size.x(), size.y()); }
|
||||
void setMaxSize(const Vector2f& size) { setMaxSize(size.x(), size.y()); }
|
||||
|
||||
void setMinSize(float width, float height);
|
||||
inline void setMinSize(const Vector2f& size) { setMinSize(size.x(), size.y()); }
|
||||
void setMinSize(const Vector2f& size) { setMinSize(size.x(), size.y()); }
|
||||
|
||||
Vector2f getRotationSize() const override;
|
||||
Vector2f getRotationSize() const override { return mRotateByTargetSize ? mTargetSize : mSize; }
|
||||
|
||||
// Applied AFTER image positioning and sizing.
|
||||
// cropTop(0.2) will crop 20% of the top of the image.
|
||||
|
@ -70,7 +70,7 @@ public:
|
|||
void setColorShiftEnd(unsigned int color);
|
||||
void setColorGradientHorizontal(bool horizontal);
|
||||
|
||||
unsigned int getColorShift() const override { return mColorShift; };
|
||||
unsigned int getColorShift() const override { return mColorShift; }
|
||||
|
||||
void setOpacity(unsigned char opacity) override;
|
||||
void setSaturation(float saturation) override;
|
||||
|
@ -79,7 +79,7 @@ public:
|
|||
void setFlipY(bool flip); // Mirror on the Y axis.
|
||||
|
||||
// Flag indicating if rotation should be based on target size vs. actual size.
|
||||
void setRotateByTargetSize(bool rotate);
|
||||
void setRotateByTargetSize(bool rotate) { mRotateByTargetSize = rotate; }
|
||||
|
||||
// Returns the size of the current texture, or (0, 0) if none is loaded.
|
||||
// May be different than drawn size (use getSize() for that).
|
||||
|
@ -87,17 +87,18 @@ public:
|
|||
|
||||
Vector2f getSize() const override;
|
||||
|
||||
bool hasImage();
|
||||
bool hasImage() { return static_cast<bool>(mTexture); }
|
||||
std::shared_ptr<TextureResource> getTexture() { return mTexture; }
|
||||
|
||||
void render(const Transform4x4f& parentTrans) override;
|
||||
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties) override;
|
||||
|
||||
virtual std::vector<HelpPrompt> getHelpPrompts() override;
|
||||
|
||||
std::shared_ptr<TextureResource> getTexture() { return mTexture; };
|
||||
|
||||
private:
|
||||
Vector2f mTargetSize;
|
||||
|
||||
|
|
|
@ -9,21 +9,21 @@
|
|||
#ifndef ES_CORE_COMPONENTS_IMAGE_GRID_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_IMAGE_GRID_COMPONENT_H
|
||||
|
||||
#include "GridTileComponent.h"
|
||||
#include "Log.h"
|
||||
#include "animations/LambdaAnimation.h"
|
||||
#include "components/IList.h"
|
||||
#include "resources/TextureResource.h"
|
||||
#include "GridTileComponent.h"
|
||||
#include "Log.h"
|
||||
|
||||
#define EXTRAITEMS 2
|
||||
|
||||
enum ScrollDirection {
|
||||
SCROLL_VERTICALLY,
|
||||
SCROLL_VERTICALLY, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
SCROLL_HORIZONTALLY
|
||||
};
|
||||
|
||||
enum ImageSource {
|
||||
THUMBNAIL,
|
||||
THUMBNAIL, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
IMAGE,
|
||||
MIXIMAGE,
|
||||
SCREENSHOT,
|
||||
|
@ -36,8 +36,7 @@ struct ImageGridData {
|
|||
std::string texturePath;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
class ImageGridComponent : public IList<ImageGridData, T>
|
||||
template <typename T> class ImageGridComponent : public IList<ImageGridData, T>
|
||||
{
|
||||
protected:
|
||||
using IList<ImageGridData, T>::mEntries;
|
||||
|
@ -49,9 +48,6 @@ protected:
|
|||
using IList<ImageGridData, T>::mSize;
|
||||
using IList<ImageGridData, T>::mCursor;
|
||||
using IList<ImageGridData, T>::mWindow;
|
||||
// The following change is required for compilation with Clang.
|
||||
// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2070
|
||||
// using IList<ImageGridData, T>::Entry;
|
||||
using IList<ImageGridData, T>::IList;
|
||||
|
||||
public:
|
||||
|
@ -66,14 +62,18 @@ public:
|
|||
bool input(InputConfig* config, Input input) override;
|
||||
void update(int deltaTime) override;
|
||||
void render(const Transform4x4f& parentTrans) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties) override;
|
||||
|
||||
void onSizeChanged() override;
|
||||
inline void setCursorChangedCallback(const std::function<void(CursorState state)>& func)
|
||||
{ mCursorChangedCallback = func; }
|
||||
void setCursorChangedCallback(const std::function<void(CursorState state)>& func)
|
||||
{
|
||||
mCursorChangedCallback = func;
|
||||
}
|
||||
|
||||
ImageSource getImageSource() { return mImageSource; };
|
||||
ImageSource getImageSource() { return mImageSource; }
|
||||
|
||||
protected:
|
||||
virtual void onCursorChanged(const CursorState& state) override;
|
||||
|
@ -81,13 +81,14 @@ protected:
|
|||
private:
|
||||
// Tiles.
|
||||
void buildTiles();
|
||||
void updateTiles(bool ascending = true, bool allowAnimation = true,
|
||||
bool updateSelectedState = true);
|
||||
void updateTiles(bool ascending = true,
|
||||
bool allowAnimation = true,
|
||||
bool updateSelectedState = true);
|
||||
void updateTileAtPos(int tilePos, int imgPos, bool allowAnimation, bool updateSelectedState);
|
||||
void calcGridDimension();
|
||||
bool isScrollLoop();
|
||||
|
||||
bool isVertical() { return mScrollDirection == SCROLL_VERTICALLY; };
|
||||
bool isVertical() { return mScrollDirection == SCROLL_VERTICALLY; }
|
||||
|
||||
// Images and entries.
|
||||
bool mEntriesDirty;
|
||||
|
@ -121,11 +122,12 @@ private:
|
|||
std::function<void(CursorState state)> mCursorChangedCallback;
|
||||
};
|
||||
|
||||
template<typename T>
|
||||
ImageGridComponent<T>::ImageGridComponent(Window* window) : IList<ImageGridData, T>(window)
|
||||
template <typename T>
|
||||
ImageGridComponent<T>::ImageGridComponent(Window* window)
|
||||
: IList<ImageGridData, T>(window)
|
||||
{
|
||||
Vector2f screen = Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
|
||||
mCamera = 0.0;
|
||||
mCameraDirection = 1.0;
|
||||
|
@ -152,7 +154,7 @@ ImageGridComponent<T>::ImageGridComponent(Window* window) : IList<ImageGridData,
|
|||
mImageSource = THUMBNAIL;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
template <typename T>
|
||||
void ImageGridComponent<T>::add(const std::string& name, const std::string& imagePath, const T& obj)
|
||||
{
|
||||
typename IList<ImageGridData, T>::Entry entry;
|
||||
|
@ -164,8 +166,7 @@ void ImageGridComponent<T>::add(const std::string& name, const std::string& imag
|
|||
mEntriesDirty = true;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
bool ImageGridComponent<T>::input(InputConfig* config, Input input)
|
||||
template <typename T> bool ImageGridComponent<T>::input(InputConfig* config, Input input)
|
||||
{
|
||||
if (input.value != 0) {
|
||||
int idx = isVertical() ? 0 : 1;
|
||||
|
@ -190,15 +191,15 @@ bool ImageGridComponent<T>::input(InputConfig* config, Input input)
|
|||
}
|
||||
else {
|
||||
if (config->isMappedLike("up", input) || config->isMappedLike("down", input) ||
|
||||
config->isMappedLike("left", input) || config->isMappedLike("right", input))
|
||||
config->isMappedLike("left", input) || config->isMappedLike("right", input)) {
|
||||
stopScrolling();
|
||||
}
|
||||
}
|
||||
|
||||
return GuiComponent::input(config, input);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void ImageGridComponent<T>::update(int deltaTime)
|
||||
template <typename T> void ImageGridComponent<T>::update(int deltaTime)
|
||||
{
|
||||
GuiComponent::update(deltaTime);
|
||||
listUpdate(deltaTime);
|
||||
|
@ -207,16 +208,15 @@ void ImageGridComponent<T>::update(int deltaTime)
|
|||
(*it)->update(deltaTime);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void ImageGridComponent<T>::render(const Transform4x4f& parentTrans)
|
||||
template <typename T> void ImageGridComponent<T>::render(const Transform4x4f& parentTrans)
|
||||
{
|
||||
Transform4x4f trans = getTransform() * parentTrans;
|
||||
Transform4x4f tileTrans = trans;
|
||||
|
||||
float offsetX = isVertical() ? 0.0f : mCamera * mCameraDirection *
|
||||
(mTileSize.x() + mMargin.x());
|
||||
float offsetY = isVertical() ? mCamera * mCameraDirection *
|
||||
(mTileSize.y() + mMargin.y()) : 0.0f;
|
||||
float offsetX =
|
||||
isVertical() ? 0.0f : mCamera * mCameraDirection * (mTileSize.x() + mMargin.x());
|
||||
float offsetY =
|
||||
isVertical() ? mCamera * mCameraDirection * (mTileSize.y() + mMargin.y()) : 0.0f;
|
||||
|
||||
tileTrans.translate(Vector3f(offsetX, offsetY, 0.0));
|
||||
|
||||
|
@ -230,9 +230,9 @@ void ImageGridComponent<T>::render(const Transform4x4f& parentTrans)
|
|||
float scaleY = trans.r1().y();
|
||||
|
||||
Vector2i pos(static_cast<int>(std::round(trans.translation()[0])),
|
||||
static_cast<int>(std::round(trans.translation()[1])));
|
||||
static_cast<int>(std::round(trans.translation()[1])));
|
||||
Vector2i size(static_cast<int>(std::round(mSize.x() * scaleX)),
|
||||
static_cast<int>(std::round(mSize.y() * scaleY)));
|
||||
static_cast<int>(std::round(mSize.y() * scaleY)));
|
||||
|
||||
Renderer::pushClipRect(pos, size);
|
||||
|
||||
|
@ -258,9 +258,11 @@ void ImageGridComponent<T>::render(const Transform4x4f& parentTrans)
|
|||
GuiComponent::renderChildren(trans);
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
template <typename T>
|
||||
void ImageGridComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& element, unsigned int properties)
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties)
|
||||
{
|
||||
// Apply theme to GuiComponent but not the size property, which will be applied
|
||||
// at the end of this function.
|
||||
|
@ -270,7 +272,7 @@ void ImageGridComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
mTheme = theme;
|
||||
|
||||
Vector2f screen = Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
|
||||
const ThemeData::ThemeElement* elem = theme->getElement(view, element, "imagegrid");
|
||||
if (elem) {
|
||||
|
@ -279,7 +281,7 @@ void ImageGridComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
|
||||
if (elem->has("padding"))
|
||||
mPadding = elem->get<Vector4f>("padding") *
|
||||
Vector4f(screen.x(), screen.y(), screen.x(), screen.y());
|
||||
Vector4f(screen.x(), screen.y(), screen.x(), screen.y());
|
||||
|
||||
if (elem->has("autoLayout"))
|
||||
mAutoLayout = elem->get<Vector2f>("autoLayout");
|
||||
|
@ -309,8 +311,8 @@ void ImageGridComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
}
|
||||
|
||||
if (elem->has("scrollDirection"))
|
||||
mScrollDirection = (ScrollDirection)(elem->
|
||||
get<std::string>("scrollDirection") == "horizontal");
|
||||
mScrollDirection =
|
||||
(ScrollDirection)(elem->get<std::string>("scrollDirection") == "horizontal");
|
||||
|
||||
if (elem->has("centerSelection")) {
|
||||
mCenterSelection = (elem->get<bool>("centerSelection"));
|
||||
|
@ -367,9 +369,8 @@ void ImageGridComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
// grid dimension, and then (re)build the tiles.
|
||||
elem = theme->getElement(view, "default", "gridtile");
|
||||
|
||||
mTileSize = elem && elem->has("size") ?
|
||||
elem->get<Vector2f>("size") * screen :
|
||||
GridTileComponent::getDefaultTileSize();
|
||||
mTileSize = elem && elem->has("size") ? elem->get<Vector2f>("size") * screen :
|
||||
GridTileComponent::getDefaultTileSize();
|
||||
|
||||
// Apply size property which will trigger a call to onSizeChanged() which will build the tiles.
|
||||
GuiComponent::applyTheme(theme, view, element, ThemeFlags::SIZE);
|
||||
|
@ -379,15 +380,13 @@ void ImageGridComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
buildTiles();
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void ImageGridComponent<T>::onSizeChanged()
|
||||
template <typename T> void ImageGridComponent<T>::onSizeChanged()
|
||||
{
|
||||
buildTiles();
|
||||
updateTiles();
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void ImageGridComponent<T>::onCursorChanged(const CursorState& state)
|
||||
template <typename T> void ImageGridComponent<T>::onCursorChanged(const CursorState& state)
|
||||
{
|
||||
if (mLastCursor == mCursor) {
|
||||
if (state == CURSOR_STOPPED && mCursorChangedCallback)
|
||||
|
@ -470,7 +469,7 @@ void ImageGridComponent<T>::onCursorChanged(const CursorState& state)
|
|||
mStartPosition = lastScroll * dimOpposite;
|
||||
}
|
||||
else if ((maxCentralCol != centralCol && col == firstVisibleCol + maxCentralCol) ||
|
||||
col == firstVisibleCol + centralCol) {
|
||||
col == firstVisibleCol + centralCol) {
|
||||
if (col == firstVisibleCol + maxCentralCol)
|
||||
mStartPosition = (col - maxCentralCol) * dimOpposite;
|
||||
else
|
||||
|
@ -507,23 +506,23 @@ void ImageGridComponent<T>::onCursorChanged(const CursorState& state)
|
|||
if (!moveCamera)
|
||||
return;
|
||||
|
||||
t -= 1; // Cubic ease out.
|
||||
float pct = Math::lerp(0, 1, t*t*t + 1);
|
||||
t -= 1.0f; // Cubic ease out.
|
||||
float pct = Math::lerp(0, 1.0f, t * t * t + 1.0f);
|
||||
t = startPos * (1.0f - pct) + endPos * pct;
|
||||
mCamera = t;
|
||||
};
|
||||
|
||||
reinterpret_cast<GuiComponent*>(this)->setAnimation(
|
||||
new LambdaAnimation(func, 250), 0, [this, direction] {
|
||||
mCamera = 0;
|
||||
updateTiles(direction, false);
|
||||
}, false, 2);
|
||||
new LambdaAnimation(func, 250), 0,
|
||||
[this, direction] {
|
||||
mCamera = 0;
|
||||
updateTiles(direction, false);
|
||||
},
|
||||
false, 2);
|
||||
}
|
||||
|
||||
|
||||
// Create and position tiles (mTiles).
|
||||
template<typename T>
|
||||
void ImageGridComponent<T>::buildTiles()
|
||||
template <typename T> void ImageGridComponent<T>::buildTiles()
|
||||
{
|
||||
mStartPosition = 0;
|
||||
mTiles.clear();
|
||||
|
@ -531,18 +530,20 @@ void ImageGridComponent<T>::buildTiles()
|
|||
calcGridDimension();
|
||||
|
||||
if (mCenterSelection) {
|
||||
int dimScrollable = (isVertical() ? mGridDimension.y() :
|
||||
mGridDimension.x()) - 2 * EXTRAITEMS;
|
||||
int dimScrollable =
|
||||
(isVertical() ? mGridDimension.y() : mGridDimension.x()) - 2 * EXTRAITEMS;
|
||||
mStartPosition -= static_cast<int>(floorf(dimScrollable / 2.0f));
|
||||
}
|
||||
|
||||
Vector2f tileDistance = mTileSize + mMargin;
|
||||
|
||||
if (mAutoLayout.x() != 0.0f && mAutoLayout.y() != 0.0f) {
|
||||
auto x = (mSize.x() - (mMargin.x() * (mAutoLayout.x() - 1.0f)) - mPadding.x() -
|
||||
mPadding.z()) / static_cast<int>(mAutoLayout.x());
|
||||
auto y = (mSize.y() - (mMargin.y() * (mAutoLayout.y() - 1.0f)) - mPadding.y() -
|
||||
mPadding.w()) / static_cast<int>(mAutoLayout.y());
|
||||
auto x =
|
||||
(mSize.x() - (mMargin.x() * (mAutoLayout.x() - 1.0f)) - mPadding.x() - mPadding.z()) /
|
||||
static_cast<int>(mAutoLayout.x());
|
||||
auto y =
|
||||
(mSize.y() - (mMargin.y() * (mAutoLayout.y() - 1.0f)) - mPadding.y() - mPadding.w()) /
|
||||
static_cast<int>(mAutoLayout.y());
|
||||
|
||||
mTileSize = Vector2f(x, y);
|
||||
tileDistance = mTileSize + mMargin;
|
||||
|
@ -566,8 +567,8 @@ void ImageGridComponent<T>::buildTiles()
|
|||
X = vert ? x : y - EXTRAITEMS;
|
||||
Y = vert ? y - EXTRAITEMS : x;
|
||||
|
||||
tile->setPosition(X * tileDistance.x() + startPosition.x(), Y *
|
||||
tileDistance.y() + startPosition.y());
|
||||
tile->setPosition(X * tileDistance.x() + startPosition.x(),
|
||||
Y * tileDistance.y() + startPosition.y());
|
||||
tile->setOrigin(0.5f, 0.5f);
|
||||
tile->setImage("");
|
||||
|
||||
|
@ -582,9 +583,10 @@ void ImageGridComponent<T>::buildTiles()
|
|||
}
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void ImageGridComponent<T>::updateTiles(bool ascending, bool allowAnimation,
|
||||
bool updateSelectedState)
|
||||
template <typename T>
|
||||
void ImageGridComponent<T>::updateTiles(bool ascending,
|
||||
bool allowAnimation,
|
||||
bool updateSelectedState)
|
||||
{
|
||||
if (!mTiles.size())
|
||||
return;
|
||||
|
@ -631,9 +633,11 @@ void ImageGridComponent<T>::updateTiles(bool ascending, bool allowAnimation,
|
|||
mLastCursor = mCursor;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
void ImageGridComponent<T>::updateTileAtPos(int tilePos, int imgPos,
|
||||
bool allowAnimation, bool updateSelectedState)
|
||||
template <typename T>
|
||||
void ImageGridComponent<T>::updateTileAtPos(int tilePos,
|
||||
int imgPos,
|
||||
bool allowAnimation,
|
||||
bool updateSelectedState)
|
||||
{
|
||||
std::shared_ptr<GridTileComponent> tile = mTiles.at(tilePos);
|
||||
|
||||
|
@ -647,7 +651,7 @@ void ImageGridComponent<T>::updateTileAtPos(int tilePos, int imgPos,
|
|||
// If we have more tiles than we can display on screen, hide them.
|
||||
// Same for tiles out of the buffer.
|
||||
if (imgPos < 0 || imgPos >= size() || tilePos < 0 ||
|
||||
tilePos >= static_cast<int>(mTiles.size())) {
|
||||
tilePos >= static_cast<int>(mTiles.size())) {
|
||||
if (updateSelectedState)
|
||||
tile->setSelected(false, allowAnimation);
|
||||
tile->reset();
|
||||
|
@ -680,14 +684,12 @@ void ImageGridComponent<T>::updateTileAtPos(int tilePos, int imgPos,
|
|||
tile->setSelected(imgPos == mCursor, allowAnimation);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate how many tiles of size mTileSize we can fit in a grid of size mSize using
|
||||
// a margin size of mMargin.
|
||||
template<typename T>
|
||||
void ImageGridComponent<T>::calcGridDimension()
|
||||
template <typename T> void ImageGridComponent<T>::calcGridDimension()
|
||||
{
|
||||
// grid_size = columns * tile_size + (columns - 1) * margin
|
||||
// <=> columns = (grid_size + margin) / (tile_size + margin)
|
||||
|
@ -700,7 +702,7 @@ void ImageGridComponent<T>::calcGridDimension()
|
|||
|
||||
// Ceil y dim so we can display partial last row.
|
||||
mGridDimension = Vector2i(static_cast<const int>(gridDimension.x()),
|
||||
static_cast<const int>(ceilf(gridDimension.y())));
|
||||
static_cast<const int>(ceilf(gridDimension.y())));
|
||||
|
||||
// Grid dimension validation.
|
||||
if (mGridDimension.x() < 1) {
|
||||
|
@ -717,13 +719,13 @@ void ImageGridComponent<T>::calcGridDimension()
|
|||
mGridDimension.x() += 2 * EXTRAITEMS;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
bool ImageGridComponent<T>::isScrollLoop() {
|
||||
template <typename T> bool ImageGridComponent<T>::isScrollLoop()
|
||||
{
|
||||
if (!mScrollLoop)
|
||||
return false;
|
||||
if (isVertical())
|
||||
return (mGridDimension.x() * (mGridDimension.y() - 2 * EXTRAITEMS)) <= mEntries.size();
|
||||
return (mGridDimension.y() * (mGridDimension.x() - 2 * EXTRAITEMS)) <= mEntries.size();
|
||||
};
|
||||
}
|
||||
|
||||
#endif // ES_CORE_COMPONENTS_IMAGE_GRID_COMPONENT_H
|
||||
|
|
|
@ -8,22 +8,21 @@
|
|||
|
||||
#include "components/MenuComponent.h"
|
||||
|
||||
#include "components/ButtonComponent.h"
|
||||
#include "Settings.h"
|
||||
#include "components/ButtonComponent.h"
|
||||
|
||||
#define BUTTON_GRID_VERT_PADDING 32.0f
|
||||
#define BUTTON_GRID_HORIZ_PADDING 10.0f
|
||||
|
||||
#define TITLE_HEIGHT (mTitle->getFont()->getLetterHeight() + TITLE_VERT_PADDING)
|
||||
|
||||
MenuComponent::MenuComponent(
|
||||
Window* window,
|
||||
std::string title,
|
||||
const std::shared_ptr<Font>& titleFont)
|
||||
: GuiComponent(window),
|
||||
mBackground(window),
|
||||
mGrid(window, Vector2i(1, 3)),
|
||||
mNeedsSaving(false)
|
||||
MenuComponent::MenuComponent(Window* window,
|
||||
std::string title,
|
||||
const std::shared_ptr<Font>& titleFont)
|
||||
: GuiComponent(window)
|
||||
, mBackground(window)
|
||||
, mGrid(window, Vector2i(1, 3))
|
||||
, mNeedsSaving(false)
|
||||
{
|
||||
addChild(&mBackground);
|
||||
addChild(&mGrid);
|
||||
|
@ -49,6 +48,7 @@ MenuComponent::MenuComponent(
|
|||
|
||||
MenuComponent::~MenuComponent()
|
||||
{
|
||||
// Save when destroyed.
|
||||
save();
|
||||
}
|
||||
|
||||
|
@ -75,15 +75,15 @@ void MenuComponent::setTitle(std::string title, const std::shared_ptr<Font>& fon
|
|||
float MenuComponent::getButtonGridHeight() const
|
||||
{
|
||||
return (mButtonGrid ? mButtonGrid->getSize().y() :
|
||||
Font::get(FONT_SIZE_MEDIUM)->getHeight() +
|
||||
(BUTTON_GRID_VERT_PADDING * Renderer::getScreenHeightModifier()));
|
||||
Font::get(FONT_SIZE_MEDIUM)->getHeight() +
|
||||
(BUTTON_GRID_VERT_PADDING * Renderer::getScreenHeightModifier()));
|
||||
}
|
||||
|
||||
void MenuComponent::updateSize()
|
||||
{
|
||||
const float maxHeight = Renderer::getScreenHeight() * 0.80f;
|
||||
float height = TITLE_HEIGHT + mList->getTotalRowHeight() + getButtonGridHeight() +
|
||||
(2.0f * Renderer::getScreenHeightModifier());
|
||||
(2.0f * Renderer::getScreenHeightModifier());
|
||||
if (height > maxHeight) {
|
||||
height = TITLE_HEIGHT + getButtonGridHeight();
|
||||
int i = 0;
|
||||
|
@ -98,14 +98,15 @@ void MenuComponent::updateSize()
|
|||
}
|
||||
}
|
||||
|
||||
float width = static_cast<float>(std::min(static_cast<int>(Renderer::getScreenHeight() *
|
||||
1.05f), static_cast<int>(Renderer::getScreenWidth() * 0.90f)));
|
||||
float width =
|
||||
static_cast<float>(std::min(static_cast<int>(Renderer::getScreenHeight() * 1.05f),
|
||||
static_cast<int>(Renderer::getScreenWidth() * 0.90f)));
|
||||
setSize(width, height);
|
||||
}
|
||||
|
||||
void MenuComponent::onSizeChanged()
|
||||
{
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f));
|
||||
|
||||
// Update grid row/column sizes.
|
||||
mGrid.setRowHeightPerc(0, TITLE_HEIGHT / mSize.y());
|
||||
|
@ -115,10 +116,11 @@ void MenuComponent::onSizeChanged()
|
|||
}
|
||||
|
||||
void MenuComponent::addButton(const std::string& name,
|
||||
const std::string& helpText, const std::function<void()>& callback)
|
||||
const std::string& helpText,
|
||||
const std::function<void()>& callback)
|
||||
{
|
||||
mButtons.push_back(std::make_shared<ButtonComponent>
|
||||
(mWindow,Utils::String::toUpper(name), helpText, callback));
|
||||
mButtons.push_back(std::make_shared<ButtonComponent>(mWindow, Utils::String::toUpper(name),
|
||||
helpText, callback));
|
||||
updateGrid();
|
||||
updateSize();
|
||||
}
|
||||
|
@ -136,30 +138,28 @@ void MenuComponent::updateGrid()
|
|||
}
|
||||
}
|
||||
|
||||
std::vector<HelpPrompt> MenuComponent::getHelpPrompts()
|
||||
std::shared_ptr<ComponentGrid> makeButtonGrid(
|
||||
Window* window, const std::vector<std::shared_ptr<ButtonComponent>>& buttons)
|
||||
{
|
||||
return mGrid.getHelpPrompts();
|
||||
}
|
||||
|
||||
std::shared_ptr<ComponentGrid> makeButtonGrid(Window* window,
|
||||
const std::vector<std::shared_ptr<ButtonComponent>>& buttons)
|
||||
{
|
||||
std::shared_ptr<ComponentGrid> buttonGrid = std::make_shared<ComponentGrid>
|
||||
(window, Vector2i(static_cast<int>(buttons.size()), 2));
|
||||
std::shared_ptr<ComponentGrid> buttonGrid =
|
||||
std::make_shared<ComponentGrid>(window, Vector2i(static_cast<int>(buttons.size()), 2));
|
||||
|
||||
// Initialize to padding.
|
||||
float buttonGridWidth = BUTTON_GRID_HORIZ_PADDING *
|
||||
Renderer::getScreenWidthModifier() * buttons.size();
|
||||
float buttonGridWidth =
|
||||
BUTTON_GRID_HORIZ_PADDING * Renderer::getScreenWidthModifier() * buttons.size();
|
||||
for (int i = 0; i < static_cast<int>(buttons.size()); i++) {
|
||||
buttonGrid->setEntry(buttons.at(i), Vector2i(i, 0), true, false);
|
||||
buttonGridWidth += buttons.at(i)->getSize().x();
|
||||
}
|
||||
for (unsigned int i = 0; i < buttons.size(); i++)
|
||||
buttonGrid->setColWidthPerc(i, (buttons.at(i)->getSize().x() +
|
||||
BUTTON_GRID_HORIZ_PADDING * Renderer::getScreenWidthModifier()) / buttonGridWidth);
|
||||
buttonGrid->setColWidthPerc(
|
||||
i, (buttons.at(i)->getSize().x() +
|
||||
BUTTON_GRID_HORIZ_PADDING * Renderer::getScreenWidthModifier()) /
|
||||
buttonGridWidth);
|
||||
|
||||
buttonGrid->setSize(buttonGridWidth, buttons.at(0)->getSize().y() +
|
||||
(BUTTON_GRID_VERT_PADDING * Renderer::getScreenHeightModifier()) + 2);
|
||||
buttonGrid->setSize(buttonGridWidth,
|
||||
buttons.at(0)->getSize().y() +
|
||||
(BUTTON_GRID_VERT_PADDING * Renderer::getScreenHeightModifier()) + 2);
|
||||
// Spacer row to deal with dropshadow to make buttons look centered.
|
||||
buttonGrid->setRowHeightPerc(1, 2 / buttonGrid->getSize().y());
|
||||
|
||||
|
|
|
@ -17,20 +17,21 @@
|
|||
|
||||
#include <cmath>
|
||||
|
||||
#define TITLE_VERT_PADDING (Renderer::getScreenHeight() * 0.0637f)
|
||||
|
||||
class ButtonComponent;
|
||||
class ImageComponent;
|
||||
|
||||
std::shared_ptr<ComponentGrid> makeButtonGrid(Window* window,
|
||||
const std::vector<std::shared_ptr<ButtonComponent>>& buttons);
|
||||
std::shared_ptr<ComponentGrid> makeButtonGrid(
|
||||
Window* window, const std::vector<std::shared_ptr<ButtonComponent>>& buttons);
|
||||
std::shared_ptr<ImageComponent> makeArrow(Window* window);
|
||||
|
||||
#define TITLE_VERT_PADDING (Renderer::getScreenHeight() * 0.0637f)
|
||||
|
||||
class MenuComponent : public GuiComponent
|
||||
{
|
||||
public:
|
||||
MenuComponent(Window* window, std::string title,
|
||||
const std::shared_ptr<Font>& titleFont = Font::get(FONT_SIZE_LARGE));
|
||||
MenuComponent(Window* window,
|
||||
std::string title,
|
||||
const std::shared_ptr<Font>& titleFont = Font::get(FONT_SIZE_LARGE));
|
||||
virtual ~MenuComponent();
|
||||
|
||||
void save();
|
||||
|
@ -38,31 +39,42 @@ public:
|
|||
|
||||
void setNeedsSaving() { mNeedsSaving = true; }
|
||||
|
||||
inline void addRow(const ComponentListRow& row, bool setCursorHere = false)
|
||||
{ mList->addRow(row, setCursorHere); updateSize(); }
|
||||
void addRow(const ComponentListRow& row, bool setCursorHere = false)
|
||||
{
|
||||
mList->addRow(row, setCursorHere);
|
||||
updateSize();
|
||||
}
|
||||
|
||||
inline void addWithLabel(const std::string& label, const std::shared_ptr<GuiComponent>& comp,
|
||||
bool setCursorHere = false, bool invert_when_selected = true)
|
||||
void addWithLabel(const std::string& label,
|
||||
const std::shared_ptr<GuiComponent>& comp,
|
||||
bool setCursorHere = false,
|
||||
bool invert_when_selected = true)
|
||||
{
|
||||
ComponentListRow row;
|
||||
row.addElement(std::make_shared<TextComponent>(mWindow,
|
||||
Utils::String::toUpper(label), Font::get(FONT_SIZE_MEDIUM), 0x777777FF), true);
|
||||
row.addElement(std::make_shared<TextComponent>(mWindow, Utils::String::toUpper(label),
|
||||
Font::get(FONT_SIZE_MEDIUM), 0x777777FF),
|
||||
true);
|
||||
row.addElement(comp, false, invert_when_selected);
|
||||
addRow(row, setCursorHere);
|
||||
}
|
||||
|
||||
inline void addSaveFunc(const std::function<void()>& func) { mSaveFuncs.push_back(func); }
|
||||
void addSaveFunc(const std::function<void()>& func) { mSaveFuncs.push_back(func); }
|
||||
|
||||
void addButton(const std::string& label, const std::string& helpText,
|
||||
const std::function<void()>& callback);
|
||||
void addButton(const std::string& label,
|
||||
const std::string& helpText,
|
||||
const std::function<void()>& callback);
|
||||
|
||||
void setTitle(std::string title, const std::shared_ptr<Font>& font);
|
||||
|
||||
void setCursorToFirstListEntry() { mList->moveCursor(-mList->getCursorId()); }
|
||||
inline void setCursorToList() { mGrid.setCursorTo(mList); }
|
||||
inline void setCursorToButtons() { assert(mButtonGrid); mGrid.setCursorTo(mButtonGrid); }
|
||||
void setCursorToList() { mGrid.setCursorTo(mList); }
|
||||
void setCursorToButtons()
|
||||
{
|
||||
assert(mButtonGrid);
|
||||
mGrid.setCursorTo(mButtonGrid);
|
||||
}
|
||||
|
||||
virtual std::vector<HelpPrompt> getHelpPrompts() override;
|
||||
virtual std::vector<HelpPrompt> getHelpPrompts() override { return mGrid.getHelpPrompts(); }
|
||||
|
||||
private:
|
||||
void updateSize();
|
||||
|
|
|
@ -8,21 +8,20 @@
|
|||
|
||||
#include "components/NinePatchComponent.h"
|
||||
|
||||
#include "resources/TextureResource.h"
|
||||
#include "Log.h"
|
||||
#include "ThemeData.h"
|
||||
#include "resources/TextureResource.h"
|
||||
|
||||
NinePatchComponent::NinePatchComponent(
|
||||
Window* window,
|
||||
const std::string& path,
|
||||
unsigned int edgeColor,
|
||||
unsigned int centerColor)
|
||||
: GuiComponent(window),
|
||||
mCornerSize(16.0f, 16.0f),
|
||||
mEdgeColor(edgeColor),
|
||||
mCenterColor(centerColor),
|
||||
mPath(path),
|
||||
mVertices(nullptr)
|
||||
NinePatchComponent::NinePatchComponent(Window* window,
|
||||
const std::string& path,
|
||||
unsigned int edgeColor,
|
||||
unsigned int centerColor)
|
||||
: GuiComponent(window)
|
||||
, mCornerSize(16.0f, 16.0f)
|
||||
, mEdgeColor(edgeColor)
|
||||
, mCenterColor(centerColor)
|
||||
, mPath(path)
|
||||
, mVertices(nullptr)
|
||||
{
|
||||
if (!mPath.empty())
|
||||
buildVertices();
|
||||
|
@ -42,8 +41,8 @@ void NinePatchComponent::updateColors()
|
|||
for (int i = 0; i < 6 * 9; i++)
|
||||
mVertices[i].col = edgeColor;
|
||||
|
||||
for (int i = 6*4; i < 6; i++)
|
||||
mVertices[(6*4)+i].col = centerColor;
|
||||
for (int i = 6 * 4; i < 6; i++)
|
||||
mVertices[(6 * 4) + i].col = centerColor;
|
||||
}
|
||||
|
||||
void NinePatchComponent::buildVertices()
|
||||
|
@ -72,19 +71,21 @@ void NinePatchComponent::buildVertices()
|
|||
mVertices = new Renderer::Vertex[6 * 9];
|
||||
|
||||
texSize = Vector2f(static_cast<float>(mTexture->getSize().x()),
|
||||
static_cast<float>(mTexture->getSize().y()));
|
||||
static_cast<float>(mTexture->getSize().y()));
|
||||
|
||||
const float imgSizeX[3] = { mCornerSize.x(), mSize.x() - mCornerSize.x() * 2, mCornerSize.x()};
|
||||
const float imgSizeY[3] = { mCornerSize.y(), mSize.y() - mCornerSize.y() * 2, mCornerSize.y()};
|
||||
const float imgPosX[3] = { 0, imgSizeX[0], imgSizeX[0] + imgSizeX[1]};
|
||||
const float imgPosY[3] = { 0, imgSizeY[0], imgSizeY[0] + imgSizeY[1]};
|
||||
// clang-format off
|
||||
const float imgSizeX[3] = { mCornerSize.x(), mSize.x() - mCornerSize.x() * 2.0f, mCornerSize.x() };
|
||||
const float imgSizeY[3] = { mCornerSize.y(), mSize.y() - mCornerSize.y() * 2.0f, mCornerSize.y() };
|
||||
const float imgPosX[3] = { 0, imgSizeX[0], imgSizeX[0] + imgSizeX[1] };
|
||||
const float imgPosY[3] = { 0, imgSizeY[0], imgSizeY[0] + imgSizeY[1] };
|
||||
|
||||
// The "1 +" in posY and "-" in sizeY is to deal with texture coordinates having a bottom
|
||||
// left corner origin vs. verticies having a top left origin.
|
||||
const float texSizeX[3] = { mCornerSize.x() / texSize.x(), (texSize.x() - mCornerSize.x() * 2) / texSize.x(), mCornerSize.x() / texSize.x() };
|
||||
const float texSizeY[3] = { -mCornerSize.y() / texSize.y(), -(texSize.y() - mCornerSize.y() * 2) / texSize.y(), -mCornerSize.y() / texSize.y() };
|
||||
const float texPosX[3] = { 0, texSizeX[0], texSizeX[0] + texSizeX[1] };
|
||||
const float texPosY[3] = { 1, 1 + texSizeY[0], 1 + texSizeY[0] + texSizeY[1] };
|
||||
const float texSizeX[3] = { mCornerSize.x() / texSize.x(), (texSize.x() - mCornerSize.x() * 2.0f) / texSize.x(), mCornerSize.x() / texSize.x() };
|
||||
const float texSizeY[3] = { -mCornerSize.y() / texSize.y(), -(texSize.y() - mCornerSize.y() * 2.0f) / texSize.y(), -mCornerSize.y() / texSize.y() };
|
||||
const float texPosX[3] = { 0.0f, texSizeX[0], texSizeX[0] + texSizeX[1] };
|
||||
const float texPosY[3] = { 1.0f, 1.0f + texSizeY[0], 1.0f + texSizeY[0] + texSizeY[1] };
|
||||
// clang-format on
|
||||
|
||||
int v = 0;
|
||||
|
||||
|
@ -96,10 +97,12 @@ void NinePatchComponent::buildVertices()
|
|||
const Vector2f texPos = Vector2f(texPosX[sliceX], texPosY[sliceY]);
|
||||
const Vector2f texSize = Vector2f(texSizeX[sliceX], texSizeY[sliceY]);
|
||||
|
||||
// clang-format off
|
||||
mVertices[v + 1] = { { imgPos.x() , imgPos.y() }, { texPos.x(), texPos.y() }, 0 };
|
||||
mVertices[v + 2] = { { imgPos.x() , imgPos.y() + imgSize.y() }, { texPos.x(), texPos.y() + texSize.y() }, 0 };
|
||||
mVertices[v + 3] = { { imgPos.x() + imgSize.x(), imgPos.y() }, { texPos.x() + texSize.x(), texPos.y() }, 0 };
|
||||
mVertices[v + 4] = { { imgPos.x() + imgSize.x(), imgPos.y() + imgSize.y() }, { texPos.x() + texSize.x(), texPos.y() + texSize.y() }, 0 };
|
||||
// clang-format on
|
||||
|
||||
// Round vertices.
|
||||
for (int i = 1; i < 5; i++)
|
||||
|
@ -141,10 +144,7 @@ void NinePatchComponent::render(const Transform4x4f& parentTrans)
|
|||
renderChildren(trans);
|
||||
}
|
||||
|
||||
void NinePatchComponent::onSizeChanged()
|
||||
{
|
||||
buildVertices();
|
||||
}
|
||||
void NinePatchComponent::onSizeChanged() { buildVertices(); }
|
||||
|
||||
void NinePatchComponent::fitTo(Vector2f size, Vector3f position, Vector2f padding)
|
||||
{
|
||||
|
@ -176,7 +176,9 @@ void NinePatchComponent::setCenterColor(unsigned int centerColor)
|
|||
}
|
||||
|
||||
void NinePatchComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& element, unsigned int properties)
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties)
|
||||
{
|
||||
GuiComponent::applyTheme(theme, view, element, properties);
|
||||
|
||||
|
|
|
@ -9,8 +9,8 @@
|
|||
#ifndef ES_CORE_COMPONENTS_NINE_PATCH_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_NINE_PATCH_COMPONENT_H
|
||||
|
||||
#include "renderers/Renderer.h"
|
||||
#include "GuiComponent.h"
|
||||
#include "renderers/Renderer.h"
|
||||
|
||||
class TextureResource;
|
||||
|
||||
|
@ -29,16 +29,19 @@ class TextureResource;
|
|||
class NinePatchComponent : public GuiComponent
|
||||
{
|
||||
public:
|
||||
NinePatchComponent(Window* window, const std::string& path = "",
|
||||
unsigned int edgeColor = 0xFFFFFFFF, unsigned int centerColor = 0xFFFFFFFF);
|
||||
NinePatchComponent(Window* window,
|
||||
const std::string& path = "",
|
||||
unsigned int edgeColor = 0xFFFFFFFF,
|
||||
unsigned int centerColor = 0xFFFFFFFF);
|
||||
virtual ~NinePatchComponent();
|
||||
|
||||
void render(const Transform4x4f& parentTrans) override;
|
||||
|
||||
void onSizeChanged() override;
|
||||
|
||||
void fitTo(Vector2f size, Vector3f position = Vector3f::Zero(),
|
||||
Vector2f padding = Vector2f::Zero());
|
||||
void fitTo(Vector2f size,
|
||||
Vector3f position = Vector3f::Zero(),
|
||||
Vector2f padding = Vector2f::Zero());
|
||||
|
||||
void setImagePath(const std::string& path);
|
||||
// Apply a color shift to the "edge" parts of the ninepatch.
|
||||
|
@ -46,15 +49,17 @@ public:
|
|||
// Apply a color shift to the "center" part of the ninepatch.
|
||||
void setCenterColor(unsigned int centerColor);
|
||||
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties) override;
|
||||
|
||||
inline const Vector2f& getCornerSize() const { return mCornerSize; };
|
||||
inline void setCornerSize(const Vector2f& size)
|
||||
const Vector2f& getCornerSize() const { return mCornerSize; }
|
||||
void setCornerSize(const Vector2f& size)
|
||||
{
|
||||
mCornerSize = size;
|
||||
buildVertices();
|
||||
};
|
||||
}
|
||||
|
||||
private:
|
||||
void buildVertices();
|
||||
|
|
|
@ -21,28 +21,20 @@
|
|||
|
||||
// Used to display a list of options.
|
||||
// Can select one or multiple options.
|
||||
|
||||
// if !multiSelect
|
||||
// * <- curEntry ->
|
||||
// Always
|
||||
// * press a -> open full list.
|
||||
|
||||
template<typename T>
|
||||
class OptionListComponent : public GuiComponent
|
||||
template <typename T> class OptionListComponent : public GuiComponent
|
||||
{
|
||||
public:
|
||||
OptionListComponent(
|
||||
Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& name,
|
||||
bool multiSelect = false)
|
||||
: GuiComponent(window),
|
||||
mHelpStyle(helpstyle),
|
||||
mMultiSelect(multiSelect),
|
||||
mName(name),
|
||||
mText(window),
|
||||
mLeftArrow(window),
|
||||
mRightArrow(window)
|
||||
OptionListComponent(Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& name,
|
||||
bool multiSelect = false)
|
||||
: GuiComponent(window)
|
||||
, mHelpStyle(helpstyle)
|
||||
, mMultiSelect(multiSelect)
|
||||
, mName(name)
|
||||
, mText(window)
|
||||
, mLeftArrow(window)
|
||||
, mRightArrow(window)
|
||||
{
|
||||
auto font = Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT);
|
||||
mText.setFont(font);
|
||||
|
@ -79,15 +71,15 @@ public:
|
|||
LOG(LogWarning) << "OptionListComponent too narrow";
|
||||
}
|
||||
|
||||
mText.setSize(mSize.x() - mLeftArrow.getSize().x() -
|
||||
mRightArrow.getSize().x(), mText.getFont()->getHeight());
|
||||
mText.setSize(mSize.x() - mLeftArrow.getSize().x() - mRightArrow.getSize().x(),
|
||||
mText.getFont()->getHeight());
|
||||
|
||||
// Position.
|
||||
mLeftArrow.setPosition(0, (mSize.y() - mLeftArrow.getSize().y()) / 2);
|
||||
mText.setPosition(mLeftArrow.getPosition().x() + mLeftArrow.getSize().x(),
|
||||
(mSize.y() - mText.getSize().y()) / 2);
|
||||
(mSize.y() - mText.getSize().y()) / 2);
|
||||
mRightArrow.setPosition(mText.getPosition().x() + mText.getSize().x(),
|
||||
(mSize.y() - mRightArrow.getSize().y()) / 2);
|
||||
(mSize.y() - mRightArrow.getSize().y()) / 2);
|
||||
}
|
||||
|
||||
bool input(InputConfig* config, Input input) override
|
||||
|
@ -115,7 +107,6 @@ public:
|
|||
mEntries.at(next).selected = true;
|
||||
onSelectedChanged();
|
||||
return true;
|
||||
|
||||
}
|
||||
else if (config->isMappedLike("right", input)) {
|
||||
// Ignore input if the component has been disabled.
|
||||
|
@ -205,7 +196,7 @@ public:
|
|||
void sortEntriesByName()
|
||||
{
|
||||
std::sort(std::begin(mEntries), std::end(mEntries),
|
||||
[](OptionListData a, OptionListData b) { return a.name < b.name; });
|
||||
[](OptionListData a, OptionListData b) { return a.name < b.name; });
|
||||
}
|
||||
|
||||
unsigned int getSelectedId()
|
||||
|
@ -217,11 +208,11 @@ public:
|
|||
}
|
||||
|
||||
LOG(LogWarning) << "OptionListComponent::getSelectedId() - "
|
||||
"no selected element found, defaulting to 0";
|
||||
"no selected element found, defaulting to 0";
|
||||
return 0;
|
||||
}
|
||||
|
||||
HelpStyle getHelpStyle() override { return mHelpStyle; };
|
||||
HelpStyle getHelpStyle() override { return mHelpStyle; }
|
||||
|
||||
private:
|
||||
struct OptionListData {
|
||||
|
@ -232,10 +223,7 @@ private:
|
|||
|
||||
HelpStyle mHelpStyle;
|
||||
|
||||
void open()
|
||||
{
|
||||
mWindow->pushGui(new OptionListPopup(mWindow, getHelpStyle(), this, mName));
|
||||
}
|
||||
void open() { mWindow->pushGui(new OptionListPopup(mWindow, getHelpStyle(), this, mName)); }
|
||||
|
||||
void onSelectedChanged()
|
||||
{
|
||||
|
@ -246,7 +234,8 @@ private:
|
|||
mText.setText(ss.str());
|
||||
mText.setSize(0, mText.getSize().y());
|
||||
setSize(mText.getSize().x() + mRightArrow.getSize().x() +
|
||||
24 * Renderer::getScreenWidthModifier(), mText.getSize().y());
|
||||
24 * Renderer::getScreenWidthModifier(),
|
||||
mText.getSize().y());
|
||||
if (mParent) // Hack since there's no "on child size changed" callback.
|
||||
mParent->onSizeChanged();
|
||||
}
|
||||
|
@ -257,8 +246,9 @@ private:
|
|||
mText.setText(Utils::String::toUpper(it->name));
|
||||
mText.setSize(0, mText.getSize().y());
|
||||
setSize(mText.getSize().x() + mLeftArrow.getSize().x() +
|
||||
mRightArrow.getSize().x() +
|
||||
24 * Renderer::getScreenWidthModifier(), mText.getSize().y());
|
||||
mRightArrow.getSize().x() +
|
||||
24.0f * Renderer::getScreenWidthModifier(),
|
||||
mText.getSize().y());
|
||||
if (mParent) // Hack since there's no "on child size changed" callback.
|
||||
mParent->onSizeChanged();
|
||||
break;
|
||||
|
@ -290,15 +280,14 @@ private:
|
|||
class OptionListPopup : public GuiComponent
|
||||
{
|
||||
public:
|
||||
OptionListPopup(
|
||||
Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
OptionListComponent<T>* parent,
|
||||
const std::string& title)
|
||||
: GuiComponent(window),
|
||||
mHelpStyle(helpstyle),
|
||||
mMenu(window, title.c_str()),
|
||||
mParent(parent)
|
||||
OptionListPopup(Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
OptionListComponent<T>* parent,
|
||||
const std::string& title)
|
||||
: GuiComponent(window)
|
||||
, mHelpStyle(helpstyle)
|
||||
, mMenu(window, title.c_str())
|
||||
, mParent(parent)
|
||||
{
|
||||
auto font = Font::get(FONT_SIZE_MEDIUM);
|
||||
ComponentListRow row;
|
||||
|
@ -308,8 +297,9 @@ private:
|
|||
|
||||
for (auto it = mParent->mEntries.begin(); it != mParent->mEntries.end(); it++) {
|
||||
row.elements.clear();
|
||||
row.addElement(std::make_shared<TextComponent>
|
||||
(mWindow, Utils::String::toUpper(it->name), font, 0x777777FF), true);
|
||||
row.addElement(std::make_shared<TextComponent>(
|
||||
mWindow, Utils::String::toUpper(it->name), font, 0x777777FF),
|
||||
true);
|
||||
|
||||
OptionListData& e = *it;
|
||||
|
||||
|
@ -367,7 +357,7 @@ private:
|
|||
}
|
||||
|
||||
mMenu.setPosition((Renderer::getScreenWidth() - mMenu.getSize().x()) / 2.0f,
|
||||
Renderer::getScreenHeight() * 0.13f);
|
||||
Renderer::getScreenHeight() * 0.13f);
|
||||
addChild(&mMenu);
|
||||
}
|
||||
|
||||
|
@ -389,7 +379,7 @@ private:
|
|||
return prompts;
|
||||
}
|
||||
|
||||
HelpStyle getHelpStyle() override { return mHelpStyle; };
|
||||
HelpStyle getHelpStyle() override { return mHelpStyle; }
|
||||
|
||||
private:
|
||||
MenuComponent mMenu;
|
||||
|
|
|
@ -9,25 +9,23 @@
|
|||
|
||||
#include "components/RatingComponent.h"
|
||||
|
||||
#include "resources/TextureResource.h"
|
||||
#include "Settings.h"
|
||||
#include "ThemeData.h"
|
||||
#include "resources/TextureResource.h"
|
||||
|
||||
RatingComponent::RatingComponent(
|
||||
Window* window,
|
||||
bool colorizeChanges)
|
||||
: GuiComponent(window),
|
||||
mColorShift(DEFAULT_COLORSHIFT),
|
||||
mColorShiftEnd(DEFAULT_COLORSHIFT),
|
||||
mUnfilledColor(DEFAULT_COLORSHIFT),
|
||||
mColorizeChanges(colorizeChanges),
|
||||
mColorOriginalValue(DEFAULT_COLORSHIFT),
|
||||
mColorChangedValue(DEFAULT_COLORSHIFT)
|
||||
RatingComponent::RatingComponent(Window* window, bool colorizeChanges)
|
||||
: GuiComponent(window)
|
||||
, mColorShift(DEFAULT_COLORSHIFT)
|
||||
, mColorShiftEnd(DEFAULT_COLORSHIFT)
|
||||
, mUnfilledColor(DEFAULT_COLORSHIFT)
|
||||
, mColorizeChanges(colorizeChanges)
|
||||
, mColorOriginalValue(DEFAULT_COLORSHIFT)
|
||||
, mColorChangedValue(DEFAULT_COLORSHIFT)
|
||||
{
|
||||
mFilledTexture = TextureResource::get(":/graphics/star_filled.svg", true);
|
||||
mUnfilledTexture = TextureResource::get(":/graphics/star_unfilled.svg", true);
|
||||
mValue = 0.5f;
|
||||
mSize = Vector2f(64 * NUM_RATING_STARS, 64);
|
||||
mSize = Vector2f(64.0f * NUM_RATING_STARS, 64.0f);
|
||||
updateVertices();
|
||||
updateColors();
|
||||
}
|
||||
|
@ -39,13 +37,13 @@ void RatingComponent::setValue(const std::string& value)
|
|||
}
|
||||
else {
|
||||
// Round up to the closest .1 value, i.e. to the closest half-icon.
|
||||
mValue = ceilf(stof(value) / 0.1f) / 10;
|
||||
mOriginalValue = static_cast<int>(mValue * 10);
|
||||
mValue = ceilf(stof(value) / 0.1f) / 10.0f;
|
||||
mOriginalValue = static_cast<int>(mValue * 10.0f);
|
||||
|
||||
// If the argument to colorize the rating icons has been passed, set the
|
||||
// color shift accordingly.
|
||||
if (mColorizeChanges) {
|
||||
if (static_cast<int>(mValue * 10) == mOriginalValue)
|
||||
if (static_cast<int>(mValue * 10.0f) == mOriginalValue)
|
||||
setColorShift(mColorOriginalValue);
|
||||
else
|
||||
setColorShift(mColorChangedValue);
|
||||
|
@ -122,6 +120,7 @@ void RatingComponent::updateVertices()
|
|||
const float fw = getSize().y() * numStars;
|
||||
const unsigned int color = Renderer::convertRGBAToABGR(mColorShift);
|
||||
|
||||
// clang-format off
|
||||
mVertices[0] = { { 0.0f, 0.0f }, { 0.0f, 1.0f }, color };
|
||||
mVertices[1] = { { 0.0f, h }, { 0.0f, 0.0f }, color };
|
||||
mVertices[2] = { { w, 0.0f }, { mValue * numStars, 1.0f }, color };
|
||||
|
@ -131,13 +130,7 @@ void RatingComponent::updateVertices()
|
|||
mVertices[5] = { { 0.0f, h }, { 0.0f, 0.0f }, color };
|
||||
mVertices[6] = { { fw, 0.0f }, { numStars, 1.0f }, color };
|
||||
mVertices[7] = { { fw, h }, { numStars, 0.0f }, color };
|
||||
|
||||
|
||||
// Disabled this code as it caused subtle but strange rendering errors
|
||||
// where the icons changed size slightly when changing rating scores.
|
||||
// // Round vertices.
|
||||
// for (int i = 0; i < 8; i++)
|
||||
// mVertices[i].pos.round();
|
||||
// clang-format on
|
||||
}
|
||||
|
||||
void RatingComponent::updateColors()
|
||||
|
@ -159,8 +152,8 @@ void RatingComponent::render(const Transform4x4f& parentTrans)
|
|||
|
||||
if (mOpacity > 0) {
|
||||
if (Settings::getInstance()->getBool("DebugImage")) {
|
||||
Renderer::drawRect(0.0f, 0.0f, mSize.y() * NUM_RATING_STARS,
|
||||
mSize.y(), 0xFF000033, 0xFF000033);
|
||||
Renderer::drawRect(0.0f, 0.0f, mSize.y() * NUM_RATING_STARS, mSize.y(), 0xFF000033,
|
||||
0xFF000033);
|
||||
}
|
||||
|
||||
if (mUnfilledTexture->bind()) {
|
||||
|
@ -189,14 +182,14 @@ void RatingComponent::render(const Transform4x4f& parentTrans)
|
|||
bool RatingComponent::input(InputConfig* config, Input input)
|
||||
{
|
||||
if (config->isMappedTo("a", input) && input.value != 0) {
|
||||
mValue += (1.f/2) / NUM_RATING_STARS;
|
||||
mValue += (1.0f / 2.0f) / NUM_RATING_STARS;
|
||||
if (mValue > 1.05f)
|
||||
mValue = 0.0f;
|
||||
|
||||
// If the argument to colorize the rating icons has been passed,
|
||||
// set the color shift accordingly.
|
||||
if (mColorizeChanges) {
|
||||
if (static_cast<int>(mValue * 10) == mOriginalValue)
|
||||
if (static_cast<int>(mValue * 10.0f) == mOriginalValue)
|
||||
setColorShift(mColorOriginalValue);
|
||||
else
|
||||
setColorShift(mColorChangedValue);
|
||||
|
@ -208,7 +201,9 @@ bool RatingComponent::input(InputConfig* config, Input input)
|
|||
}
|
||||
|
||||
void RatingComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& element, unsigned int properties)
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties)
|
||||
{
|
||||
using namespace ThemeFlags;
|
||||
|
||||
|
|
|
@ -10,18 +10,13 @@
|
|||
#ifndef ES_APP_COMPONENTS_RATING_COMPONENT_H
|
||||
#define ES_APP_COMPONENTS_RATING_COMPONENT_H
|
||||
|
||||
#include "renderers/Renderer.h"
|
||||
#include "GuiComponent.h"
|
||||
#include "renderers/Renderer.h"
|
||||
|
||||
class TextureResource;
|
||||
|
||||
#define NUM_RATING_STARS 5
|
||||
|
||||
// Used to visually display/edit some sort of "score" - e.g. 5/10, 3/5, etc.
|
||||
// setSize(x, y) works a little differently than you might expect:
|
||||
// * (0, y != 0) - x will be automatically calculated (5*y).
|
||||
// * (x != 0, 0) - y will be automatically calculated (x/5).
|
||||
// * (x != 0, y != 0) - you better be sure x = y*5.
|
||||
class RatingComponent : public GuiComponent
|
||||
{
|
||||
public:
|
||||
|
@ -40,13 +35,15 @@ public:
|
|||
|
||||
// Multiply all pixels in the image by this color when rendering.
|
||||
void setColorShift(unsigned int color) override;
|
||||
unsigned int getColorShift() const override { return mColorShift; };
|
||||
unsigned int getColorShift() const override { return mColorShift; }
|
||||
|
||||
void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; };
|
||||
void setChangedColor(unsigned int color) override { mColorChangedValue = color; };
|
||||
void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; }
|
||||
void setChangedColor(unsigned int color) override { mColorChangedValue = color; }
|
||||
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties) override;
|
||||
|
||||
virtual std::vector<HelpPrompt> getHelpPrompts() override;
|
||||
|
||||
|
|
|
@ -9,22 +9,21 @@
|
|||
|
||||
#include "components/ScrollableContainer.h"
|
||||
|
||||
#include "Window.h"
|
||||
#include "animations/LambdaAnimation.h"
|
||||
#include "math/Vector2i.h"
|
||||
#include "renderers/Renderer.h"
|
||||
#include "resources/Font.h"
|
||||
#include "Window.h"
|
||||
|
||||
ScrollableContainer::ScrollableContainer(
|
||||
Window* window)
|
||||
: GuiComponent(window),
|
||||
mAutoScrollDelay(0),
|
||||
mAutoScrollSpeed(0),
|
||||
mAutoScrollAccumulator(0),
|
||||
mScrollPos(0, 0),
|
||||
mScrollDir(0, 0),
|
||||
mAutoScrollResetAccumulator(0),
|
||||
mFontSize(0.0f)
|
||||
ScrollableContainer::ScrollableContainer(Window* window)
|
||||
: GuiComponent(window)
|
||||
, mAutoScrollDelay(0)
|
||||
, mAutoScrollSpeed(0)
|
||||
, mAutoScrollAccumulator(0)
|
||||
, mScrollPos(0, 0)
|
||||
, mScrollDir(0, 0)
|
||||
, mAutoScrollResetAccumulator(0)
|
||||
, mFontSize(0.0f)
|
||||
{
|
||||
// Set the modifier to get equivalent scrolling speed regardless of screen resolution.
|
||||
mResolutionModifier = Renderer::getScreenHeightModifier();
|
||||
|
@ -33,7 +32,8 @@ ScrollableContainer::ScrollableContainer(
|
|||
// For narrower aspect ratios than 16:9 there is a need to set an additional compensation
|
||||
// to get somehow consistent scrolling speeds.
|
||||
float aspectCompensation = static_cast<float>(Renderer::getScreenHeight()) /
|
||||
static_cast<float>(Renderer::getScreenWidth()) - 0.5625f;
|
||||
static_cast<float>(Renderer::getScreenWidth()) -
|
||||
0.5625f;
|
||||
if (aspectCompensation > 0)
|
||||
mResolutionModifier += aspectCompensation * 4.0f;
|
||||
|
||||
|
@ -42,24 +42,14 @@ ScrollableContainer::ScrollableContainer(
|
|||
mAutoScrollSpeedConstant = AUTO_SCROLL_SPEED;
|
||||
}
|
||||
|
||||
Vector2f ScrollableContainer::getScrollPos() const
|
||||
{
|
||||
return mScrollPos;
|
||||
}
|
||||
|
||||
void ScrollableContainer::setScrollPos(const Vector2f& pos)
|
||||
{
|
||||
mScrollPos = pos;
|
||||
}
|
||||
|
||||
void ScrollableContainer::setAutoScroll(bool autoScroll)
|
||||
{
|
||||
if (autoScroll) {
|
||||
mScrollDir = Vector2f(0, 1);
|
||||
mAutoScrollDelay = static_cast<int>(mAutoScrollDelayConstant);
|
||||
mAutoScrollSpeed = mAutoScrollSpeedConstant;
|
||||
mAutoScrollSpeed = static_cast<int>(static_cast<float>(mAutoScrollSpeedConstant) /
|
||||
mResolutionModifier);
|
||||
mAutoScrollSpeed =
|
||||
static_cast<int>(static_cast<float>(mAutoScrollSpeedConstant) / mResolutionModifier);
|
||||
reset();
|
||||
}
|
||||
else {
|
||||
|
@ -71,7 +61,8 @@ void ScrollableContainer::setAutoScroll(bool autoScroll)
|
|||
}
|
||||
|
||||
void ScrollableContainer::setScrollParameters(float autoScrollDelayConstant,
|
||||
float autoScrollResetDelayConstant, int autoScrollSpeedConstant)
|
||||
float autoScrollResetDelayConstant,
|
||||
int autoScrollSpeedConstant)
|
||||
{
|
||||
mAutoScrollResetDelayConstant = autoScrollResetDelayConstant;
|
||||
mAutoScrollDelayConstant = autoScrollDelayConstant;
|
||||
|
@ -90,7 +81,7 @@ void ScrollableContainer::update(int deltaTime)
|
|||
{
|
||||
// Don't scroll if the media viewer or screensaver is active or if text scrolling is disabled;
|
||||
if (mWindow->isMediaViewerActive() || mWindow->isScreensaverActive() ||
|
||||
!mWindow->getAllowTextScrolling()) {
|
||||
!mWindow->getAllowTextScrolling()) {
|
||||
if (mScrollPos != 0 && !mWindow->isLaunchScreenDisplayed())
|
||||
reset();
|
||||
return;
|
||||
|
@ -105,8 +96,8 @@ void ScrollableContainer::update(int deltaTime)
|
|||
|
||||
// Also adjust the scrolling speed based on the size of the font.
|
||||
float fontSizeModifier = mSmallFontSize / mFontSize;
|
||||
adjustedAutoScrollSpeed = static_cast<int>(adjustedAutoScrollSpeed *
|
||||
fontSizeModifier * fontSizeModifier);
|
||||
adjustedAutoScrollSpeed =
|
||||
static_cast<int>(adjustedAutoScrollSpeed * fontSizeModifier * fontSizeModifier);
|
||||
|
||||
if (adjustedAutoScrollSpeed < 0)
|
||||
adjustedAutoScrollSpeed = 1;
|
||||
|
@ -165,11 +156,11 @@ void ScrollableContainer::render(const Transform4x4f& parentTrans)
|
|||
Transform4x4f trans = parentTrans * getTransform();
|
||||
|
||||
Vector2i clipPos(static_cast<int>(trans.translation().x()),
|
||||
static_cast<int>(trans.translation().y()));
|
||||
static_cast<int>(trans.translation().y()));
|
||||
|
||||
Vector3f dimScaled = trans * Vector3f(mSize.x(), mSize.y(), 0);
|
||||
Vector2i clipDim(static_cast<int>((dimScaled.x()) - trans.translation().x()),
|
||||
static_cast<int>((dimScaled.y()) - trans.translation().y()));
|
||||
static_cast<int>((dimScaled.y()) - trans.translation().y()));
|
||||
|
||||
Renderer::pushClipRect(clipPos, clipDim);
|
||||
|
||||
|
|
|
@ -24,11 +24,13 @@ class ScrollableContainer : public GuiComponent
|
|||
public:
|
||||
ScrollableContainer(Window* window);
|
||||
|
||||
Vector2f getScrollPos() const;
|
||||
void setScrollPos(const Vector2f& pos);
|
||||
Vector2f getScrollPos() const { return mScrollPos; }
|
||||
void setScrollPos(const Vector2f& pos) { mScrollPos = pos; }
|
||||
|
||||
void setAutoScroll(bool autoScroll);
|
||||
void setScrollParameters(float autoScrollDelayConstant, float autoScrollResetDelayConstant,
|
||||
int autoScrollSpeedConstant) override;
|
||||
void setScrollParameters(float autoScrollDelayConstant,
|
||||
float autoScrollResetDelayConstant,
|
||||
int autoScrollSpeedConstant) override;
|
||||
void reset();
|
||||
|
||||
void update(int deltaTime) override;
|
||||
|
|
|
@ -14,23 +14,19 @@
|
|||
#define MOVE_REPEAT_RATE 40
|
||||
|
||||
SliderComponent::SliderComponent(
|
||||
Window* window,
|
||||
float min,
|
||||
float max,
|
||||
float increment,
|
||||
const std::string& suffix)
|
||||
: GuiComponent(window),
|
||||
mMin(min),
|
||||
mMax(max),
|
||||
mSingleIncrement(increment),
|
||||
mMoveRate(0),
|
||||
mKnob(window),
|
||||
mSuffix(suffix)
|
||||
Window* window, float min, float max, float increment, const std::string& suffix)
|
||||
: GuiComponent(window)
|
||||
, mMin(min)
|
||||
, mMax(max)
|
||||
, mSingleIncrement(increment)
|
||||
, mMoveRate(0)
|
||||
, mKnob(window)
|
||||
, mSuffix(suffix)
|
||||
{
|
||||
assert((min - max) != 0);
|
||||
|
||||
// Some sane default value.
|
||||
mValue = (max + min) / 2;
|
||||
mValue = (max + min) / 2.0f;
|
||||
|
||||
mKnob.setOrigin(0.5f, 0.5f);
|
||||
mKnob.setImage(":/graphics/slider_knob.svg");
|
||||
|
@ -87,14 +83,15 @@ void SliderComponent::render(const Transform4x4f& parentTrans)
|
|||
if (mValueCache)
|
||||
mFont->renderTextCache(mValueCache.get());
|
||||
|
||||
float width = mSize.x() - mKnob.getSize().x() -
|
||||
(mValueCache ? mValueCache->metrics.size.x() +
|
||||
(4 * Renderer::getScreenWidthModifier()) : 0);
|
||||
float width =
|
||||
mSize.x() - mKnob.getSize().x() -
|
||||
(mValueCache ? mValueCache->metrics.size.x() + (4.0f * Renderer::getScreenWidthModifier()) :
|
||||
0);
|
||||
|
||||
// Render line.
|
||||
const float lineWidth = 2 * Renderer::getScreenHeightModifier();;
|
||||
Renderer::drawRect(mKnob.getSize().x() / 2, mSize.y() / 2 -
|
||||
lineWidth / 2, width, lineWidth, 0x777777FF, 0x777777FF);
|
||||
const float lineWidth = 2.0f * Renderer::getScreenHeightModifier();
|
||||
Renderer::drawRect(mKnob.getSize().x() / 2.0f, mSize.y() / 2.0f - lineWidth / 2.0f, width,
|
||||
lineWidth, 0x777777FF, 0x777777FF);
|
||||
|
||||
// Render knob.
|
||||
mKnob.render(trans);
|
||||
|
@ -113,10 +110,7 @@ void SliderComponent::setValue(float value)
|
|||
onValueChanged();
|
||||
}
|
||||
|
||||
float SliderComponent::getValue()
|
||||
{
|
||||
return mValue;
|
||||
}
|
||||
float SliderComponent::getValue() { return mValue; }
|
||||
|
||||
void SliderComponent::onSizeChanged()
|
||||
{
|
||||
|
@ -146,18 +140,20 @@ void SliderComponent::onValueChanged()
|
|||
const std::string max = ss.str();
|
||||
|
||||
Vector2f textSize = mFont->sizeText(max);
|
||||
mValueCache = std::shared_ptr<TextCache>(mFont->buildTextCache(val, mSize.x() -
|
||||
textSize.x(), (mSize.y() - textSize.y()) / 2, 0x777777FF));
|
||||
mValueCache = std::shared_ptr<TextCache>(mFont->buildTextCache(
|
||||
val, mSize.x() - textSize.x(), (mSize.y() - textSize.y()) / 2.0f, 0x777777FF));
|
||||
mValueCache->metrics.size[0] = textSize.x(); // Fudge the width.
|
||||
}
|
||||
|
||||
// Update knob position/size.
|
||||
mKnob.setResize(0, mSize.y() * 0.7f);
|
||||
float lineLength = mSize.x() - mKnob.getSize().x() -
|
||||
(mValueCache ? mValueCache->metrics.size.x() +
|
||||
(4 * Renderer::getScreenWidthModifier()) : 0);
|
||||
mKnob.setPosition(((mValue - mMin / 2) / mMax) * lineLength +
|
||||
mKnob.getSize().x() / 2, mSize.y() / 2);
|
||||
float lineLength =
|
||||
mSize.x() - mKnob.getSize().x() -
|
||||
(mValueCache ? mValueCache->metrics.size.x() + (4.0f * Renderer::getScreenWidthModifier()) :
|
||||
0);
|
||||
|
||||
mKnob.setPosition(((mValue - mMin / 2.0f) / mMax) * lineLength + mKnob.getSize().x() / 2.0f,
|
||||
mSize.y() / 2.0f);
|
||||
}
|
||||
|
||||
std::vector<HelpPrompt> SliderComponent::getHelpPrompts()
|
||||
|
|
|
@ -9,8 +9,8 @@
|
|||
#ifndef ES_CORE_COMPONENTS_SLIDER_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_SLIDER_COMPONENT_H
|
||||
|
||||
#include "components/ImageComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
#include "components/ImageComponent.h"
|
||||
|
||||
class Font;
|
||||
class TextCache;
|
||||
|
@ -20,13 +20,9 @@ class SliderComponent : public GuiComponent
|
|||
{
|
||||
public:
|
||||
// Minimum value (far left of the slider), maximum value (far right of the slider),
|
||||
// increment size (how much just pressing L/R moves by), unit to display (optional).
|
||||
// increment size (how much pressing L/R moves by), unit to display (optional).
|
||||
SliderComponent(
|
||||
Window* window,
|
||||
float min,
|
||||
float max,
|
||||
float increment,
|
||||
const std::string& suffix = "");
|
||||
Window* window, float min, float max, float increment, const std::string& suffix = "");
|
||||
|
||||
void setValue(float val);
|
||||
float getValue();
|
||||
|
|
|
@ -10,31 +10,19 @@
|
|||
|
||||
#include "resources/Font.h"
|
||||
|
||||
SwitchComponent::SwitchComponent(
|
||||
Window* window,
|
||||
bool state)
|
||||
: GuiComponent(window),
|
||||
mImage(window),
|
||||
mState(state),
|
||||
mOriginalValue(state),
|
||||
mColorOriginalValue(DEFAULT_COLORSHIFT),
|
||||
mColorChangedValue(DEFAULT_COLORSHIFT)
|
||||
SwitchComponent::SwitchComponent(Window* window, bool state)
|
||||
: GuiComponent(window)
|
||||
, mImage(window)
|
||||
, mState(state)
|
||||
, mOriginalValue(state)
|
||||
, mColorOriginalValue(DEFAULT_COLORSHIFT)
|
||||
, mColorChangedValue(DEFAULT_COLORSHIFT)
|
||||
{
|
||||
mImage.setImage(":/graphics/off.svg");
|
||||
mImage.setResize(0, Font::get(FONT_SIZE_MEDIUM)->getLetterHeight());
|
||||
mSize = mImage.getSize();
|
||||
}
|
||||
|
||||
void SwitchComponent::onSizeChanged()
|
||||
{
|
||||
mImage.setSize(mSize);
|
||||
}
|
||||
|
||||
void SwitchComponent::setResize(float width, float height)
|
||||
{
|
||||
mImage.setResize(width, height);
|
||||
}
|
||||
|
||||
bool SwitchComponent::input(InputConfig* config, Input input)
|
||||
{
|
||||
if (config->isMappedTo("a", input) && input.value) {
|
||||
|
@ -61,21 +49,13 @@ void SwitchComponent::render(const Transform4x4f& parentTrans)
|
|||
renderChildren(trans);
|
||||
}
|
||||
|
||||
bool SwitchComponent::getState() const
|
||||
{
|
||||
return mState;
|
||||
}
|
||||
|
||||
void SwitchComponent::setState(bool state)
|
||||
{
|
||||
mState = state;
|
||||
onStateChanged();
|
||||
}
|
||||
|
||||
std::string SwitchComponent::getValue() const
|
||||
{
|
||||
return mState ? "true" : "false";
|
||||
}
|
||||
std::string SwitchComponent::getValue() const { return mState ? "true" : "false"; }
|
||||
|
||||
void SwitchComponent::setValue(const std::string& statestring)
|
||||
{
|
||||
|
@ -88,26 +68,6 @@ void SwitchComponent::setValue(const std::string& statestring)
|
|||
onStateChanged();
|
||||
}
|
||||
|
||||
unsigned char SwitchComponent::getOpacity() const
|
||||
{
|
||||
return mImage.getOpacity();
|
||||
}
|
||||
|
||||
void SwitchComponent::setOpacity(unsigned char opacity)
|
||||
{
|
||||
mImage.setOpacity(opacity);
|
||||
}
|
||||
|
||||
void SwitchComponent::setColorShift(unsigned int color)
|
||||
{
|
||||
mImage.setColorShift(color);
|
||||
}
|
||||
|
||||
unsigned int SwitchComponent::getColorShift() const
|
||||
{
|
||||
return mImage.getColorShift();
|
||||
}
|
||||
|
||||
void SwitchComponent::onStateChanged()
|
||||
{
|
||||
mImage.setImage(mState ? ":/graphics/on.svg" : ":/graphics/off.svg");
|
||||
|
|
|
@ -9,8 +9,8 @@
|
|||
#ifndef ES_CORE_COMPONENTS_SWITCH_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_SWITCH_COMPONENT_H
|
||||
|
||||
#include "components/ImageComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
#include "components/ImageComponent.h"
|
||||
|
||||
// A simple "on/off" switch.
|
||||
class SwitchComponent : public GuiComponent
|
||||
|
@ -20,25 +20,25 @@ public:
|
|||
|
||||
bool input(InputConfig* config, Input input) override;
|
||||
void render(const Transform4x4f& parentTrans) override;
|
||||
void onSizeChanged() override;
|
||||
void onSizeChanged() override { mImage.setSize(mSize); }
|
||||
|
||||
void setResize(float width, float height) override;
|
||||
void setResize(float width, float height) override { mImage.setResize(width, height); }
|
||||
|
||||
bool getState() const;
|
||||
bool getState() const { return mState; }
|
||||
void setState(bool state);
|
||||
std::string getValue() const override;
|
||||
void setValue(const std::string& statestring) override;
|
||||
|
||||
void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; };
|
||||
void setChangedColor(unsigned int color) override { mColorChangedValue = color; };
|
||||
void setCallback(const std::function<void()>& callbackFunc) { mToggleCallback = callbackFunc; };
|
||||
void setOriginalColor(unsigned int color) override { mColorOriginalValue = color; }
|
||||
void setChangedColor(unsigned int color) override { mColorChangedValue = color; }
|
||||
void setCallback(const std::function<void()>& callbackFunc) { mToggleCallback = callbackFunc; }
|
||||
|
||||
unsigned char getOpacity() const override;
|
||||
void setOpacity(unsigned char opacity) override;
|
||||
unsigned char getOpacity() const override { return mImage.getOpacity(); }
|
||||
void setOpacity(unsigned char opacity) override { mImage.setOpacity(opacity); }
|
||||
// Multiply all pixels in the image by this color when rendering.
|
||||
void setColorShift(unsigned int color) override;
|
||||
void setColorShift(unsigned int color) override { mImage.setColorShift(color); }
|
||||
|
||||
unsigned int getColorShift() const override;
|
||||
unsigned int getColorShift() const override { return mImage.getColorShift(); }
|
||||
|
||||
virtual std::vector<HelpPrompt> getHelpPrompts() override;
|
||||
|
||||
|
|
|
@ -8,49 +8,47 @@
|
|||
|
||||
#include "components/TextComponent.h"
|
||||
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Log.h"
|
||||
#include "Settings.h"
|
||||
#include "utils/StringUtil.h"
|
||||
|
||||
TextComponent::TextComponent(
|
||||
Window* window)
|
||||
: GuiComponent(window),
|
||||
mFont(Font::get(FONT_SIZE_MEDIUM)),
|
||||
mUppercase(false),
|
||||
mColor(0x000000FF),
|
||||
mAutoCalcExtent(true, true),
|
||||
mHorizontalAlignment(ALIGN_LEFT),
|
||||
mVerticalAlignment(ALIGN_CENTER),
|
||||
mLineSpacing(1.5f),
|
||||
mNoTopMargin(false),
|
||||
mBgColor(0),
|
||||
mMargin(0.0f),
|
||||
mRenderBackground(false)
|
||||
TextComponent::TextComponent(Window* window)
|
||||
: GuiComponent(window)
|
||||
, mFont(Font::get(FONT_SIZE_MEDIUM))
|
||||
, mUppercase(false)
|
||||
, mColor(0x000000FF)
|
||||
, mAutoCalcExtent(true, true)
|
||||
, mHorizontalAlignment(ALIGN_LEFT)
|
||||
, mVerticalAlignment(ALIGN_CENTER)
|
||||
, mLineSpacing(1.5f)
|
||||
, mNoTopMargin(false)
|
||||
, mBgColor(0)
|
||||
, mMargin(0.0f)
|
||||
, mRenderBackground(false)
|
||||
{
|
||||
}
|
||||
|
||||
TextComponent::TextComponent(
|
||||
Window* window,
|
||||
const std::string& text,
|
||||
const std::shared_ptr<Font>& font,
|
||||
unsigned int color,
|
||||
Alignment align,
|
||||
Vector3f pos,
|
||||
Vector2f size,
|
||||
unsigned int bgcolor,
|
||||
float margin)
|
||||
: GuiComponent(window),
|
||||
mFont(nullptr),
|
||||
mUppercase(false),
|
||||
mColor(0x000000FF),
|
||||
mAutoCalcExtent(true, true),
|
||||
mHorizontalAlignment(align),
|
||||
mVerticalAlignment(ALIGN_CENTER),
|
||||
mLineSpacing(1.5f),
|
||||
mNoTopMargin(false),
|
||||
mBgColor(0),
|
||||
mMargin(margin),
|
||||
mRenderBackground(false)
|
||||
TextComponent::TextComponent(Window* window,
|
||||
const std::string& text,
|
||||
const std::shared_ptr<Font>& font,
|
||||
unsigned int color,
|
||||
Alignment align,
|
||||
Vector3f pos,
|
||||
Vector2f size,
|
||||
unsigned int bgcolor,
|
||||
float margin)
|
||||
: GuiComponent(window)
|
||||
, mFont(nullptr)
|
||||
, mUppercase(false)
|
||||
, mColor(0x000000FF)
|
||||
, mAutoCalcExtent(true, true)
|
||||
, mHorizontalAlignment(align)
|
||||
, mVerticalAlignment(ALIGN_CENTER)
|
||||
, mLineSpacing(1.5f)
|
||||
, mNoTopMargin(false)
|
||||
, mBgColor(0)
|
||||
, mMargin(margin)
|
||||
, mRenderBackground(false)
|
||||
{
|
||||
setFont(font);
|
||||
setColor(color);
|
||||
|
@ -87,45 +85,30 @@ void TextComponent::setBackgroundColor(unsigned int color)
|
|||
mBgColorOpacity = mBgColor & 0x000000FF;
|
||||
}
|
||||
|
||||
void TextComponent::setRenderBackground(bool render)
|
||||
{
|
||||
mRenderBackground = render;
|
||||
}
|
||||
|
||||
// Scale the opacity.
|
||||
void TextComponent::setOpacity(unsigned char opacity)
|
||||
{
|
||||
// This function is mostly called to do fading in-out of the Text component element.
|
||||
// Therefore, we assume here that opacity is a fractional value (expressed as an int 0-255),
|
||||
// of the opacity originally set with setColor() or setBackgroundColor().
|
||||
unsigned char o = static_cast<unsigned char>(static_cast<float>(opacity) / 255.f *
|
||||
static_cast<float>(mColorOpacity));
|
||||
// This function is mostly called to do fade in and fade out of the text component element.
|
||||
// Therefore we assume here that opacity is a fractional value (expressed as an unsigned
|
||||
// char 0 - 255) of the opacity originally set with setColor() or setBackgroundColor().
|
||||
unsigned char o = static_cast<unsigned char>(static_cast<float>(opacity) / 255.0f *
|
||||
static_cast<float>(mColorOpacity));
|
||||
mColor = (mColor & 0xFFFFFF00) | static_cast<unsigned char>(o);
|
||||
|
||||
unsigned char bgo = static_cast<unsigned char>(static_cast<float>(opacity) / 255.f *
|
||||
static_cast<float>(mBgColorOpacity));
|
||||
unsigned char bgo = static_cast<unsigned char>(static_cast<float>(opacity) / 255.0f *
|
||||
static_cast<float>(mBgColorOpacity));
|
||||
mBgColor = (mBgColor & 0xFFFFFF00) | static_cast<unsigned char>(bgo);
|
||||
|
||||
onColorChanged();
|
||||
GuiComponent::setOpacity(opacity);
|
||||
}
|
||||
|
||||
unsigned char TextComponent::getOpacity() const
|
||||
{
|
||||
return mColor & 0x000000FF;
|
||||
}
|
||||
|
||||
void TextComponent::setText(const std::string& text)
|
||||
{
|
||||
mText = text;
|
||||
onTextChanged();
|
||||
}
|
||||
|
||||
void TextComponent::setHiddenText(const std::string& text)
|
||||
{
|
||||
mHiddenText = text;
|
||||
}
|
||||
|
||||
void TextComponent::setUppercase(bool uppercase)
|
||||
{
|
||||
mUppercase = uppercase;
|
||||
|
@ -148,17 +131,21 @@ void TextComponent::render(const Transform4x4f& parentTrans)
|
|||
const Vector2f& textSize = mTextCache->metrics.size;
|
||||
float yOff = 0;
|
||||
switch (mVerticalAlignment) {
|
||||
case ALIGN_TOP:
|
||||
case ALIGN_TOP: {
|
||||
yOff = 0;
|
||||
break;
|
||||
case ALIGN_BOTTOM:
|
||||
}
|
||||
case ALIGN_BOTTOM: {
|
||||
yOff = (getSize().y() - textSize.y());
|
||||
break;
|
||||
case ALIGN_CENTER:
|
||||
}
|
||||
case ALIGN_CENTER: {
|
||||
yOff = (getSize().y() - textSize.y()) / 2.0f;
|
||||
break;
|
||||
default:
|
||||
}
|
||||
default: {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Vector3f off(0, yOff, 0);
|
||||
|
||||
|
@ -174,22 +161,26 @@ void TextComponent::render(const Transform4x4f& parentTrans)
|
|||
// Draw the text area, where the text actually is located.
|
||||
if (Settings::getInstance()->getBool("DebugText")) {
|
||||
switch (mHorizontalAlignment) {
|
||||
case ALIGN_LEFT:
|
||||
Renderer::drawRect(0.0f, 0.0f, mTextCache->metrics.size.x(),
|
||||
mTextCache->metrics.size.y(), 0x00000033, 0x00000033);
|
||||
break;
|
||||
case ALIGN_CENTER:
|
||||
Renderer::drawRect((mSize.x() - mTextCache->metrics.size.x()) / 2.0f, 0.0f,
|
||||
mTextCache->metrics.size.x(), mTextCache->metrics.size.y(),
|
||||
0x00000033, 0x00000033);
|
||||
break;
|
||||
case ALIGN_RIGHT:
|
||||
Renderer::drawRect(mSize.x() - mTextCache->metrics.size.x(), 0.0f,
|
||||
mTextCache->metrics.size.x(), mTextCache->metrics.size.y(),
|
||||
0x00000033, 0x00000033);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
case ALIGN_LEFT: {
|
||||
Renderer::drawRect(0.0f, 0.0f, mTextCache->metrics.size.x(),
|
||||
mTextCache->metrics.size.y(), 0x00000033, 0x00000033);
|
||||
break;
|
||||
}
|
||||
case ALIGN_CENTER: {
|
||||
Renderer::drawRect((mSize.x() - mTextCache->metrics.size.x()) / 2.0f, 0.0f,
|
||||
mTextCache->metrics.size.x(), mTextCache->metrics.size.y(),
|
||||
0x00000033, 0x00000033);
|
||||
break;
|
||||
}
|
||||
case ALIGN_RIGHT: {
|
||||
Renderer::drawRect(mSize.x() - mTextCache->metrics.size.x(), 0.0f,
|
||||
mTextCache->metrics.size.x(), mTextCache->metrics.size.y(),
|
||||
0x00000033, 0x00000033);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
mFont->renderTextCache(mTextCache.get());
|
||||
|
@ -203,8 +194,10 @@ void TextComponent::calculateExtent()
|
|||
}
|
||||
else {
|
||||
if (mAutoCalcExtent.y())
|
||||
mSize[1] = mFont->sizeWrappedText(mUppercase ? Utils::String::toUpper(mText)
|
||||
: mText, getSize().x(), mLineSpacing).y();
|
||||
mSize[1] = mFont
|
||||
->sizeWrappedText(mUppercase ? Utils::String::toUpper(mText) : mText,
|
||||
getSize().x(), mLineSpacing)
|
||||
.y();
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -246,14 +239,14 @@ void TextComponent::onTextChanged()
|
|||
|
||||
text.append(abbrev);
|
||||
|
||||
mTextCache = std::shared_ptr<TextCache>(f->buildTextCache(text, Vector2f(0, 0),
|
||||
(mColor >> 8 << 8) | mOpacity, mSize.x(), mHorizontalAlignment,
|
||||
mLineSpacing, mNoTopMargin));
|
||||
mTextCache = std::shared_ptr<TextCache>(
|
||||
f->buildTextCache(text, Vector2f(0, 0), (mColor >> 8 << 8) | mOpacity, mSize.x(),
|
||||
mHorizontalAlignment, mLineSpacing, mNoTopMargin));
|
||||
}
|
||||
else {
|
||||
mTextCache = std::shared_ptr<TextCache>(f->buildTextCache(f->wrapText(
|
||||
text, mSize.x()), Vector2f(0, 0), (mColor >> 8 << 8) | mOpacity, mSize.x(),
|
||||
mHorizontalAlignment, mLineSpacing, mNoTopMargin));
|
||||
mTextCache = std::shared_ptr<TextCache>(f->buildTextCache(
|
||||
f->wrapText(text, mSize.x()), Vector2f(0, 0), (mColor >> 8 << 8) | mOpacity, mSize.x(),
|
||||
mHorizontalAlignment, mLineSpacing, mNoTopMargin));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -269,10 +262,7 @@ void TextComponent::setHorizontalAlignment(Alignment align)
|
|||
onTextChanged();
|
||||
}
|
||||
|
||||
void TextComponent::setVerticalAlignment(Alignment align)
|
||||
{
|
||||
mVerticalAlignment = align;
|
||||
}
|
||||
void TextComponent::setVerticalAlignment(Alignment align) { mVerticalAlignment = align; }
|
||||
|
||||
void TextComponent::setLineSpacing(float spacing)
|
||||
{
|
||||
|
@ -286,28 +276,10 @@ void TextComponent::setNoTopMargin(bool margin)
|
|||
onTextChanged();
|
||||
}
|
||||
|
||||
std::string TextComponent::getValue() const
|
||||
{
|
||||
return mText;
|
||||
}
|
||||
|
||||
void TextComponent::setValue(const std::string& value)
|
||||
{
|
||||
setText(value);
|
||||
}
|
||||
|
||||
std::string TextComponent::getHiddenValue() const
|
||||
{
|
||||
return mHiddenText;
|
||||
}
|
||||
|
||||
void TextComponent::setHiddenValue(const std::string& value)
|
||||
{
|
||||
setHiddenText(value);
|
||||
}
|
||||
|
||||
void TextComponent::applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties)
|
||||
void TextComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties)
|
||||
{
|
||||
GuiComponent::applyTheme(theme, view, element, properties);
|
||||
|
||||
|
|
|
@ -9,8 +9,8 @@
|
|||
#ifndef ES_CORE_COMPONENTS_TEXT_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_TEXT_COMPONENT_H
|
||||
|
||||
#include "resources/Font.h"
|
||||
#include "GuiComponent.h"
|
||||
#include "resources/Font.h"
|
||||
|
||||
class ThemeData;
|
||||
|
||||
|
@ -25,46 +25,47 @@ class TextComponent : public GuiComponent
|
|||
{
|
||||
public:
|
||||
TextComponent(Window* window);
|
||||
TextComponent(
|
||||
Window* window,
|
||||
const std::string& text,
|
||||
const std::shared_ptr<Font>& font,
|
||||
unsigned int color = 0x000000FF,
|
||||
Alignment align = ALIGN_LEFT,
|
||||
Vector3f pos = Vector3f::Zero(),
|
||||
Vector2f size = Vector2f::Zero(),
|
||||
unsigned int bgcolor = 0x00000000,
|
||||
float margin = 0.0f);
|
||||
TextComponent(Window* window,
|
||||
const std::string& text,
|
||||
const std::shared_ptr<Font>& font,
|
||||
unsigned int color = 0x000000FF,
|
||||
Alignment align = ALIGN_LEFT,
|
||||
Vector3f pos = Vector3f::Zero(),
|
||||
Vector2f size = Vector2f::Zero(),
|
||||
unsigned int bgcolor = 0x00000000,
|
||||
float margin = 0.0f);
|
||||
|
||||
void setFont(const std::shared_ptr<Font>& font);
|
||||
void setUppercase(bool uppercase);
|
||||
void onSizeChanged() override;
|
||||
void setText(const std::string& text);
|
||||
void setHiddenText(const std::string& text);
|
||||
void setHiddenText(const std::string& text) { mHiddenText = text; }
|
||||
void setColor(unsigned int color) override;
|
||||
void setHorizontalAlignment(Alignment align);
|
||||
void setVerticalAlignment(Alignment align);
|
||||
void setLineSpacing(float spacing);
|
||||
void setNoTopMargin(bool margin);
|
||||
void setBackgroundColor(unsigned int color);
|
||||
void setRenderBackground(bool render);
|
||||
void setRenderBackground(bool render) { mRenderBackground = render; }
|
||||
|
||||
void render(const Transform4x4f& parentTrans) override;
|
||||
|
||||
std::string getValue() const override;
|
||||
void setValue(const std::string& value) override;
|
||||
std::string getValue() const override { return mText; }
|
||||
void setValue(const std::string& value) override { setText(value); }
|
||||
|
||||
std::string getHiddenValue() const override;
|
||||
void setHiddenValue(const std::string& value) override;
|
||||
std::string getHiddenValue() const override { return mHiddenText; }
|
||||
void setHiddenValue(const std::string& value) override { setHiddenText(value); }
|
||||
|
||||
unsigned char getOpacity() const override;
|
||||
unsigned char getOpacity() const override { return mColor & 0x000000FF; }
|
||||
void setOpacity(unsigned char opacity) override;
|
||||
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties) override;
|
||||
|
||||
unsigned int getColor() const override { return mColor; };
|
||||
inline std::shared_ptr<Font> getFont() const override { return mFont; }
|
||||
unsigned int getColor() const override { return mColor; }
|
||||
std::shared_ptr<Font> getFont() const override { return mFont; }
|
||||
Alignment getHorizontalAlignment() { return mHorizontalAlignment; }
|
||||
Alignment getVerticalAlignment() { return mVerticalAlignment; }
|
||||
|
||||
|
@ -77,7 +78,6 @@ protected:
|
|||
|
||||
private:
|
||||
void calculateExtent();
|
||||
|
||||
void onColorChanged();
|
||||
|
||||
unsigned int mColor;
|
||||
|
|
|
@ -8,24 +8,23 @@
|
|||
|
||||
#include "components/TextEditComponent.h"
|
||||
|
||||
#include "resources/Font.h"
|
||||
#include "utils/StringUtil.h"
|
||||
|
||||
#define TEXT_PADDING_HORIZ 10
|
||||
#define TEXT_PADDING_VERT 2
|
||||
#define TEXT_PADDING_HORIZ 10.0f
|
||||
#define TEXT_PADDING_VERT 2.0f
|
||||
|
||||
#define CURSOR_REPEAT_START_DELAY 500
|
||||
#define CURSOR_REPEAT_SPEED 28 // Lower is faster.
|
||||
|
||||
TextEditComponent::TextEditComponent(
|
||||
Window* window)
|
||||
: GuiComponent(window),
|
||||
mBox(window, ":/graphics/textinput.svg"),
|
||||
mFocused(false),
|
||||
mScrollOffset(0.0f, 0.0f),
|
||||
mCursor(0), mEditing(false),
|
||||
mFont(Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT)),
|
||||
mCursorRepeatDir(0)
|
||||
TextEditComponent::TextEditComponent(Window* window)
|
||||
: GuiComponent(window)
|
||||
, mBox(window, ":/graphics/textinput.svg")
|
||||
, mFocused(false)
|
||||
, mScrollOffset(0.0f, 0.0f)
|
||||
, mCursor(0)
|
||||
, mEditing(false)
|
||||
, mFont(Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT))
|
||||
, mCursorRepeatDir(0)
|
||||
{
|
||||
addChild(&mBox);
|
||||
onFocusLost();
|
||||
|
@ -47,8 +46,9 @@ void TextEditComponent::onFocusLost()
|
|||
|
||||
void TextEditComponent::onSizeChanged()
|
||||
{
|
||||
mBox.fitTo(mSize, Vector3f::Zero(), Vector2f(-34 + mResolutionAdjustment, -32 -
|
||||
(TEXT_PADDING_VERT * Renderer::getScreenHeightModifier())));
|
||||
mBox.fitTo(mSize, Vector3f::Zero(),
|
||||
Vector2f(-34 + mResolutionAdjustment,
|
||||
-32 - (TEXT_PADDING_VERT * Renderer::getScreenHeightModifier())));
|
||||
onTextChanged(); // Wrap point probably changed.
|
||||
}
|
||||
|
||||
|
@ -59,11 +59,6 @@ void TextEditComponent::setValue(const std::string& val)
|
|||
onTextChanged();
|
||||
}
|
||||
|
||||
std::string TextEditComponent::getValue() const
|
||||
{
|
||||
return mText;
|
||||
}
|
||||
|
||||
void TextEditComponent::textInput(const std::string& text)
|
||||
{
|
||||
if (mEditing) {
|
||||
|
@ -103,33 +98,35 @@ void TextEditComponent::stopEditing()
|
|||
|
||||
bool TextEditComponent::input(InputConfig* config, Input input)
|
||||
{
|
||||
bool const cursor_left = (config->getDeviceId() != DEVICE_KEYBOARD &&
|
||||
config->isMappedLike("left", input)) || (config->getDeviceId() == DEVICE_KEYBOARD &&
|
||||
input.id == SDLK_LEFT);
|
||||
bool const cursor_right = (config->getDeviceId() != DEVICE_KEYBOARD &&
|
||||
config->isMappedLike("right", input)) || (config->getDeviceId() == DEVICE_KEYBOARD &&
|
||||
input.id == SDLK_RIGHT);
|
||||
bool const cursor_up = (config->getDeviceId() != DEVICE_KEYBOARD &&
|
||||
config->isMappedLike("up", input)) || (config->getDeviceId() == DEVICE_KEYBOARD &&
|
||||
input.id == SDLK_UP);
|
||||
bool const cursor_down = (config->getDeviceId() != DEVICE_KEYBOARD &&
|
||||
config->isMappedLike("down", input)) || (config->getDeviceId() == DEVICE_KEYBOARD &&
|
||||
input.id == SDLK_DOWN);
|
||||
bool const cursor_left =
|
||||
(config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("left", input)) ||
|
||||
(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_LEFT);
|
||||
bool const cursor_right =
|
||||
(config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("right", input)) ||
|
||||
(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RIGHT);
|
||||
bool const cursor_up =
|
||||
(config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("up", input)) ||
|
||||
(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_UP);
|
||||
bool const cursor_down =
|
||||
(config->getDeviceId() != DEVICE_KEYBOARD && config->isMappedLike("down", input)) ||
|
||||
(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_DOWN);
|
||||
bool const shoulder_left = (config->isMappedLike("leftshoulder", input));
|
||||
bool const shoulder_right = (config->isMappedLike("rightshoulder", input));
|
||||
bool const trigger_left = (config->isMappedLike("lefttrigger", input));
|
||||
bool const trigger_right = (config->isMappedLike("righttrigger", input));
|
||||
|
||||
if (input.value == 0) {
|
||||
if (cursor_left || cursor_right || cursor_up || cursor_down ||
|
||||
shoulder_left || shoulder_right | trigger_left || trigger_right)
|
||||
if (cursor_left || cursor_right || cursor_up || cursor_down || shoulder_left ||
|
||||
shoulder_right | trigger_left || trigger_right) {
|
||||
mCursorRepeatDir = 0;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((config->isMappedTo("a", input) || (config->getDeviceId() == DEVICE_KEYBOARD &&
|
||||
input.id == SDLK_RETURN)) && mFocused && !mEditing) {
|
||||
if ((config->isMappedTo("a", input) ||
|
||||
(config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_RETURN)) &&
|
||||
mFocused && !mEditing) {
|
||||
startEditing();
|
||||
return true;
|
||||
}
|
||||
|
@ -146,8 +143,8 @@ bool TextEditComponent::input(InputConfig* config, Input input)
|
|||
|
||||
// Done editing (accept changes).
|
||||
if ((config->getDeviceId() == DEVICE_KEYBOARD && input.id == SDLK_ESCAPE) ||
|
||||
(config->getDeviceId() != DEVICE_KEYBOARD && (config->isMappedTo("a", input) ||
|
||||
config->isMappedTo("b", input)))) {
|
||||
(config->getDeviceId() != DEVICE_KEYBOARD &&
|
||||
(config->isMappedTo("a", input) || config->isMappedTo("b", input)))) {
|
||||
mTextOrig = mText;
|
||||
stopEditing();
|
||||
return true;
|
||||
|
@ -181,21 +178,22 @@ bool TextEditComponent::input(InputConfig* config, Input input)
|
|||
}
|
||||
else if (config->getDeviceId() == DEVICE_KEYBOARD) {
|
||||
switch (input.id) {
|
||||
case SDLK_HOME:
|
||||
setCursor(0);
|
||||
break;
|
||||
|
||||
case SDLK_END:
|
||||
setCursor(std::string::npos);
|
||||
break;
|
||||
|
||||
case SDLK_DELETE:
|
||||
if (mCursor < mText.length()) {
|
||||
// Fake as Backspace one char to the right.
|
||||
moveCursor(1);
|
||||
textInput("\b");
|
||||
case SDLK_HOME: {
|
||||
setCursor(0);
|
||||
break;
|
||||
}
|
||||
case SDLK_END: {
|
||||
setCursor(std::string::npos);
|
||||
break;
|
||||
}
|
||||
case SDLK_DELETE: {
|
||||
if (mCursor < mText.length()) {
|
||||
// Fake as Backspace one char to the right.
|
||||
moveCursor(1);
|
||||
textInput("\b");
|
||||
}
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Consume all input when editing text.
|
||||
|
@ -241,10 +239,10 @@ void TextEditComponent::setCursor(size_t pos)
|
|||
|
||||
void TextEditComponent::onTextChanged()
|
||||
{
|
||||
std::string wrappedText = (isMultiline() ?
|
||||
mFont->wrapText(mText, getTextAreaSize().x()) : mText);
|
||||
mTextCache = std::unique_ptr<TextCache>
|
||||
(mFont->buildTextCache(wrappedText, 0, 0, 0x77777700 | getOpacity()));
|
||||
std::string wrappedText =
|
||||
(isMultiline() ? mFont->wrapText(mText, getTextAreaSize().x()) : mText);
|
||||
mTextCache = std::unique_ptr<TextCache>(
|
||||
mFont->buildTextCache(wrappedText, 0, 0, 0x77777700 | getOpacity()));
|
||||
|
||||
if (mCursor > static_cast<int>(mText.length()))
|
||||
mCursor = static_cast<unsigned int>(mText.length());
|
||||
|
@ -253,13 +251,14 @@ void TextEditComponent::onTextChanged()
|
|||
void TextEditComponent::onCursorChanged()
|
||||
{
|
||||
if (isMultiline()) {
|
||||
Vector2f textSize = mFont->
|
||||
getWrappedTextCursorOffset(mText, getTextAreaSize().x(), mCursor);
|
||||
Vector2f textSize =
|
||||
mFont->getWrappedTextCursorOffset(mText, getTextAreaSize().x(), mCursor);
|
||||
|
||||
if (mScrollOffset.y() + getTextAreaSize().y() < textSize.y() +
|
||||
mFont->getHeight()) // Need to scroll down?
|
||||
// Need to scroll down?
|
||||
if (mScrollOffset.y() + getTextAreaSize().y() < textSize.y() + mFont->getHeight())
|
||||
mScrollOffset[1] = textSize.y() - getTextAreaSize().y() + mFont->getHeight();
|
||||
else if (mScrollOffset.y() > textSize.y()) // Need to scroll up?
|
||||
// Need to scroll up?
|
||||
else if (mScrollOffset.y() > textSize.y())
|
||||
mScrollOffset[1] = textSize.y();
|
||||
}
|
||||
else {
|
||||
|
@ -282,11 +281,11 @@ void TextEditComponent::render(const Transform4x4f& parentTrans)
|
|||
trans.translation() += Vector3f(getTextAreaPos().x(), getTextAreaPos().y(), 0);
|
||||
|
||||
Vector2i clipPos(static_cast<int>(trans.translation().x()),
|
||||
static_cast<int>(trans.translation().y()));
|
||||
static_cast<int>(trans.translation().y()));
|
||||
// Use "text area" size for clipping.
|
||||
Vector3f dimScaled = trans * Vector3f(getTextAreaSize().x(), getTextAreaSize().y(), 0);
|
||||
Vector2i clipDim(static_cast<int>((dimScaled.x()) - trans.translation().x()),
|
||||
static_cast<int>((dimScaled.y()) - trans.translation().y()));
|
||||
static_cast<int>((dimScaled.y()) - trans.translation().y()));
|
||||
Renderer::pushClipRect(clipPos, clipDim);
|
||||
|
||||
trans.translate(Vector3f(-mScrollOffset.x(), -mScrollOffset.y(), 0));
|
||||
|
@ -310,28 +309,24 @@ void TextEditComponent::render(const Transform4x4f& parentTrans)
|
|||
}
|
||||
|
||||
float cursorHeight = mFont->getHeight() * 0.8f;
|
||||
Renderer::drawRect(cursorPos.x(), cursorPos.y() + (mFont->getHeight() - cursorHeight) / 2,
|
||||
2.0f * Renderer::getScreenWidthModifier(), cursorHeight, 0x000000FF, 0x000000FF);
|
||||
Renderer::drawRect(
|
||||
cursorPos.x(), cursorPos.y() + (mFont->getHeight() - cursorHeight) / 2.0f,
|
||||
2.0f * Renderer::getScreenWidthModifier(), cursorHeight, 0x000000FF, 0x000000FF);
|
||||
}
|
||||
}
|
||||
|
||||
bool TextEditComponent::isMultiline()
|
||||
{
|
||||
return (getSize().y() > mFont->getHeight() * 1.25f);
|
||||
}
|
||||
|
||||
Vector2f TextEditComponent::getTextAreaPos() const
|
||||
{
|
||||
return Vector2f((-mResolutionAdjustment +
|
||||
(TEXT_PADDING_HORIZ * Renderer::getScreenWidthModifier())) / 2.0f,
|
||||
(TEXT_PADDING_VERT * Renderer::getScreenHeightModifier()) / 2.0f);
|
||||
return Vector2f(
|
||||
(-mResolutionAdjustment + (TEXT_PADDING_HORIZ * Renderer::getScreenWidthModifier())) / 2.0f,
|
||||
(TEXT_PADDING_VERT * Renderer::getScreenHeightModifier()) / 2.0f);
|
||||
}
|
||||
|
||||
Vector2f TextEditComponent::getTextAreaSize() const
|
||||
{
|
||||
return Vector2f(mSize.x() + mResolutionAdjustment -
|
||||
(TEXT_PADDING_HORIZ * Renderer::getScreenWidthModifier()), mSize.y() -
|
||||
(TEXT_PADDING_VERT * Renderer::getScreenHeightModifier()));
|
||||
(TEXT_PADDING_HORIZ * Renderer::getScreenWidthModifier()),
|
||||
mSize.y() - (TEXT_PADDING_VERT * Renderer::getScreenHeightModifier()));
|
||||
}
|
||||
|
||||
std::vector<HelpPrompt> TextEditComponent::getHelpPrompts()
|
||||
|
|
|
@ -9,8 +9,9 @@
|
|||
#ifndef ES_CORE_COMPONENTS_TEXT_EDIT_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_TEXT_EDIT_COMPONENT_H
|
||||
|
||||
#include "components/NinePatchComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
#include "components/NinePatchComponent.h"
|
||||
#include "resources/Font.h"
|
||||
|
||||
class Font;
|
||||
class TextCache;
|
||||
|
@ -32,13 +33,13 @@ public:
|
|||
void onSizeChanged() override;
|
||||
|
||||
void setValue(const std::string& val) override;
|
||||
std::string getValue() const override;
|
||||
std::string getValue() const override { return mText; }
|
||||
|
||||
void startEditing();
|
||||
void stopEditing();
|
||||
|
||||
inline bool isEditing() const { return mEditing; };
|
||||
inline std::shared_ptr<Font> getFont() const override{ return mFont; }
|
||||
bool isEditing() const { return mEditing; }
|
||||
std::shared_ptr<Font> getFont() const override { return mFont; }
|
||||
|
||||
void setCursor(size_t pos);
|
||||
|
||||
|
@ -51,7 +52,7 @@ private:
|
|||
void updateCursorRepeat(int deltaTime);
|
||||
void moveCursor(int amt);
|
||||
|
||||
bool isMultiline();
|
||||
bool isMultiline() { return (getSize().y() > mFont->getHeight() * 1.25f); }
|
||||
Vector2f getTextAreaPos() const;
|
||||
Vector2f getTextAreaSize() const;
|
||||
|
||||
|
|
|
@ -9,12 +9,12 @@
|
|||
#ifndef ES_APP_COMPONENTS_TEXT_LIST_COMPONENT_H
|
||||
#define ES_APP_COMPONENTS_TEXT_LIST_COMPONENT_H
|
||||
|
||||
#include "Log.h"
|
||||
#include "Sound.h"
|
||||
#include "components/IList.h"
|
||||
#include "math/Misc.h"
|
||||
#include "resources/Font.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "Log.h"
|
||||
#include "Sound.h"
|
||||
|
||||
#include <memory>
|
||||
|
||||
|
@ -26,8 +26,7 @@ struct TextListData {
|
|||
};
|
||||
|
||||
// A graphical list. Supports multiple colors for rows and scrolling.
|
||||
template <typename T>
|
||||
class TextListComponent : public IList<TextListData, T>
|
||||
template <typename T> class TextListComponent : public IList<TextListData, T>
|
||||
{
|
||||
protected:
|
||||
using IList<TextListData, T>::mEntries;
|
||||
|
@ -38,9 +37,6 @@ protected:
|
|||
using IList<TextListData, T>::mSize;
|
||||
using IList<TextListData, T>::mCursor;
|
||||
using IList<TextListData, T>::mWindow;
|
||||
// The following change is required for compilation with Clang.
|
||||
// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#2070
|
||||
// using IList<TextListData, T>::Entry;
|
||||
using IList<TextListData, T>::IList;
|
||||
|
||||
public:
|
||||
|
@ -53,45 +49,51 @@ public:
|
|||
bool input(InputConfig* config, Input input) override;
|
||||
void update(int deltaTime) override;
|
||||
void render(const Transform4x4f& parentTrans) override;
|
||||
void applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties) override;
|
||||
void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties) override;
|
||||
|
||||
void add(const std::string& name, const T& obj, unsigned int colorId);
|
||||
|
||||
enum Alignment {
|
||||
ALIGN_LEFT,
|
||||
ALIGN_LEFT, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
ALIGN_CENTER,
|
||||
ALIGN_RIGHT
|
||||
};
|
||||
|
||||
inline void setAlignment(Alignment align) { mAlignment = align; }
|
||||
void setAlignment(Alignment align) { mAlignment = align; }
|
||||
|
||||
inline void setCursorChangedCallback(const std::function<void(CursorState state)>& func)
|
||||
{ mCursorChangedCallback = func; }
|
||||
void setCursorChangedCallback(const std::function<void(CursorState state)>& func)
|
||||
{
|
||||
mCursorChangedCallback = func;
|
||||
}
|
||||
|
||||
inline void setFont(const std::shared_ptr<Font>& font)
|
||||
void setFont(const std::shared_ptr<Font>& font)
|
||||
{
|
||||
mFont = font;
|
||||
for (auto it = mEntries.begin(); it != mEntries.end(); it++)
|
||||
it->data.textCache.reset();
|
||||
}
|
||||
|
||||
inline void setUppercase(bool /*uppercase*/)
|
||||
void setUppercase(bool /*uppercase*/)
|
||||
{
|
||||
mUppercase = true;
|
||||
for (auto it = mEntries.begin(); it != mEntries.end(); it++)
|
||||
it->data.textCache.reset();
|
||||
}
|
||||
|
||||
inline void setSelectorHeight(float selectorScale) { mSelectorHeight = selectorScale; }
|
||||
inline void setSelectorOffsetY(float selectorOffsetY) { mSelectorOffsetY = selectorOffsetY; }
|
||||
inline void setSelectorColor(unsigned int color) { mSelectorColor = color; }
|
||||
inline void setSelectorColorEnd(unsigned int color) { mSelectorColorEnd = color; }
|
||||
inline void setSelectorColorGradientHorizontal(bool horizontal)
|
||||
{ mSelectorColorGradientHorizontal = horizontal; }
|
||||
inline void setSelectedColor(unsigned int color) { mSelectedColor = color; }
|
||||
inline void setColor(unsigned int id, unsigned int color) { mColors[id] = color; }
|
||||
inline void setLineSpacing(float lineSpacing) { mLineSpacing = lineSpacing; }
|
||||
void setSelectorHeight(float selectorScale) { mSelectorHeight = selectorScale; }
|
||||
void setSelectorOffsetY(float selectorOffsetY) { mSelectorOffsetY = selectorOffsetY; }
|
||||
void setSelectorColor(unsigned int color) { mSelectorColor = color; }
|
||||
void setSelectorColorEnd(unsigned int color) { mSelectorColorEnd = color; }
|
||||
void setSelectorColorGradientHorizontal(bool horizontal)
|
||||
{
|
||||
mSelectorColorGradientHorizontal = horizontal;
|
||||
}
|
||||
void setSelectedColor(unsigned int color) { mSelectedColor = color; }
|
||||
void setColor(unsigned int id, unsigned int color) { mColors[id] = color; }
|
||||
void setLineSpacing(float lineSpacing) { mLineSpacing = lineSpacing; }
|
||||
|
||||
protected:
|
||||
virtual void onScroll() override
|
||||
|
@ -128,8 +130,9 @@ private:
|
|||
};
|
||||
|
||||
template <typename T>
|
||||
TextListComponent<T>::TextListComponent(Window* window) :
|
||||
IList<TextListData, T>(window), mSelectorImage(window)
|
||||
TextListComponent<T>::TextListComponent(Window* window)
|
||||
: IList<TextListData, T>(window)
|
||||
, mSelectorImage(window)
|
||||
{
|
||||
mMarqueeOffset = 0;
|
||||
mMarqueeOffset2 = 0;
|
||||
|
@ -152,8 +155,7 @@ TextListComponent<T>::TextListComponent(Window* window) :
|
|||
mColors[1] = 0x00FF00FF;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void TextListComponent<T>::render(const Transform4x4f& parentTrans)
|
||||
template <typename T> void TextListComponent<T>::render(const Transform4x4f& parentTrans)
|
||||
{
|
||||
if (size() == 0)
|
||||
return;
|
||||
|
@ -164,14 +166,14 @@ void TextListComponent<T>::render(const Transform4x4f& parentTrans)
|
|||
int startEntry = 0;
|
||||
float y = 0;
|
||||
|
||||
const float entrySize = std::max(font->getHeight(1.0),
|
||||
static_cast<float>(font->getSize())) * mLineSpacing;
|
||||
const float entrySize =
|
||||
std::max(font->getHeight(1.0), static_cast<float>(font->getSize())) * mLineSpacing;
|
||||
|
||||
// Number of entries that can fit on the screen simultaneously.
|
||||
int screenCount = static_cast<int>(mSize.y() / entrySize + 0.5f);
|
||||
|
||||
if (size() >= screenCount) {
|
||||
startEntry = mCursor - screenCount/2;
|
||||
startEntry = mCursor - screenCount / 2;
|
||||
if (startEntry < 0)
|
||||
startEntry = 0;
|
||||
if (startEntry >= size() - screenCount)
|
||||
|
@ -185,36 +187,31 @@ void TextListComponent<T>::render(const Transform4x4f& parentTrans)
|
|||
// Draw selector bar.
|
||||
if (startEntry < listCutoff) {
|
||||
if (mSelectorImage.hasImage()) {
|
||||
mSelectorImage.setPosition(0.0f, (mCursor - startEntry) *
|
||||
entrySize + mSelectorOffsetY, 0.0f);
|
||||
mSelectorImage.setPosition(0.0f, (mCursor - startEntry) * entrySize + mSelectorOffsetY,
|
||||
0.0f);
|
||||
mSelectorImage.render(trans);
|
||||
}
|
||||
else {
|
||||
Renderer::setMatrix(trans);
|
||||
Renderer::drawRect(
|
||||
0.0f,
|
||||
(mCursor - startEntry) * entrySize + mSelectorOffsetY,
|
||||
mSize.x(),
|
||||
mSelectorHeight,
|
||||
mSelectorColor,
|
||||
mSelectorColorEnd,
|
||||
mSelectorColorGradientHorizontal);
|
||||
Renderer::drawRect(0.0f, (mCursor - startEntry) * entrySize + mSelectorOffsetY,
|
||||
mSize.x(), mSelectorHeight, mSelectorColor, mSelectorColorEnd,
|
||||
mSelectorColorGradientHorizontal);
|
||||
}
|
||||
}
|
||||
|
||||
if (Settings::getInstance()->getBool("DebugText")) {
|
||||
Renderer::drawRect(mHorizontalMargin, 0.0f, mSize.x() - mHorizontalMargin * 2.0f,
|
||||
mSize.y(), 0x00000033, 0x00000033);
|
||||
Renderer::drawRect(mHorizontalMargin, 0.0f, mSize.x() - mHorizontalMargin * 2.0f, mSize.y(),
|
||||
0x00000033, 0x00000033);
|
||||
Renderer::drawRect(0.0f, 0.0f, mSize.x(), mSize.y(), 0x0000FF33, 0x0000FF33);
|
||||
}
|
||||
|
||||
// Clip to inside margins.
|
||||
Vector3f dim(mSize.x(), mSize.y(), 0.0f);
|
||||
dim = trans * dim - trans.translation();
|
||||
Renderer::pushClipRect(Vector2i(static_cast<int>(trans.translation().x() +
|
||||
mHorizontalMargin), static_cast<int>(trans.translation().y())),
|
||||
Vector2i(static_cast<int>(dim.x() - mHorizontalMargin * 2.0f),
|
||||
static_cast<int>(dim.y())));
|
||||
Renderer::pushClipRect(
|
||||
Vector2i(static_cast<int>(trans.translation().x() + mHorizontalMargin),
|
||||
static_cast<int>(trans.translation().y())),
|
||||
Vector2i(static_cast<int>(dim.x() - mHorizontalMargin * 2.0f), static_cast<int>(dim.y())));
|
||||
|
||||
for (int i = startEntry; i < listCutoff; i++) {
|
||||
typename IList<TextListData, T>::Entry& entry = mEntries.at(static_cast<unsigned int>(i));
|
||||
|
@ -226,9 +223,8 @@ void TextListComponent<T>::render(const Transform4x4f& parentTrans)
|
|||
color = mColors[entry.data.colorId];
|
||||
|
||||
if (!entry.data.textCache)
|
||||
entry.data.textCache = std::unique_ptr<TextCache>(
|
||||
font->buildTextCache(mUppercase ?
|
||||
Utils::String::toUpper(entry.name) : entry.name, 0, 0, 0x000000FF));
|
||||
entry.data.textCache = std::unique_ptr<TextCache>(font->buildTextCache(
|
||||
mUppercase ? Utils::String::toUpper(entry.name) : entry.name, 0, 0, 0x000000FF));
|
||||
|
||||
// If a game is marked as hidden, lower the text opacity a lot.
|
||||
// If a game is marked to not be counted, lower the opacity a moderate amount.
|
||||
|
@ -242,21 +238,21 @@ void TextListComponent<T>::render(const Transform4x4f& parentTrans)
|
|||
Vector3f offset(0.0f, y, 0.0f);
|
||||
|
||||
switch (mAlignment) {
|
||||
case ALIGN_LEFT:
|
||||
offset[0] = mHorizontalMargin;
|
||||
break;
|
||||
case ALIGN_CENTER:
|
||||
offset[0] = static_cast<float>((mSize.x() -
|
||||
entry.data.textCache->metrics.size.x()) / 2.0f);
|
||||
if (offset[0] < mHorizontalMargin)
|
||||
case ALIGN_LEFT:
|
||||
offset[0] = mHorizontalMargin;
|
||||
break;
|
||||
case ALIGN_RIGHT:
|
||||
offset[0] = (mSize.x() - entry.data.textCache->metrics.size.x());
|
||||
offset[0] -= mHorizontalMargin;
|
||||
if (offset[0] < mHorizontalMargin)
|
||||
offset[0] = mHorizontalMargin;
|
||||
break;
|
||||
break;
|
||||
case ALIGN_CENTER:
|
||||
offset[0] =
|
||||
static_cast<float>((mSize.x() - entry.data.textCache->metrics.size.x()) / 2.0f);
|
||||
if (offset[0] < mHorizontalMargin)
|
||||
offset[0] = mHorizontalMargin;
|
||||
break;
|
||||
case ALIGN_RIGHT:
|
||||
offset[0] = (mSize.x() - entry.data.textCache->metrics.size.x());
|
||||
offset[0] -= mHorizontalMargin;
|
||||
if (offset[0] < mHorizontalMargin)
|
||||
offset[0] = mHorizontalMargin;
|
||||
break;
|
||||
}
|
||||
|
||||
// Render text.
|
||||
|
@ -291,8 +287,7 @@ void TextListComponent<T>::render(const Transform4x4f& parentTrans)
|
|||
GuiComponent::renderChildren(trans);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool TextListComponent<T>::input(InputConfig* config, Input input)
|
||||
template <typename T> bool TextListComponent<T>::input(InputConfig* config, Input input)
|
||||
{
|
||||
if (size() > 0) {
|
||||
if (input.value != 0) {
|
||||
|
@ -324,12 +319,11 @@ bool TextListComponent<T>::input(InputConfig* config, Input input)
|
|||
}
|
||||
}
|
||||
else {
|
||||
if (config->isMappedLike("down", input) ||
|
||||
config->isMappedLike("up", input) ||
|
||||
config->isMappedLike("rightshoulder", input) ||
|
||||
config->isMappedLike("leftshoulder", input) ||
|
||||
config->isMappedLike("lefttrigger", input) ||
|
||||
config->isMappedLike("righttrigger", input))
|
||||
if (config->isMappedLike("down", input) || config->isMappedLike("up", input) ||
|
||||
config->isMappedLike("rightshoulder", input) ||
|
||||
config->isMappedLike("leftshoulder", input) ||
|
||||
config->isMappedLike("lefttrigger", input) ||
|
||||
config->isMappedLike("righttrigger", input))
|
||||
stopScrolling();
|
||||
}
|
||||
}
|
||||
|
@ -337,8 +331,7 @@ bool TextListComponent<T>::input(InputConfig* config, Input input)
|
|||
return GuiComponent::input(config, input);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void TextListComponent<T>::update(int deltaTime)
|
||||
template <typename T> void TextListComponent<T>::update(int deltaTime)
|
||||
{
|
||||
listUpdate(deltaTime);
|
||||
|
||||
|
@ -351,8 +344,10 @@ void TextListComponent<T>::update(int deltaTime)
|
|||
mMarqueeOffset2 = 0;
|
||||
|
||||
// If we're not scrolling and this object's text exceeds our size, then marquee it.
|
||||
const float textLength = mFont->sizeText(Utils::String::toUpper(
|
||||
mEntries.at(static_cast<unsigned int>(mCursor)).name)).x();
|
||||
const float textLength = mFont
|
||||
->sizeText(Utils::String::toUpper(
|
||||
mEntries.at(static_cast<unsigned int>(mCursor)).name))
|
||||
.x();
|
||||
const float limit = mSize.x() - mHorizontalMargin * 2.0f;
|
||||
|
||||
if (textLength > limit) {
|
||||
|
@ -371,7 +366,8 @@ void TextListComponent<T>::update(int deltaTime)
|
|||
mMarqueeTime -= maxTime;
|
||||
|
||||
mMarqueeOffset = static_cast<int>(Math::Scroll::loop(delay, scrollTime + returnTime,
|
||||
static_cast<float>(mMarqueeTime), scrollLength + returnLength));
|
||||
static_cast<float>(mMarqueeTime),
|
||||
scrollLength + returnLength));
|
||||
|
||||
if (mMarqueeOffset > (scrollLength - (limit - returnLength)))
|
||||
mMarqueeOffset2 = static_cast<int>(mMarqueeOffset - (scrollLength + returnLength));
|
||||
|
@ -394,8 +390,7 @@ void TextListComponent<T>::add(const std::string& name, const T& obj, unsigned i
|
|||
static_cast<IList<TextListData, T>*>(this)->add(entry);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void TextListComponent<T>::onCursorChanged(const CursorState& state)
|
||||
template <typename T> void TextListComponent<T>::onCursorChanged(const CursorState& state)
|
||||
{
|
||||
mMarqueeOffset = 0;
|
||||
mMarqueeOffset2 = 0;
|
||||
|
@ -407,7 +402,9 @@ void TextListComponent<T>::onCursorChanged(const CursorState& state)
|
|||
|
||||
template <typename T>
|
||||
void TextListComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view, const std::string& element, unsigned int properties)
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties)
|
||||
{
|
||||
GuiComponent::applyTheme(theme, view, element, properties);
|
||||
|
||||
|
@ -424,8 +421,8 @@ void TextListComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
if (elem->has("selectorColorEnd"))
|
||||
setSelectorColorEnd(elem->get<unsigned int>("selectorColorEnd"));
|
||||
if (elem->has("selectorGradientType"))
|
||||
setSelectorColorGradientHorizontal(!(elem->get<std::string>
|
||||
("selectorGradientType").compare("horizontal")));
|
||||
setSelectorColorGradientHorizontal(
|
||||
!(elem->get<std::string>("selectorGradientType").compare("horizontal")));
|
||||
if (elem->has("selectedColor"))
|
||||
setSelectedColor(elem->get<unsigned int>("selectedColor"));
|
||||
if (elem->has("primaryColor"))
|
||||
|
@ -435,8 +432,8 @@ void TextListComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
}
|
||||
|
||||
setFont(Font::getFromTheme(elem, properties, mFont));
|
||||
const float selectorHeight = std::max(mFont->getHeight(1.0),
|
||||
static_cast<float>(mFont->getSize())) * mLineSpacing;
|
||||
const float selectorHeight =
|
||||
std::max(mFont->getHeight(1.0), static_cast<float>(mFont->getSize())) * mLineSpacing;
|
||||
setSelectorHeight(selectorHeight);
|
||||
|
||||
if (properties & ALIGNMENT) {
|
||||
|
@ -453,8 +450,8 @@ void TextListComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
}
|
||||
if (elem->has("horizontalMargin")) {
|
||||
mHorizontalMargin = elem->get<float>("horizontalMargin") *
|
||||
(this->mParent ? this->mParent->getSize().x() :
|
||||
static_cast<float>(Renderer::getScreenWidth()));
|
||||
(this->mParent ? this->mParent->getSize().x() :
|
||||
static_cast<float>(Renderer::getScreenWidth()));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -468,7 +465,7 @@ void TextListComponent<T>::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
|||
setSelectorHeight(elem->get<float>("selectorHeight") * Renderer::getScreenHeight());
|
||||
if (elem->has("selectorOffsetY")) {
|
||||
float scale = this->mParent ? this->mParent->getSize().y() :
|
||||
static_cast<float>(Renderer::getScreenHeight());
|
||||
static_cast<float>(Renderer::getScreenHeight());
|
||||
setSelectorOffsetY(elem->get<float>("selectorOffsetY") * scale);
|
||||
}
|
||||
else {
|
||||
|
|
|
@ -8,39 +8,38 @@
|
|||
|
||||
#include "components/VideoComponent.h"
|
||||
|
||||
#include "resources/ResourceManager.h"
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "ThemeData.h"
|
||||
#include "Window.h"
|
||||
#include "resources/ResourceManager.h"
|
||||
#include "utils/FileSystemUtil.h"
|
||||
|
||||
#include <SDL2/SDL_timer.h>
|
||||
|
||||
#define SCREENSAVER_FADE_IN_TIME 1100
|
||||
#define MEDIA_VIEWER_FADE_IN_TIME 600
|
||||
|
||||
VideoComponent::VideoComponent(
|
||||
Window* window)
|
||||
: GuiComponent(window),
|
||||
mWindow(window),
|
||||
mStaticImage(window),
|
||||
mVideoHeight(0),
|
||||
mVideoWidth(0),
|
||||
mStartDelayed(false),
|
||||
mIsPlaying(false),
|
||||
mIsActuallyPlaying(false),
|
||||
mPause(false),
|
||||
mShowing(false),
|
||||
mDisable(false),
|
||||
mMediaViewerMode(false),
|
||||
mScreensaverActive(false),
|
||||
mScreensaverMode(false),
|
||||
mGameLaunched(false),
|
||||
mBlockPlayer(false),
|
||||
mTargetIsMax(false),
|
||||
mFadeIn(1.0),
|
||||
mTargetSize(0, 0),
|
||||
mVideoAreaPos(0, 0),
|
||||
mVideoAreaSize(0, 0)
|
||||
VideoComponent::VideoComponent(Window* window)
|
||||
: GuiComponent(window)
|
||||
, mWindow(window)
|
||||
, mStaticImage(window)
|
||||
, mVideoHeight(0)
|
||||
, mVideoWidth(0)
|
||||
, mStartDelayed(false)
|
||||
, mIsPlaying(false)
|
||||
, mIsActuallyPlaying(false)
|
||||
, mPause(false)
|
||||
, mShowing(false)
|
||||
, mDisable(false)
|
||||
, mMediaViewerMode(false)
|
||||
, mScreensaverActive(false)
|
||||
, mScreensaverMode(false)
|
||||
, mGameLaunched(false)
|
||||
, mBlockPlayer(false)
|
||||
, mTargetIsMax(false)
|
||||
, mFadeIn(1.0)
|
||||
, mTargetSize(0, 0)
|
||||
, mVideoAreaPos(0, 0)
|
||||
, mVideoAreaSize(0, 0)
|
||||
{
|
||||
// Setup the default configuration.
|
||||
mConfig.showSnapshotDelay = false;
|
||||
|
@ -79,11 +78,6 @@ bool VideoComponent::setVideo(std::string path)
|
|||
return false;
|
||||
}
|
||||
|
||||
void VideoComponent::setDefaultVideo()
|
||||
{
|
||||
setVideo(mConfig.defaultVideoPath);
|
||||
}
|
||||
|
||||
void VideoComponent::setImage(std::string path)
|
||||
{
|
||||
// Check that the image has changed.
|
||||
|
@ -94,21 +88,6 @@ void VideoComponent::setImage(std::string path)
|
|||
mStaticImagePath = path;
|
||||
}
|
||||
|
||||
void VideoComponent::setScreensaverMode(bool isScreensaver)
|
||||
{
|
||||
mScreensaverMode = isScreensaver;
|
||||
}
|
||||
|
||||
void VideoComponent::setMediaViewerMode(bool isMediaViewer)
|
||||
{
|
||||
mMediaViewerMode = isMediaViewer;
|
||||
}
|
||||
|
||||
void VideoComponent::setOpacity(unsigned char opacity)
|
||||
{
|
||||
mOpacity = opacity;
|
||||
}
|
||||
|
||||
void VideoComponent::onShow()
|
||||
{
|
||||
mBlockPlayer = false;
|
||||
|
@ -192,21 +171,6 @@ void VideoComponent::topWindow(bool isTop)
|
|||
manageState();
|
||||
}
|
||||
|
||||
void VideoComponent::onOriginChanged()
|
||||
{
|
||||
mStaticImage.setOrigin(mOrigin);
|
||||
}
|
||||
|
||||
void VideoComponent::onPositionChanged()
|
||||
{
|
||||
mStaticImage.setPosition(mPosition);
|
||||
}
|
||||
|
||||
void VideoComponent::onSizeChanged()
|
||||
{
|
||||
mStaticImage.onSizeChanged();
|
||||
}
|
||||
|
||||
void VideoComponent::render(const Transform4x4f& parentTrans)
|
||||
{
|
||||
if (!isVisible())
|
||||
|
@ -237,19 +201,22 @@ void VideoComponent::renderSnapshot(const Transform4x4f& parentTrans)
|
|||
// set to start playing the video immediately. Although this may seem a bit inconsistent it
|
||||
// simply looks better than leaving an empty space where the video would have been located.
|
||||
if (mWindow->getGuiStackSize() > 1 || (mConfig.showSnapshotNoVideo && mVideoPath.empty()) ||
|
||||
(mStartDelayed && mConfig.showSnapshotDelay)) {
|
||||
(mStartDelayed && mConfig.showSnapshotDelay)) {
|
||||
mStaticImage.setOpacity(mOpacity);
|
||||
mStaticImage.render(parentTrans);
|
||||
}
|
||||
}
|
||||
|
||||
void VideoComponent::applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties)
|
||||
void VideoComponent::applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties)
|
||||
{
|
||||
using namespace ThemeFlags;
|
||||
|
||||
GuiComponent::applyTheme(theme, view, element, (properties ^ ThemeFlags::SIZE) |
|
||||
((properties & (ThemeFlags::SIZE | POSITION)) ? ORIGIN : 0));
|
||||
GuiComponent::applyTheme(theme, view, element,
|
||||
(properties ^ ThemeFlags::SIZE) |
|
||||
((properties & (ThemeFlags::SIZE | POSITION)) ? ORIGIN : 0));
|
||||
|
||||
const ThemeData::ThemeElement* elem = theme->getElement(view, element, "video");
|
||||
|
||||
|
@ -257,8 +224,8 @@ void VideoComponent::applyTheme(const std::shared_ptr<ThemeData>& theme, const s
|
|||
return;
|
||||
|
||||
Vector2f scale = getParent() ? getParent()->getSize() :
|
||||
Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
Vector2f(static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()));
|
||||
|
||||
if (properties & ThemeFlags::SIZE) {
|
||||
if (elem->has("size")) {
|
||||
|
@ -308,12 +275,12 @@ void VideoComponent::update(int deltaTime)
|
|||
// Fade in videos, the time period is a bit different between the screensaver,
|
||||
// media viewer and gamelist view.
|
||||
if (mScreensaverMode && mFadeIn < 1.0f) {
|
||||
mFadeIn = Math::clamp(mFadeIn + (deltaTime /
|
||||
static_cast<float>(SCREENSAVER_FADE_IN_TIME)), 0.0f, 1.0f);
|
||||
mFadeIn = Math::clamp(mFadeIn + (deltaTime / static_cast<float>(SCREENSAVER_FADE_IN_TIME)),
|
||||
0.0f, 1.0f);
|
||||
}
|
||||
else if (mMediaViewerMode && mFadeIn < 1.0f) {
|
||||
mFadeIn = Math::clamp(mFadeIn + (deltaTime /
|
||||
static_cast<float>(MEDIA_VIEWER_FADE_IN_TIME)), 0.0f, 1.0f);
|
||||
mFadeIn = Math::clamp(mFadeIn + (deltaTime / static_cast<float>(MEDIA_VIEWER_FADE_IN_TIME)),
|
||||
0.0f, 1.0f);
|
||||
}
|
||||
else if (mFadeIn < 1.0f) {
|
||||
mFadeIn = Math::clamp(mFadeIn + 0.01f, 0.0f, 1.0f);
|
||||
|
|
|
@ -9,8 +9,8 @@
|
|||
#ifndef ES_CORE_COMPONENTS_VIDEO_COMPONENT_H
|
||||
#define ES_CORE_COMPONENTS_VIDEO_COMPONENT_H
|
||||
|
||||
#include "components/ImageComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
#include "components/ImageComponent.h"
|
||||
|
||||
#include <string>
|
||||
|
||||
|
@ -34,15 +34,15 @@ public:
|
|||
// Loads the video at the given filepath.
|
||||
bool setVideo(std::string path);
|
||||
// Configures the component to show the default video.
|
||||
void setDefaultVideo();
|
||||
void setDefaultVideo() { setVideo(mConfig.defaultVideoPath); }
|
||||
// Loads a static image that is displayed if the video cannot be played.
|
||||
void setImage(std::string path);
|
||||
// Sets whether we're in media viewer mode.
|
||||
void setMediaViewerMode(bool isMediaViewer);
|
||||
void setMediaViewerMode(bool isMediaViewer) { mMediaViewerMode = isMediaViewer; }
|
||||
// Sets whether we're in screensaver mode.
|
||||
void setScreensaverMode(bool isScreensaver);
|
||||
void setScreensaverMode(bool isScreensaver) { mScreensaverMode = isScreensaver; }
|
||||
// Set the opacity for the embedded static image.
|
||||
void setOpacity(unsigned char opacity) override;
|
||||
void setOpacity(unsigned char opacity) override { mOpacity = opacity; }
|
||||
|
||||
virtual void onShow() override;
|
||||
virtual void onHide() override;
|
||||
|
@ -57,15 +57,17 @@ public:
|
|||
virtual void topWindow(bool isTop) override;
|
||||
|
||||
// These functions update the embedded static image.
|
||||
void onOriginChanged() override;
|
||||
void onPositionChanged() override;
|
||||
void onSizeChanged() override;
|
||||
void onOriginChanged() override { mStaticImage.setOrigin(mOrigin); }
|
||||
void onPositionChanged() override { mStaticImage.setPosition(mPosition); }
|
||||
void onSizeChanged() override { mStaticImage.onSizeChanged(); }
|
||||
|
||||
void render(const Transform4x4f& parentTrans) override;
|
||||
void renderSnapshot(const Transform4x4f& parentTrans);
|
||||
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme, const std::string& view,
|
||||
const std::string& element, unsigned int properties) override;
|
||||
virtual void applyTheme(const std::shared_ptr<ThemeData>& theme,
|
||||
const std::string& view,
|
||||
const std::string& element,
|
||||
unsigned int properties) override;
|
||||
|
||||
virtual std::vector<HelpPrompt> getHelpPrompts() override;
|
||||
|
||||
|
@ -76,24 +78,24 @@ public:
|
|||
// zero, no resizing. This can be set before or after a video is loaded.
|
||||
// setMaxSize() and setResize() are mutually exclusive.
|
||||
virtual void setResize(float width, float height) override = 0;
|
||||
inline void setResize(const Vector2f& size) { setResize(size.x(), size.y()); }
|
||||
void setResize(const Vector2f& size) { setResize(size.x(), size.y()); }
|
||||
|
||||
// Resize the video to be as large as possible but fit within a box of this size.
|
||||
// This can be set before or after a video is loaded.
|
||||
// Never breaks the aspect ratio. setMaxSize() and setResize() are mutually exclusive.
|
||||
virtual void setMaxSize(float width, float height) = 0;
|
||||
inline void setMaxSize(const Vector2f& size) { setMaxSize(size.x(), size.y()); }
|
||||
void setMaxSize(const Vector2f& size) { setMaxSize(size.x(), size.y()); }
|
||||
|
||||
private:
|
||||
// Start the video immediately.
|
||||
virtual void startVideo() {};
|
||||
virtual void startVideo() {}
|
||||
// Stop the video.
|
||||
virtual void stopVideo() {};
|
||||
virtual void stopVideo() {}
|
||||
// Pause the video when a game has been launched.
|
||||
virtual void pauseVideo() {};
|
||||
virtual void pauseVideo() {}
|
||||
// Handle looping of the video. Must be called periodically.
|
||||
virtual void handleLooping() {};
|
||||
virtual void updatePlayer() {};
|
||||
virtual void handleLooping() {}
|
||||
virtual void updatePlayer() {}
|
||||
|
||||
// Start the video after any configured delay.
|
||||
void startVideoWithDelay();
|
||||
|
|
|
@ -8,48 +8,44 @@
|
|||
|
||||
#include "components/VideoFFmpegComponent.h"
|
||||
|
||||
#include "resources/TextureResource.h"
|
||||
#include "AudioManager.h"
|
||||
#include "Settings.h"
|
||||
#include "Window.h"
|
||||
#include "resources/TextureResource.h"
|
||||
|
||||
#define DEBUG_VIDEO false
|
||||
|
||||
VideoFFmpegComponent::VideoFFmpegComponent(
|
||||
Window* window)
|
||||
: VideoComponent(window),
|
||||
mFrameProcessingThread(nullptr),
|
||||
mFormatContext(nullptr),
|
||||
mVideoStream(nullptr),
|
||||
mAudioStream(nullptr),
|
||||
mVideoCodec(nullptr),
|
||||
mAudioCodec(nullptr),
|
||||
mVideoCodecContext(nullptr),
|
||||
mAudioCodecContext(nullptr),
|
||||
mVBufferSrcContext(nullptr),
|
||||
mVBufferSinkContext(nullptr),
|
||||
mVFilterGraph(nullptr),
|
||||
mVFilterInputs(nullptr),
|
||||
mVFilterOutputs(nullptr),
|
||||
mABufferSrcContext(nullptr),
|
||||
mABufferSinkContext(nullptr),
|
||||
mAFilterGraph(nullptr),
|
||||
mAFilterInputs(nullptr),
|
||||
mAFilterOutputs(nullptr),
|
||||
mVideoTimeBase(0.0l),
|
||||
mVideoTargetQueueSize(0),
|
||||
mAudioTargetQueueSize(0),
|
||||
mAccumulatedTime(0),
|
||||
mStartTimeAccumulation(false),
|
||||
mDecodedFrame(false),
|
||||
mEndOfVideo(false)
|
||||
VideoFFmpegComponent::VideoFFmpegComponent(Window* window)
|
||||
: VideoComponent(window)
|
||||
, mFrameProcessingThread(nullptr)
|
||||
, mFormatContext(nullptr)
|
||||
, mVideoStream(nullptr)
|
||||
, mAudioStream(nullptr)
|
||||
, mVideoCodec(nullptr)
|
||||
, mAudioCodec(nullptr)
|
||||
, mVideoCodecContext(nullptr)
|
||||
, mAudioCodecContext(nullptr)
|
||||
, mVBufferSrcContext(nullptr)
|
||||
, mVBufferSinkContext(nullptr)
|
||||
, mVFilterGraph(nullptr)
|
||||
, mVFilterInputs(nullptr)
|
||||
, mVFilterOutputs(nullptr)
|
||||
, mABufferSrcContext(nullptr)
|
||||
, mABufferSinkContext(nullptr)
|
||||
, mAFilterGraph(nullptr)
|
||||
, mAFilterInputs(nullptr)
|
||||
, mAFilterOutputs(nullptr)
|
||||
, mVideoTimeBase(0.0l)
|
||||
, mVideoTargetQueueSize(0)
|
||||
, mAudioTargetQueueSize(0)
|
||||
, mAccumulatedTime(0)
|
||||
, mStartTimeAccumulation(false)
|
||||
, mDecodedFrame(false)
|
||||
, mEndOfVideo(false)
|
||||
{
|
||||
}
|
||||
|
||||
VideoFFmpegComponent::~VideoFFmpegComponent()
|
||||
{
|
||||
stopVideo();
|
||||
}
|
||||
VideoFFmpegComponent::~VideoFFmpegComponent() { stopVideo(); }
|
||||
|
||||
void VideoFFmpegComponent::setResize(float width, float height)
|
||||
{
|
||||
|
@ -96,7 +92,6 @@ void VideoFFmpegComponent::resize()
|
|||
|
||||
mSize[1] = std::round(mSize[1]);
|
||||
mSize[0] = (mSize[1] / textureSize.y()) * textureSize.x();
|
||||
|
||||
}
|
||||
else {
|
||||
// If both components are set, we just stretch.
|
||||
|
@ -127,8 +122,8 @@ void VideoFFmpegComponent::render(const Transform4x4f& parentTrans)
|
|||
unsigned int color;
|
||||
if (mDecodedFrame && mFadeIn < 1) {
|
||||
const unsigned int fadeIn = static_cast<int>(mFadeIn * 255.0f);
|
||||
color = Renderer::convertRGBAToABGR((fadeIn << 24) |
|
||||
(fadeIn << 16) | (fadeIn << 8) | 255);
|
||||
color =
|
||||
Renderer::convertRGBAToABGR((fadeIn << 24) | (fadeIn << 16) | (fadeIn << 8) | 255);
|
||||
}
|
||||
else {
|
||||
color = 0xFFFFFFFF;
|
||||
|
@ -139,13 +134,16 @@ void VideoFFmpegComponent::render(const Transform4x4f& parentTrans)
|
|||
// Render the black rectangle behind the video.
|
||||
if (mVideoRectangleCoords.size() == 4) {
|
||||
Renderer::drawRect(mVideoRectangleCoords[0], mVideoRectangleCoords[1],
|
||||
mVideoRectangleCoords[2], mVideoRectangleCoords[3], 0x000000FF, 0x000000FF);
|
||||
mVideoRectangleCoords[2], mVideoRectangleCoords[3], // Line break.
|
||||
0x000000FF, 0x000000FF);
|
||||
}
|
||||
|
||||
// clang-format off
|
||||
vertices[0] = { { 0.0f , 0.0f }, { 0.0f, 0.0f }, color };
|
||||
vertices[1] = { { 0.0f , mSize.y() }, { 0.0f, 1.0f }, color };
|
||||
vertices[2] = { { mSize.x(), 0.0f }, { 1.0f, 0.0f }, color };
|
||||
vertices[3] = { { mSize.x(), mSize.y() }, { 1.0f, 1.0f }, color };
|
||||
// clang-format on
|
||||
|
||||
// Round vertices.
|
||||
for (int i = 0; i < 4; i++)
|
||||
|
@ -167,8 +165,8 @@ void VideoFFmpegComponent::render(const Transform4x4f& parentTrans)
|
|||
int pictureHeight = 0;
|
||||
|
||||
if (pictureSize > 0) {
|
||||
tempPictureRGBA.insert(tempPictureRGBA.begin(),
|
||||
mOutputPicture.pictureRGBA.begin(), mOutputPicture.pictureRGBA.end());
|
||||
tempPictureRGBA.insert(tempPictureRGBA.begin(), mOutputPicture.pictureRGBA.begin(),
|
||||
mOutputPicture.pictureRGBA.end());
|
||||
pictureWidth = mOutputPicture.width;
|
||||
pictureHeight = mOutputPicture.height;
|
||||
|
||||
|
@ -188,14 +186,14 @@ void VideoFFmpegComponent::render(const Transform4x4f& parentTrans)
|
|||
|
||||
mTexture->bind();
|
||||
|
||||
#if defined(USE_OPENGL_21)
|
||||
#if defined(USE_OPENGL_21)
|
||||
// Render scanlines if this option is enabled. However, if this is the media viewer
|
||||
// or the video screensaver, then skip this as the scanline rendering is then handled
|
||||
// in those modules as a postprocessing step.
|
||||
if ((!mScreensaverMode && !mMediaViewerMode) &&
|
||||
Settings::getInstance()->getBool("GamelistVideoScanlines"))
|
||||
Settings::getInstance()->getBool("GamelistVideoScanlines"))
|
||||
vertices[0].shaders = Renderer::SHADER_SCANLINES;
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Render it.
|
||||
Renderer::setMatrix(trans);
|
||||
|
@ -215,16 +213,17 @@ void VideoFFmpegComponent::updatePlayer()
|
|||
mAudioMutex.lock();
|
||||
if (mOutputAudio.size()) {
|
||||
AudioManager::getInstance()->processStream(&mOutputAudio.at(0),
|
||||
static_cast<unsigned int>(mOutputAudio.size()));
|
||||
static_cast<unsigned int>(mOutputAudio.size()));
|
||||
mOutputAudio.clear();
|
||||
}
|
||||
mAudioMutex.unlock();
|
||||
|
||||
if (mIsActuallyPlaying && mStartTimeAccumulation) {
|
||||
mAccumulatedTime += static_cast<double>(
|
||||
std::chrono::duration_cast<std::chrono::nanoseconds>
|
||||
(std::chrono::high_resolution_clock::now() -
|
||||
mTimeReference).count()) / 1000000000.0l;
|
||||
mAccumulatedTime +=
|
||||
static_cast<double>(std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
std::chrono::high_resolution_clock::now() - mTimeReference)
|
||||
.count()) /
|
||||
1000000000.0l;
|
||||
}
|
||||
|
||||
mTimeReference = std::chrono::high_resolution_clock::now();
|
||||
|
@ -232,7 +231,7 @@ void VideoFFmpegComponent::updatePlayer()
|
|||
if (!mFrameProcessingThread) {
|
||||
AudioManager::getInstance()->unmuteStream();
|
||||
mFrameProcessingThread =
|
||||
std::make_unique<std::thread>(&VideoFFmpegComponent::frameProcessing, this);
|
||||
std::make_unique<std::thread>(&VideoFFmpegComponent::frameProcessing, this);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -291,7 +290,7 @@ bool VideoFFmpegComponent::setupVideoFilters()
|
|||
|
||||
if (!(mVFilterGraph = avfilter_graph_alloc())) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): "
|
||||
"Couldn't allocate filter graph";
|
||||
"Couldn't allocate filter graph";
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -302,14 +301,14 @@ bool VideoFFmpegComponent::setupVideoFilters()
|
|||
const AVFilter* bufferSrc = avfilter_get_by_name("buffer");
|
||||
if (!bufferSrc) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): "
|
||||
"Couldn't find \"buffer\" filter";
|
||||
"Couldn't find \"buffer\" filter";
|
||||
return false;
|
||||
}
|
||||
|
||||
const AVFilter* bufferSink = avfilter_get_by_name("buffersink");
|
||||
if (!bufferSink) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): "
|
||||
"Couldn't find \"buffersink\" filter";
|
||||
"Couldn't find \"buffersink\" filter";
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -322,41 +321,30 @@ bool VideoFFmpegComponent::setupVideoFilters()
|
|||
width += 16 - modulo;
|
||||
|
||||
std::string filterArguments =
|
||||
"width=" + std::to_string(width) + ":" +
|
||||
"height=" + std::to_string(height) +
|
||||
":pix_fmt=" + av_get_pix_fmt_name(mVideoCodecContext->pix_fmt) +
|
||||
":time_base=" + std::to_string(mVideoStream->time_base.num) + "/" +
|
||||
std::to_string(mVideoStream->time_base.den) +
|
||||
":sar=" + std::to_string(mVideoCodecContext->sample_aspect_ratio.num) + "/" +
|
||||
std::to_string(mVideoCodecContext->sample_aspect_ratio.den);
|
||||
"width=" + std::to_string(width) + ":" + "height=" + std::to_string(height) +
|
||||
":pix_fmt=" + av_get_pix_fmt_name(mVideoCodecContext->pix_fmt) +
|
||||
":time_base=" + std::to_string(mVideoStream->time_base.num) + "/" +
|
||||
std::to_string(mVideoStream->time_base.den) +
|
||||
":sar=" + std::to_string(mVideoCodecContext->sample_aspect_ratio.num) + "/" +
|
||||
std::to_string(mVideoCodecContext->sample_aspect_ratio.den);
|
||||
|
||||
returnValue = avfilter_graph_create_filter(
|
||||
&mVBufferSrcContext,
|
||||
bufferSrc,
|
||||
"in",
|
||||
filterArguments.c_str(),
|
||||
nullptr,
|
||||
mVFilterGraph);
|
||||
returnValue = avfilter_graph_create_filter(&mVBufferSrcContext, bufferSrc, "in",
|
||||
filterArguments.c_str(), nullptr, mVFilterGraph);
|
||||
|
||||
if (returnValue < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): "
|
||||
"Couldn't create filter instance for buffer source: " <<
|
||||
av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
"Couldn't create filter instance for buffer source: "
|
||||
<< av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
returnValue = avfilter_graph_create_filter(
|
||||
&mVBufferSinkContext,
|
||||
bufferSink,
|
||||
"out",
|
||||
nullptr,
|
||||
nullptr,
|
||||
mVFilterGraph);
|
||||
returnValue = avfilter_graph_create_filter(&mVBufferSinkContext, bufferSink, "out", nullptr,
|
||||
nullptr, mVFilterGraph);
|
||||
|
||||
if (returnValue < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): "
|
||||
"Couldn't create filter instance for buffer sink: " <<
|
||||
av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
"Couldn't create filter instance for buffer sink: "
|
||||
<< av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -376,34 +364,32 @@ bool VideoFFmpegComponent::setupVideoFilters()
|
|||
// Whether to upscale the frame rate to 60 FPS.
|
||||
if (Settings::getInstance()->getBool("VideoUpscaleFrameRate")) {
|
||||
if (modulo > 0)
|
||||
filterDescription =
|
||||
"scale=width=" + std::to_string(width) +
|
||||
":height=" + std::to_string(height) +
|
||||
",fps=fps=60,";
|
||||
filterDescription = "scale=width=" + std::to_string(width) +
|
||||
":height=" + std::to_string(height) + ",fps=fps=60,";
|
||||
else
|
||||
filterDescription = "fps=fps=60,";
|
||||
|
||||
// The "framerate" filter is a more advanced way to upscale the frame rate using
|
||||
// interpolation. However I have not been able to get this to work with slice
|
||||
// threading so the performance is poor. As such it's disabled for now.
|
||||
// if (modulo > 0)
|
||||
// filterDescription =
|
||||
// "scale=width=" + std::to_string(width) +
|
||||
// ":height=" + std::to_string(height) +
|
||||
// ",framerate=fps=60,";
|
||||
// else
|
||||
// filterDescription = "framerate=fps=60,";
|
||||
// if (modulo > 0)
|
||||
// filterDescription =
|
||||
// "scale=width=" + std::to_string(width) +
|
||||
// ":height=" + std::to_string(height) +
|
||||
// ",framerate=fps=60,";
|
||||
// else
|
||||
// filterDescription = "framerate=fps=60,";
|
||||
}
|
||||
|
||||
filterDescription += "format=pix_fmts=" + std::string(av_get_pix_fmt_name(outPixFormats[0]));
|
||||
|
||||
returnValue = avfilter_graph_parse_ptr(mVFilterGraph, filterDescription.c_str(),
|
||||
&mVFilterInputs, &mVFilterOutputs, nullptr);
|
||||
&mVFilterInputs, &mVFilterOutputs, nullptr);
|
||||
|
||||
if (returnValue < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): "
|
||||
"Couldn't add graph filter: " <<
|
||||
av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
"Couldn't add graph filter: "
|
||||
<< av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -411,8 +397,8 @@ bool VideoFFmpegComponent::setupVideoFilters()
|
|||
|
||||
if (returnValue < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupVideoFilters(): "
|
||||
"Couldn't configure graph: " <<
|
||||
av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
"Couldn't configure graph: "
|
||||
<< av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -431,7 +417,7 @@ bool VideoFFmpegComponent::setupAudioFilters()
|
|||
|
||||
if (!(mAFilterGraph = avfilter_graph_alloc())) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): "
|
||||
"Couldn't allocate filter graph";
|
||||
"Couldn't allocate filter graph";
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -442,55 +428,45 @@ bool VideoFFmpegComponent::setupAudioFilters()
|
|||
const AVFilter* bufferSrc = avfilter_get_by_name("abuffer");
|
||||
if (!bufferSrc) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): "
|
||||
"Couldn't find \"abuffer\" filter";
|
||||
"Couldn't find \"abuffer\" filter";
|
||||
return false;
|
||||
}
|
||||
|
||||
const AVFilter* bufferSink = avfilter_get_by_name("abuffersink");
|
||||
if (!bufferSink) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): "
|
||||
"Couldn't find \"abuffersink\" filter";
|
||||
"Couldn't find \"abuffersink\" filter";
|
||||
return false;
|
||||
}
|
||||
|
||||
char channelLayout[512];
|
||||
av_get_channel_layout_string(channelLayout, sizeof(channelLayout),
|
||||
mAudioCodecContext->channels, mAudioCodecContext->channel_layout);
|
||||
av_get_channel_layout_string(channelLayout, sizeof(channelLayout), mAudioCodecContext->channels,
|
||||
mAudioCodecContext->channel_layout);
|
||||
|
||||
std::string filterArguments =
|
||||
"time_base=" + std::to_string(mAudioStream->time_base.num) + "/" +
|
||||
std::to_string(mAudioStream->time_base.den) +
|
||||
":sample_rate=" + std::to_string(mAudioCodecContext->sample_rate) +
|
||||
":sample_fmt=" + av_get_sample_fmt_name(mAudioCodecContext->sample_fmt) +
|
||||
":channel_layout=" + channelLayout;
|
||||
"time_base=" + std::to_string(mAudioStream->time_base.num) + "/" +
|
||||
std::to_string(mAudioStream->time_base.den) +
|
||||
":sample_rate=" + std::to_string(mAudioCodecContext->sample_rate) +
|
||||
":sample_fmt=" + av_get_sample_fmt_name(mAudioCodecContext->sample_fmt) +
|
||||
":channel_layout=" + channelLayout;
|
||||
|
||||
returnValue = avfilter_graph_create_filter(
|
||||
&mABufferSrcContext,
|
||||
bufferSrc,
|
||||
"in",
|
||||
filterArguments.c_str(),
|
||||
nullptr,
|
||||
mAFilterGraph);
|
||||
returnValue = avfilter_graph_create_filter(&mABufferSrcContext, bufferSrc, "in",
|
||||
filterArguments.c_str(), nullptr, mAFilterGraph);
|
||||
|
||||
if (returnValue < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): "
|
||||
"Couldn't create filter instance for buffer source: " <<
|
||||
av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
"Couldn't create filter instance for buffer source: "
|
||||
<< av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
returnValue = avfilter_graph_create_filter(
|
||||
&mABufferSinkContext,
|
||||
bufferSink,
|
||||
"out",
|
||||
nullptr,
|
||||
nullptr,
|
||||
mAFilterGraph);
|
||||
returnValue = avfilter_graph_create_filter(&mABufferSinkContext, bufferSink, "out", nullptr,
|
||||
nullptr, mAFilterGraph);
|
||||
|
||||
if (returnValue < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): "
|
||||
"Couldn't create filter instance for buffer sink: " <<
|
||||
av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
"Couldn't create filter instance for buffer sink: "
|
||||
<< av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -506,18 +482,18 @@ bool VideoFFmpegComponent::setupAudioFilters()
|
|||
mAFilterOutputs->next = nullptr;
|
||||
|
||||
std::string filterDescription =
|
||||
"aresample=" + std::to_string(outSampleRates[0]) + "," +
|
||||
"aformat=sample_fmts=" + av_get_sample_fmt_name(outSampleFormats[0]) +
|
||||
":channel_layouts=stereo,"
|
||||
"asetnsamples=n=1024:p=0";
|
||||
"aresample=" + std::to_string(outSampleRates[0]) + "," +
|
||||
"aformat=sample_fmts=" + av_get_sample_fmt_name(outSampleFormats[0]) +
|
||||
":channel_layouts=stereo,"
|
||||
"asetnsamples=n=1024:p=0";
|
||||
|
||||
returnValue = avfilter_graph_parse_ptr(mAFilterGraph, filterDescription.c_str(),
|
||||
&mAFilterInputs, &mAFilterOutputs, nullptr);
|
||||
&mAFilterInputs, &mAFilterOutputs, nullptr);
|
||||
|
||||
if (returnValue < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): "
|
||||
"Couldn't add graph filter: " <<
|
||||
av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
"Couldn't add graph filter: "
|
||||
<< av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -525,8 +501,8 @@ bool VideoFFmpegComponent::setupAudioFilters()
|
|||
|
||||
if (returnValue < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::setupAudioFilters(): "
|
||||
"Couldn't configure graph: " <<
|
||||
av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
"Couldn't configure graph: "
|
||||
<< av_make_error_string(errorMessage, sizeof(errorMessage), returnValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -544,20 +520,20 @@ void VideoFFmpegComponent::readFrames()
|
|||
return;
|
||||
|
||||
if (mVideoCodecContext && mFormatContext) {
|
||||
if (mVideoFrameQueue.size() < mVideoTargetQueueSize || (mAudioStreamIndex >= 0 &&
|
||||
mAudioFrameQueue.size() < mAudioTargetQueueSize)) {
|
||||
if (mVideoFrameQueue.size() < mVideoTargetQueueSize ||
|
||||
(mAudioStreamIndex >= 0 && mAudioFrameQueue.size() < mAudioTargetQueueSize)) {
|
||||
while ((readFrameReturn = av_read_frame(mFormatContext, mPacket)) >= 0) {
|
||||
if (mPacket->stream_index == mVideoStreamIndex) {
|
||||
if (!avcodec_send_packet(mVideoCodecContext, mPacket) &&
|
||||
!avcodec_receive_frame(mVideoCodecContext, mVideoFrame)) {
|
||||
!avcodec_receive_frame(mVideoCodecContext, mVideoFrame)) {
|
||||
|
||||
// We have a video frame that needs conversion to RGBA format.
|
||||
int returnValue = av_buffersrc_add_frame_flags(mVBufferSrcContext,
|
||||
mVideoFrame, AV_BUFFERSRC_FLAG_KEEP_REF);
|
||||
int returnValue = av_buffersrc_add_frame_flags(
|
||||
mVBufferSrcContext, mVideoFrame, AV_BUFFERSRC_FLAG_KEEP_REF);
|
||||
|
||||
if (returnValue < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::readFrames(): "
|
||||
"Couldn't add video frame to buffer source";
|
||||
"Couldn't add video frame to buffer source";
|
||||
}
|
||||
|
||||
av_packet_unref(mPacket);
|
||||
|
@ -566,15 +542,15 @@ void VideoFFmpegComponent::readFrames()
|
|||
}
|
||||
else if (mPacket->stream_index == mAudioStreamIndex) {
|
||||
if (!avcodec_send_packet(mAudioCodecContext, mPacket) &&
|
||||
!avcodec_receive_frame(mAudioCodecContext, mAudioFrame)) {
|
||||
!avcodec_receive_frame(mAudioCodecContext, mAudioFrame)) {
|
||||
|
||||
// We have an audio frame that needs conversion and resampling.
|
||||
int returnValue = av_buffersrc_add_frame_flags(mABufferSrcContext,
|
||||
mAudioFrame, AV_BUFFERSRC_FLAG_KEEP_REF);
|
||||
int returnValue = av_buffersrc_add_frame_flags(
|
||||
mABufferSrcContext, mAudioFrame, AV_BUFFERSRC_FLAG_KEEP_REF);
|
||||
|
||||
if (returnValue < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::readFrames(): "
|
||||
"Couldn't add audio frame to buffer source";
|
||||
"Couldn't add audio frame to buffer source";
|
||||
}
|
||||
|
||||
av_packet_unref(mPacket);
|
||||
|
@ -606,21 +582,20 @@ void VideoFFmpegComponent::getProcessedFrames()
|
|||
// (picture) should be displayed. The packet DTS value is used for the basis of
|
||||
// the calculation as per the recommendation in the FFmpeg documentation for
|
||||
// the av_read_frame function.
|
||||
double pts = static_cast<double>(mVideoFrameResampled->pkt_dts) *
|
||||
av_q2d(mVideoStream->time_base);
|
||||
double pts =
|
||||
static_cast<double>(mVideoFrameResampled->pkt_dts) * av_q2d(mVideoStream->time_base);
|
||||
|
||||
// Needs to be adjusted if changing the rate?
|
||||
double frameDuration = static_cast<double>(mVideoFrameResampled->pkt_duration) *
|
||||
av_q2d(mVideoStream->time_base);
|
||||
av_q2d(mVideoStream->time_base);
|
||||
|
||||
currFrame.pts = pts;
|
||||
currFrame.frameDuration = frameDuration;
|
||||
|
||||
int bufferSize = mVideoFrameResampled->width * mVideoFrameResampled->height * 4;
|
||||
|
||||
currFrame.frameRGBA.insert(currFrame.frameRGBA.begin(),
|
||||
&mVideoFrameResampled->data[0][0],
|
||||
&mVideoFrameResampled->data[0][bufferSize]);
|
||||
currFrame.frameRGBA.insert(currFrame.frameRGBA.begin(), &mVideoFrameResampled->data[0][0],
|
||||
&mVideoFrameResampled->data[0][bufferSize]);
|
||||
|
||||
mVideoFrameQueue.push(currFrame);
|
||||
av_frame_unref(mVideoFrameResampled);
|
||||
|
@ -629,8 +604,8 @@ void VideoFFmpegComponent::getProcessedFrames()
|
|||
// Audio frames.
|
||||
// When resampling, we may not always get a frame returned from the sink as there may not
|
||||
// have been enough data available to the filter.
|
||||
while (mAudioCodecContext && av_buffersink_get_frame(mABufferSinkContext,
|
||||
mAudioFrameResampled) >= 0) {
|
||||
while (mAudioCodecContext &&
|
||||
av_buffersink_get_frame(mABufferSinkContext, mAudioFrameResampled) >= 0) {
|
||||
|
||||
AudioFrame currFrame;
|
||||
AVRational timeBase;
|
||||
|
@ -644,11 +619,11 @@ void VideoFFmpegComponent::getProcessedFrames()
|
|||
currFrame.pts = pts;
|
||||
|
||||
int bufferSize = mAudioFrameResampled->nb_samples * mAudioFrameResampled->channels *
|
||||
av_get_bytes_per_sample(AV_SAMPLE_FMT_FLT);
|
||||
av_get_bytes_per_sample(AV_SAMPLE_FMT_FLT);
|
||||
|
||||
currFrame.resampledData.insert(currFrame.resampledData.begin(),
|
||||
&mAudioFrameResampled->data[0][0],
|
||||
&mAudioFrameResampled->data[0][bufferSize]);
|
||||
&mAudioFrameResampled->data[0][0],
|
||||
&mAudioFrameResampled->data[0][bufferSize]);
|
||||
|
||||
mAudioFrameQueue.push(currFrame);
|
||||
av_frame_unref(mAudioFrameResampled);
|
||||
|
@ -674,22 +649,21 @@ void VideoFFmpegComponent::outputFrames()
|
|||
if (mAudioFrameQueue.front().pts < mAccumulatedTime + AUDIO_BUFFER) {
|
||||
// Enable only when needed, as this generates a lot of debug output.
|
||||
if (DEBUG_VIDEO) {
|
||||
LOG(LogDebug) << "Processing audio frame with PTS: " <<
|
||||
mAudioFrameQueue.front().pts;
|
||||
LOG(LogDebug) << "Total audio frames processed / audio frame queue size: " <<
|
||||
mAudioFrameCount << " / " << std::to_string(mAudioFrameQueue.size());
|
||||
LOG(LogDebug) << "Processing audio frame with PTS: "
|
||||
<< mAudioFrameQueue.front().pts;
|
||||
LOG(LogDebug) << "Total audio frames processed / audio frame queue size: "
|
||||
<< mAudioFrameCount << " / "
|
||||
<< std::to_string(mAudioFrameQueue.size());
|
||||
}
|
||||
|
||||
bool outputSound = false;
|
||||
|
||||
if ((!mScreensaverMode && !mMediaViewerMode) &&
|
||||
Settings::getInstance()->getBool("GamelistVideoAudio"))
|
||||
Settings::getInstance()->getBool("GamelistVideoAudio"))
|
||||
outputSound = true;
|
||||
else if (mScreensaverMode && Settings::getInstance()->
|
||||
getBool("ScreensaverVideoAudio"))
|
||||
else if (mScreensaverMode && Settings::getInstance()->getBool("ScreensaverVideoAudio"))
|
||||
outputSound = true;
|
||||
else if (mMediaViewerMode && Settings::getInstance()->
|
||||
getBool("MediaViewerVideoAudio"))
|
||||
else if (mMediaViewerMode && Settings::getInstance()->getBool("MediaViewerVideoAudio"))
|
||||
outputSound = true;
|
||||
|
||||
if (outputSound) {
|
||||
|
@ -697,8 +671,8 @@ void VideoFFmpegComponent::outputFrames()
|
|||
mAudioMutex.lock();
|
||||
|
||||
mOutputAudio.insert(mOutputAudio.end(),
|
||||
mAudioFrameQueue.front().resampledData.begin(),
|
||||
mAudioFrameQueue.front().resampledData.end());
|
||||
mAudioFrameQueue.front().resampledData.begin(),
|
||||
mAudioFrameQueue.front().resampledData.end());
|
||||
|
||||
mAudioMutex.unlock();
|
||||
}
|
||||
|
@ -717,10 +691,11 @@ void VideoFFmpegComponent::outputFrames()
|
|||
if (mVideoFrameQueue.front().pts < mAccumulatedTime) {
|
||||
// Enable only when needed, as this generates a lot of debug output.
|
||||
if (DEBUG_VIDEO) {
|
||||
LOG(LogDebug) << "Processing video frame with PTS: " <<
|
||||
mVideoFrameQueue.front().pts;
|
||||
LOG(LogDebug) << "Total video frames processed / video frame queue size: " <<
|
||||
mVideoFrameCount << " / " << std::to_string(mVideoFrameQueue.size());
|
||||
LOG(LogDebug) << "Processing video frame with PTS: "
|
||||
<< mVideoFrameQueue.front().pts;
|
||||
LOG(LogDebug) << "Total video frames processed / video frame queue size: "
|
||||
<< mVideoFrameCount << " / "
|
||||
<< std::to_string(mVideoFrameQueue.size());
|
||||
}
|
||||
|
||||
mPictureMutex.lock();
|
||||
|
@ -734,7 +709,7 @@ void VideoFFmpegComponent::outputFrames()
|
|||
// rates close to, or at, the rendering frame rate, for example 59.94 and 60 FPS.
|
||||
if (mDecodedFrame && !mOutputPicture.hasBeenRendered) {
|
||||
double timeDifference = mAccumulatedTime - mVideoFrameQueue.front().pts -
|
||||
mVideoFrameQueue.front().frameDuration * 2.0l;
|
||||
mVideoFrameQueue.front().frameDuration * 2.0l;
|
||||
if (timeDifference < mVideoFrameQueue.front().frameDuration) {
|
||||
mPictureMutex.unlock();
|
||||
break;
|
||||
|
@ -743,8 +718,8 @@ void VideoFFmpegComponent::outputFrames()
|
|||
|
||||
mOutputPicture.pictureRGBA.clear();
|
||||
mOutputPicture.pictureRGBA.insert(mOutputPicture.pictureRGBA.begin(),
|
||||
mVideoFrameQueue.front().frameRGBA.begin(),
|
||||
mVideoFrameQueue.front().frameRGBA.end());
|
||||
mVideoFrameQueue.front().frameRGBA.begin(),
|
||||
mVideoFrameQueue.front().frameRGBA.end());
|
||||
|
||||
mOutputPicture.width = mVideoFrameQueue.front().width;
|
||||
mOutputPicture.height = mVideoFrameQueue.front().height;
|
||||
|
@ -802,10 +777,10 @@ void VideoFFmpegComponent::calculateBlackRectangle()
|
|||
rectHeight = mSize.y();
|
||||
}
|
||||
// Populate the rectangle coordinates to be used in render().
|
||||
mVideoRectangleCoords.push_back(std::round(mVideoAreaPos.x() -
|
||||
rectWidth * mOrigin.x()));
|
||||
mVideoRectangleCoords.push_back(std::round(mVideoAreaPos.y() -
|
||||
rectHeight * mOrigin.y()));
|
||||
mVideoRectangleCoords.push_back(
|
||||
std::round(mVideoAreaPos.x() - rectWidth * mOrigin.x()));
|
||||
mVideoRectangleCoords.push_back(
|
||||
std::round(mVideoAreaPos.y() - rectHeight * mOrigin.y()));
|
||||
mVideoRectangleCoords.push_back(std::round(rectWidth));
|
||||
mVideoRectangleCoords.push_back(std::round(rectHeight));
|
||||
}
|
||||
|
@ -852,14 +827,16 @@ void VideoFFmpegComponent::startVideo()
|
|||
// File operations and basic setup.
|
||||
|
||||
if (avformat_open_input(&mFormatContext, filePath.c_str(), nullptr, nullptr)) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't open video file \"" <<
|
||||
mVideoPath << "\"";
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): "
|
||||
"Couldn't open video file \""
|
||||
<< mVideoPath << "\"";
|
||||
return;
|
||||
}
|
||||
|
||||
if (avformat_find_stream_info(mFormatContext, nullptr)) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't read stream information"
|
||||
"from video file \"" << mVideoPath << "\"";
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): "
|
||||
"Couldn't read stream information from video file \""
|
||||
<< mVideoPath << "\"";
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -868,12 +845,13 @@ void VideoFFmpegComponent::startVideo()
|
|||
|
||||
// Video stream setup.
|
||||
|
||||
mVideoStreamIndex = av_find_best_stream(
|
||||
mFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
|
||||
mVideoStreamIndex =
|
||||
av_find_best_stream(mFormatContext, AVMEDIA_TYPE_VIDEO, -1, -1, nullptr, 0);
|
||||
|
||||
if (mVideoStreamIndex < 0) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't retrieve video stream "
|
||||
"for file \"" << mVideoPath << "\"";
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): "
|
||||
"Couldn't retrieve video stream for file \""
|
||||
<< mVideoPath << "\"";
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -884,16 +862,18 @@ void VideoFFmpegComponent::startVideo()
|
|||
mVideoCodec = const_cast<AVCodec*>(avcodec_find_decoder(mVideoStream->codecpar->codec_id));
|
||||
|
||||
if (!mVideoCodec) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't find a suitable video "
|
||||
"codec for file \"" << mVideoPath << "\"";
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): "
|
||||
"Couldn't find a suitable video codec for file \""
|
||||
<< mVideoPath << "\"";
|
||||
return;
|
||||
}
|
||||
|
||||
mVideoCodecContext = avcodec_alloc_context3(mVideoCodec);
|
||||
|
||||
if (!mVideoCodec) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't allocate video "
|
||||
"codec context for file \"" << mVideoPath << "\"";
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): "
|
||||
"Couldn't allocate video codec context for file \""
|
||||
<< mVideoPath << "\"";
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -901,35 +881,38 @@ void VideoFFmpegComponent::startVideo()
|
|||
mVideoCodecContext->flags |= AV_CODEC_FLAG_TRUNCATED;
|
||||
|
||||
if (avcodec_parameters_to_context(mVideoCodecContext, mVideoStream->codecpar)) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't fill the video "
|
||||
"codec context parameters for file \"" << mVideoPath << "\"";
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): "
|
||||
"Couldn't fill the video codec context parameters for file \""
|
||||
<< mVideoPath << "\"";
|
||||
return;
|
||||
}
|
||||
|
||||
if (avcodec_open2(mVideoCodecContext, mVideoCodec, nullptr)) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't initialize the "
|
||||
"video codec context for file \"" << mVideoPath << "\"";
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): "
|
||||
"Couldn't initialize the video codec context for file \""
|
||||
<< mVideoPath << "\"";
|
||||
return;
|
||||
}
|
||||
|
||||
// Audio stream setup, optional as some videos may not have any audio tracks.
|
||||
|
||||
mAudioStreamIndex = av_find_best_stream(
|
||||
mFormatContext, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
|
||||
mAudioStreamIndex =
|
||||
av_find_best_stream(mFormatContext, AVMEDIA_TYPE_AUDIO, -1, -1, nullptr, 0);
|
||||
|
||||
if (mAudioStreamIndex < 0) {
|
||||
LOG(LogDebug) << "VideoFFmpegComponent::startVideo(): Couldn't retrieve audio stream "
|
||||
"for file \"" << mVideoPath << "\"";
|
||||
LOG(LogDebug) << "VideoFFmpegComponent::startVideo(): "
|
||||
"Couldn't retrieve audio stream for file \""
|
||||
<< mVideoPath << "\"";
|
||||
}
|
||||
|
||||
if (mAudioStreamIndex >= 0) {
|
||||
mAudioStream = mFormatContext->streams[mAudioStreamIndex];
|
||||
mAudioCodec = const_cast<AVCodec*>(
|
||||
avcodec_find_decoder(mAudioStream->codecpar->codec_id));
|
||||
mAudioCodec =
|
||||
const_cast<AVCodec*>(avcodec_find_decoder(mAudioStream->codecpar->codec_id));
|
||||
|
||||
if (!mAudioCodec) {
|
||||
LOG(LogError) << "Couldn't find a suitable audio codec for file \"" <<
|
||||
mVideoPath << "\"";
|
||||
LOG(LogError) << "Couldn't find a suitable audio codec for file \"" << mVideoPath
|
||||
<< "\"";
|
||||
return;
|
||||
}
|
||||
|
||||
|
@ -943,14 +926,16 @@ void VideoFFmpegComponent::startVideo()
|
|||
mAudioCodecContext->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
|
||||
|
||||
if (avcodec_parameters_to_context(mAudioCodecContext, mAudioStream->codecpar)) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't fill the audio "
|
||||
"codec context parameters for file \"" << mVideoPath << "\"";
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): "
|
||||
"Couldn't fill the audio codec context parameters for file \""
|
||||
<< mVideoPath << "\"";
|
||||
return;
|
||||
}
|
||||
|
||||
if (avcodec_open2(mAudioCodecContext, mAudioCodec, nullptr)) {
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): Couldn't initialize the "
|
||||
"audio codec context for file \"" << mVideoPath << "\"";
|
||||
LOG(LogError) << "VideoFFmpegComponent::startVideo(): "
|
||||
"Couldn't initialize the audio codec context for file \""
|
||||
<< mVideoPath << "\"";
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
@ -959,7 +944,7 @@ void VideoFFmpegComponent::startVideo()
|
|||
|
||||
// Set some reasonable target queue sizes (buffers).
|
||||
mVideoTargetQueueSize = static_cast<int>(av_q2d(mVideoStream->avg_frame_rate) / 2.0l);
|
||||
if (mAudioStreamIndex >=0)
|
||||
if (mAudioStreamIndex >= 0)
|
||||
mAudioTargetQueueSize = mAudioStream->codecpar->channels * 15;
|
||||
else
|
||||
mAudioTargetQueueSize = 30;
|
||||
|
@ -1035,7 +1020,7 @@ void VideoFFmpegComponent::handleLooping()
|
|||
// If the screensaver video swap time is set to 0, it means we should
|
||||
// skip to the next game when the video has finished playing.
|
||||
if (mScreensaverMode &&
|
||||
Settings::getInstance()->getInt("ScreensaverSwapVideoTimeout") == 0) {
|
||||
Settings::getInstance()->getInt("ScreensaverSwapVideoTimeout") == 0) {
|
||||
mWindow->screensaverTriggerNextGame();
|
||||
}
|
||||
else {
|
||||
|
|
|
@ -14,8 +14,7 @@
|
|||
|
||||
#include "VideoComponent.h"
|
||||
|
||||
extern "C"
|
||||
{
|
||||
extern "C" {
|
||||
#include <libavcodec/avcodec.h>
|
||||
#include <libavfilter/avfilter.h>
|
||||
#include <libavfilter/buffersink.h>
|
||||
|
@ -89,8 +88,8 @@ private:
|
|||
AVFormatContext* mFormatContext;
|
||||
AVStream* mVideoStream;
|
||||
AVStream* mAudioStream;
|
||||
AVCodec *mVideoCodec;
|
||||
AVCodec *mAudioCodec;
|
||||
AVCodec* mVideoCodec;
|
||||
AVCodec* mAudioCodec;
|
||||
AVCodecContext* mVideoCodecContext;
|
||||
AVCodecContext* mAudioCodecContext;
|
||||
int mVideoStreamIndex;
|
||||
|
|
|
@ -9,10 +9,10 @@
|
|||
#if defined(_RPI_)
|
||||
#include "components/VideoOmxComponent.h"
|
||||
|
||||
#include "renderers/Renderer.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "AudioManager.h"
|
||||
#include "Settings.h"
|
||||
#include "renderers/Renderer.h"
|
||||
#include "utils/StringUtil.h"
|
||||
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
|
@ -21,18 +21,19 @@
|
|||
class VolumeControl
|
||||
{
|
||||
public:
|
||||
static std::shared_ptr<VolumeControl> & getInstance();
|
||||
static std::shared_ptr<VolumeControl>& getInstance();
|
||||
int getVolume() const;
|
||||
};
|
||||
|
||||
VideoOmxComponent::VideoOmxComponent(Window* window) :
|
||||
VideoComponent(window),
|
||||
mPlayerPid(-1)
|
||||
VideoOmxComponent::VideoOmxComponent(Window* window)
|
||||
: VideoComponent(window)
|
||||
, mPlayerPid(-1)
|
||||
{
|
||||
}
|
||||
|
||||
VideoOmxComponent::~VideoOmxComponent()
|
||||
{
|
||||
// Stop video when destroyed.
|
||||
stopVideo();
|
||||
}
|
||||
|
||||
|
@ -79,8 +80,8 @@ void VideoOmxComponent::startVideo()
|
|||
mPlayingVideoPath = mVideoPath;
|
||||
|
||||
// Disable AudioManager so video can play, in case we're requesting ALSA.
|
||||
if (Utils::String::startsWith(Settings::getInstance()->
|
||||
getString("OMXAudioDev").c_str(), "alsa"))
|
||||
if (Utils::String::startsWith(Settings::getInstance()->getString("OMXAudioDev").c_str(),
|
||||
"alsa"))
|
||||
AudioManager::getInstance()->deinit();
|
||||
|
||||
// Start the player process.
|
||||
|
@ -112,66 +113,84 @@ void VideoOmxComponent::startVideo()
|
|||
const int x2 = static_cast<int>(x1 + mSize.x());
|
||||
const int y2 = static_cast<int>(y1 + mSize.y());
|
||||
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
|
||||
}
|
||||
break;
|
||||
} break;
|
||||
|
||||
case 1: {
|
||||
const int x1 = static_cast<int>(Renderer::getWindowWidth() -
|
||||
Renderer::getScreenOffsetY() - y - mSize.y());
|
||||
const int x1 =
|
||||
static_cast<int>(Renderer::getWindowWidth() -
|
||||
Renderer::getScreenOffsetY() - y - mSize.y());
|
||||
const int y1 = static_cast<int>(Renderer::getScreenOffsetX() + x);
|
||||
const int x2 = static_cast<int>(x1 + mSize.y());
|
||||
const int y2 = static_cast<int>(y1 + mSize.x());
|
||||
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
|
||||
}
|
||||
break;
|
||||
} break;
|
||||
|
||||
case 2: {
|
||||
const int x1 = static_cast<int>(Renderer::getWindowWidth() -
|
||||
Renderer::getScreenOffsetX() - x - mSize.x());
|
||||
const int y1 = static_cast<int>(Renderer::getWindowHeight() -
|
||||
Renderer::getScreenOffsetY() - y - mSize.y());
|
||||
const int x1 =
|
||||
static_cast<int>(Renderer::getWindowWidth() -
|
||||
Renderer::getScreenOffsetX() - x - mSize.x());
|
||||
const int y1 =
|
||||
static_cast<int>(Renderer::getWindowHeight() -
|
||||
Renderer::getScreenOffsetY() - y - mSize.y());
|
||||
const int x2 = static_cast<int>(x1 + mSize.x());
|
||||
const int y2 = static_cast<int>(y1 + mSize.y());
|
||||
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
|
||||
}
|
||||
break;
|
||||
} break;
|
||||
|
||||
case 3: {
|
||||
const int x1 = static_cast<int>(Renderer::getScreenOffsetY() + y);
|
||||
const int y1 = static_cast<int>(Renderer::getWindowHeight() -
|
||||
Renderer::getScreenOffsetX() - x - mSize.x());
|
||||
const int y1 =
|
||||
static_cast<int>(Renderer::getWindowHeight() -
|
||||
Renderer::getScreenOffsetX() - x - mSize.x());
|
||||
const int x2 = static_cast<int>(x1 + mSize.y());
|
||||
const int y2 = static_cast<int>(y1 + mSize.x());
|
||||
sprintf(buf1, "%d,%d,%d,%d", x1, y1, x2, y2);
|
||||
}
|
||||
break;
|
||||
} break;
|
||||
}
|
||||
|
||||
// Rotate the video.
|
||||
switch (Renderer::getScreenRotate()) {
|
||||
case 0: { sprintf(buf2, "%d", static_cast<int>(0)); } break;
|
||||
case 1: { sprintf(buf2, "%d", static_cast<int>(90)); } break;
|
||||
case 2: { sprintf(buf2, "%d", static_cast<int>(180)); } break;
|
||||
case 3: { sprintf(buf2, "%d", static_cast<int>(270)); } break;
|
||||
case 0: {
|
||||
sprintf(buf2, "%d", static_cast<int>(0));
|
||||
} break;
|
||||
case 1: {
|
||||
sprintf(buf2, "%d", static_cast<int>(90));
|
||||
} break;
|
||||
case 2: {
|
||||
sprintf(buf2, "%d", static_cast<int>(180));
|
||||
} break;
|
||||
case 3: {
|
||||
sprintf(buf2, "%d", static_cast<int>(270));
|
||||
} break;
|
||||
}
|
||||
|
||||
// We need to specify the layer of 10000 or above to ensure the video is
|
||||
// displayed on top of our SDL display.
|
||||
const char* argv[] = { "", "--layer", "10010", "--loop", "--no-osd",
|
||||
"--aspect-mode", "letterbox", "--vol", "0", "-o", "both",
|
||||
"--win", buf1, "--orientation", buf2, "", "", "", "", "", "",
|
||||
"", "", "", "", "", NULL };
|
||||
const char* argv[] = { "", "--layer",
|
||||
"10010", "--loop",
|
||||
"--no-osd", "--aspect-mode",
|
||||
"letterbox", "--vol",
|
||||
"0", "-o",
|
||||
"both", "--win",
|
||||
buf1, "--orientation",
|
||||
buf2, "",
|
||||
"", "",
|
||||
"", "",
|
||||
"", "",
|
||||
"", "",
|
||||
"", "",
|
||||
NULL };
|
||||
|
||||
// Check if we want to mute the audio.
|
||||
if ((!Settings::getInstance()->getBool("GamelistVideoAudio") ||
|
||||
static_cast<float>(VolumeControl::getInstance()->getVolume()) == 0) ||
|
||||
(!Settings::getInstance()->getBool("ScreensaverVideoAudio") &&
|
||||
mScreensaverMode)) {
|
||||
static_cast<float>(VolumeControl::getInstance()->getVolume()) == 0) ||
|
||||
(!Settings::getInstance()->getBool("ScreensaverVideoAudio") &&
|
||||
mScreensaverMode)) {
|
||||
argv[8] = "-1000000";
|
||||
}
|
||||
else {
|
||||
float percentVolume =
|
||||
static_cast<float>(VolumeControl::getInstance()->getVolume());
|
||||
static_cast<float>(VolumeControl::getInstance()->getVolume());
|
||||
int OMXVolume = static_cast<int>((percentVolume - 98) * 105);
|
||||
argv[8] = std::to_string(OMXVolume).c_str();
|
||||
}
|
||||
|
|
|
@ -10,12 +10,12 @@
|
|||
|
||||
#include "components/VideoVlcComponent.h"
|
||||
|
||||
#include "renderers/Renderer.h"
|
||||
#include "resources/TextureResource.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "AudioManager.h"
|
||||
#include "Settings.h"
|
||||
#include "Window.h"
|
||||
#include "renderers/Renderer.h"
|
||||
#include "resources/TextureResource.h"
|
||||
#include "utils/StringUtil.h"
|
||||
|
||||
#if defined(__APPLE__)
|
||||
#include "utils/FileSystemUtil.h"
|
||||
|
@ -26,19 +26,18 @@
|
|||
#include <vlc/vlc.h>
|
||||
|
||||
#if defined(_WIN64)
|
||||
#include <cstring>
|
||||
#include <codecvt>
|
||||
#include <cstring>
|
||||
#endif
|
||||
|
||||
libvlc_instance_t* VideoVlcComponent::mVLC = nullptr;
|
||||
|
||||
VideoVlcComponent::VideoVlcComponent(
|
||||
Window* window)
|
||||
: VideoComponent(window),
|
||||
mMediaPlayer(nullptr),
|
||||
mMedia(nullptr),
|
||||
mContext({}),
|
||||
mHasSetAudioVolume(false)
|
||||
VideoVlcComponent::VideoVlcComponent(Window* window)
|
||||
: VideoComponent(window)
|
||||
, mMediaPlayer(nullptr)
|
||||
, mMedia(nullptr)
|
||||
, mContext({})
|
||||
, mHasSetAudioVolume(false)
|
||||
{
|
||||
// Get an empty texture for rendering the video.
|
||||
mTexture = TextureResource::get("");
|
||||
|
@ -86,7 +85,7 @@ void VideoVlcComponent::setupVLC()
|
|||
if (!mVLC) {
|
||||
const char* args[] = { "--quiet" };
|
||||
|
||||
#if defined(__APPLE__)
|
||||
#if defined(__APPLE__)
|
||||
// It's required to set the VLC_PLUGIN_PATH variable on macOS, or the libVLC
|
||||
// initialization will fail (with no error message).
|
||||
std::string vlcPluginPath = Utils::FileSystem::getExePath() + "/plugins";
|
||||
|
@ -94,7 +93,7 @@ void VideoVlcComponent::setupVLC()
|
|||
setenv("VLC_PLUGIN_PATH", vlcPluginPath.c_str(), 1);
|
||||
else
|
||||
setenv("VLC_PLUGIN_PATH", "/Applications/VLC.app/Contents/MacOS/plugins/", 1);
|
||||
#endif
|
||||
#endif
|
||||
|
||||
mVLC = libvlc_new(1, args);
|
||||
}
|
||||
|
@ -105,7 +104,8 @@ void VideoVlcComponent::setupContext()
|
|||
if (!mContext.valid) {
|
||||
// Create an RGBA surface to render the video into.
|
||||
mContext.surface = SDL_CreateRGBSurface(SDL_SWSURFACE, static_cast<int>(mVideoWidth),
|
||||
static_cast<int>(mVideoHeight), 32, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff);
|
||||
static_cast<int>(mVideoHeight), 32, 0xff000000,
|
||||
0x00ff0000, 0x0000ff00, 0x000000ff);
|
||||
mContext.mutex = SDL_CreateMutex();
|
||||
mContext.valid = true;
|
||||
resize();
|
||||
|
@ -148,7 +148,6 @@ void VideoVlcComponent::resize()
|
|||
|
||||
mSize[1] = std::round(mSize[1]);
|
||||
mSize[0] = (mSize[1] / textureSize.y()) * textureSize.x();
|
||||
|
||||
}
|
||||
else {
|
||||
// If both components are set, we just stretch.
|
||||
|
@ -196,8 +195,8 @@ void VideoVlcComponent::render(const Transform4x4f& parentTrans)
|
|||
unsigned int color;
|
||||
if (mFadeIn < 1) {
|
||||
const unsigned int fadeIn = static_cast<int>(mFadeIn * 255.0f);
|
||||
color = Renderer::convertRGBAToABGR((fadeIn << 24) |
|
||||
(fadeIn << 16) | (fadeIn << 8) | 255);
|
||||
color =
|
||||
Renderer::convertRGBAToABGR((fadeIn << 24) | (fadeIn << 16) | (fadeIn << 8) | 255);
|
||||
}
|
||||
else {
|
||||
color = 0xFFFFFFFF;
|
||||
|
@ -209,13 +208,16 @@ void VideoVlcComponent::render(const Transform4x4f& parentTrans)
|
|||
// Render the black rectangle behind the video.
|
||||
if (mVideoRectangleCoords.size() == 4) {
|
||||
Renderer::drawRect(mVideoRectangleCoords[0], mVideoRectangleCoords[1],
|
||||
mVideoRectangleCoords[2], mVideoRectangleCoords[3], 0x000000FF, 0x000000FF);
|
||||
mVideoRectangleCoords[2], mVideoRectangleCoords[3], // Line break.
|
||||
0x000000FF, 0x000000FF);
|
||||
}
|
||||
|
||||
// clang-format off
|
||||
vertices[0] = { { 0.0f , 0.0f }, { 0.0f, 0.0f }, color };
|
||||
vertices[1] = { { 0.0f , mSize.y() }, { 0.0f, 1.0f }, color };
|
||||
vertices[2] = { { mSize.x(), 0.0f }, { 1.0f, 0.0f }, color };
|
||||
vertices[3] = { { mSize.x(), mSize.y() }, { 1.0f, 1.0f }, color };
|
||||
// clang-format on
|
||||
|
||||
// Round vertices.
|
||||
for (int i = 0; i < 4; i++)
|
||||
|
@ -223,17 +225,18 @@ void VideoVlcComponent::render(const Transform4x4f& parentTrans)
|
|||
|
||||
// Build a texture for the video frame.
|
||||
mTexture->initFromPixels(reinterpret_cast<unsigned char*>(mContext.surface->pixels),
|
||||
mContext.surface->w, mContext.surface->h);
|
||||
mContext.surface->w, mContext.surface->h);
|
||||
mTexture->bind();
|
||||
|
||||
#if defined(USE_OPENGL_21)
|
||||
#if defined(USE_OPENGL_21)
|
||||
// Render scanlines if this option is enabled. However, if this is the media viewer
|
||||
// or the video screensaver, then skip this as the scanline rendering is then handled
|
||||
// in those modules as a postprocessing step.
|
||||
if ((!mScreensaverMode && !mMediaViewerMode) &&
|
||||
Settings::getInstance()->getBool("GamelistVideoScanlines"))
|
||||
Settings::getInstance()->getBool("GamelistVideoScanlines")) {
|
||||
vertices[0].shaders = Renderer::SHADER_SCANLINES;
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// Render it.
|
||||
Renderer::setMatrix(trans);
|
||||
|
@ -283,10 +286,10 @@ void VideoVlcComponent::calculateBlackRectangle()
|
|||
rectHeight = mSize.y();
|
||||
}
|
||||
// Populate the rectangle coordinates to be used in render().
|
||||
mVideoRectangleCoords.push_back(std::round(mVideoAreaPos.x() -
|
||||
rectWidth * mOrigin.x()));
|
||||
mVideoRectangleCoords.push_back(std::round(mVideoAreaPos.y() -
|
||||
rectHeight * mOrigin.y()));
|
||||
mVideoRectangleCoords.push_back(
|
||||
std::round(mVideoAreaPos.x() - rectWidth * mOrigin.x()));
|
||||
mVideoRectangleCoords.push_back(
|
||||
std::round(mVideoAreaPos.y() - rectHeight * mOrigin.y()));
|
||||
mVideoRectangleCoords.push_back(std::round(rectWidth));
|
||||
mVideoRectangleCoords.push_back(std::round(rectHeight));
|
||||
}
|
||||
|
@ -310,20 +313,18 @@ void VideoVlcComponent::setAudioVolume()
|
|||
bool outputSound = false;
|
||||
|
||||
if ((!mScreensaverMode && !mMediaViewerMode) &&
|
||||
Settings::getInstance()->getBool("GamelistVideoAudio"))
|
||||
Settings::getInstance()->getBool("GamelistVideoAudio"))
|
||||
outputSound = true;
|
||||
else if (mScreensaverMode && Settings::getInstance()->
|
||||
getBool("ScreensaverVideoAudio"))
|
||||
else if (mScreensaverMode && Settings::getInstance()->getBool("ScreensaverVideoAudio"))
|
||||
outputSound = true;
|
||||
else if (mMediaViewerMode && Settings::getInstance()->
|
||||
getBool("MediaViewerVideoAudio"))
|
||||
else if (mMediaViewerMode && Settings::getInstance()->getBool("MediaViewerVideoAudio"))
|
||||
outputSound = true;
|
||||
|
||||
if (outputSound) {
|
||||
if (libvlc_audio_get_mute(mMediaPlayer) == 1)
|
||||
libvlc_audio_set_mute(mMediaPlayer, 0);
|
||||
libvlc_audio_set_volume(mMediaPlayer,
|
||||
Settings::getInstance()->getInt("SoundVolumeVideos"));
|
||||
Settings::getInstance()->getInt("SoundVolumeVideos"));
|
||||
}
|
||||
else {
|
||||
libvlc_audio_set_volume(mMediaPlayer, 0);
|
||||
|
@ -339,11 +340,11 @@ void VideoVlcComponent::startVideo()
|
|||
mVideoWidth = 0;
|
||||
mVideoHeight = 0;
|
||||
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
std::string path(Utils::String::replace(mVideoPath, "/", "\\"));
|
||||
#else
|
||||
#else
|
||||
std::string path(mVideoPath);
|
||||
#endif
|
||||
#endif
|
||||
// Make sure we have a video path.
|
||||
if (mVLC && (path.size() > 0)) {
|
||||
// Set the video that we are going to be playing so we don't attempt to restart it.
|
||||
|
@ -356,8 +357,8 @@ void VideoVlcComponent::startVideo()
|
|||
int parseResult;
|
||||
|
||||
// Asynchronous media parsing.
|
||||
libvlc_event_attach(libvlc_media_event_manager(mMedia),
|
||||
libvlc_MediaParsedChanged, VlcMediaParseCallback, 0);
|
||||
libvlc_event_attach(libvlc_media_event_manager(mMedia), libvlc_MediaParsedChanged,
|
||||
VlcMediaParseCallback, 0);
|
||||
parseResult = libvlc_media_parse_with_options(mMedia, libvlc_media_parse_local, -1);
|
||||
|
||||
if (!parseResult) {
|
||||
|
@ -382,8 +383,8 @@ void VideoVlcComponent::startVideo()
|
|||
}
|
||||
libvlc_media_tracks_release(tracks, track_count);
|
||||
libvlc_media_parse_stop(mMedia);
|
||||
libvlc_event_detach(libvlc_media_event_manager(mMedia),
|
||||
libvlc_MediaParsedChanged, VlcMediaParseCallback, 0);
|
||||
libvlc_event_detach(libvlc_media_event_manager(mMedia), libvlc_MediaParsedChanged,
|
||||
VlcMediaParseCallback, 0);
|
||||
|
||||
// Make sure we found a valid video track.
|
||||
if ((mVideoWidth > 0) && (mVideoHeight > 0)) {
|
||||
|
@ -395,32 +396,36 @@ void VideoVlcComponent::startVideo()
|
|||
// The code below enables the libVLC audio output to be processed inside ES-DE.
|
||||
// Unfortunately this causes excessive stuttering for some reason that I still
|
||||
// don't understand, so at the moment this code is disabled.
|
||||
// auto audioFormatCallback = [](void **data, char *format,
|
||||
// unsigned *rate, unsigned *channels) -> int {
|
||||
// format = const_cast<char*>("F32L");
|
||||
// *rate = 48000;
|
||||
// *channels = 2;
|
||||
// return 0;
|
||||
// };
|
||||
//
|
||||
// libvlc_audio_set_format_callbacks(mMediaPlayer,
|
||||
// audioFormatCallback, nullptr);
|
||||
//
|
||||
// auto audioPlayCallback = [](void* data, const void* samples,
|
||||
// unsigned count, int64_t pts) {
|
||||
// AudioManager::getInstance()->processStream(samples, count);
|
||||
// };
|
||||
//
|
||||
// libvlc_audio_set_callbacks(mMediaPlayer, audioPlayCallback,
|
||||
// nullptr, nullptr, nullptr, nullptr, this);
|
||||
// auto audioFormatCallback = [](void **data, char *format,
|
||||
// unsigned *rate, unsigned *channels) -> int {
|
||||
// format = const_cast<char*>("F32L");
|
||||
// *rate = 48000;
|
||||
// *channels = 2;
|
||||
// return 0;
|
||||
// };
|
||||
//
|
||||
// libvlc_audio_set_format_callbacks(mMediaPlayer,
|
||||
// audioFormatCallback, nullptr);
|
||||
//
|
||||
// auto audioPlayCallback = [](void* data, const void*
|
||||
// samples,
|
||||
// unsigned count, int64_t pts) {
|
||||
// AudioManager::getInstance()->processStream(samples,
|
||||
// count);
|
||||
// };
|
||||
//
|
||||
// libvlc_audio_set_callbacks(mMediaPlayer,
|
||||
// audioPlayCallback,
|
||||
// nullptr, nullptr, nullptr, nullptr, this);
|
||||
|
||||
libvlc_video_set_format(mMediaPlayer, "RGBA", static_cast<int>(mVideoWidth),
|
||||
static_cast<int>(mVideoHeight), static_cast<int>(mVideoWidth * 4));
|
||||
static_cast<int>(mVideoHeight),
|
||||
static_cast<int>(mVideoWidth * 4));
|
||||
|
||||
// Lock video memory as a preparation for rendering a frame.
|
||||
auto videoLockCallback = [](void* data, void** p_pixels) -> void* {
|
||||
struct VideoContext* videoContext =
|
||||
reinterpret_cast<struct VideoContext*>(data);
|
||||
reinterpret_cast<struct VideoContext*>(data);
|
||||
SDL_LockMutex(videoContext->mutex);
|
||||
SDL_LockSurface(videoContext->surface);
|
||||
*p_pixels = videoContext->surface->pixels;
|
||||
|
@ -428,15 +433,15 @@ void VideoVlcComponent::startVideo()
|
|||
};
|
||||
|
||||
// Unlock the video memory after rendering a frame.
|
||||
auto videoUnlockCallback = [](void* data, void*, void *const*) {
|
||||
auto videoUnlockCallback = [](void* data, void*, void* const*) {
|
||||
struct VideoContext* videoContext =
|
||||
reinterpret_cast<struct VideoContext*>(data);
|
||||
reinterpret_cast<struct VideoContext*>(data);
|
||||
SDL_UnlockSurface(videoContext->surface);
|
||||
SDL_UnlockMutex(videoContext->mutex);
|
||||
};
|
||||
|
||||
libvlc_video_set_callbacks(mMediaPlayer, videoLockCallback,
|
||||
videoUnlockCallback, nullptr, reinterpret_cast<void*>(&mContext));
|
||||
libvlc_video_set_callbacks(mMediaPlayer, videoLockCallback, videoUnlockCallback,
|
||||
nullptr, reinterpret_cast<void*>(&mContext));
|
||||
|
||||
libvlc_media_player_play(mMediaPlayer);
|
||||
|
||||
|
@ -517,7 +522,7 @@ void VideoVlcComponent::handleLooping()
|
|||
// If the screensaver video swap time is set to 0, it means we should
|
||||
// skip to the next game when the video has finished playing.
|
||||
if (mScreensaverMode &&
|
||||
Settings::getInstance()->getInt("ScreensaverSwapVideoTimeout") == 0) {
|
||||
Settings::getInstance()->getInt("ScreensaverSwapVideoTimeout") == 0) {
|
||||
mWindow->screensaverTriggerNextGame();
|
||||
}
|
||||
else {
|
||||
|
@ -527,13 +532,13 @@ void VideoVlcComponent::handleLooping()
|
|||
bool outputSound = false;
|
||||
|
||||
if ((!mScreensaverMode && !mMediaViewerMode) &&
|
||||
Settings::getInstance()->getBool("GamelistVideoAudio"))
|
||||
Settings::getInstance()->getBool("GamelistVideoAudio"))
|
||||
outputSound = true;
|
||||
else if (mScreensaverMode && Settings::getInstance()->
|
||||
getBool("ScreensaverVideoAudio"))
|
||||
else if (mScreensaverMode &&
|
||||
Settings::getInstance()->getBool("ScreensaverVideoAudio"))
|
||||
outputSound = true;
|
||||
else if (mMediaViewerMode && Settings::getInstance()->
|
||||
getBool("MediaViewerVideoAudio"))
|
||||
else if (mMediaViewerMode &&
|
||||
Settings::getInstance()->getBool("MediaViewerVideoAudio"))
|
||||
outputSound = true;
|
||||
|
||||
if (!outputSound)
|
||||
|
|
|
@ -66,7 +66,7 @@ private:
|
|||
// Handle looping the video. Must be called periodically.
|
||||
virtual void handleLooping() override;
|
||||
|
||||
static void VlcMediaParseCallback(const libvlc_event_t *event, void *user_data) {};
|
||||
static void VlcMediaParseCallback(const libvlc_event_t* event, void* user_data) {}
|
||||
|
||||
static VideoVlcComponent* sInstance;
|
||||
static libvlc_instance_t* mVLC;
|
||||
|
|
|
@ -10,68 +10,68 @@
|
|||
|
||||
#include "guis/GuiComplexTextEditPopup.h"
|
||||
|
||||
#include "Window.h"
|
||||
#include "components/ButtonComponent.h"
|
||||
#include "components/MenuComponent.h"
|
||||
#include "components/TextEditComponent.h"
|
||||
#include "guis/GuiMsgBox.h"
|
||||
#include "Window.h"
|
||||
|
||||
GuiComplexTextEditPopup::GuiComplexTextEditPopup(
|
||||
Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& title,
|
||||
const std::string& infoString1,
|
||||
const std::string& infoString2,
|
||||
const std::string& initValue,
|
||||
const std::function<void(const std::string&)>& okCallback,
|
||||
bool multiLine,
|
||||
const std::string& acceptBtnText,
|
||||
const std::string& saveConfirmationText,
|
||||
const std::string& loadBtnText,
|
||||
const std::string& loadBtnHelpText,
|
||||
const std::string& clearBtnText,
|
||||
const std::string& clearBtnHelpText,
|
||||
bool hideCancelButton)
|
||||
: GuiComponent(window),
|
||||
mHelpStyle(helpstyle),
|
||||
mBackground(window, ":/graphics/frame.svg"),
|
||||
mGrid(window, Vector2i(1, 5)),
|
||||
mMultiLine(multiLine),
|
||||
mInitValue(initValue),
|
||||
mOkCallback(okCallback),
|
||||
mSaveConfirmationText(saveConfirmationText),
|
||||
mHideCancelButton(hideCancelButton)
|
||||
Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& title,
|
||||
const std::string& infoString1,
|
||||
const std::string& infoString2,
|
||||
const std::string& initValue,
|
||||
const std::function<void(const std::string&)>& okCallback,
|
||||
bool multiLine,
|
||||
const std::string& acceptBtnText,
|
||||
const std::string& saveConfirmationText,
|
||||
const std::string& loadBtnText,
|
||||
const std::string& loadBtnHelpText,
|
||||
const std::string& clearBtnText,
|
||||
const std::string& clearBtnHelpText,
|
||||
bool hideCancelButton)
|
||||
: GuiComponent(window)
|
||||
, mHelpStyle(helpstyle)
|
||||
, mBackground(window, ":/graphics/frame.svg")
|
||||
, mGrid(window, Vector2i(1, 5))
|
||||
, mMultiLine(multiLine)
|
||||
, mInitValue(initValue)
|
||||
, mOkCallback(okCallback)
|
||||
, mSaveConfirmationText(saveConfirmationText)
|
||||
, mHideCancelButton(hideCancelButton)
|
||||
{
|
||||
addChild(&mBackground);
|
||||
addChild(&mGrid);
|
||||
|
||||
mTitle = std::make_shared<TextComponent>(mWindow, Utils::String::toUpper(title),
|
||||
Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER);
|
||||
mInfoString1 = std::make_shared<TextComponent>(mWindow, infoString1,
|
||||
Font::get(FONT_SIZE_SMALL), 0x555555FF, ALIGN_CENTER);
|
||||
mInfoString2 = std::make_shared<TextComponent>(mWindow, infoString2,
|
||||
Font::get(FONT_SIZE_SMALL), 0x555555FF, ALIGN_CENTER);
|
||||
Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER);
|
||||
mInfoString1 = std::make_shared<TextComponent>(mWindow, infoString1, Font::get(FONT_SIZE_SMALL),
|
||||
0x555555FF, ALIGN_CENTER);
|
||||
mInfoString2 = std::make_shared<TextComponent>(mWindow, infoString2, Font::get(FONT_SIZE_SMALL),
|
||||
0x555555FF, ALIGN_CENTER);
|
||||
|
||||
mText = std::make_shared<TextEditComponent>(mWindow);
|
||||
mText->setValue(initValue);
|
||||
|
||||
std::vector<std::shared_ptr<ButtonComponent>> buttons;
|
||||
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, acceptBtnText, acceptBtnText,
|
||||
[this, okCallback] {
|
||||
okCallback(mText->getValue());
|
||||
delete this;
|
||||
}));
|
||||
[this, okCallback] {
|
||||
okCallback(mText->getValue());
|
||||
delete this;
|
||||
}));
|
||||
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, loadBtnText, loadBtnHelpText,
|
||||
[this, infoString2] {
|
||||
mText->setValue(infoString2);
|
||||
mText->setCursor(0);
|
||||
mText->setCursor(infoString2.size());
|
||||
}));
|
||||
[this, infoString2] {
|
||||
mText->setValue(infoString2);
|
||||
mText->setCursor(0);
|
||||
mText->setCursor(infoString2.size());
|
||||
}));
|
||||
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, clearBtnText, clearBtnHelpText,
|
||||
[this] { mText->setValue(""); }));
|
||||
[this] { mText->setValue(""); }));
|
||||
if (!mHideCancelButton)
|
||||
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "CANCEL", "discard changes",
|
||||
[this] { delete this; }));
|
||||
[this] { delete this; }));
|
||||
|
||||
mButtonGrid = makeButtonGrid(mWindow, buttons);
|
||||
|
||||
|
@ -79,14 +79,14 @@ GuiComplexTextEditPopup::GuiComplexTextEditPopup(
|
|||
mGrid.setEntry(mInfoString1, Vector2i(0, 1), false, true);
|
||||
mGrid.setEntry(mInfoString2, Vector2i(0, 2), false, false);
|
||||
mGrid.setEntry(mText, Vector2i(0, 3), true, false, Vector2i(1, 1),
|
||||
GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM);
|
||||
GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM);
|
||||
mGrid.setEntry(mButtonGrid, Vector2i(0, 4), true, false);
|
||||
mGrid.setRowHeightPerc(1, 0.15f, true);
|
||||
|
||||
float textHeight = mText->getFont()->getHeight();
|
||||
|
||||
if (multiLine)
|
||||
textHeight *= 6;
|
||||
textHeight *= 6.0f;
|
||||
|
||||
// Adjust the width relative to the aspect ratio of the screen to make the GUI look coherent
|
||||
// regardless of screen type. The 1.778 aspect ratio value is the 16:9 reference.
|
||||
|
@ -97,18 +97,17 @@ GuiComplexTextEditPopup::GuiComplexTextEditPopup(
|
|||
mText->setSize(0, textHeight);
|
||||
mInfoString2->setSize(infoWidth, mInfoString2->getFont()->getHeight());
|
||||
|
||||
setSize(windowWidth, mTitle->getFont()->getHeight() + textHeight +
|
||||
mButtonGrid->getSize().y() + mButtonGrid->getSize().y() * 1.85f);
|
||||
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2,
|
||||
(Renderer::getScreenHeight() - mSize.y()) / 2);
|
||||
setSize(windowWidth, mTitle->getFont()->getHeight() + textHeight + mButtonGrid->getSize().y() +
|
||||
mButtonGrid->getSize().y() * 1.85f);
|
||||
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2.0f,
|
||||
(Renderer::getScreenHeight() - mSize.y()) / 2.0f);
|
||||
mText->startEditing();
|
||||
}
|
||||
|
||||
void GuiComplexTextEditPopup::onSizeChanged()
|
||||
{
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
|
||||
|
||||
mText->setSize(mSize.x() - 40, mText->getSize().y());
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f));
|
||||
mText->setSize(mSize.x() - 40.0f, mText->getSize().y());
|
||||
|
||||
// Update grid.
|
||||
mGrid.setRowHeightPerc(0, mTitle->getFont()->getHeight() / mSize.y());
|
||||
|
@ -122,13 +121,22 @@ bool GuiComplexTextEditPopup::input(InputConfig* config, Input input)
|
|||
return true;
|
||||
|
||||
if (!mHideCancelButton) {
|
||||
// Pressing back when not text editing closes us.
|
||||
// Pressing back when not text editing closes us.
|
||||
if (config->isMappedTo("b", input) && input.value) {
|
||||
if (mText->getValue() != mInitValue) {
|
||||
// Changes were made, ask if the user wants to save them.
|
||||
mWindow->pushGui(new GuiMsgBox(mWindow, mHelpStyle, mSaveConfirmationText, "YES",
|
||||
[this] { this->mOkCallback(mText->getValue()); delete this; return true; },
|
||||
"NO", [this] { delete this; return false; }));
|
||||
mWindow->pushGui(new GuiMsgBox(
|
||||
mWindow, mHelpStyle, mSaveConfirmationText, "YES",
|
||||
[this] {
|
||||
this->mOkCallback(mText->getValue());
|
||||
delete this;
|
||||
return true;
|
||||
},
|
||||
"NO",
|
||||
[this] {
|
||||
delete this;
|
||||
return false;
|
||||
}));
|
||||
}
|
||||
else {
|
||||
delete this;
|
||||
|
|
|
@ -11,9 +11,9 @@
|
|||
#ifndef ES_CORE_GUIS_GUI_COMPLEX_TEXT_EDIT_POPUP_H
|
||||
#define ES_CORE_GUIS_GUI_COMPLEX_TEXT_EDIT_POPUP_H
|
||||
|
||||
#include "GuiComponent.h"
|
||||
#include "components/ComponentGrid.h"
|
||||
#include "components/NinePatchComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
|
||||
class TextComponent;
|
||||
class TextEditComponent;
|
||||
|
@ -21,28 +21,27 @@ class TextEditComponent;
|
|||
class GuiComplexTextEditPopup : public GuiComponent
|
||||
{
|
||||
public:
|
||||
GuiComplexTextEditPopup(
|
||||
Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& title,
|
||||
const std::string& infoString1,
|
||||
const std::string& infoString2,
|
||||
const std::string& initValue,
|
||||
const std::function<void(const std::string&)>& okCallback,
|
||||
bool multiLine,
|
||||
const std::string& acceptBtnText = "OK",
|
||||
const std::string& saveConfirmationText = "SAVE CHANGES?",
|
||||
const std::string& loadBtnText = "LOAD",
|
||||
const std::string& loadBtnHelpText = "load default",
|
||||
const std::string& clearBtnText = "CLEAR",
|
||||
const std::string& clearBtnHelpText = "clear",
|
||||
bool hideCancelButton = false);
|
||||
GuiComplexTextEditPopup(Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& title,
|
||||
const std::string& infoString1,
|
||||
const std::string& infoString2,
|
||||
const std::string& initValue,
|
||||
const std::function<void(const std::string&)>& okCallback,
|
||||
bool multiLine,
|
||||
const std::string& acceptBtnText = "OK",
|
||||
const std::string& saveConfirmationText = "SAVE CHANGES?",
|
||||
const std::string& loadBtnText = "LOAD",
|
||||
const std::string& loadBtnHelpText = "load default",
|
||||
const std::string& clearBtnText = "CLEAR",
|
||||
const std::string& clearBtnHelpText = "clear",
|
||||
bool hideCancelButton = false);
|
||||
|
||||
bool input(InputConfig* config, Input input) override;
|
||||
void onSizeChanged() override;
|
||||
|
||||
std::vector<HelpPrompt> getHelpPrompts() override;
|
||||
HelpStyle getHelpStyle() override { return mHelpStyle; };
|
||||
HelpStyle getHelpStyle() override { return mHelpStyle; }
|
||||
|
||||
private:
|
||||
NinePatchComponent mBackground;
|
||||
|
|
|
@ -8,25 +8,24 @@
|
|||
|
||||
#include "guis/GuiDetectDevice.h"
|
||||
|
||||
#include "InputManager.h"
|
||||
#include "Window.h"
|
||||
#include "components/TextComponent.h"
|
||||
#include "guis/GuiInputConfig.h"
|
||||
#include "utils/FileSystemUtil.h"
|
||||
#include "utils/StringUtil.h"
|
||||
#include "InputManager.h"
|
||||
#include "Window.h"
|
||||
|
||||
#define HOLD_TIME 1000
|
||||
|
||||
GuiDetectDevice::GuiDetectDevice(
|
||||
Window* window,
|
||||
bool firstRun,
|
||||
bool forcedConfig,
|
||||
const std::function<void()>& doneCallback)
|
||||
: GuiComponent(window),
|
||||
mFirstRun(firstRun),
|
||||
mForcedConfig(forcedConfig),
|
||||
mBackground(window, ":/graphics/frame.svg"),
|
||||
mGrid(window, Vector2i(1, 5))
|
||||
GuiDetectDevice::GuiDetectDevice(Window* window,
|
||||
bool firstRun,
|
||||
bool forcedConfig,
|
||||
const std::function<void()>& doneCallback)
|
||||
: GuiComponent(window)
|
||||
, mFirstRun(firstRun)
|
||||
, mForcedConfig(forcedConfig)
|
||||
, mBackground(window, ":/graphics/frame.svg")
|
||||
, mGrid(window, Vector2i(1, 5))
|
||||
{
|
||||
mHoldingConfig = nullptr;
|
||||
mHoldTime = 0;
|
||||
|
@ -36,8 +35,9 @@ GuiDetectDevice::GuiDetectDevice(
|
|||
addChild(&mGrid);
|
||||
|
||||
// Title.
|
||||
mTitle = std::make_shared<TextComponent>(mWindow, firstRun ? "WELCOME" :
|
||||
"CONFIGURE INPUT DEVICE", Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER);
|
||||
mTitle =
|
||||
std::make_shared<TextComponent>(mWindow, firstRun ? "WELCOME" : "CONFIGURE INPUT DEVICE",
|
||||
Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER);
|
||||
mGrid.setEntry(mTitle, Vector2i(0, 0), false, true, Vector2i(1, 1), GridFlags::BORDER_BOTTOM);
|
||||
|
||||
// Device info.
|
||||
|
@ -52,33 +52,33 @@ GuiDetectDevice::GuiDetectDevice(
|
|||
if (numDevices > 1 && Settings::getInstance()->getBool("InputOnlyFirstController"))
|
||||
deviceInfo << " (ONLY ACCEPTING INPUT FROM FIRST CONTROLLER)";
|
||||
|
||||
mDeviceInfo = std::make_shared<TextComponent>(mWindow, deviceInfo.str(),
|
||||
Font::get(FONT_SIZE_SMALL), 0x999999FF, ALIGN_CENTER);
|
||||
mDeviceInfo = std::make_shared<TextComponent>(
|
||||
mWindow, deviceInfo.str(), Font::get(FONT_SIZE_SMALL), 0x999999FF, ALIGN_CENTER);
|
||||
mGrid.setEntry(mDeviceInfo, Vector2i(0, 1), false, true);
|
||||
|
||||
// Message.
|
||||
if (numDevices > 0) {
|
||||
mMsg1 = std::make_shared<TextComponent>(mWindow,
|
||||
"HOLD A BUTTON ON YOUR GAMEPAD OR KEYBOARD TO CONFIGURE IT",
|
||||
Font::get(FONT_SIZE_SMALL), 0x777777FF, ALIGN_CENTER);
|
||||
mMsg1 = std::make_shared<TextComponent>(
|
||||
mWindow, "HOLD A BUTTON ON YOUR GAMEPAD OR KEYBOARD TO CONFIGURE IT",
|
||||
Font::get(FONT_SIZE_SMALL), 0x777777FF, ALIGN_CENTER);
|
||||
}
|
||||
else {
|
||||
mMsg1 = std::make_shared<TextComponent>(mWindow,
|
||||
"HOLD A BUTTON ON YOUR KEYBOARD TO CONFIGURE IT",
|
||||
Font::get(FONT_SIZE_SMALL), 0x777777FF, ALIGN_CENTER);
|
||||
mMsg1 = std::make_shared<TextComponent>(
|
||||
mWindow, "HOLD A BUTTON ON YOUR KEYBOARD TO CONFIGURE IT", Font::get(FONT_SIZE_SMALL),
|
||||
0x777777FF, ALIGN_CENTER);
|
||||
}
|
||||
|
||||
mGrid.setEntry(mMsg1, Vector2i(0, 2), false, true);
|
||||
|
||||
const std::string msg2str = firstRun ?
|
||||
"PRESS ESC TO SKIP (OR F4 TO QUIT AT ANY TIME)" : "PRESS ESC TO CANCEL";
|
||||
mMsg2 = std::make_shared<TextComponent>(mWindow, msg2str,
|
||||
Font::get(FONT_SIZE_SMALL), 0x777777FF, ALIGN_CENTER);
|
||||
const std::string msg2str =
|
||||
firstRun ? "PRESS ESC TO SKIP (OR F4 TO QUIT AT ANY TIME)" : "PRESS ESC TO CANCEL";
|
||||
mMsg2 = std::make_shared<TextComponent>(mWindow, msg2str, Font::get(FONT_SIZE_SMALL),
|
||||
0x777777FF, ALIGN_CENTER);
|
||||
mGrid.setEntry(mMsg2, Vector2i(0, 3), false, true);
|
||||
|
||||
// Currently held device.
|
||||
mDeviceHeld = std::make_shared<TextComponent>(mWindow, "",
|
||||
Font::get(FONT_SIZE_MEDIUM), 0xFFFFFFFF, ALIGN_CENTER);
|
||||
mDeviceHeld = std::make_shared<TextComponent>(mWindow, "", Font::get(FONT_SIZE_MEDIUM),
|
||||
0xFFFFFFFF, ALIGN_CENTER);
|
||||
mGrid.setEntry(mDeviceHeld, Vector2i(0, 4), false, true);
|
||||
|
||||
// Adjust the width relative to the aspect ratio of the screen to make the GUI look coherent
|
||||
|
@ -87,27 +87,27 @@ GuiDetectDevice::GuiDetectDevice(
|
|||
float width = Math::clamp(0.60f * aspectValue, 0.50f, 0.80f) * Renderer::getScreenWidth();
|
||||
|
||||
setSize(width, Renderer::getScreenHeight() * 0.5f);
|
||||
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2,
|
||||
(Renderer::getScreenHeight() - mSize.y()) / 2);
|
||||
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2.0f,
|
||||
(Renderer::getScreenHeight() - mSize.y()) / 2.0f);
|
||||
}
|
||||
|
||||
void GuiDetectDevice::onSizeChanged()
|
||||
{
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f));
|
||||
|
||||
// Grid.
|
||||
mGrid.setSize(mSize);
|
||||
mGrid.setRowHeightPerc(0, mTitle->getFont()->getHeight() / mSize.y());
|
||||
//mGrid.setRowHeightPerc(1, mDeviceInfo->getFont()->getHeight() / mSize.y());
|
||||
// mGrid.setRowHeightPerc(1, mDeviceInfo->getFont()->getHeight() / mSize.y());
|
||||
mGrid.setRowHeightPerc(2, mMsg1->getFont()->getHeight() / mSize.y());
|
||||
mGrid.setRowHeightPerc(3, mMsg2->getFont()->getHeight() / mSize.y());
|
||||
//mGrid.setRowHeightPerc(4, mDeviceHeld->getFont()->getHeight() / mSize.y());
|
||||
// mGrid.setRowHeightPerc(4, mDeviceHeld->getFont()->getHeight() / mSize.y());
|
||||
}
|
||||
|
||||
bool GuiDetectDevice::input(InputConfig* config, Input input)
|
||||
{
|
||||
if (!mFirstRun && input.device == DEVICE_KEYBOARD && input.type == TYPE_KEY &&
|
||||
input.value && input.id == SDLK_ESCAPE) {
|
||||
if (!mFirstRun && input.device == DEVICE_KEYBOARD && input.type == TYPE_KEY && input.value &&
|
||||
input.id == SDLK_ESCAPE) {
|
||||
// Cancel the configuration.
|
||||
delete this; // Delete GUI element.
|
||||
return true;
|
||||
|
@ -115,15 +115,15 @@ bool GuiDetectDevice::input(InputConfig* config, Input input)
|
|||
// First run, but the user chooses to skip the configuration. This will default to the
|
||||
// built-in keyboard mappings.
|
||||
else if (mFirstRun && input.device == DEVICE_KEYBOARD && input.type == TYPE_KEY &&
|
||||
input.value && input.id == SDLK_ESCAPE) {
|
||||
if (mDoneCallback)
|
||||
mDoneCallback();
|
||||
delete this; // Delete GUI element.
|
||||
return true;
|
||||
input.value && input.id == SDLK_ESCAPE) {
|
||||
if (mDoneCallback)
|
||||
mDoneCallback();
|
||||
delete this; // Delete GUI element.
|
||||
return true;
|
||||
}
|
||||
|
||||
if (input.type == TYPE_BUTTON || input.type == TYPE_AXIS || input.type == TYPE_KEY ||
|
||||
input.type == TYPE_CEC_BUTTON) {
|
||||
input.type == TYPE_CEC_BUTTON) {
|
||||
if (input.value && mHoldingConfig == nullptr) {
|
||||
// Started holding.
|
||||
mHoldingConfig = config;
|
||||
|
@ -146,8 +146,8 @@ void GuiDetectDevice::update(int deltaTime)
|
|||
// configuration unless the flag to force the configuration was passed on the
|
||||
// command line.
|
||||
if (!mForcedConfig && mFirstRun &&
|
||||
Utils::FileSystem::exists(InputManager::getConfigPath()) &&
|
||||
InputManager::getInstance()->getNumConfiguredDevices() > 0) {
|
||||
Utils::FileSystem::exists(InputManager::getConfigPath()) &&
|
||||
InputManager::getInstance()->getNumConfiguredDevices() > 0) {
|
||||
if (mDoneCallback)
|
||||
mDoneCallback();
|
||||
delete this; // Delete GUI element.
|
||||
|
|
|
@ -9,17 +9,19 @@
|
|||
#ifndef ES_CORE_GUIS_GUI_DETECT_DEVICE_H
|
||||
#define ES_CORE_GUIS_GUI_DETECT_DEVICE_H
|
||||
|
||||
#include "GuiComponent.h"
|
||||
#include "components/ComponentGrid.h"
|
||||
#include "components/NinePatchComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
|
||||
class TextComponent;
|
||||
|
||||
class GuiDetectDevice : public GuiComponent
|
||||
{
|
||||
public:
|
||||
GuiDetectDevice(Window* window, bool firstRun, bool forcedConfig,
|
||||
const std::function<void()>& doneCallback);
|
||||
GuiDetectDevice(Window* window,
|
||||
bool firstRun,
|
||||
bool forcedConfig,
|
||||
const std::function<void()>& doneCallback);
|
||||
|
||||
bool input(InputConfig* config, Input input) override;
|
||||
void update(int deltaTime) override;
|
||||
|
|
|
@ -8,12 +8,12 @@
|
|||
|
||||
#include "guis/GuiInputConfig.h"
|
||||
|
||||
#include "components/ButtonComponent.h"
|
||||
#include "components/MenuComponent.h"
|
||||
#include "guis/GuiMsgBox.h"
|
||||
#include "InputManager.h"
|
||||
#include "Log.h"
|
||||
#include "Window.h"
|
||||
#include "components/ButtonComponent.h"
|
||||
#include "components/MenuComponent.h"
|
||||
#include "guis/GuiMsgBox.h"
|
||||
|
||||
#define HOLD_TO_SKIP_MS 1000
|
||||
|
||||
|
@ -27,23 +27,22 @@ struct InputConfigStructure {
|
|||
static const int inputCount = 24;
|
||||
static InputConfigStructure sGuiInputConfigList[inputCount];
|
||||
|
||||
GuiInputConfig::GuiInputConfig(
|
||||
Window* window,
|
||||
InputConfig* target,
|
||||
bool reconfigureAll,
|
||||
const std::function<void()>& okCallback)
|
||||
: GuiComponent(window),
|
||||
mBackground(window, ":/graphics/frame.svg"),
|
||||
mGrid(window, Vector2i(1, 7)),
|
||||
mTargetConfig(target),
|
||||
mHoldingInput(false)
|
||||
GuiInputConfig::GuiInputConfig(Window* window,
|
||||
InputConfig* target,
|
||||
bool reconfigureAll,
|
||||
const std::function<void()>& okCallback)
|
||||
: GuiComponent(window)
|
||||
, mBackground(window, ":/graphics/frame.svg")
|
||||
, mGrid(window, Vector2i(1, 7))
|
||||
, mTargetConfig(target)
|
||||
, mHoldingInput(false)
|
||||
{
|
||||
// Populate the configuration list with the text and icons applicable to the
|
||||
// configured controller type.
|
||||
populateConfigList();
|
||||
|
||||
LOG(LogInfo) << "Configuring device " << target->getDeviceId() << " (" <<
|
||||
target->getDeviceName() << ").";
|
||||
LOG(LogInfo) << "Configuring device " << target->getDeviceId() << " ("
|
||||
<< target->getDeviceName() << ").";
|
||||
|
||||
if (reconfigureAll)
|
||||
target->clear();
|
||||
|
@ -57,8 +56,8 @@ GuiInputConfig::GuiInputConfig(
|
|||
// 0 is a spacer row.
|
||||
mGrid.setEntry(std::make_shared<GuiComponent>(mWindow), Vector2i(0, 0), false);
|
||||
|
||||
mTitle = std::make_shared<TextComponent>(mWindow, "CONFIGURING",
|
||||
Font::get(FONT_SIZE_LARGE), 0x555555FF, ALIGN_CENTER);
|
||||
mTitle = std::make_shared<TextComponent>(mWindow, "CONFIGURING", Font::get(FONT_SIZE_LARGE),
|
||||
0x555555FF, ALIGN_CENTER);
|
||||
mGrid.setEntry(mTitle, Vector2i(0, 1), false, true);
|
||||
|
||||
std::stringstream ss;
|
||||
|
@ -67,13 +66,15 @@ GuiInputConfig::GuiInputConfig(
|
|||
else if (target->getDeviceId() == DEVICE_CEC)
|
||||
ss << "CEC";
|
||||
else
|
||||
ss << "GAMEPAD " << (target->getDeviceId() + 1) << " (" << target->getDeviceName() << ")";
|
||||
mSubtitle1 = std::make_shared<TextComponent>(mWindow, Utils::String::toUpper(ss.str()),
|
||||
Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER);
|
||||
ss << "GAMEPAD " << (target->getDeviceId() + 1) << " (" << target->getDeviceName() << ")";
|
||||
mSubtitle1 =
|
||||
std::make_shared<TextComponent>(mWindow, Utils::String::toUpper(ss.str()),
|
||||
Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER);
|
||||
mGrid.setEntry(mSubtitle1, Vector2i(0, 2), false, true);
|
||||
|
||||
mSubtitle2 = std::make_shared<TextComponent>(mWindow, "HOLD ANY BUTTON 1 SECOND TO SKIP",
|
||||
Font::get(FONT_SIZE_SMALL), 0x999999FF, ALIGN_CENTER);
|
||||
mSubtitle2 =
|
||||
std::make_shared<TextComponent>(mWindow, "HOLD ANY BUTTON 1 SECOND TO SKIP",
|
||||
Font::get(FONT_SIZE_SMALL), 0x999999FF, ALIGN_CENTER);
|
||||
// The opacity will be set to visible for any row that is skippable.
|
||||
mSubtitle2->setOpacity(0);
|
||||
|
||||
|
@ -98,12 +99,13 @@ GuiInputConfig::GuiInputConfig(
|
|||
spacer->setSize(16, 0);
|
||||
row.addElement(spacer, false);
|
||||
|
||||
auto text = std::make_shared<TextComponent>(mWindow,
|
||||
sGuiInputConfigList[i].dispName, Font::get(FONT_SIZE_MEDIUM), 0x777777FF);
|
||||
auto text = std::make_shared<TextComponent>(mWindow, sGuiInputConfigList[i].dispName,
|
||||
Font::get(FONT_SIZE_MEDIUM), 0x777777FF);
|
||||
row.addElement(text, true);
|
||||
|
||||
auto mapping = std::make_shared<TextComponent>(mWindow, "-NOT DEFINED-",
|
||||
Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT), 0x999999FF, ALIGN_RIGHT);
|
||||
Font::get(FONT_SIZE_MEDIUM, FONT_PATH_LIGHT),
|
||||
0x999999FF, ALIGN_RIGHT);
|
||||
setNotDefined(mapping); // Overrides the text and color set above.
|
||||
row.addElement(mapping, true);
|
||||
mMappings.push_back(mapping);
|
||||
|
@ -142,9 +144,10 @@ GuiInputConfig::GuiInputConfig(
|
|||
else {
|
||||
// Button released. Make sure we were holding something and we let go of
|
||||
// what we were previously holding.
|
||||
if (!mHoldingInput || mHeldInput.device != input.device || mHeldInput.id !=
|
||||
input.id || mHeldInput.type != input.type)
|
||||
if (!mHoldingInput || mHeldInput.device != input.device ||
|
||||
mHeldInput.id != input.id || mHeldInput.type != input.type) {
|
||||
return true;
|
||||
}
|
||||
|
||||
mHoldingInput = false;
|
||||
|
||||
|
@ -177,8 +180,8 @@ GuiInputConfig::GuiInputConfig(
|
|||
delete this;
|
||||
};
|
||||
|
||||
buttons.push_back(std::make_shared<ButtonComponent>
|
||||
(mWindow, "OK", "ok", [this, okFunction] { okFunction(); }));
|
||||
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "OK", "ok",
|
||||
[this, okFunction] { okFunction(); }));
|
||||
|
||||
mButtonGrid = makeButtonGrid(mWindow, buttons);
|
||||
mGrid.setEntry(mButtonGrid, Vector2i(0, 6), true, false);
|
||||
|
@ -190,122 +193,76 @@ GuiInputConfig::GuiInputConfig(
|
|||
|
||||
setSize(width, Renderer::getScreenHeight() * 0.75f);
|
||||
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2.0f,
|
||||
(Renderer::getScreenHeight() - mSize.y()) / 2.0f);
|
||||
(Renderer::getScreenHeight() - mSize.y()) / 2.0f);
|
||||
}
|
||||
|
||||
void GuiInputConfig::populateConfigList()
|
||||
{
|
||||
std::string controllerType = Settings::getInstance()->getString("InputControllerType");
|
||||
|
||||
sGuiInputConfigList[0] =
|
||||
{ "Up", false, "D-PAD UP", ":/help/dpad_up.svg" };
|
||||
sGuiInputConfigList[1] =
|
||||
{ "Down", false, "D-PAD DOWN", ":/help/dpad_down.svg" };
|
||||
sGuiInputConfigList[2] =
|
||||
{ "Left", false, "D-PAD LEFT", ":/help/dpad_left.svg" };
|
||||
sGuiInputConfigList[3] =
|
||||
{ "Right", false, "D-PAD RIGHT", ":/help/dpad_right.svg" };
|
||||
// clang-format off
|
||||
sGuiInputConfigList[0] = { "Up", false, "D-PAD UP", ":/help/dpad_up.svg" };
|
||||
sGuiInputConfigList[1] = { "Down", false, "D-PAD DOWN", ":/help/dpad_down.svg" };
|
||||
sGuiInputConfigList[2] = { "Left", false, "D-PAD LEFT", ":/help/dpad_left.svg" };
|
||||
sGuiInputConfigList[3] = { "Right", false, "D-PAD RIGHT", ":/help/dpad_right.svg" };
|
||||
|
||||
if (controllerType == "snes") {
|
||||
sGuiInputConfigList[4] =
|
||||
{ "Back", false, "SELECT", ":/help/button_back_SNES.svg" };
|
||||
sGuiInputConfigList[5] =
|
||||
{ "Start", false, "START", ":/help/button_start_SNES.svg" };
|
||||
sGuiInputConfigList[6] =
|
||||
{ "A", false, "B", ":/help/mbuttons_a_SNES.svg" };
|
||||
sGuiInputConfigList[7] =
|
||||
{ "B", false, "A", ":/help/mbuttons_b_SNES.svg" };
|
||||
sGuiInputConfigList[8] =
|
||||
{ "X", true, "Y", ":/help/mbuttons_x_SNES.svg" };
|
||||
sGuiInputConfigList[9] =
|
||||
{ "Y", true, "X", ":/help/mbuttons_y_SNES.svg" };
|
||||
sGuiInputConfigList[4] = { "Back", false, "SELECT", ":/help/button_back_SNES.svg" };
|
||||
sGuiInputConfigList[5] = { "Start", false, "START", ":/help/button_start_SNES.svg" };
|
||||
sGuiInputConfigList[6] = { "A", false, "B", ":/help/mbuttons_a_SNES.svg" };
|
||||
sGuiInputConfigList[7] = { "B", false, "A", ":/help/mbuttons_b_SNES.svg" };
|
||||
sGuiInputConfigList[8] = { "X", true, "Y", ":/help/mbuttons_x_SNES.svg" };
|
||||
sGuiInputConfigList[9] = { "Y", true, "X", ":/help/mbuttons_y_SNES.svg" };
|
||||
}
|
||||
else if (controllerType == "ps4") {
|
||||
sGuiInputConfigList[4] =
|
||||
{ "Back", false, "SHARE", ":/help/button_back_PS4.svg" };
|
||||
sGuiInputConfigList[5] =
|
||||
{ "Start", false, "OPTIONS", ":/help/button_start_PS4.svg" };
|
||||
sGuiInputConfigList[6] =
|
||||
{ "A", false, "CROSS", ":/help/mbuttons_a_PS.svg" };
|
||||
sGuiInputConfigList[7] =
|
||||
{ "B", false, "CIRCLE", ":/help/mbuttons_b_PS.svg" };
|
||||
sGuiInputConfigList[8] =
|
||||
{ "X", true, "SQUARE", ":/help/mbuttons_x_PS.svg" };
|
||||
sGuiInputConfigList[9] =
|
||||
{ "Y", true, "TRIANGLE", ":/help/mbuttons_y_PS.svg" };
|
||||
sGuiInputConfigList[4] = { "Back", false, "SHARE", ":/help/button_back_PS4.svg" };
|
||||
sGuiInputConfigList[5] = { "Start", false, "OPTIONS", ":/help/button_start_PS4.svg" };
|
||||
sGuiInputConfigList[6] = { "A", false, "CROSS", ":/help/mbuttons_a_PS.svg" };
|
||||
sGuiInputConfigList[7] = { "B", false, "CIRCLE", ":/help/mbuttons_b_PS.svg" };
|
||||
sGuiInputConfigList[8] = { "X", true, "SQUARE", ":/help/mbuttons_x_PS.svg" };
|
||||
sGuiInputConfigList[9] = { "Y", true, "TRIANGLE", ":/help/mbuttons_y_PS.svg" };
|
||||
}
|
||||
else if (controllerType == "ps5") {
|
||||
sGuiInputConfigList[4] =
|
||||
{ "Back", false, "CREATE", ":/help/button_back_PS5.svg" };
|
||||
sGuiInputConfigList[5] =
|
||||
{ "Start", false, "OPTIONS", ":/help/button_start_PS5.svg" };
|
||||
sGuiInputConfigList[6] =
|
||||
{ "A", false, "CROSS", ":/help/mbuttons_a_PS.svg" };
|
||||
sGuiInputConfigList[7] =
|
||||
{ "B", false, "CIRCLE", ":/help/mbuttons_b_PS.svg" };
|
||||
sGuiInputConfigList[8] =
|
||||
{ "X", true, "SQUARE", ":/help/mbuttons_x_PS.svg" };
|
||||
sGuiInputConfigList[9] =
|
||||
{ "Y", true, "TRIANGLE", ":/help/mbuttons_y_PS.svg" };
|
||||
sGuiInputConfigList[4] = { "Back", false, "CREATE", ":/help/button_back_PS5.svg" };
|
||||
sGuiInputConfigList[5] = { "Start", false, "OPTIONS", ":/help/button_start_PS5.svg" };
|
||||
sGuiInputConfigList[6] = { "A", false, "CROSS", ":/help/mbuttons_a_PS.svg" };
|
||||
sGuiInputConfigList[7] = { "B", false, "CIRCLE", ":/help/mbuttons_b_PS.svg" };
|
||||
sGuiInputConfigList[8] = { "X", true, "SQUARE", ":/help/mbuttons_x_PS.svg" };
|
||||
sGuiInputConfigList[9] = { "Y", true, "TRIANGLE", ":/help/mbuttons_y_PS.svg" };
|
||||
}
|
||||
else if (controllerType == "xbox360") {
|
||||
sGuiInputConfigList[4] =
|
||||
{ "Back", false, "BACK", ":/help/button_back_XBOX360.svg" };
|
||||
sGuiInputConfigList[5] =
|
||||
{ "Start", false, "START", ":/help/button_start_XBOX360.svg" };
|
||||
sGuiInputConfigList[6] =
|
||||
{ "A", false, "A", ":/help/mbuttons_a_XBOX.svg" };
|
||||
sGuiInputConfigList[7] =
|
||||
{ "B", false, "B", ":/help/mbuttons_b_XBOX.svg" };
|
||||
sGuiInputConfigList[8] =
|
||||
{ "X", true, "X", ":/help/mbuttons_x_XBOX.svg" };
|
||||
sGuiInputConfigList[9] =
|
||||
{ "Y", true, "Y", ":/help/mbuttons_y_XBOX.svg" };
|
||||
sGuiInputConfigList[4] = { "Back", false, "BACK", ":/help/button_back_XBOX360.svg" };
|
||||
sGuiInputConfigList[5] = { "Start", false, "START", ":/help/button_start_XBOX360.svg" };
|
||||
sGuiInputConfigList[6] = { "A", false, "A", ":/help/mbuttons_a_XBOX.svg" };
|
||||
sGuiInputConfigList[7] = { "B", false, "B", ":/help/mbuttons_b_XBOX.svg" };
|
||||
sGuiInputConfigList[8] = { "X", true, "X", ":/help/mbuttons_x_XBOX.svg" };
|
||||
sGuiInputConfigList[9] = { "Y", true, "Y", ":/help/mbuttons_y_XBOX.svg" };
|
||||
}
|
||||
else {
|
||||
// Xbox One and later.
|
||||
sGuiInputConfigList[4] =
|
||||
{ "Back", false, "VIEW", ":/help/button_back_XBOX.svg" };
|
||||
sGuiInputConfigList[5] =
|
||||
{ "Start", false, "MENU", ":/help/button_start_XBOX.svg" };
|
||||
sGuiInputConfigList[6] =
|
||||
{ "A", false, "A", ":/help/mbuttons_a_XBOX.svg" };
|
||||
sGuiInputConfigList[7] =
|
||||
{ "B", false, "B", ":/help/mbuttons_b_XBOX.svg" };
|
||||
sGuiInputConfigList[8] =
|
||||
{ "X", true, "X", ":/help/mbuttons_x_XBOX.svg" };
|
||||
sGuiInputConfigList[9] =
|
||||
{ "Y", true, "Y", ":/help/mbuttons_y_XBOX.svg" };
|
||||
sGuiInputConfigList[4] = { "Back", false, "VIEW", ":/help/button_back_XBOX.svg" };
|
||||
sGuiInputConfigList[5] = { "Start", false, "MENU", ":/help/button_start_XBOX.svg" };
|
||||
sGuiInputConfigList[6] = { "A", false, "A", ":/help/mbuttons_a_XBOX.svg" };
|
||||
sGuiInputConfigList[7] = { "B", false, "B", ":/help/mbuttons_b_XBOX.svg" };
|
||||
sGuiInputConfigList[8] = { "X", true, "X", ":/help/mbuttons_x_XBOX.svg" };
|
||||
sGuiInputConfigList[9] = { "Y", true, "Y", ":/help/mbuttons_y_XBOX.svg" };
|
||||
}
|
||||
|
||||
sGuiInputConfigList[10] =
|
||||
{ "LeftShoulder", true, "LEFT SHOULDER", ":/help/button_l.svg" };
|
||||
sGuiInputConfigList[11] =
|
||||
{ "RightShoulder", true, "RIGHT SHOULDER", ":/help/button_r.svg" };
|
||||
sGuiInputConfigList[12] =
|
||||
{ "LeftTrigger", true, "LEFT TRIGGER", ":/help/button_lt.svg" };
|
||||
sGuiInputConfigList[13] =
|
||||
{ "RightTrigger", true, "RIGHT TRIGGER", ":/help/button_rt.svg" };
|
||||
sGuiInputConfigList[14] =
|
||||
{ "LeftThumbstickUp", true, "LEFT THUMBSTICK UP", ":/help/thumbstick_up.svg" };
|
||||
sGuiInputConfigList[15] =
|
||||
{ "LeftThumbstickDown", true, "LEFT THUMBSTICK DOWN", ":/help/thumbstick_down.svg" };
|
||||
sGuiInputConfigList[16] =
|
||||
{ "LeftThumbstickLeft", true, "LEFT THUMBSTICK LEFT", ":/help/thumbstick_left.svg" };
|
||||
sGuiInputConfigList[17] =
|
||||
{ "LeftThumbstickRight", true, "LEFT THUMBSTICK RIGHT", ":/help/thumbstick_right.svg" };
|
||||
sGuiInputConfigList[18] =
|
||||
{ "LeftThumbstickClick", true, "LEFT THUMBSTICK CLICK", ":/help/thumbstick_click.svg" };
|
||||
sGuiInputConfigList[19] =
|
||||
{ "RightThumbstickUp", true, "RIGHT THUMBSTICK UP", ":/help/thumbstick_up.svg" };
|
||||
sGuiInputConfigList[20] =
|
||||
{ "RightThumbstickDown", true, "RIGHT THUMBSTICK DOWN", ":/help/thumbstick_down.svg" };
|
||||
sGuiInputConfigList[21] =
|
||||
{ "RightThumbstickLeft", true, "RIGHT THUMBSTICK LEFT", ":/help/thumbstick_left.svg" };
|
||||
sGuiInputConfigList[22] =
|
||||
{ "RightThumbstickRight", true, "RIGHT THUMBSTICK RIGHT", ":/help/thumbstick_right.svg" };
|
||||
sGuiInputConfigList[23] =
|
||||
{ "RightThumbstickClick", true, "RIGHT THUMBSTICK CLICK", ":/help/thumbstick_click.svg" };
|
||||
sGuiInputConfigList[10] = { "LeftShoulder", true, "LEFT SHOULDER", ":/help/button_l.svg" };
|
||||
sGuiInputConfigList[11] = { "RightShoulder", true, "RIGHT SHOULDER", ":/help/button_r.svg" };
|
||||
sGuiInputConfigList[12] = { "LeftTrigger", true, "LEFT TRIGGER", ":/help/button_lt.svg" };
|
||||
sGuiInputConfigList[13] = { "RightTrigger", true, "RIGHT TRIGGER", ":/help/button_rt.svg" };
|
||||
sGuiInputConfigList[14] = { "LeftThumbstickUp", true, "LEFT THUMBSTICK UP", ":/help/thumbstick_up.svg" };
|
||||
sGuiInputConfigList[15] = { "LeftThumbstickDown", true, "LEFT THUMBSTICK DOWN", ":/help/thumbstick_down.svg" };
|
||||
sGuiInputConfigList[16] = { "LeftThumbstickLeft", true, "LEFT THUMBSTICK LEFT", ":/help/thumbstick_left.svg" };
|
||||
sGuiInputConfigList[17] = { "LeftThumbstickRight", true, "LEFT THUMBSTICK RIGHT", ":/help/thumbstick_right.svg" };
|
||||
sGuiInputConfigList[18] = { "LeftThumbstickClick", true, "LEFT THUMBSTICK CLICK", ":/help/thumbstick_click.svg" };
|
||||
sGuiInputConfigList[19] = { "RightThumbstickUp", true, "RIGHT THUMBSTICK UP", ":/help/thumbstick_up.svg" };
|
||||
sGuiInputConfigList[20] = { "RightThumbstickDown", true, "RIGHT THUMBSTICK DOWN", ":/help/thumbstick_down.svg" };
|
||||
sGuiInputConfigList[21] = { "RightThumbstickLeft", true, "RIGHT THUMBSTICK LEFT", ":/help/thumbstick_left.svg" };
|
||||
sGuiInputConfigList[22] = { "RightThumbstickRight", true, "RIGHT THUMBSTICK RIGHT", ":/help/thumbstick_right.svg" };
|
||||
sGuiInputConfigList[23] = { "RightThumbstickClick", true, "RIGHT THUMBSTICK CLICK", ":/help/thumbstick_click.svg" };
|
||||
// clang-format on
|
||||
}
|
||||
|
||||
void GuiInputConfig::update(int deltaTime)
|
||||
|
@ -336,7 +293,7 @@ void GuiInputConfig::update(int deltaTime)
|
|||
|
||||
void GuiInputConfig::onSizeChanged()
|
||||
{
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f));
|
||||
|
||||
// Update grid.
|
||||
mGrid.setSize(mSize);
|
||||
|
@ -400,8 +357,8 @@ bool GuiInputConfig::assign(Input input, int inputId)
|
|||
// If this input is mapped to something other than "nothing" or the current row,
|
||||
// generate an error. (If it's the same as what it was before, allow it.)
|
||||
if (mTargetConfig->getMappedTo(input).size() > 0 &&
|
||||
!mTargetConfig->isMappedTo(sGuiInputConfigList[inputId].name, input) &&
|
||||
sGuiInputConfigList[inputId].name != "HotKeyEnable") {
|
||||
!mTargetConfig->isMappedTo(sGuiInputConfigList[inputId].name, input) &&
|
||||
sGuiInputConfigList[inputId].name != "HotKeyEnable") {
|
||||
error(mMappings.at(inputId), "Already mapped!");
|
||||
return false;
|
||||
}
|
||||
|
@ -411,8 +368,8 @@ bool GuiInputConfig::assign(Input input, int inputId)
|
|||
input.configured = true;
|
||||
mTargetConfig->mapInput(sGuiInputConfigList[inputId].name, input);
|
||||
|
||||
LOG(LogInfo) << "Mapping [" << input.string() << "] to [" <<
|
||||
sGuiInputConfigList[inputId].name << "]";
|
||||
LOG(LogInfo) << "Mapping [" << input.string() << "] to [" << sGuiInputConfigList[inputId].name
|
||||
<< "]";
|
||||
|
||||
return true;
|
||||
}
|
||||
|
|
|
@ -9,9 +9,9 @@
|
|||
#ifndef ES_CORE_GUIS_GUI_INPUT_CONFIG_H
|
||||
#define ES_CORE_GUIS_GUI_INPUT_CONFIG_H
|
||||
|
||||
#include "GuiComponent.h"
|
||||
#include "components/ComponentGrid.h"
|
||||
#include "components/NinePatchComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
|
||||
class ComponentList;
|
||||
class TextComponent;
|
||||
|
@ -19,8 +19,10 @@ class TextComponent;
|
|||
class GuiInputConfig : public GuiComponent
|
||||
{
|
||||
public:
|
||||
GuiInputConfig(Window* window, InputConfig* target, bool reconfigureAll,
|
||||
const std::function<void()>& okCallback);
|
||||
GuiInputConfig(Window* window,
|
||||
InputConfig* target,
|
||||
bool reconfigureAll,
|
||||
const std::function<void()>& okCallback);
|
||||
|
||||
void populateConfigList();
|
||||
|
||||
|
|
|
@ -14,50 +14,55 @@
|
|||
|
||||
#define HORIZONTAL_PADDING_PX 20
|
||||
|
||||
GuiMsgBox::GuiMsgBox(Window* window, const HelpStyle& helpstyle, const std::string& text,
|
||||
const std::string& name1, const std::function<void()>& func1,
|
||||
const std::string& name2, const std::function<void()>& func2,
|
||||
const std::string& name3, const std::function<void()>& func3,
|
||||
bool disableBackButton,
|
||||
bool deleteOnButtonPress)
|
||||
: GuiComponent(window),
|
||||
mHelpStyle(helpstyle),
|
||||
mBackground(window, ":/graphics/frame.svg"),
|
||||
mGrid(window, Vector2i(1, 2)),
|
||||
mDisableBackButton(disableBackButton),
|
||||
mDeleteOnButtonPress(deleteOnButtonPress)
|
||||
GuiMsgBox::GuiMsgBox(Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& text,
|
||||
const std::string& name1,
|
||||
const std::function<void()>& func1,
|
||||
const std::string& name2,
|
||||
const std::function<void()>& func2,
|
||||
const std::string& name3,
|
||||
const std::function<void()>& func3,
|
||||
bool disableBackButton,
|
||||
bool deleteOnButtonPress)
|
||||
: GuiComponent(window)
|
||||
, mHelpStyle(helpstyle)
|
||||
, mBackground(window, ":/graphics/frame.svg")
|
||||
, mGrid(window, Vector2i(1, 2))
|
||||
, mDisableBackButton(disableBackButton)
|
||||
, mDeleteOnButtonPress(deleteOnButtonPress)
|
||||
{
|
||||
// Adjust the width relative to the aspect ratio of the screen to make the GUI look coherent
|
||||
// regardless of screen type. The 1.778 aspect ratio value is the 16:9 reference.
|
||||
float aspectValue = 1.778f / Renderer::getScreenAspectRatio();
|
||||
|
||||
float width = floorf(Math::clamp(0.60f * aspectValue, 0.60f, 0.80f) *
|
||||
Renderer::getScreenWidth());
|
||||
float minWidth = floorf(Math::clamp(0.30f * aspectValue, 0.10f, 0.50f) *
|
||||
Renderer::getScreenWidth());
|
||||
float width =
|
||||
floorf(Math::clamp(0.60f * aspectValue, 0.60f, 0.80f) * Renderer::getScreenWidth());
|
||||
float minWidth =
|
||||
floorf(Math::clamp(0.30f * aspectValue, 0.10f, 0.50f) * Renderer::getScreenWidth());
|
||||
|
||||
mMsg = std::make_shared<TextComponent>(mWindow, text, Font::get(FONT_SIZE_MEDIUM),
|
||||
0x777777FF, ALIGN_CENTER);
|
||||
mMsg = std::make_shared<TextComponent>(mWindow, text, Font::get(FONT_SIZE_MEDIUM), 0x777777FF,
|
||||
ALIGN_CENTER);
|
||||
mGrid.setEntry(mMsg, Vector2i(0, 0), false, false);
|
||||
|
||||
// Create the buttons.
|
||||
mButtons.push_back(std::make_shared<ButtonComponent>
|
||||
(mWindow, name1, name1, std::bind(&GuiMsgBox::deleteMeAndCall, this, func1)));
|
||||
mButtons.push_back(std::make_shared<ButtonComponent>(
|
||||
mWindow, name1, name1, std::bind(&GuiMsgBox::deleteMeAndCall, this, func1)));
|
||||
if (!name2.empty())
|
||||
mButtons.push_back(std::make_shared<ButtonComponent>
|
||||
(mWindow, name2, name2, std::bind(&GuiMsgBox::deleteMeAndCall, this, func2)));
|
||||
mButtons.push_back(std::make_shared<ButtonComponent>(
|
||||
mWindow, name2, name2, std::bind(&GuiMsgBox::deleteMeAndCall, this, func2)));
|
||||
if (!name3.empty())
|
||||
mButtons.push_back(std::make_shared<ButtonComponent>
|
||||
(mWindow, name3, name3, std::bind(&GuiMsgBox::deleteMeAndCall, this, func3)));
|
||||
mButtons.push_back(std::make_shared<ButtonComponent>(
|
||||
mWindow, name3, name3, std::bind(&GuiMsgBox::deleteMeAndCall, this, func3)));
|
||||
|
||||
// Set accelerator automatically (button to press when "b" is pressed).
|
||||
// Set accelerator automatically (button to press when "B" is pressed).
|
||||
if (mButtons.size() == 1) {
|
||||
mAcceleratorFunc = mButtons.front()->getPressedFunc();
|
||||
}
|
||||
else {
|
||||
for (auto it = mButtons.cbegin(); it != mButtons.cend(); it++) {
|
||||
if (Utils::String::toUpper((*it)->getText()) == "OK" ||
|
||||
Utils::String::toUpper((*it)->getText()) == "NO") {
|
||||
Utils::String::toUpper((*it)->getText()) == "NO") {
|
||||
mAcceleratorFunc = (*it)->getPressedFunc();
|
||||
break;
|
||||
}
|
||||
|
@ -80,14 +85,14 @@ GuiMsgBox::GuiMsgBox(Window* window, const HelpStyle& helpstyle, const std::stri
|
|||
|
||||
// Now that we know width, we can find height.
|
||||
mMsg->setSize(width, 0); // mMsg->getSize.y() now returns the proper length.
|
||||
const float msgHeight = std::max(Font::get(FONT_SIZE_LARGE)->getHeight(),
|
||||
mMsg->getSize().y() * 1.225f);
|
||||
const float msgHeight =
|
||||
std::max(Font::get(FONT_SIZE_LARGE)->getHeight(), mMsg->getSize().y() * 1.225f);
|
||||
setSize(width + HORIZONTAL_PADDING_PX * 2 * Renderer::getScreenWidthModifier(),
|
||||
msgHeight + mButtonGrid->getSize().y());
|
||||
|
||||
// Center for good measure.
|
||||
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2.0f,
|
||||
(Renderer::getScreenHeight() - mSize.y()) / 2.0f);
|
||||
(Renderer::getScreenHeight() - mSize.y()) / 2.0f);
|
||||
|
||||
addChild(&mBackground);
|
||||
addChild(&mGrid);
|
||||
|
@ -103,8 +108,8 @@ void GuiMsgBox::changeText(const std::string& newText)
|
|||
// reference.
|
||||
float aspectValue = 1.778f / Renderer::getScreenAspectRatio();
|
||||
|
||||
float width = floorf(Math::clamp(0.60f * aspectValue, 0.60f, 0.80f) *
|
||||
Renderer::getScreenWidth());
|
||||
float width =
|
||||
floorf(Math::clamp(0.60f * aspectValue, 0.60f, 0.80f) * Renderer::getScreenWidth());
|
||||
float minWidth = Renderer::getScreenWidth() * 0.3f;
|
||||
|
||||
// Decide final width.
|
||||
|
@ -119,8 +124,8 @@ void GuiMsgBox::changeText(const std::string& newText)
|
|||
|
||||
// Now that we know width, we can find height.
|
||||
mMsg->setSize(width, 0); // mMsg->getSize.y() now returns the proper length.
|
||||
const float msgHeight = std::max(Font::get(FONT_SIZE_LARGE)->getHeight(),
|
||||
mMsg->getSize().y() * 1.225f);
|
||||
const float msgHeight =
|
||||
std::max(Font::get(FONT_SIZE_LARGE)->getHeight(), mMsg->getSize().y() * 1.225f);
|
||||
setSize(width + HORIZONTAL_PADDING_PX * 2 * Renderer::getScreenWidthModifier(),
|
||||
msgHeight + mButtonGrid->getSize().y());
|
||||
}
|
||||
|
@ -152,10 +157,10 @@ void GuiMsgBox::onSizeChanged()
|
|||
|
||||
// Update messagebox size.
|
||||
mMsg->setSize(mSize.x() - HORIZONTAL_PADDING_PX * 2 * Renderer::getScreenWidthModifier(),
|
||||
mGrid.getRowHeight(0));
|
||||
mGrid.getRowHeight(0));
|
||||
mGrid.onSizeChanged();
|
||||
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f));
|
||||
}
|
||||
|
||||
void GuiMsgBox::deleteMeAndCall(const std::function<void()>& func)
|
||||
|
|
|
@ -10,9 +10,9 @@
|
|||
#ifndef ES_CORE_GUIS_GUI_MSG_BOX_H
|
||||
#define ES_CORE_GUIS_GUI_MSG_BOX_H
|
||||
|
||||
#include "GuiComponent.h"
|
||||
#include "components/ComponentGrid.h"
|
||||
#include "components/NinePatchComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
|
||||
class ButtonComponent;
|
||||
class TextComponent;
|
||||
|
@ -20,18 +20,17 @@ class TextComponent;
|
|||
class GuiMsgBox : public GuiComponent
|
||||
{
|
||||
public:
|
||||
GuiMsgBox(
|
||||
Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& text,
|
||||
const std::string& name1 = "OK",
|
||||
const std::function<void()>& func1 = nullptr,
|
||||
const std::string& name2 = "",
|
||||
const std::function<void()>& func2 = nullptr,
|
||||
const std::string& name3 = "",
|
||||
const std::function<void()>& func3 = nullptr,
|
||||
bool disableBackButton = false,
|
||||
bool deleteOnButtonPress = true);
|
||||
GuiMsgBox(Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& text,
|
||||
const std::string& name1 = "OK",
|
||||
const std::function<void()>& func1 = nullptr,
|
||||
const std::string& name2 = "",
|
||||
const std::function<void()>& func2 = nullptr,
|
||||
const std::string& name3 = "",
|
||||
const std::function<void()>& func3 = nullptr,
|
||||
bool disableBackButton = false,
|
||||
bool deleteOnButtonPress = true);
|
||||
|
||||
void changeText(const std::string& newText);
|
||||
|
||||
|
@ -39,7 +38,7 @@ public:
|
|||
void onSizeChanged() override;
|
||||
|
||||
std::vector<HelpPrompt> getHelpPrompts() override;
|
||||
HelpStyle getHelpStyle() override { return mHelpStyle; };
|
||||
HelpStyle getHelpStyle() override { return mHelpStyle; }
|
||||
|
||||
private:
|
||||
void deleteMeAndCall(const std::function<void()>& func);
|
||||
|
|
|
@ -8,58 +8,60 @@
|
|||
|
||||
#include "guis/GuiTextEditPopup.h"
|
||||
|
||||
#include "Window.h"
|
||||
#include "components/ButtonComponent.h"
|
||||
#include "components/MenuComponent.h"
|
||||
#include "components/TextEditComponent.h"
|
||||
#include "guis/GuiMsgBox.h"
|
||||
#include "Window.h"
|
||||
|
||||
GuiTextEditPopup::GuiTextEditPopup(
|
||||
Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& title,
|
||||
const std::string& initValue,
|
||||
const std::function<void(const std::string&)>& okCallback,
|
||||
bool multiLine,
|
||||
const std::string& acceptBtnText,
|
||||
const std::string& saveConfirmationText)
|
||||
: GuiComponent(window),
|
||||
mHelpStyle(helpstyle),
|
||||
mBackground(window, ":/graphics/frame.svg"),
|
||||
mGrid(window, Vector2i(1, 3)),
|
||||
mMultiLine(multiLine),
|
||||
mInitValue(initValue),
|
||||
mOkCallback(okCallback),
|
||||
mSaveConfirmationText(saveConfirmationText)
|
||||
GuiTextEditPopup::GuiTextEditPopup(Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& title,
|
||||
const std::string& initValue,
|
||||
const std::function<void(const std::string&)>& okCallback,
|
||||
bool multiLine,
|
||||
const std::string& acceptBtnText,
|
||||
const std::string& saveConfirmationText)
|
||||
: GuiComponent(window)
|
||||
, mHelpStyle(helpstyle)
|
||||
, mBackground(window, ":/graphics/frame.svg")
|
||||
, mGrid(window, Vector2i(1, 3))
|
||||
, mMultiLine(multiLine)
|
||||
, mInitValue(initValue)
|
||||
, mOkCallback(okCallback)
|
||||
, mSaveConfirmationText(saveConfirmationText)
|
||||
{
|
||||
addChild(&mBackground);
|
||||
addChild(&mGrid);
|
||||
|
||||
mTitle = std::make_shared<TextComponent>(mWindow, Utils::String::toUpper(title),
|
||||
Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER);
|
||||
Font::get(FONT_SIZE_MEDIUM), 0x555555FF, ALIGN_CENTER);
|
||||
|
||||
mText = std::make_shared<TextEditComponent>(mWindow);
|
||||
mText->setValue(initValue);
|
||||
|
||||
std::vector<std::shared_ptr<ButtonComponent>> buttons;
|
||||
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, acceptBtnText, acceptBtnText,
|
||||
[this, okCallback] { okCallback(mText->getValue()); delete this; }));
|
||||
[this, okCallback] {
|
||||
okCallback(mText->getValue());
|
||||
delete this;
|
||||
}));
|
||||
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "CLEAR", "clear",
|
||||
[this] { mText->setValue(""); }));
|
||||
[this] { mText->setValue(""); }));
|
||||
buttons.push_back(std::make_shared<ButtonComponent>(mWindow, "CANCEL", "discard changes",
|
||||
[this] { delete this; }));
|
||||
[this] { delete this; }));
|
||||
|
||||
mButtonGrid = makeButtonGrid(mWindow, buttons);
|
||||
|
||||
mGrid.setEntry(mTitle, Vector2i(0, 0), false, true);
|
||||
mGrid.setEntry(mText, Vector2i(0, 1), true, false, Vector2i(1, 1),
|
||||
GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM);
|
||||
GridFlags::BORDER_TOP | GridFlags::BORDER_BOTTOM);
|
||||
mGrid.setEntry(mButtonGrid, Vector2i(0, 2), true, false);
|
||||
|
||||
float textHeight = mText->getFont()->getHeight();
|
||||
|
||||
if (multiLine)
|
||||
textHeight *= 6;
|
||||
textHeight *= 6.0f;
|
||||
mText->setSize(0, textHeight);
|
||||
|
||||
// Adjust the width relative to the aspect ratio of the screen to make the GUI look coherent
|
||||
|
@ -67,16 +69,16 @@ GuiTextEditPopup::GuiTextEditPopup(
|
|||
float aspectValue = 1.778f / Renderer::getScreenAspectRatio();
|
||||
float width = Math::clamp(0.50f * aspectValue, 0.40f, 0.70f) * Renderer::getScreenWidth();
|
||||
|
||||
setSize(width, mTitle->getFont()->getHeight() +
|
||||
textHeight + mButtonGrid->getSize().y() + mButtonGrid->getSize().y() / 2);
|
||||
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2, (Renderer::getScreenHeight() -
|
||||
mSize.y()) / 2);
|
||||
setSize(width, mTitle->getFont()->getHeight() + textHeight + mButtonGrid->getSize().y() +
|
||||
mButtonGrid->getSize().y() / 2.0f);
|
||||
setPosition((Renderer::getScreenWidth() - mSize.x()) / 2.0f,
|
||||
(Renderer::getScreenHeight() - mSize.y()) / 2.0f);
|
||||
mText->startEditing();
|
||||
}
|
||||
|
||||
void GuiTextEditPopup::onSizeChanged()
|
||||
{
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32, -32));
|
||||
mBackground.fitTo(mSize, Vector3f::Zero(), Vector2f(-32.0f, -32.0f));
|
||||
|
||||
mText->setSize(mSize.x() - 40, mText->getSize().y());
|
||||
|
||||
|
@ -95,9 +97,18 @@ bool GuiTextEditPopup::input(InputConfig* config, Input input)
|
|||
if (config->isMappedTo("b", input) && input.value) {
|
||||
if (mText->getValue() != mInitValue) {
|
||||
// Changes were made, ask if the user wants to save them.
|
||||
mWindow->pushGui(new GuiMsgBox(mWindow, mHelpStyle, mSaveConfirmationText, "YES",
|
||||
[this] { this->mOkCallback(mText->getValue()); delete this; return true; },
|
||||
"NO", [this] { delete this; return false; }));
|
||||
mWindow->pushGui(new GuiMsgBox(
|
||||
mWindow, mHelpStyle, mSaveConfirmationText, "YES",
|
||||
[this] {
|
||||
this->mOkCallback(mText->getValue());
|
||||
delete this;
|
||||
return true;
|
||||
},
|
||||
"NO",
|
||||
[this] {
|
||||
delete this;
|
||||
return false;
|
||||
}));
|
||||
}
|
||||
else {
|
||||
delete this;
|
||||
|
|
|
@ -9,9 +9,9 @@
|
|||
#ifndef ES_CORE_GUIS_GUI_TEXT_EDIT_POPUP_H
|
||||
#define ES_CORE_GUIS_GUI_TEXT_EDIT_POPUP_H
|
||||
|
||||
#include "GuiComponent.h"
|
||||
#include "components/ComponentGrid.h"
|
||||
#include "components/NinePatchComponent.h"
|
||||
#include "GuiComponent.h"
|
||||
|
||||
class TextComponent;
|
||||
class TextEditComponent;
|
||||
|
@ -19,21 +19,20 @@ class TextEditComponent;
|
|||
class GuiTextEditPopup : public GuiComponent
|
||||
{
|
||||
public:
|
||||
GuiTextEditPopup(
|
||||
Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& title,
|
||||
const std::string& initValue,
|
||||
const std::function<void(const std::string&)>& okCallback,
|
||||
bool multiLine,
|
||||
const std::string& acceptBtnText = "OK",
|
||||
const std::string& saveConfirmationText = "SAVE CHANGES?");
|
||||
GuiTextEditPopup(Window* window,
|
||||
const HelpStyle& helpstyle,
|
||||
const std::string& title,
|
||||
const std::string& initValue,
|
||||
const std::function<void(const std::string&)>& okCallback,
|
||||
bool multiLine,
|
||||
const std::string& acceptBtnText = "OK",
|
||||
const std::string& saveConfirmationText = "SAVE CHANGES?");
|
||||
|
||||
bool input(InputConfig* config, Input input) override;
|
||||
void onSizeChanged() override;
|
||||
|
||||
std::vector<HelpPrompt> getHelpPrompts() override;
|
||||
HelpStyle getHelpStyle() override { return mHelpStyle; };
|
||||
HelpStyle getHelpStyle() override { return mHelpStyle; }
|
||||
|
||||
private:
|
||||
NinePatchComponent mBackground;
|
||||
|
|
|
@ -17,20 +17,22 @@ namespace Math
|
|||
|
||||
float smoothStep(const float _left, const float _right, const float _x)
|
||||
{
|
||||
const float x = clamp((_x - _left)/(_right - _left), 0.0f, 1.0f);
|
||||
const float x = clamp((_x - _left) / (_right - _left), 0.0f, 1.0f);
|
||||
return x * x * (3 - (2 * x));
|
||||
}
|
||||
|
||||
float smootherStep(const float _left, const float _right, const float _x)
|
||||
{
|
||||
const float x = clamp((_x - _left)/(_right - _left), 0.0f, 1.0f);
|
||||
const float x = clamp((_x - _left) / (_right - _left), 0.0f, 1.0f);
|
||||
return x * x * x * (x * ((x * 6) - 15) + 10);
|
||||
}
|
||||
|
||||
namespace Scroll
|
||||
{
|
||||
float bounce(const float _delayTime, const float _scrollTime,
|
||||
const float _currentTime, const float _scrollLength)
|
||||
float bounce(const float _delayTime,
|
||||
const float _scrollTime,
|
||||
const float _currentTime,
|
||||
const float _scrollLength)
|
||||
{
|
||||
if (_currentTime < _delayTime) {
|
||||
// Wait.
|
||||
|
@ -47,16 +49,18 @@ namespace Math
|
|||
}
|
||||
else if (_currentTime < (_delayTime + _scrollTime + _delayTime + _scrollTime)) {
|
||||
// Lerp back from scrollLength to 0.
|
||||
const float fraction = (_currentTime - _delayTime - _scrollTime -
|
||||
_delayTime) / _scrollTime;
|
||||
const float fraction =
|
||||
(_currentTime - _delayTime - _scrollTime - _delayTime) / _scrollTime;
|
||||
return lerp(_scrollLength, 0.0f, smootherStep(0, 1, fraction));
|
||||
}
|
||||
// And back to waiting.
|
||||
return 0;
|
||||
}
|
||||
|
||||
float loop(const float _delayTime, const float _scrollTime,
|
||||
const float _currentTime, const float _scrollLength)
|
||||
float loop(const float _delayTime,
|
||||
const float _scrollTime,
|
||||
const float _currentTime,
|
||||
const float _scrollLength)
|
||||
{
|
||||
if (_currentTime < _delayTime) {
|
||||
// Wait.
|
||||
|
@ -72,5 +76,7 @@ namespace Math
|
|||
return 0;
|
||||
|
||||
} // Math::Scroll::loop
|
||||
} // Math::Scroll::
|
||||
} // Math::
|
||||
|
||||
} // namespace Scroll
|
||||
|
||||
} // namespace Math
|
||||
|
|
|
@ -11,15 +11,14 @@
|
|||
|
||||
#include <algorithm>
|
||||
|
||||
#define ES_PI (3.1415926535897932384626433832795028841971693993751058209749445923)
|
||||
#define ES_RAD_TO_DEG(_x) ((_x) * (180.0 / ES_PI))
|
||||
#define ES_DEG_TO_RAD(_x) ((_x) * (ES_PI / 180.0))
|
||||
#define ES_PI (3.1415926535897932384626433832795028841971693993751058209749445923)
|
||||
#define ES_RAD_TO_DEG(_x) ((_x) * (180.0 / ES_PI))
|
||||
#define ES_DEG_TO_RAD(_x) ((_x) * (ES_PI / 180.0))
|
||||
|
||||
namespace Math
|
||||
{
|
||||
// When moving to the C++20 standard these functions are no longer required.
|
||||
template<typename T>
|
||||
T const& clamp(const T& _num, const T& _min, const T& _max)
|
||||
template <typename T> T const& clamp(const T& _num, const T& _min, const T& _max)
|
||||
{
|
||||
return std::max(std::min(_num, _max), _min);
|
||||
}
|
||||
|
@ -30,11 +29,16 @@ namespace Math
|
|||
|
||||
namespace Scroll
|
||||
{
|
||||
float bounce(const float _delayTime, const float _scrollTime,
|
||||
const float _currentTime, const float _scrollLength);
|
||||
float loop(const float _delayTime, const float _scrollTime,
|
||||
const float _currentTime, const float _scrollLength);
|
||||
}
|
||||
}
|
||||
float bounce(const float _delayTime,
|
||||
const float _scrollTime,
|
||||
const float _currentTime,
|
||||
const float _scrollLength);
|
||||
float loop(const float _delayTime,
|
||||
const float _scrollTime,
|
||||
const float _currentTime,
|
||||
const float _scrollLength);
|
||||
} // namespace Scroll
|
||||
|
||||
} // namespace Math
|
||||
|
||||
#endif // ES_CORE_MATH_MISC_H
|
||||
|
|
|
@ -10,6 +10,7 @@
|
|||
|
||||
#include <cmath>
|
||||
|
||||
// clang-format off
|
||||
const Transform4x4f Transform4x4f::operator*(const Transform4x4f& _other) const
|
||||
{
|
||||
const float* tm = reinterpret_cast<const float*>(this);
|
||||
|
@ -321,3 +322,4 @@ Transform4x4f& Transform4x4f::round()
|
|||
|
||||
return *this;
|
||||
}
|
||||
// clang-format on
|
||||
|
|
|
@ -9,44 +9,43 @@
|
|||
#ifndef ES_CORE_MATH_TRANSFORM4X4F_H
|
||||
#define ES_CORE_MATH_TRANSFORM4X4F_H
|
||||
|
||||
#include "math/Vector4f.h"
|
||||
#include "math/Vector3f.h"
|
||||
#include "math/Vector4f.h"
|
||||
|
||||
class Transform4x4f
|
||||
{
|
||||
public:
|
||||
Transform4x4f() {}
|
||||
Transform4x4f(
|
||||
const Vector4f& _r0,
|
||||
const Vector4f& _r1,
|
||||
const Vector4f& _r2,
|
||||
const Vector4f& _r3)
|
||||
: mR0(_r0),
|
||||
mR1(_r1),
|
||||
mR2(_r2),
|
||||
mR3(_r3) {}
|
||||
Transform4x4f(const Vector4f& _r0,
|
||||
const Vector4f& _r1,
|
||||
const Vector4f& _r2,
|
||||
const Vector4f& _r3)
|
||||
: mR0(_r0)
|
||||
, mR1(_r1)
|
||||
, mR2(_r2)
|
||||
, mR3(_r3)
|
||||
{
|
||||
}
|
||||
|
||||
const Transform4x4f operator*(const Transform4x4f& _other) const;
|
||||
const Vector3f operator*(const Vector3f& _other) const;
|
||||
Transform4x4f& operator*=(const Transform4x4f& _other)
|
||||
{ *this = *this * _other; return *this; }
|
||||
{
|
||||
*this = *this * _other;
|
||||
return *this;
|
||||
}
|
||||
|
||||
inline Vector4f& r0() { return mR0; }
|
||||
inline Vector4f& r1() { return mR1; }
|
||||
inline Vector4f& r2() { return mR2; }
|
||||
inline Vector4f& r3() { return mR3; }
|
||||
inline const Vector4f& r0() const { return mR0; }
|
||||
inline const Vector4f& r1() const { return mR1; }
|
||||
inline const Vector4f& r2() const { return mR2; }
|
||||
inline const Vector4f& r3() const { return mR3; }
|
||||
Vector4f& r0() { return mR0; }
|
||||
Vector4f& r1() { return mR1; }
|
||||
Vector4f& r2() { return mR2; }
|
||||
Vector4f& r3() { return mR3; }
|
||||
const Vector4f& r0() const { return mR0; }
|
||||
const Vector4f& r1() const { return mR1; }
|
||||
const Vector4f& r2() const { return mR2; }
|
||||
const Vector4f& r3() const { return mR3; }
|
||||
|
||||
Transform4x4f& orthoProjection(
|
||||
float _left,
|
||||
float _right,
|
||||
float _bottom,
|
||||
float _top,
|
||||
float _near,
|
||||
float _far);
|
||||
float _left, float _right, float _bottom, float _top, float _near, float _far);
|
||||
Transform4x4f& invert(const Transform4x4f& _other);
|
||||
Transform4x4f& scale(const Vector3f& _scale);
|
||||
Transform4x4f& rotate(const float _angle, const Vector3f& _axis);
|
||||
|
@ -56,11 +55,13 @@ public:
|
|||
Transform4x4f& translate(const Vector3f& _translation);
|
||||
Transform4x4f& round();
|
||||
|
||||
inline Vector3f& translation() { return mR3.v3(); }
|
||||
inline const Vector3f& translation() const { return mR3.v3(); }
|
||||
Vector3f& translation() { return mR3.v3(); }
|
||||
const Vector3f& translation() const { return mR3.v3(); }
|
||||
|
||||
static const Transform4x4f Identity()
|
||||
{ return { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } }; }
|
||||
{
|
||||
return { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
|
||||
}
|
||||
|
||||
protected:
|
||||
Vector4f mR0;
|
||||
|
|
|
@ -20,26 +20,41 @@ class Vector2f
|
|||
{
|
||||
public:
|
||||
Vector2f() {}
|
||||
Vector2f(const float _f) : mX(_f), mY(_f) {}
|
||||
Vector2f(const float _x, const float _y) : mX(_x), mY(_y) {}
|
||||
explicit Vector2f(const Vector3f& _v) : mX((reinterpret_cast<const Vector2f&>(_v)).mX),
|
||||
mY((reinterpret_cast<const Vector2f&>(_v)).mY) {}
|
||||
explicit Vector2f(const Vector4f& _v) : mX((reinterpret_cast<const Vector2f&>(_v)).mX),
|
||||
mY((reinterpret_cast<const Vector2f&>(_v)).mY) {}
|
||||
Vector2f(const float _f)
|
||||
: mX(_f)
|
||||
, mY(_f)
|
||||
{
|
||||
}
|
||||
Vector2f(const float _x, const float _y)
|
||||
: mX(_x)
|
||||
, mY(_y)
|
||||
{
|
||||
}
|
||||
explicit Vector2f(const Vector3f& _v)
|
||||
: mX((reinterpret_cast<const Vector2f&>(_v)).mX)
|
||||
, mY((reinterpret_cast<const Vector2f&>(_v)).mY)
|
||||
{
|
||||
}
|
||||
explicit Vector2f(const Vector4f& _v)
|
||||
: mX((reinterpret_cast<const Vector2f&>(_v)).mX)
|
||||
, mY((reinterpret_cast<const Vector2f&>(_v)).mY)
|
||||
{
|
||||
}
|
||||
|
||||
// clang-format off
|
||||
const bool operator==(const Vector2f& _other) const
|
||||
{ return ((mX == _other.mX) && (mY == _other.mY)); }
|
||||
{ return ((mX == _other.mX) && (mY == _other.mY)); }
|
||||
const bool operator!=(const Vector2f& _other) const
|
||||
{ return ((mX != _other.mX) || (mY != _other.mY)); }
|
||||
{ return ((mX != _other.mX) || (mY != _other.mY)); }
|
||||
|
||||
const Vector2f operator+(const Vector2f& _other) const
|
||||
{ return { mX + _other.mX, mY + _other.mY }; }
|
||||
{ return { mX + _other.mX, mY + _other.mY }; }
|
||||
const Vector2f operator-(const Vector2f& _other) const
|
||||
{ return { mX - _other.mX, mY - _other.mY }; }
|
||||
{ return { mX - _other.mX, mY - _other.mY }; }
|
||||
const Vector2f operator*(const Vector2f& _other) const
|
||||
{ return { mX * _other.mX, mY * _other.mY }; }
|
||||
{ return { mX * _other.mX, mY * _other.mY }; }
|
||||
const Vector2f operator/(const Vector2f& _other) const
|
||||
{ return { mX / _other.mX, mY / _other.mY }; }
|
||||
{ return { mX / _other.mX, mY / _other.mY }; }
|
||||
|
||||
const Vector2f operator+(const float& _other) const { return { mX + _other, mY + _other }; }
|
||||
const Vector2f operator-(const float& _other) const { return { mX - _other, mY - _other }; }
|
||||
|
@ -59,21 +74,22 @@ public:
|
|||
Vector2f& operator/=(const float& _other) { *this = *this / _other; return *this; }
|
||||
|
||||
float& operator[](const int _index)
|
||||
{ assert(_index < 2 && "index out of range"); return (&mX)[_index]; }
|
||||
{ assert(_index < 2 && "index out of range"); return (&mX)[_index]; }
|
||||
const float& operator[](const int _index) const
|
||||
{ assert(_index < 2 && "index out of range"); return (&mX)[_index]; }
|
||||
{ assert(_index < 2 && "index out of range"); return (&mX)[_index]; }
|
||||
// clang-format on
|
||||
|
||||
inline float& x() { return mX; }
|
||||
inline float& y() { return mY; }
|
||||
inline const float& x() const { return mX; }
|
||||
inline const float& y() const { return mY; }
|
||||
float& x() { return mX; }
|
||||
float& y() { return mY; }
|
||||
const float& x() const { return mX; }
|
||||
const float& y() const { return mY; }
|
||||
|
||||
Vector2f& round();
|
||||
Vector2f& lerp (const Vector2f& _start, const Vector2f& _end, const float _fraction);
|
||||
Vector2f& lerp(const Vector2f& _start, const Vector2f& _end, const float _fraction);
|
||||
|
||||
static const Vector2f Zero() { return { 0, 0 }; }
|
||||
static const Vector2f UnitX() { return { 1, 0 }; }
|
||||
static const Vector2f UnitY() { return { 0, 1 }; }
|
||||
static const Vector2f Zero() { return { 0.0f, 0.0f }; }
|
||||
static const Vector2f UnitX() { return { 1.0f, 0.0f }; }
|
||||
static const Vector2f UnitY() { return { 0.0f, 1.0f }; }
|
||||
|
||||
private:
|
||||
float mX;
|
||||
|
|
|
@ -15,22 +15,31 @@ class Vector2i
|
|||
{
|
||||
public:
|
||||
Vector2i() {}
|
||||
Vector2i(const int _i) : mX(_i), mY(_i) {}
|
||||
Vector2i(const int _x, const int _y) : mX(_x), mY(_y) {}
|
||||
Vector2i(const int _i)
|
||||
: mX(_i)
|
||||
, mY(_i)
|
||||
{
|
||||
}
|
||||
Vector2i(const int _x, const int _y)
|
||||
: mX(_x)
|
||||
, mY(_y)
|
||||
{
|
||||
}
|
||||
|
||||
// clang-format off
|
||||
const bool operator==(const Vector2i& _other) const
|
||||
{ return ((mX == _other.mX) && (mY == _other.mY)); }
|
||||
{ return ((mX == _other.mX) && (mY == _other.mY)); }
|
||||
const bool operator!=(const Vector2i& _other) const
|
||||
{ return ((mX != _other.mX) || (mY != _other.mY)); }
|
||||
{ return ((mX != _other.mX) || (mY != _other.mY)); }
|
||||
|
||||
const Vector2i operator+(const Vector2i& _other) const
|
||||
{ return { mX + _other.mX, mY + _other.mY }; }
|
||||
{ return { mX + _other.mX, mY + _other.mY }; }
|
||||
const Vector2i operator-(const Vector2i& _other) const
|
||||
{ return { mX - _other.mX, mY - _other.mY }; }
|
||||
{ return { mX - _other.mX, mY - _other.mY }; }
|
||||
const Vector2i operator*(const Vector2i& _other) const
|
||||
{ return { mX * _other.mX, mY * _other.mY }; }
|
||||
{ return { mX * _other.mX, mY * _other.mY }; }
|
||||
const Vector2i operator/(const Vector2i& _other) const
|
||||
{ return { mX / _other.mX, mY / _other.mY }; }
|
||||
{ return { mX / _other.mX, mY / _other.mY }; }
|
||||
|
||||
const Vector2i operator+(const int& _other) const { return { mX + _other, mY + _other }; }
|
||||
const Vector2i operator-(const int& _other) const { return { mX - _other, mY - _other }; }
|
||||
|
@ -50,14 +59,15 @@ public:
|
|||
Vector2i& operator/=(const int& _other) { *this = *this / _other; return *this; }
|
||||
|
||||
int& operator[](const int _index)
|
||||
{ assert(_index < 2 && "index out of range"); return (&mX)[_index]; }
|
||||
{ assert(_index < 2 && "index out of range"); return (&mX)[_index]; }
|
||||
const int& operator[](const int _index) const
|
||||
{ assert(_index < 2 && "index out of range"); return (&mX)[_index]; }
|
||||
{ assert(_index < 2 && "index out of range"); return (&mX)[_index]; }
|
||||
// clang-format on
|
||||
|
||||
inline int& x() { return mX; }
|
||||
inline int& y() { return mY; }
|
||||
inline const int& x() const { return mX; }
|
||||
inline const int& y() const { return mY; }
|
||||
int& x() { return mX; }
|
||||
int& y() { return mY; }
|
||||
const int& x() const { return mX; }
|
||||
const int& y() const { return mY; }
|
||||
|
||||
static const Vector2i Zero() { return { 0, 0 }; }
|
||||
static const Vector2i UnitX() { return { 1, 0 }; }
|
||||
|
|
|
@ -20,39 +20,60 @@ class Vector3f
|
|||
{
|
||||
public:
|
||||
Vector3f() {}
|
||||
Vector3f(const float _f) : mX(_f), mY(_f), mZ(_f) {}
|
||||
Vector3f(const float _x, const float _y, const float _z) : mX(_x), mY(_y), mZ(_z) {}
|
||||
explicit Vector3f(const Vector2f& _v) : mX((reinterpret_cast<const Vector3f&>(_v)).mX),
|
||||
mY((reinterpret_cast<const Vector3f&>(_v)).mY), mZ(0) {}
|
||||
Vector3f(const float _f)
|
||||
: mX(_f)
|
||||
, mY(_f)
|
||||
, mZ(_f)
|
||||
{
|
||||
}
|
||||
Vector3f(const float _x, const float _y, const float _z)
|
||||
: mX(_x)
|
||||
, mY(_y)
|
||||
, mZ(_z)
|
||||
{
|
||||
}
|
||||
explicit Vector3f(const Vector2f& _v)
|
||||
: mX((reinterpret_cast<const Vector3f&>(_v)).mX)
|
||||
, mY((reinterpret_cast<const Vector3f&>(_v)).mY)
|
||||
, mZ(0)
|
||||
{
|
||||
}
|
||||
explicit Vector3f(const Vector2f& _v, const float _z)
|
||||
: mX((reinterpret_cast<const Vector3f&>(_v)).mX),
|
||||
mY((reinterpret_cast<const Vector3f&>(_v)).mY), mZ(_z) {}
|
||||
explicit Vector3f(const Vector4f& _v) : mX((reinterpret_cast<const Vector3f&>(_v)).mX),
|
||||
mY((reinterpret_cast<const Vector3f&>(_v)).mY),
|
||||
mZ((reinterpret_cast<const Vector3f&>(_v)).mZ) {}
|
||||
: mX((reinterpret_cast<const Vector3f&>(_v)).mX)
|
||||
, mY((reinterpret_cast<const Vector3f&>(_v)).mY)
|
||||
, mZ(_z)
|
||||
{
|
||||
}
|
||||
explicit Vector3f(const Vector4f& _v)
|
||||
: mX((reinterpret_cast<const Vector3f&>(_v)).mX)
|
||||
, mY((reinterpret_cast<const Vector3f&>(_v)).mY)
|
||||
, mZ((reinterpret_cast<const Vector3f&>(_v)).mZ)
|
||||
{
|
||||
}
|
||||
|
||||
// clang-format off
|
||||
const bool operator==(const Vector3f& _other) const
|
||||
{ return ((mX == _other.mX) && (mY == _other.mY) && (mZ == _other.mZ)); }
|
||||
{ return ((mX == _other.mX) && (mY == _other.mY) && (mZ == _other.mZ)); }
|
||||
const bool operator!=(const Vector3f& _other) const
|
||||
{ return ((mX != _other.mX) || (mY != _other.mY) || (mZ != _other.mZ)); }
|
||||
{ return ((mX != _other.mX) || (mY != _other.mY) || (mZ != _other.mZ)); }
|
||||
|
||||
const Vector3f operator+(const Vector3f& _other) const
|
||||
{ return { mX + _other.mX, mY + _other.mY, mZ + _other.mZ }; }
|
||||
{ return { mX + _other.mX, mY + _other.mY, mZ + _other.mZ }; }
|
||||
const Vector3f operator-(const Vector3f& _other) const
|
||||
{ return { mX - _other.mX, mY - _other.mY, mZ - _other.mZ }; }
|
||||
{ return { mX - _other.mX, mY - _other.mY, mZ - _other.mZ }; }
|
||||
const Vector3f operator*(const Vector3f& _other) const
|
||||
{ return { mX * _other.mX, mY * _other.mY, mZ * _other.mZ }; }
|
||||
{ return { mX * _other.mX, mY * _other.mY, mZ * _other.mZ }; }
|
||||
const Vector3f operator/(const Vector3f& _other) const
|
||||
{ return { mX / _other.mX, mY / _other.mY, mZ / _other.mZ }; }
|
||||
{ return { mX / _other.mX, mY / _other.mY, mZ / _other.mZ }; }
|
||||
|
||||
const Vector3f operator+(const float& _other) const
|
||||
{ return { mX + _other, mY + _other, mZ + _other }; }
|
||||
{ return { mX + _other, mY + _other, mZ + _other }; }
|
||||
const Vector3f operator-(const float& _other) const
|
||||
{ return { mX - _other, mY - _other, mZ - _other }; }
|
||||
{ return { mX - _other, mY - _other, mZ - _other }; }
|
||||
const Vector3f operator*(const float& _other) const
|
||||
{ return { mX * _other, mY * _other, mZ * _other }; }
|
||||
{ return { mX * _other, mY * _other, mZ * _other }; }
|
||||
const Vector3f operator/(const float& _other) const
|
||||
{ return { mX / _other, mY / _other, mZ / _other }; }
|
||||
{ return { mX / _other, mY / _other, mZ / _other }; }
|
||||
|
||||
const Vector3f operator-() const { return { -mX , -mY, -mZ }; }
|
||||
|
||||
|
@ -67,27 +88,28 @@ public:
|
|||
Vector3f& operator/=(const float& _other) { *this = *this / _other; return *this; }
|
||||
|
||||
float& operator[](const int _index)
|
||||
{ assert(_index < 3 && "index out of range"); return (&mX)[_index]; }
|
||||
{ assert(_index < 3 && "index out of range"); return (&mX)[_index]; }
|
||||
const float& operator[](const int _index) const
|
||||
{ assert(_index < 3 && "index out of range"); return (&mX)[_index]; }
|
||||
{ assert(_index < 3 && "index out of range"); return (&mX)[_index]; }
|
||||
// clang-format on
|
||||
|
||||
inline float& x() { return mX; }
|
||||
inline float& y() { return mY; }
|
||||
inline float& z() { return mZ; }
|
||||
inline const float& x() const { return mX; }
|
||||
inline const float& y() const { return mY; }
|
||||
inline const float& z() const { return mZ; }
|
||||
float& x() { return mX; }
|
||||
float& y() { return mY; }
|
||||
float& z() { return mZ; }
|
||||
const float& x() const { return mX; }
|
||||
const float& y() const { return mY; }
|
||||
const float& z() const { return mZ; }
|
||||
|
||||
inline Vector2f& v2() { return *reinterpret_cast<Vector2f*>(this); }
|
||||
inline const Vector2f& v2() const { return *reinterpret_cast<const Vector2f*>(this); }
|
||||
Vector2f& v2() { return *reinterpret_cast<Vector2f*>(this); }
|
||||
const Vector2f& v2() const { return *reinterpret_cast<const Vector2f*>(this); }
|
||||
|
||||
Vector3f& round();
|
||||
Vector3f& lerp(const Vector3f& _start, const Vector3f& _end, const float _fraction);
|
||||
|
||||
static const Vector3f Zero() { return { 0, 0, 0 }; }
|
||||
static const Vector3f UnitX() { return { 1, 0, 0 }; }
|
||||
static const Vector3f UnitY() { return { 0, 1, 0 }; }
|
||||
static const Vector3f UnitZ() { return { 0, 0, 1 }; }
|
||||
static const Vector3f Zero() { return { 0.0f, 0.0f, 0.0f }; }
|
||||
static const Vector3f UnitX() { return { 1.0f, 0.0f, 0.0f }; }
|
||||
static const Vector3f UnitY() { return { 0.0f, 1.0f, 0.0f }; }
|
||||
static const Vector3f UnitZ() { return { 0.0f, 0.0f, 1.0f }; }
|
||||
|
||||
private:
|
||||
float mX;
|
||||
|
|
|
@ -20,51 +20,81 @@ class Vector4f
|
|||
{
|
||||
public:
|
||||
Vector4f() {}
|
||||
Vector4f(const float _f) : mX(_f), mY(_f), mZ(_f), mW(_f) {}
|
||||
Vector4f(const float _f)
|
||||
: mX(_f)
|
||||
, mY(_f)
|
||||
, mZ(_f)
|
||||
, mW(_f)
|
||||
{
|
||||
}
|
||||
Vector4f(const float _x, const float _y, const float _z, const float _w)
|
||||
: mX(_x), mY(_y), mZ(_z), mW(_w) {}
|
||||
: mX(_x)
|
||||
, mY(_y)
|
||||
, mZ(_z)
|
||||
, mW(_w)
|
||||
{
|
||||
}
|
||||
explicit Vector4f(const Vector2f& _v)
|
||||
: mX((reinterpret_cast<const Vector4f&>(_v)).mX),
|
||||
mY((reinterpret_cast<const Vector4f&>(_v)).mY), mZ(0), mW(0) {}
|
||||
: mX((reinterpret_cast<const Vector4f&>(_v)).mX)
|
||||
, mY((reinterpret_cast<const Vector4f&>(_v)).mY)
|
||||
, mZ(0)
|
||||
, mW(0)
|
||||
{
|
||||
}
|
||||
explicit Vector4f(const Vector2f& _v, const float _z)
|
||||
: mX((reinterpret_cast<const Vector4f&>(_v)).mX),
|
||||
mY((reinterpret_cast<const Vector4f&>(_v)).mY), mZ(_z), mW(0) {}
|
||||
: mX((reinterpret_cast<const Vector4f&>(_v)).mX)
|
||||
, mY((reinterpret_cast<const Vector4f&>(_v)).mY)
|
||||
, mZ(_z)
|
||||
, mW(0)
|
||||
{
|
||||
}
|
||||
explicit Vector4f(const Vector2f& _v, const float _z, const float _w)
|
||||
: mX((reinterpret_cast<const Vector4f&>(_v)).mX),
|
||||
mY((reinterpret_cast<const Vector4f&>(_v)).mY), mZ(_z), mW(_w) {}
|
||||
: mX((reinterpret_cast<const Vector4f&>(_v)).mX)
|
||||
, mY((reinterpret_cast<const Vector4f&>(_v)).mY)
|
||||
, mZ(_z)
|
||||
, mW(_w)
|
||||
{
|
||||
}
|
||||
explicit Vector4f(const Vector3f& _v)
|
||||
: mX((reinterpret_cast<const Vector4f&>(_v)).mX),
|
||||
mY((reinterpret_cast<const Vector4f&>(_v)).mY),
|
||||
mZ((reinterpret_cast<const Vector4f&>(_v)).mZ), mW(0) {}
|
||||
: mX((reinterpret_cast<const Vector4f&>(_v)).mX)
|
||||
, mY((reinterpret_cast<const Vector4f&>(_v)).mY)
|
||||
, mZ((reinterpret_cast<const Vector4f&>(_v)).mZ)
|
||||
, mW(0)
|
||||
{
|
||||
}
|
||||
explicit Vector4f(const Vector3f& _v, const float _w)
|
||||
: mX((reinterpret_cast<const Vector4f&>(_v)).mX),
|
||||
mY((reinterpret_cast<const Vector4f&>(_v)).mY),
|
||||
mZ((reinterpret_cast<const Vector4f&>(_v)).mZ), mW(_w) {}
|
||||
: mX((reinterpret_cast<const Vector4f&>(_v)).mX)
|
||||
, mY((reinterpret_cast<const Vector4f&>(_v)).mY)
|
||||
, mZ((reinterpret_cast<const Vector4f&>(_v)).mZ)
|
||||
, mW(_w)
|
||||
{
|
||||
}
|
||||
|
||||
// clang-format off
|
||||
const bool operator==(const Vector4f& _other) const
|
||||
{ return ((mX == _other.mX) && (mY == _other.mY) &&
|
||||
(mZ == _other.mZ) && (mW == _other.mW)); }
|
||||
{ return ((mX == _other.mX) && (mY == _other.mY) &&
|
||||
(mZ == _other.mZ) && (mW == _other.mW)); }
|
||||
const bool operator!=(const Vector4f& _other) const
|
||||
{ return ((mX != _other.mX) || (mY != _other.mY) ||
|
||||
(mZ != _other.mZ) || (mW != _other.mW)); }
|
||||
{ return ((mX != _other.mX) || (mY != _other.mY) ||
|
||||
(mZ != _other.mZ) || (mW != _other.mW)); }
|
||||
|
||||
const Vector4f operator+(const Vector4f& _other) const
|
||||
{ return { mX + _other.mX, mY + _other.mY, mZ + _other.mZ, mW + _other.mW }; }
|
||||
{ return { mX + _other.mX, mY + _other.mY, mZ + _other.mZ, mW + _other.mW }; }
|
||||
const Vector4f operator-(const Vector4f& _other) const
|
||||
{ return { mX - _other.mX, mY - _other.mY, mZ - _other.mZ, mW - _other.mW }; }
|
||||
{ return { mX - _other.mX, mY - _other.mY, mZ - _other.mZ, mW - _other.mW }; }
|
||||
const Vector4f operator*(const Vector4f& _other) const
|
||||
{ return { mX * _other.mX, mY * _other.mY, mZ * _other.mZ, mW * _other.mW }; }
|
||||
{ return { mX * _other.mX, mY * _other.mY, mZ * _other.mZ, mW * _other.mW }; }
|
||||
const Vector4f operator/(const Vector4f& _other) const
|
||||
{ return { mX / _other.mX, mY / _other.mY, mZ / _other.mZ, mW / _other.mW }; }
|
||||
{ return { mX / _other.mX, mY / _other.mY, mZ / _other.mZ, mW / _other.mW }; }
|
||||
|
||||
const Vector4f operator+(const float& _other) const
|
||||
{ return { mX + _other, mY + _other, mZ + _other, mW + _other }; }
|
||||
{ return { mX + _other, mY + _other, mZ + _other, mW + _other }; }
|
||||
const Vector4f operator-(const float& _other) const
|
||||
{ return { mX - _other, mY - _other, mZ - _other, mW - _other }; }
|
||||
{ return { mX - _other, mY - _other, mZ - _other, mW - _other }; }
|
||||
const Vector4f operator*(const float& _other) const
|
||||
{ return { mX * _other, mY * _other, mZ * _other, mW * _other }; }
|
||||
{ return { mX * _other, mY * _other, mZ * _other, mW * _other }; }
|
||||
const Vector4f operator/(const float& _other) const
|
||||
{ return { mX / _other, mY / _other, mZ / _other, mW / _other }; }
|
||||
{ return { mX / _other, mY / _other, mZ / _other, mW / _other }; }
|
||||
|
||||
const Vector4f operator-() const { return {-mX , -mY, -mZ, -mW }; }
|
||||
|
||||
|
@ -79,33 +109,34 @@ public:
|
|||
Vector4f& operator/=(const float& _other) { *this = *this / _other; return *this; }
|
||||
|
||||
float& operator[](const int _index)
|
||||
{ assert(_index < 4 && "index out of range"); return (&mX)[_index]; }
|
||||
{ assert(_index < 4 && "index out of range"); return (&mX)[_index]; }
|
||||
const float& operator[](const int _index) const
|
||||
{ assert(_index < 4 && "index out of range"); return (&mX)[_index]; }
|
||||
{ assert(_index < 4 && "index out of range"); return (&mX)[_index]; }
|
||||
// clang-format on
|
||||
|
||||
inline float& x() { return mX; }
|
||||
inline float& y() { return mY; }
|
||||
inline float& z() { return mZ; }
|
||||
inline float& w() { return mW; }
|
||||
inline const float& x() const { return mX; }
|
||||
inline const float& y() const { return mY; }
|
||||
inline const float& z() const { return mZ; }
|
||||
inline const float& w() const { return mW; }
|
||||
float& x() { return mX; }
|
||||
float& y() { return mY; }
|
||||
float& z() { return mZ; }
|
||||
float& w() { return mW; }
|
||||
const float& x() const { return mX; }
|
||||
const float& y() const { return mY; }
|
||||
const float& z() const { return mZ; }
|
||||
const float& w() const { return mW; }
|
||||
|
||||
inline Vector2f& v2() { return *reinterpret_cast<Vector2f*>(this); }
|
||||
inline const Vector2f& v2() const { return *reinterpret_cast<const Vector2f*>(this); }
|
||||
Vector2f& v2() { return *reinterpret_cast<Vector2f*>(this); }
|
||||
const Vector2f& v2() const { return *reinterpret_cast<const Vector2f*>(this); }
|
||||
|
||||
inline Vector3f& v3() { return *reinterpret_cast<Vector3f*>(this); }
|
||||
inline const Vector3f& v3() const { return *reinterpret_cast<const Vector3f*>(this); }
|
||||
Vector3f& v3() { return *reinterpret_cast<Vector3f*>(this); }
|
||||
const Vector3f& v3() const { return *reinterpret_cast<const Vector3f*>(this); }
|
||||
|
||||
Vector4f& round();
|
||||
Vector4f& lerp (const Vector4f& _start, const Vector4f& _end, const float _fraction);
|
||||
Vector4f& lerp(const Vector4f& _start, const Vector4f& _end, const float _fraction);
|
||||
|
||||
static const Vector4f Zero() { return { 0, 0, 0, 0 }; }
|
||||
static const Vector4f UnitX() { return { 1, 0, 0, 0 }; }
|
||||
static const Vector4f UnitY() { return { 0, 1, 0, 0 }; }
|
||||
static const Vector4f UnitZ() { return { 0, 0, 1, 0 }; }
|
||||
static const Vector4f UnitW() { return { 0, 0, 0, 1 }; }
|
||||
static const Vector4f Zero() { return { 0.0f, 0.0f, 0.0f, 0.0f }; }
|
||||
static const Vector4f UnitX() { return { 1.0f, 0.0f, 0.0f, 0.0f }; }
|
||||
static const Vector4f UnitY() { return { 0.0f, 1.0f, 0.0f, 0.0f }; }
|
||||
static const Vector4f UnitZ() { return { 0.0f, 0.0f, 1.0f, 0.0f }; }
|
||||
static const Vector4f UnitW() { return { 0.0f, 0.0f, 0.0f, 1.0f }; }
|
||||
|
||||
private:
|
||||
float mX;
|
||||
|
|
|
@ -8,18 +8,18 @@
|
|||
|
||||
#include "renderers/Renderer.h"
|
||||
|
||||
#include "math/Transform4x4f.h"
|
||||
#include "math/Vector2i.h"
|
||||
#include "resources/ResourceManager.h"
|
||||
#include "ImageIO.h"
|
||||
#include "Log.h"
|
||||
#include "Settings.h"
|
||||
#include "Shader_GL21.h"
|
||||
#include "math/Transform4x4f.h"
|
||||
#include "math/Vector2i.h"
|
||||
#include "resources/ResourceManager.h"
|
||||
|
||||
#include <SDL2/SDL.h>
|
||||
#include <stack>
|
||||
|
||||
#if defined (_WIN64)
|
||||
#if defined(_WIN64)
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
|
@ -44,31 +44,31 @@ namespace Renderer
|
|||
{
|
||||
size_t width = 0;
|
||||
size_t height = 0;
|
||||
ResourceData resData = ResourceManager::getInstance()->
|
||||
getFileData(":/graphics/window_icon_256.png");
|
||||
ResourceData resData =
|
||||
ResourceManager::getInstance()->getFileData(":/graphics/window_icon_256.png");
|
||||
std::vector<unsigned char> rawData =
|
||||
ImageIO::loadFromMemoryRGBA32(resData.ptr.get(), resData.length, width, height);
|
||||
ImageIO::loadFromMemoryRGBA32(resData.ptr.get(), resData.length, width, height);
|
||||
|
||||
if (!rawData.empty()) {
|
||||
ImageIO::flipPixelsVert(rawData.data(), width, height);
|
||||
|
||||
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
|
||||
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
|
||||
unsigned int rmask = 0xFF000000;
|
||||
unsigned int gmask = 0x00FF0000;
|
||||
unsigned int bmask = 0x0000FF00;
|
||||
unsigned int amask = 0x000000FF;
|
||||
#else
|
||||
#else
|
||||
unsigned int rmask = 0x000000FF;
|
||||
unsigned int gmask = 0x0000FF00;
|
||||
unsigned int bmask = 0x00FF0000;
|
||||
unsigned int amask = 0xFF000000;
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Try creating SDL surface from logo data.
|
||||
SDL_Surface* logoSurface = SDL_CreateRGBSurfaceFrom(
|
||||
static_cast<void*>(rawData.data()),
|
||||
static_cast<int>(width), static_cast<int>(height), 32,
|
||||
static_cast<int>((width * 4)), rmask, gmask, bmask, amask);
|
||||
SDL_Surface* logoSurface =
|
||||
SDL_CreateRGBSurfaceFrom(static_cast<void*>(rawData.data()),
|
||||
static_cast<int>(width), static_cast<int>(height), 32,
|
||||
static_cast<int>((width * 4)), rmask, gmask, bmask, amask);
|
||||
|
||||
if (logoSurface != nullptr) {
|
||||
SDL_SetWindowIcon(sdlWindow, logoSurface);
|
||||
|
@ -100,8 +100,8 @@ namespace Renderer
|
|||
|
||||
int availableDisplays = SDL_GetNumVideoDisplays();
|
||||
if (displayIndex > availableDisplays - 1) {
|
||||
LOG(LogWarning) << "Requested display " << std::to_string(displayIndex + 1) <<
|
||||
" does not exist, changing to display 1";
|
||||
LOG(LogWarning) << "Requested display " << std::to_string(displayIndex + 1)
|
||||
<< " does not exist, changing to display 1";
|
||||
displayIndex = 0;
|
||||
}
|
||||
else {
|
||||
|
@ -111,7 +111,7 @@ namespace Renderer
|
|||
SDL_DisplayMode displayMode;
|
||||
SDL_GetDesktopDisplayMode(displayIndex, &displayMode);
|
||||
|
||||
#if defined (_WIN64)
|
||||
#if defined(_WIN64)
|
||||
// Tell Windows that we're DPI aware so that we can set a physical resolution and
|
||||
// avoid any automatic DPI scaling.
|
||||
SetProcessDPIAware();
|
||||
|
@ -122,28 +122,35 @@ namespace Renderer
|
|||
SDL_GetDisplayBounds(displayIndex, &displayBounds);
|
||||
displayMode.w = displayBounds.w;
|
||||
displayMode.h = displayBounds.h;
|
||||
#endif
|
||||
#endif
|
||||
|
||||
windowWidth = Settings::getInstance()->getInt("WindowWidth") ?
|
||||
Settings::getInstance()->getInt("WindowWidth") : displayMode.w;
|
||||
Settings::getInstance()->getInt("WindowWidth") :
|
||||
displayMode.w;
|
||||
windowHeight = Settings::getInstance()->getInt("WindowHeight") ?
|
||||
Settings::getInstance()->getInt("WindowHeight") : displayMode.h;
|
||||
Settings::getInstance()->getInt("WindowHeight") :
|
||||
displayMode.h;
|
||||
screenWidth = Settings::getInstance()->getInt("ScreenWidth") ?
|
||||
Settings::getInstance()->getInt("ScreenWidth") : windowWidth;
|
||||
Settings::getInstance()->getInt("ScreenWidth") :
|
||||
windowWidth;
|
||||
screenHeight = Settings::getInstance()->getInt("ScreenHeight") ?
|
||||
Settings::getInstance()->getInt("ScreenHeight") : windowHeight;
|
||||
Settings::getInstance()->getInt("ScreenHeight") :
|
||||
windowHeight;
|
||||
screenOffsetX = Settings::getInstance()->getInt("ScreenOffsetX") ?
|
||||
Settings::getInstance()->getInt("ScreenOffsetX") : 0;
|
||||
Settings::getInstance()->getInt("ScreenOffsetX") :
|
||||
0;
|
||||
screenOffsetY = Settings::getInstance()->getInt("ScreenOffsetY") ?
|
||||
Settings::getInstance()->getInt("ScreenOffsetY") : 0;
|
||||
Settings::getInstance()->getInt("ScreenOffsetY") :
|
||||
0;
|
||||
screenRotate = Settings::getInstance()->getInt("ScreenRotate") ?
|
||||
Settings::getInstance()->getInt("ScreenRotate") : 0;
|
||||
Settings::getInstance()->getInt("ScreenRotate") :
|
||||
0;
|
||||
|
||||
// Prevent the application window from minimizing when switching windows (when launching
|
||||
// games or when manually switching windows using the task switcher).
|
||||
SDL_SetHint(SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS, "0");
|
||||
|
||||
#if defined(__unix__)
|
||||
#if defined(__unix__)
|
||||
// Disabling desktop composition can lead to better framerates and a more fluid user
|
||||
// interface, but with some drivers it can cause strange behaviours when returning to
|
||||
// the desktop.
|
||||
|
@ -151,29 +158,28 @@ namespace Renderer
|
|||
SDL_SetHint(SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, "1");
|
||||
else
|
||||
SDL_SetHint(SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR, "0");
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(__APPLE__) || defined(__unix__)
|
||||
#if defined(__APPLE__) || defined(__unix__)
|
||||
bool userResolution = false;
|
||||
// Check if the user has changed the resolution from the command line.
|
||||
if (windowWidth != displayMode.w || windowHeight != displayMode.h)
|
||||
userResolution = true;
|
||||
// Not sure if this could be a useful setting for some users.
|
||||
// SDL_SetHint(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, "0");
|
||||
#endif
|
||||
|
||||
setupWindow();
|
||||
// Not sure if this could be a useful setting for some users.
|
||||
// SDL_SetHint(SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES, "0");
|
||||
#endif
|
||||
|
||||
unsigned int windowFlags;
|
||||
setupWindow();
|
||||
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
// For Windows, always set the mode to windowed, as full screen mode seems to
|
||||
// behave quite erratic. There may be a proper fix for this, but for now windowed
|
||||
// mode seems to behave well and it's almost completely seamless, especially with
|
||||
// a hidden taskbar. As well, setting SDL_WINDOW_BORDERLESS introduces issues too
|
||||
// so unfortunately this needs to be avoided.
|
||||
windowFlags = getWindowFlags();
|
||||
#elif defined(__APPLE__)
|
||||
#elif defined(__APPLE__)
|
||||
// This seems to be the only full window mode that somehow works on macOS as a real
|
||||
// fullscreen mode will do lots of weird stuff like preventing window switching
|
||||
// or refusing to let emulators run at all. SDL_WINDOW_FULLSCREEN_DESKTOP almost
|
||||
|
@ -190,7 +196,7 @@ namespace Renderer
|
|||
// If the user has changed the resolution from the command line, then add a
|
||||
// border to the window.
|
||||
windowFlags = SDL_WINDOW_ALLOW_HIGHDPI | getWindowFlags();
|
||||
#else
|
||||
#else
|
||||
if (Settings::getInstance()->getBool("Windowed")) {
|
||||
windowFlags = getWindowFlags();
|
||||
}
|
||||
|
@ -205,17 +211,17 @@ namespace Renderer
|
|||
else {
|
||||
windowFlags = SDL_WINDOW_FULLSCREEN | getWindowFlags();
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
if ((sdlWindow = SDL_CreateWindow("EmulationStation",
|
||||
SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),
|
||||
SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),
|
||||
windowWidth, windowHeight, windowFlags)) == nullptr) {
|
||||
if ((sdlWindow =
|
||||
SDL_CreateWindow("EmulationStation", SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex),
|
||||
SDL_WINDOWPOS_UNDEFINED_DISPLAY(displayIndex), windowWidth,
|
||||
windowHeight, windowFlags)) == nullptr) {
|
||||
LOG(LogError) << "Couldn't create SDL window. " << SDL_GetError();
|
||||
return false;
|
||||
}
|
||||
|
||||
#if defined(__APPLE__)
|
||||
#if defined(__APPLE__)
|
||||
// The code below is required as the high DPI scaling on macOS is very bizarre and is
|
||||
// measured in "points" rather than pixels (even though the naming convention sure looks
|
||||
// like pixels). For example there could be a 1920x1080 entry in the OS display settings
|
||||
|
@ -231,25 +237,25 @@ namespace Renderer
|
|||
SDL_GL_GetDrawableSize(sdlWindow, &width, nullptr);
|
||||
int scaleFactor = static_cast<int>(width / windowWidth);
|
||||
|
||||
LOG(LogInfo) << "Display resolution: " << std::to_string(displayMode.w) << "x" <<
|
||||
std::to_string(displayMode.h) << " (physical resolution " <<
|
||||
std::to_string(displayMode.w * scaleFactor) << "x" <<
|
||||
std::to_string(displayMode.h * scaleFactor) << ")";
|
||||
LOG(LogInfo) << "EmulationStation resolution: " << std::to_string(windowWidth) << "x" <<
|
||||
std::to_string(windowHeight) << " (physical resolution " <<
|
||||
std::to_string(windowWidth * scaleFactor) << "x" <<
|
||||
std::to_string(windowHeight * scaleFactor) << ")";
|
||||
LOG(LogInfo) << "Display resolution: " << std::to_string(displayMode.w) << "x"
|
||||
<< std::to_string(displayMode.h) << " (physical resolution "
|
||||
<< std::to_string(displayMode.w * scaleFactor) << "x"
|
||||
<< std::to_string(displayMode.h * scaleFactor) << ")";
|
||||
LOG(LogInfo) << "EmulationStation resolution: " << std::to_string(windowWidth) << "x"
|
||||
<< std::to_string(windowHeight) << " (physical resolution "
|
||||
<< std::to_string(windowWidth * scaleFactor) << "x"
|
||||
<< std::to_string(windowHeight * scaleFactor) << ")";
|
||||
|
||||
windowWidth *= scaleFactor;
|
||||
windowHeight *= scaleFactor;
|
||||
screenWidth *= scaleFactor;
|
||||
screenHeight *= scaleFactor;
|
||||
#else
|
||||
LOG(LogInfo) << "Display resolution: " << std::to_string(displayMode.w) << "x" <<
|
||||
std::to_string(displayMode.h);
|
||||
LOG(LogInfo) << "EmulationStation resolution: " << std::to_string(windowWidth) << "x" <<
|
||||
std::to_string(windowHeight);
|
||||
#endif
|
||||
#else
|
||||
LOG(LogInfo) << "Display resolution: " << std::to_string(displayMode.w) << "x"
|
||||
<< std::to_string(displayMode.h);
|
||||
LOG(LogInfo) << "EmulationStation resolution: " << std::to_string(windowWidth) << "x"
|
||||
<< std::to_string(windowHeight);
|
||||
#endif
|
||||
|
||||
screenHeightModifier = static_cast<float>(screenHeight) / 1080.0f;
|
||||
screenWidthModifier = static_cast<float>(screenWidth) / 1920.0f;
|
||||
|
@ -263,14 +269,14 @@ namespace Renderer
|
|||
setIcon();
|
||||
setSwapInterval();
|
||||
|
||||
#if defined(_WIN64)
|
||||
// It seems as if Windows needs this to avoid a brief white screen flash on startup.
|
||||
// Possibly this is driver-specific rather than OS-specific. There is additional code
|
||||
// in init() to work around the white screen flash issue on all operating systems.
|
||||
#if defined(_WIN64)
|
||||
swapBuffers();
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if defined(USE_OPENGL_21)
|
||||
#if defined(USE_OPENGL_21)
|
||||
LOG(LogInfo) << "Loading shaders...";
|
||||
|
||||
std::vector<std::string> shaderFiles;
|
||||
|
@ -294,19 +300,17 @@ namespace Renderer
|
|||
|
||||
sShaderProgramVector.push_back(loadShader);
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
static void destroyWindow()
|
||||
{
|
||||
#if defined(USE_OPENGL_21)
|
||||
for (auto it = sShaderProgramVector.cbegin();
|
||||
it != sShaderProgramVector.cend(); it++) {
|
||||
#if defined(USE_OPENGL_21)
|
||||
for (auto it = sShaderProgramVector.cbegin(); it != sShaderProgramVector.cend(); it++)
|
||||
delete *it;
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
destroyContext();
|
||||
SDL_DestroyWindow(sdlWindow);
|
||||
|
@ -332,42 +336,42 @@ namespace Renderer
|
|||
viewport.w = screenWidth;
|
||||
viewport.h = screenHeight;
|
||||
projection.orthoProjection(0.0f, static_cast<float>(screenWidth),
|
||||
static_cast<float>(screenHeight), 0.0f, -1.0f, 1.0f);
|
||||
static_cast<float>(screenHeight), 0.0f, -1.0f, 1.0f);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 1: {
|
||||
viewport.x = windowWidth - screenOffsetY - screenHeight;
|
||||
viewport.y = screenOffsetX;
|
||||
viewport.w = screenHeight;
|
||||
viewport.h = screenWidth;
|
||||
projection.orthoProjection(0.0f, static_cast<float>(screenHeight),
|
||||
static_cast<float>(screenWidth), 0.0f, -1.0f, 1.0f);
|
||||
projection.rotate(static_cast<float>(ES_DEG_TO_RAD(90)), {0, 0, 1});
|
||||
projection.translate({0, screenHeight * -1.0f, 0});
|
||||
static_cast<float>(screenWidth), 0.0f, -1.0f, 1.0f);
|
||||
projection.rotate(static_cast<float>(ES_DEG_TO_RAD(90)), { 0, 0, 1 });
|
||||
projection.translate({ 0, screenHeight * -1.0f, 0 });
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 2: {
|
||||
viewport.x = windowWidth - screenOffsetX - screenWidth;
|
||||
viewport.x = windowWidth - screenOffsetX - screenWidth;
|
||||
viewport.y = windowHeight - screenOffsetY - screenHeight;
|
||||
viewport.w = screenWidth;
|
||||
viewport.h = screenHeight;
|
||||
projection.orthoProjection(0.0f, static_cast<float>(screenWidth),
|
||||
static_cast<float>(screenHeight), 0.0f, -1.0f, 1.0f);
|
||||
projection.rotate(static_cast<float>(ES_DEG_TO_RAD(180)), {0, 0, 1});
|
||||
projection.translate({screenWidth * -1.0f, screenHeight * -1.0f, 0});
|
||||
static_cast<float>(screenHeight), 0.0f, -1.0f, 1.0f);
|
||||
projection.rotate(static_cast<float>(ES_DEG_TO_RAD(180)), { 0, 0, 1 });
|
||||
projection.translate({ screenWidth * -1.0f, screenHeight * -1.0f, 0 });
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case 3: {
|
||||
viewport.x = screenOffsetY;
|
||||
viewport.y = windowHeight - screenOffsetX - screenWidth;
|
||||
viewport.w = screenHeight;
|
||||
viewport.h = screenWidth;
|
||||
projection.orthoProjection(0.0f, static_cast<float>(screenHeight),
|
||||
static_cast<float>(screenWidth), 0.0f, -1.0f, 1.0f);
|
||||
projection.rotate(static_cast<float>(ES_DEG_TO_RAD(270)), {0, 0, 1});
|
||||
projection.translate({screenWidth * -1.0f, 0, 0});
|
||||
static_cast<float>(screenWidth), 0.0f, -1.0f, 1.0f);
|
||||
projection.rotate(static_cast<float>(ES_DEG_TO_RAD(270)), { 0, 0, 1 });
|
||||
projection.translate({ screenWidth * -1.0f, 0, 0 });
|
||||
break;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
mProjectionMatrix = projection;
|
||||
|
@ -377,7 +381,7 @@ namespace Renderer
|
|||
|
||||
// This is required to avoid a brief white screen flash during startup on some systems.
|
||||
Renderer::drawRect(0.0f, 0.0f, static_cast<float>(Renderer::getScreenWidth()),
|
||||
static_cast<float>(Renderer::getScreenHeight()), 0x000000FF, 0x000000FF);
|
||||
static_cast<float>(Renderer::getScreenHeight()), 0x000000FF, 0x000000FF);
|
||||
swapBuffers();
|
||||
|
||||
return true;
|
||||
|
@ -385,6 +389,7 @@ namespace Renderer
|
|||
|
||||
void deinit()
|
||||
{
|
||||
// Destroy the window.
|
||||
destroyWindow();
|
||||
}
|
||||
|
||||
|
@ -400,32 +405,38 @@ namespace Renderer
|
|||
switch (screenRotate) {
|
||||
case 0:
|
||||
box = Rect(screenOffsetX + box.x, screenOffsetY + box.y, box.w, box.h);
|
||||
break;
|
||||
break;
|
||||
case 1:
|
||||
box = Rect(windowWidth - screenOffsetY - box.y - box.h,
|
||||
screenOffsetX + box.x, box.h, box.w);
|
||||
break;
|
||||
box = Rect(windowWidth - screenOffsetY - box.y - box.h, screenOffsetX + box.x,
|
||||
box.h, box.w);
|
||||
break;
|
||||
case 2:
|
||||
box = Rect(windowWidth - screenOffsetX - box.x - box.w, windowHeight -
|
||||
screenOffsetY - box.y - box.h, box.w, box.h);
|
||||
break;
|
||||
box = Rect(windowWidth - screenOffsetX - box.x - box.w,
|
||||
windowHeight - screenOffsetY - box.y - box.h, box.w, box.h);
|
||||
break;
|
||||
case 3:
|
||||
box = Rect(screenOffsetY + box.y, windowHeight -
|
||||
screenOffsetX - box.x - box.w, box.h, box.w);
|
||||
break;
|
||||
box = Rect(screenOffsetY + box.y, windowHeight - screenOffsetX - box.x - box.w,
|
||||
box.h, box.w);
|
||||
break;
|
||||
}
|
||||
|
||||
// Make sure the box fits within clipStack.top(), and clip further accordingly.
|
||||
if (clipStack.size()) {
|
||||
const Rect& top = clipStack.top();
|
||||
if ( top.x > box.x) box.x = top.x;
|
||||
if ( top.y > box.y) box.y = top.y;
|
||||
if ((top.x + top.w) < (box.x + box.w)) box.w = (top.x + top.w) - box.x;
|
||||
if ((top.y + top.h) < (box.y + box.h)) box.h = (top.y + top.h) - box.y;
|
||||
if (top.x > box.x)
|
||||
box.x = top.x;
|
||||
if (top.y > box.y)
|
||||
box.y = top.y;
|
||||
if ((top.x + top.w) < (box.x + box.w))
|
||||
box.w = (top.x + top.w) - box.x;
|
||||
if ((top.y + top.h) < (box.y + box.h))
|
||||
box.h = (top.y + top.h) - box.y;
|
||||
}
|
||||
|
||||
if (box.w < 0) box.w = 0;
|
||||
if (box.h < 0) box.h = 0;
|
||||
if (box.w < 0)
|
||||
box.w = 0;
|
||||
if (box.h < 0)
|
||||
box.h = 0;
|
||||
|
||||
clipStack.push(box);
|
||||
|
||||
|
@ -447,18 +458,17 @@ namespace Renderer
|
|||
setScissor(clipStack.top());
|
||||
}
|
||||
|
||||
void drawRect(
|
||||
const float _x,
|
||||
const float _y,
|
||||
const float _w,
|
||||
const float _h,
|
||||
const unsigned int _color,
|
||||
const unsigned int _colorEnd,
|
||||
bool horizontalGradient,
|
||||
const float _opacity,
|
||||
const Transform4x4f& _trans,
|
||||
const Blend::Factor _srcBlendFactor,
|
||||
const Blend::Factor _dstBlendFactor)
|
||||
void drawRect(const float _x,
|
||||
const float _y,
|
||||
const float _w,
|
||||
const float _h,
|
||||
const unsigned int _color,
|
||||
const unsigned int _colorEnd,
|
||||
bool horizontalGradient,
|
||||
const float _opacity,
|
||||
const Transform4x4f& _trans,
|
||||
const Blend::Factor _srcBlendFactor,
|
||||
const Blend::Factor _dstBlendFactor)
|
||||
{
|
||||
const unsigned int color = convertRGBAToABGR(_color);
|
||||
const unsigned int colorEnd = convertRGBAToABGR(_colorEnd);
|
||||
|
@ -474,10 +484,12 @@ namespace Renderer
|
|||
if (_hL > 0.0f && _hL < 1.0f)
|
||||
_hL = 1.0f;
|
||||
|
||||
// clang-format off
|
||||
vertices[0] = { { _x , _y }, { 0.0f, 0.0f }, color };
|
||||
vertices[1] = { { _x , _y + _hL }, { 0.0f, 0.0f }, horizontalGradient ? colorEnd : color };
|
||||
vertices[2] = { { _x + _wL, _y }, { 0.0f, 0.0f }, horizontalGradient ? color : colorEnd };
|
||||
vertices[3] = { { _x + _wL, _y + _hL }, { 0.0f, 0.0f }, colorEnd };
|
||||
// clang-format on
|
||||
|
||||
// Round vertices.
|
||||
for (int i = 0; i < 4; i++)
|
||||
|
@ -524,17 +536,13 @@ namespace Renderer
|
|||
index++;
|
||||
}
|
||||
|
||||
if (sShaderProgramVector.size() > index-1)
|
||||
return sShaderProgramVector[index-1];
|
||||
if (sShaderProgramVector.size() > index - 1)
|
||||
return sShaderProgramVector[index - 1];
|
||||
else
|
||||
return nullptr;
|
||||
};
|
||||
|
||||
const Transform4x4f getProjectionMatrix()
|
||||
{
|
||||
return mProjectionMatrix;
|
||||
}
|
||||
|
||||
const Transform4x4f getProjectionMatrix() { return mProjectionMatrix; }
|
||||
SDL_Window* getSDLWindow() { return sdlWindow; }
|
||||
int getWindowWidth() { return windowWidth; }
|
||||
int getWindowHeight() { return windowHeight; }
|
||||
|
@ -547,4 +555,4 @@ namespace Renderer
|
|||
float getScreenHeightModifier() { return screenHeightModifier; }
|
||||
float getScreenAspectRatio() { return screenAspectRatio; }
|
||||
|
||||
} // Renderer::
|
||||
} // namespace Renderer
|
||||
|
|
|
@ -9,26 +9,27 @@
|
|||
#ifndef ES_CORE_RENDERER_RENDERER_H
|
||||
#define ES_CORE_RENDERER_RENDERER_H
|
||||
|
||||
#include "math/Transform4x4f.h"
|
||||
#include "math/Vector2f.h"
|
||||
#include "Log.h"
|
||||
#include "Shader_GL21.h"
|
||||
#include "math/Transform4x4f.h"
|
||||
#include "math/Vector2f.h"
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
class Transform4x4f;
|
||||
class Vector2i;
|
||||
struct SDL_Window;
|
||||
|
||||
class Transform4x4f;
|
||||
class Vector2i;
|
||||
|
||||
namespace Renderer
|
||||
{
|
||||
const unsigned int SHADER_DESATURATE = 1;
|
||||
const unsigned int SHADER_OPACITY = 2;
|
||||
const unsigned int SHADER_DIM = 4;
|
||||
const unsigned int SHADER_BLUR_HORIZONTAL = 8;
|
||||
const unsigned int SHADER_BLUR_VERTICAL = 16;
|
||||
const unsigned int SHADER_SCANLINES = 32;
|
||||
const unsigned int SHADER_DESATURATE = 1;
|
||||
const unsigned int SHADER_OPACITY = 2;
|
||||
const unsigned int SHADER_DIM = 4;
|
||||
const unsigned int SHADER_BLUR_HORIZONTAL = 8;
|
||||
const unsigned int SHADER_BLUR_VERTICAL = 16;
|
||||
const unsigned int SHADER_SCANLINES = 32;
|
||||
|
||||
struct shaderParameters {
|
||||
std::array<GLfloat, 2> textureSize;
|
||||
|
@ -39,40 +40,40 @@ namespace Renderer
|
|||
unsigned int blurPasses;
|
||||
|
||||
shaderParameters()
|
||||
: textureSize({0.0f, 0.0f}),
|
||||
textureCoordinates({0.0f, 0.0f, 0.0f, 0.0f}),
|
||||
fragmentSaturation(1.0f),
|
||||
fragmentDimValue(0.4f),
|
||||
fragmentOpacity(1.0f),
|
||||
blurPasses(1)
|
||||
{};
|
||||
: textureSize({ 0.0f, 0.0f })
|
||||
, textureCoordinates({ 0.0f, 0.0f, 0.0f, 0.0f })
|
||||
, fragmentSaturation(1.0f)
|
||||
, fragmentDimValue(0.4f)
|
||||
, fragmentOpacity(1.0f)
|
||||
, blurPasses(1)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
static std::vector<Shader*> sShaderProgramVector;
|
||||
static GLuint shaderFBO;
|
||||
static Transform4x4f mProjectionMatrix;
|
||||
|
||||
#if !defined(NDEBUG)
|
||||
#define GL_CHECK_ERROR(Function) (Function, _GLCheckError(#Function))
|
||||
#if !defined(NDEBUG)
|
||||
#define GL_CHECK_ERROR(Function) (Function, _GLCheckError(#Function))
|
||||
|
||||
static void _GLCheckError(const std::string& _funcName)
|
||||
{
|
||||
const GLenum errorCode = glGetError();
|
||||
|
||||
if (errorCode != GL_NO_ERROR) {
|
||||
#if defined(USE_OPENGL_21)
|
||||
LOG(LogError) << "OpenGL error: " << _funcName <<
|
||||
" failed with error code: 0x" << std::hex << errorCode;
|
||||
#else
|
||||
LOG(LogError) << "OpenGLES error: " << _funcName <<
|
||||
" failed with error code: 0x" << std::hex << errorCode;
|
||||
#endif
|
||||
|
||||
#if defined(USE_OPENGL_21)
|
||||
LOG(LogError) << "OpenGL error: " << _funcName << " failed with error code: 0x"
|
||||
<< std::hex << errorCode;
|
||||
#else
|
||||
LOG(LogError) << "OpenGLES error: " << _funcName << " failed with error code: 0x"
|
||||
<< std::hex << errorCode;
|
||||
#endif
|
||||
}
|
||||
}
|
||||
#else
|
||||
#define GL_CHECK_ERROR(Function) (Function)
|
||||
#endif
|
||||
#else
|
||||
#define GL_CHECK_ERROR(Function) (Function)
|
||||
#endif
|
||||
|
||||
namespace Blend
|
||||
{
|
||||
|
@ -93,37 +94,33 @@ namespace Renderer
|
|||
namespace Texture
|
||||
{
|
||||
enum Type {
|
||||
RGBA = 0,
|
||||
RGBA = 0, // Replace with AllowShortEnumsOnASingleLine: false (clang-format >=11.0).
|
||||
ALPHA = 1
|
||||
};
|
||||
}
|
||||
|
||||
struct Rect {
|
||||
Rect(
|
||||
const int _x,
|
||||
const int _y,
|
||||
const int _w,
|
||||
const int _h)
|
||||
: x(_x),
|
||||
y(_y),
|
||||
w(_w),
|
||||
h(_h) {}
|
||||
Rect(const int _x, const int _y, const int _w, const int _h)
|
||||
: x(_x)
|
||||
, y(_y)
|
||||
, w(_w)
|
||||
, h(_h)
|
||||
{
|
||||
}
|
||||
int x;
|
||||
int y;
|
||||
int w;
|
||||
int h;
|
||||
};
|
||||
|
||||
struct Vertex
|
||||
{
|
||||
struct Vertex {
|
||||
Vertex() {}
|
||||
Vertex(
|
||||
const Vector2f& _pos,
|
||||
const Vector2f& _tex,
|
||||
const unsigned int _col)
|
||||
: pos(_pos),
|
||||
tex(_tex),
|
||||
col(_col) { }
|
||||
Vertex(const Vector2f& _pos, const Vector2f& _tex, const unsigned int _col)
|
||||
: pos(_pos)
|
||||
, tex(_tex)
|
||||
, col(_col)
|
||||
{
|
||||
}
|
||||
Vector2f pos;
|
||||
Vector2f tex;
|
||||
unsigned int col;
|
||||
|
@ -136,18 +133,17 @@ namespace Renderer
|
|||
void deinit();
|
||||
void pushClipRect(const Vector2i& _pos, const Vector2i& _size);
|
||||
void popClipRect();
|
||||
void drawRect(
|
||||
const float _x,
|
||||
const float _y,
|
||||
const float _w,
|
||||
const float _h,
|
||||
const unsigned int _color,
|
||||
const unsigned int _colorEnd,
|
||||
bool horizontalGradient = false,
|
||||
const float _opacity = 1.0,
|
||||
const Transform4x4f& _trans = Transform4x4f::Identity(),
|
||||
const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA,
|
||||
const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA);
|
||||
void drawRect(const float _x,
|
||||
const float _y,
|
||||
const float _w,
|
||||
const float _h,
|
||||
const unsigned int _color,
|
||||
const unsigned int _colorEnd,
|
||||
bool horizontalGradient = false,
|
||||
const float _opacity = 1.0,
|
||||
const Transform4x4f& _trans = Transform4x4f::Identity(),
|
||||
const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA,
|
||||
const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA);
|
||||
SDL_Window* getSDLWindow();
|
||||
int getWindowWidth();
|
||||
int getWindowHeight();
|
||||
|
@ -166,49 +162,46 @@ namespace Renderer
|
|||
Shader* getShaderProgram(unsigned int shaderID);
|
||||
const Transform4x4f getProjectionMatrix();
|
||||
void shaderPostprocessing(unsigned int shaders,
|
||||
const Renderer::shaderParameters& parameters = shaderParameters(),
|
||||
unsigned char* textureRGBA = nullptr);
|
||||
const Renderer::shaderParameters& parameters = shaderParameters(),
|
||||
unsigned char* textureRGBA = nullptr);
|
||||
|
||||
static unsigned int getWindowFlags() { return SDL_WINDOW_OPENGL; }
|
||||
|
||||
// API specific.
|
||||
unsigned int getWindowFlags();
|
||||
void setupWindow();
|
||||
bool createContext();
|
||||
void destroyContext();
|
||||
unsigned int createTexture(
|
||||
const Texture::Type _type,
|
||||
const bool _linear,
|
||||
const bool _repeat,
|
||||
const unsigned int _width,
|
||||
const unsigned int _height,
|
||||
void* _data);
|
||||
unsigned int createTexture(const Texture::Type _type,
|
||||
const bool _linear,
|
||||
const bool _repeat,
|
||||
const unsigned int _width,
|
||||
const unsigned int _height,
|
||||
void* _data);
|
||||
void destroyTexture(const unsigned int _texture);
|
||||
void updateTexture(
|
||||
const unsigned int _texture,
|
||||
const Texture::Type _type,
|
||||
const unsigned int _x,
|
||||
const unsigned _y,
|
||||
const unsigned int _width,
|
||||
const unsigned int _height,
|
||||
void* _data);
|
||||
void updateTexture(const unsigned int _texture,
|
||||
const Texture::Type _type,
|
||||
const unsigned int _x,
|
||||
const unsigned _y,
|
||||
const unsigned int _width,
|
||||
const unsigned int _height,
|
||||
void* _data);
|
||||
void bindTexture(const unsigned int _texture);
|
||||
void drawLines(
|
||||
const Vertex* _vertices,
|
||||
const unsigned int _numVertices,
|
||||
const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA,
|
||||
const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA);
|
||||
void drawTriangleStrips(
|
||||
const Vertex* _vertices,
|
||||
const unsigned int _numVertices,
|
||||
const Transform4x4f& _trans = Transform4x4f::Identity(),
|
||||
const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA,
|
||||
const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA,
|
||||
const shaderParameters& _parameters = shaderParameters());
|
||||
void drawLines(const Vertex* _vertices,
|
||||
const unsigned int _numVertices,
|
||||
const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA,
|
||||
const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA);
|
||||
void drawTriangleStrips(const Vertex* _vertices,
|
||||
const unsigned int _numVertices,
|
||||
const Transform4x4f& _trans = Transform4x4f::Identity(),
|
||||
const Blend::Factor _srcBlendFactor = Blend::SRC_ALPHA,
|
||||
const Blend::Factor _dstBlendFactor = Blend::ONE_MINUS_SRC_ALPHA,
|
||||
const shaderParameters& _parameters = shaderParameters());
|
||||
void setProjection(const Transform4x4f& _projection);
|
||||
void setMatrix(const Transform4x4f& _matrix);
|
||||
void setViewport(const Rect& _viewport);
|
||||
void setScissor(const Rect& _scissor);
|
||||
void setSwapInterval();
|
||||
void swapBuffers();
|
||||
}
|
||||
|
||||
} // namespace Renderer
|
||||
|
||||
#endif // ES_CORE_RENDERER_RENDERER_H
|
||||
|
|
|
@ -8,10 +8,10 @@
|
|||
|
||||
#if defined(USE_OPENGL_21)
|
||||
|
||||
#include "math/Transform4x4f.h"
|
||||
#include "renderers/Renderer.h"
|
||||
#include "Settings.h"
|
||||
#include "Shader_GL21.h"
|
||||
#include "math/Transform4x4f.h"
|
||||
#include "renderers/Renderer.h"
|
||||
|
||||
namespace Renderer
|
||||
{
|
||||
|
@ -20,6 +20,7 @@ namespace Renderer
|
|||
|
||||
static GLenum convertBlendFactor(const Blend::Factor _blendFactor)
|
||||
{
|
||||
// clang-format off
|
||||
switch (_blendFactor) {
|
||||
case Blend::ZERO: { return GL_ZERO; } break;
|
||||
case Blend::ONE: { return GL_ONE; } break;
|
||||
|
@ -33,31 +34,29 @@ namespace Renderer
|
|||
case Blend::ONE_MINUS_DST_ALPHA: { return GL_ONE_MINUS_DST_ALPHA; } break;
|
||||
default: { return GL_ZERO; }
|
||||
}
|
||||
// clang-format on
|
||||
}
|
||||
|
||||
static GLenum convertTextureType(const Texture::Type _type)
|
||||
{
|
||||
// clang-format off
|
||||
switch (_type) {
|
||||
case Texture::RGBA: { return GL_RGBA; } break;
|
||||
case Texture::ALPHA: { return GL_ALPHA; } break;
|
||||
default: { return GL_ZERO; }
|
||||
}
|
||||
}
|
||||
|
||||
unsigned int getWindowFlags()
|
||||
{
|
||||
return SDL_WINDOW_OPENGL;
|
||||
// clang-format on
|
||||
}
|
||||
|
||||
void setupWindow()
|
||||
{
|
||||
#if defined(__APPLE__)
|
||||
#if defined(__APPLE__)
|
||||
// This is required on macOS, as the operating system will otherwise insist on using
|
||||
// a newer OpenGL version which completely breaks the application.
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);
|
||||
#else
|
||||
#else
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
|
||||
#endif
|
||||
#endif
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
|
||||
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
|
||||
|
||||
|
@ -78,32 +77,34 @@ namespace Renderer
|
|||
return false;
|
||||
}
|
||||
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
glewInit();
|
||||
#endif
|
||||
#endif
|
||||
|
||||
SDL_GL_MakeCurrent(getSDLWindow(), sdlContext);
|
||||
|
||||
std::string vendor = glGetString(GL_VENDOR) ?
|
||||
reinterpret_cast<const char*>(glGetString(GL_VENDOR)) : "";
|
||||
std::string renderer = glGetString(GL_RENDERER) ?
|
||||
reinterpret_cast<const char*>(glGetString(GL_RENDERER)) : "";
|
||||
std::string version = glGetString(GL_VERSION) ?
|
||||
reinterpret_cast<const char*>(glGetString(GL_VERSION)) : "";
|
||||
std::string vendor =
|
||||
glGetString(GL_VENDOR) ? reinterpret_cast<const char*>(glGetString(GL_VENDOR)) : "";
|
||||
std::string renderer =
|
||||
glGetString(GL_RENDERER) ? reinterpret_cast<const char*>(glGetString(GL_RENDERER)) : "";
|
||||
std::string version =
|
||||
glGetString(GL_VERSION) ? reinterpret_cast<const char*>(glGetString(GL_VERSION)) : "";
|
||||
std::string extensions = glGetString(GL_EXTENSIONS) ?
|
||||
reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)) : "";
|
||||
reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)) :
|
||||
"";
|
||||
|
||||
LOG(LogInfo) << "GL vendor: " << vendor;
|
||||
LOG(LogInfo) << "GL renderer: " << renderer;
|
||||
LOG(LogInfo) << "GL version: " << version;
|
||||
#if defined(_WIN64)
|
||||
#if defined(_WIN64)
|
||||
LOG(LogInfo) << "EmulationStation renderer: OpenGL 2.1 with GLEW";
|
||||
#else
|
||||
#else
|
||||
LOG(LogInfo) << "EmulationStation renderer: OpenGL 2.1";
|
||||
#endif
|
||||
#endif
|
||||
LOG(LogInfo) << "Checking available OpenGL extensions...";
|
||||
std::string glExts = glGetString(GL_EXTENSIONS) ?
|
||||
reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)) : "";
|
||||
reinterpret_cast<const char*>(glGetString(GL_EXTENSIONS)) :
|
||||
"";
|
||||
if (extensions.find("GL_ARB_texture_non_power_of_two") == std::string::npos) {
|
||||
LOG(LogError) << "GL_ARB_texture_non_power_of_two: MISSING";
|
||||
missingExtension = true;
|
||||
|
@ -137,7 +138,7 @@ namespace Renderer
|
|||
return false;
|
||||
}
|
||||
|
||||
uint8_t data[4] = {255, 255, 255, 255};
|
||||
uint8_t data[4] = { 255, 255, 255, 255 };
|
||||
whiteTexture = createTexture(Texture::RGBA, false, true, 1, 1, data);
|
||||
|
||||
GL_CHECK_ERROR(glClearColor(0.0f, 0.0f, 0.0f, 1.0f));
|
||||
|
@ -162,13 +163,12 @@ namespace Renderer
|
|||
sdlContext = nullptr;
|
||||
}
|
||||
|
||||
unsigned int createTexture(
|
||||
const Texture::Type _type,
|
||||
const bool _linear,
|
||||
const bool _repeat,
|
||||
const unsigned int _width,
|
||||
const unsigned int _height,
|
||||
void* _data)
|
||||
unsigned int createTexture(const Texture::Type _type,
|
||||
const bool _linear,
|
||||
const bool _repeat,
|
||||
const unsigned int _width,
|
||||
const unsigned int _height,
|
||||
void* _data)
|
||||
{
|
||||
const GLenum type = convertTextureType(_type);
|
||||
unsigned int texture;
|
||||
|
@ -176,16 +176,19 @@ namespace Renderer
|
|||
GL_CHECK_ERROR(glGenTextures(1, &texture));
|
||||
GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, texture));
|
||||
|
||||
GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, _repeat ?
|
||||
static_cast<GLfloat>(GL_REPEAT) : static_cast<GLfloat>(GL_CLAMP_TO_EDGE)));
|
||||
GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, _repeat ?
|
||||
static_cast<GLfloat>(GL_REPEAT) : static_cast<GLfloat>(GL_CLAMP_TO_EDGE)));
|
||||
GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, _linear ?
|
||||
static_cast<GLfloat>(GL_LINEAR) : static_cast<GLfloat>(GL_NEAREST)));
|
||||
GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
|
||||
_repeat ? static_cast<GLfloat>(GL_REPEAT) :
|
||||
static_cast<GLfloat>(GL_CLAMP_TO_EDGE)));
|
||||
GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
|
||||
_repeat ? static_cast<GLfloat>(GL_REPEAT) :
|
||||
static_cast<GLfloat>(GL_CLAMP_TO_EDGE)));
|
||||
GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
|
||||
_linear ? static_cast<GLfloat>(GL_LINEAR) :
|
||||
static_cast<GLfloat>(GL_NEAREST)));
|
||||
GL_CHECK_ERROR(glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST));
|
||||
|
||||
GL_CHECK_ERROR(glTexImage2D(GL_TEXTURE_2D, 0, type, _width, _height, 0, type,
|
||||
GL_UNSIGNED_BYTE, _data));
|
||||
GL_UNSIGNED_BYTE, _data));
|
||||
|
||||
return texture;
|
||||
}
|
||||
|
@ -195,20 +198,19 @@ namespace Renderer
|
|||
GL_CHECK_ERROR(glDeleteTextures(1, &_texture));
|
||||
}
|
||||
|
||||
void updateTexture(
|
||||
const unsigned int _texture,
|
||||
const Texture::Type _type,
|
||||
const unsigned int _x,
|
||||
const unsigned _y,
|
||||
const unsigned int _width,
|
||||
const unsigned int _height,
|
||||
void* _data)
|
||||
void updateTexture(const unsigned int _texture,
|
||||
const Texture::Type _type,
|
||||
const unsigned int _x,
|
||||
const unsigned _y,
|
||||
const unsigned int _width,
|
||||
const unsigned int _height,
|
||||
void* _data)
|
||||
{
|
||||
const GLenum type = convertTextureType(_type);
|
||||
|
||||
GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, _texture));
|
||||
GL_CHECK_ERROR(glTexSubImage2D(GL_TEXTURE_2D, 0, _x, _y, _width, _height,
|
||||
type, GL_UNSIGNED_BYTE, _data));
|
||||
GL_CHECK_ERROR(glTexSubImage2D(GL_TEXTURE_2D, 0, _x, _y, _width, _height, type,
|
||||
GL_UNSIGNED_BYTE, _data));
|
||||
GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, whiteTexture));
|
||||
}
|
||||
|
||||
|
@ -220,29 +222,27 @@ namespace Renderer
|
|||
GL_CHECK_ERROR(glBindTexture(GL_TEXTURE_2D, _texture));
|
||||
}
|
||||
|
||||
void drawLines(
|
||||
const Vertex* _vertices,
|
||||
const unsigned int _numVertices,
|
||||
const Blend::Factor _srcBlendFactor,
|
||||
const Blend::Factor _dstBlendFactor)
|
||||
void drawLines(const Vertex* _vertices,
|
||||
const unsigned int _numVertices,
|
||||
const Blend::Factor _srcBlendFactor,
|
||||
const Blend::Factor _dstBlendFactor)
|
||||
{
|
||||
GL_CHECK_ERROR(glVertexPointer(2, GL_FLOAT, sizeof(Vertex), &_vertices[0].pos));
|
||||
GL_CHECK_ERROR(glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &_vertices[0].tex));
|
||||
GL_CHECK_ERROR(glColorPointer( 4, GL_UNSIGNED_BYTE, sizeof(Vertex), &_vertices[0].col));
|
||||
GL_CHECK_ERROR(glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &_vertices[0].col));
|
||||
|
||||
GL_CHECK_ERROR(glBlendFunc(convertBlendFactor(_srcBlendFactor),
|
||||
convertBlendFactor(_dstBlendFactor)));
|
||||
GL_CHECK_ERROR(
|
||||
glBlendFunc(convertBlendFactor(_srcBlendFactor), convertBlendFactor(_dstBlendFactor)));
|
||||
|
||||
GL_CHECK_ERROR(glDrawArrays(GL_LINES, 0, _numVertices));
|
||||
}
|
||||
|
||||
void drawTriangleStrips(
|
||||
const Vertex* _vertices,
|
||||
const unsigned int _numVertices,
|
||||
const Transform4x4f& _trans,
|
||||
const Blend::Factor _srcBlendFactor,
|
||||
const Blend::Factor _dstBlendFactor,
|
||||
const shaderParameters& _parameters)
|
||||
void drawTriangleStrips(const Vertex* _vertices,
|
||||
const unsigned int _numVertices,
|
||||
const Transform4x4f& _trans,
|
||||
const Blend::Factor _srcBlendFactor,
|
||||
const Blend::Factor _dstBlendFactor,
|
||||
const shaderParameters& _parameters)
|
||||
{
|
||||
float width = _vertices[3].pos[0];
|
||||
float height = _vertices[3].pos[1];
|
||||
|
@ -251,17 +251,17 @@ namespace Renderer
|
|||
GL_CHECK_ERROR(glTexCoordPointer(2, GL_FLOAT, sizeof(Vertex), &_vertices[0].tex));
|
||||
GL_CHECK_ERROR(glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(Vertex), &_vertices[0].col));
|
||||
|
||||
GL_CHECK_ERROR(glBlendFunc(convertBlendFactor(_srcBlendFactor),
|
||||
convertBlendFactor(_dstBlendFactor)));
|
||||
GL_CHECK_ERROR(
|
||||
glBlendFunc(convertBlendFactor(_srcBlendFactor), convertBlendFactor(_dstBlendFactor)));
|
||||
|
||||
#if defined(USE_OPENGL_21)
|
||||
#if defined(USE_OPENGL_21)
|
||||
if (_vertices[0].shaders == 0) {
|
||||
GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices));
|
||||
}
|
||||
else {
|
||||
// If saturation is set below the maximum (default) value, run the
|
||||
// desaturation shader.
|
||||
if (_vertices->saturation < 1.0 || _parameters.fragmentSaturation < 1.0) {
|
||||
if (_vertices->saturation < 1.0f || _parameters.fragmentSaturation < 1.0f) {
|
||||
Shader* runShader = getShaderProgram(SHADER_DESATURATE);
|
||||
// Only try to use the shader if it has been loaded properly.
|
||||
if (runShader) {
|
||||
|
@ -278,9 +278,8 @@ namespace Renderer
|
|||
if (runShader) {
|
||||
runShader->activateShaders();
|
||||
runShader->setModelViewProjectionMatrix(getProjectionMatrix() * _trans);
|
||||
_vertices->opacity < 1.0 ?
|
||||
runShader->setOpacity(_vertices->opacity) :
|
||||
runShader->setOpacity(_parameters.fragmentOpacity);
|
||||
_vertices->opacity < 1.0f ? runShader->setOpacity(_vertices->opacity) :
|
||||
runShader->setOpacity(_parameters.fragmentOpacity);
|
||||
GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices));
|
||||
runShader->deactivateShaders();
|
||||
}
|
||||
|
@ -303,7 +302,7 @@ namespace Renderer
|
|||
if (runShader) {
|
||||
runShader->activateShaders();
|
||||
runShader->setModelViewProjectionMatrix(getProjectionMatrix() * _trans);
|
||||
runShader->setTextureSize({width, height});
|
||||
runShader->setTextureSize({ width, height });
|
||||
GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices));
|
||||
runShader->deactivateShaders();
|
||||
}
|
||||
|
@ -314,7 +313,7 @@ namespace Renderer
|
|||
if (runShader) {
|
||||
runShader->activateShaders();
|
||||
runShader->setModelViewProjectionMatrix(getProjectionMatrix() * _trans);
|
||||
runShader->setTextureSize({width, height});
|
||||
runShader->setTextureSize({ width, height });
|
||||
GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices));
|
||||
runShader->deactivateShaders();
|
||||
}
|
||||
|
@ -338,20 +337,20 @@ namespace Renderer
|
|||
// scanlines to videos with non-standard aspect ratios.
|
||||
float relativeWidth = width / getScreenWidth();
|
||||
float relativeAdjustment = (relativeWidth + relativeHeight) / 2.0f;
|
||||
float modifier = 1.41f + relativeAdjustment / 7.0f -
|
||||
(0.14f * screenHeightModifier);
|
||||
float modifier =
|
||||
1.41f + relativeAdjustment / 7.0f - (0.14f * screenHeightModifier);
|
||||
shaderHeight = height * modifier;
|
||||
}
|
||||
if (runShader) {
|
||||
runShader->activateShaders();
|
||||
runShader->setModelViewProjectionMatrix(getProjectionMatrix() * _trans);
|
||||
runShader->setTextureSize({shaderWidth, shaderHeight});
|
||||
runShader->setTextureSize({ shaderWidth, shaderHeight });
|
||||
GL_CHECK_ERROR(glDrawArrays(GL_TRIANGLE_STRIP, 0, _numVertices));
|
||||
runShader->deactivateShaders();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
}
|
||||
|
||||
void setProjection(const Transform4x4f& _projection)
|
||||
|
@ -372,8 +371,8 @@ namespace Renderer
|
|||
void setViewport(const Rect& _viewport)
|
||||
{
|
||||
// glViewport starts at the bottom left of the window.
|
||||
GL_CHECK_ERROR(glViewport( _viewport.x, getWindowHeight() -
|
||||
_viewport.y - _viewport.h, _viewport.w, _viewport.h));
|
||||
GL_CHECK_ERROR(glViewport(_viewport.x, getWindowHeight() - _viewport.y - _viewport.h,
|
||||
_viewport.w, _viewport.h));
|
||||
}
|
||||
|
||||
void setScissor(const Rect& _scissor)
|
||||
|
@ -383,8 +382,8 @@ namespace Renderer
|
|||
}
|
||||
else {
|
||||
// glScissor starts at the bottom left of the window.
|
||||
GL_CHECK_ERROR(glScissor(_scissor.x, getWindowHeight() -
|
||||
_scissor.y - _scissor.h, _scissor.w, _scissor.h));
|
||||
GL_CHECK_ERROR(glScissor(_scissor.x, getWindowHeight() - _scissor.y - _scissor.h,
|
||||
_scissor.w, _scissor.h));
|
||||
GL_CHECK_ERROR(glEnable(GL_SCISSOR_TEST));
|
||||
}
|
||||
}
|
||||
|
@ -413,11 +412,12 @@ namespace Renderer
|
|||
GL_CHECK_ERROR(glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
|
||||
}
|
||||
|
||||
void shaderPostprocessing(unsigned int shaders, const Renderer::shaderParameters& parameters,
|
||||
unsigned char* textureRGBA)
|
||||
void shaderPostprocessing(unsigned int shaders,
|
||||
const Renderer::shaderParameters& parameters,
|
||||
unsigned char* textureRGBA)
|
||||
{
|
||||
Vertex vertices[4];
|
||||
std::vector<unsigned int>shaderList;
|
||||
std::vector<unsigned int> shaderList;
|
||||
GLuint width = getScreenWidth();
|
||||
GLuint height = getScreenHeight();
|
||||
float widthf = static_cast<float>(width);
|
||||
|
@ -425,10 +425,12 @@ namespace Renderer
|
|||
|
||||
// Set vertex positions and texture coordinates to full screen as all
|
||||
// postprocessing is applied to the complete screen area.
|
||||
vertices[0] = { { 0, 0 }, { 0, 1 }, 0 };
|
||||
vertices[1] = { { 0, heightf }, { 0, 0 }, 0 };
|
||||
vertices[2] = { { widthf, 0 }, { 1, 1 }, 0 };
|
||||
vertices[3] = { { widthf, heightf }, { 1, 0 }, 0};
|
||||
// clang-format off
|
||||
vertices[0] = { { 0.0f , 0.0f }, { 0.0f, 1.0f }, 0 };
|
||||
vertices[1] = { { 0.0f , heightf }, { 0.0f, 0.0f }, 0 };
|
||||
vertices[2] = { { widthf, 0.0f }, { 1.0f, 1.0f }, 0 };
|
||||
vertices[3] = { { widthf, heightf }, { 1.0f, 0.0f }, 0 };
|
||||
// clang-format on
|
||||
|
||||
if (shaders & Renderer::SHADER_DESATURATE)
|
||||
shaderList.push_back(Renderer::SHADER_DESATURATE);
|
||||
|
@ -457,27 +459,24 @@ namespace Renderer
|
|||
// For the blur shaders there is an optional variable to set the number of passes
|
||||
// to execute, which proportionally affects the blur amount.
|
||||
if (shaderList[i] == Renderer::SHADER_BLUR_HORIZONTAL ||
|
||||
shaderList[i] == Renderer::SHADER_BLUR_VERTICAL)
|
||||
shaderList[i] == Renderer::SHADER_BLUR_VERTICAL) {
|
||||
shaderPasses = parameters.blurPasses;
|
||||
}
|
||||
|
||||
for (int p = 0; p < shaderPasses; p++) {
|
||||
GL_CHECK_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, shaderFBO));
|
||||
|
||||
// Attach the texture to the shader framebuffer.
|
||||
GL_CHECK_ERROR(glFramebufferTexture2D(
|
||||
GL_FRAMEBUFFER,
|
||||
GL_COLOR_ATTACHMENT0,
|
||||
GL_TEXTURE_2D,
|
||||
screenTexture,
|
||||
0));
|
||||
GL_CHECK_ERROR(glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
|
||||
GL_TEXTURE_2D, screenTexture, 0));
|
||||
|
||||
// Blit the screen contents to screenTexture.
|
||||
GL_CHECK_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height,
|
||||
GL_COLOR_BUFFER_BIT, GL_NEAREST));
|
||||
GL_COLOR_BUFFER_BIT, GL_NEAREST));
|
||||
|
||||
// Apply/render the shaders.
|
||||
drawTriangleStrips(vertices, 4, Transform4x4f::Identity(),
|
||||
Blend::SRC_ALPHA, Blend::ONE_MINUS_SRC_ALPHA, parameters);
|
||||
drawTriangleStrips(vertices, 4, Transform4x4f::Identity(), Blend::SRC_ALPHA,
|
||||
Blend::ONE_MINUS_SRC_ALPHA, parameters);
|
||||
|
||||
// If textureRGBA has an address, it means that the output should go to this
|
||||
// texture rather than to the screen. The glReadPixels() function is slow, but
|
||||
|
@ -485,8 +484,8 @@ namespace Renderer
|
|||
// screen texture, it doesn't really matter.
|
||||
if (textureRGBA) {
|
||||
GL_CHECK_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, shaderFBO));
|
||||
GL_CHECK_ERROR(glReadPixels(0, 0, width, height,
|
||||
GL_RGBA, GL_UNSIGNED_BYTE, textureRGBA));
|
||||
GL_CHECK_ERROR(
|
||||
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, textureRGBA));
|
||||
GL_CHECK_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0));
|
||||
}
|
||||
else {
|
||||
|
@ -494,7 +493,7 @@ namespace Renderer
|
|||
GL_CHECK_ERROR(glBindFramebuffer(GL_READ_FRAMEBUFFER, shaderFBO));
|
||||
GL_CHECK_ERROR(glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0));
|
||||
GL_CHECK_ERROR(glBlitFramebuffer(0, 0, width, height, 0, 0, width, height,
|
||||
GL_COLOR_BUFFER_BIT, GL_NEAREST));
|
||||
GL_COLOR_BUFFER_BIT, GL_NEAREST));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -503,6 +502,6 @@ namespace Renderer
|
|||
destroyTexture(screenTexture);
|
||||
}
|
||||
|
||||
} // Renderer::
|
||||
} // namespace Renderer
|
||||
|
||||
#endif // USE_OPENGL_21
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue