-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDataSource.cs
More file actions
543 lines (497 loc) · 18.2 KB
/
DataSource.cs
File metadata and controls
543 lines (497 loc) · 18.2 KB
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//using System.ServiceModel.Channels;
//using System.ServiceModel;
using System.IO;
using System.Threading;
using System.Collections.Concurrent;
namespace DataSource
{
public class DS
{
//private static int SHORT_BYTES = 2;
private static int INT_BYTES = 4;
//private static int LONG_BYTES = 8;
private static int FLOAT_BYTES = 4;
private static int DOUBLE_BYTES = 8;
private const byte GET_PLAYER_LOCATION = 0;
private const byte GET_WORLD_PATH = 20;
private const byte SET_PLAYER_LOCATION = 30;
private const byte ACK_COMMAND = 99;
public const byte SAVE_WAYPOINT = 100;
public const byte SAVE_HOUSE_POINT = 101;
public const byte SAVE_PORTAL_POINT = 102;
public const byte SAVE_FIGHT_POINT = 103;
public const byte SAVE_SPOT_POINT = 104;
public const byte SAVE_DEATH_POINT = 105;
public const byte SAVE_HEAR_POINT = 106;
/// <summary>
/// True if connected.
/// </summary>
public static bool isConnected
{
get
{
return client != null && client.Connected;
}
}
public static void ShutDown()
{
shuttingDown = true;
client.Disconnect();
}
private static bool shuttingDown = false;
protected static BytesEventTcpClient client;
protected static DSHandlerPlayerLocation playerLocationHandler;
public static void InitializePlayerLocation(DSHandlerPlayerLocation handlerparam)
{
playerLocationHandler = handlerparam;
}
protected static DSHandlerConnectionStatusChanged connectionStatusChangedHandler;
public static void InitializeConnectionStatusChanged(DSHandlerConnectionStatusChanged handlerparam)
{
connectionStatusChangedHandler = handlerparam;
}
protected static DSHandlerWorldPath worldPathHandler;
public static void InitializeWorldPath(DSHandlerWorldPath handlerparam)
{
worldPathHandler = handlerparam;
}
private static void ConnectionStatusChanged(ConnectionStatus connectionStatus)
{
if (connectionStatusChangedHandler != null)
connectionStatusChangedHandler.ConnectionStatusChanged(connectionStatus);
}
/// <summary>
/// Requests from the Minecraft Client the player's location.
/// </summary>
public static void GetPlayerLocation(string name)
{
if (isConnected)
{
int nameLength = name.Length;
byte[] data = new byte[1 + 4 + nameLength];
data[0] = GET_PLAYER_LOCATION;
InsertBytes(data, 1, ByteConverter.GetBytes(nameLength));
InsertBytes(data, 5, ByteConverter.GetBytes(name));
client.Send(data);
}
}
public static void SetPlayerLocation(string name, int x, int y, int z)
{
int nameLength = name.Length;
byte[] data = new byte[1 + 4 + nameLength + (DOUBLE_BYTES * 3)];
int i = 0;
data[i] = SET_PLAYER_LOCATION;
i++;
InsertBytes(data, i, ByteConverter.GetBytes(x)); // X
i += INT_BYTES;
InsertBytes(data, i, ByteConverter.GetBytes(y)); // Y
i += INT_BYTES;
InsertBytes(data, i, ByteConverter.GetBytes(z)); // Z
i += INT_BYTES;
InsertBytes(data, i, ByteConverter.GetBytes(nameLength));
i += INT_BYTES;
InsertBytes(data, i, ByteConverter.GetBytes(name));
i += nameLength;
client.Send(data);
}
/// <summary>
/// Requests from the Minecraft Client the player's location.
/// </summary>
public static void GetWorldPath(string name)
{
if (isConnected)
{
int nameLength = name.Length;
byte[] data = new byte[1 + 4 + nameLength];
data[0] = GET_WORLD_PATH;
InsertBytes(data, 1, ByteConverter.GetBytes(nameLength));
InsertBytes(data, 5, ByteConverter.GetBytes(name));
client.Send(data);
}
}
//private static System.Diagnostics.Stopwatch sw;
/// <summary>
/// Handles a message received from the Minecraft Client.
/// </summary>
/// <param name="message">The string received from the Minecraft Client.</param>
private static void HandleMessage(byte[] message)
{
if (message.Length <= 0)
return;
byte messageType = message[0];
if (messageType == GET_PLAYER_LOCATION)
{
//if (sw == null)
// sw = new System.Diagnostics.Stopwatch();
//else
//{
// sw.Stop();
// File.AppendAllText("getplayerlocationlog.txt", sw.ElapsedTicks + Environment.NewLine);
// sw.Reset();
//}
HandlePlayerLocation(message);
//sw.Start();
}
else if (messageType == GET_WORLD_PATH)
{
HandleWorldPath(message);
}
else if (messageType >= SAVE_WAYPOINT && messageType <= SAVE_HEAR_POINT)
{
HandleTrackerCommand(message);
}
else
{
Console.WriteLine("Got message: " + message[0].ToString());
}
}
private static void HandleTrackerCommand(byte[] message)
{
if (worldPathHandler != null)
{
try
{
int reqIdx = 1;
int sizeOfPlayerName = ByteConverter.ToInt32(message, reqIdx);
reqIdx += INT_BYTES;
string pName = ByteConverter.ToString(message, reqIdx, sizeOfPlayerName);
reqIdx += sizeOfPlayerName;
int sizeOfDesc = ByteConverter.ToInt32(message, reqIdx);
reqIdx += INT_BYTES;
string desc = ByteConverter.ToString(message, reqIdx, sizeOfDesc);
reqIdx += sizeOfPlayerName;
string response;
response = worldPathHandler.CommandReceived(message[0], pName, desc);
if (response != null) {
int responseLength = response.Length;
int pNameLength = pName.Length;
byte[] data = new byte[1 + 4 + responseLength + 4 + pNameLength];
int i = 0;
data[i] = ACK_COMMAND;
i++;
InsertBytes(data, i, ByteConverter.GetBytes(pNameLength));
i += INT_BYTES;
InsertBytes(data, i, ByteConverter.GetBytes(pName));
i += pNameLength;
InsertBytes(data, i, ByteConverter.GetBytes(responseLength));
i += INT_BYTES;
InsertBytes(data, i, ByteConverter.GetBytes(response));
i += responseLength;
client.Send(data);
}
}
catch (Exception ex)
{
File.AppendAllText("errordump.txt", "\r\nAn error occurred while handling a world path.\r\n" + ex.ToString() + "\r\n");
System.Windows.Forms.MessageBox.Show("An error occurred while handling a world path." + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);
}
}
}
private static void HandlePlayerLocation(byte[] message)
{
try
{
if (playerLocationHandler == null)
return;
List<Entity> players = new List<Entity>();
int reqIdx = 1;
int sizeOfPlayerName = ByteConverter.ToInt32(message, reqIdx);
reqIdx += INT_BYTES;
string playerName = ByteConverter.ToString(message, reqIdx, sizeOfPlayerName);
reqIdx += sizeOfPlayerName;
Entity playerMe = null;
while (reqIdx < message.Length)
{
Entity p = new Entity();
p.z = -ByteConverter.ToDouble(message, reqIdx);
reqIdx += DOUBLE_BYTES;
p.x = ByteConverter.ToDouble(message, reqIdx);
reqIdx += DOUBLE_BYTES;
p.y = ByteConverter.ToDouble(message, reqIdx);
reqIdx += DOUBLE_BYTES;
p.rotation = ByteConverter.ToSingle(message, reqIdx);
reqIdx += FLOAT_BYTES;
p.pitch = ByteConverter.ToSingle(message, reqIdx);
reqIdx += FLOAT_BYTES;
int namesize = ByteConverter.ToInt32(message, reqIdx);
reqIdx += INT_BYTES;
p.name = ByteConverter.ToString(message, reqIdx, namesize);
reqIdx += namesize;
p.isNPC = ByteConverter.ToBoolean(message, reqIdx);
reqIdx++;
p.Calc();
AddEntity(players, p, playerName);
if (p.name == playerName)
playerMe = p;
}
if (playerMe != null)
{
try
{
playerLocationHandler.PlayerLocationReceived(players, playerMe);
}
catch (Exception ex)
{
File.AppendAllText("errordump.txt", "\r\nAn error occurred while handling a player location.\r\n" + ex.ToString() + "\r\n");
System.Windows.Forms.MessageBox.Show("An error occurred while handling a player location." + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
return;
}
}
private static void HandleWorldPath(byte[] message)
{
string worldInfo = ByteConverter.ToString(message, 1, message.Length - 1);
if (worldInfo == "Unknown")
if (worldPathHandler != null)
try
{
worldPathHandler.WorldPathReceived("Unknown", 0, "Unknown", 0, 0, 0);
}
catch (Exception ex)
{
File.AppendAllText("errordump.txt", "\r\nAn error occurred while handling a world path.\r\n" + ex.ToString() + "\r\n");
System.Windows.Forms.MessageBox.Show("An error occurred while handling a world path." + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);
}
string[] parts = worldInfo.Split('|');
if (parts.Length < 6)
return;
else if (parts.Length > 6)
{
// In case the path SOMEHOW had a | in it, the string array will be messed up. Maybe I am just paranoid.
StringBuilder sbPathParts = new StringBuilder();
for (int i = 0; i <= parts.Length - 6; i++)
sbPathParts.Append(parts[i]);
string[] partsNew = new string[6];
partsNew[0] = sbPathParts.ToString();
for (int i = parts.Length - 5, j = 1; i < parts.Length; i++, j++)
partsNew[j] = parts[i];
parts = partsNew;
}
int dimension;
if (!int.TryParse(parts[1], out dimension))
dimension = 0;
int spawnX;
if (!int.TryParse(parts[3], out spawnX))
spawnX = 0;
int spawnY;
if (!int.TryParse(parts[4], out spawnY))
spawnY = 0;
int spawnZ;
if (!int.TryParse(parts[5], out spawnZ))
spawnZ = 0;
if (worldPathHandler != null)
try
{
worldPathHandler.WorldPathReceived(parts[0], dimension, parts[2], spawnX, spawnY, spawnZ);
}
catch (Exception ex)
{
File.AppendAllText("errordump.txt", "\r\nAn error occurred while handling a world path.\r\n" + ex.ToString() + "\r\n");
System.Windows.Forms.MessageBox.Show("An error occurred while handling a world path." + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);
}
}
/// <summary>
/// Checks PermissionManager and adds the entity to the list if allowed.
/// </summary>
/// <param name="players"></param>
/// <param name="p"></param>
private static void AddEntity(List<Entity> entities, Entity e, string playerName)
{
if (!e.isNPC)
{
entities.Add(e);
}
}
public static void InsertBytes(byte[] destination, int destinationOffset, byte[] source)
{
if (destination.Length - destinationOffset < source.Length)
return;
for (int i = 0; i < source.Length; i++, destinationOffset++)
destination[destinationOffset] = source[i];
}
#region Networking
protected static string lastHost = "";
protected static ushort lastPort = 12345;
public static void Connect(string host, ushort port, bool isRetry = false)
{
if (shuttingDown)
return;
if (!isRetry)
ConnectionStatusChanged(ConnectionStatus.Connecting);
client = new BytesEventTcpClient();
client.OnConnect += new EventTcpClient.OnConnectEventHandler(client_OnConnect);
client.OnDataReceived += new BytesEventTcpClient.BytesReceivedEventHandler(client_OnDataReceived);
client.OnDisconnect += new EventTcpClient.OnDisconnectEventHandler(client_OnDisconnect);
client.OnRefused += new EventTcpClient.OnRefusedEventHandler(client_OnRefused);
lastHost = host;
lastPort = port;
client.Connect(host, port);
}
public static void Disconnect()
{
if (client != null ) {
client.Disconnect();
client = null;
}
}
/// <summary>
/// Called if a connection is refused (unable to connect).
/// </summary>
static void client_OnRefused()
{
ConnectionStatusChanged(ConnectionStatus.Refused);
//System.Windows.Forms.MessageBox.Show("Connection refused. If Minecraft is already running and a world is loaded, you may have forgotten to install Risugami's ModLoader, or the Automap mod may not be installed correctly.");
Console.WriteLine("Connection Refused");
Connect(lastHost, lastPort, true);
}
public static bool doReconnect = true;
/// <summary>
/// Called when we get disconnected.
/// </summary>
static void client_OnDisconnect()
{
ConnectionStatusChanged(ConnectionStatus.Disconnected);
//if (!shuttingDown)
// System.Windows.Forms.MessageBox.Show("Disconnected");
Console.WriteLine("Disconnected");
if (doReconnect) {
Connect(lastHost, lastPort, true);
}
}
/// <summary>
/// Called when data is received.
/// </summary>
/// <param name="message">A byte array that has been received.</param>
static void client_OnDataReceived(byte[] message)
{
HandleMessage(message);
}
/// <summary>
/// Called when we establish a connection.
/// </summary>
static void client_OnConnect()
{
ConnectionStatusChanged(ConnectionStatus.Connected);
Console.WriteLine("Connected");
}
#endregion
}
public interface DSHandlerPlayerLocation
{
void PlayerLocationReceived(List<Entity> players, Entity userPlayer);
}
public enum ConnectionStatus { Idle, Connecting, Connected, Refused, Disconnected };
public interface DSHandlerConnectionStatusChanged
{
void ConnectionStatusChanged(ConnectionStatus newStatus);
}
public interface DSHandlerWorldPath
{
void WorldPathReceived(string worldPath, int dimension, string worldName, int spawnX, int spawnY, int spawnZ);
string CommandReceived(byte command, string playerName, string desc);
}
public class Entity
{
public string name = "default";
public double x = 0;
public double y = 0;
public double z = 0;
public int ix = 0;
public int iy = 0;
public int iz = 0;
public double rotation = 0;
public float pitch = 0;
public bool isNPC = false;
public Entity()
{
}
public void Calc()
{
ix = (int)Math.Floor(x);
iy = (int)Math.Floor(y);
iz = (int)Math.Floor(z);
this.rotation = (Math.PI / 180) * (rotation - 90);
}
}
public static class ByteConverter
{
public static byte[] GetBytes(int data)
{
return new byte[]
{
(byte) ((data >> 24) & 0xff),
(byte) ((data >> 16) & 0xff),
(byte) ((data >> 8) & 0xff),
(byte) ((data >> 0) & 0xff),
};
}
public static byte[] GetBytes(string data)
{
try
{
return Encoding.UTF8.GetBytes(data);
}
catch (Exception)
{
return new byte[0];
}
}
public static int ToInt32(byte[] data, int startIndex)
{
if (data == null || data.Length - startIndex < 4)
return 0;
// ----------
return (int)( // NOTE: type cast not necessary for int
(0xff & data[startIndex]) << 24
| (0xff & data[startIndex + 1]) << 16
| (0xff & data[startIndex + 2]) << 8
| (0xff & data[startIndex + 3]) << 0);
}
public static float ToSingle(byte[] data, int startIndex)
{
byte[] temp = new byte[4];
temp[0] = data[startIndex + 3];
temp[1] = data[startIndex + 2];
temp[2] = data[startIndex + 1];
temp[3] = data[startIndex + 0];
return System.BitConverter.ToSingle(temp, 0);
}
public static double ToDouble(byte[] data, int startIndex)
{
byte[] temp = new byte[8];
temp[0] = data[startIndex + 7];
temp[1] = data[startIndex + 6];
temp[2] = data[startIndex + 5];
temp[3] = data[startIndex + 4];
temp[4] = data[startIndex + 3];
temp[5] = data[startIndex + 2];
temp[6] = data[startIndex + 1];
temp[7] = data[startIndex + 0];
return System.BitConverter.ToDouble(temp, 0);
}
public static bool ToBoolean(byte[] data, int startIndex)
{
return (data == null || data.Length - startIndex < 1) ? false : data[startIndex] != 0x00;
}
public static string ToString(byte[] message, int startIndex, int bytesToConvert)
{
try
{
return Encoding.UTF8.GetString(message, startIndex, bytesToConvert);
}
catch (Exception)
{
return "";
}
}
}
}