File: OSCStatsSender.cpp

package info (click to toggle)
spring 88.0%2Bdfsg1-1.1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 41,524 kB
  • sloc: cpp: 343,114; ansic: 38,414; python: 12,257; java: 12,203; awk: 5,748; sh: 1,204; xml: 997; perl: 405; objc: 192; makefile: 181; php: 134; sed: 2
file content (367 lines) | stat: -rwxr-xr-x 9,503 bytes parent folder | download
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
/* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */

#include <boost/asio.hpp> // must be included before streflop!

#include "OSCStatsSender.h"

#include "Game.h"
#include "GameVersion.h"
#include "GlobalUnsynced.h"
#include "Player.h"
#include "PlayerHandler.h"
#include "Sim/Misc/TeamHandler.h"
#include "System/Config/ConfigHandler.h"
#include "System/Log/ILog.h"
#include "System/Net/Socket.h"

#include "lib/streflop/streflop_cond.h"
#include "lib/oscpack/OscOutboundPacketStream.h"


CONFIG(bool, OscStatsSenderEnabled).defaultValue(false);
CONFIG(std::string, OscStatsSenderDestinationAddress).defaultValue("127.0.0.1");

CONFIG(int, OscStatsSenderDestinationPort)
	.defaultValue(6447)
	.minimumValue(0)
	.maximumValue(65535);

COSCStatsSender* COSCStatsSender::singleton = NULL;

struct COSCStatsSender::NetStruct
{
	NetStruct() : outSocket(NULL), destination(NULL) {};
	boost::asio::ip::udp::socket* outSocket;
	boost::asio::ip::udp::endpoint* destination;
};

COSCStatsSender::COSCStatsSender(const std::string& dstAddress,
		unsigned int dstPort)
		: sendingEnabled(false), dstAddress(dstAddress), dstPort(dstPort),
		network(NULL),
		oscOutputBuffer(NULL), oscPacker(NULL)
{
	SetEnabled(configHandler->GetBool("OscStatsSenderEnabled"));
}
COSCStatsSender::~COSCStatsSender() {
	SetEnabled(false);
}


void COSCStatsSender::SetEnabled(bool enabled) {

	bool statusChanged = (enabled != sendingEnabled);
	this->sendingEnabled = enabled;

	if (statusChanged) {
		if (enabled) {
			oscOutputBuffer = new char[OSC_OUTPUT_BUFFER_SIZE];
			oscPacker = new osc::OutboundPacketStream(oscOutputBuffer,
					OSC_OUTPUT_BUFFER_SIZE);
			network = new NetStruct;
			network->outSocket = new boost::asio::ip::udp::socket(netcode::netservice, boost::asio::ip::udp::endpoint(boost::asio::ip::address_v6::any(), 0));
			boost::asio::socket_base::broadcast option(true);
			network->outSocket->set_option(option);
			UpdateDestination();
			LOG("Sending spring Statistics over OSC to: %s:%u",
					dstAddress.c_str(), dstPort);

			SendInit();
		} else {
			delete oscPacker;
			oscPacker = NULL;
			delete network->outSocket;
			network->outSocket = NULL;
			delete network->destination;
			network->destination = NULL;
			delete network;
			delete [] oscOutputBuffer;
			oscOutputBuffer = NULL;
		}
	}
}
bool COSCStatsSender::IsEnabled() const {
	return sendingEnabled;
}

COSCStatsSender* COSCStatsSender::GetInstance() {

	if (COSCStatsSender::singleton == NULL) {
		std::string dstAddress = configHandler->GetString("OscStatsSenderDestinationAddress");
		unsigned int dstPort   = configHandler->GetInt("OscStatsSenderDestinationPort");

		static COSCStatsSender instance(dstAddress, dstPort);
		COSCStatsSender::singleton = &instance;
	}

	return COSCStatsSender::singleton;
}


