Leviathan  0.8.0.0
Leviathan game engine
Leviathan::SyncedVariables Class Reference

Class that synchronizes some key variables with another instance. More...

#include <SyncedVariables.h>

+ Inheritance diagram for Leviathan::SyncedVariables:

Classes

struct  SendDataSyncAllStruct
 

Public Member Functions

DLLEXPORT SyncedVariables (NetworkHandler *owner, NETWORKED_TYPE type, NetworkInterface *handlinginterface)
 Construct an instance that must be owned by a NetworkHandler. More...
 
DLLEXPORT ~SyncedVariables ()
 The destructor doesn't force other instances to remove their variables. More...
 
DLLEXPORT bool AddNewVariable (std::shared_ptr< SyncedValue > newvalue)
 Adds a new variable to be synced. More...
 
DLLEXPORT bool HandleSyncRequests (std::shared_ptr< NetworkRequest > request, Connection *connection)
 Handles all requests aimed at the synchronized variables. More...
 
DLLEXPORT bool HandleResponseOnlySync (std::shared_ptr< NetworkResponse > response, Connection *connection)
 Handles a response only packet, if it is a sync packet. More...
 
DLLEXPORT void PrepareForFullSync ()
 Call before requesting full value sync. More...
 
DLLEXPORT bool IsSyncDone ()
 Returns true if we have received a sync complete notification. More...
 
DLLEXPORT bool IsVariableNameUsed (Lock &guard, const std::string &name)
 Checks whether a name is already in use. More...
 
DLLEXPORT FORCE_INLINE bool IsVariableNameUsed (const std::string &name)
 Short version for IsVariableNameUsed. More...
 
DLLEXPORT void SetExpectedNumberOfVariablesReceived (size_t amount)
 Sets the expected number of variables received. More...
 
- Public Member Functions inherited from Leviathan::BaseNotifierAll
 BaseNotifierAll ()
 
 ~BaseNotifierAll ()
 
- Public Member Functions inherited from Leviathan::BaseNotifier< BaseNotifierAll, BaseNotifiableAll >
 BaseNotifier (BaseNotifierAll *ourptr)
 
virtual ~BaseNotifier ()
 
void ReleaseChildHooks ()
 Release function that unhooks all child objects. More...
 
void ReleaseChildHooks (Lock &guard)
 
FORCE_INLINE bool ConnectToNotifiable (BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *child)
 Connects this to a notifiable object for holding a reference to it. More...
 
bool ConnectToNotifiable (Lock &guard, BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *child, Lock &childlock)
 The actual implementation of ConnecToNotifiable. More...
 
virtual void NotifyAll (Lock &guard)
 Notifies the children about something. More...
 
bool UnConnectFromNotifiable (Lock &guard, BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *unhookfrom)
 Disconnects from previously connected notifiable. More...
 
FORCE_INLINE bool UnConnectFromNotifiable (BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *child)
 
bool UnConnectFromNotifiable (int id)
 Searches the connected notifiable objects and calls the above function with it's pointer. More...
 
bool IsConnectedTo (BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *check, Lock &guard)
 Actual implementation of this method. More...
 
FORCE_INLINE bool IsConnectedTo (BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *check)
 Returns true when the specified object is already connected. More...
 
void _OnUnhookNotifiable (Lock &guard, BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *childtoremove, Lock &childlock)
 
void _OnHookNotifiable (Lock &guard, BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *child, Lock &childlock)
 
BaseNotifierAllGetActualPointerToNotifierObject ()
 Gets the internal pointer to the actual object. More...
 
virtual void OnNotified (Lock &ownlock, BaseNotifiableAll *child, Lock &childlock)
 Called when one of our children notifies us about something. More...
 
- Public Member Functions inherited from Leviathan::ThreadSafeGeneric< MutexType >
DLLEXPORT ThreadSafeGeneric ()
 
DLLEXPORT ~ThreadSafeGeneric ()
 
FORCE_INLINE void VerifyLock (RecursiveLock &guard) const
 
FORCE_INLINE void VerifyLock (Lock &lockit) const
 

Protected Member Functions

void _NotifyUpdatedValue (const SyncedValue *const valtosync, int useid=-1)
 Sends update notifications about a variable. More...
 
void _NotifyUpdatedValue (Lock &guard, const SyncedValue *const valtosync, int useid=-1)
 
void _NotifyUpdatedValue (Lock &guard, SyncedResource *valtosync, int useid=-1)
 
std::shared_ptr< SentNetworkThing_SendValueToSingleReceiver (Connection *unsafeptr, const SyncedValue *const valtosync)
 
