ServerRepository.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. """ServerRepository module: contains the ServerRepository class"""
  2. from panda3d.core import *
  3. from panda3d.direct import *
  4. from direct.distributed.MsgTypesCMU import *
  5. from direct.task import Task
  6. from direct.directnotify import DirectNotifyGlobal
  7. from direct.distributed.PyDatagram import PyDatagram
  8. class ServerRepository:
  9. """ This maintains the server-side connection with a Panda server.
  10. It is only for use with the Panda LAN server provided by CMU."""
  11. notify = DirectNotifyGlobal.directNotify.newCategory("ServerRepository")
  12. class Client:
  13. """ This internal class keeps track of the data associated
  14. with each connected client. """
  15. def __init__(self, connection, netAddress, doIdBase):
  16. # The connection used to communicate with the client.
  17. self.connection = connection
  18. # The net address to the client, including IP address.
  19. # Used for reporting purposes only.
  20. self.netAddress = netAddress
  21. # The first doId in the range assigned to the client.
  22. # This also serves as a unique numeric ID for this client.
  23. # (It is sometimes called "avatarId" in some update
  24. # messages, even though the client is not required to use
  25. # this particular number as an avatar ID.)
  26. self.doIdBase = doIdBase
  27. # The set of zoneIds that the client explicitly has
  28. # interest in. The client will receive updates for all
  29. # distributed objects appearing in one of these zones.
  30. # (The client will also receive updates for all zones in
  31. # which any one of the distributed obejcts that it has
  32. # created still exist.)
  33. self.explicitInterestZoneIds = set()
  34. # The set of interest zones sent to the client at the last
  35. # update. This is the actual set of zones the client is
  36. # informed of. Changing the explicitInterestZoneIds,
  37. # above, creating or deleting objects in different zones,
  38. # or moving objects between zones, might influence this
  39. # set.
  40. self.currentInterestZoneIds = set()
  41. # A dictionary of doId -> Object, for distributed objects
  42. # currently in existence that were created by the client.
  43. self.objectsByDoId = {}
  44. # A dictionary of zoneId -> set([Object]), listing the
  45. # distributed objects assigned to each zone, of the
  46. # objects created by this client.
  47. self.objectsByZoneId = {}
  48. class Object:
  49. """ This internal class keeps track of the data associated
  50. with each extent distributed object. """
  51. def __init__(self, doId, zoneId, dclass):
  52. # The object's distributed ID.
  53. self.doId = doId
  54. # The object's current zone. Each object is associated
  55. # with only one zone.
  56. self.zoneId = zoneId
  57. # The object's class type.
  58. self.dclass = dclass
  59. # Note that the server does not store any other data about
  60. # the distributed objects; in particular, it doesn't
  61. # record its current fields. That is left to the clients.
  62. def __init__(self, tcpPort, serverAddress = None,
  63. udpPort = None, dcFileNames = None,
  64. threadedNet = None):
  65. if threadedNet is None:
  66. # Default value.
  67. threadedNet = config.GetBool('threaded-net', False)
  68. # Set up networking interfaces.
  69. numThreads = 0
  70. if threadedNet:
  71. numThreads = 1
  72. self.qcm = QueuedConnectionManager()
  73. self.qcl = QueuedConnectionListener(self.qcm, numThreads)
  74. self.qcr = QueuedConnectionReader(self.qcm, numThreads)
  75. self.cw = ConnectionWriter(self.qcm, numThreads)
  76. taskMgr.setupTaskChain('flushTask')
  77. if threadedNet:
  78. taskMgr.setupTaskChain('flushTask', numThreads = 1,
  79. threadPriority = TPLow, frameSync = True)
  80. self.tcpRendezvous = self.qcm.openTCPServerRendezvous(
  81. serverAddress or '', tcpPort, 10)
  82. self.qcl.addConnection(self.tcpRendezvous)
  83. taskMgr.add(self.listenerPoll, "serverListenerPollTask")
  84. taskMgr.add(self.readerPollUntilEmpty, "serverReaderPollTask")
  85. taskMgr.add(self.clientHardDisconnectTask, "clientHardDisconnect")
  86. # A set of clients that have recently been written to and may
  87. # need to be flushed.
  88. self.needsFlush = set()
  89. collectTcpInterval = ConfigVariableDouble('collect-tcp-interval').getValue()
  90. taskMgr.doMethodLater(collectTcpInterval, self.flushTask, 'flushTask',
  91. taskChain = 'flushTask')
  92. # A dictionary of connection -> Client object, tracking all of
  93. # the clients we currently have connected.
  94. self.clientsByConnection = {}
  95. # A similar dictionary of doIdBase -> Client object, indexing
  96. # by the client's doIdBase number instead.
  97. self.clientsByDoIdBase = {}
  98. # A dictionary of zoneId -> set([Client]), listing the clients
  99. # that have an interest in each zoneId.
  100. self.zonesToClients = {}
  101. # A dictionary of zoneId -> set([Object]), listing the
  102. # distributed objects assigned to each zone, globally.
  103. self.objectsByZoneId = {}
  104. # The number of doId's to assign to each client. Must remain
  105. # constant during server lifetime.
  106. self.doIdRange = base.config.GetInt('server-doid-range', 1000000)
  107. # An allocator object that assigns the next doIdBase to each
  108. # client.
  109. self.idAllocator = UniqueIdAllocator(0, 0xffffffff / self.doIdRange)
  110. self.dcFile = DCFile()
  111. self.dcSuffix = ''
  112. self.readDCFile(dcFileNames)
  113. def flushTask(self, task):
  114. """ This task is run periodically to flush any connections
  115. that might need it. It's only necessary in cases where
  116. collect-tcp is set true (if this is false, messages are sent
  117. immediately and do not require periodic flushing). """
  118. flush = self.needsFlush
  119. self.needsFlush = set()
  120. for client in flush:
  121. client.connection.flush()
  122. return Task.again
  123. def setTcpHeaderSize(self, headerSize):
  124. """Sets the header size of TCP packets. At the present, legal
  125. values for this are 0, 2, or 4; this specifies the number of
  126. bytes to use encode the datagram length at the start of each
  127. TCP datagram. Sender and receiver must independently agree on
  128. this."""
  129. self.qcr.setTcpHeaderSize(headerSize)
  130. self.cw.setTcpHeaderSize(headerSize)
  131. def getTcpHeaderSize(self):
  132. """Returns the current setting of TCP header size. See
  133. setTcpHeaderSize(). """
  134. return self.qcr.getTcpHeaderSize()
  135. def importModule(self, dcImports, moduleName, importSymbols):
  136. """ Imports the indicated moduleName and all of its symbols
  137. into the current namespace. This more-or-less reimplements
  138. the Python import command. """
  139. module = __import__(moduleName, globals(), locals(), importSymbols)
  140. if importSymbols:
  141. # "from moduleName import symbolName, symbolName, ..."
  142. # Copy just the named symbols into the dictionary.
  143. if importSymbols == ['*']:
  144. # "from moduleName import *"
  145. if hasattr(module, "__all__"):
  146. importSymbols = module.__all__
  147. else:
  148. importSymbols = module.__dict__.keys()
  149. for symbolName in importSymbols:
  150. if hasattr(module, symbolName):
  151. dcImports[symbolName] = getattr(module, symbolName)
  152. else:
  153. raise Exception('Symbol %s not defined in module %s.' % (symbolName, moduleName))
  154. else:
  155. # "import moduleName"
  156. # Copy the root module name into the dictionary.
  157. # Follow the dotted chain down to the actual module.
  158. components = moduleName.split('.')
  159. dcImports[components[0]] = module
  160. def readDCFile(self, dcFileNames = None):
  161. """
  162. Reads in the dc files listed in dcFileNames, or if
  163. dcFileNames is None, reads in all of the dc files listed in
  164. the Configrc file.
  165. """
  166. dcFile = self.dcFile
  167. dcFile.clear()
  168. self.dclassesByName = {}
  169. self.dclassesByNumber = {}
  170. self.hashVal = 0
  171. dcImports = {}
  172. if dcFileNames == None:
  173. readResult = dcFile.readAll()
  174. if not readResult:
  175. self.notify.error("Could not read dc file.")
  176. else:
  177. searchPath = getModelPath().getValue()
  178. for dcFileName in dcFileNames:
  179. pathname = Filename(dcFileName)
  180. vfs.resolveFilename(pathname, searchPath)
  181. readResult = dcFile.read(pathname)
  182. if not readResult:
  183. self.notify.error("Could not read dc file: %s" % (pathname))
  184. self.hashVal = dcFile.getHash()
  185. # Now import all of the modules required by the DC file.
  186. for n in range(dcFile.getNumImportModules()):
  187. moduleName = dcFile.getImportModule(n)
  188. # Maybe the module name is represented as "moduleName/AI".
  189. suffix = moduleName.split('/')
  190. moduleName = suffix[0]
  191. if self.dcSuffix and self.dcSuffix in suffix[1:]:
  192. moduleName += self.dcSuffix
  193. importSymbols = []
  194. for i in range(dcFile.getNumImportSymbols(n)):
  195. symbolName = dcFile.getImportSymbol(n, i)
  196. # Maybe the symbol name is represented as "symbolName/AI".
  197. suffix = symbolName.split('/')
  198. symbolName = suffix[0]
  199. if self.dcSuffix and self.dcSuffix in suffix[1:]:
  200. symbolName += self.dcSuffix
  201. importSymbols.append(symbolName)
  202. self.importModule(dcImports, moduleName, importSymbols)
  203. # Now get the class definition for the classes named in the DC
  204. # file.
  205. for i in range(dcFile.getNumClasses()):
  206. dclass = dcFile.getClass(i)
  207. number = dclass.getNumber()
  208. className = dclass.getName() + self.dcSuffix
  209. # Does the class have a definition defined in the newly
  210. # imported namespace?
  211. classDef = dcImports.get(className)
  212. # Also try it without the dcSuffix.
  213. if classDef == None:
  214. className = dclass.getName()
  215. classDef = dcImports.get(className)
  216. if classDef == None:
  217. self.notify.debug("No class definition for %s." % (className))
  218. else:
  219. if type(classDef) == types.ModuleType:
  220. if not hasattr(classDef, className):
  221. self.notify.error("Module %s does not define class %s." % (className, className))
  222. classDef = getattr(classDef, className)
  223. if type(classDef) != types.ClassType and type(classDef) != types.TypeType:
  224. self.notify.error("Symbol %s is not a class name." % (className))
  225. else:
  226. dclass.setClassDef(classDef)
  227. self.dclassesByName[className] = dclass
  228. if number >= 0:
  229. self.dclassesByNumber[number] = dclass
  230. # listens for new clients
  231. def listenerPoll(self, task):
  232. if self.qcl.newConnectionAvailable():
  233. rendezvous = PointerToConnection()
  234. netAddress = NetAddress()
  235. newConnection = PointerToConnection()
  236. retVal = self.qcl.getNewConnection(rendezvous, netAddress,
  237. newConnection)
  238. if not retVal:
  239. return Task.cont
  240. # Crazy dereferencing
  241. newConnection = newConnection.p()
  242. # Add clients information to dictionary
  243. id = self.idAllocator.allocate()
  244. doIdBase = id * self.doIdRange + 1
  245. self.notify.info(
  246. "Got client %s from %s" % (doIdBase, netAddress))
  247. client = self.Client(newConnection, netAddress, doIdBase)
  248. self.clientsByConnection[client.connection] = client
  249. self.clientsByDoIdBase[client.doIdBase] = client
  250. # Now we can start listening to that new connection.
  251. self.qcr.addConnection(newConnection)
  252. self.lastConnection = newConnection
  253. self.sendDoIdRange(client)
  254. return Task.cont
  255. def readerPollUntilEmpty(self, task):
  256. """ continuously polls for new messages on the server """
  257. while self.readerPollOnce():
  258. pass
  259. return Task.cont
  260. def readerPollOnce(self):
  261. """ checks for available messages to the server """
  262. availGetVal = self.qcr.dataAvailable()
  263. if availGetVal:
  264. datagram = NetDatagram()
  265. readRetVal = self.qcr.getData(datagram)
  266. if readRetVal:
  267. # need to send to message processing unit
  268. self.handleDatagram(datagram)
  269. return availGetVal
  270. def handleDatagram(self, datagram):
  271. """ switching station for messages """
  272. client = self.clientsByConnection.get(datagram.getConnection())
  273. if not client:
  274. # This shouldn't be possible, though it appears to happen
  275. # sometimes?
  276. self.notify.warning(
  277. "Ignoring datagram from unknown connection %s" % (datagram.getConnection()))
  278. return
  279. if self.notify.getDebug():
  280. self.notify.debug(
  281. "ServerRepository received datagram from %s:" % (client.doIdBase))
  282. #datagram.dumpHex(ostream)
  283. dgi = DatagramIterator(datagram)
  284. type = dgi.getUint16()
  285. if type == CLIENT_DISCONNECT_CMU:
  286. self.handleClientDisconnect(client)
  287. elif type == CLIENT_SET_INTEREST_CMU:
  288. self.handleClientSetInterest(client, dgi)
  289. elif type == CLIENT_OBJECT_GENERATE_CMU:
  290. self.handleClientCreateObject(datagram, dgi)
  291. elif type == CLIENT_OBJECT_UPDATE_FIELD:
  292. self.handleClientObjectUpdateField(datagram, dgi)
  293. elif type == CLIENT_OBJECT_UPDATE_FIELD_TARGETED_CMU:
  294. self.handleClientObjectUpdateField(datagram, dgi, targeted = True)
  295. elif type == OBJECT_DELETE_CMU:
  296. self.handleClientDeleteObject(datagram, dgi.getUint32())
  297. elif type == OBJECT_SET_ZONE_CMU:
  298. self.handleClientObjectSetZone(datagram, dgi)
  299. else:
  300. self.handleMessageType(type, dgi)
  301. def handleMessageType(self, msgType, di):
  302. self.notify.warning("unrecognized message type %s" % (msgType))
  303. def handleClientCreateObject(self, datagram, dgi):
  304. """ client wants to create an object, so we store appropriate
  305. data, and then pass message along to corresponding zones """
  306. connection = datagram.getConnection()
  307. zoneId = dgi.getUint32()
  308. classId = dgi.getUint16()
  309. doId = dgi.getUint32()
  310. client = self.clientsByConnection[connection]
  311. if self.getDoIdBase(doId) != client.doIdBase:
  312. self.notify.warning(
  313. "Ignoring attempt to create invalid doId %s from client %s" % (doId, client.doIdBase))
  314. return
  315. dclass = self.dclassesByNumber[classId]
  316. object = client.objectsByDoId.get(doId)
  317. if object:
  318. # This doId is already in use; thus, this message is
  319. # really just an update.
  320. if object.dclass != dclass:
  321. self.notify.warning(
  322. "Ignoring attempt to change object %s from %s to %s by client %s" % (
  323. doId, object.dclass.getName(), dclass.getName(), client.doIdBase))
  324. return
  325. self.setObjectZone(client, object, zoneId)
  326. else:
  327. if self.notify.getDebug():
  328. self.notify.debug(
  329. "Creating object %s of type %s by client %s" % (
  330. doId, dclass.getName(), client.doIdBase))
  331. object = self.Object(doId, zoneId, dclass)
  332. client.objectsByDoId[doId] = object
  333. client.objectsByZoneId.setdefault(zoneId, set()).add(object)
  334. self.objectsByZoneId.setdefault(zoneId, set()).add(object)
  335. self.updateClientInterestZones(client)
  336. # Rebuild the new datagram that we'll send on. We shim in the
  337. # doIdBase of the owner.
  338. dg = PyDatagram()
  339. dg.addUint16(OBJECT_GENERATE_CMU)
  340. dg.addUint32(client.doIdBase)
  341. dg.addUint32(zoneId)
  342. dg.addUint16(classId)
  343. dg.addUint32(doId)
  344. dg.appendData(dgi.getRemainingBytes())
  345. self.sendToZoneExcept(zoneId, dg, [client])
  346. def handleClientObjectUpdateField(self, datagram, dgi, targeted = False):
  347. """ Received an update request from a client. """
  348. connection = datagram.getConnection()
  349. client = self.clientsByConnection[connection]
  350. if targeted:
  351. targetId = dgi.getUint32()
  352. doId = dgi.getUint32()
  353. fieldId = dgi.getUint16()
  354. doIdBase = self.getDoIdBase(doId)
  355. owner = self.clientsByDoIdBase.get(doIdBase)
  356. object = owner and owner.objectsByDoId.get(doId)
  357. if not object:
  358. self.notify.warning(
  359. "Ignoring update for unknown object %s from client %s" % (
  360. doId, client.doIdBase))
  361. return
  362. dcfield = object.dclass.getFieldByIndex(fieldId)
  363. if dcfield == None:
  364. self.notify.warning(
  365. "Ignoring update for field %s on object %s from client %s; no such field for class %s." % (
  366. fieldId, doId, client.doIdBase, object.dclass.getName()))
  367. if client != owner:
  368. # This message was not sent by the object's owner.
  369. if not dcfield.hasKeyword('clsend') and not dcfield.hasKeyword('p2p'):
  370. self.notify.warning(
  371. "Ignoring update for %s.%s on object %s from client %s: not owner" % (
  372. object.dclass.getName(), dcfield.getName(), doId, client.doIdBase))
  373. return
  374. # We reformat the message slightly to insert the sender's
  375. # doIdBase.
  376. dg = PyDatagram()
  377. dg.addUint16(OBJECT_UPDATE_FIELD_CMU)
  378. dg.addUint32(client.doIdBase)
  379. dg.addUint32(doId)
  380. dg.addUint16(fieldId)
  381. dg.appendData(dgi.getRemainingBytes())
  382. if targeted:
  383. # A targeted update: only to the indicated client.
  384. target = self.clientsByDoIdBase.get(targetId)
  385. if not target:
  386. self.notify.warning(
  387. "Ignoring targeted update to %s for %s.%s on object %s from client %s: target not known" % (
  388. targetId,
  389. dclass.getName(), dcfield.getName(), doId, client.doIdBase))
  390. return
  391. self.cw.send(dg, target.connection)
  392. self.needsFlush.add(target)
  393. elif dcfield.hasKeyword('p2p'):
  394. # p2p: to object owner only
  395. self.cw.send(dg, owner.connection)
  396. self.needsFlush.add(owner)
  397. elif dcfield.hasKeyword('broadcast'):
  398. # Broadcast: to everyone except orig sender
  399. self.sendToZoneExcept(object.zoneId, dg, [client])
  400. elif dcfield.hasKeyword('reflect'):
  401. # Reflect: broadcast to everyone including orig sender
  402. self.sendToZoneExcept(object.zoneId, dg, [])
  403. else:
  404. self.notify.warning(
  405. "Message is not broadcast or p2p")
  406. def getDoIdBase(self, doId):
  407. """ Given a doId, return the corresponding doIdBase. This
  408. will be the owner of the object (clients may only create
  409. object doId's within their assigned range). """
  410. return int(doId / self.doIdRange) * self.doIdRange + 1
  411. def handleClientDeleteObject(self, datagram, doId):
  412. """ client deletes an object, let everyone who has interest in
  413. the object's zone know about it. """
  414. connection = datagram.getConnection()
  415. client = self.clientsByConnection[connection]
  416. object = client.objectsByDoId.get(doId)
  417. if not object:
  418. self.notify.warning(
  419. "Ignoring update for unknown object %s from client %s" % (
  420. doId, client.doIdBase))
  421. return
  422. self.sendToZoneExcept(object.zoneId, datagram, [])
  423. self.objectsByZoneId[object.zoneId].remove(object)
  424. if not self.objectsByZoneId[object.zoneId]:
  425. del self.objectsByZoneId[object.zoneId]
  426. client.objectsByZoneId[object.zoneId].remove(object)
  427. if not client.objectsByZoneId[object.zoneId]:
  428. del client.objectsByZoneId[object.zoneId]
  429. del client.objectsByDoId[doId]
  430. self.updateClientInterestZones(client)
  431. def handleClientObjectSetZone(self, datagram, dgi):
  432. """ The client is telling us the object is changing to a new
  433. zone. """
  434. doId = dgi.getUint32()
  435. zoneId = dgi.getUint32()
  436. connection = datagram.getConnection()
  437. client = self.clientsByConnection[connection]
  438. object = client.objectsByDoId.get(doId)
  439. if not object:
  440. # Don't know this object.
  441. self.notify.warning("Ignoring object location for %s: unknown" % (doId))
  442. return
  443. self.setObjectZone(client, object, zoneId)
  444. def setObjectZone(self, owner, object, zoneId):
  445. if object.zoneId == zoneId:
  446. # No change.
  447. return
  448. oldZoneId = object.zoneId
  449. self.objectsByZoneId[object.zoneId].remove(object)
  450. if not self.objectsByZoneId[object.zoneId]:
  451. del self.objectsByZoneId[object.zoneId]
  452. owner.objectsByZoneId[object.zoneId].remove(object)
  453. if not owner.objectsByZoneId[object.zoneId]:
  454. del owner.objectsByZoneId[object.zoneId]
  455. object.zoneId = zoneId
  456. self.objectsByZoneId.setdefault(zoneId, set()).add(object)
  457. owner.objectsByZoneId.setdefault(zoneId, set()).add(object)
  458. self.updateClientInterestZones(owner)
  459. # Any clients that are listening to oldZoneId but not zoneId
  460. # should receive a disable message: this object has just gone
  461. # out of scope for you.
  462. datagram = PyDatagram()
  463. datagram.addUint16(OBJECT_DISABLE_CMU)
  464. datagram.addUint32(object.doId)
  465. for client in self.zonesToClients[oldZoneId]:
  466. if client != owner:
  467. if zoneId not in client.currentInterestZoneIds:
  468. self.cw.send(datagram, client.connection)
  469. self.needsFlush.add(client)
  470. # The client is now responsible for sending a generate for the
  471. # object that just switched zones, to inform the clients that
  472. # are listening to the new zoneId but not the old zoneId.
  473. def sendDoIdRange(self, client):
  474. """ sends the client the range of doid's that the client can
  475. use """
  476. datagram = NetDatagram()
  477. datagram.addUint16(SET_DOID_RANGE_CMU)
  478. datagram.addUint32(client.doIdBase)
  479. datagram.addUint32(self.doIdRange)
  480. self.cw.send(datagram, client.connection)
  481. self.needsFlush.add(client)
  482. # a client disconnected from us, we need to update our data, also
  483. # tell other clients to remove the disconnected clients objects
  484. def handleClientDisconnect(self, client):
  485. for zoneId in client.currentInterestZoneIds:
  486. if len(self.zonesToClients[zoneId]) == 1:
  487. del self.zonesToClients[zoneId]
  488. else:
  489. self.zonesToClients[zoneId].remove(client)
  490. for object in client.objectsByDoId.values():
  491. #create and send delete message
  492. datagram = NetDatagram()
  493. datagram.addUint16(OBJECT_DELETE_CMU)
  494. datagram.addUint32(object.doId)
  495. self.sendToZoneExcept(object.zoneId, datagram, [])
  496. self.objectsByZoneId[object.zoneId].remove(object)
  497. if not self.objectsByZoneId[object.zoneId]:
  498. del self.objectsByZoneId[object.zoneId]
  499. client.objectsByDoId = {}
  500. client.objectsByZoneId = {}
  501. del self.clientsByConnection[client.connection]
  502. del self.clientsByDoIdBase[client.doIdBase]
  503. id = client.doIdBase / self.doIdRange
  504. self.idAllocator.free(id)
  505. self.qcr.removeConnection(client.connection)
  506. self.qcm.closeConnection(client.connection)
  507. def handleClientSetInterest(self, client, dgi):
  508. """ The client is specifying a particular set of zones it is
  509. interested in. """
  510. zoneIds = set()
  511. while dgi.getRemainingSize() > 0:
  512. zoneId = dgi.getUint32()
  513. zoneIds.add(zoneId)
  514. client.explicitInterestZoneIds = zoneIds
  515. self.updateClientInterestZones(client)
  516. def updateClientInterestZones(self, client):
  517. """ Something about the client has caused its set of interest
  518. zones to potentially change. Recompute them. """
  519. origZoneIds = client.currentInterestZoneIds
  520. newZoneIds = client.explicitInterestZoneIds | set(client.objectsByZoneId.keys())
  521. if origZoneIds == newZoneIds:
  522. # No change.
  523. return
  524. client.currentInterestZoneIds = newZoneIds
  525. addedZoneIds = newZoneIds - origZoneIds
  526. removedZoneIds = origZoneIds - newZoneIds
  527. for zoneId in addedZoneIds:
  528. self.zonesToClients.setdefault(zoneId, set()).add(client)
  529. # The client is opening interest in this zone. Need to get
  530. # all of the data from clients who may have objects in
  531. # this zone
  532. datagram = NetDatagram()
  533. datagram.addUint16(REQUEST_GENERATES_CMU)
  534. datagram.addUint32(zoneId)
  535. self.sendToZoneExcept(zoneId, datagram, [client])
  536. datagram = PyDatagram()
  537. datagram.addUint16(OBJECT_DISABLE_CMU)
  538. for zoneId in removedZoneIds:
  539. self.zonesToClients[zoneId].remove(client)
  540. # The client is abandoning interest in this zone. Any
  541. # objects in this zone should be disabled for the client.
  542. for object in self.objectsByZoneId.get(zoneId, []):
  543. datagram.addUint32(object.doId)
  544. self.cw.send(datagram, client.connection)
  545. self.needsFlush.add(client)
  546. def clientHardDisconnectTask(self, task):
  547. """ client did not tell us he was leaving but we lost connection to
  548. him, so we need to update our data and tell others """
  549. for client in self.clientsByConnection.values():
  550. if not self.qcr.isConnectionOk(client.connection):
  551. self.handleClientDisconnect(client)
  552. return Task.cont
  553. def sendToZoneExcept(self, zoneId, datagram, exceptionList):
  554. """sends a message to everyone who has interest in the
  555. indicated zone, except for the clients on exceptionList."""
  556. if self.notify.getDebug():
  557. self.notify.debug(
  558. "ServerRepository sending to all in zone %s except %s:" % (zoneId, [c.doIdBase for c in exceptionList]))
  559. #datagram.dumpHex(ostream)
  560. for client in self.zonesToClients.get(zoneId, []):
  561. if client not in exceptionList:
  562. if self.notify.getDebug():
  563. self.notify.debug(
  564. " -> %s" % (client.doIdBase))
  565. self.cw.send(datagram, client.connection)
  566. self.needsFlush.add(client)
  567. def sendToAllExcept(self, datagram, exceptionList):
  568. """ sends a message to all connected clients, except for
  569. clients on exceptionList. """
  570. if self.notify.getDebug():
  571. self.notify.debug(
  572. "ServerRepository sending to all except %s:" % ([c.doIdBase for c in exceptionList],))
  573. #datagram.dumpHex(ostream)
  574. for client in self.clientsByConnection.values():
  575. if client not in exceptionList:
  576. if self.notify.getDebug():
  577. self.notify.debug(
  578. " -> %s" % (client.doIdBase))
  579. self.cw.send(datagram, client.connection)
  580. self.needsFlush.add(client)