bool COSCStatsSender::SendInit() {

	if (IsEnabled()) {
		try {
			return SendInitialInfo()
					&& SendTeamStatsTitles()
					&& SendPlayerStatsTitles();
		} catch (const boost::system::system_error& ex) {
			LOG_L(L_ERROR, "Failed sending OSC Stats init: %s", ex.what());
			return false;
		}
	} else {
		return false;
	}
}

bool COSCStatsSender::Update(int frameNum) {

	if (IsEnabled() && IsTimeToSend(frameNum)) {
		try {
			// Try to send team stats first, as they are more important,
			// more interesting.
			return SendTeamStats() && SendPlayerStats();
		} catch (const boost::system::system_error& ex) {
			LOG_L(L_ERROR, "Failed sending OSC Stats init: %s", ex.what());
			return false;
		}
	} else {
		return false;
	}
}


void COSCStatsSender::SetDestinationAddress(const std::string& address) {
	this->dstAddress = address;
	UpdateDestination();
}
const std::string& COSCStatsSender::GetDestinationAddress() const {
	return dstAddress;
}

void COSCStatsSender::SetDestinationPort(unsigned int port) {
	this->dstPort = port;
	UpdateDestination();
}
unsigned int COSCStatsSender::GetDestinationPort() const {
	return dstPort;
}


void COSCStatsSender::UpdateDestination() {

	if (network->destination == NULL) {
		network->destination = new boost::asio::ip::udp::endpoint();
	}
	network->destination->address(netcode::WrapIP(dstAddress));
	network->destination->port(dstPort);
}

bool COSCStatsSender::IsTimeToSend(int frameNum) {

	if (IsEnabled() && !((frameNum+5) & 31)) {
		return true;
	}

	return false;
}

bool COSCStatsSender::SendOscBuffer() {

	bool success = false;

	if (oscPacker->IsReady()) {
		network->outSocket->send_to(boost::asio::buffer((const unsigned char*) oscPacker->Data(), oscPacker->Size()), *network->destination);
		oscPacker->Clear();

		success = true;
	}

	return success;
}

bool COSCStatsSender::SendInitialInfo() {

	if (IsEnabled()) {
		(*oscPacker)
				<< osc::BeginBundleImmediate
					<< osc::BeginMessage(OSC_MSG_TOPIC_INIT_TITLES)
						<< "Engine name"
						<< "Engine version"
						<< "Number of teams"
					<< osc::EndMessage
					<< osc::BeginMessage(OSC_MSG_TOPIC_INIT_VALUES)
						<< "spring"
						<< SpringVersion::GetFull().c_str()
						<< teamHandler->ActiveTeams()
					<< osc::EndMessage
				<< osc::EndBundle;

		return SendOscBuffer();
	} else {
		return false;
	}
}
bool COSCStatsSender::SendPlayerStatsTitles() {

	if (IsEnabled()) {
		(*oscPacker)
				<< osc::BeginBundleImmediate
					<< osc::BeginMessage(OSC_MSG_TOPIC_PLAYER_TITLES)
						<< "Player Name"
						<< "Mouse clicks per minute"
						<< "Mouse movement in pixels per minute"
						<< "Keyboard presses per minute"
						<< "Unit commands per minute"
						<< "Average command size (units affected per command)"
					<< osc::EndMessage
				<< osc::EndBundle;

		return SendOscBuffer();
	} else {
		return false;
	}
}

bool COSCStatsSender::SendPlayerStats() {

	static const CPlayer* localPlayer = playerHandler->Player(gu->myPlayerNum);
	static const char* localPlayerName = localPlayer->name.c_str();

	if (IsEnabled()) {
		// get the latest player stats
		const CPlayer::Statistics& playerStats = localPlayer->currentStats;

		(*oscPacker)
				<< osc::BeginBundleImmediate
					<< osc::BeginMessage(OSC_MSG_TOPIC_PLAYER_VALUES)
						<< (const char*) localPlayerName
						<< (float) (playerStats.mouseClicks*60/game->totalGameTime)
						<< (float) (playerStats.mousePixels*60/game->totalGameTime)
						<< (float) (playerStats.keyPresses*60/game->totalGameTime)
						<< (float) (playerStats.numCommands*60/game->totalGameTime)
						<< (float) ((playerStats.numCommands != 0) ?
							((float) playerStats.unitCommands / playerStats.numCommands) : 0.0)
					<< osc::EndMessage
				<< osc::EndBundle;

		return SendOscBuffer();
	} else {
		return false;
	}
}