std::shared_ptr< SentNetworkThing_SendValueToSingleReceiver (Connection *unsafeptr, SyncedResource *valtosync)
 
void _UpdateFromNetworkReceive (ResponseSyncValData *datatouse, Lock &guard)
 
void _IWasUpdated (SyncedResource *me)
 SyncedResource calls this when it is updated. More...
 
void _OnSyncedResourceReceived (const std::string &name, sf::Packet &packetdata)
 This is called when an update to a SyncedResource is received through the network. More...
 
void _UpdateReceiveCount (const std::string &nameofthing)
 Updates the number of synced values received during SyncDone. More...
 
- Protected Member Functions inherited from Leviathan::BaseNotifier< BaseNotifierAll, BaseNotifiableAll >
virtual void _OnNotifiableConnected (Lock &guard, BaseNotifiableAll *childadded, Lock &childlock)
 
virtual void _OnNotifiableDisconnected (Lock &guard, BaseNotifiableAll *childtoremove, Lock &childlock)
 

Static Protected Member Functions

static void _RunSendAllVariablesTask (Connection *connection, SyncedVariables *instance, std::shared_ptr< SendDataSyncAllStruct > data)
 

Protected Attributes

NetworkInterfaceCorrespondingInterface
 
NetworkHandlerOwner
 
bool IsHost
 
bool SyncDone = false
 Set when sync complete packet is received. More...
 
std::vector< std::unique_ptr< std::string > > ValueNamesUpdated
 
size_t ExpectedThingCount = 0
 The expected number of variables to receive during SyncDone is false. More...
 
size_t ActualGotThingCount = 0
 The number of variables received thus far. More...
 
std::vector< std::shared_ptr< SyncedValue > > ToSyncValues
 Contains the values that are to be synced. More...
 
- Protected Attributes inherited from Leviathan::BaseNotifier< BaseNotifierAll, BaseNotifiableAll >
BaseNotifierAllPointerToOurNotifier
 Stores a pointer to the object that is inherited from this. More...
 
std::vector< BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *> ConnectedChildren
 Vector of other objects that this is connected to. More...
 
- Protected Attributes inherited from Leviathan::ThreadSafeGeneric< MutexType >
MutexType ObjectsLock
 

Additional Inherited Members

- Public Types inherited from Leviathan::ThreadSafeGeneric< MutexType >
using LockT = typename LockTypeResolver< MutexType >::LType
 

Detailed Description

Class that synchronizes some key variables with another instance.

By default this doesn't synchronize anything. You will have to manually add variables

Todo:

Events

Add function to be able to check if sync completed successfully

Definition at line 67 of file SyncedVariables.h.

Constructor & Destructor Documentation

◆ SyncedVariables()

DLLEXPORT Leviathan::SyncedVariables::SyncedVariables ( NetworkHandler owner,
NETWORKED_TYPE  type,
NetworkInterface handlinginterface 
)

Construct an instance that must be owned by a NetworkHandler.

Definition at line 16 of file SyncedVariables.cpp.

17  :
18  CorrespondingInterface(handlinginterface), Owner(owner),
20 {
21 
22 }
NetworkInterface * CorrespondingInterface

◆ ~SyncedVariables()

DLLEXPORT Leviathan::SyncedVariables::~SyncedVariables ( )

The destructor doesn't force other instances to remove their variables.

Definition at line 24 of file SyncedVariables.cpp.

24  {
25 
27 }
void ReleaseChildHooks()
Release function that unhooks all child objects.
Definition: BaseNotifier.h:17

Member Function Documentation

◆ _IWasUpdated()

void Leviathan::SyncedVariables::_IWasUpdated ( SyncedResource me)
protected

SyncedResource calls this when it is updated.

◆ _NotifyUpdatedValue() [1/3]

void Leviathan::SyncedVariables::_NotifyUpdatedValue ( const SyncedValue *const  valtosync,
int  useid = -1 
)
inlineprotected

Sends update notifications about a variable.

Definition at line 129 of file SyncedVariables.h.

129  {
130 
131  GUARD_LOCK();
132  _NotifyUpdatedValue(guard, valtosync, useid);
133  }
void _NotifyUpdatedValue(const SyncedValue *const valtosync, int useid=-1)
Sends update notifications about a variable.
#define GUARD_LOCK()
Definition: ThreadSafe.h:111

◆ _NotifyUpdatedValue() [2/3]

void SyncedVariables::_NotifyUpdatedValue ( Lock guard,
const SyncedValue *const  valtosync,
int  useid = -1 
)
protected

