aboutsummaryrefslogtreecommitdiff
path: root/src/guiKeyChangeMenu.cpp
blob: 07137d1bc9be06446cf133d567f4a4c4a65d1178 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
/*
 Minetest
 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
 Copyright (C) 2013 Ciaran Gultnieks <ciaran@ciarang.com>
 Copyright (C) 2013 teddydestodes <derkomtur@schattengang.net>

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU Lesser General Public License as published by
 the Free Software Foundation; either version 2.1 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 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public License along
 with this program; if not, write to the Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "guiKeyChangeMenu.h"
#include "debug.h"
#include "serialization.h"
#include <string>
#include <IGUICheckBox.h>
#include <IGUIEditBox.h>
#include <IGUIButton.h>
#include <IGUIStaticText.h>
#include <IGUIFont.h>
#include "settings.h"
#include <algorithm>

#include "mainmenumanager.h"  // for g_gamecallback

#define KMaxButtonPerColumns 12

extern MainGameCallback *g_gamecallback;

enum
{
	GUI_ID_BACK_BUTTON = 101, GUI_ID_ABORT_BUTTON, GUI_ID_SCROLL_BAR,
	// buttons
	GUI_ID_KEY_FORWARD_BUTTON,
	GUI_ID_KEY_BACKWARD_BUTTON,
	GUI_ID_KEY_LEFT_BUTTON,
	GUI_ID_KEY_RIGHT_BUTTON,
	GUI_ID_KEY_USE_BUTTON,
	GUI_ID_KEY_FLY_BUTTON,
	GUI_ID_KEY_FAST_BUTTON,
	GUI_ID_KEY_JUMP_BUTTON,
	GUI_ID_KEY_NOCLIP_BUTTON,
	GUI_ID_KEY_CINEMATIC_BUTTON,
	GUI_ID_KEY_CHAT_BUTTON,
	GUI_ID_KEY_CMD_BUTTON,
	GUI_ID_KEY_CONSOLE_BUTTON,
	GUI_ID_KEY_SNEAK_BUTTON,
	GUI_ID_KEY_DROP_BUTTON,
	GUI_ID_KEY_INVENTORY_BUTTON,
	GUI_ID_KEY_DUMP_BUTTON,
	GUI_ID_KEY_RANGE_BUTTON,
	GUI_ID_KEY_ZOOM_BUTTON,
	// other
	GUI_ID_CB_AUX1_DESCENDS,
	GUI_ID_CB_DOUBLETAP_JUMP,
};

GUIKeyChangeMenu::GUIKeyChangeMenu(gui::IGUIEnvironment* env,
				gui::IGUIElement* parent, s32 id, IMenuManager *menumgr) :
GUIModalMenu(env, parent, id, menumgr)
{
	shift_down = false;
	activeKey = -1;
	this->key_used_text = NULL;
	init_keys();
	for(size_t i=0; i<key_settings.size(); i++)
		this->key_used.push_back(key_settings.at(i)->key);
}

GUIKeyChangeMenu::~GUIKeyChangeMenu()
{
	removeChildren();

	for (std::vector<key_setting*>::iterator iter = key_settings.begin();
			iter != key_settings.end(); ++iter) {
		delete[] (*iter)->button_name;
		delete (*iter);
	}
	key_settings.clear();
}

void GUIKeyChangeMenu::removeChildren()
{
	const core::list<gui::IGUIElement*> &children = getChildren();
	core::list<gui::IGUIElement*> children_copy;
	for (core::list<gui::IGUIElement*>::ConstIterator i = children.begin(); i
		 != children.end(); i++)
	{
		children_copy.push_back(*i);
	}
	for (core::list<gui::IGUIElement*>::Iterator i = children_copy.begin(); i
		 != children_copy.end(); i++)
	{
		(*i)->remove();
	}
}

void GUIKeyChangeMenu::regenerateGui(v2u32 screensize)
{
	removeChildren();
	v2s32 size(620, 430);
	
	core::rect < s32 > rect(screensize.X / 2 - size.X / 2,
							screensize.Y / 2 - size.Y / 2, screensize.X / 2 + size.X / 2,
							screensize.Y / 2 + size.Y / 2);

	DesiredRect = rect;
	recalculateAbsolutePosition(false);

	v2s32 topleft(0, 0);
	
	{
		core::rect < s32 > rect(0, 0, 600, 40);
		rect += topleft + v2s32(25, 3);
		//gui::IGUIStaticText *t =
		const wchar_t *text = wgettext("Keybindings. (If this menu screws up, remove stuff from minetest.conf)");
		Environment->addStaticText(text,
								   rect, false, true, this, -1);
		delete[] text;
		//t->setTextAlignment(gui::EGUIA_CENTER, gui::EGUIA_UPPERLEFT);
	}

	// Build buttons

	v2s32 offset(25, 60);

	for(size_t i = 0; i < key_settings.size(); i++)
	{
		key_setting *k = key_settings.at(i);
		{
			core::rect < s32 > rect(0, 0, 150, 20);
			rect += topleft + v2s32(offset.X, offset.Y);
			Environment->addStaticText(k->button_name, rect, false, true, this, -1);
		}

		{
			core::rect < s32 > rect(0, 0, 100, 30);
			rect += topleft + v2s32(offset.X + 115, offset.Y - 5);
			const wchar_t *text = wgettext(k->key.name());
			k->button = Environment->addButton(rect, this, k->id, text);
			delete[] text;
		}
		if(i + 1 == KMaxButtonPerColumns)
			offset = v2s32(260, 60);
		else
			offset += v2s32(0, 25);
	}
	
	{
		s32 option_x = offset.X;
		s32 option_y = offset.Y + 5;
		u32 option_w = 180;
		{
			core::rect<s32> rect(0, 0, option_w, 30);
			rect += topleft + v2s32(option_x, option_y);
			const wchar_t *text = wgettext("\"Use\" = climb down");
			Environment->addCheckBox(g_settings->getBool("aux1_descends"), rect, this,
					GUI_ID_CB_AUX1_DESCENDS, text);
			delete[] text;
		}
		offset += v2s32(0, 25);
	}

	{
		s32 option_x = offset.X;
		s32 option_y = offset.Y + 5;
		u32 option_w = 280;
		{
			core::rect<s32> rect(0, 0, option_w, 30);
			rect += topleft + v2s32(option_x, option_y);
			const wchar_t *text = wgettext("Double tap \"jump\" to toggle fly");
			Environment->addCheckBox(g_settings->getBool("doubletap_jump"), rect, this,
					GUI_ID_CB_DOUBLETAP_JUMP, text);
			delete[] text;
		}
		offset += v2s32(0, 25);
	}

	{
		core::rect < s32 > rect(0, 0, 100, 30);
		rect += topleft + v2s32(size.X / 2 - 105, size.Y - 40);
		const wchar_t *text =  wgettext("Save");
		Environment->addButton(rect, this, GUI_ID_BACK_BUTTON,
				 text);
		delete[] text;
	}
	{
		core::rect < s32 > rect(0, 0, 100, 30);
		rect += topleft + v2s32(size.X / 2 + 5, size.Y - 40);
		const wchar_t *text = wgettext("Cancel");
		Environment->addButton(rect, this, GUI_ID_ABORT_BUTTON,
				text);
		delete[] text;
	}	
}

void GUIKeyChangeMenu::drawMenu()
{
	gui::IGUISkin* skin = Environment->getSkin();
	if (!skin)
		return;
	video::IVideoDriver* driver = Environment->getVideoDriver();

	video::SColor bgcolor(140, 0, 0, 0);

	{
		core::rect < s32 > rect(0, 0, 620, 620);
		rect += AbsoluteRect.UpperLeftCorner;
		driver->draw2DRectangle(bgcolor, rect, &AbsoluteClippingRect);
	}

	gui::IGUIElement::draw();
}

bool GUIKeyChangeMenu::acceptInput()
{
	for(size_t i = 0; i < key_settings.size(); i++)
	{
		key_setting *k = key_settings.at(i);
		g_settings->set(k->setting_name, k->key.sym());
	}
	{
		gui::IGUIElement *e = getElementFromId(GUI_ID_CB_AUX1_DESCENDS);
		if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX)
			g_settings->setBool("aux1_descends", ((gui::IGUICheckBox*)e)->isChecked());
	}
	{
		gui::IGUIElement *e = getElementFromId(GUI_ID_CB_DOUBLETAP_JUMP);
		if(e != NULL && e->getType() == gui::EGUIET_CHECK_BOX)
			g_settings->setBool("doubletap_jump", ((gui::IGUICheckBox*)e)->isChecked());
	}

	clearKeyCache();

	g_gamecallback->signalKeyConfigChange();

	return true;
}

bool GUIKeyChangeMenu::resetMenu()
{
	if (activeKey >= 0)
	{
		for(size_t i = 0; i < key_settings.size(); i++)
		{
			key_setting *k = key_settings.at(i);
			if(k->id == activeKey)
			{
				const wchar_t *text = wgettext(k->key.name());
				k->button->setText(text);
				delete[] text;
				break;
			}
		}
		activeKey = -1;
		return false;
	}
	return true;
}
bool GUIKeyChangeMenu::OnEvent(const SEvent& event)
{
	if (event.EventType == EET_KEY_INPUT_EVENT && activeKey >= 0
			&& event.KeyInput.PressedDown) {
		
		bool prefer_character = shift_down;
		KeyPress kp(event.KeyInput, prefer_character);
		
		bool shift_went_down = false;
		if(!shift_down &&
				(event.KeyInput.Key == irr::KEY_SHIFT ||
				event.KeyInput.Key == irr::KEY_LSHIFT ||
				event.KeyInput.Key == irr::KEY_RSHIFT))
			shift_went_down = true;

		// Remove Key already in use message
		if(this->key_used_text)
		{
			this->key_used_text->remove();
			this->key_used_text = NULL;
		}
		// Display Key already in use message
		if (std::find(this->key_used.begin(), this->key_used.end(), kp) != this->key_used.end())
		{
			core::rect < s32 > rect(0, 0, 600, 40);
			rect += v2s32(0, 0) + v2s32(25, 30);
			const wchar_t *text = wgettext("Key already in use");
			this->key_used_text = Environment->addStaticText(text,
					rect, false, true, this, -1);
			delete[] text;
			//infostream << "Key already in use" << std::endl;
		}

		// But go on
		{
			key_setting *k = NULL;
			for(size_t i = 0; i < key_settings.size(); i++)
			{
				if(key_settings.at(i)->id == activeKey)
				{
					k = key_settings.at(i);
					break;
				}
			}
			FATAL_ERROR_IF(k == NULL, "Key setting not found");
			k->key = kp;
			const wchar_t *text = wgettext(k->key.name());
			k->button->setText(text);
			delete[] text;

			this->key_used.push_back(kp);

			// Allow characters made with shift
			if(shift_went_down){
				shift_down = true;
				return false;
			}else{
				activeKey = -1;
				return true;
			}
		}
	} else if (event.EventType == EET_KEY_INPUT_EVENT && activeKey < 0
			&& event.KeyInput.PressedDown
			&& event.KeyInput.Key == irr::KEY_ESCAPE) {
		quitMenu();
		return true;
	} else if (event.EventType == EET_GUI_EVENT) {
		if (event.GUIEvent.EventType == gui::EGET_ELEMENT_FOCUS_LOST
			&& isVisible())
		{
			if (!canTakeFocus(event.GUIEvent.Element))
			{
				dstream << "GUIMainMenu: Not allowing focus change."
				<< std::endl;
				// Returning true disables focus change
				return true;
			}
		}
		if (event.GUIEvent.EventType == gui::EGET_BUTTON_CLICKED)
		{
			switch (event.GUIEvent.Caller->getID())
			{
				case GUI_ID_BACK_BUTTON: //back
					acceptInput();
					quitMenu();
					return true;
				case GUI_ID_ABORT_BUTTON: //abort
					quitMenu();
					return true;
				default:
					key_setting *k = NULL;
					for(size_t i = 0; i < key_settings.size(); i++)
					{
						if(key_settings.at(i)->id == event.GUIEvent.Caller->getID())
						{
							k = key_settings.at(i);
							break;
						}
					}
					FATAL_ERROR_IF(k == NULL, "Key setting not found");

					resetMenu();
					shift_down = false;
					activeKey = event.GUIEvent.Caller->getID();
					const wchar_t *text = wgettext("press key");
					k->button->setText(text);
					delete[] text;
					this->key_used.erase(std::remove(this->key_used.begin(),
							this->key_used.end(), k->key), this->key_used.end());
					break;
			}
			Environment->setFocus(this);
		}
	}
	return Parent ? Parent->OnEvent(event) : false;
}

void GUIKeyChangeMenu::add_key(int id, const wchar_t *button_name, const std::string &setting_name)
{
	key_setting *k = new key_setting;
	k->id = id;

	k->button_name = button_name;
	k->setting_name = setting_name;
	k->key = getKeySetting(k->setting_name.c_str());
	key_settings.push_back(k);
}

void GUIKeyChangeMenu::init_keys()
{
	this->add_key(GUI_ID_KEY_FORWARD_BUTTON,   wgettext("Forward"),          "keymap_forward");
	this->add_key(GUI_ID_KEY_BACKWARD_BUTTON,  wgettext("Backward"),         "keymap_backward");
	this->add_key(GUI_ID_KEY_LEFT_BUTTON,      wgettext("Left"),             "keymap_left");
	this->add_key(GUI_ID_KEY_RIGHT_BUTTON,     wgettext("Right"),            "keymap_right");
	this->add_key(GUI_ID_KEY_USE_BUTTON,       wgettext("Use"),              "keymap_special1");
	this->add_key(GUI_ID_KEY_JUMP_BUTTON,      wgettext("Jump"),             "keymap_jump");
	this->add_key(GUI_ID_KEY_SNEAK_BUTTON,     wgettext("Sneak"),            "keymap_sneak");
	this->add_key(GUI_ID_KEY_DROP_BUTTON,      wgettext("Drop"),             "keymap_drop");
	this->add_key(GUI_ID_KEY_INVENTORY_BUTTON, wgettext("Inventory"),        "keymap_inventory");
	this->add_key(GUI_ID_KEY_CHAT_BUTTON,      wgettext("Chat"),             "keymap_chat");
	this->add_key(GUI_ID_KEY_CMD_BUTTON,       wgettext("Command"),          "keymap_cmd");
	this->add_key(GUI_ID_KEY_CONSOLE_BUTTON,   wgettext("Console"),          "keymap_console");
	this->add_key(GUI_ID_KEY_FLY_BUTTON,       wgettext("Toggle fly"),       "keymap_freemove");
	this->add_key(GUI_ID_KEY_FAST_BUTTON,      wgettext("Toggle fast"),      "keymap_fastmove");
	this->add_key(GUI_ID_KEY_CINEMATIC_BUTTON, wgettext("Toggle Cinematic"), "keymap_cinematic");
	this->add_key(GUI_ID_KEY_NOCLIP_BUTTON,    wgettext("Toggle noclip"),    "keymap_noclip");
	this->add_key(GUI_ID_KEY_RANGE_BUTTON,     wgettext("Range select"),     "keymap_rangeselect");
	this->add_key(GUI_ID_KEY_DUMP_BUTTON,      wgettext("Print stacks"),     "keymap_print_debug_stacks");
	this->add_key(GUI_ID_KEY_ZOOM_BUTTON,      wgettext("Zoom"),             "keymap_zoom");
}

ss="hl opt">: blocks) { v3s16 p = block.first; m_blocks_modified.insert(p); if (m_blocks_sending.find(p) != m_blocks_sending.end()) m_blocks_sending.erase(p); if (m_blocks_sent.find(p) != m_blocks_sent.end()) m_blocks_sent.erase(p); } } void RemoteClient::notifyEvent(ClientStateEvent event) { std::ostringstream myerror; switch (m_state) { case CS_Invalid: //intentionally do nothing break; case CS_Created: switch (event) { case CSE_Hello: m_state = CS_HelloSent; break; case CSE_InitLegacy: m_state = CS_AwaitingInit2; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SetDenied: m_state = CS_Denied; break; /* GotInit2 SetDefinitionsSent SetMediaSent */ default: myerror << "Created: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_Denied: /* don't do anything if in denied state */ break; case CS_HelloSent: switch(event) { case CSE_AuthAccept: m_state = CS_AwaitingInit2; if (chosen_mech == AUTH_MECHANISM_SRP || chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD) srp_verifier_delete((SRPVerifier *) auth_data); chosen_mech = AUTH_MECHANISM_NONE; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SetDenied: m_state = CS_Denied; if (chosen_mech == AUTH_MECHANISM_SRP || chosen_mech == AUTH_MECHANISM_LEGACY_PASSWORD) srp_verifier_delete((SRPVerifier *) auth_data); chosen_mech = AUTH_MECHANISM_NONE; break; default: myerror << "HelloSent: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_AwaitingInit2: switch(event) { case CSE_GotInit2: confirmSerializationVersion(); m_state = CS_InitDone; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SetDenied: m_state = CS_Denied; break; /* Init SetDefinitionsSent SetMediaSent */ default: myerror << "InitSent: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_InitDone: switch(event) { case CSE_SetDefinitionsSent: m_state = CS_DefinitionsSent; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SetDenied: m_state = CS_Denied; break; /* Init GotInit2 SetMediaSent */ default: myerror << "InitDone: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_DefinitionsSent: switch(event) { case CSE_SetClientReady: m_state = CS_Active; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SetDenied: m_state = CS_Denied; break; /* Init GotInit2 SetDefinitionsSent */ default: myerror << "DefinitionsSent: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); } break; case CS_Active: switch(event) { case CSE_SetDenied: m_state = CS_Denied; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SudoSuccess: m_state = CS_SudoMode; if (chosen_mech == AUTH_MECHANISM_SRP) srp_verifier_delete((SRPVerifier *) auth_data); chosen_mech = AUTH_MECHANISM_NONE; break; /* Init GotInit2 SetDefinitionsSent SetMediaSent SetDenied */ default: myerror << "Active: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); break; } break; case CS_SudoMode: switch(event) { case CSE_SetDenied: m_state = CS_Denied; break; case CSE_Disconnect: m_state = CS_Disconnecting; break; case CSE_SudoLeave: m_state = CS_Active; break; default: myerror << "Active: Invalid client state transition! " << event; throw ClientStateError(myerror.str()); break; } break; case CS_Disconnecting: /* we are already disconnecting */ break; } } u64 RemoteClient::uptime() const { return porting::getTimeS() - m_connection_time; } ClientInterface::ClientInterface(const std::shared_ptr<con::Connection> & con) : m_con(con), m_env(NULL), m_print_info_timer(0.0f) { } ClientInterface::~ClientInterface() { /* Delete clients */ { RecursiveMutexAutoLock clientslock(m_clients_mutex); for (auto &client_it : m_clients) { // Delete client delete client_it.second; } } } std::vector<session_t> ClientInterface::getClientIDs(ClientState min_state) { std::vector<session_t> reply; RecursiveMutexAutoLock clientslock(m_clients_mutex); for (const auto &m_client : m_clients) { if (m_client.second->getState() >= min_state) reply.push_back(m_client.second->peer_id); } return reply; } void ClientInterface::markBlockposAsNotSent(const v3s16 &pos) { RecursiveMutexAutoLock clientslock(m_clients_mutex); for (const auto &client : m_clients) { if (client.second->getState() >= CS_Active) client.second->SetBlockNotSent(pos); } } /** * Verify if user limit was reached. * User limit count all clients from HelloSent state (MT protocol user) to Active state * @return true if user limit was reached */ bool ClientInterface::isUserLimitReached() { return getClientIDs(CS_HelloSent).size() >= g_settings->getU16("max_users"); } void ClientInterface::step(float dtime) { m_print_info_timer += dtime; if (m_print_info_timer >= 30.0f) { m_print_info_timer = 0.0f; UpdatePlayerList(); } } void ClientInterface::UpdatePlayerList() { if (m_env) { std::vector<session_t> clients = getClientIDs(); m_clients_names.clear(); if (!clients.empty()) infostream<<"Players:"<<std::endl; for (session_t i : clients) { RemotePlayer *player = m_env->getPlayer(i); if (player == NULL) continue; infostream << "* " << player->getName() << "\t"; { RecursiveMutexAutoLock clientslock(m_clients_mutex); RemoteClient* client = lockedGetClientNoEx(i); if (client) client->PrintInfo(infostream); } m_clients_names.emplace_back(player->getName()); } } } void ClientInterface::send(session_t peer_id, u8 channelnum, NetworkPacket *pkt, bool reliable) { m_con->Send(peer_id, channelnum, pkt, reliable); } void ClientInterface::sendToAll(NetworkPacket *pkt) { RecursiveMutexAutoLock clientslock(m_clients_mutex); for (auto &client_it : m_clients) { RemoteClient *client = client_it.second; if (client->net_proto_version != 0) { m_con->Send(client->peer_id, clientCommandFactoryTable[pkt->getCommand()].channel, pkt, clientCommandFactoryTable[pkt->getCommand()].reliable); } } } void ClientInterface::sendToAllCompat(NetworkPacket *pkt, NetworkPacket *legacypkt, u16 min_proto_ver) { RecursiveMutexAutoLock clientslock(m_clients_mutex); for (auto &client_it : m_clients) { RemoteClient *client = client_it.second; NetworkPacket *pkt_to_send = nullptr; if (client->net_proto_version >= min_proto_ver) { pkt_to_send = pkt; } else if (client->net_proto_version != 0) { pkt_to_send = legacypkt; } else { warningstream << "Client with unhandled version to handle: '" << client->net_proto_version << "'"; continue; } m_con->Send(client->peer_id, clientCommandFactoryTable[pkt_to_send->getCommand()].channel, pkt_to_send, clientCommandFactoryTable[pkt_to_send->getCommand()].reliable); } } RemoteClient* ClientInterface::getClientNoEx(session_t peer_id, ClientState state_min) { RecursiveMutexAutoLock clientslock(m_clients_mutex); RemoteClientMap::const_iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their // access is denied, and this event occurs later then. if (n == m_clients.end()) return NULL; if (n->second->getState() >= state_min) return n->second; return NULL; } RemoteClient* ClientInterface::lockedGetClientNoEx(session_t peer_id, ClientState state_min) { RemoteClientMap::const_iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their // access is denied, and this event occurs later then. if (n == m_clients.end()) return NULL; if (n->second->getState() >= state_min) return n->second; return NULL; } ClientState ClientInterface::getClientState(session_t peer_id) { RecursiveMutexAutoLock clientslock(m_clients_mutex); RemoteClientMap::const_iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their // access is denied, and this event occurs later then. if (n == m_clients.end()) return CS_Invalid; return n->second->getState(); } void ClientInterface::setPlayerName(session_t peer_id, const std::string &name) { RecursiveMutexAutoLock clientslock(m_clients_mutex); RemoteClientMap::iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their // access is denied, and this event occurs later then. if (n != m_clients.end()) n->second->setName(name); } void ClientInterface::DeleteClient(session_t peer_id) { RecursiveMutexAutoLock conlock(m_clients_mutex); // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // The client may not exist; clients are immediately removed if their // access is denied, and this event occurs later then. if (n == m_clients.end()) return; /* Mark objects to be not known by the client */ //TODO this should be done by client destructor!!! RemoteClient *client = n->second; // Handle objects for (u16 id : client->m_known_objects) { // Get object ServerActiveObject* obj = m_env->getActiveObject(id); if(obj && obj->m_known_by_count > 0) obj->m_known_by_count--; } // Delete client delete m_clients[peer_id]; m_clients.erase(peer_id); } void ClientInterface::CreateClient(session_t peer_id) { RecursiveMutexAutoLock conlock(m_clients_mutex); // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // The client shouldn't already exist if (n != m_clients.end()) return; // Create client RemoteClient *client = new RemoteClient(); client->peer_id = peer_id; m_clients[client->peer_id] = client; } void ClientInterface::event(session_t peer_id, ClientStateEvent event) { { RecursiveMutexAutoLock clientlock(m_clients_mutex); // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // No client to deliver event if (n == m_clients.end()) return; n->second->notifyEvent(event); } if ((event == CSE_SetClientReady) || (event == CSE_Disconnect) || (event == CSE_SetDenied)) { UpdatePlayerList(); } } u16 ClientInterface::getProtocolVersion(session_t peer_id) { RecursiveMutexAutoLock conlock(m_clients_mutex); // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // No client to get version if (n == m_clients.end()) return 0; return n->second->net_proto_version; } void ClientInterface::setClientVersion(session_t peer_id, u8 major, u8 minor, u8 patch, const std::string &full) { RecursiveMutexAutoLock conlock(m_clients_mutex); // Error check RemoteClientMap::iterator n = m_clients.find(peer_id); // No client to set versions