merging uni's and trunk branches. Not everything tested right now

git-svn-id: svn+ssh://svn.code.sf.net/p/supertuxkart/code/main/branches/hilnius@13577 178a84e3-b1eb-0310-8ba1-8eac791a3b58
This commit is contained in:
hilnius 2013-08-27 01:02:41 +00:00
commit 8233b8067d
83 changed files with 2013 additions and 562 deletions

View File

@ -0,0 +1,19 @@
<stkgui>
<div x="2%" y="5%" width="96%" height="85%" layout="vertical-row" >
<label id="info" proportion="1" width="90%" align="center" text_align="center" word_wrap="true" text=""/>
<spacer height="20" width="50">
<buttonbar id="options" width="90%" height="30%" align="center">
<icon-button id="view" width="64" height="64" icon="gui/difficulty_medium.png"
I18N="User info dialog" text="View friends" label_location="bottom"/>
<icon-button id="cancel" width="64" height="64" icon="gui/main_quit.png"
I18N="User info dialog" text="Close" label_location="bottom"/>
</buttonbar>
</div>
</stkgui>

View File

@ -1,6 +1,8 @@
<stkgui>
<div x="1%" y="1%" width="98%" height="98%" layout="vertical-row" >
<icon-button id="back" x="0" y="0" height="8%" icon="gui/back.png"/>
<div x="1%" y="2%" width="98%" height="96%" layout="vertical-row" >
<header id="title" text_align="center" width="80%" align="center" text="..."/>
@ -11,27 +13,23 @@
<icon-button id="tab_friends" width="128" height="128" icon="gui/options_players.png" I18N="Section in the profile menu" text="Friends"/>
</tabs>
<box proportion="1" width="100%" layout="vertical-row">
<div x="1%" y="2%" width="98%" height="96%" layout="horizontal-row" >
<div proportion="2" height="100%" layout="vertical-row">
<box proportion="2" width="100%" align="center" layout="vertical-row" padding="6">
<list id="friends_list" x="0" y="0" width="100%" height="100%"/>
</box>
<spacer width="10" height="10"/>
<label height="fit" text_align="left" I18N="Profile friends" text="Look for more friends:"/>
<spacer width="10" height="10"/>
<div height="fit" width="100%" layout="horizontal-row" align="center">
<textbox id="search_box" proportion="1" height="100%"/>
<spacer width="10" height="10"/>
<button id="search_button" height="fit" width="fit" text="Search" />
</div>
</div>
<spacer width="2%" height="10"/>
<div proportion="1" height="100%" layout="horizontal-row" > </div>
</div>
<box proportion="1" width="100%" layout="vertical-row" padding="6">
<list id="friends_list" x="0" y="0" width="100%" height="100%"/>
</box>
<div id="search_div" height="fit" width="100%" layout="vertical-row">
<spacer width="10" height="10"/>
<box height="fit" width="100%" layout="vertical-row">
<label height="fit" text_align="left" I18N="Profile friends" text="Look for more friends:"/>
<spacer width="10" height="10"/>
<div height="fit" width="100%" layout="horizontal-row" align="center">
<textbox id="search_box" proportion="1" height="fit"/>
<spacer width="10" height="100%"/>
<button id="search_button" height="100%" width="fit" text="Search" />
</div>
</box>
</div>
</div>
<icon-button id="back" x="0" y="0" height="8%" icon="gui/back.png"/>
</stkgui>

View File

@ -0,0 +1,41 @@
<stkgui>
<div x="2%" y="5%" width="96%" height="85%" layout="vertical-row" >
<header id="title" width="96%" height="fit" text_align="center" word_wrap="true"
I18N="User info dialog' dialog" text="User Info"/>
<spacer height="20" width="50">
<div width="80%" align="center" layout="vertical-row" height="fit" >
<div width="100%" height="fit" layout="horizontal-row" >
<label proportion="1" text_align="left" I18N="User info dialog" text="Name"/>
<label id="name" proportion="2" text_align="left" text=""/>
</div>
</div>
<spacer height="20" width="50">
<label id="info" proportion="1" width="90%" align="center" text_align="center" word_wrap="true" text=""/>
<spacer height="20" width="50">
<buttonbar id="options" width="90%" height="20%" align="center">
<icon-button id="remove" width="64" height="64" icon="gui/package-uninstall.png"
I18N="User info dialog" text="Remove" label_location="bottom"/>
<icon-button id="friend" width="64" height="64" icon="gui/main_help.png"
I18N="User info dialog" text="Add Friend" label_location="bottom"/>
<icon-button id="accept" width="64" height="64" icon="gui/green_check.png"
I18N="User info dialog" text="Accept" label_location="bottom"/>
<icon-button id="decline" width="64" height="64" icon="gui/red_mark.png"
I18N="User info dialog" text="Decline" label_location="bottom"/>
<icon-button id="enter" width="64" height="64" icon="gui/difficulty_medium.png"
I18N="User info dialog" text="View" label_location="bottom"/>
<icon-button id="cancel" width="64" height="64" icon="gui/main_quit.png"
I18N="User info dialog" text="Close" label_location="bottom"/>
</buttonbar>
</div>
</stkgui>

View File

@ -1,23 +1,24 @@
<stkgui>
<div x="0%" y="0%" width="100%" height="98%" layout="vertical-row" >
<div x="0" y="0" width="100%" layout="horizontal-row" height="8%">
<icon-button id="back" height="100%" icon="gui/back.png"/>
<header text_align="center" proportion="1" text="Server Selection" align="center"/>
</div>
<div height="fit" width="100%" layout="horizontal-row" align="center">
<textbox id="search_box" proportion="1" height="100%"/>
<spacer width="30" height="10"/>
<button id="search_button" height="fit" width="fit" text="Search" />
<icon-button id="back" x="0" y="0" height="8%" icon="gui/back.png"/>
<div x="1%" y="0%" width="98%" height="99%" layout="vertical-row" >
<header text_align="center" height="fit" text="User search" align="center"/>
<spacer width="10" height="10"/>
<div height="fit" width="100%" layout="horizontal-row" align="center">
<textbox id="search_box" height="fit" proportion="1" height="100%"/>
<spacer width="10" height="10"/>
<button id="search_button" height="100%" width="fit" text="Search" />
</div>
<spacer width="10" height="10"/>
<box proportion="1" width="100%" align="center" layout="vertical-row" padding="6">
<list id="user_list" x="0" y="0" width="100%" height="100%"/>
</box>
</div>
<box proportion="1" width="98%" align="center" layout="vertical-row" padding="6">
<list id="user_list" x="0" y="0" width="100%" height="100%"/>
</box>
</div>
</stkgui>

View File

@ -13,8 +13,8 @@ void main()
{
float inter = dot(normal, eyeVec);
float m = texture2D(tex, vec2(0.5, uv.y)).r;
inter = 1 - inter;
float alpha = inter + 1;// * m;
inter = 1.0 - inter;
float alpha = inter + 1.0;// * m;
gl_FragColor = vec4(0.8, 0.16, 0.48, alpha);
}

View File

@ -9,3 +9,4 @@ The following changes have been made:
- a workaround for every other RTTs flipping
- aabbox intersection support
- texture override
- non-triangle VBO support

View File

@ -76,6 +76,11 @@ namespace scene
return Material;
}
virtual scene::E_PRIMITIVE_TYPE getPrimitiveType() const
{
return scene::EPT_TRIANGLES;
}
//! Get bounding box
virtual const core::aabbox3d<f32>& getBoundingBox() const
{

View File

@ -18,7 +18,9 @@ namespace scene
{
public:
//! Default constructor for empty meshbuffer
CMeshBuffer():ChangedID_Vertex(1),ChangedID_Index(1),MappingHint_Vertex(EHM_NEVER), MappingHint_Index(EHM_NEVER)
CMeshBuffer(): ChangedID_Vertex(1), ChangedID_Index(1),
MappingHint_Vertex(EHM_NEVER), MappingHint_Index(EHM_NEVER),
Primitive(EPT_TRIANGLES)
{
#ifdef _DEBUG
setDebugName("SMeshBuffer");
@ -171,6 +173,10 @@ namespace scene
return Vertices[i].TCoords;
}
virtual scene::E_PRIMITIVE_TYPE getPrimitiveType() const
{
return Primitive;
}
//! Append the vertices and indices to the current buffer
/** Only works for compatible types, i.e. either the same type
@ -285,6 +291,9 @@ namespace scene
core::array<u16> Indices;
//! Bounding box of this meshbuffer.
core::aabbox3d<f32> BoundingBox;
//! What kind of primitives does this buffer contain? Default triangles
scene::E_PRIMITIVE_TYPE Primitive;
};
//! Standard meshbuffer

View File

@ -112,6 +112,9 @@ namespace scene
//! returns texture coord of vertex i
virtual core::vector2df& getTCoords(u32 i) = 0;
//! Returns the primitive type of this buffer
virtual scene::E_PRIMITIVE_TYPE getPrimitiveType() const = 0;
//! Append the vertices and indices to the current buffer
/** Only works for compatible vertex types.
\param vertices Pointer to a vertex array.

View File

@ -1459,6 +1459,9 @@ namespace video
//! Get the maximum texture size supported.
virtual core::dimension2du getMaxTextureSize() const =0;
//! Convert the number of indices to the number of primitives
virtual u32 indiceToPrimitiveCount(scene::E_PRIMITIVE_TYPE pType, u32 count) const = 0;
//! Color conversion convenience function
/** Convert an image (as array of pixels) from source to destination
array, thereby converting the color format. The pixel size is

View File

@ -22,7 +22,7 @@ struct SSkinMeshBuffer : public IMeshBuffer
SSkinMeshBuffer(video::E_VERTEX_TYPE vt=video::EVT_STANDARD) :
ChangedID_Vertex(1), ChangedID_Index(1), VertexType(vt),
MappingHint_Vertex(EHM_NEVER), MappingHint_Index(EHM_NEVER),
BoundingBoxNeedsRecalculated(true)
BoundingBoxNeedsRecalculated(true), Primitive(EPT_TRIANGLES)
{
#ifdef _DEBUG
setDebugName("SSkinMeshBuffer");
@ -325,6 +325,12 @@ struct SSkinMeshBuffer : public IMeshBuffer
}
}
virtual scene::E_PRIMITIVE_TYPE getPrimitiveType() const
{
return Primitive;
}
//! append the vertices and indices to the current buffer
virtual void append(const void* const vertices, u32 numVertices, const u16* const indices, u32 numIndices) {}
@ -394,6 +400,9 @@ struct SSkinMeshBuffer : public IMeshBuffer
E_HARDWARE_MAPPING MappingHint_Index:3;
bool BoundingBoxNeedsRecalculated:1;
//! What kind of primitives does this buffer contain? Default triangles
scene::E_PRIMITIVE_TYPE Primitive;
};

View File

@ -279,6 +279,9 @@ namespace core
//! Builds a left-handed orthogonal projection matrix.
CMatrix4<T>& buildProjectionMatrixOrthoLH(f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar);
//! Builds a left-handed orthogonal projection matrix, with specific corners.
CMatrix4<T>& buildProjectionMatrixOrthoLH(f32 left, f32 right, f32 up, f32 down, f32 zNear, f32 zFar);
//! Builds a right-handed orthogonal projection matrix.
CMatrix4<T>& buildProjectionMatrixOrthoRH(f32 widthOfViewVolume, f32 heightOfViewVolume, f32 zNear, f32 zFar);
@ -1633,6 +1636,41 @@ namespace core
return *this;
}
// Builds a left-handed orthogonal projection matrix, with specific corners.
template <class T>
inline CMatrix4<T>& CMatrix4<T>::buildProjectionMatrixOrthoLH(
f32 left, f32 right, f32 up, f32 down,
f32 zNear, f32 zFar)
{
_IRR_DEBUG_BREAK_IF(zNear == zFar); //divide by zero
_IRR_DEBUG_BREAK_IF(right == left); //divide by zero
_IRR_DEBUG_BREAK_IF(up == down); //divide by zero
M[0] = (T)(2/(right - left));
M[1] = 0;
M[2] = 0;
M[3] = 0;
M[4] = 0;
M[5] = (T)(2/(up - down));
M[6] = 0;
M[7] = 0;
M[8] = 0;
M[9] = 0;
M[10] = (T)(1/(zFar - zNear));
M[11] = 0;
M[12] = (T)-((right + left) / (right - left));
M[13] = (T)-((up + down) / (up - down));
M[14] = (T)(zNear/(zNear-zFar));
M[15] = 1;
#if defined ( USE_MATRIX_TEST )
definitelyIdentityMatrix=false;
#endif
return *this;
}
// Builds a right-handed orthogonal projection matrix.
template <class T>

View File

@ -1518,7 +1518,7 @@ void CNullDriver::drawMeshBuffer(const scene::IMeshBuffer* mb)
if (HWBuffer)
drawHardwareBuffer(HWBuffer);
else
drawVertexPrimitiveList(mb->getVertices(), mb->getVertexCount(), mb->getIndices(), mb->getIndexCount()/3, mb->getVertexType(), scene::EPT_TRIANGLES, mb->getIndexType());
drawVertexPrimitiveList(mb->getVertices(), mb->getVertexCount(), mb->getIndices(), indiceToPrimitiveCount(mb->getPrimitiveType(), mb->getIndexCount()), mb->getVertexType(), mb->getPrimitiveType(), mb->getIndexType());
}
@ -2444,6 +2444,32 @@ void CNullDriver::convertColor(const void* sP, ECOLOR_FORMAT sF, s32 sN,
video::CColorConverter::convert_viaFormat(sP, sF, sN, dP, dF);
}
u32 CNullDriver::indiceToPrimitiveCount(scene::E_PRIMITIVE_TYPE ptype, u32 count) const
{
switch (ptype)
{
case scene::EPT_POINTS:
case scene::EPT_POINT_SPRITES:
case scene::EPT_LINE_LOOP:
case scene::EPT_POLYGON:
return count;
case scene::EPT_LINE_STRIP:
return count - 1;
case scene::EPT_LINES:
return count/2;
case scene::EPT_TRIANGLE_STRIP:
case scene::EPT_TRIANGLE_FAN:
return count - 2;
case scene::EPT_TRIANGLES:
return count/3;
case scene::EPT_QUAD_STRIP:
return (count - 2) / 2;
case scene::EPT_QUADS:
return count/4;
default:
return count;
}
}
} // end namespace
} // end namespace

View File

@ -94,6 +94,8 @@ namespace video
//! Returns amount of textures currently loaded
virtual u32 getTextureCount() const;
virtual u32 indiceToPrimitiveCount(scene::E_PRIMITIVE_TYPE pType, u32 count) const;
//! Renames a texture
virtual void renameTexture(ITexture* texture, const io::path& newName);

View File

@ -1301,7 +1301,7 @@ void COpenGLDriver::drawHardwareBuffer(SHWBufferLink *_HWBuffer)
indexList=0;
}
drawVertexPrimitiveList(vertices, mb->getVertexCount(), indexList, mb->getIndexCount()/3, mb->getVertexType(), scene::EPT_TRIANGLES, mb->getIndexType());
drawVertexPrimitiveList(vertices, mb->getVertexCount(), indexList, indiceToPrimitiveCount(mb->getPrimitiveType(), mb->getIndexCount()), mb->getVertexType(), mb->getPrimitiveType(), mb->getIndexType());
if (HWBuffer->Mapped_Vertex!=scene::EHM_NEVER)
extGlBindBuffer(GL_ARRAY_BUFFER, 0);

View File

@ -51,6 +51,7 @@ src/graphics/stars.cpp
src/guiengine/abstract_state_manager.cpp
src/guiengine/abstract_top_level_container.cpp
src/guiengine/CGUISpriteBank.cpp
src/guiengine/dialog_queue.cpp
src/guiengine/engine.cpp
src/guiengine/event_handler.cpp
src/guiengine/layout_manager.cpp
@ -178,7 +179,6 @@ src/online/profile_manager.cpp
src/online/request.cpp
src/online/server.cpp
src/online/servers_manager.cpp
src/online/user.cpp
src/physics/btKart.cpp
src/physics/btKartRaycast.cpp
src/physics/btUprightConstraint.cpp
@ -208,6 +208,7 @@ src/states_screens/dialogs/enter_player_name_dialog.cpp
src/states_screens/dialogs/gp_info_dialog.cpp
src/states_screens/dialogs/login_dialog.cpp
src/states_screens/dialogs/message_dialog.cpp
src/states_screens/dialogs/notification_dialog.cpp
src/states_screens/dialogs/player_info_dialog.cpp
src/states_screens/dialogs/press_a_key_dialog.cpp
src/states_screens/dialogs/race_paused_dialog.cpp
@ -217,6 +218,7 @@ src/states_screens/dialogs/select_challenge.cpp
src/states_screens/dialogs/server_info_dialog.cpp
src/states_screens/dialogs/track_info_dialog.cpp
src/states_screens/dialogs/tutorial_message_dialog.cpp
src/states_screens/dialogs/user_info_dialog.cpp
src/states_screens/dialogs/vote_dialog.cpp
src/states_screens/feature_unlocked.cpp
src/states_screens/grand_prix_lose.cpp
@ -347,6 +349,7 @@ src/graphics/slip_stream.hpp
src/graphics/stars.hpp
src/guiengine/abstract_state_manager.hpp
src/guiengine/abstract_top_level_container.hpp
src/guiengine/dialog_queue.hpp
src/guiengine/engine.hpp
src/guiengine/event_handler.hpp
src/guiengine/layout_manager.hpp
@ -476,7 +479,6 @@ src/online/profile_manager.hpp
src/online/request.hpp
src/online/server.hpp
src/online/servers_manager.hpp
src/online/user.hpp
src/physics/btKart.hpp
src/physics/btKartRaycast.hpp
src/physics/btUprightConstraint.hpp
@ -509,6 +511,7 @@ src/states_screens/dialogs/enter_player_name_dialog.hpp
src/states_screens/dialogs/gp_info_dialog.hpp
src/states_screens/dialogs/login_dialog.hpp
src/states_screens/dialogs/message_dialog.hpp
src/states_screens/dialogs/notification_dialog.hpp
src/states_screens/dialogs/player_info_dialog.hpp
src/states_screens/dialogs/press_a_key_dialog.hpp
src/states_screens/dialogs/race_paused_dialog.hpp
@ -518,6 +521,7 @@ src/states_screens/dialogs/select_challenge.hpp
src/states_screens/dialogs/server_info_dialog.hpp
src/states_screens/dialogs/track_info_dialog.hpp
src/states_screens/dialogs/tutorial_message_dialog.hpp
src/states_screens/dialogs/user_info_dialog.hpp
src/states_screens/dialogs/vote_dialog.hpp
src/states_screens/feature_unlocked.hpp
src/states_screens/grand_prix_lose.hpp

View File

@ -154,14 +154,16 @@ void SFXManager::loadSfx()
std::cerr << "Could not read sounf effects XML file " << sfx_config_name.c_str() << std::endl;
}
int i;
const int amount = root->getNumNodes();
for (int i=0; i<amount; i++)
for (i=0; i<amount; i++)
{
const XMLNode* node = root->getNode(i);
if (node->getName() == "sfx")
{
loadSingleSfx(node);
loadSingleSfx(node, "", false);
}
else
{
@ -171,7 +173,27 @@ void SFXManager::loadSfx()
}// nend for
delete root;
} // loadSfx
// Now load them in parallel
const int max = m_all_sfx_types.size();
SFXBuffer **array = new SFXBuffer *[max];
i = 0;
for (std::map<std::string, SFXBuffer*>::iterator it = m_all_sfx_types.begin();
it != m_all_sfx_types.end(); it++)
{
SFXBuffer* const buffer = (*it).second;
array[i++] = buffer;
}
#pragma omp parallel for private(i)
for (i = 0; i < max; i++)
{
array[i]->load();
}
delete [] array;
} // loadSfx
// -----------------------------------------------------------------------------
/** Introduces a mechanism by which one can load sound effects beyond the basic
@ -188,7 +210,8 @@ SFXBuffer* SFXManager::addSingleSfx(const std::string &sfx_name,
bool positional,
float rolloff,
float max_width,
float gain)
float gain,
const bool load)
{
SFXBuffer* buffer = new SFXBuffer(sfx_file, positional, rolloff, max_width, gain);
@ -205,7 +228,7 @@ SFXBuffer* SFXManager::addSingleSfx(const std::string &sfx_name,
if (UserConfigParams::logMisc())
Log::debug("SFXManager", "Loading SFX %s\n", sfx_file.c_str());
if (buffer->load()) return buffer;
if (load && buffer->load()) return buffer;
return NULL;
} // addSingleSFX
@ -215,7 +238,8 @@ SFXBuffer* SFXManager::addSingleSfx(const std::string &sfx_name,
* \param node The XML node with the data for this sfx.
*/
SFXBuffer* SFXManager::loadSingleSfx(const XMLNode* node,
const std::string &path)
const std::string &path,
const bool load)
{
std::string filename;
@ -254,7 +278,8 @@ SFXBuffer* SFXManager::loadSingleSfx(const XMLNode* node,
tmpbuffer.isPositional(),
tmpbuffer.getRolloff(),
tmpbuffer.getMaxDist(),
tmpbuffer.getGain());
tmpbuffer.getGain(),
load);
} // loadSingleSfx