Definition at line 301 of file SyncedVariables.cpp.

303 {
304  // Create an update packet //
305 
306  auto tmpresponse = std::make_shared<ResponseSyncValData>(useid,
307  *valtosync->GetVariableAccess());
308 
309  const auto& connections = Owner->GetInterface()->GetClientConnections();
310 
311  // Send it //
312  for(auto& Connection : connections){
313 
314  // Send to connection //
316  }
317 }
virtual DLLEXPORT std::vector< std::shared_ptr< Connection > > & GetClientConnections()=0
If this is a server returns all the clients.
DLLEXPORT std::shared_ptr< SentRequest > SendPacketToConnection(const std::shared_ptr< NetworkRequest > &request, RECEIVE_GUARANTEE guarantee)
Definition: Connection.cpp:139
NetworkInterface * GetInterface()
Returns interface object. Type depends on AppType.
DLLEXPORT NamedVariableList * GetVariableAccess() const
Gets a direct access to the variables.
Class that handles a single connection to another instance.
Definition: Connection.h:105

◆ _NotifyUpdatedValue() [3/3]

void Leviathan::SyncedVariables::_NotifyUpdatedValue ( Lock guard,
SyncedResource valtosync,
int  useid = -1 
)
protected

Definition at line 319 of file SyncedVariables.cpp.

321 {
322  // Only update if we are a host //
323  if(!IsHost)
324  return;
325 
326  // Serialize it to a packet //
327  sf::Packet packet;
328 
329  valtosync->AddDataToPacket(guard, packet);
330 
331  auto tmpresponse = std::make_shared<ResponseSyncResourceData>(0,
332  std::string(reinterpret_cast<const char*>(packet.getData()), packet.getDataSize()));
333 
334  const auto& connections = Owner->GetInterface()->GetClientConnections();
335 
336  // Send it //
337  for (auto& Connection : connections) {
338 
339  // Send to connection //
341  }
342 }
virtual DLLEXPORT std::vector< std::shared_ptr< Connection > > & GetClientConnections()=0
If this is a server returns all the clients.
DLLEXPORT std::shared_ptr< SentRequest > SendPacketToConnection(const std::shared_ptr< NetworkRequest > &request, RECEIVE_GUARANTEE guarantee)
Definition: Connection.cpp:139
virtual DLLEXPORT void AddDataToPacket(Lock &guard, sf::Packet &packet)
Serializes the name to a packet.
NetworkInterface * GetInterface()
Returns interface object. Type depends on AppType.
Class that handles a single connection to another instance.
Definition: Connection.h:105

◆ _OnSyncedResourceReceived()

void Leviathan::SyncedVariables::_OnSyncedResourceReceived ( const std::string &  name,
sf::Packet &  packetdata 
)
protected

This is called when an update to a SyncedResource is received through the network.

Definition at line 364 of file SyncedVariables.cpp.

366 {
367  GUARD_LOCK();
368 
369  // Search through our SyncedResources //
370  for(size_t i = 0; i < ConnectedChildren.size(); i++){
371  // Check does it match the name //
372  auto tmpvar = static_cast<SyncedResource*>(
373  ConnectedChildren[i]->GetActualPointerToNotifiableObject());
374 
375  if(tmpvar->Name == name){
376 
377  // Unlock to allow BaseNotifiable to lock us //
378  guard.unlock();
379 
380  // It is this //
381  tmpvar->UpdateDataFromPacket(packetdata);
382 
383  guard.lock();
384 
385  // Do some updating if we are doing a full sync //
386  if(!SyncDone){
387 
388  _UpdateReceiveCount(name);
389  }
390  return;
391  }
392  }
393  Logger::Get()->Warning("SyncedVariables: synced resource with the name \""+name+"\" was not found/updated");
394 }
virtual DLLEXPORT bool UpdateDataFromPacket(Lock &guard, sf::Packet &packet)
Assigns data from a packet to this resource.
void _UpdateReceiveCount(const std::string &nameofthing)
Updates the number of synced values received during SyncDone.
DLLEXPORT void Warning(const std::string &data) override
Definition: Logger.cpp:190
Base class for all values that are to be automatically synced between clients.
static DLLEXPORT Logger * Get()
Definition: Logger.cpp:106
bool SyncDone
Set when sync complete packet is received.
std::vector< BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *> ConnectedChildren
Vector of other objects that this is connected to.
Definition: BaseNotifier.h:99
#define GUARD_LOCK()
Definition: ThreadSafe.h:111

◆ _RunSendAllVariablesTask()

