Planet
navi homePPSaboutscreenshotsdownloaddevelopmentforum

source: code/branches/SuperOrxoBros_HS18/SuperOrxoBros_HS18/src/external/enet/host.c @ 12175

Last change on this file since 12175 was 12175, checked in by siramesh, 5 years ago

Super Orxo Bros (Sidharth Ramesh, Nisa Balta, Jeff Ren)

File size: 17.9 KB
Line 
1/**
2 @file host.c
3 @brief ENet host management functions
4*/
5#define ENET_BUILDING_LIB 1
6#include <string.h>
7#include <time.h>
8#include "enet/enet.h"
9
10static ENetSocket
11enet_socket_create_bind (const ENetAddress * address, ENetAddressFamily family)
12{
13    ENetSocket socket = enet_socket_create (ENET_SOCKET_TYPE_DATAGRAM, family);
14    if (socket == ENET_SOCKET_NULL)
15        return ENET_SOCKET_NULL;
16
17    /* This is not a conditional bind anymore,
18     * because WSARecvFrom returned WSAEINVAL on the IPv6 socket.
19     * TODO: Check for it's consequences. */
20    if (enet_socket_bind (socket, address, family) < 0)
21    {
22        enet_socket_destroy (socket);
23        return ENET_SOCKET_NULL;
24    }
25
26    enet_socket_set_option (socket, ENET_SOCKOPT_NONBLOCK, 1);
27    enet_socket_set_option (socket, ENET_SOCKOPT_BROADCAST, 1);
28    enet_socket_set_option (socket, ENET_SOCKOPT_RCVBUF, ENET_HOST_RECEIVE_BUFFER_SIZE);
29    enet_socket_set_option (socket, ENET_SOCKOPT_SNDBUF, ENET_HOST_SEND_BUFFER_SIZE);
30
31    return socket;
32}
33
34/** @defgroup host ENet host functions
35    @{
36*/
37
38/** Creates a host for communicating to peers. 
39
40    @param address   the address at which other peers may connect to this host.  If NULL, then no peers may connect to the host.
41    @param peerCount the maximum number of peers that should be allocated for the host.
42    @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT
43    @param incomingBandwidth downstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth.
44    @param outgoingBandwidth upstream bandwidth of the host in bytes/second; if 0, ENet will assume unlimited bandwidth.
45
46    @returns the host on success and NULL on failure
47
48    @remarks ENet will strategically drop packets on specific sides of a connection between hosts
49    to ensure the host's bandwidth is not overwhelmed.  The bandwidth parameters also determine
50    the window size of a connection which limits the amount of reliable packets that may be in transit
51    at any given time.
52*/
53ENetHost *
54enet_host_create (const ENetAddress * address, size_t peerCount, size_t channelLimit, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth)
55{
56    ENetHost * host;
57    ENetPeer * currentPeer;
58    int family;
59
60    if (peerCount > ENET_PROTOCOL_MAXIMUM_PEER_ID)
61      return NULL;
62
63    host = (ENetHost *) enet_malloc (sizeof (ENetHost));
64    if (host == NULL)
65      return NULL;
66
67    host -> peers = (ENetPeer *) enet_malloc (peerCount * sizeof (ENetPeer));
68    if (host -> peers == NULL)
69    {
70       enet_free (host);
71
72       return NULL;
73    }
74    memset (host -> peers, 0, peerCount * sizeof (ENetPeer));
75
76    family = (address == NULL || !memcmp (& address -> host, & ENET_HOST_ANY, sizeof (ENetHostAddress))) ?
77        ENET_IPV4 | ENET_IPV6 :
78        enet_get_address_family (address);
79
80    host -> socket4 = (family & ENET_IPV4) ?
81      enet_socket_create_bind (address, ENET_IPV4) :
82      ENET_SOCKET_NULL;
83    host -> socket6 = (family & ENET_IPV6) ?
84      enet_socket_create_bind (address, ENET_IPV6) :
85      ENET_SOCKET_NULL;
86
87    if (host -> socket4 == ENET_SOCKET_NULL && host -> socket6 == ENET_SOCKET_NULL)
88    {
89        enet_free (host -> peers);
90        enet_free (host);
91        return NULL;
92    }
93
94    if (address != NULL)
95      host -> address = * address;
96
97    if (! channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
98      channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
99    else
100    if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
101      channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
102
103    host -> randomSeed = (enet_uint32) time(NULL) + (enet_uint32) (size_t) host;
104    host -> randomSeed = (host -> randomSeed << 16) | (host -> randomSeed >> 16);
105    host -> channelLimit = channelLimit;
106    host -> incomingBandwidth = incomingBandwidth;
107    host -> outgoingBandwidth = outgoingBandwidth;
108    host -> bandwidthThrottleEpoch = 0;
109    host -> recalculateBandwidthLimits = 0;
110    host -> mtu = ENET_HOST_DEFAULT_MTU;
111    host -> peerCount = peerCount;
112    host -> commandCount = 0;
113    host -> bufferCount = 0;
114    host -> checksum = NULL;
115    host -> receivedAddress.host = ENET_HOST_ANY;
116    host -> receivedAddress.port = 0;
117    host -> receivedData = NULL;
118    host -> receivedDataLength = 0;
119     
120    host -> totalSentData = 0;
121    host -> totalSentPackets = 0;
122    host -> totalReceivedData = 0;
123    host -> totalReceivedPackets = 0;
124
125    host -> compressor.context = NULL;
126    host -> compressor.compress = NULL;
127    host -> compressor.decompress = NULL;
128    host -> compressor.destroy = NULL;
129
130    enet_list_clear (& host -> dispatchQueue);
131
132    for (currentPeer = host -> peers;
133         currentPeer < & host -> peers [host -> peerCount];
134         ++ currentPeer)
135    {
136       currentPeer -> host = host;
137       currentPeer -> incomingPeerID = currentPeer - host -> peers;
138       currentPeer -> outgoingSessionID = currentPeer -> incomingSessionID = 0xFF;
139       currentPeer -> data = NULL;
140
141       enet_list_clear (& currentPeer -> acknowledgements);
142       enet_list_clear (& currentPeer -> sentReliableCommands);
143       enet_list_clear (& currentPeer -> sentUnreliableCommands);
144       enet_list_clear (& currentPeer -> outgoingReliableCommands);
145       enet_list_clear (& currentPeer -> outgoingUnreliableCommands);
146       enet_list_clear (& currentPeer -> dispatchedCommands);
147
148       enet_peer_reset (currentPeer);
149    }
150
151    return host;
152}
153
154/** Destroys the host and all resources associated with it.
155    @param host pointer to the host to destroy
156*/
157void
158enet_host_destroy (ENetHost * host)
159{
160    ENetPeer * currentPeer;
161
162    if (host -> socket4 != ENET_SOCKET_NULL)
163      enet_socket_destroy (host -> socket4);
164    if (host -> socket6 != ENET_SOCKET_NULL)
165      enet_socket_destroy (host -> socket6);
166
167    for (currentPeer = host -> peers;
168         currentPeer < & host -> peers [host -> peerCount];
169         ++ currentPeer)
170    {
171       enet_peer_reset (currentPeer);
172    }
173
174    if (host -> compressor.context != NULL && host -> compressor.destroy)
175      (* host -> compressor.destroy) (host -> compressor.context);
176
177    enet_free (host -> peers);
178    enet_free (host);
179}
180
181/** Initiates a connection to a foreign host.
182    @param host host seeking the connection
183    @param address destination for the connection
184    @param channelCount number of channels to allocate
185    @param data user data supplied to the receiving host
186    @returns a peer representing the foreign host on success, NULL on failure
187    @remarks The peer returned will have not completed the connection until enet_host_service()
188    notifies of an ENET_EVENT_TYPE_CONNECT event for the peer.
189*/
190ENetPeer *
191enet_host_connect (ENetHost * host, const ENetAddress * address, size_t channelCount, enet_uint32 data)
192{
193    ENetPeer * currentPeer;
194    ENetChannel * channel;
195    ENetProtocol command;
196
197    if (channelCount < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
198      channelCount = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
199    else
200    if (channelCount > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
201      channelCount = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
202
203    for (currentPeer = host -> peers;
204         currentPeer < & host -> peers [host -> peerCount];
205         ++ currentPeer)
206    {
207       if (currentPeer -> state == ENET_PEER_STATE_DISCONNECTED)
208         break;
209    }
210
211    if (currentPeer >= & host -> peers [host -> peerCount])
212      return NULL;
213
214    currentPeer -> channels = (ENetChannel *) enet_malloc (channelCount * sizeof (ENetChannel));
215    if (currentPeer -> channels == NULL)
216      return NULL;
217    currentPeer -> channelCount = channelCount;
218    currentPeer -> state = ENET_PEER_STATE_CONNECTING;
219    currentPeer -> address = * address;
220    currentPeer -> connectID = ++ host -> randomSeed;
221
222    if (host -> outgoingBandwidth == 0)
223      currentPeer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
224    else
225      currentPeer -> windowSize = (host -> outgoingBandwidth /
226                                    ENET_PEER_WINDOW_SIZE_SCALE) * 
227                                      ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
228
229    if (currentPeer -> windowSize < ENET_PROTOCOL_MINIMUM_WINDOW_SIZE)
230      currentPeer -> windowSize = ENET_PROTOCOL_MINIMUM_WINDOW_SIZE;
231    else
232    if (currentPeer -> windowSize > ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE)
233      currentPeer -> windowSize = ENET_PROTOCOL_MAXIMUM_WINDOW_SIZE;
234         
235    for (channel = currentPeer -> channels;
236         channel < & currentPeer -> channels [channelCount];
237         ++ channel)
238    {
239        channel -> outgoingReliableSequenceNumber = 0;
240        channel -> outgoingUnreliableSequenceNumber = 0;
241        channel -> incomingReliableSequenceNumber = 0;
242
243        enet_list_clear (& channel -> incomingReliableCommands);
244        enet_list_clear (& channel -> incomingUnreliableCommands);
245
246        channel -> usedReliableWindows = 0;
247        memset (channel -> reliableWindows, 0, sizeof (channel -> reliableWindows));
248    }
249       
250    command.header.command = ENET_PROTOCOL_COMMAND_CONNECT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
251    command.header.channelID = 0xFF;
252    command.connect.outgoingPeerID = ENET_HOST_TO_NET_16 (currentPeer -> incomingPeerID);
253    command.connect.incomingSessionID = currentPeer -> incomingSessionID;
254    command.connect.outgoingSessionID = currentPeer -> outgoingSessionID;
255    command.connect.mtu = ENET_HOST_TO_NET_32 (currentPeer -> mtu);
256    command.connect.windowSize = ENET_HOST_TO_NET_32 (currentPeer -> windowSize);
257    command.connect.channelCount = ENET_HOST_TO_NET_32 (channelCount);
258    command.connect.incomingBandwidth = ENET_HOST_TO_NET_32 (host -> incomingBandwidth);
259    command.connect.outgoingBandwidth = ENET_HOST_TO_NET_32 (host -> outgoingBandwidth);
260    command.connect.packetThrottleInterval = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleInterval);
261    command.connect.packetThrottleAcceleration = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleAcceleration);
262    command.connect.packetThrottleDeceleration = ENET_HOST_TO_NET_32 (currentPeer -> packetThrottleDeceleration);
263    command.connect.connectID = currentPeer -> connectID;
264    command.connect.data = ENET_HOST_TO_NET_32 (data);
265 
266    enet_peer_queue_outgoing_command (currentPeer, & command, NULL, 0, 0);
267
268    return currentPeer;
269}
270
271/** Queues a packet to be sent to all peers associated with the host.
272    @param host host on which to broadcast the packet
273    @param channelID channel on which to broadcast
274    @param packet packet to broadcast
275*/
276void
277enet_host_broadcast (ENetHost * host, enet_uint8 channelID, ENetPacket * packet)
278{
279    ENetPeer * currentPeer;
280
281    for (currentPeer = host -> peers;
282         currentPeer < & host -> peers [host -> peerCount];
283         ++ currentPeer)
284    {
285       if (currentPeer -> state != ENET_PEER_STATE_CONNECTED)
286         continue;
287
288       enet_peer_send (currentPeer, channelID, packet);
289    }
290
291    if (packet -> referenceCount == 0)
292      enet_packet_destroy (packet);
293}
294
295/** Sets the packet compressor the host should use to compress and decompress packets.
296    @param host host to enable or disable compression for
297    @param compressor callbacks for for the packet compressor; if NULL, then compression is disabled
298*/
299void
300enet_host_compress (ENetHost * host, const ENetCompressor * compressor)
301{
302    if (host -> compressor.context != NULL && host -> compressor.destroy)
303      (* host -> compressor.destroy) (host -> compressor.context);
304
305    if (compressor)
306      host -> compressor = * compressor;
307    else
308      host -> compressor.context = NULL;
309}
310
311/** Limits the maximum allowed channels of future incoming connections.
312    @param host host to limit
313    @param channelLimit the maximum number of channels allowed; if 0, then this is equivalent to ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT
314*/
315void
316enet_host_channel_limit (ENetHost * host, size_t channelLimit)
317{
318    if (! channelLimit || channelLimit > ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT)
319      channelLimit = ENET_PROTOCOL_MAXIMUM_CHANNEL_COUNT;
320    else
321    if (channelLimit < ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT)
322      channelLimit = ENET_PROTOCOL_MINIMUM_CHANNEL_COUNT;
323
324    host -> channelLimit = channelLimit;
325}
326
327
328/** Adjusts the bandwidth limits of a host.
329    @param host host to adjust
330    @param incomingBandwidth new incoming bandwidth
331    @param outgoingBandwidth new outgoing bandwidth
332    @remarks the incoming and outgoing bandwidth parameters are identical in function to those
333    specified in enet_host_create().
334*/
335void
336enet_host_bandwidth_limit (ENetHost * host, enet_uint32 incomingBandwidth, enet_uint32 outgoingBandwidth)
337{
338    host -> incomingBandwidth = incomingBandwidth;
339    host -> outgoingBandwidth = outgoingBandwidth;
340    host -> recalculateBandwidthLimits = 1;
341}
342
343void
344enet_host_bandwidth_throttle (ENetHost * host)
345{
346    enet_uint32 timeCurrent = enet_time_get (),
347           elapsedTime = timeCurrent - host -> bandwidthThrottleEpoch,
348           peersTotal = 0,
349           dataTotal = 0,
350           peersRemaining,
351           bandwidth,
352           throttle = 0,
353           bandwidthLimit = 0;
354    int needsAdjustment;
355    ENetPeer * peer;
356    ENetProtocol command;
357
358    if (elapsedTime < ENET_HOST_BANDWIDTH_THROTTLE_INTERVAL)
359      return;
360
361    for (peer = host -> peers;
362         peer < & host -> peers [host -> peerCount];
363         ++ peer)
364    {
365        if (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)
366          continue;
367
368        ++ peersTotal;
369        dataTotal += peer -> outgoingDataTotal;
370    }
371
372    if (peersTotal == 0)
373      return;
374
375    peersRemaining = peersTotal;
376    needsAdjustment = 1;
377
378    if (host -> outgoingBandwidth == 0)
379      bandwidth = ~0;
380    else
381      bandwidth = (host -> outgoingBandwidth * elapsedTime) / 1000;
382
383    while (peersRemaining > 0 && needsAdjustment != 0)
384    {
385        needsAdjustment = 0;
386       
387        if (dataTotal < bandwidth)
388          throttle = ENET_PEER_PACKET_THROTTLE_SCALE;
389        else
390          throttle = (bandwidth * ENET_PEER_PACKET_THROTTLE_SCALE) / dataTotal;
391
392        for (peer = host -> peers;
393             peer < & host -> peers [host -> peerCount];
394             ++ peer)
395        {
396            enet_uint32 peerBandwidth;
397           
398            if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) ||
399                peer -> incomingBandwidth == 0 ||
400                peer -> outgoingBandwidthThrottleEpoch == timeCurrent)
401              continue;
402
403            peerBandwidth = (peer -> incomingBandwidth * elapsedTime) / 1000;
404            if ((throttle * peer -> outgoingDataTotal) / ENET_PEER_PACKET_THROTTLE_SCALE <= peerBandwidth)
405              continue;
406
407            peer -> packetThrottleLimit = (peerBandwidth * 
408                                            ENET_PEER_PACKET_THROTTLE_SCALE) / peer -> outgoingDataTotal;
409           
410            if (peer -> packetThrottleLimit == 0)
411              peer -> packetThrottleLimit = 1;
412           
413            if (peer -> packetThrottle > peer -> packetThrottleLimit)
414              peer -> packetThrottle = peer -> packetThrottleLimit;
415
416            peer -> outgoingBandwidthThrottleEpoch = timeCurrent;
417
418           
419            needsAdjustment = 1;
420            -- peersRemaining;
421            bandwidth -= peerBandwidth;
422            dataTotal -= peerBandwidth;
423        }
424    }
425
426    if (peersRemaining > 0)
427    for (peer = host -> peers;
428         peer < & host -> peers [host -> peerCount];
429         ++ peer)
430    {
431        if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) ||
432            peer -> outgoingBandwidthThrottleEpoch == timeCurrent)
433          continue;
434
435        peer -> packetThrottleLimit = throttle;
436
437        if (peer -> packetThrottle > peer -> packetThrottleLimit)
438          peer -> packetThrottle = peer -> packetThrottleLimit;
439    }
440   
441    if (host -> recalculateBandwidthLimits)
442    {
443       host -> recalculateBandwidthLimits = 0;
444
445       peersRemaining = peersTotal;
446       bandwidth = host -> incomingBandwidth;
447       needsAdjustment = 1;
448
449       if (bandwidth == 0)
450         bandwidthLimit = 0;
451       else
452       while (peersRemaining > 0 && needsAdjustment != 0)
453       {
454           needsAdjustment = 0;
455           bandwidthLimit = bandwidth / peersRemaining;
456
457           for (peer = host -> peers;
458                peer < & host -> peers [host -> peerCount];
459                ++ peer)
460           {
461               if ((peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER) ||
462                   peer -> incomingBandwidthThrottleEpoch == timeCurrent)
463                 continue;
464
465               if (peer -> outgoingBandwidth > 0 &&
466                   peer -> outgoingBandwidth >= bandwidthLimit)
467                 continue;
468
469               peer -> incomingBandwidthThrottleEpoch = timeCurrent;
470 
471               needsAdjustment = 1;
472               -- peersRemaining;
473               bandwidth -= peer -> outgoingBandwidth;
474           }
475       }
476
477       for (peer = host -> peers;
478            peer < & host -> peers [host -> peerCount];
479            ++ peer)
480       {
481           if (peer -> state != ENET_PEER_STATE_CONNECTED && peer -> state != ENET_PEER_STATE_DISCONNECT_LATER)
482             continue;
483
484           command.header.command = ENET_PROTOCOL_COMMAND_BANDWIDTH_LIMIT | ENET_PROTOCOL_COMMAND_FLAG_ACKNOWLEDGE;
485           command.header.channelID = 0xFF;
486           command.bandwidthLimit.outgoingBandwidth = ENET_HOST_TO_NET_32 (host -> outgoingBandwidth);
487
488           if (peer -> incomingBandwidthThrottleEpoch == timeCurrent)
489             command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32 (peer -> outgoingBandwidth);
490           else
491             command.bandwidthLimit.incomingBandwidth = ENET_HOST_TO_NET_32 (bandwidthLimit);
492
493           enet_peer_queue_outgoing_command (peer, & command, NULL, 0, 0);
494       } 
495    }
496
497    host -> bandwidthThrottleEpoch = timeCurrent;
498
499    for (peer = host -> peers;
500         peer < & host -> peers [host -> peerCount];
501         ++ peer)
502    {
503        peer -> incomingDataTotal = 0;
504        peer -> outgoingDataTotal = 0;
505    }
506}
507   
508/** @} */
Note: See TracBrowser for help on using the repository browser.