View File

@ -106,13 +106,15 @@ public:
virtual ~SFXManager();
bool sfxAllowed();
SFXBuffer* loadSingleSfx(const XMLNode* node,
const std::string &path=std::string(""));
const std::string &path=std::string(""),
const bool load = true);
SFXBuffer* addSingleSfx(const std::string &sfx_name,
const std::string &filename,
bool positional,
float rolloff,
float max_width,
float gain);
float gain,
const bool load = true);
SFXBase* createSoundSource(SFXBuffer* info,
const bool addToSFXList=true,

View File

@ -687,7 +687,7 @@ namespace UserConfigParams
"Everything related to online play.") );
PARAM_PREFIX StringUserConfigParam m_server_multiplayer
PARAM_DEFAULT( StringUserConfigParam( "http://api.stkaddons.net/",
PARAM_DEFAULT( StringUserConfigParam( "https://api.stkaddons.net/",
"server_multiplayer",
&m_online_group,
"The server used for online multiplayer."));

View File

@ -1022,7 +1022,6 @@ void Material::setMaterialProperties(video::SMaterial *m, scene::IMeshBuffer* m
}
if (m_smooth_reflection_shader)
{
IVideoDriver* video_driver = irr_driver->getVideoDriver();
if (UserConfigParams::m_pixel_shaders &&
irr_driver->isGLSL())
{
@ -1308,7 +1307,6 @@ void Material::setMaterialProperties(video::SMaterial *m, scene::IMeshBuffer* m
if (m_graphical_effect == GE_WATER_SHADER)
{
IVideoDriver* video_driver = irr_driver->getVideoDriver();
if (UserConfigParams::m_pixel_shaders &&
irr_driver->isGLSL())
{
@ -1345,7 +1343,6 @@ void Material::setMaterialProperties(video::SMaterial *m, scene::IMeshBuffer* m
if (m_graphical_effect == GE_GRASS)
{
IVideoDriver* video_driver = irr_driver->getVideoDriver();
if (UserConfigParams::m_pixel_shaders &&
irr_driver->isGLSL())
{

View File

@ -0,0 +1,82 @@
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2013 Glenn De Jonghe
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "guiengine/dialog_queue.hpp"
#include "assert.h"
using namespace GUIEngine;
namespace GUIEngine
{
static DialogQueue* dialog_queue_singleton(NULL);
DialogQueue* DialogQueue::get()
{
if (dialog_queue_singleton == NULL)
dialog_queue_singleton = new DialogQueue();
return dialog_queue_singleton;
}
void DialogQueue::deallocate()
{
delete dialog_queue_singleton;
dialog_queue_singleton = NULL;
} // deallocate
// ----------------------------------------------------------------------------
DialogQueue::DialogQueue()
{
m_closer = NULL;
}
// ----------------------------------------------------------------------------
void DialogQueue::pushDialog(ModalDialog * dialog, bool closes_any_dialog)
{
assert(!dialog->isInited());
if(closes_any_dialog)
{
delete m_closer;
m_closer = dialog;
}
else
m_queue.push(dialog);
}
// ----------------------------------------------------------------------------
void DialogQueue::update()
{
if(m_closer != NULL)
{
ModalDialog::dismiss();
m_closer->load();
m_closer = NULL;
}
else if(!m_queue.empty())
{
ModalDialog * entry = m_queue.front();
if(!ModalDialog::isADialogActive())
{
entry->load();
m_queue.pop();
}
}
}
}

View File

@ -0,0 +1,47 @@
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2013 Glenn De Jonghe
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_DIALOG_QUEUE_HPP
#define HEADER_DIALOG_QUEUE_HPP
#include <queue>
#include "guiengine/modaldialog.hpp"
/**
* \ingroup guiengine
*/
namespace GUIEngine
{
class DialogQueue
{
private :
std::queue<ModalDialog *> m_queue;
ModalDialog * m_closer;
DialogQueue();
public :
/**Singleton */
static DialogQueue * get();
static void deallocate();
void pushDialog(ModalDialog * dialog, bool closes_any_dialog = false);
void update();
};
}
#endif

View File

@ -657,6 +657,7 @@ namespace GUIEngine
#include "guiengine/screen.hpp"
#include "guiengine/skin.hpp"
#include "guiengine/widget.hpp"
#include "guiengine/dialog_queue.hpp"
#include "modes/demo_world.hpp"
#include "modes/world.hpp"
#include "states_screens/race_gui_base.hpp"
@ -835,6 +836,7 @@ namespace GUIEngine
{
widget->update(dt);
}
DialogQueue::get()->update();
}
}

View File

@ -47,17 +47,19 @@ using namespace GUIEngine;
// ----------------------------------------------------------------------------
ModalDialog::ModalDialog(const float percentWidth, const float percentHeight,
ModalDialogLocation location)
ModalDialog::ModalDialog(const float percentWidth, const float percentHeight, ModalDialogLocation location)
{
m_dialog_location = location;
doInit(percentWidth, percentHeight);
m_init = false;
m_percent_width = percentWidth;
m_percent_height = percentHeight;
}
// ----------------------------------------------------------------------------
void ModalDialog::loadFromFile(const char* xmlFile)
{
doInit();
IXMLReader* xml = file_manager->createXMLReader( (file_manager->getGUIDir() + xmlFile).c_str() );
if (xml == NULL)
{
@ -82,15 +84,17 @@ void ModalDialog::loadFromFile(const char* xmlFile)
// ----------------------------------------------------------------------------
void ModalDialog::doInit(const float percentWidth, const float percentHeight)
void ModalDialog::doInit()
{
if(m_init) return;
m_init = true;
pointer_was_shown = irr_driver->isPointerShown();
irr_driver->showPointer();
const core::dimension2d<u32>& frame_size = GUIEngine::getDriver()->getCurrentRenderTargetSize();
const int w = (int)(frame_size.Width*percentWidth);
const int h = (int)(frame_size.Height*percentHeight);
const int w = (int)(frame_size.Width* m_percent_width);
const int h = (int)(frame_size.Height* m_percent_height);
assert(frame_size.Width > 0);
assert(frame_size.Height > 0);

View File

@ -55,11 +55,12 @@ namespace GUIEngine
class ModalDialog : public SkinWidgetContainer, public AbstractTopLevelContainer
{
private:
/** Because C++ doesn't support constructor delegation... */
void doInit(const float percentWidth, const float percentHeight);
ModalDialogLocation m_dialog_location;
float m_percent_width, m_percent_height;
bool m_init;
protected:
irr::gui::IGUIWindow* m_irrlicht_window;
@ -85,10 +86,15 @@ namespace GUIEngine
* that takes a XML file as argument is used)
*/
virtual void loadedFromFile() {}
void doInit();
public:
LEAK_CHECK()
/** Because C++ doesn't support constructor delegation... */
bool isInited() {return m_init;}
virtual ~ModalDialog();
/** Returns whether to block event propagation (usually, you will want to block events you processed) */
@ -115,6 +121,7 @@ namespace GUIEngine
* init(), which is invoked afer widgets were added)
*/
virtual void beforeAddingWidgets() {}
virtual void load() {}
/** \brief Optional callback invoked after widgets have been add()ed */
virtual void init() {}

View File

@ -960,9 +960,9 @@ bool Kart::isNearGround() const
*/
void Kart::setShieldTime(float t)
{
if(this->isShielded())
if(isShielded())
{
this->getAttachment()->setTimeLeft(t);
getAttachment()->setTimeLeft(t);
}
}
// ------------------------------------------------------------------------
@ -975,7 +975,8 @@ bool Kart::isShielded() const
return getAttachment()->getType() == Attachment::ATTACH_BUBBLEGUM_SHIELD;
else
return false;
}
} // isShielded
// ------------------------------------------------------------------------
/**
*Returns the remaining time the kart is protected by a shield.
@ -986,7 +987,8 @@ float Kart::getShieldTime() const
return getAttachment()->getTimeLeft();
else
return 0.0f;
}
} // getShieldTime
// ------------------------------------------------------------------------
/**
* Decreases the kart's shield time.
@ -994,7 +996,7 @@ float Kart::getShieldTime() const
*/
void Kart::decreaseShieldTime(float t)
{
if(this->isShielded())
if(isShielded())
{
getAttachment()->setTimeLeft( getAttachment()->getTimeLeft() - t );
if(t == 0.0f)
@ -1007,13 +1009,10 @@ void Kart::decreaseShieldTime(float t)
//Let the kart drop a bubble gum, if the shield was not damaged.
//This is the default, whenever a powerup is used by a kart.
//It is turned off, if the shield was reduced below zero by a hit. (Or by intently damaging the shield.)
if(!this->isShielded())
if(!isShielded())
m_bubble_drop = false;
}
} // decreaseShieldTime
//-----------------------------------------------------------------------------
/** Shows the star effect for a certain time.

View File

@ -31,6 +31,7 @@
#include "modes/world.hpp"
#include "network/protocol_manager.hpp"
#include "network/network_world.hpp"
#include "online/http_manager.hpp"
#include "race/race_manager.hpp"
#include "states_screens/state_manager.hpp"
#include "utils/profiler.hpp"
@ -153,6 +154,10 @@ void MainLoop::run()
ProtocolManager::getInstance()->update();
PROFILER_POP_CPU_MARKER();
PROFILER_PUSH_CPU_MARKER("Database polling update", 0x00, 0x7F, 0x7F);
Online::HTTPManager::get()->update(dt);
PROFILER_POP_CPU_MARKER();
PROFILER_SYNC_FRAME();
}
else if (!m_abort && ProfileWorld::isNoGraphics())
@ -160,6 +165,10 @@ void MainLoop::run()
PROFILER_PUSH_CPU_MARKER("Protocol manager update", 0x7F, 0x00, 0x7F);
ProtocolManager::getInstance()->update();
PROFILER_POP_CPU_MARKER();
PROFILER_PUSH_CPU_MARKER("Database polling update", 0x00, 0x7F, 0x7F);
Online::HTTPManager::get()->update(dt);
PROFILER_POP_CPU_MARKER();
}
PROFILER_SYNC_FRAME();

View File

@ -21,6 +21,7 @@
#include <IMeshSceneNode.h>
#include "audio/music_manager.hpp"
#include "audio/sfx_base.hpp"
#include "io/file_manager.hpp"
#include "karts/abstract_kart.hpp"
#include "karts/kart.hpp"
@ -60,6 +61,8 @@ void SoccerWorld::init()
}
m_goal_target = race_manager->getMaxGoal();
printf("Max Goal: %d\n", m_goal_target);
m_goal_sound = sfx_manager->createSoundSource("goal_scored");
} // init
//-----------------------------------------------------------------------------
@ -101,12 +104,16 @@ void SoccerWorld::onCheckGoalTriggered(bool first_goal)
{
//I18N: soccer mode
m_race_gui->addMessage(_("GOAL!"), NULL,
/* time */ 3.0f,
/* time */ 3.0f,
video::SColor(255,255,255,255),
/*important*/ true,
/*big font*/ true);
m_team_goals[first_goal]++;
m_team_goals[first_goal ? 0 : 1]++;
//printf("Score:\nTeam One %d : %d Team Two\n", m_team_goals[0], m_team_goals[1]);
World *world = World::getWorld();
world->setPhase(WorldStatus::GOAL_PHASE);
world->setClockMode(World::CLOCK_COUNTDOWN, 1.0);
m_goal_sound->play();
}
//m_check_goals_enabled = false; // TODO: remove?
@ -122,8 +129,8 @@ void SoccerWorld::onCheckGoalTriggered(bool first_goal)
if(!obj->isSoccerBall())
continue;
obj->reset();
obj->getPhysics()->reset();
obj->reset();
obj->getPhysics()->reset();
}
//Resetting the ball triggers the goal check line one more time.
@ -140,7 +147,6 @@ void SoccerWorld::onCheckGoalTriggered(bool first_goal)
}*/
// TODO: rescue the karts
// TODO: score a point
} // onCheckGoalTriggered
//-----------------------------------------------------------------------------
@ -153,11 +159,11 @@ bool SoccerWorld::isRaceOver()
{
return false;
}
// One team scored the target goals ...
// One team scored the target goals ...
else if(getScore(0) >= m_goal_target ||
getScore(1) >= m_goal_target )
{
return true;
return true;
}
// TODO
return getCurrentNumKarts()==1 || getCurrentNumPlayers()==0;
@ -178,7 +184,7 @@ void SoccerWorld::terminateRace()
/** Returns the data to display in the race gui.
*/
void SoccerWorld::getKartsDisplayInfo(
std::vector<RaceGUIBase::KartIconDisplayInfo> *info)
std::vector<RaceGUIBase::KartIconDisplayInfo> *info)
{
// TODO!!
/*
@ -248,7 +254,7 @@ void SoccerWorld::moveKartAfterRescue(AbstractKart* kart)
if(kart_x!=currentKart_x && kart_z !=currentKartk_z)
{
float absDistance = fabs(currentKart_x - v.getX()) +
fabs(currentKartk_z - v.getZ());
fabs(currentKartk_z - v.getZ());
if(absDistance < CLEAR_SPAWN_RANGE)
{
spawnPointClear = false;
@ -316,9 +322,9 @@ void SoccerWorld::initKartList()
SoccerTeam round_robin_team = SOCCER_TEAM_RED;
for(unsigned int n=0; n<kart_amount; n++)
{
if(race_manager->getLocalKartInfo(n).getSoccerTeam() == SOCCER_TEAM_NONE)
race_manager->setLocalKartSoccerTeam(
race_manager->getLocalKartInfo(n).getLocalPlayerId(),round_robin_team);
if(race_manager->getLocalKartInfo(n).getSoccerTeam() == SOCCER_TEAM_NONE)
race_manager->setLocalKartSoccerTeam(
race_manager->getLocalKartInfo(n).getLocalPlayerId(),round_robin_team);
team_karts_amount[race_manager->getLocalKartInfo(n).getSoccerTeam()]++;
@ -329,19 +335,19 @@ void SoccerWorld::initKartList()
//Loading the indicator textures
irr::video::ITexture *redTeamTexture = irr_driver->getTexture(
file_manager->getTextureFile("soccer_player_red.png"));
file_manager->getTextureFile("soccer_player_red.png"));
irr::video::ITexture *blueTeamTexture = irr_driver->getTexture(
file_manager->getTextureFile("soccer_player_blue.png"));
file_manager->getTextureFile("soccer_player_blue.png"));
//Assigning indicators
for(unsigned int i=0; i<kart_amount; i++)
{
scene::ISceneNode *hatNode;
if(race_manager->getLocalKartInfo(i).getSoccerTeam() == SOCCER_TEAM_RED)
hatNode = irr_driver->addBillboard(core::dimension2d<irr::f32>(0.3f,0.3f)
,redTeamTexture,m_karts[i]->getNode(), true);
hatNode = irr_driver->addBillboard(core::dimension2d<irr::f32>(0.3f,0.3f),
redTeamTexture,m_karts[i]->getNode(), true);
else
hatNode = irr_driver->addBillboard(core::dimension2d<irr::f32>(0.3f,0.3f)
,blueTeamTexture,m_karts[i]->getNode(),true);
hatNode = irr_driver->addBillboard(core::dimension2d<irr::f32>(0.3f,0.3f),
blueTeamTexture,m_karts[i]->getNode(),true);
hatNode->setPosition(m_karts[i]->getKartModel()->getHatOffset());
}
@ -364,61 +370,67 @@ void SoccerWorld::initKartList()
//-----------------------------------------------------------------------------
int SoccerWorld::getScore(unsigned int i)
{
return m_team_goals[i];
return m_team_goals[i];
}
//-----------------------------------------------------------------------------
int SoccerWorld::getTeamLeader(unsigned int team)
{
for(unsigned int i = 0; i< m_karts.size(); i++)
{
if(race_manager->getLocalKartInfo(i).getSoccerTeam() == (SoccerTeam) team)
return i;
}
return -1;
}
for(unsigned int i = 0; i< m_karts.size(); i++){
if(race_manager->getLocalKartInfo(i).getSoccerTeam() == (SoccerTeam) team)
return i;
}
return -1;
}
//-----------------------------------------------------------------------------
AbstractKart *SoccerWorld::createKart(const std::string &kart_ident, int index,
int local_player_id, int global_player_id,
RaceManager::KartType kart_type)
int local_player_id, int global_player_id,
RaceManager::KartType kart_type)
{
int posIndex = index;
if(race_manager->getLocalKartInfo(index).getSoccerTeam() == SOCCER_TEAM_RED)
{
if(index % 2 != 0) posIndex += 1;
}
else if(race_manager->getLocalKartInfo(index).getSoccerTeam() == SOCCER_TEAM_BLUE)
{
if(index % 2 != 1) posIndex += 1;
}
int position = index+1;
btTransform init_pos = m_track->getStartTransform(posIndex);
AbstractKart *new_kart = new Kart(kart_ident, index, position, init_pos);
new_kart->init(race_manager->getKartType(index));
Controller *controller = NULL;
switch(kart_type)
{
case RaceManager::KT_PLAYER:
controller = new PlayerController(new_kart,
StateManager::get()->getActivePlayer(local_player_id),
local_player_id);
m_num_players ++;
break;
case RaceManager::KT_NETWORK_PLAYER:
break; // Avoid compiler warning about enum not handled.
//controller = new NetworkController(kart_ident, position, init_pos,
// global_player_id);
//m_num_players++;
//break;
case RaceManager::KT_AI:
controller = loadAIController(new_kart);
break;
case RaceManager::KT_GHOST:
break;
case RaceManager::KT_LEADER:
break;
}
int posIndex = index;
if(race_manager->getLocalKartInfo(index).getSoccerTeam() == SOCCER_TEAM_RED)
{
if(index % 2 != 0) posIndex += 1;
}
else if(race_manager->getLocalKartInfo(index).getSoccerTeam() == SOCCER_TEAM_BLUE)
{
if(index % 2 != 1) posIndex += 1;
}
int position = index+1;
btTransform init_pos = m_track->getStartTransform(posIndex);
AbstractKart *new_kart = new Kart(kart_ident, index, position, init_pos);
new_kart->init(race_manager->getKartType(index));
Controller *controller = NULL;
switch(kart_type)
{
case RaceManager::KT_PLAYER:
controller = new PlayerController(new_kart,
StateManager::get()->getActivePlayer(local_player_id),
local_player_id);
m_num_players ++;
break;
case RaceManager::KT_NETWORK_PLAYER:
break; // Avoid compiler warning about enum not handled.
//controller = new NetworkController(kart_ident, position, init_pos,
// global_player_id);
//m_num_players++;
//break;
case RaceManager::KT_AI:
controller = loadAIController(new_kart);
break;
case RaceManager::KT_GHOST:
break;
case RaceManager::KT_LEADER:
break;
}
new_kart->setController(controller);
new_kart->setController(controller);
return new_kart;
return new_kart;
} // createKart
//-----------------------------------------------------------------------------
void SoccerWorld::countdownReachedZero()
{
World *world = World::getWorld();
world->setPhase(World::RACE_PHASE);
} // countdownReachedZero

View File

@ -50,6 +50,7 @@ private:
/** Whether or not goals can be scored (they are disabled when a point is scored
and re-enabled when the next game can be played)*/
bool m_can_score_points;
SFXBase *m_goal_sound;
/** Team karts */
@ -79,6 +80,8 @@ public:
virtual void update(float dt);
virtual void countdownReachedZero();
void onCheckGoalTriggered(bool first_goal);
int getTeamLeader(unsigned int i);

View File

@ -233,6 +233,9 @@ void WorldStatus::update(const float dt)
case FINISH_PHASE:
// Nothing to do here.
break;
case GOAL_PHASE:
// Nothing to do here as well.
default: break;
}

View File

@ -77,7 +77,10 @@ public:
IN_GAME_MENU_PHASE,
// Undefined, used in asserts to catch incorrect states.
UNDEFINED_PHASE
UNDEFINED_PHASE,
//Goal scored phase
GOAL_PHASE
};
protected:
/** Sound to play at the beginning of a race, during which a

View File

@ -47,7 +47,7 @@ void GameSetup::addPlayer(NetworkPlayerProfile* profile)
{
m_players.push_back(profile);
Log::info("GameSetup", "New player in the game setup. Global id : %u, "
"Race id : %d.", profile->user_profile->getUserID(), profile->race_id);
"Race id : %d.", profile->user_profile->getID(), profile->race_id);
}
//-----------------------------------------------------------------------------
@ -56,7 +56,7 @@ bool GameSetup::removePlayer(uint32_t id)
{
for (unsigned int i = 0; i < m_players.size(); i++)
{
if (m_players[i]->user_profile->getUserID() == id)
if (m_players[i]->user_profile->getID() == id)
{
delete m_players[i];
m_players.erase(m_players.begin()+i, m_players.begin()+i+1);
@ -150,7 +150,7 @@ const NetworkPlayerProfile* GameSetup::getProfile(uint32_t id)
{
for (unsigned int i = 0; i < m_players.size(); i++)
{
if (m_players[i]->user_profile->getUserID() == id)
if (m_players[i]->user_profile->getID() == id)
{
return m_players[i];
}

View File

@ -22,7 +22,7 @@
#ifndef GAME_SETUP_HPP
#define GAME_SETUP_HPP
#include "online/user.hpp"
#include "online/profile.hpp"
#include <vector>
#include <string>
@ -38,7 +38,7 @@ class NetworkPlayerProfile
uint8_t race_id; //!< The id of the player for the race
std::string kart_name; //!< The selected kart.
Online::User* user_profile; //!< Pointer to the lobby profile
Online::Profile* user_profile; //!< Pointer to the lobby profile
uint8_t world_kart_id; //!< the kart id in the World class (pointer to AbstractKart)
};

View File

@ -34,7 +34,7 @@ void* protocolManagerUpdate(void* data)
while(!manager->exit())
{
manager->update();
irr_driver->getDevice()->sleep(20);
usleep(2000);
}
return NULL;
}
@ -44,7 +44,7 @@ void* protocolManagerAsynchronousUpdate(void* data)
while(!manager->exit())
{
manager->asynchronousUpdate();
irr_driver->getDevice()->sleep(20);
usleep(2000);
}
return NULL;
}

View File

@ -160,7 +160,7 @@ void ClientLobbyRoomProtocol::update()
{
NetworkString ns;
// 1 (connection request), 4 (size of id), global id
ns.ai8(1).ai8(4).ai32(Online::CurrentUser::get()->getUserID());
ns.ai8(1).ai8(4).ai32(Online::CurrentUser::get()->getID());
m_listener->sendMessage(this, ns);
m_state = REQUESTING_CONNECTION;
}
@ -222,7 +222,7 @@ void ClientLobbyRoomProtocol::newPlayer(Event* event)
uint32_t global_id = data.gui32(1);
uint8_t race_id = data.gui8(6);
if (global_id == Online::CurrentUser::get()->getUserID())
if (global_id == Online::CurrentUser::get()->getID())
{
Log::error("ClientLobbyRoomProtocol", "The server notified me that i'm a new player in the room (not normal).");
}
@ -232,7 +232,7 @@ void ClientLobbyRoomProtocol::newPlayer(Event* event)
NetworkPlayerProfile* profile = new NetworkPlayerProfile();
profile->kart_name = "";
profile->race_id = race_id;
profile->user_profile = new Online::User(global_id);
profile->user_profile = new Online::Profile(global_id, "");
m_setup->addPlayer(profile);
}
else
@ -295,7 +295,7 @@ void ClientLobbyRoomProtocol::connectionAccepted(Event* event)
STKPeer* peer = *(event->peer);
uint32_t global_id = data.gui32(8);
if (global_id == Online::CurrentUser::get()->getUserID())
if (global_id == Online::CurrentUser::get()->getID())
{
Log::info("ClientLobbyRoomProtocol", "The server accepted the connection.");
@ -303,7 +303,7 @@ void ClientLobbyRoomProtocol::connectionAccepted(Event* event)
NetworkPlayerProfile* profile = new NetworkPlayerProfile();
profile->kart_name = "";
profile->race_id = data.gui8(1);
profile->user_profile = Online::CurrentUser::get();
profile->user_profile = Online::CurrentUser::get()->getProfile();
m_setup->addPlayer(profile);
// connection token
uint32_t token = data.gui32(3);
@ -320,9 +320,11 @@ void ClientLobbyRoomProtocol::connectionAccepted(Event* event)
{
if (data[0] != 1 || data[2] != 4)
Log::error("ClientLobbyRoomProtocol", "Bad format in players list.");
uint8_t race_id = data[1];
uint32_t global_id = data.gui32(3);
Online::User* new_user = new Online::User(global_id);
Online::Profile* new_user = new Online::Profile(global_id, "");
NetworkPlayerProfile* profile2 = new NetworkPlayerProfile();
profile2->race_id = race_id;
profile2->user_profile = new_user;

View File

@ -46,7 +46,7 @@ void GetPeerAddress::asynchronousUpdate()
{
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getUserID());
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("peer_id",m_peer_id);
m_request->setParameter("action","get");

View File

@ -43,7 +43,7 @@ void HidePublicAddress::asynchronousUpdate()
{
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getUserID());
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("action","unset");

View File

@ -45,7 +45,7 @@ void QuickJoinProtocol::asynchronousUpdate()
TransportAddress addr = NetworkManager::getInstance()->getPublicAddress();
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getUserID());
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("action","quick-join");

View File

@ -45,7 +45,7 @@ void RequestConnection::asynchronousUpdate()
{
m_request = new Online::CurrentUser::ServerJoinRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getUserID());
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("server_id",m_server_id);
m_request->setParameter("action","request-connection");

View File

@ -170,7 +170,7 @@ void ServerLobbyRoomProtocol::checkIncomingConnectionRequests()
TransportAddress addr = NetworkManager::getInstance()->getPublicAddress();
Online::XMLRequest* request = new Online::XMLRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
request->setParameter("id",Online::CurrentUser::get()->getUserID());
request->setParameter("id",Online::CurrentUser::get()->getProfile()->getID());
request->setParameter("token",Online::CurrentUser::get()->getToken());
request->setParameter("address",addr.ip);
request->setParameter("port",addr.port);
@ -361,8 +361,8 @@ void ServerLobbyRoomProtocol::connectionRequested(Event* event)
for (unsigned int i = 0; i < players.size(); i++)
{
// do not duplicate the player into the message
if (players[i]->race_id != m_next_id && players[i]->user_profile->getUserID() != player_id)
message_ack.ai8(1).ai8(players[i]->race_id).ai8(4).ai32(players[i]->user_profile->getUserID());
if (players[i]->race_id != m_next_id && players[i]->user_profile->getID() != player_id)
message_ack.ai8(1).ai8(players[i]->race_id).ai8(4).ai32(players[i]->user_profile->getID());
}
m_listener->sendMessage(this, peer, message_ack);
@ -371,7 +371,7 @@ void ServerLobbyRoomProtocol::connectionRequested(Event* event)
NetworkPlayerProfile* profile = new NetworkPlayerProfile();
profile->race_id = m_next_id;
profile->kart_name = "";
profile->user_profile = new Online::User(player_id);
profile->user_profile = new Online::Profile(player_id, "");
m_setup->addPlayer(profile);
peer->setPlayerProfile(profile);
Log::verbose("ServerLobbyRoomProtocol", "New player.");

View File

@ -44,7 +44,7 @@ void ShowPublicAddress::asynchronousUpdate()
TransportAddress addr = NetworkManager::getInstance()->getPublicAddress();
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getUserID());
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("address",addr.ip);
m_request->setParameter("port",addr.port);

View File

@ -103,7 +103,7 @@ void StartGameProtocol::update()
// have to add self first
for (unsigned int i = 0; i < players.size(); i++)
{
bool is_me = (players[i]->user_profile == Online::CurrentUser::get());
bool is_me = (players[i]->user_profile == Online::CurrentUser::get()->getProfile());
if (is_me)
{
NetworkPlayerProfile* profile = players[i];
@ -131,7 +131,7 @@ void StartGameProtocol::update()
}
for (unsigned int i = 0; i < players.size(); i++)
{
bool is_me = (players[i]->user_profile == Online::CurrentUser::get());
bool is_me = (players[i]->user_profile == Online::CurrentUser::get()->getProfile());
NetworkPlayerProfile* profile = players[i];
RemoteKartInfo rki(profile->race_id, profile->kart_name,
profile->user_profile->getUserName(), profile->race_id, !is_me);

View File

@ -43,7 +43,7 @@ void StartServer::asynchronousUpdate()
TransportAddress addr = NetworkManager::getInstance()->getPublicAddress();
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getUserID());
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("address",addr.ip);
m_request->setParameter("port",addr.port);

View File

@ -48,7 +48,7 @@ void StopServer::asynchronousUpdate()
TransportAddress addr = NetworkManager::getInstance()->getPublicAddress();
m_request = new Online::XMLRequest();
m_request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
m_request->setParameter("id",Online::CurrentUser::get()->getUserID());
m_request->setParameter("id",Online::CurrentUser::get()->getID());
m_request->setParameter("token",Online::CurrentUser::get()->getToken());
m_request->setParameter("address",addr.ip);
m_request->setParameter("port",addr.port);

View File

@ -22,9 +22,14 @@
#include "addons/addons_manager.hpp"
#include "config/user_config.hpp"
#include "online/servers_manager.hpp"
#include "online/profile_manager.hpp"
#include "utils/log.hpp"
#include "utils/translation.hpp"
#include "addons/addon.hpp"
#include "guiengine/dialog_queue.hpp"
#include "states_screens/dialogs/user_info_dialog.hpp"
#include "states_screens/dialogs/notification_dialog.hpp"
#include "states_screens/online_profile_friends.hpp"
#include <sstream>
#include <stdlib.h>
@ -50,18 +55,18 @@ namespace Online{
// ============================================================================
CurrentUser::CurrentUser()
: User("",0)
{
setUserState (US_SIGNED_OUT);
setToken("");
setSaveSession(false);
m_state = US_SIGNED_OUT;
m_token = "";
m_save_session = false;
m_profile = NULL;
}
// ============================================================================
const XMLRequest * CurrentUser::requestRecovery( const irr::core::stringw &username,
const irr::core::stringw &email)
{
assert(getUserState() == US_SIGNED_OUT || getUserState() == US_GUEST);
assert(m_state == US_SIGNED_OUT || m_state == US_GUEST);
XMLRequest * request = new XMLRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("recovery"));
@ -78,7 +83,7 @@ namespace Online{
const irr::core::stringw &email,
bool terms)
{
assert(getUserState() == US_SIGNED_OUT || getUserState() == US_GUEST);
assert(m_state == US_SIGNED_OUT || m_state == US_GUEST);
XMLRequest * request = new XMLRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("register"));
@ -92,28 +97,27 @@ namespace Online{
}
// ============================================================================
const CurrentUser::SignInRequest * CurrentUser::requestSavedSession()
void CurrentUser::requestSavedSession()
{
SignInRequest * request = NULL;
if(getUserState() != US_SIGNED_IN && UserConfigParams::m_saved_session)
if(m_state != US_SIGNED_IN && UserConfigParams::m_saved_session)
{
request = new SignInRequest();
request = new SignInRequest(true);
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action",std::string("saved-session"));
request->setParameter("userid", UserConfigParams::m_saved_user);
request->setParameter("token", UserConfigParams::m_saved_token.c_str());
HTTPManager::get()->addRequest(request);
setUserState (US_SIGNING_IN);
m_state = US_SIGNING_IN;
}
return request;
}
CurrentUser::SignInRequest * CurrentUser::requestSignIn( const irr::core::stringw &username,
const irr::core::stringw &password,
bool save_session, bool request_now)
{
assert(getUserState() == US_SIGNED_OUT);
setSaveSession(save_session);
assert(m_state == US_SIGNED_OUT);
m_save_session = save_session;
SignInRequest * request = new SignInRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action",std::string("connect"));
@ -122,7 +126,7 @@ namespace Online{
if (request_now)
{
HTTPManager::get()->addRequest(request);
setUserState (US_SIGNING_IN);
m_state = US_SIGNING_IN;
}
return request;
}
@ -136,21 +140,23 @@ namespace Online{
setToken(token);
irr::core::stringw username("");
int username_fetched = input->get("username", &username);
setUserName(username);
uint32_t userid(0);
int userid_fetched = input->get("userid", &userid);
setUserID(userid);
m_profile = new Profile(userid, username, true);
assert(token_fetched && username_fetched && userid_fetched);
setUserState (US_SIGNED_IN);
m_state = US_SIGNED_IN;
if(getSaveSession())
{
UserConfigParams::m_saved_user = getUserID();
UserConfigParams::m_saved_user = getID();
UserConfigParams::m_saved_token = getToken();
UserConfigParams::m_saved_session = true;
}
ProfileManager::get()->addPersistent(m_profile);
m_profile->fetchFriends();
HTTPManager::get()->startPolling();
}
else
setUserState (US_SIGNED_OUT);
m_state = US_SIGNED_OUT;
}
void CurrentUser::SignInRequest::callback()
@ -163,12 +169,12 @@ namespace Online{
const CurrentUser::ServerCreationRequest * CurrentUser::requestServerCreation( const irr::core::stringw &name,
int max_players)
{
assert(getUserState() == US_SIGNED_IN);
assert(m_state == US_SIGNED_IN);
ServerCreationRequest * request = new ServerCreationRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("create_server"));
request->setParameter("token", getToken());
request->setParameter("userid", getUserID());
request->setParameter("userid", getID());
request->setParameter("name", name);
request->setParameter("max_players", max_players);
HTTPManager::get()->addRequest(request);
@ -187,14 +193,15 @@ namespace Online{
// ============================================================================
const CurrentUser::SignOutRequest * CurrentUser::requestSignOut(){
assert(getUserState() == US_SIGNED_IN || getUserState() == US_GUEST);
assert(m_state == US_SIGNED_IN || m_state == US_GUEST);
SignOutRequest * request = new SignOutRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action",std::string("disconnect"));
request->setParameter("token", getToken());
request->setParameter("userid", getUserID());
request->setParameter("userid", getID());
HTTPManager::get()->addRequest(request);
setUserState (US_SIGNING_OUT);
m_state = US_SIGNING_OUT;
HTTPManager::get()->stopPolling();
return request;
}
@ -205,9 +212,9 @@ namespace Online{
Log::warn("CurrentUser::signOut", "%s", _("There were some connection issues while signing out. Report a bug if this caused issues."));
}
setToken("");
setUserName("");
setUserID(0);
setUserState (US_SIGNED_OUT);
ProfileManager::get()->clearPersistent();
m_profile = NULL;
m_state = US_SIGNED_OUT;
UserConfigParams::m_saved_user = 0;
UserConfigParams::m_saved_token = "";
UserConfigParams::m_saved_session = false;
@ -223,12 +230,12 @@ namespace Online{
CurrentUser::ServerJoinRequest * CurrentUser::requestServerJoin(uint32_t server_id,
bool request_now)
{
assert(getUserState() == US_SIGNED_IN || getUserState() == US_GUEST);
assert(m_state == US_SIGNED_IN || m_state == US_GUEST);
ServerJoinRequest * request = new ServerJoinRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "address-management.php");
request->setParameter("action",std::string("request-connection"));
request->setParameter("token", getToken());
request->setParameter("id", getUserID());
request->setParameter("id", getID());
request->setParameter("server_id", server_id);
if (request_now)
HTTPManager::get()->addRequest(request);
@ -237,7 +244,7 @@ namespace Online{
void CurrentUser::ServerJoinRequest::callback()
{
if(isSuccess())
if(m_success)
{
uint32_t server_id;
m_result->get("serverid", &server_id);
@ -250,12 +257,12 @@ namespace Online{
const XMLRequest * CurrentUser::requestGetAddonVote( const std::string & addon_id) const
{
assert(isRegisteredUser());
assert(m_state == US_SIGNED_IN);
XMLRequest * request = new XMLRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("get-addon-vote"));
request->setParameter("token", getToken());
request->setParameter("userid", getUserID());
request->setParameter("userid", getID());
request->setParameter("addonid", addon_id.substr(6));
HTTPManager::get()->addRequest(request);
return request;
@ -265,12 +272,12 @@ namespace Online{
const XMLRequest * CurrentUser::requestUserSearch( const irr::core::stringw & search_string) const
{
assert(isRegisteredUser());
assert(m_state == US_SIGNED_IN);
XMLRequest * request = new XMLRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("user-search"));
request->setParameter("token", getToken());
request->setParameter("userid", getUserID());
request->setParameter("userid", getID());
request->setParameter("search-string", search_string);
HTTPManager::get()->addRequest(request);
return request;
@ -278,21 +285,21 @@ namespace Online{
// ============================================================================
const CurrentUser::setAddonVoteRequest * CurrentUser::requestSetAddonVote( const std::string & addon_id, float rating) const
const CurrentUser::SetAddonVoteRequest * CurrentUser::requestSetAddonVote( const std::string & addon_id, float rating) const
{
assert(isRegisteredUser());
CurrentUser::setAddonVoteRequest * request = new CurrentUser::setAddonVoteRequest();
assert(m_state == US_SIGNED_IN);
CurrentUser::SetAddonVoteRequest * request = new CurrentUser::SetAddonVoteRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("set-addon-vote"));
request->setParameter("token", getToken());
request->setParameter("userid", getUserID());
request->setParameter("userid", getID());
request->setParameter("addonid", addon_id.substr(6));
request->setParameter("rating", rating);
HTTPManager::get()->addRequest(request);
return request;
}
void CurrentUser::setAddonVoteRequest::callback()
void CurrentUser::SetAddonVoteRequest::callback()
{
if(m_success)
{
@ -306,11 +313,310 @@ namespace Online{
// ============================================================================
const irr::core::stringw CurrentUser::getUserName() const
void CurrentUser::requestFriendRequest(const uint32_t friend_id) const
{
if((getUserState() == US_SIGNED_IN ) || (getUserState() == US_GUEST))
return User::getUserName();
assert(m_state == US_SIGNED_IN);
CurrentUser::FriendRequest * request = new CurrentUser::FriendRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("friend-request"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("friendid", friend_id);
HTTPManager::get()->addRequest(request);
}
void CurrentUser::FriendRequest::callback()
{
uint32_t id(0);
m_result->get("friendid", &id);
irr::core::stringw info_text("");
if(m_success)
{
CurrentUser::get()->getProfile()->addFriend(id);
ProfileManager::get()->getProfileByID(id)->setRelationInfo(new Profile::RelationInfo(_("Today"), false, true, false));
OnlineProfileFriends::getInstance()->refreshFriendsList();
info_text = _("Friend request send!");
}
else
return _("Currently not signed in");
info_text = m_info;
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!m_success, true), true);
}
// ============================================================================
void CurrentUser::requestAcceptFriend(const uint32_t friend_id) const
{
assert(m_state == US_SIGNED_IN);
CurrentUser::AcceptFriendRequest * request = new CurrentUser::AcceptFriendRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("accept-friend-request"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("friendid", friend_id);
HTTPManager::get()->addRequest(request);
}
void CurrentUser::AcceptFriendRequest::callback()
{
uint32_t id(0);
m_result->get("friendid", &id);
irr::core::stringw info_text("");
if(m_success)
{
Profile * profile = ProfileManager::get()->getProfileByID(id);
profile->setFriend();
profile->setRelationInfo(new Profile::RelationInfo(_("Today"), false, false, true));
OnlineProfileFriends::getInstance()->refreshFriendsList();
info_text = _("Friend request accepted!");
}
else
info_text = m_info;
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!m_success, true), true);
}
// ============================================================================
void CurrentUser::requestDeclineFriend(const uint32_t friend_id) const
{
assert(m_state == US_SIGNED_IN);
CurrentUser::DeclineFriendRequest * request = new CurrentUser::DeclineFriendRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("decline-friend-request"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("friendid", friend_id);
HTTPManager::get()->addRequest(request);
}
void CurrentUser::DeclineFriendRequest::callback()
{
uint32_t id(0);
m_result->get("friendid", &id);
irr::core::stringw info_text("");
if(m_success)
{
CurrentUser::get()->getProfile()->removeFriend(id);
ProfileManager::get()->moveToCache(id);
ProfileManager::get()->getProfileByID(id)->deleteRelationalInfo();
OnlineProfileFriends::getInstance()->refreshFriendsList();
info_text = _("Friend request declined!");
}
else
info_text = m_info;
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!m_success, true), true);
}
// ============================================================================
void CurrentUser::requestCancelFriend(const uint32_t friend_id) const
{
assert(m_state == US_SIGNED_IN);
CurrentUser::CancelFriendRequest * request = new CurrentUser::CancelFriendRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("cancel-friend-request"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("friendid", friend_id);
HTTPManager::get()->addRequest(request);
}
void CurrentUser::CancelFriendRequest::callback()
{
uint32_t id(0);
m_result->get("friendid", &id);
irr::core::stringw info_text("");
if(m_success)
{
CurrentUser::get()->getProfile()->removeFriend(id);
ProfileManager::get()->moveToCache(id);
ProfileManager::get()->getProfileByID(id)->deleteRelationalInfo();
OnlineProfileFriends::getInstance()->refreshFriendsList();
info_text = _("Friend request cancelled!");
}
else
info_text = m_info;
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!m_success, true), true);
}
// ============================================================================
void CurrentUser::requestRemoveFriend(const uint32_t friend_id) const
{
assert(m_state == US_SIGNED_IN);
CurrentUser::RemoveFriendRequest * request = new CurrentUser::RemoveFriendRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("remove-friend"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
request->setParameter("friendid", friend_id);
HTTPManager::get()->addRequest(request);
}
void CurrentUser::RemoveFriendRequest::callback()
{
uint32_t id(0);
m_result->get("friendid", &id);
irr::core::stringw info_text("");
if(m_success)
{
CurrentUser::get()->getProfile()->removeFriend(id);
ProfileManager::get()->moveToCache(id);
ProfileManager::get()->getProfileByID(id)->deleteRelationalInfo();
OnlineProfileFriends::getInstance()->refreshFriendsList();
info_text = _("Friend removed!");
}
else
info_text = m_info;
GUIEngine::DialogQueue::get()->pushDialog( new UserInfoDialog(id, info_text,!m_success, true), true);
}
// ============================================================================
void CurrentUser::requestPoll()
{
assert(m_state == US_SIGNED_IN);
CurrentUser::PollRequest * request = new CurrentUser::PollRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action", std::string("poll"));
request->setParameter("token", getToken());
request->setParameter("userid", getID());
HTTPManager::get()->addRequest(request);
}
void CurrentUser::PollRequest::callback()
{
if(m_success)
{
std::string online_friends_string("");
if(m_result->get("online", &online_friends_string) == 1)
{
std::vector<std::string> parts = StringUtils::split(online_friends_string, ' ');
std::vector<uint32_t> online_friends;
for(unsigned int i = 0; i < parts.size(); ++i)
{
online_friends.push_back(atoi(parts[i].c_str()));
}
bool went_offline = false;
std::vector<uint32_t> friends = CurrentUser::get()->getProfile()->getFriends();
std::vector<irr::core::stringw> to_notify;
for(unsigned int i = 0; i < friends.size(); ++i)
{
bool now_online = false;
std::vector<uint32_t>::iterator iter;
for (iter = online_friends.begin(); iter != online_friends.end();)
{
if (*iter == friends[i])
{
now_online = true;
online_friends.erase(iter++);
break;
}
else
++iter;
}
Profile * profile = ProfileManager::get()->getProfileByID(friends[i]);
Profile::RelationInfo * relation_info = profile->getRelationInfo();
if( relation_info->isOnline() )
{
if (!now_online)
{
relation_info->setOnline(false);
went_offline = true;
}
}
else
{
if (now_online)
{
relation_info->setOnline(true);
profile->setFriend();
to_notify.push_back(profile->getUserName());
}
}
}
if(to_notify.size() > 0)
{
irr::core::stringw message("");
if(to_notify.size() == 1)
{
message = to_notify[0] + irr::core::stringw(_(" is now online."));
}
else if(to_notify.size() == 2)
{
message = to_notify[0] + irr::core::stringw(_(" and ")) + to_notify[1] + irr::core::stringw(_(" are now online."));
}
else if(to_notify.size() == 3)
{
message = to_notify[0] + irr::core::stringw(_(", ")) + to_notify[1] + irr::core::stringw(_(" and ")) + to_notify[2] + irr::core::stringw(_(" are now online."));
}
else if(to_notify.size() > 3)
{
message = StringUtils::toWString(to_notify.size()) + irr::core::stringw(_(" friends are now online."));
}
GUIEngine::DialogQueue::get()->pushDialog( new NotificationDialog(NotificationDialog::T_Friends, message), false);
OnlineProfileFriends::getInstance()->refreshFriendsList();
}
else if(went_offline)
{
OnlineProfileFriends::getInstance()->refreshFriendsList();
}
}
int friend_request_count = 0;
for(unsigned int i = 0; i < m_result->getNumNodes(); i++)
{
const XMLNode * node = m_result->getNode(i);
if(node->getName() == "new_friend_request")
{
Profile::RelationInfo * ri = new Profile::RelationInfo("New", false, true, true);
Profile * p = new Profile(node);
p->setRelationInfo(ri);
ProfileManager::get()->addPersistent(p);
friend_request_count++;
}
}
if(friend_request_count > 0)
{
irr::core::stringw message("");
if(friend_request_count > 1)
{
message = irr::core::stringw(_("You have ")) + StringUtils::toWString(friend_request_count) + irr::core::stringw(_(" new friend requests!."));
}
else
{
message = _("You have a new friend request!");
}
GUIEngine::DialogQueue::get()->pushDialog( new NotificationDialog(NotificationDialog::T_Friends, message), false);
OnlineProfileFriends::getInstance()->refreshFriendsList();
}
}
// FIXME show connection error??
// after 2 misses I'll show something
}
// ============================================================================
irr::core::stringw CurrentUser::getUserName() const
{
if((m_state == US_SIGNED_IN ) || (m_state == US_GUEST))
{
assert(m_profile != NULL);
return m_profile->getUserName();
}
return _("Currently not signed in");
}
// ============================================================================
uint32_t CurrentUser::getID() const
{
if((m_state == US_SIGNED_IN ))
{
assert(m_profile != NULL);
return m_profile->getID();
}
return 0;
}
} // namespace Online

View File

@ -19,9 +19,8 @@
#ifndef HEADER_CURRENT_ONLINE_USER_HPP
#define HEADER_CURRENT_ONLINE_USER_HPP
#include "http_manager.hpp"
#include "online/http_manager.hpp"
#include "online/server.hpp"
#include "online/user.hpp"
#include "online/profile.hpp"
#include "utils/types.hpp"
#include "utils/synchronised.hpp"
@ -39,7 +38,7 @@ namespace Online{
* \brief Class that represents an online registered user
* \ingroup online
*/
class CurrentUser : public User
class CurrentUser
{
public:
enum UserState
@ -51,60 +50,88 @@ namespace Online{
US_SIGNING_OUT
};
enum RequestType
{
RT_SIGN_IN = 1,
RT_SIGN_OUT,
RT_SIGN_UP,
RT_SERVER_JOIN,
RT_SERVER_CREATION
};
class SignInRequest : public XMLRequest
{
virtual void callback ();
public:
SignInRequest() : XMLRequest(RT_SIGN_IN) {}
SignInRequest(bool manage_memory = false) : XMLRequest(manage_memory) {}
};
class SignOutRequest : public XMLRequest
{
virtual void callback ();
public:
SignOutRequest() : XMLRequest(RT_SIGN_OUT) {}
SignOutRequest() : XMLRequest() {}
};
class ServerCreationRequest : public XMLRequest {
virtual void callback ();
uint32_t m_created_server_id;
public:
ServerCreationRequest() : XMLRequest(RT_SERVER_CREATION) {}
ServerCreationRequest() : XMLRequest() {}
const uint32_t getCreatedServerID() const { assert(isDone()); return m_created_server_id;}
};
class ServerJoinRequest : public XMLRequest {
virtual void callback ();
public:
ServerJoinRequest() : XMLRequest(RT_SERVER_JOIN) {}
ServerJoinRequest() : XMLRequest() {}
};
class setAddonVoteRequest : public XMLRequest {
class SetAddonVoteRequest : public XMLRequest {
virtual void callback ();
public:
setAddonVoteRequest() : XMLRequest() {}
SetAddonVoteRequest() : XMLRequest() {}
};
class FriendRequest : public XMLRequest {
virtual void callback ();
public:
FriendRequest() : XMLRequest(true) {}
};
class AcceptFriendRequest : public XMLRequest {
virtual void callback ();
public:
AcceptFriendRequest() : XMLRequest(true) {}
};
class DeclineFriendRequest : public XMLRequest {
virtual void callback ();
public:
DeclineFriendRequest() : XMLRequest(true) {}
};
class RemoveFriendRequest : public XMLRequest {
virtual void callback ();
public:
RemoveFriendRequest() : XMLRequest(true) {}
};
class CancelFriendRequest : public XMLRequest {
virtual void callback ();
public:
CancelFriendRequest() : XMLRequest(true) {}
};
class PollRequest : public XMLRequest {
virtual void callback ();
public:
PollRequest() : XMLRequest(true) {}
};
private:
Synchronised<std::string> m_token;
Synchronised<bool> m_save_session;
Synchronised<UserState> m_state;
std::string m_token;
bool m_save_session;
UserState m_state;
Profile * m_profile;
bool getSaveSession() const { return m_save_session.getAtomic(); }
bool getSaveSession() const { return m_save_session; }
void setUserState (UserState user_state) { m_state.setAtomic(user_state); }
void setSaveSession (bool save_session) { m_save_session.setAtomic(save_session); }
void setToken (const std::string & token) { m_token.setAtomic(token); }
void setUserState (UserState user_state) { m_state = user_state; }
void setSaveSession (bool save_session) { m_save_session = save_session; }
void setToken (const std::string & token) { m_token= token; }
CurrentUser();
@ -116,7 +143,7 @@ namespace Online{
static CurrentUser * get();
static void deallocate();
const SignInRequest * requestSavedSession();
void requestSavedSession();
SignInRequest * requestSignIn( const irr::core::stringw &username,
const irr::core::stringw &password,
bool save_session,
@ -127,7 +154,7 @@ namespace Online{
/** Register */
const XMLRequest * requestSignUp( const irr::core::stringw &username,
const XMLRequest * requestSignUp( const irr::core::stringw &username,
const irr::core::stringw &password,
const irr::core::stringw &password_ver,
const irr::core::stringw &email,
@ -137,18 +164,26 @@ namespace Online{
const irr::core::stringw &email);
const XMLRequest * requestGetAddonVote(const std::string & addon_id) const;
const setAddonVoteRequest * requestSetAddonVote(const std::string & addon_id, float rating) const;
const SetAddonVoteRequest * requestSetAddonVote(const std::string & addon_id, float rating) const;
void requestFriendRequest(const uint32_t friend_id) const;
void requestAcceptFriend(const uint32_t friend_id) const;
void requestDeclineFriend(const uint32_t friend_id) const;
void requestRemoveFriend(const uint32_t friend_id) const;
void requestCancelFriend(const uint32_t friend_id) const;
const XMLRequest * requestUserSearch(const irr::core::stringw & search_string) const;
/** Returns the username if signed in. */
const irr::core::stringw getUserName() const;
const UserState getUserState() const { return m_state.getAtomic(); }
bool isRegisteredUser() const {
MutexLocker(m_state);
return m_state.getData() == US_SIGNED_IN;
}
const std::string getToken() const { return m_token.getAtomic(); }
irr::core::stringw getUserName() const;
uint32_t getID() const;
const UserState getUserState() const { return m_state; }
bool isRegisteredUser() const { return m_state == US_SIGNED_IN; }
const std::string & getToken() const { return m_token; }
Profile * getProfile() const { return m_profile; }
void requestPoll();
}; // class CurrentUser

View File

@ -20,6 +20,9 @@
#include "online/http_manager.hpp"
#include "online/current_user.hpp"
#include "states_screens/state_manager.hpp"
#include <iostream>
#include <stdio.h>
#include <memory.h>
@ -41,7 +44,11 @@
# include <unistd.h>
#endif
using namespace Online;
namespace Online{
#define MENU_POLLING_INTERVAL 10.0f
#define GAME_POLLING_INTERVAL 15.0f
static HTTPManager * http_singleton = NULL;
@ -51,6 +58,7 @@ namespace Online{
{
http_singleton = new HTTPManager();
http_singleton->startNetworkThread();
CurrentUser::get()->requestSavedSession();
}
return http_singleton;
} // get
@ -71,6 +79,8 @@ namespace Online{
curl_global_init(CURL_GLOBAL_DEFAULT);
pthread_cond_init(&m_cond_request, NULL);
m_abort.setAtomic(false);
m_time_since_poll = MENU_POLLING_INTERVAL * (2.0/3.0);
m_polling = false;
}
// ============================================================================
@ -157,6 +167,7 @@ namespace Online{
m_request_queue.unlock();
} // addRequest
// ----------------------------------------------------------------------------
/** Immediately performs a request synchronously
* \param request The pointer to the new request to insert.
@ -166,6 +177,8 @@ namespace Online{
assert(request->isAllowedToAdd());
request->setBusy();
request->execute();
request->callback();
request->setDone();
} // synchronousRequest
// ---------------------------------------------------------------------------
@ -197,11 +210,7 @@ namespace Online{
me->m_request_queue.getData().pop();
me->m_request_queue.unlock();
me->m_current_request->execute();
if(me->m_current_request->manageMemory())
{
delete me->m_current_request;
me->m_current_request = NULL;
}
me->addResult(me->m_current_request);
me->m_request_queue.lock();
} // while
@ -219,6 +228,57 @@ namespace Online{
pthread_exit(NULL);
return 0;
} // mainLoop
void HTTPManager::addResult(Online::Request *request)
{
assert(request->isBusy());
m_result_queue.lock();
m_result_queue.getData().push(request);
m_result_queue.unlock();
}
void HTTPManager::handleResultQueue()
{
Request * request = NULL;
m_result_queue.lock();
if(!m_result_queue.getData().empty())
{
request = m_result_queue.getData().front();
m_result_queue.getData().pop();
}
m_result_queue.unlock();
if(request != NULL)
{
request->callback();
if(request->manageMemory())
{
delete request;
request = NULL;
}
else
request->setDone();
}
}
void HTTPManager::update(float dt){
handleResultQueue();
//Database polling starts here, only needed for registered users
if(!CurrentUser::get()->isRegisteredUser())
return;
m_time_since_poll += dt;
float interval = GAME_POLLING_INTERVAL;
if (StateManager::get()->getGameState() == GUIEngine::MENU)
interval = MENU_POLLING_INTERVAL;
if(m_time_since_poll > interval)
{
m_time_since_poll = 0;
CurrentUser::get()->requestPoll();
}
}
} // namespace Online

View File

@ -48,7 +48,8 @@ namespace Online{
{
protected:
/** Ment for networking threads */
float m_time_since_poll;
bool m_polling;
/** The current requested being worked on. */
Online::Request * m_current_request;
@ -70,6 +71,11 @@ namespace Online{
>
> m_request_queue;
Synchronised< std::queue<Online::Request*> > m_result_queue;
void addResult(Online::Request *request);
void handleResultQueue();
static void *mainLoop(void *obj);
void startNetworkThread();
@ -83,6 +89,9 @@ namespace Online{
static void deallocate();
static bool isRunning();
void startPolling(){ m_polling = true; }
void stopPolling(){ m_polling = false; }
//Execute
std::string getPage(Online::Request * request);
XMLNode * getXMLFromPage(Online::Request * request);
@ -93,6 +102,7 @@ namespace Online{
void stopNetworkThread();
bool getAbort(){ return m_abort.getAtomic(); };
void update(float dt);
}; //class HTTPManager
} // namespace Online

View File

@ -82,6 +82,13 @@ namespace Online
return irr::core::stringw(_("Fetching friends")) + loadingDots();
}
// ------------------------------------------------------------------------
irr::core::stringw processing()
{
return irr::core::stringw(_("Processing")) + loadingDots();
}
// ------------------------------------------------------------------------
irr::core::stringw loadingDots(bool spaces, float interval, int max_dots)
{

View File

@ -36,6 +36,7 @@ namespace Online
irr::core::stringw creatingServer ();
irr::core::stringw fetchingServers ();
irr::core::stringw fetchingFriends ();
irr::core::stringw processing ();
irr::core::stringw signedInAs (const irr::core::stringw & name);
} // namespace Messages
}// namespace Online

View File

@ -35,19 +35,78 @@ using namespace Online;
namespace Online{
// ============================================================================
Profile::Profile(User * user)
Profile::RelationInfo::RelationInfo(const irr::core::stringw & date, bool is_online, bool is_pending, bool is_asker)
{
setState (S_READY);
m_is_current_user = false;
m_cache_bit = false;
m_id = user->getUserID();
m_username = user->getUserName();
m_is_current_user = (m_id == CurrentUser::get()->getUserID());
m_date = date;
m_is_online = is_online;
m_is_pending = is_pending;
m_is_asker = is_asker;
}
// ============================================================================
void Profile::RelationInfo::setOnline(bool online)
{
m_is_online = online;
if(m_is_online)
m_is_pending = false;
}
// ============================================================================
Profile::Profile( const uint32_t & userid,
const irr::core::stringw & username,
bool is_current_user)
{
m_state = S_READY;
m_cache_bit = true;
m_id = userid;
m_is_current_user = is_current_user;
m_username = username;
m_has_fetched_friends = false;
m_friends_list_request = NULL;
m_relation_info = NULL;
m_is_friend = false;
}
Profile::Profile(const XMLNode * xml, ConstructorType type)
{
m_relation_info = NULL;
m_is_friend = false;
if(type == C_RELATION_INFO){
irr::core::stringw date("");
xml->get("date", &date);
std::string is_pending_string("");
xml->get("is_pending", &is_pending_string);
bool is_pending = is_pending_string == "yes";
bool is_asker(false);
bool is_online(false);
if(is_pending)
{
std::string is_asker_string("");
xml->get("is_asker", &is_asker_string);
is_asker = is_asker_string == "yes";
}
else
{
std::string is_online_string("");
xml->get("online", &is_online_string);
is_online = is_online_string == "yes";
m_is_friend = true;
}
m_relation_info = new RelationInfo(date, is_online, is_pending, is_asker);
xml = xml->getNode("user");
}
xml->get("id", &m_id);
xml->get("user_name", &m_username);
m_cache_bit = true;
m_has_fetched_friends = false;
m_is_current_user = (m_id == CurrentUser::get()->getID());
m_state = S_READY;
}
// ============================================================================
Profile::~Profile()
{
delete m_relation_info;
}
// ============================================================================
@ -56,8 +115,8 @@ namespace Online{
assert(CurrentUser::get()->isRegisteredUser());
if(m_has_fetched_friends)
return;
setState (S_FETCHING);
m_friends_list_request = requestFriendsList();
m_state = S_FETCHING;
requestFriendsList();
}
// ============================================================================
@ -65,34 +124,38 @@ namespace Online{
void Profile::friendsListCallback(const XMLNode * input)
{
const XMLNode * friends_xml = input->getNode("friends");
m_friends.clearAndDeleteAll();
uint32_t friendid(0);
irr::core::stringw username("");
m_friends.clear();
for (unsigned int i = 0; i < friends_xml->getNumNodes(); i++)
{
friends_xml->getNode(i)->get("friend_id", &friendid);
friends_xml->getNode(i)->get("friend_name", &username);
m_friends.push_back(new User(username, friendid));
Profile * profile;
if(m_is_current_user)
{
profile = new Profile(friends_xml->getNode(i) , C_RELATION_INFO);
ProfileManager::get()->addPersistent(profile);
}
else
{
profile = new Profile(friends_xml->getNode(i)->getNode("user"), C_DEFAULT);
ProfileManager::get()->addToCache(profile);
}
m_friends.push_back(profile->getID());
}
m_has_fetched_friends = true;
delete m_friends_list_request;
m_friends_list_request = NULL;
Profile::setState (Profile::S_READY);
m_state = S_READY;
}
// ============================================================================
const Profile::FriendsListRequest * Profile::requestFriendsList()
void Profile::requestFriendsList()
{
FriendsListRequest * request = new FriendsListRequest();
request->setURL((std::string)UserConfigParams::m_server_multiplayer + "client-user.php");
request->setParameter("action",std::string("get-friends-list"));
request->setParameter("token", CurrentUser::get()->getToken());
request->setParameter("userid", CurrentUser::get()->getUserID());
request->setParameter("userid", CurrentUser::get()->getID());
request->setParameter("visitingid", m_id);
HTTPManager::get()->addRequest(request);
return request;
}
void Profile::FriendsListRequest::callback()
@ -105,9 +168,43 @@ namespace Online{
// ============================================================================
const PtrVector<Online::User> & Profile::getFriends()
void Profile::removeFriend( const uint32_t id)
{
assert (m_has_fetched_friends && getState() == S_READY);
assert (m_has_fetched_friends);
std::vector<uint32_t>::iterator iter;
for (iter = m_friends.begin(); iter != m_friends.end();)
{
if (*iter == id)
{
m_friends.erase(iter++);
break;
}
else
++iter;
}
}
// ============================================================================
void Profile::addFriend( const uint32_t id)
{
assert (m_has_fetched_friends);
//FIXME check if it's not already in there
m_friends.push_back(id);
}
// ============================================================================
void Profile::deleteRelationalInfo()
{
delete m_relation_info;
m_relation_info = NULL;
}
// ============================================================================
const std::vector<uint32_t> & Profile::getFriends()
{
assert (m_has_fetched_friends && m_state == S_READY);
return m_friends;
}
// ============================================================================

View File

@ -21,7 +21,6 @@
#include "http_manager.hpp"
#include "online/request.hpp"
#include "online/user.hpp"
#include "utils/types.hpp"
#include "utils/ptr_vector.hpp"
@ -41,12 +40,34 @@ namespace Online{
class Profile
{
public :
enum ConstructorType
{
C_DEFAULT = 1,
C_RELATION_INFO
};
class RelationInfo
{
private:
bool m_is_online;
bool m_is_pending;
bool m_is_asker;
irr::core::stringw m_date;
public:
RelationInfo(const irr::core::stringw & date, bool is_online, bool is_pending, bool is_asker = false);
bool isPending(){return m_is_pending;}
bool isAsker(){return m_is_asker;}
const irr::core::stringw & getDate() { return m_date; }
bool isOnline() const { return m_is_online; }
void setOnline(bool online);
};
class FriendsListRequest : public XMLRequest
{
virtual void callback ();
public:
FriendsListRequest() : XMLRequest() {}
FriendsListRequest() : XMLRequest(0, true) {}
};
typedef std::vector<uint32_t> IDList;
private:
enum State
@ -55,38 +76,49 @@ namespace Online{
S_READY
};
Synchronised<State> m_state;
State m_state;
bool m_is_current_user;
uint32_t m_id;
irr::core::stringw m_username;
RelationInfo * m_relation_info;
bool m_is_friend;
bool m_has_fetched_friends;
PtrVector<Online::User> m_friends;
const FriendsListRequest * m_friends_list_request;
std::vector<uint32_t> m_friends;
bool m_cache_bit;
void setState(State state) { m_state.setAtomic(state); }
const State getState() const { return m_state.getAtomic(); }
const FriendsListRequest * requestFriendsList();
void requestFriendsList();
void friendsListCallback(const XMLNode * input);
public:
Profile(User * user);
void fetchFriends();
const PtrVector<Online::User> & getFriends();
Profile( const uint32_t & userid,
const irr::core::stringw & username,
bool is_current_user = false);
Profile( const XMLNode * xml,
ConstructorType type = C_DEFAULT);
~Profile();
void fetchFriends();
const std::vector<uint32_t> & getFriends();
bool isFetching() { return getState() == S_FETCHING; }
bool isReady() { return getState() == S_READY; }
bool isFetching() const { return m_state == S_FETCHING; }
bool isReady() const { return m_state == S_READY; }
void setCacheBit() { m_cache_bit = true; }
void unsetCacheBit() { m_cache_bit = false; }
bool getCacheBit() { return m_cache_bit; }
uint32_t getID() { return m_id; }
irr::core::stringw getUsername() { return m_username; }
bool isCurrentUser() const { return m_is_current_user; }
bool isFriend() const { return m_is_friend; }
void setFriend() { m_is_friend = true; }
void removeFriend(const uint32_t id);
void addFriend(const uint32_t id);
void deleteRelationalInfo();
RelationInfo * getRelationInfo() { return m_relation_info; }
void setRelationInfo(RelationInfo * r){ delete m_relation_info; m_relation_info = r;}
void setCacheBit() { m_cache_bit = true; }
void unsetCacheBit() { m_cache_bit = false; }
bool getCacheBit() const { return m_cache_bit; }
uint32_t getID() const { return m_id; }
const irr::core::stringw & getUserName() const { return m_username; }
}; // class CurrentUser

View File

@ -52,12 +52,24 @@ namespace Online{
}
// ============================================================================
ProfileManager::~ProfileManager()
{
ProfilesMap::iterator it;
for ( it = m_profiles_persistent.begin(); it != m_profiles_persistent.end(); ++it ) {
delete it->second;
}
for ( it = m_profiles_cache.begin(); it != m_profiles_persistent.end(); ++it ) {
delete it->second;
}
}
void ProfileManager::iterateCache()
// ============================================================================
void ProfileManager::iterateCache(Profile * profile)
{
if(m_profiles_cache.size() == m_max_cache_size)
{
m_currently_visiting->setCacheBit();
profile->setCacheBit();
ProfilesMap::iterator iter;
for (iter = m_profiles_cache.begin(); iter != m_profiles_cache.end(); ++iter)
{
@ -69,14 +81,14 @@ namespace Online{
{
iter->second->unsetCacheBit();
}
m_currently_visiting->setCacheBit();
profile->setCacheBit();
}
}
// ============================================================================
void ProfileManager::addToCache(Profile * profile)
void ProfileManager::directToCache(Profile * profile)
{
assert(profile != NULL);
if(m_profiles_cache.size() == m_max_cache_size)
@ -86,8 +98,11 @@ namespace Online{
{
if (!iter->second->getCacheBit())
{
m_profiles_cache.erase(iter++);
continue;
ProfilesMap::iterator toErase = iter;
++iter;
delete toErase->second;
m_profiles_cache.erase(toErase);
break;
}
else
++iter;
@ -99,33 +114,117 @@ namespace Online{
}
// ============================================================================
void ProfileManager::setVisiting(User * user)
void ProfileManager::addPersistent(Profile * profile)
{
assert(user != NULL);
if( m_profiles_cache.find(user->getUserID()) == m_profiles_cache.end())
if(inPersistent(profile->getID()))
{
//cache miss
m_currently_visiting = new Profile(user);
addToCache(m_currently_visiting);
delete m_profiles_persistent[profile->getID()];
m_profiles_persistent[profile->getID()] = profile;
}
else
{
//cache hit
m_currently_visiting = m_profiles_cache[user->getUserID()];
m_profiles_persistent[profile->getID()] = profile;
}
iterateCache();
}
// ============================================================================
void ProfileManager::deleteFromPersistent(const uint32_t id)
{
if (inPersistent(id))
{
delete m_profiles_persistent[id];
m_profiles_persistent.erase(id);
}
else
Log::warn("ProfileManager::removePersistent", "Tried to remove profile with id %d from persistent while not present", id);
}
// ============================================================================
Profile * ProfileManager::getProfileByID(uint32_t id)
void ProfileManager::clearPersistent()
{
if( m_profiles_cache.find(id) == m_profiles_cache.end())
{
Log::info("getProfileByID","here");
return NULL;
ProfilesMap::iterator it;
for ( it = m_profiles_persistent.begin(); it != m_profiles_persistent.end(); ++it ) {
delete it->second;
}
return m_profiles_cache[id];
m_profiles_persistent.clear();
}
// ============================================================================
void ProfileManager::moveToCache(const uint32_t id)
{
if (inPersistent(id))
{
Profile * profile = getProfileByID(id);
m_profiles_persistent.erase(id);
addToCache(profile);
}
else
Log::warn("ProfileManager::removePersistent", "Tried to move profile with id %d from persistent to cache while not present", id);
}
// ============================================================================
void ProfileManager::addToCache(Profile * profile)
{
if(inPersistent(profile->getID()))
{
//FIXME should do updating of values
}
else if(cacheHit(profile->getID()))
{
//FIXME should do updating of values
delete profile;
}
else
{
directToCache(profile);
}
Log::info("persistent size","%d", m_profiles_persistent.size());
Log::info("cache size","%d", m_profiles_cache.size());
}
// ============================================================================
bool ProfileManager::inPersistent(const uint32_t id)
{
if (m_profiles_persistent.find(id) != m_profiles_persistent.end())
{
return true;
}
return false;
}
// ============================================================================
bool ProfileManager::cacheHit(const uint32_t id)
{
if (m_profiles_cache.find(id) != m_profiles_cache.end())
{
iterateCache(m_profiles_cache[id]);
return true;
}
return false;
}
// ============================================================================
void ProfileManager::setVisiting(const uint32_t id)
{
m_currently_visiting = getProfileByID(id);
}
// ============================================================================
Profile * ProfileManager::getProfileByID(const uint32_t id)
{
if(inPersistent(id))
return m_profiles_persistent[id];
if(cacheHit(id))
return m_profiles_cache[id];
return NULL;
}

View File

@ -19,7 +19,6 @@
#ifndef HEADER_ONLINE_PROFILE_MANAGER_HPP
#define HEADER_ONLINE_PROFILE_MANAGER_HPP
#include "online/user.hpp"
#include "utils/types.hpp"
#include "online/profile.hpp"
@ -41,30 +40,33 @@ namespace Online{
private:
ProfileManager ();
enum State
{
S_FETCHING = 1,
S_READY
};
~ProfileManager ();
typedef std::map<uint32_t, Profile*> ProfilesMap;
ProfilesMap m_profiles_cache;
ProfilesMap m_profiles_persistent; // current user and friends
Profile * m_currently_visiting;
static const unsigned int m_max_cache_size = 5;
static const unsigned int m_max_cache_size = 20;
void iterateCache();
void addToCache(Profile * profile);
void iterateCache(Profile * profile);
void directToCache(Profile * profile);
public:
/**Singleton */
static ProfileManager * get();
static void deallocate();
void setVisiting(Online::User * user);
void addToCache(Profile * profile);
void addPersistent(Profile * profile);
void deleteFromPersistent(const uint32_t id);
void clearPersistent();
void moveToCache(const uint32_t id);
void setVisiting(const uint32_t id);
bool cacheHit(const uint32_t id);
bool inPersistent(const uint32_t id);
Profile * getVisitingProfile() {return m_currently_visiting;}
Profile * getProfileByID(uint32_t id);
Profile * getProfileByID(const uint32_t id);
}; // class CurrentUser

View File

@ -34,7 +34,7 @@ namespace Online{
// =========================================================================================
Request::Request(int type, bool manage_memory, int priority)
Request::Request(bool manage_memory, int priority, int type)
: m_type(type), m_manage_memory(manage_memory), m_priority(priority)
{
m_cancel.setAtomic(false);
@ -55,16 +55,13 @@ namespace Online{
void Request::afterOperation()
{
m_state.setAtomic(S_DONE);
}
// =========================================================================================
HTTPRequest::HTTPRequest(int type, bool manage_memory, int priority)
: Request(priority, manage_memory, type)
HTTPRequest::HTTPRequest(bool manage_memory, int priority)
: Request(manage_memory, priority, 0)
{
//Negative numbers are reserved for special requests ment for the HTTP Manager
assert(type >= 0);
m_url = "";
m_parameters = new Parameters();
m_progress.setAtomic(0);
@ -78,7 +75,9 @@ namespace Online{
bool HTTPRequest::isAllowedToAdd()
{
if (!Request::isAllowedToAdd() || m_url.size() < 5 || ( m_url.substr(0, 5) != "http:"))
{
return false;
}
return true;
}
@ -99,6 +98,13 @@ namespace Online{
curl_easy_setopt(m_curl_session, CURLOPT_CONNECTTIMEOUT, 20);
curl_easy_setopt(m_curl_session, CURLOPT_LOW_SPEED_LIMIT, 10);
curl_easy_setopt(m_curl_session, CURLOPT_LOW_SPEED_TIME, 20);
//https
struct curl_slist *chunk = NULL;
chunk = curl_slist_append(chunk, "Host: api.stkaddons.net");
curl_easy_setopt(m_curl_session, CURLOPT_HTTPHEADER, chunk);
curl_easy_setopt(m_curl_session, CURLOPT_CAINFO, (file_manager->getDataDir() + "web.tuxfamily.org.pem").c_str());
curl_easy_setopt(m_curl_session, CURLOPT_SSL_VERIFYPEER, 0L);
//curl_easy_setopt(m_curl_session, CURLOPT_VERBOSE, 1L);
}
void HTTPRequest::operation()
@ -145,7 +151,6 @@ namespace Online{
setProgress(-1.0f);
Request::afterOperation();
curl_easy_cleanup(m_curl_session);
callback();
}
size_t HTTPRequest::WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
@ -201,8 +206,8 @@ namespace Online{
// =========================================================================================
XMLRequest::XMLRequest(int type, bool manage_memory, int priority)
: HTTPRequest(priority, manage_memory, type)
XMLRequest::XMLRequest(bool manage_memory, int priority)
: HTTPRequest(manage_memory, priority)
{
m_string_buffer = "";
m_info = "";

View File

@ -40,9 +40,8 @@ namespace Online{
class Request
{
private:
/** Can be used as identifier for the user.
/** Type of the request
* Has 0 as default value.
* Only requests ment to control the HTTP Manager should use negative values, for all other uses positive values are obliged
* */
const int m_type;
/** True if the memory for this Request should be managed by
@ -73,13 +72,12 @@ namespace Online{
virtual void afterOperation();
public:
/** Negative numbers are reserved for requests that are special for the HTTP Manager*/
enum RequestType
{
RT_QUIT = -1
RT_QUIT = 1
};
Request(int type, bool manage_memory, int priority);
Request(bool manage_memory, int priority, int type);
virtual ~Request();
void execute();
@ -101,6 +99,9 @@ namespace Online{
/** Returns if this request is done. */
bool isDone() const { return m_state.getAtomic() == S_DONE; }
// ------------------------------------------------------------------------
/** Should only be called by the manager */
void setDone() { m_state.setAtomic(S_DONE); }
// ------------------------------------------------------------------------
/** Returns if this request is being prepared. */
bool isPreparing() const { return m_state.getAtomic() == S_PREPARING; }
// ------------------------------------------------------------------------
@ -113,6 +114,9 @@ namespace Online{
/** Virtual method to check if a request has initialized all needed members to a valid value. */
virtual bool isAllowedToAdd() const { return isPreparing(); }
/** Executed when a request has finished. */
virtual void callback() {}
/** This class is used by the priority queue to sort requests by priority.
*/
class Compare
@ -150,8 +154,7 @@ namespace Online{
virtual void prepareOperation() OVERRIDE;
virtual void operation() OVERRIDE;
virtual void afterOperation() OVERRIDE;
/** Executed when a request has finished. */
virtual void callback() {}
static int progressDownload( void *clientp,
double dltotal,
@ -166,7 +169,7 @@ namespace Online{
public :
HTTPRequest(int type = 0, bool manage_memory = false, int priority = 1);
HTTPRequest(bool manage_memory = false, int priority = 1);
virtual ~HTTPRequest();
void setParameter(const std::string & name, const std::string &value){
@ -211,7 +214,7 @@ namespace Online{
virtual void afterOperation() OVERRIDE;
public :
XMLRequest(int type = 0, bool manage_memory = false, int priority = 1);
XMLRequest(bool manage_memory = false, int priority = 1);
virtual ~XMLRequest();
const XMLNode * getResult() const;

View File

@ -37,16 +37,12 @@ namespace Online {
class ServersManager
{
public:
enum RequestType
{
RT_REFRESH = 1
};
class RefreshRequest : public XMLRequest
{
virtual void callback ();
public:
RefreshRequest() : XMLRequest(RT_REFRESH) {}
RefreshRequest() : XMLRequest() {}
};
private:

View File

@ -1,53 +0,0 @@
//
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2013 Glenn De Jonghe
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "online/user.hpp"
#include <sstream>
#include <stdlib.h>
using namespace Online;
namespace Online{
// ============================================================================
User::User ( const irr::core::stringw & username,
const uint32_t & userid
)
{
setUserName(username);
setUserID(userid);
}
// ============================================================================
User::User(uint32_t id)
{
setUserName("");
setUserID(id);
}
// ============================================================================
User::User ( const XMLNode * xml)
{
irr::core::stringw username("");
xml->get("user_name", &username);
setUserName(username);
uint32_t id;
xml->get("id", &id);
setUserID(id);
}
} // namespace Online

View File

@ -1,59 +0,0 @@
//
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2013 Glenn De Jonghe
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_ONLINE_USER_HPP
#define HEADER_ONLINE_USER_HPP
#include <irrString.h>
#include "utils/types.hpp"
#include "utils/synchronised.hpp"
#include "io/xml_node.hpp"
namespace Online{
/**
* \brief Class that represents an online registered user
* \ingroup online
*/
class User
{
private:
Synchronised<irr::core::stringw> m_name;
Synchronised<uint32_t> m_id;
protected:
void setUserName (const irr::core::stringw & name) { m_name.setAtomic(name); }
void setUserID (const uint32_t & id) { m_id.setAtomic(id); }
public:
User( const irr::core::stringw & username,
const uint32_t & userid
);
User( const XMLNode * xml);
virtual ~User() {};
virtual const irr::core::stringw getUserName() const { return m_name.getAtomic(); }
const uint32_t getUserID() const { return m_id.getAtomic(); }
User(uint32_t id);
}; // class User
} // namespace Online
#endif
/*EOF*/

View File

@ -32,15 +32,24 @@ using namespace GUIEngine;
MessageDialog::MessageDialog(irr::core::stringw msg, MessageDialogType type, IConfirmDialogListener* listener, bool own_listener) :
ModalDialog(0.6f, 0.6f)
{
doInit(msg, type, listener, own_listener);
m_msg = msg;
doInit(type, listener, own_listener);
}
// ------------------------------------------------------------------------------------------------------
MessageDialog::MessageDialog(irr::core::stringw msg) :
MessageDialog::MessageDialog(irr::core::stringw msg, bool from_queue) :
ModalDialog(0.6f, 0.6f)
{
doInit(msg, MessageDialog::MESSAGE_DIALOG_OK, NULL, false);
m_msg = msg;
if(!from_queue) load();
}
// ------------------------------------------------------------------------------------------------------
void MessageDialog::load()
{
doInit(MessageDialog::MESSAGE_DIALOG_OK, NULL, false);
}
// ------------------------------------------------------------------------------------------------------
@ -57,7 +66,7 @@ MessageDialog::~MessageDialog()
// ------------------------------------------------------------------------------------------------------
void MessageDialog::doInit(irr::core::stringw msg, MessageDialogType type,
void MessageDialog::doInit(MessageDialogType type,
IConfirmDialogListener* listener, bool own_listener)
{
if (StateManager::get()->getGameState() == GUIEngine::GAME)
@ -72,7 +81,7 @@ void MessageDialog::doInit(irr::core::stringw msg, MessageDialogType type,
m_own_listener = own_listener;
LabelWidget* message = getWidget<LabelWidget>("title");
message->setText( msg.c_str(), false );
message->setText( m_msg.c_str(), false );
// If the dialog is a simple 'OK' dialog, then hide the "Yes" button and
// change "Cancel" to "OK"

View File

@ -68,7 +68,8 @@ private:
IConfirmDialogListener* m_listener;
bool m_own_listener;
void doInit(irr::core::stringw msg, MessageDialogType type, IConfirmDialogListener* listener, bool own_listener);
irr::core::stringw m_msg;
void doInit(MessageDialogType type, IConfirmDialogListener* listener, bool own_listener);
public:
@ -84,13 +85,14 @@ public:
* Variant of MessageDialog where cancelling is not possible (i.e. just shows a message box with OK)
* \param msg Message to display in the dialog
*/
MessageDialog(irr::core::stringw msg);
MessageDialog(irr::core::stringw msg, bool from_queue = false);
~MessageDialog();
virtual void onEnterPressedInternal();
virtual void onUpdate(float dt);
virtual void load();
GUIEngine::EventPropagation processEvent(const std::string& eventSource);
};

View File

@ -0,0 +1,135 @@
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2013 Glenn De Jonghe
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "states_screens/dialogs/notification_dialog.hpp"
#include <IGUIEnvironment.h>
#include "audio/sfx_manager.hpp"
#include "guiengine/engine.hpp"
#include "states_screens/state_manager.hpp"
#include "states_screens/online_profile_friends.hpp"
#include "utils/translation.hpp"
using namespace GUIEngine;
using namespace irr;
using namespace irr::gui;
using namespace Online;
// -----------------------------------------------------------------------------
NotificationDialog::NotificationDialog(Type type, const core::stringw info, bool from_queue)
: ModalDialog(0.8f,0.5f)
{
m_info = info;
m_type = type;
if(!from_queue) load();
}
void NotificationDialog::load()
{
loadFromFile("online/notification_dialog.stkgui");
}
void NotificationDialog::beforeAddingWidgets()
{
m_self_destroy = false;
m_view = false;
m_info_widget = getWidget<LabelWidget>("info");
assert(m_info_widget != NULL);
m_info_widget->setText(m_info, false);
m_options_widget = getWidget<RibbonWidget>("options");
assert(m_options_widget != NULL);
m_view_widget = getWidget<IconButtonWidget>("view");
assert(m_view_widget != NULL);
m_cancel_widget = getWidget<IconButtonWidget>("cancel");
assert(m_cancel_widget != NULL);
m_options_widget->setFocusForPlayer(PLAYER_ID_GAME_MASTER);
}
// -----------------------------------------------------------------------------
NotificationDialog::~NotificationDialog()
{
}
// -----------------------------------------------------------------------------
GUIEngine::EventPropagation NotificationDialog::processEvent(const std::string& eventSource)
{
if (eventSource == m_options_widget->m_properties[PROP_ID])
{
const std::string& selection = m_options_widget->getSelectionIDString(PLAYER_ID_GAME_MASTER);
if (selection == m_cancel_widget->m_properties[PROP_ID])
{
m_self_destroy = true;
return GUIEngine::EVENT_BLOCK;
}
else if(selection == m_view_widget->m_properties[PROP_ID])
{
m_view = true;
return GUIEngine::EVENT_BLOCK;
}
}
return GUIEngine::EVENT_LET;
}
// -----------------------------------------------------------------------------
void NotificationDialog::onEnterPressedInternal()
{
//If enter was pressed while none of the buttons was focused interpret as close
const int playerID = PLAYER_ID_GAME_MASTER;
if (GUIEngine::isFocusedForPlayer(m_options_widget, playerID))
return;
m_self_destroy = true;
}
// -----------------------------------------------------------------------------
bool NotificationDialog::onEscapePressed()
{
if (m_cancel_widget->isActivated())
m_self_destroy = true;
return false;
}
// -----------------------------------------------------------------------------
void NotificationDialog::onUpdate(float dt)
{
//If we want to open the registration dialog, we need to close this one first
m_view && (m_self_destroy = true);
// It's unsafe to delete from inside the event handler so we do it here
if (m_self_destroy)
{
ModalDialog::dismiss();
if (m_view)
{
if(m_type == T_Friends)
{
ProfileManager::get()->setVisiting(CurrentUser::get()->getID());
StateManager::get()->pushScreen(OnlineProfileFriends::getInstance());
}
}
return;
}
}

View File

@ -0,0 +1,68 @@
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2013 Glenn De Jonghe
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_NOTIFICATION_DIALOG_HPP
#define HEADER_NOTIFICATION_DIALOG_HPP
#include <irrString.h>
#include "guiengine/modaldialog.hpp"
#include "guiengine/widgets.hpp"
#include "online/current_user.hpp"
#include "utils/types.hpp"
/**
* \brief Dialog that allows a user to sign in
* \ingroup states_screens
*/
class NotificationDialog : public GUIEngine::ModalDialog
{
public:
enum Type
{
T_Friends = 1
};
private:
bool m_self_destroy;
bool m_view;
Type m_type;
irr::core::stringw m_info;
GUIEngine::LabelWidget * m_info_widget;
GUIEngine::RibbonWidget * m_options_widget;
GUIEngine::IconButtonWidget * m_view_widget;
GUIEngine::IconButtonWidget * m_cancel_widget;
public:
NotificationDialog(Type type, const core::stringw info, bool from_queue = true);
~NotificationDialog();
virtual void beforeAddingWidgets();
virtual void load();
void onEnterPressedInternal();
GUIEngine::EventPropagation processEvent(const std::string& eventSource);
virtual bool onEscapePressed();
virtual void onUpdate(float dt);
};
#endif

View File

@ -40,7 +40,7 @@ RegistrationDialog::RegistrationDialog() :
{
m_sign_up_request = NULL;
m_self_destroy = false;
m_show_registration_input = true;
m_show_registration_input = false;
m_show_registration_terms = false;
m_show_registration_info = false;
m_username = "";
@ -49,6 +49,7 @@ RegistrationDialog::RegistrationDialog() :
m_password = "";
m_password_confirm = "";
m_agreement = false;
showRegistrationInput();
}
// -----------------------------------------------------------------------------
@ -62,8 +63,9 @@ RegistrationDialog::~RegistrationDialog()
void RegistrationDialog::showRegistrationInput()
{
if(isInited())
clearWindow();
m_show_registration_input = false;
clearWindow();
m_phase = Input;
loadFromFile("online/registration_input.stkgui");
@ -110,7 +112,8 @@ void RegistrationDialog::showRegistrationInput()
void RegistrationDialog::showRegistrationTerms()
{
m_show_registration_terms = false;
clearWindow();
if(isInited())
clearWindow();
m_phase = Terms;
loadFromFile("online/registration_terms.stkgui");
@ -154,7 +157,8 @@ void RegistrationDialog::showRegistrationTerms()
void RegistrationDialog::showRegistrationInfo()
{
m_show_registration_info = false;
clearWindow();
if(isInited())
clearWindow();
m_phase = Info;
loadFromFile("online/registration_info.stkgui");

View File

@ -0,0 +1,228 @@
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2013 Glenn De Jonghe
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include "states_screens/dialogs/user_info_dialog.hpp"
#include <IGUIEnvironment.h>
#include "audio/sfx_manager.hpp"
#include "guiengine/engine.hpp"
#include "states_screens/state_manager.hpp"
#include "states_screens/online_profile_overview.hpp"
#include "utils/translation.hpp"
#include "online/messages.hpp"
using namespace GUIEngine;
using namespace irr;
using namespace irr::gui;
using namespace Online;
// -----------------------------------------------------------------------------
UserInfoDialog::UserInfoDialog(uint32_t showing_id, const core::stringw info, bool error, bool from_queue)
: ModalDialog(0.8f,0.8f), m_showing_id(showing_id)
{
m_error = error;
m_info = info;
if(!from_queue) load();
}
void UserInfoDialog::load()
{
loadFromFile("online/user_info_dialog.stkgui");
if(m_error)
m_info_widget->setErrorColor();
m_name_widget->setText(m_profile->getUserName(),false);
m_info_widget->setText(m_info, false);
if(m_remove_widget->isVisible() && !m_profile->isFriend())
m_remove_widget->setLabel("Cancel Request");
}
void UserInfoDialog::beforeAddingWidgets()
{
m_profile = ProfileManager::get()->getProfileByID(m_showing_id);
m_self_destroy = false;
m_enter_profile = false;
m_processing = false;
m_name_widget = getWidget<LabelWidget>("name");
assert(m_name_widget != NULL);
m_info_widget = getWidget<LabelWidget>("info");
assert(m_info_widget != NULL);
m_options_widget = getWidget<RibbonWidget>("options");
assert(m_options_widget != NULL);
m_remove_widget = getWidget<IconButtonWidget>("remove");
assert(m_remove_widget != NULL);
m_friend_widget = getWidget<IconButtonWidget>("friend");
assert(m_friend_widget != NULL);
m_accept_widget = getWidget<IconButtonWidget>("accept");
assert(m_accept_widget != NULL);
m_decline_widget = getWidget<IconButtonWidget>("decline");
assert(m_decline_widget != NULL);
m_enter_widget = getWidget<IconButtonWidget>("enter");
assert(m_enter_widget != NULL);
m_cancel_widget = getWidget<IconButtonWidget>("cancel");
assert(m_cancel_widget != NULL);
m_options_widget->setFocusForPlayer(PLAYER_ID_GAME_MASTER);
m_accept_widget->setVisible(false);
m_decline_widget->setVisible(false);
m_remove_widget->setVisible(false);
if(m_profile->isCurrentUser())
{
m_friend_widget->setVisible(false);
}
if(m_profile->isFriend())
{
m_friend_widget->setVisible(false);
m_remove_widget->setVisible(true);
}
Profile::RelationInfo * relation_info = m_profile->getRelationInfo();
if(relation_info != NULL)
{
if(relation_info->isPending())
{
m_friend_widget->setVisible(false);
if(relation_info->isAsker())
{
m_accept_widget->setVisible(true);
m_decline_widget->setVisible(true);
}
else
{
m_remove_widget->setVisible(true);
}
}
}
}
// -----------------------------------------------------------------------------
UserInfoDialog::~UserInfoDialog()
{
}
// -----------------------------------------------------------------------------
GUIEngine::EventPropagation UserInfoDialog::processEvent(const std::string& eventSource)
{
if (eventSource == m_options_widget->m_properties[PROP_ID])
{
const std::string& selection = m_options_widget->getSelectionIDString(PLAYER_ID_GAME_MASTER);
if (selection == m_cancel_widget->m_properties[PROP_ID])
{
m_self_destroy = true;
return GUIEngine::EVENT_BLOCK;
}
else if(selection == m_enter_widget->m_properties[PROP_ID])
{
ProfileManager::get()->setVisiting(m_profile->getID());
m_enter_profile = true;
m_options_widget->setDeactivated();
return GUIEngine::EVENT_BLOCK;
}
else if(selection == m_friend_widget->m_properties[PROP_ID])
{
CurrentUser::get()->requestFriendRequest(m_profile->getID());
m_processing = true;
m_options_widget->setDeactivated();
return GUIEngine::EVENT_BLOCK;
}
else if(selection == m_remove_widget->m_properties[PROP_ID])
{
if(m_profile->getRelationInfo()->isPending())
CurrentUser::get()->requestCancelFriend(m_profile->getID());
else
CurrentUser::get()->requestRemoveFriend(m_profile->getID());
m_processing = true;
m_options_widget->setDeactivated();
return GUIEngine::EVENT_BLOCK;
}
else if(selection == m_accept_widget->m_properties[PROP_ID])
{
CurrentUser::get()->requestAcceptFriend(m_profile->getID());
m_processing = true;
m_options_widget->setDeactivated();
return GUIEngine::EVENT_BLOCK;
}
else if(selection == m_decline_widget->m_properties[PROP_ID])
{
CurrentUser::get()->requestDeclineFriend(m_profile->getID());
m_processing = true;
m_options_widget->setDeactivated();
return GUIEngine::EVENT_BLOCK;
}
}
return GUIEngine::EVENT_LET;
}
// -----------------------------------------------------------------------------
void UserInfoDialog::deactivate()
{
m_options_widget->setDeactivated();
}
// -----------------------------------------------------------------------------
void UserInfoDialog::activate()
{
}
// -----------------------------------------------------------------------------
void UserInfoDialog::onEnterPressedInternal()
{
//If enter was pressed while none of the buttons was focused interpret as join event
const int playerID = PLAYER_ID_GAME_MASTER;
if (GUIEngine::isFocusedForPlayer(m_options_widget, playerID))
return;
m_self_destroy = true;
}
// -----------------------------------------------------------------------------
bool UserInfoDialog::onEscapePressed()
{
if (m_cancel_widget->isActivated())
m_self_destroy = true;
return false;
}
// -----------------------------------------------------------------------------
void UserInfoDialog::onUpdate(float dt)
{
if(m_processing) m_info_widget->setText(Messages::processing(), false);
//If we want to open the registration dialog, we need to close this one first
m_enter_profile && (m_self_destroy = true);
// It's unsafe to delete from inside the event handler so we do it here
if (m_self_destroy)
{
ModalDialog::dismiss();
if (m_enter_profile)
StateManager::get()->replaceTopMostScreen(OnlineProfileOverview::getInstance());
return;
}
}

View File

@ -0,0 +1,79 @@
// SuperTuxKart - a fun racing game with go-kart
// Copyright (C) 2013 Glenn De Jonghe
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#ifndef HEADER_USER_INFO_DIALOG_HPP
#define HEADER_USER_INFO_DIALOG_HPP
#include <irrString.h>
#include "guiengine/modaldialog.hpp"
#include "guiengine/widgets.hpp"
#include "online/profile_manager.hpp"
#include "online/current_user.hpp"
#include "utils/types.hpp"
/**
* \brief Dialog that allows a user to sign in
* \ingroup states_screens
*/
class UserInfoDialog : public GUIEngine::ModalDialog
{
private:
bool m_self_destroy;
bool m_enter_profile;
bool m_processing;
bool m_error;
irr::core::stringw m_info;
const uint32_t m_showing_id;
Online::Profile * m_profile;
GUIEngine::LabelWidget * m_name_widget;
GUIEngine::LabelWidget * m_info_widget;
GUIEngine::RibbonWidget * m_options_widget;
GUIEngine::IconButtonWidget * m_remove_widget;
GUIEngine::IconButtonWidget * m_friend_widget;
GUIEngine::IconButtonWidget * m_accept_widget;
GUIEngine::IconButtonWidget * m_decline_widget;
GUIEngine::IconButtonWidget * m_enter_widget;
GUIEngine::IconButtonWidget * m_cancel_widget;
void requestJoin();
void activate();
void deactivate();
public:
UserInfoDialog(uint32_t showing_id, const core::stringw info = "", bool error = false, bool from_queue = false);
~UserInfoDialog();
virtual void beforeAddingWidgets();
virtual void load();
void onEnterPressedInternal();
GUIEngine::EventPropagation processEvent(const std::string& eventSource);
virtual bool onEscapePressed();
virtual void onUpdate(float dt);
};
#endif

View File

@ -46,7 +46,7 @@ private:
const std::string m_addon_id;
bool m_self_destroy;
const Online::XMLRequest * m_fetch_vote_request;
const Online::CurrentUser::setAddonVoteRequest * m_perform_vote_request;
const Online::CurrentUser::SetAddonVoteRequest * m_perform_vote_request;
GUIEngine::LabelWidget * m_info_widget;

View File

@ -38,7 +38,7 @@
#include "karts/kart_properties.hpp"
#include "karts/kart_properties_manager.hpp"
#include "modes/overworld.hpp"
#include "online/user.hpp"
#include "online/profile.hpp"
#include "states_screens/race_setup_screen.hpp"
#include "states_screens/state_manager.hpp"
#include "utils/translation.hpp"
@ -183,7 +183,7 @@ void PlayerNameSpinner::markAsCorrect()
PlayerKartWidget::PlayerKartWidget(KartSelectionScreen* parent,
StateManager::ActivePlayer* associatedPlayer,
Online::User* associatedUser,
Online::Profile* associatedUser,
core::recti area, const int playerID,
std::string kartGroup,
const int irrlichtWidgetID) : Widget(WTYPE_DIV)

View File

@ -244,7 +244,7 @@ class PlayerKartWidget : public GUIEngine::Widget,
/** Object representing this player */
StateManager::ActivePlayer* m_associatedPlayer; // local info
int m_playerID;
Online::User* m_associated_user; // network info
Online::Profile* m_associated_user; // network info
/** Internal name of the spinner; useful to interpret spinner events,
* which contain the name of the activated object */
@ -276,7 +276,7 @@ public:
PlayerKartWidget(KartSelectionScreen* parent,
StateManager::ActivePlayer* associatedPlayer,
Online::User* associatedUser,
Online::Profile* associatedUser,
core::recti area, const int playerID,
std::string kartGroup,
const int irrlichtWidgetID=-1);

View File

@ -66,7 +66,7 @@ void NetworkKartSelectionScreen::init()
for (unsigned int i = 0; i < players.size(); i++)
{
if (players[i]->user_profile == Online::CurrentUser::get())
if (players[i]->user_profile == Online::CurrentUser::get()->getProfile())
{
m_id_mapping.insert(m_id_mapping.begin(),players[i]->race_id); //!< first kart widget always me
Log::info("NKSS", "Insert %d at pos 0", players[i]->race_id);

View File

@ -45,9 +45,8 @@ void OnlineProfileBase::loadedFromFile()
{
m_profile_tabs = this->getWidget<RibbonWidget>("profile_tabs");
assert(m_profile_tabs != NULL);
LabelWidget * header = this->getWidget<LabelWidget>("title");
assert(header != NULL);
header->setText(_("Your profile"), false);
m_header = this->getWidget<LabelWidget>("title");
assert(m_header != NULL);
m_overview_tab = (IconButtonWidget *) m_profile_tabs->findWidgetNamed("tab_overview");
assert(m_overview_tab != NULL);
@ -65,6 +64,12 @@ void OnlineProfileBase::init()
m_overview_tab->setTooltip( _("Overview") );
m_friends_tab->setTooltip( _("Friends") );
m_visiting_profile = ProfileManager::get()->getVisitingProfile();
if (m_visiting_profile->isCurrentUser())
m_header->setText(_("Your profile"), false);
else
m_header->setText( m_visiting_profile->getUserName() + _("'s profile"), false);
} // init
// -----------------------------------------------------------------------------

View File

@ -24,6 +24,7 @@
#include "guiengine/screen.hpp"
#include "guiengine/widgets.hpp"
#include "online/profile.hpp"
namespace GUIEngine { class Widget; }
@ -36,10 +37,13 @@ class OnlineProfileBase : public GUIEngine::Screen
{
protected:
OnlineProfileBase(const char* filename);
GUIEngine::LabelWidget * m_header;
GUIEngine::RibbonWidget* m_profile_tabs;
GUIEngine::IconButtonWidget * m_overview_tab;
GUIEngine::IconButtonWidget * m_friends_tab;
Online::Profile * m_visiting_profile;
public:
/** \brief implement callback from parent class GUIEngine::Screen */

View File

@ -23,6 +23,7 @@
#include "guiengine/widget.hpp"
#include "states_screens/state_manager.hpp"
#include "states_screens/online_user_search.hpp"
#include "states_screens/dialogs/user_info_dialog.hpp"
#include "utils/translation.hpp"
#include "online/messages.hpp"
@ -42,6 +43,8 @@ DEFINE_SCREEN_SINGLETON( OnlineProfileFriends );
OnlineProfileFriends::OnlineProfileFriends() : OnlineProfileBase("online/profile_friends.stkgui")
{
m_selected_friend_index = -1;
m_own_profile = true;
} // OnlineProfileFriends
// -----------------------------------------------------------------------------
@ -63,7 +66,12 @@ void OnlineProfileFriends::loadedFromFile()
void OnlineProfileFriends::beforeAddingWidget()
{
m_friends_list_widget->clearColumns();
m_friends_list_widget->addColumn( _("Friends"), 3 );
m_friends_list_widget->addColumn( _("Username"), 2 );
if(m_own_profile)
{
m_friends_list_widget->addColumn( _("Since"), 1 );
m_friends_list_widget->addColumn( _("Status"), 2 );
}
}
// -----------------------------------------------------------------------------
@ -71,13 +79,17 @@ void OnlineProfileFriends::beforeAddingWidget()
void OnlineProfileFriends::init()
{
OnlineProfileBase::init();
if(m_own_profile != m_visiting_profile->isCurrentUser())
{
m_own_profile = m_visiting_profile->isCurrentUser();
GUIEngine::reshowCurrentScreen();
return;
}
m_profile_tabs->select( m_friends_tab->m_properties[PROP_ID], PLAYER_ID_GAME_MASTER );
m_visiting_profile = ProfileManager::get()->getVisitingProfile();
assert(m_visiting_profile != NULL);
m_visiting_profile->fetchFriends();
m_waiting_for_friends = true;
m_friends_list_widget->clear();
m_friends_list_widget->addItem("spacer", L"");
m_friends_list_widget->addItem("loading", Messages::fetchingFriends());
} // init
// -----------------------------------------------------------------------------
@ -89,7 +101,12 @@ void OnlineProfileFriends::eventCallback(Widget* widget, const std::string& name
{
OnlineUserSearch * instance = OnlineUserSearch::getInstance();
instance->setSearchString(m_search_box_widget->getText().trim());
StateManager::get()->pushScreen(instance);
StateManager::get()->replaceTopMostScreen(instance);
}
else if (name == m_friends_list_widget->m_properties[GUIEngine::PROP_ID])
{
m_selected_friend_index = m_friends_list_widget->getSelectionID();
new UserInfoDialog(m_visiting_profile->getFriends()[m_selected_friend_index]);
}
} // eventCallback
@ -101,17 +118,31 @@ void OnlineProfileFriends::onUpdate(float delta, irr::video::IVideoDriver* driv
if(m_visiting_profile->isReady())
{
m_friends_list_widget->clear();
for(int i = 0; i < m_visiting_profile->getFriends().size(); i++)
for(unsigned int i = 0; i < m_visiting_profile->getFriends().size(); i++)
{
PtrVector<GUIEngine::ListWidget::ListCell> * row = new PtrVector<GUIEngine::ListWidget::ListCell>;
row->push_back(new GUIEngine::ListWidget::ListCell(m_visiting_profile->getFriends()[i].getUserName(),-1,3));
m_friends_list_widget->addItem("server", row);
Profile * friend_profile = ProfileManager::get()->getProfileByID(m_visiting_profile->getFriends()[i]);
row->push_back(new GUIEngine::ListWidget::ListCell(friend_profile->getUserName(),-1,2));
if(m_visiting_profile->isCurrentUser())
{
Profile::RelationInfo * relation_info = friend_profile->getRelationInfo();
row->push_back(new GUIEngine::ListWidget::ListCell(relation_info->getDate(),-1,1, true));
irr::core::stringw status("");
if(relation_info->isPending())
{
status = (relation_info->isAsker() ? _("New Request") : _("Pending"));
}
else
status = (relation_info->isOnline() ? _("Online") : _("Offline"));
row->push_back(new GUIEngine::ListWidget::ListCell(status,-1,2, true));
}
m_friends_list_widget->addItem("friend", row);
}
m_waiting_for_friends = false;
}
else
{
m_friends_list_widget->renameItem("loading", Messages::fetchingFriends());
m_friends_list_widget->renameItem("loading", Messages::fetchingFriends());
}
}
}

View File

@ -44,8 +44,10 @@ private:
GUIEngine::ButtonWidget * m_search_button_widget;
GUIEngine::TextBoxWidget * m_search_box_widget;
Online::Profile * m_visiting_profile;
int m_selected_friend_index;
bool m_waiting_for_friends;
bool m_own_profile;
bool m_refresh_screen;
public:
friend class GUIEngine::ScreenSingleton<OnlineProfileFriends>;
@ -62,6 +64,8 @@ public:
virtual void onUpdate(float delta, irr::video::IVideoDriver* driver) OVERRIDE;
virtual void beforeAddingWidget() OVERRIDE;
virtual void refreshFriendsList() {m_waiting_for_friends = true; }
};
#endif

View File

@ -60,16 +60,12 @@ DEFINE_SCREEN_SINGLETON( OnlineScreen );
OnlineScreen::OnlineScreen() : Screen("online/main.stkgui")
{
m_recorded_state = CurrentUser::US_SIGNED_OUT;
const CurrentUser::SignInRequest * request = CurrentUser::get()->requestSavedSession();
if(request != NULL)
m_requests.push_back(request);
} // OnlineScreen
// ----------------------------------------------------------------------------
OnlineScreen::~OnlineScreen()
{
m_requests.clearAndDeleteAll();
}
// ----------------------------------------------------------------------------
@ -172,28 +168,6 @@ void OnlineScreen::onUpdate(float delta, irr::video::IVideoDriver* driver)
{
m_online_status_widget->setText(Messages::signingOut(), false);
}
for(int i = m_requests.size()-1; i>=0; --i)
{
if(m_requests[i].isDone())
{
if(m_requests[i].getType() == CurrentUser::RT_SIGN_IN)
{
if(m_requests[i].isSuccess())
{
new MessageDialog(_("Signed in."));
}
else
{
sfx_manager->quickSound( "anvil" );
new MessageDialog(m_requests[i].getInfo());
}
}else if(m_requests[i].getType() == CurrentUser::RT_SIGN_OUT)
{
new MessageDialog(_("Signed out successfully."));
}
m_requests.erase(i);
}
}
} // onUpdate
// ----------------------------------------------------------------------------
@ -210,32 +184,32 @@ void OnlineScreen::eventCallback(Widget* widget, const std::string& name, const
if (ribbon == NULL) return;
std::string selection = ribbon->getSelectionIDString(PLAYER_ID_GAME_MASTER);
if (selection == "sign_in")
if (selection == m_sign_in_widget->m_properties[PROP_ID])
{
new LoginDialog(LoginDialog::Normal);
}
else if (selection == "sign_out")
else if (selection == m_sign_out_widget->m_properties[PROP_ID])
{
CurrentUser::get()->requestSignOut();
}
else if (selection == m_profile_widget->m_properties[PROP_ID])
{
ProfileManager::get()->setVisiting(CurrentUser::get());
ProfileManager::get()->setVisiting(CurrentUser::get()->getID());
StateManager::get()->pushScreen(OnlineProfileOverview::getInstance());
}
else if (selection == "register")
else if (selection == m_register_widget->m_properties[PROP_ID])
{
new RegistrationDialog();
}
else if (selection == "find_server")
else if (selection == m_find_server_widget->m_properties[PROP_ID])
{
StateManager::get()->pushScreen(ServerSelection::getInstance());
}
else if (selection == "create_server")
else if (selection == m_create_server_widget->m_properties[PROP_ID])
{
StateManager::get()->pushScreen(CreateServerScreen::getInstance());
}
else if (selection == "quick_play")
else if (selection == m_quick_play_widget->m_properties[PROP_ID])
{
//FIXME temporary and the request join + join sequence should be placed in one method somewhere
// refresh server list

View File

@ -55,8 +55,6 @@ private:
Online::CurrentUser::UserState m_recorded_state;
PtrVector<const Online::XMLRequest> m_requests;
/** \brief Checks if the recorded state differs from the actual state and sets it. */
bool hasStateChanged();
/** \brief Sets which widget has to be focused. Depends on the user state. */

View File

@ -21,7 +21,7 @@
#include <assert.h>
#include "guiengine/modaldialog.hpp"
//#include "states_screens/dialogs/user_info_dialog.hpp"
#include "states_screens/dialogs/user_info_dialog.hpp"
#include "states_screens/state_manager.hpp"
#include "states_screens/dialogs/message_dialog.hpp"
#include "utils/translation.hpp"
@ -48,8 +48,6 @@ OnlineUserSearch::OnlineUserSearch() : Screen("online/user_search.stkgui")
OnlineUserSearch::~OnlineUserSearch()
{
delete m_search_request;
m_users.clearAndDeleteAll();
} // OnlineUserSearch
// ----------------------------------------------------------------------------
@ -65,21 +63,25 @@ void OnlineUserSearch::tearDown()
void OnlineUserSearch::parseResult(const XMLNode * input)
{
m_users.clearAndDeleteAll();
m_users.clear();
const XMLNode * users_xml = input->getNode("users");
for (unsigned int i = 0; i < users_xml->getNumNodes(); i++)
{
m_users.push_back(new User(users_xml->getNode(i)));
Profile * profile = new Profile(users_xml->getNode(i));
ProfileManager::get()->addToCache(profile);
m_users.push_back(profile->getID());
}
}
void OnlineUserSearch::showList()
{
m_user_list_widget->clear();
for(int i=0; i < m_users.size(); i++)
for(unsigned int i=0; i < m_users.size(); i++)
{
PtrVector<GUIEngine::ListWidget::ListCell> * row = new PtrVector<GUIEngine::ListWidget::ListCell>;
row->push_back(new GUIEngine::ListWidget::ListCell(m_users[i].getUserName(),-1,3));
Profile * profile = ProfileManager::get()->getProfileByID(m_users[i]);
assert(profile != NULL);
row->push_back(new GUIEngine::ListWidget::ListCell(profile->getUserName(),-1,3));
m_user_list_widget->addItem("user", row);
}
}
@ -92,6 +94,8 @@ void OnlineUserSearch::search()
m_search_request = CurrentUser::get()->requestUserSearch(m_search_string);
else
m_fake_refresh = true;
m_user_list_widget->clear();
m_user_list_widget->addItem("spacer", L"");
m_user_list_widget->addItem("loading", Messages::searching());
m_back_widget->setDeactivated();
m_search_box_widget->setDeactivated();
@ -132,9 +136,7 @@ void OnlineUserSearch::init()
} // init
// ----------------------------------------------------------------------------
void OnlineUserSearch::eventCallback( GUIEngine::Widget* widget,
const std::string& name,
const int playerID)
void OnlineUserSearch::eventCallback( GUIEngine::Widget* widget, const std::string& name, const int playerID)
{
if (name == m_back_widget->m_properties[GUIEngine::PROP_ID])
{
@ -143,7 +145,7 @@ void OnlineUserSearch::eventCallback( GUIEngine::Widget* widget,
else if (name == m_user_list_widget->m_properties[GUIEngine::PROP_ID])
{
m_selected_index = m_user_list_widget->getSelectionID();
//new UserInfoDialog(m_users[m_selected_index]); FIXME
new UserInfoDialog(m_users[m_selected_index]);
}
else if (name == m_search_button_widget->m_properties[GUIEngine::PROP_ID])
{

View File

@ -20,7 +20,7 @@
#include "guiengine/screen.hpp"
#include "guiengine/widgets.hpp"
#include "online/user.hpp"
#include "online/profile.hpp"
#include "online/request.hpp"
#include "utils/ptr_vector.hpp"
@ -49,7 +49,7 @@ private:
int m_selected_index;
irr::core::stringw m_search_string;
irr::core::stringw m_last_search_string;
PtrVector<Online::User> m_users;
Online::Profile::IDList m_users;
const Online::XMLRequest * m_search_request;
bool m_fake_refresh;

View File

@ -169,6 +169,8 @@ void RaceGUI::renderGlobal(float dt)
{
drawGlobalReadySetGo();
}
if(world->getPhase() == World::GOAL_PHASE)
drawGlobalGoal();
// Timer etc. are not displayed unless the game is actually started.
if(!world->isRacePhase()) return;
@ -264,14 +266,12 @@ void RaceGUI::drawScores()
irr_driver->getVideoDriver()->draw2DImage(m_marker, position, source,
NULL, NULL, true);
core::stringw score = StringUtils::toWString(soccerWorld->getScore(i));
int stringWidth =
GUIEngine::getFont()->getDimension(score.c_str()).Width;
int stringHeight =
int string_height =
GUIEngine::getFont()->getDimension(score.c_str()).Height;
core::recti pos(position.UpperLeftCorner.X + 5,
position.LowerRightCorner.Y + offsetY,
position.LowerRightCorner.X,
position.LowerRightCorner.Y + stringHeight);
position.LowerRightCorner.Y + string_height);
font->draw(score.c_str(),pos,color);
offsetX += position.LowerRightCorner.X;

View File

@ -69,6 +69,8 @@ RaceGUIBase::RaceGUIBase()
m_string_set = _("Set!");
//I18N: as in "ready, set, go", shown at the beginning of the race
m_string_go = _("Go!");
//Shown when a goal is scored
m_string_goal = "GOAL!";
// Make the two materials permanent (in case that they are not listed
// in the textures/materials.xml file).
m_music_icon = material_manager->getMaterial("notes.png",
@ -675,6 +677,16 @@ void RaceGUIBase::drawGlobalMusicDescription()
NULL, NULL, true);
} // drawGlobalMusicDescription
//-----------------------------------------------------------------------------
void RaceGUIBase::drawGlobalGoal(){
static video::SColor color = video::SColor(255, 255, 255, 255);
core::rect<s32> pos(UserConfigParams::m_width>>1,
UserConfigParams::m_height>>1,
UserConfigParams::m_width>>1,
UserConfigParams::m_height>>1);
gui::IGUIFont* font = GUIEngine::getTitleFont();
font->draw(m_string_goal.c_str(), pos, color, true, true);
}
// ----------------------------------------------------------------------------
/** Draws the ready-set-go message on the screen.
*/

View File

@ -127,7 +127,7 @@ private:
Material *m_music_icon;
/** Translated strings 'ready', 'set', 'go'. */
core::stringw m_string_ready, m_string_set, m_string_go;
core::stringw m_string_ready, m_string_set, m_string_go, m_string_goal;
/** Translated string 'Top %d' displayed every frame. */
core::stringw m_string_top;
@ -199,6 +199,7 @@ protected:
const core::vector2df &scaling);
void drawGlobalMusicDescription();
void drawGlobalReadySetGo ();
void drawGlobalGoal ();
void drawPlungerInFace(const Camera *camera, float dt);
/** Instructs the base gui to ignore unimportant messages (like
* item messages).

View File

@ -30,7 +30,6 @@
#include "main_loop.hpp"
#include "modes/profile_world.hpp"
#include "modes/world.hpp"
#include "online/user.hpp"
#include "utils/translation.hpp"
#include "utils/log.hpp"
@ -102,8 +101,7 @@ void StateManager::updateActivePlayerIDs()
// ----------------------------------------------------------------------------
int StateManager::createActivePlayer(PlayerProfile *profile, InputDevice *device,
Online::User* user)
int StateManager::createActivePlayer(PlayerProfile *profile, InputDevice *device, Online::Profile* user)
{
ActivePlayer *p;
int i;
@ -255,7 +253,7 @@ void StateManager::onStackEmptied()
StateManager::ActivePlayer::ActivePlayer(PlayerProfile* player,
InputDevice *device,
Online::User* user)
Online::Profile* user)
{
#ifdef DEBUG
m_magic_number = 0xAC1EF1AE;

View File

@ -36,7 +36,7 @@ class InputDevice;
struct Input;
namespace Online
{
class User;
class Profile;
}
namespace GUIEngine
@ -76,7 +76,7 @@ public:
{
friend class StateManager;
Online::User *m_online_user;
Online::Profile *m_online_user;
PlayerProfile *m_player;
InputDevice *m_device;
@ -86,7 +86,7 @@ public:
/** ID of this player within the list of active players */
int m_id;
ActivePlayer(PlayerProfile* player, InputDevice* device, Online::User* user);
ActivePlayer(PlayerProfile* player, InputDevice* device, Online::Profile* user);
#ifdef DEBUG
unsigned int m_magic_number;
@ -128,14 +128,14 @@ public:
void setPlayerProfile(PlayerProfile* player);
// --------------------------------------------------------------------
Online::User* getOnlineUser()
Online::Profile* getOnlineUser()
{
return m_online_user;
}
// --------------------------------------------------------------------
/** Call to change the identity of this player (useful when player is
* selecting his identity) */
void setOnlineUser(Online::User* user) { m_online_user = user; }
void setOnlineUser(Online::Profile* user) { m_online_user = user; }
// --------------------------------------------------------------------
/** ID of this player within the list of active players */
@ -193,7 +193,7 @@ public:
*/
const PlayerProfile* getActivePlayerProfile(const int id);
int createActivePlayer(PlayerProfile *profile, InputDevice *device, Online::User* use);
int createActivePlayer(PlayerProfile *profile, InputDevice *device, Online::Profile* use);
void removeActivePlayer(int id);
int activePlayerCount();