bool COSCStatsSender::SendTeamStatsTitles() {

	if (IsEnabled()) {
		(*oscPacker)
				<< osc::BeginBundleImmediate
					<< osc::BeginMessage(OSC_MSG_TOPIC_TEAM_TITLES)
						<< "Team number"

						<< "Metal used"
						<< "Energy used"
						<< "Metal produced"
						<< "Energy produced"

						<< "Metal excess"
						<< "Energy excess"

						<< "Metal received"
						<< "Energy received"

						<< "Metal sent"
						<< "Energy sent"

						<< "Metal stored"
						<< "Energy stored"

						<< "Active Units"
						<< "Units killed"

						<< "Units produced"
						<< "Units died"

						<< "Units received"
						<< "Units sent"
						<< "Units captured"
						<< "Units stolen"

						<< "Damage Dealt"
						<< "Damage Received"
					<< osc::EndMessage
				<< osc::EndBundle;

		return SendOscBuffer();
	} else {
		return false;
	}
}

bool COSCStatsSender::SendTeamStats() {

	static const int teamId = gu->myTeam;
	static unsigned int prevHistSize = 0;

	if (IsEnabled()) {
		std::list<CTeam::Statistics> statHistory =
				teamHandler->Team(teamId)->statHistory;
		unsigned int currHistSize = statHistory.size();
		// only send if we did not yet send the latest history stats
		if (currHistSize <= prevHistSize) {
			return false;
		}

		// get the latest history stats
		std::list<CTeam::Statistics>::const_iterator latestStats_p =
				--(statHistory.end());
		const CTeam::Statistics& teamStats = *latestStats_p;

		(*oscPacker)
				<< osc::BeginBundleImmediate
					<< osc::BeginMessage(OSC_MSG_TOPIC_TEAM_VALUES)
						<< (int) teamId

						<< (float) teamStats.metalUsed
						<< (float) teamStats.energyUsed
						<< (float) teamStats.metalProduced
						<< (float) teamStats.energyProduced

						<< (float) teamStats.metalExcess
						<< (float) teamStats.energyExcess

						<< (float) teamStats.metalReceived
						<< (float) teamStats.energyReceived

						<< (float) teamStats.metalSent
						<< (float) teamStats.energySent

						<< (float) (teamStats.metalProduced+teamStats.metalReceived
							- (teamStats.metalUsed+teamStats.metalSent+teamStats.metalExcess))
						<< (float) (teamStats.energyProduced+teamStats.energyReceived
							- (teamStats.energyUsed+teamStats.energySent+teamStats.energyExcess))

						<< (int) (teamStats.unitsProduced+teamStats.unitsReceived+teamStats.unitsCaptured
							- (teamStats.unitsDied+teamStats.unitsSent+teamStats.unitsOutCaptured))
						<< (int) teamStats.unitsKilled

						<< (int) teamStats.unitsProduced
						<< (int) teamStats.unitsDied

						<< (int) teamStats.unitsReceived
						<< (int) teamStats.unitsSent
						<< (int) teamStats.unitsCaptured
						<< (int) teamStats.unitsOutCaptured

						<< (float) teamStats.damageDealt
						<< (float) teamStats.damageReceived
					<< osc::EndMessage
				<< osc::EndBundle;

		prevHistSize = currHistSize;

		return SendOscBuffer();
	} else {
		return false;
	}
}