void SyncedVariables::_RunSendAllVariablesTask ( Connection connection,
SyncedVariables instance,
std::shared_ptr< SendDataSyncAllStruct data 
)
staticprotected

Definition at line 55 of file SyncedVariables.cpp.

57 {
58  // Get the loop count //
59  // Fetch our object //
60  std::shared_ptr<QueuedTask> threadspecific =
62 
63  auto tmpptr =
64  dynamic_cast<RepeatCountedDelayedTask*>(
65  threadspecific.get());
66 
67  LEVIATHAN_ASSERT(tmpptr != NULL,
68  "this is not what I wanted, passed wrong task "
69  "object to task");
70 
71  // Get the value //
72  size_t curpos = tmpptr->GetRepeatCount();
73 
74  GUARD_LOCK_OTHER(instance);
75 
76  if(curpos >= instance->ToSyncValues.size() && curpos >=
77  instance->ConnectedChildren.size())
78  {
79 
80  Logger::Get()->Error("SyncedVariables: queued task "
81  "trying to sync variable that is out of vector range");
82  return;
83  }
84 
85  // Sync the value //
86  if(curpos < instance->ToSyncValues.size()){
87  const SyncedValue* valtosend =
88  instance->ToSyncValues[curpos].get();
89 
90  // Send it //
91  data->SentThings.push_back(
92  instance->_SendValueToSingleReceiver(connection,
93  valtosend));
94  }
95 
96  // Sync the resource //
97  if(curpos < instance->ConnectedChildren.size()){
98 
99  auto tmpvar = static_cast<SyncedResource*>(
100  instance->ConnectedChildren[curpos]->
101  GetActualPointerToNotifiableObject());
102 
103  // Send it //
104  data->SentThings.push_back(
105  instance->_SendValueToSingleReceiver(
106  connection, tmpvar));
107  }
108 
109  // Check is this the last one //
110  if(tmpptr->IsThisLastRepeat()){
111  // Set as done //
112  data->SentAll = true;
113  }
114 }
std::shared_ptr< QueuedTask > QuickTaskAccess
Definition: TaskThread.h:18
Encapsulates a function that is ran after a time period and repeated certain amount.
Definition: QueuedTask.h:238
Class that encapsulates a value that can be used for syncing.
#define GUARD_LOCK_OTHER(x)
Definition: ThreadSafe.h:124
#define LEVIATHAN_ASSERT(x, msg)
Definition: Define.h:98
Base class for all values that are to be automatically synced between clients.
static DLLEXPORT Logger * Get()
Definition: Logger.cpp:106
std::vector< std::shared_ptr< SyncedValue > > ToSyncValues
Contains the values that are to be synced.
static DLLEXPORT ThreadSpecificData * GetThreadSpecificThreadObject()
Returns thread specific data about QueuedTask and TaskThread object.
Definition: TaskThread.cpp:171
DLLEXPORT void Error(const std::string &data) override
Definition: Logger.cpp:177
std::vector< BaseNotifiable< ParentType, ChildType > * > ConnectedChildren
Vector of other objects that this is connected to.
Definition: BaseNotifier.h:99
std::shared_ptr< SentNetworkThing > _SendValueToSingleReceiver(Connection *unsafeptr, const SyncedValue *const valtosync)

◆ _SendValueToSingleReceiver() [1/2]

shared_ptr< SentNetworkThing > Leviathan::SyncedVariables::_SendValueToSingleReceiver ( Connection unsafeptr,
const SyncedValue *const  valtosync 
)
protected

Definition at line 344 of file SyncedVariables.cpp.

