aboutsummaryrefslogtreecommitdiff
path: root/src/fontengine.cpp
blob: da327c3f603cc93ffc3398db79591e866d82a0ca (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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
/*
Minetest
Copyright (C) 2010-2014 sapier <sapier at gmx dot 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 "fontengine.h"
#include "log.h"
#include "config.h"
#include "porting.h"
#include "constants.h"
#include "filesys.h"

#if USE_FREETYPE
#include "gettext.h"
#include "xCGUITTFont.h"
#endif

/** maximum size distance for getting a "similar" font size */
#define MAX_FONT_SIZE_OFFSET 10

/** reference to access font engine, has to be initialized by main */
FontEngine* g_fontengine = NULL;

/** callback to be used on change of font size setting */
static void font_setting_changed(const std::string &name, void *userdata)
{
	g_fontengine->readSettings();
}

/******************************************************************************/
FontEngine::FontEngine(Settings* main_settings, gui::IGUIEnvironment* env) :
	m_settings(main_settings),
	m_env(env),
	m_font_cache(),
	m_currentMode(FM_Standard),
	m_lastMode(),
	m_lastSize(0),
	m_lastFont(NULL)
{

	for (unsigned int i = 0; i < FM_MaxMode; i++) {
		m_default_size[i] = (FontMode) FONT_SIZE_UNSPECIFIED;
	}

	assert(m_settings != NULL); // pre-condition
	assert(m_env != NULL); // pre-condition
	assert(m_env->getSkin() != NULL); // pre-condition

	m_currentMode = FM_Simple;

#if USE_FREETYPE
	if (g_settings->getBool("freetype")) {
		m_default_size[FM_Standard] = m_settings->getU16("font_size");
		m_default_size[FM_Fallback] = m_settings->getU16("fallback_font_size");
		m_default_size[FM_Mono]     = m_settings->getU16("mono_font_size");

		if (is_yes(gettext("needs_fallback_font"))) {
			m_currentMode = FM_Fallback;
		}
		else {
			m_currentMode = FM_Standard;
		}
	}

	// having freetype but not using it is quite a strange case so we need to do
	// special handling for it
	if (m_currentMode == FM_Simple) {
		std::stringstream fontsize;
		fontsize << DEFAULT_FONT_SIZE;
		m_settings->setDefault("font_size", fontsize.str());
		m_settings->setDefault("mono_font_size", fontsize.str());
	}
#endif

	m_default_size[FM_Simple]       = m_settings->getU16("font_size");
	m_default_size[FM_SimpleMono]   = m_settings->getU16("mono_font_size");

	updateSkin();

	if (m_currentMode == FM_Standard) {
		m_settings->registerChangedCallback("font_size", font_setting_changed, NULL);
		m_settings->registerChangedCallback("font_path", font_setting_changed, NULL);
		m_settings->registerChangedCallback("font_shadow", font_setting_changed, NULL);
		m_settings->registerChangedCallback("font_shadow_alpha", font_setting_changed, NULL);
	}
	else if (m_currentMode == FM_Fallback) {
		m_settings->registerChangedCallback("fallback_font_size", font_setting_changed, NULL);
		m_settings->registerChangedCallback("fallback_font_path", font_setting_changed, NULL);
		m_settings->registerChangedCallback("fallback_font_shadow", font_setting_changed, NULL);
		m_settings->registerChangedCallback("fallback_font_shadow_alpha", font_setting_changed, NULL);
	}

	m_settings->registerChangedCallback("mono_font_path", font_setting_changed, NULL);
	m_settings->registerChangedCallback("mono_font_size", font_setting_changed, NULL);
	m_settings->registerChangedCallback("screen_dpi", font_setting_changed, NULL);
	m_settings->registerChangedCallback("gui_scaling", font_setting_changed, NULL);
}

/******************************************************************************/
FontEngine::~FontEngine()
{
	cleanCache();
}

/******************************************************************************/
void FontEngine::cleanCache()
{
	for ( unsigned int i = 0; i < FM_MaxMode; i++) {

		for (std::map<unsigned int, irr::gui::IGUIFont*>::iterator iter
				= m_font_cache[i].begin();
				iter != m_font_cache[i].end(); ++iter) {
			iter->second->drop();
			iter->second = NULL;
		}
		m_font_cache[i].clear();
	}
}

/******************************************************************************/
irr::gui::IGUIFont* FontEngine::getFont(unsigned int font_size, FontMode mode)
{
	if (mode == FM_Unspecified) {
		mode = m_currentMode;
	}
	else if ((mode == FM_Mono) && (m_currentMode == FM_Simple)) {
		mode = FM_SimpleMono;
	}

	if (font_size == FONT_SIZE_UNSPECIFIED) {
		font_size = m_default_size[mode];
	}

	if ((font_size == m_lastSize) && (mode == m_lastMode)) {
		return m_lastFont;
	}

	if (m_font_cache[mode].find(font_size) == m_font_cache[mode].end()) {
		initFont(font_size, mode);
	}

	if (m_font_cache[mode].find(font_size) == m_font_cache[mode].end()) {
		return NULL;
	}

	m_lastSize = font_size;
	m_lastMode = mode;
	m_lastFont = m_font_cache[mode][font_size];

	return m_font_cache[mode][font_size];
}

/******************************************************************************/
unsigned int FontEngine::getTextHeight(unsigned int font_size, FontMode mode)
{
	irr::gui::IGUIFont* font = getFont(font_size, mode);

	// use current skin font as fallback
	if (font == NULL) {
		font = m_env->getSkin()->getFont();
	}
	FATAL_ERROR_IF(font == NULL, "Could not get skin font");

	return font->getDimension(L"Some unimportant example String").Height;
}

/******************************************************************************/
unsigned int FontEngine::getTextWidth(const std::wstring& text,
		unsigned int font_size, FontMode mode)
{
	irr::gui::IGUIFont* font = getFont(font_size, mode);

	// use current skin font as fallback
	if (font == NULL) {
		font = m_env->getSkin()->getFont();
	}
	FATAL_ERROR_IF(font == NULL, "Could not get font");

	return font->getDimension(text.c_str()).Width;
}


/** get line height for a specific font (including empty room between lines) */
unsigned int FontEngine::getLineHeight(unsigned int font_size, FontMode mode)
{
	irr::gui::IGUIFont* font = getFont(font_size, mode);

	// use current skin font as fallback
	if (font == NULL) {
		font = m_env->getSkin()->getFont();
	}
	FATAL_ERROR_IF(font == NULL, "Could not get font");

	return font->getDimension(L"Some unimportant example String").Height
			+ font->getKerningHeight();
}

/******************************************************************************/
unsigned int FontEngine::getDefaultFontSize()
{
	return m_default_size[m_currentMode];
}

/******************************************************************************/
void FontEngine::readSettings()
{
#if USE_FREETYPE
	if (g_settings->getBool("freetype")) {
		m_default_size[FM_Standard] = m_settings->getU16("font_size");
		m_default_size[FM_Fallback] = m_settings->getU16("fallback_font_size");
		m_default_size[FM_Mono]     = m_settings->getU16("mono_font_size");

		if (is_yes(gettext("needs_fallback_font"))) {
			m_currentMode = FM_Fallback;
		}
		else {
			m_currentMode = FM_Standard;
		}
	}
#endif
	m_default_size[FM_Simple]       = m_settings->getU16("font_size");
	m_default_size[FM_SimpleMono]   = m_settings->getU16("mono_font_size");

	cleanCache();
	updateFontCache();
	updateSkin();
}

/******************************************************************************/
void FontEngine::updateSkin()
{
	gui::IGUIFont *font = getFont();

	if (font)
		m_env->getSkin()->setFont(font);
	else
		errorstream << "FontEngine: Default font file: " <<
				"\n\t\"" << m_settings->get("font_path") << "\"" <<
				"\n\trequired for current screen configuration was not found" <<
				" or was invalid file format." <<
				"\n\tUsing irrlicht default font." << std::endl;

	// If we did fail to create a font our own make irrlicht find a default one
	font = m_env->getSkin()->getFont();
	FATAL_ERROR_IF(font == NULL, "Could not create/get font");

	u32 text_height = font->getDimension(L"Hello, world!").Height;
	infostream << "text_height=" << text_height << std::endl;
}

/******************************************************************************/
void FontEngine::updateFontCache()
{
	/* the only font to be initialized is default one,
	 * all others are re-initialized on demand */
	initFont(m_default_size[m_currentMode], m_currentMode);

	/* reset font quick access */
	m_lastMode = FM_Unspecified;
	m_lastSize = 0;
	m_lastFont = NULL;
}

/******************************************************************************/
void FontEngine::initFont(unsigned int basesize, FontMode mode)
{

	std::string font_config_prefix;

	if (mode == FM_Unspecified) {
		mode = m_currentMode;
	}

	switch (mode) {

		case FM_Standard:
			font_config_prefix = "";
			break;

		case FM_Fallback:
			font_config_prefix = "fallback_";
			break;

		case FM_Mono:
			font_config_prefix = "mono_";
			if (m_currentMode == FM_Simple)
				mode = FM_SimpleMono;
			break;

		case FM_Simple: /* Fallthrough */
		case FM_SimpleMono: /* Fallthrough */
		default:
			font_config_prefix = "";

	}

	if (m_font_cache[mode].find(basesize) != m_font_cache[mode].end())
		return;

	if ((mode == FM_Simple) || (mode == FM_SimpleMono)) {
		initSimpleFont(basesize, mode);
		return;
	}
#if USE_FREETYPE
	else {
		if (! is_yes(m_settings->get("freetype"))) {
			return;
		}
		unsigned int size = floor(
				porting::getDisplayDensity() *
				m_settings->getFloat("gui_scaling") *
				basesize);
		u32 font_shadow       = 0;
		u32 font_shadow_alpha = 0;

		try {
			font_shadow =
					g_settings->getU16(font_config_prefix + "font_shadow");
		} catch (SettingNotFoundException&) {}
		try {
			font_shadow_alpha =
					g_settings->getU16(font_config_prefix + "font_shadow_alpha");
		} catch (SettingNotFoundException&) {}

		std::string font_path = g_settings->get(font_config_prefix + "font_path");

		irr::gui::IGUIFont* font = gui::CGUITTFont::createTTFont(m_env,
				font_path.c_str(), size, true, true, font_shadow,
				font_shadow_alpha);

		if (font != NULL) {
			m_font_cache[mode][basesize] = font;
			return;
		}

		// try fallback font
		errorstream << "FontEngine: failed to load: " << font_path << ", trying to fall back "
				"to fallback font" << std::endl;

		font_path = g_settings->get(font_config_prefix + "fallback_font_path");

		font = gui::CGUITTFont::createTTFont(m_env,
			font_path.c_str(), size, true, true, font_shadow,
			font_shadow_alpha);

		if (font != NULL) {
			m_font_cache[mode][basesize] = font;
			return;
		}

		// give up
		errorstream << "FontEngine: failed to load freetype font: "
				<< font_path << std::endl;
		errorstream << "minetest can not continue without a valid font. Please correct "
				"the 'font_path' setting or install the font file in the proper "
				"location" << std::endl;
		abort();
	}
#endif
}

/** initialize a font without freetype */
void FontEngine::initSimpleFont(unsigned int basesize, FontMode mode)
{
	assert(mode == FM_Simple || mode == FM_SimpleMono); // pre-condition

	std::string font_path = "";
	if (mode == FM_Simple) {
		font_path = m_settings->get("font_path");
	} else {
		font_path = m_settings->get("mono_font_path");
	}
	std::string basename = font_path;
	std::string ending = font_path.substr(font_path.length() -4);

	if (ending == ".ttf") {
		errorstream << "FontEngine: Not trying to open \"" << font_path
				<< "\" which seems to be a truetype font." << std::endl;
		return;
	}

	if ((ending == ".xml") || (ending == ".png")) {
		basename = font_path.substr(0,font_path.length()-4);
	}

	if (basesize == FONT_SIZE_UNSPECIFIED)
		basesize = DEFAULT_FONT_SIZE;

	unsigned int size = floor(
			porting::getDisplayDensity() *
			m_settings->getFloat("gui_scaling") *
			basesize);

	irr::gui::IGUIFont* font = NULL;

	for(unsigned int offset = 0; offset < MAX_FONT_SIZE_OFFSET; offset++) {

		// try opening positive offset
		std::stringstream fontsize_plus_png;
		fontsize_plus_png << basename << "_" << (size + offset) << ".png";

		if (fs::PathExists(fontsize_plus_png.str())) {
			font = m_env->getFont(fontsize_plus_png.str().c_str());

			if (font) {
				verbosestream << "FontEngine: found font: " << fontsize_plus_png.str() << std::endl;
				break;
			}
		}

		std::stringstream fontsize_plus_xml;
		fontsize_plus_xml << basename << "_" << (size + offset) << ".xml";

		if (fs::PathExists(fontsize_plus_xml.str())) {
			font = m_env->getFont(fontsize_plus_xml.str().c_str());

			if (font) {
				verbosestream << "FontEngine: found font: " << fontsize_plus_xml.str() << std::endl;
				break;
			}
		}

		// try negative offset
		std::stringstream fontsize_minus_png;
		fontsize_minus_png << basename << "_" << (size - offset) << ".png";

		if (fs::PathExists(fontsize_minus_png.str())) {
			font = m_env->getFont(fontsize_minus_png.str().c_str());

			if (font) {
				verbosestream << "FontEngine: found font: " << fontsize_minus_png.str() << std::endl;
				break;
			}
		}

		std::stringstream fontsize_minus_xml;
		fontsize_minus_xml << basename << "_" << (size - offset) << ".xml";

		if (fs::PathExists(fontsize_minus_xml.str())) {
			font = m_env->getFont(fontsize_minus_xml.str().c_str());

			if (font) {
				verbosestream << "FontEngine: found font: " << fontsize_minus_xml.str() << std::endl;
				break;
			}
		}
	}

	// try name direct
	if (font == NULL) {
		if (fs::PathExists(font_path)) {
			font = m_env->getFont(font_path.c_str());
			if (font)
				verbosestream << "FontEngine: found font: " << font_path << std::endl;
		}
	}

	if (font != NULL) {
		font->grab();
		m_font_cache[mode][basesize] = font;
	}
}
n class="hl opt">= m_env.getLocalPlayer(); assert(player != NULL); player->setPosition(playerpos); infostream << "Client: received map seed: " << m_map_seed << std::endl; infostream << "Client: received recommended send interval " << m_recommended_send_interval<<std::endl; // Reply to server /*~ DO NOT TRANSLATE THIS LITERALLY! This is a special string which needs to contain the translation's language code (e.g. "de" for German). */ std::string lang = gettext("LANG_CODE"); if (lang == "LANG_CODE") lang = ""; NetworkPacket resp_pkt(TOSERVER_INIT2, sizeof(u16) + lang.size()); resp_pkt << lang; Send(&resp_pkt); m_state = LC_Init; } void Client::handleCommand_AcceptSudoMode(NetworkPacket* pkt) { deleteAuthData(); m_password = m_new_password; verbosestream << "Client: Recieved TOCLIENT_ACCEPT_SUDO_MODE." << std::endl; // send packet to actually set the password startAuth(AUTH_MECHANISM_FIRST_SRP); // reset again m_chosen_auth_mech = AUTH_MECHANISM_NONE; } void Client::handleCommand_DenySudoMode(NetworkPacket* pkt) { ChatMessage *chatMessage = new ChatMessage(CHATMESSAGE_TYPE_SYSTEM, L"Password change denied. Password NOT changed."); pushToChatQueue(chatMessage); // reset everything and be sad deleteAuthData(); } void Client::handleCommand_AccessDenied(NetworkPacket* pkt) { // The server didn't like our password. Note, this needs // to be processed even if the serialisation format has // not been agreed yet, the same as TOCLIENT_INIT. m_access_denied = true; m_access_denied_reason = "Unknown"; if (pkt->getCommand() != TOCLIENT_ACCESS_DENIED) { // 13/03/15 Legacy code from 0.4.12 and lesser but is still used // in some places of the server code if (pkt->getSize() >= 2) { std::wstring wide_reason; *pkt >> wide_reason; m_access_denied_reason = wide_to_utf8(wide_reason); } return; } if (pkt->getSize() < 1) return; u8 denyCode = SERVER_ACCESSDENIED_UNEXPECTED_DATA; *pkt >> denyCode; if (denyCode == SERVER_ACCESSDENIED_SHUTDOWN || denyCode == SERVER_ACCESSDENIED_CRASH) { *pkt >> m_access_denied_reason; if (m_access_denied_reason.empty()) { m_access_denied_reason = accessDeniedStrings[denyCode]; } u8 reconnect; *pkt >> reconnect; m_access_denied_reconnect = reconnect & 1; } else if (denyCode == SERVER_ACCESSDENIED_CUSTOM_STRING) { *pkt >> m_access_denied_reason; } else if (denyCode == SERVER_ACCESSDENIED_TOO_MANY_USERS) { m_access_denied_reason = accessDeniedStrings[denyCode]; m_access_denied_reconnect = true; } else if (denyCode < SERVER_ACCESSDENIED_MAX) { m_access_denied_reason = accessDeniedStrings[denyCode]; } else { // Allow us to add new error messages to the // protocol without raising the protocol version, if we want to. // Until then (which may be never), this is outside // of the defined protocol. *pkt >> m_access_denied_reason; if (m_access_denied_reason.empty()) { m_access_denied_reason = "Unknown"; } } } void Client::handleCommand_RemoveNode(NetworkPacket* pkt) { if (pkt->getSize() < 6) return; v3s16 p; *pkt >> p; removeNode(p); } void Client::handleCommand_AddNode(NetworkPacket* pkt) { if (pkt->getSize() < 6 + MapNode::serializedLength(m_server_ser_ver)) return; v3s16 p; *pkt >> p; MapNode n; n.deSerialize(pkt->getU8Ptr(6), m_server_ser_ver); bool remove_metadata = true; u32 index = 6 + MapNode::serializedLength(m_server_ser_ver); if ((pkt->getSize() >= index + 1) && pkt->getU8(index)) { remove_metadata = false; } addNode(p, n, remove_metadata); } void Client::handleCommand_NodemetaChanged(NetworkPacket *pkt) { if (pkt->getSize() < 1) return; std::istringstream is(pkt->readLongString(), std::ios::binary); std::stringstream sstr; decompressZlib(is, sstr); NodeMetadataList meta_updates_list(false); meta_updates_list.deSerialize(sstr, m_itemdef, true); Map &map = m_env.getMap(); for (NodeMetadataMap::const_iterator i = meta_updates_list.begin(); i != meta_updates_list.end(); ++i) { v3s16 pos = i->first; if (map.isValidPosition(pos) && map.setNodeMetadata(pos, i->second)) continue; // Prevent from deleting metadata // Meta couldn't be set, unused metadata delete i->second; } } void Client::handleCommand_BlockData(NetworkPacket* pkt) { // Ignore too small packet if (pkt->getSize() < 6) return; v3s16 p; *pkt >> p; std::string datastring(pkt->getString(6), pkt->getSize() - 6); std::istringstream istr(datastring, std::ios_base::binary); MapSector *sector; MapBlock *block; v2s16 p2d(p.X, p.Z); sector = m_env.getMap().emergeSector(p2d); assert(sector->getPos() == p2d); block = sector->getBlockNoCreateNoEx(p.Y); if (block) { /* Update an existing block */ block->deSerialize(istr, m_server_ser_ver, false); block->deSerializeNetworkSpecific(istr); } else { /* Create a new block */ block = new MapBlock(&m_env.getMap(), p, this); block->deSerialize(istr, m_server_ser_ver, false); block->deSerializeNetworkSpecific(istr); sector->insertBlock(block); } if (m_localdb) { ServerMap::saveBlock(block, m_localdb); } /* Add it to mesh update queue and set it to be acknowledged after update. */ addUpdateMeshTaskWithEdge(p, true); } void Client::handleCommand_Inventory(NetworkPacket* pkt) { if (pkt->getSize() < 1) return; std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); player->inventory.deSerialize(is); m_update_wielded_item = true; delete m_inventory_from_server; m_inventory_from_server = new Inventory(player->inventory); m_inventory_from_server_age = 0.0; } void Client::handleCommand_TimeOfDay(NetworkPacket* pkt) { if (pkt->getSize() < 2) return; u16 time_of_day; *pkt >> time_of_day; time_of_day = time_of_day % 24000; float time_speed = 0; if (pkt->getSize() >= 2 + 4) { *pkt >> time_speed; } else { // Old message; try to approximate speed of time by ourselves float time_of_day_f = (float)time_of_day / 24000.0f; float tod_diff_f = 0; if (time_of_day_f < 0.2 && m_last_time_of_day_f > 0.8) tod_diff_f = time_of_day_f - m_last_time_of_day_f + 1.0f; else tod_diff_f = time_of_day_f - m_last_time_of_day_f; m_last_time_of_day_f = time_of_day_f; float time_diff = m_time_of_day_update_timer; m_time_of_day_update_timer = 0; if (m_time_of_day_set) { time_speed = (3600.0f * 24.0f) * tod_diff_f / time_diff; infostream << "Client: Measured time_of_day speed (old format): " << time_speed << " tod_diff_f=" << tod_diff_f << " time_diff=" << time_diff << std::endl; } } // Update environment m_env.setTimeOfDay(time_of_day); m_env.setTimeOfDaySpeed(time_speed); m_time_of_day_set = true; //u32 dr = m_env.getDayNightRatio(); //infostream << "Client: time_of_day=" << time_of_day // << " time_speed=" << time_speed // << " dr=" << dr << std::endl; } void Client::handleCommand_ChatMessage(NetworkPacket *pkt) { /* u8 version u8 message_type u16 sendername length wstring sendername u16 length wstring message */ ChatMessage *chatMessage = new ChatMessage(); u8 version, message_type; *pkt >> version >> message_type; if (version != 1 || message_type >= CHATMESSAGE_TYPE_MAX) { delete chatMessage; return; } u64 timestamp; *pkt >> chatMessage->sender >> chatMessage->message >> timestamp; chatMessage->timestamp = static_cast<std::time_t>(timestamp); chatMessage->type = (ChatMessageType) message_type; // @TODO send this to CSM using ChatMessage object if (modsLoaded() && m_script->on_receiving_message( wide_to_utf8(chatMessage->message))) { // Message was consumed by CSM and should not be handled by client delete chatMessage; } else { pushToChatQueue(chatMessage); } } void Client::handleCommand_ActiveObjectRemoveAdd(NetworkPacket* pkt) { /* u16 count of removed objects for all removed objects { u16 id } u16 count of added objects for all added objects { u16 id u8 type u32 initialization data length string initialization data } */ try { u8 type; u16 removed_count, added_count, id; // Read removed objects *pkt >> removed_count; for (u16 i = 0; i < removed_count; i++) { *pkt >> id; m_env.removeActiveObject(id); } // Read added objects *pkt >> added_count; for (u16 i = 0; i < added_count; i++) { *pkt >> id >> type; m_env.addActiveObject(id, type, pkt->readLongString()); } } catch (PacketError &e) { infostream << "handleCommand_ActiveObjectRemoveAdd: " << e.what() << ". The packet is unreliable, ignoring" << std::endl; } // m_activeobjects_received is false before the first // TOCLIENT_ACTIVE_OBJECT_REMOVE_ADD packet is received m_activeobjects_received = true; } void Client::handleCommand_ActiveObjectMessages(NetworkPacket* pkt) { /* for all objects { u16 id u16 message length string message } */ std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); try { while (is.good()) { u16 id = readU16(is); if (!is.good()) break; std::string message = deSerializeString16(is); // Pass on to the environment m_env.processActiveObjectMessage(id, message); } } catch (SerializationError &e) { errorstream << "Client::handleCommand_ActiveObjectMessages: " << "caught SerializationError: " << e.what() << std::endl; } } void Client::handleCommand_Movement(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); float mad, maa, maf, msw, mscr, msf, mscl, msj, lf, lfs, ls, g; *pkt >> mad >> maa >> maf >> msw >> mscr >> msf >> mscl >> msj >> lf >> lfs >> ls >> g; player->movement_acceleration_default = mad * BS; player->movement_acceleration_air = maa * BS; player->movement_acceleration_fast = maf * BS; player->movement_speed_walk = msw * BS; player->movement_speed_crouch = mscr * BS; player->movement_speed_fast = msf * BS; player->movement_speed_climb = mscl * BS; player->movement_speed_jump = msj * BS; player->movement_liquid_fluidity = lf * BS; player->movement_liquid_fluidity_smooth = lfs * BS; player->movement_liquid_sink = ls * BS; player->movement_gravity = g * BS; } void Client::handleCommand_Fov(NetworkPacket *pkt) { f32 fov; bool is_multiplier = false; f32 transition_time = 0.0f; *pkt >> fov >> is_multiplier; // Wrap transition_time extraction within a // try-catch to preserve backwards compat try { *pkt >> transition_time; } catch (PacketError &e) {}; LocalPlayer *player = m_env.getLocalPlayer(); assert(player); player->setFov({ fov, is_multiplier, transition_time }); m_camera->notifyFovChange(); } void Client::handleCommand_HP(NetworkPacket *pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); u16 oldhp = player->hp; u16 hp; *pkt >> hp; player->hp = hp; if (modsLoaded()) m_script->on_hp_modification(hp); if (hp < oldhp) { // Add to ClientEvent queue ClientEvent *event = new ClientEvent(); event->type = CE_PLAYER_DAMAGE; event->player_damage.amount = oldhp - hp; m_client_event_queue.push(event); } } void Client::handleCommand_Breath(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); u16 breath; *pkt >> breath; player->setBreath(breath); } void Client::handleCommand_MovePlayer(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); v3f pos; f32 pitch, yaw; *pkt >> pos >> pitch >> yaw; player->setPosition(pos); infostream << "Client got TOCLIENT_MOVE_PLAYER" << " pos=(" << pos.X << "," << pos.Y << "," << pos.Z << ")" << " pitch=" << pitch << " yaw=" << yaw << std::endl; /* Add to ClientEvent queue. This has to be sent to the main program because otherwise it would just force the pitch and yaw values to whatever the camera points to. */ ClientEvent *event = new ClientEvent(); event->type = CE_PLAYER_FORCE_MOVE; event->player_force_move.pitch = pitch; event->player_force_move.yaw = yaw; m_client_event_queue.push(event); } void Client::handleCommand_DeathScreen(NetworkPacket* pkt) { bool set_camera_point_target; v3f camera_point_target; *pkt >> set_camera_point_target; *pkt >> camera_point_target; ClientEvent *event = new ClientEvent(); event->type = CE_DEATHSCREEN; event->deathscreen.set_camera_point_target = set_camera_point_target; event->deathscreen.camera_point_target_x = camera_point_target.X; event->deathscreen.camera_point_target_y = camera_point_target.Y; event->deathscreen.camera_point_target_z = camera_point_target.Z; m_client_event_queue.push(event); } void Client::handleCommand_AnnounceMedia(NetworkPacket* pkt) { u16 num_files; *pkt >> num_files; infostream << "Client: Received media announcement: packet size: " << pkt->getSize() << std::endl; if (m_media_downloader == NULL || m_media_downloader->isStarted()) { const char *problem = m_media_downloader ? "we already saw another announcement" : "all media has been received already"; errorstream << "Client: Received media announcement but " << problem << "! " << " files=" << num_files << " size=" << pkt->getSize() << std::endl; return; } // Mesh update thread must be stopped while // updating content definitions sanity_check(!m_mesh_update_thread.isRunning()); for (u16 i = 0; i < num_files; i++) { std::string name, sha1_base64; *pkt >> name >> sha1_base64; std::string sha1_raw = base64_decode(sha1_base64); m_media_downloader->addFile(name, sha1_raw); } try { std::string str; *pkt >> str; Strfnd sf(str); while(!sf.at_end()) { std::string baseurl = trim(sf.next(",")); if (!baseurl.empty()) m_media_downloader->addRemoteServer(baseurl); } } catch(SerializationError& e) { // not supported by server or turned off } m_media_downloader->step(this); } void Client::handleCommand_Media(NetworkPacket* pkt) { /* u16 command u16 total number of file bunches u16 index of this bunch u32 number of files in this bunch for each file { u16 length of name string name u32 length of data data } */ u16 num_bunches; u16 bunch_i; u32 num_files; *pkt >> num_bunches >> bunch_i >> num_files; infostream << "Client: Received files: bunch " << bunch_i << "/" << num_bunches << " files=" << num_files << " size=" << pkt->getSize() << std::endl; if (num_files == 0) return; if (!m_media_downloader || !m_media_downloader->isStarted()) { const char *problem = m_media_downloader ? "media has not been requested" : "all media has been received already"; errorstream << "Client: Received media but " << problem << "! " << " bunch " << bunch_i << "/" << num_bunches << " files=" << num_files << " size=" << pkt->getSize() << std::endl; return; } // Mesh update thread must be stopped while // updating content definitions sanity_check(!m_mesh_update_thread.isRunning()); for (u32 i=0; i < num_files; i++) { std::string name; *pkt >> name; std::string data = pkt->readLongString(); m_media_downloader->conventionalTransferDone( name, data, this); } } void Client::handleCommand_NodeDef(NetworkPacket* pkt) { infostream << "Client: Received node definitions: packet size: " << pkt->getSize() << std::endl; // Mesh update thread must be stopped while // updating content definitions sanity_check(!m_mesh_update_thread.isRunning()); // Decompress node definitions std::istringstream tmp_is(pkt->readLongString(), std::ios::binary); std::ostringstream tmp_os; decompressZlib(tmp_is, tmp_os); // Deserialize node definitions std::istringstream tmp_is2(tmp_os.str()); m_nodedef->deSerialize(tmp_is2); m_nodedef_received = true; } void Client::handleCommand_ItemDef(NetworkPacket* pkt) { infostream << "Client: Received item definitions: packet size: " << pkt->getSize() << std::endl; // Mesh update thread must be stopped while // updating content definitions sanity_check(!m_mesh_update_thread.isRunning()); // Decompress item definitions std::istringstream tmp_is(pkt->readLongString(), std::ios::binary); std::ostringstream tmp_os; decompressZlib(tmp_is, tmp_os); // Deserialize node definitions std::istringstream tmp_is2(tmp_os.str()); m_itemdef->deSerialize(tmp_is2); m_itemdef_received = true; } void Client::handleCommand_PlaySound(NetworkPacket* pkt) { /* [0] u32 server_id [4] u16 name length [6] char name[len] [ 6 + len] f32 gain [10 + len] u8 type [11 + len] (f32 * 3) pos [23 + len] u16 object_id [25 + len] bool loop [26 + len] f32 fade [30 + len] f32 pitch [34 + len] bool ephemeral */ s32 server_id; std::string name; float gain; u8 type; // 0=local, 1=positional, 2=object v3f pos; u16 object_id; bool loop; float fade = 0.0f; float pitch = 1.0f; bool ephemeral = false; *pkt >> server_id >> name >> gain >> type >> pos >> object_id >> loop; try { *pkt >> fade; *pkt >> pitch; *pkt >> ephemeral; } catch (PacketError &e) {}; // Start playing int client_id = -1; switch(type) { case 0: // local client_id = m_sound->playSound(name, loop, gain, fade, pitch); break; case 1: // positional client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch); break; case 2: { // object ClientActiveObject *cao = m_env.getActiveObject(object_id); if (cao) pos = cao->getPosition(); client_id = m_sound->playSoundAt(name, loop, gain, pos, pitch); break; } default: break; } if (client_id != -1) { // for ephemeral sounds, server_id is not meaningful if (!ephemeral) { m_sounds_server_to_client[server_id] = client_id; m_sounds_client_to_server[client_id] = server_id; } if (object_id != 0) m_sounds_to_objects[client_id] = object_id; } } void Client::handleCommand_StopSound(NetworkPacket* pkt) { s32 server_id; *pkt >> server_id; std::unordered_map<s32, int>::iterator i = m_sounds_server_to_client.find(server_id); if (i != m_sounds_server_to_client.end()) { int client_id = i->second; m_sound->stopSound(client_id); } } void Client::handleCommand_FadeSound(NetworkPacket *pkt) { s32 sound_id; float step; float gain; *pkt >> sound_id >> step >> gain; std::unordered_map<s32, int>::const_iterator i = m_sounds_server_to_client.find(sound_id); if (i != m_sounds_server_to_client.end()) m_sound->fadeSound(i->second, step, gain); } void Client::handleCommand_Privileges(NetworkPacket* pkt) { m_privileges.clear(); infostream << "Client: Privileges updated: "; u16 num_privileges; *pkt >> num_privileges; for (u16 i = 0; i < num_privileges; i++) { std::string priv; *pkt >> priv; m_privileges.insert(priv); infostream << priv << " "; } infostream << std::endl; } void Client::handleCommand_InventoryFormSpec(NetworkPacket* pkt) { LocalPlayer *player = m_env.getLocalPlayer(); assert(player != NULL); // Store formspec in LocalPlayer player->inventory_formspec = pkt->readLongString(); } void Client::handleCommand_DetachedInventory(NetworkPacket* pkt) { std::string name; bool keep_inv = true; *pkt >> name >> keep_inv; infostream << "Client: Detached inventory update: \"" << name << "\", mode=" << (keep_inv ? "update" : "remove") << std::endl; const auto &inv_it = m_detached_inventories.find(name); if (!keep_inv) { if (inv_it != m_detached_inventories.end()) { delete inv_it->second; m_detached_inventories.erase(inv_it); } return; } Inventory *inv = nullptr; if (inv_it == m_detached_inventories.end()) { inv = new Inventory(m_itemdef); m_detached_inventories[name] = inv; } else { inv = inv_it->second; } u16 ignore; *pkt >> ignore; // this used to be the length of the following string, ignore it std::string contents(pkt->getRemainingString(), pkt->getRemainingBytes()); std::istringstream is(contents, std::ios::binary); inv->deSerialize(is); } void Client::handleCommand_ShowFormSpec(NetworkPacket* pkt) { std::string formspec = pkt->readLongString(); std::string formname; *pkt >> formname; ClientEvent *event = new ClientEvent(); event->type = CE_SHOW_FORMSPEC; // pointer is required as event is a struct only! // adding a std:string to a struct isn't possible event->show_formspec.formspec = new std::string(formspec); event->show_formspec.formname = new std::string(formname); m_client_event_queue.push(event); } void Client::handleCommand_SpawnParticle(NetworkPacket* pkt) { std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); ParticleParameters p; p.deSerialize(is, m_proto_ver); ClientEvent *event = new ClientEvent(); event->type = CE_SPAWN_PARTICLE; event->spawn_particle = new ParticleParameters(p); m_client_event_queue.push(event); } void Client::handleCommand_AddParticleSpawner(NetworkPacket* pkt) { std::string datastring(pkt->getString(0), pkt->getSize()); std::istringstream is(datastring, std::ios_base::binary); ParticleSpawnerParameters p; u32 server_id; u16 attached_id = 0; p.amount = readU16(is); p.time = readF32(is); p.minpos = readV3F32(is); p.maxpos = readV3F32(is); p.minvel = readV3F32(is); p.maxvel = readV3F32(is); p.minacc = readV3F32(is);