346 {
347  // Create an update packet //
348  return unsafeptr->SendPacketToConnection(std::make_shared<ResponseSyncValData>(
350 }
DLLEXPORT std::shared_ptr< SentRequest > SendPacketToConnection(const std::shared_ptr< NetworkRequest > &request, RECEIVE_GUARANTEE guarantee)
Definition: Connection.cpp:139
DLLEXPORT NamedVariableList * GetVariableAccess() const
Gets a direct access to the variables.

◆ _SendValueToSingleReceiver() [2/2]

shared_ptr< SentNetworkThing > Leviathan::SyncedVariables::_SendValueToSingleReceiver ( Connection unsafeptr,
SyncedResource valtosync 
)
protected

Definition at line 352 of file SyncedVariables.cpp.

354 {
355  sf::Packet packet;
356 
357  valtosync->AddDataToPacket(packet);
358 
359  return unsafeptr->SendPacketToConnection(std::make_shared<ResponseSyncResourceData>(0,
360  std::string(reinterpret_cast<const char*>(packet.getData()),
361  packet.getDataSize())), RECEIVE_GUARANTEE::Critical);
362 }
DLLEXPORT std::shared_ptr< SentRequest > SendPacketToConnection(const std::shared_ptr< NetworkRequest > &request, RECEIVE_GUARANTEE guarantee)
Definition: Connection.cpp:139
virtual DLLEXPORT void AddDataToPacket(Lock &guard, sf::Packet &packet)
Serializes the name to a packet.

◆ _UpdateFromNetworkReceive()

void Leviathan::SyncedVariables::_UpdateFromNetworkReceive ( ResponseSyncValData *  datatouse,
Lock guard 
)
protected

Definition at line 396 of file SyncedVariables.cpp.

398 {
400  "Hosts cannot received value updates by others, use server side commands");
401 
402  // Get the data from it //
403  const NamedVariableList& data = datatouse->SyncValueData;
404 
405  // Match a variable with the name //
406  for(size_t i = 0; i < ToSyncValues.size(); i++){
407 
408  NamedVariableList* tmpaccess = ToSyncValues[i]->GetVariableAccess();
409 
410  if(tmpaccess->CompareName(data.GetName())){
411 
412  // Update the value //
413  if(*tmpaccess == data){
414 
415  Logger::Get()->Info("SyncedVariables: no need to update variable "+ data.GetName());
416  return;
417  }
418 
419  // Set it //
420  *tmpaccess = data;
421 
422  // Do some updating if we are doing a full sync //
423  if(!SyncDone){
424 
426  }
427  }
428  }
429 
430  // Add a new variable //
431  Logger::Get()->Info("SyncedVariables: adding a new variable, because value for it was received, "+
432  data.GetName());
433 
434  ToSyncValues.push_back(shared_ptr<SyncedValue>(new SyncedValue(
435  new NamedVariableList(data), true, true)));
436 
437  ToSyncValues.back()->_MasterYouCalled(this);
438 }
hosts one or more VariableBlocks keeping only one name for all of them
Definition: NamedVars.h:27
DLLEXPORT void Info(const std::string &data) override
Definition: Logger.cpp:164
void _UpdateReceiveCount(const std::string &nameofthing)
Updates the number of synced values received during SyncDone.
DLLEXPORT bool CompareName(const std::string &name) const
Definition: NamedVars.cpp:485
Class that encapsulates a value that can be used for syncing.
#define LEVIATHAN_ASSERT(x, msg)
Definition: Define.h:98
static DLLEXPORT Logger * Get()
Definition: Logger.cpp:106
std::vector< std::shared_ptr< SyncedValue > > ToSyncValues
Contains the values that are to be synced.
bool SyncDone
Set when sync complete packet is received.
std::string GetName() const
Definition: NamedVars.h:139

◆ _UpdateReceiveCount()

void Leviathan::SyncedVariables::_UpdateReceiveCount ( const std::string &  nameofthing)
protected

Updates the number of synced values received during SyncDone.

Definition at line 452 of file SyncedVariables.cpp.

452  {
453  // Check is it already updated (values can update while a sync is being done) //
454  for(size_t i = 0; i < ValueNamesUpdated.size(); i++){
455 
456  if(*ValueNamesUpdated[i] == nameofthing)
457  return;
458  }
459 
460  // Add it //
461  ValueNamesUpdated.push_back(unique_ptr<std::string>(new std::string(nameofthing)));
462 
463  // Increment count and notify //
465 
466  auto iface = Owner->GetClientInterface();
467  if(iface)
469 }
DLLEXPORT void OnUpdateFullSynchronizationState(size_t variablesgot, size_t expectedvariables)
Called directly by SyncedVariables to update the status string.
NetworkClientInterface * GetClientInterface()
std::vector< std::unique_ptr< std::string > > ValueNamesUpdated
size_t ActualGotThingCount
The number of variables received thus far.
size_t ExpectedThingCount
The expected number of variables to receive during SyncDone is false.

◆ AddNewVariable()

DLLEXPORT bool Leviathan::SyncedVariables::AddNewVariable ( std::shared_ptr< SyncedValue newvalue)

Adds a new variable to be synced.

The variable is automatically then broadcasted to all the connected instances (or the server if this instance is a client)

Note
(Verify this, might be false) The variable needs to be added on both the client and the server for this to work. Not doing this may cause the client to get kicked
Returns
The value is true if it was added
See also
SyncedValue

Definition at line 29 of file SyncedVariables.cpp.

29  {
30  GUARD_LOCK();
31 
32  // Check do we already have a variable with that name //
33  if(IsVariableNameUsed(guard, newvalue->GetVariableAccess()->GetName())){
34  // Shouldn't add another with the same name //
35  return false;
36  }
37 
38  // Add it //
39  Logger::Get()->Info("SyncedVariables: added a new value, "+
40  newvalue->GetVariableAccess()->GetName());
41  ToSyncValues.push_back(newvalue);
42 
43  // Notify update //
44  _NotifyUpdatedValue(guard, newvalue.get());
45 
46  return true;
47 }
DLLEXPORT bool IsVariableNameUsed(Lock &guard, const std::string &name)
Checks whether a name is already in use.
DLLEXPORT void Info(const std::string &data) override
Definition: Logger.cpp:164
static DLLEXPORT Logger * Get()
Definition: Logger.cpp:106
std::vector< std::shared_ptr< SyncedValue > > ToSyncValues
Contains the values that are to be synced.
void _NotifyUpdatedValue(const SyncedValue *const valtosync, int useid=-1)
Sends update notifications about a variable.
#define GUARD_LOCK()
Definition: ThreadSafe.h:111

◆ HandleResponseOnlySync()

DLLEXPORT bool Leviathan::SyncedVariables::HandleResponseOnlySync ( std::shared_ptr< NetworkResponse response,
Connection connection 
)

Handles a response only packet, if it is a sync packet.

Note
This will most likely only receive variable updated notifications

Definition at line 207 of file SyncedVariables.cpp.

209 {
210  // Switch on the type and see if we can do something with it //
211  switch(response->GetType()){
213  {
214  // We got some data that requires syncing //
215  if(IsHost){
216 
217  Logger::Get()->Warning("SyncedVariables: HandleResponseOnlySync: we are a host "
218  "and got update data, ignoring (use server commands to change "
219  "data on the server)");
220  return true;
221  }
222 
223  // Update the wanted value //
224  auto* tmpptr = static_cast<ResponseSyncValData*>(response.get());
225 
226  // Call updating function //
227  GUARD_LOCK();
228  _UpdateFromNetworkReceive(tmpptr, guard);
229 
230  return true;
231  }
233  {
234  // We got custom sync data //
235  if(IsHost){
236 
237  Logger::Get()->Warning("SyncedVariables: HandleResponseOnlySync: we are a "
238  "host and got update data, ignoring (use server commands to change "
239  "data on the server)");
240  return true;
241  }
242 
243  auto* tmpptr = static_cast<ResponseSyncResourceData*>(response.get());
244 
245  // Create the packet from the data //
246  sf::Packet ourdatapacket;
247  ourdatapacket.append(tmpptr->OurCustomData.c_str(), tmpptr->OurCustomData.size());
248 
249  const std::string lookforname =
251 
252  // Update the one matching the name //
253  _OnSyncedResourceReceived(lookforname, ourdatapacket);
254  return true;
255  }
257  {
258  // Check if it succeeded or if it failed //
259  auto* dataptr = static_cast<ResponseSyncDataEnd*>(response.get());
260 
261  if(dataptr->Succeeded){
262 
263  Logger::Get()->Info("SyncedVariables: variable sync reported as successful "
264  "by the host");
265  } else {
266 
267  Logger::Get()->Info("SyncedVariables: variable sync reported as FAILED "
268  "by the host");
269 
270  DEBUG_BREAK;
271  // Close connection //
272  connection->SendCloseConnectionPacket();
273  }
274 
275  // Mark sync as ended //
276  SyncDone = true;
277 
278  return true;
279  }
280  default:
281  return false;
282  }
283 
284  // Could not process //
285  return false;
286 }
DLLEXPORT void Info(const std::string &data) override
Definition: Logger.cpp:164
DLLEXPORT void SendCloseConnectionPacket()
Sends a packet that tells the other side to disconnect.
Definition: Connection.cpp:260
Sends a update/new SyncedValue.
DLLEXPORT void Warning(const std::string &data) override
Definition: Logger.cpp:190
static DLLEXPORT std::string GetSyncedResourceNameFromPacket(sf::Packet &packet)
Gets a name from packet leaving only the variable data there.
void _OnSyncedResourceReceived(const std::string &name, sf::Packet &packetdata)
This is called when an update to a SyncedResource is received through the network.
Contains SyncedResource update notification.
static DLLEXPORT Logger * Get()
Definition: Logger.cpp:106
bool SyncDone
Set when sync complete packet is received.
void _UpdateFromNetworkReceive(ResponseSyncValData *datatouse, Lock &guard)
#define GUARD_LOCK()
Definition: ThreadSafe.h:111

◆ HandleSyncRequests()

DLLEXPORT bool Leviathan::SyncedVariables::HandleSyncRequests ( std::shared_ptr< NetworkRequest request,
Connection connection 
)

Handles all requests aimed at the synchronized variables.

Definition at line 116 of file SyncedVariables.cpp.

118 {
119  // Switch on the type and see if we can do something with it //
120  switch(request->GetType()){
122  {
123  // Notify that we accepted this //
124  // Send the number of values as the string parameter //
125  connection->SendPacketToConnection(
126  std::make_shared<ResponseServerAllow>(request->GetIDForResponse(),
128  ToSyncValues.size() + ConnectedChildren.size())),
130 
131  auto taskdata = std::make_shared<SendDataSyncAllStruct>();
132 
133  // Prepare a task that sends all of the values //
134  Engine::Get()->GetThreadingManager()->QueueTask(std::make_shared<
136  [=]() -> void
137  {
138  _RunSendAllVariablesTask(connection, this, taskdata);
139 
140 
141 
142  }, MillisecondDuration(50),
143  MillisecondDuration(10), (int)max(ToSyncValues.size(),
144  ConnectedChildren.size())));
145 
146  // Queue a finish checking task //
148  std::make_shared<RepeatingDelayedTask>(
149  [=]() -> void {
150 
151  // Check is it done //
152  if(!taskdata->SentAll)
153  return;
154 
155  // See if all have been sent //
156  for(size_t i = 0; i < taskdata->SentThings.size(); i++){
157 
158  if(!taskdata->SentThings[i]->IsFinalized())
159  return;
160  }
161 
162  // Stop after this loop //
163  // Fetch our object //
164  std::shared_ptr<QueuedTask> threadspecific =
166  auto tmpptr =
167  dynamic_cast<RepeatingDelayedTask*>(threadspecific.get());
168 
169  // Disable the repeating //
170  tmpptr->SetRepeatStatus(false);
171 
172  bool succeeded = true;
173 
174  // Check did some fail //
175  for(size_t i = 0; i < taskdata->SentThings.size(); i++){
176 
177  if(!taskdata->SentThings[i]->GetStatus()){
178  // Failed to send it //
179 
180  succeeded = false;
181  break;
182  }
183  }
184 
185  connection->SendPacketToConnection(
186  std::make_shared<ResponseSyncDataEnd>(0, succeeded),
188 
190 
191  return true;
192  }
194  {
195  // Send the value //
196  DEBUG_BREAK;
197  return true;
198  }
199  default:
200  return false;
201  }
202 
203  // Could not process //
204  return false;
205 }
std::chrono::duration< int64_t, std::milli > MillisecondDuration
Definition: TimeIncludes.h:13
DLLEXPORT std::shared_ptr< SentRequest > SendPacketToConnection(const std::shared_ptr< NetworkRequest > &request, RECEIVE_GUARANTEE guarantee)
Definition: Connection.cpp:139
DLLEXPORT void QueueTask(std::shared_ptr< QueuedTask > task)
Adds a task to the queue.
std::shared_ptr< QueuedTask > QuickTaskAccess
Definition: TaskThread.h:18
Server has accepted the request and will handle it soon.
Encapsulates a function that is ran after a time period and repeated certain amount.
Definition: QueuedTask.h:238
Encapsulates a function that is ran after a time period.
Definition: QueuedTask.h:160
static std::string ToString(const T &val)
Definition: Convert.h:72
static void _RunSendAllVariablesTask(Connection *connection, SyncedVariables *instance, std::shared_ptr< SendDataSyncAllStruct > data)
std::vector< std::shared_ptr< SyncedValue > > ToSyncValues
Contains the values that are to be synced.
DLLEXPORT void SetRepeatStatus(bool newvalue)
Sets the variable ShouldRunAgain to newvalue.
Definition: QueuedTask.cpp:144
static DLLEXPORT Engine * Get()
Definition: Engine.cpp:85
static DLLEXPORT ThreadSpecificData * GetThreadSpecificThreadObject()
Returns thread specific data about QueuedTask and TaskThread object.
Definition: TaskThread.cpp:171
std::vector< BaseNotifiable< BaseNotifierAll, BaseNotifiableAll > *> ConnectedChildren
Vector of other objects that this is connected to.
Definition: BaseNotifier.h:99
ThreadingManager * GetThreadingManager()
Definition: Engine.h:217

◆ IsSyncDone()

DLLEXPORT bool Leviathan::SyncedVariables::IsSyncDone ( )

Returns true if we have received a sync complete notification.

See also
PrepareForFullSync

Definition at line 448 of file SyncedVariables.cpp.

448  {
449  return SyncDone;
450 }
bool SyncDone
Set when sync complete packet is received.

◆ IsVariableNameUsed() [1/2]

DLLEXPORT bool Leviathan::SyncedVariables::IsVariableNameUsed ( Lock guard,
const std::string &  name 
)

Checks whether a name is already in use.

Definition at line 288 of file SyncedVariables.cpp.

290 {
291  // Loop all and compare their names //
292  for(size_t i = 0; i < ToSyncValues.size(); i++){
293  if(ToSyncValues[i]->GetVariableAccess()->CompareName(name))
294  return true;
295  }
296 
297  // Didn't match any names //
298  return false;
299 }
std::vector< std::shared_ptr< SyncedValue > > ToSyncValues
Contains the values that are to be synced.

◆ IsVariableNameUsed() [2/2]

DLLEXPORT FORCE_INLINE bool Leviathan::SyncedVariables::IsVariableNameUsed ( const std::string &  name)
inline

Short version for IsVariableNameUsed.

Definition at line 114 of file SyncedVariables.h.

114  {
115  GUARD_LOCK();
116  return IsVariableNameUsed(guard, name);
117  }
DLLEXPORT bool IsVariableNameUsed(Lock &guard, const std::string &name)
Checks whether a name is already in use.
#define GUARD_LOCK()
Definition: ThreadSafe.h:111

◆ PrepareForFullSync()

DLLEXPORT void Leviathan::SyncedVariables::PrepareForFullSync ( )

Call before requesting full value sync.

Note
Without calling this IsSyncDone won't work

Definition at line 440 of file SyncedVariables.cpp.

440  {
441  // Reset some variables //
442  SyncDone = false;
443  ExpectedThingCount = 0;
444  ValueNamesUpdated.clear();
446 }
std::vector< std::unique_ptr< std::string > > ValueNamesUpdated
size_t ActualGotThingCount
The number of variables received thus far.
bool SyncDone
Set when sync complete packet is received.
size_t ExpectedThingCount
The expected number of variables to receive during SyncDone is false.

◆ SetExpectedNumberOfVariablesReceived()

DLLEXPORT void Leviathan::SyncedVariables::SetExpectedNumberOfVariablesReceived ( size_t  amount)

Sets the expected number of variables received.

Precondition
PrepareForFullSync must be called before this

This is usually called by NetworkClientInterface when it receives a response to a full sync request

Definition at line 471 of file SyncedVariables.cpp.

471  {
472  ExpectedThingCount = amount;
473 }
size_t ExpectedThingCount
The expected number of variables to receive during SyncDone is false.

Member Data Documentation

◆ ActualGotThingCount

size_t Leviathan::SyncedVariables::ActualGotThingCount = 0
protected

The number of variables received thus far.

Definition at line 187 of file SyncedVariables.h.

◆ CorrespondingInterface

NetworkInterface* Leviathan::SyncedVariables::CorrespondingInterface
protected

Interface used to ask for permission to do many things (like add new client when they request it)

Definition at line 163 of file SyncedVariables.h.

◆ ExpectedThingCount

size_t Leviathan::SyncedVariables::ExpectedThingCount = 0
protected

The expected number of variables to receive during SyncDone is false.

Definition at line 184 of file SyncedVariables.h.

◆ IsHost

bool Leviathan::SyncedVariables::IsHost
protected

Should be set to true when a server

Note
This is used to control if multiple other instances are allowed and if changed values are sent

Definition at line 172 of file SyncedVariables.h.

◆ Owner

NetworkHandler* Leviathan::SyncedVariables::Owner
protected

NetworkHandler that owns this and is used to verify Connection unsafe pointers when they actually need to be used

Definition at line 167 of file SyncedVariables.h.

◆ SyncDone

bool Leviathan::SyncedVariables::SyncDone = false
protected

Set when sync complete packet is received.

Definition at line 175 of file SyncedVariables.h.

◆ ToSyncValues

std::vector<std::shared_ptr<SyncedValue> > Leviathan::SyncedVariables::ToSyncValues
protected

Contains the values that are to be synced.

Definition at line 190 of file SyncedVariables.h.

◆ ValueNamesUpdated

std::vector<std::unique_ptr<std::string> > Leviathan::SyncedVariables::ValueNamesUpdated
protected

List of variables that have been updated while SyncDone is false

This is used to keep track of how many values have been updated

Todo:
Potentially use a map here

Definition at line 181 of file SyncedVariables.h.


The documentation for this class was generated from the following files: