ClientRepository.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427
  1. """ClientRepository module: contains the ClientRepository class"""
  2. from ClientRepositoryBase import ClientRepositoryBase
  3. from direct.directnotify import DirectNotifyGlobal
  4. from MsgTypesCMU import *
  5. from PyDatagram import PyDatagram
  6. from PyDatagramIterator import PyDatagramIterator
  7. from pandac.PandaModules import UniqueIdAllocator
  8. import types
  9. class ClientRepository(ClientRepositoryBase):
  10. """
  11. This is the open-source ClientRepository as provided by CMU. It
  12. communicates with the ServerRepository in this same directory.
  13. If you are looking for the VR Studio's implementation of the
  14. client repository, look to OTPClientRepository (elsewhere).
  15. """
  16. notify = DirectNotifyGlobal.directNotify.newCategory("ClientRepository")
  17. # This is required by DoCollectionManager, even though it's not
  18. # used by this implementation.
  19. GameGlobalsId = 0
  20. doNotDeallocateChannel = True
  21. def __init__(self, dcFileNames = None, dcSuffix = '', connectMethod = None,
  22. threadedNet = None):
  23. ClientRepositoryBase.__init__(self, dcFileNames = dcFileNames, dcSuffix = dcSuffix, connectMethod = connectMethod, threadedNet = threadedNet)
  24. self.setHandleDatagramsInternally(False)
  25. base.finalExitCallbacks.append(self.shutdown)
  26. # The doId allocator. The CMU LAN server may choose to
  27. # send us a block of doIds. If it chooses to do so, then we
  28. # may create objects, using those doIds.
  29. self.doIdAllocator = None
  30. self.doIdBase = 0
  31. self.doIdLast = 0
  32. # The doIdBase of the client message currently being
  33. # processed.
  34. self.currentSenderId = None
  35. # Explicitly-requested interest zones.
  36. self.interestZones = []
  37. def handleSetDoIdrange(self, di):
  38. self.doIdBase = di.getUint32()
  39. self.doIdLast = self.doIdBase + di.getUint32()
  40. self.doIdAllocator = UniqueIdAllocator(self.doIdBase, self.doIdLast - 1)
  41. self.ourChannel = self.doIdBase
  42. self.createReady()
  43. def createReady(self):
  44. # Now that we've got a doId range, we can safely generate new
  45. # distributed objects.
  46. messenger.send('createReady', taskChain = 'default')
  47. messenger.send(self.uniqueName('createReady'), taskChain = 'default')
  48. def handleRequestGenerates(self, di):
  49. # When new clients join the zone of an object, they need to hear
  50. # about it, so we send out all of our information about objects in
  51. # that particular zone.
  52. zone = di.getUint32()
  53. for obj in self.doId2do.values():
  54. if obj.zoneId == zone:
  55. if (self.isLocalId(obj.doId)):
  56. self.resendGenerate(obj)
  57. def resendGenerate(self, obj):
  58. """ Sends the generate message again for an already-generated
  59. object, presumably to inform any newly-arrived clients of this
  60. object's current state. """
  61. # get the list of "ram" fields that aren't
  62. # required. These are fields whose values should
  63. # persist even if they haven't been received
  64. # lately, so we have to re-broadcast these values
  65. # in case the new client hasn't heard their latest
  66. # values.
  67. extraFields = []
  68. for i in range(obj.dclass.getNumInheritedFields()):
  69. field = obj.dclass.getInheritedField(i)
  70. if field.hasKeyword('broadcast') and field.hasKeyword('ram') and not field.hasKeyword('required'):
  71. if field.asMolecularField():
  72. # It's a molecular field; this means
  73. # we have to pack the components.
  74. # Fortunately, we'll find those
  75. # separately through the iteration, so
  76. # we can ignore this field itself.
  77. continue
  78. extraFields.append(field.getName())
  79. datagram = self.formatGenerate(obj, extraFields)
  80. self.send(datagram)
  81. def handleGenerate(self, di):
  82. self.currentSenderId = di.getUint32()
  83. zoneId = di.getUint32()
  84. classId = di.getUint16()
  85. doId = di.getUint32()
  86. # Look up the dclass
  87. dclass = self.dclassesByNumber[classId]
  88. distObj = self.doId2do.get(doId)
  89. if distObj and distObj.dclass == dclass:
  90. # We've already got this object. Probably this is just a
  91. # repeat-generate, synthesized for the benefit of someone
  92. # else who just entered the zone. Accept the new updates,
  93. # but don't make a formal generate.
  94. assert(self.notify.debug("performing generate-update for %s %s" % (dclass.getName(), doId)))
  95. dclass.receiveUpdateBroadcastRequired(distObj, di)
  96. dclass.receiveUpdateOther(distObj, di)
  97. return
  98. assert(self.notify.debug("performing generate for %s %s" % (dclass.getName(), doId)))
  99. dclass.startGenerate()
  100. # Create a new distributed object, and put it in the dictionary
  101. distObj = self.generateWithRequiredOtherFields(dclass, doId, di, 0, zoneId)
  102. dclass.stopGenerate()
  103. def allocateDoId(self):
  104. """ Returns a newly-allocated doId. Call freeDoId() when the
  105. object has been deleted. """
  106. return self.doIdAllocator.allocate()
  107. def reserveDoId(self, doId):
  108. """ Removes the indicate doId from the available pool, as if
  109. it had been explicitly allocated. You may pass it to
  110. freeDoId() later if you wish. """
  111. self.doIdAllocator.initialReserveId(doId)
  112. return doId
  113. def freeDoId(self, doId):
  114. """ Returns a doId back into the free pool for re-use. """
  115. assert self.isLocalId(doId)
  116. self.doIdAllocator.free(doId)
  117. def storeObjectLocation(self, object, parentId, zoneId):
  118. # The CMU implementation doesn't use the DoCollectionManager
  119. # much.
  120. object.parentId = parentId
  121. object.zoneId = zoneId
  122. def createDistributedObject(self, className = None, distObj = None,
  123. zoneId = 0, optionalFields = None,
  124. doId = None, reserveDoId = False):
  125. """ To create a DistributedObject, you must pass in either the
  126. name of the object's class, or an already-created instance of
  127. the class (or both). If you pass in just a class name (to the
  128. className parameter), then a default instance of the object
  129. will be created, with whatever parameters the default
  130. constructor supplies. Alternatively, if you wish to create
  131. some initial values different from the default, you can create
  132. the instance yourself and supply it to the distObj parameter,
  133. then that instance will be used instead. (It should be a
  134. newly-created object, not one that has already been manifested
  135. on the network or previously passed through
  136. createDistributedObject.) In either case, the new
  137. DistributedObject is returned from this method.
  138. This method will issue the appropriate network commands to
  139. make this object appear on all of the other clients.
  140. You should supply an initial zoneId in which to manifest the
  141. object. The fields marked "required" or "ram" will be
  142. broadcast to all of the other clients; if you wish to
  143. broadcast additional field values at this time as well, pass a
  144. list of field names in the optionalFields parameters.
  145. Normally, doId is None, to mean allocate a new doId for the
  146. object. If you wish to use a particular doId, pass it in
  147. here. If you also pass reserveDoId = True, this doId will be
  148. reserved from the allocation pool using self.reserveDoId().
  149. You are responsible for ensuring this doId falls within the
  150. client's allowable doId range and has not already been
  151. assigned to another object. """
  152. if not className:
  153. if not distObj:
  154. self.notify.error("Must specify either a className or a distObj.")
  155. className = distObj.__class__.__name__
  156. if doId is None:
  157. doId = self.allocateDoId()
  158. elif reserveDoId:
  159. self.reserveDoId(doId)
  160. dclass = self.dclassesByName.get(className)
  161. if not dclass:
  162. self.notify.error("Unknown distributed class: %s" % (distObj.__class__))
  163. classDef = dclass.getClassDef()
  164. if classDef == None:
  165. self.notify.error("Could not create an undefined %s object." % (
  166. dclass.getName()))
  167. if not distObj:
  168. distObj = classDef(self)
  169. if not isinstance(distObj, classDef):
  170. self.notify.error("Object %s is not an instance of %s" % (distObj.__class__.__name__, classDef.__name__))
  171. distObj.dclass = dclass
  172. distObj.doId = doId
  173. self.doId2do[doId] = distObj
  174. distObj.generateInit()
  175. distObj._retrieveCachedData()
  176. distObj.generate()
  177. distObj.setLocation(0, zoneId)
  178. distObj.announceGenerate()
  179. datagram = self.formatGenerate(distObj, optionalFields)
  180. self.send(datagram)
  181. return distObj
  182. def formatGenerate(self, distObj, extraFields):
  183. """ Returns a datagram formatted for sending the generate message for the indicated object. """
  184. return distObj.dclass.clientFormatGenerateCMU(distObj, distObj.doId, distObj.zoneId, extraFields)
  185. def sendDeleteMsg(self, doId):
  186. datagram = PyDatagram()
  187. datagram.addUint16(OBJECT_DELETE_CMU)
  188. datagram.addUint32(doId)
  189. self.send(datagram)
  190. def sendDisconnect(self):
  191. if self.isConnected():
  192. # Tell the game server that we're going:
  193. datagram = PyDatagram()
  194. # Add message type
  195. datagram.addUint16(CLIENT_DISCONNECT_CMU)
  196. # Send the message
  197. self.send(datagram)
  198. self.notify.info("Sent disconnect message to server")
  199. self.disconnect()
  200. self.stopHeartbeat()
  201. def setInterestZones(self, interestZoneIds):
  202. """ Changes the set of zones that this particular client is
  203. interested in hearing about. """
  204. datagram = PyDatagram()
  205. # Add message type
  206. datagram.addUint16(CLIENT_SET_INTEREST_CMU)
  207. for zoneId in interestZoneIds:
  208. datagram.addUint32(zoneId)
  209. # send the message
  210. self.send(datagram)
  211. self.interestZones = interestZoneIds[:]
  212. def setObjectZone(self, distObj, zoneId):
  213. """ Moves the object into the indicated zone. """
  214. distObj.b_setLocation(0, zoneId)
  215. assert distObj.zoneId == zoneId
  216. # Tell all of the clients monitoring the new zone that we've
  217. # arrived.
  218. self.resendGenerate(distObj)
  219. def sendSetLocation(self, doId, parentId, zoneId):
  220. datagram = PyDatagram()
  221. datagram.addUint16(OBJECT_SET_ZONE_CMU)
  222. datagram.addUint32(doId)
  223. datagram.addUint32(zoneId)
  224. self.send(datagram)
  225. def sendHeartbeat(self):
  226. datagram = PyDatagram()
  227. # Add message type
  228. datagram.addUint16(CLIENT_HEARTBEAT_CMU)
  229. # Send it!
  230. self.send(datagram)
  231. self.lastHeartbeat = globalClock.getRealTime()
  232. # This is important enough to consider flushing immediately
  233. # (particularly if we haven't run readerPollTask recently).
  234. self.considerFlush()
  235. def isLocalId(self, doId):
  236. """ Returns true if this doId is one that we're the owner of,
  237. false otherwise. """
  238. return ((doId >= self.doIdBase) and (doId < self.doIdLast))
  239. def haveCreateAuthority(self):
  240. """ Returns true if this client has been assigned a range of
  241. doId's it may use to create objects, false otherwise. """
  242. return (self.doIdLast > self.doIdBase)
  243. def getAvatarIdFromSender(self):
  244. """ Returns the doIdBase of the client that originally sent
  245. the current update message. This is only defined when
  246. processing an update message or a generate message. """
  247. return self.currentSenderId
  248. def handleDatagram(self, di):
  249. if self.notify.getDebug():
  250. print "ClientRepository received datagram:"
  251. di.getDatagram().dumpHex(ostream)
  252. msgType = self.getMsgType()
  253. self.currentSenderId = None
  254. # These are the sort of messages we may expect from the public
  255. # Panda server.
  256. if msgType == SET_DOID_RANGE_CMU:
  257. self.handleSetDoIdrange(di)
  258. elif msgType == OBJECT_GENERATE_CMU:
  259. self.handleGenerate(di)
  260. elif msgType == OBJECT_UPDATE_FIELD_CMU:
  261. self.handleUpdateField(di)
  262. elif msgType == OBJECT_DISABLE_CMU:
  263. self.handleDisable(di)
  264. elif msgType == OBJECT_DELETE_CMU:
  265. self.handleDelete(di)
  266. elif msgType == REQUEST_GENERATES_CMU:
  267. self.handleRequestGenerates(di)
  268. else:
  269. self.handleMessageType(msgType, di)
  270. # If we're processing a lot of datagrams within one frame, we
  271. # may forget to send heartbeats. Keep them coming!
  272. self.considerHeartbeat()
  273. def handleMessageType(self, msgType, di):
  274. self.notify.error("unrecognized message type %s" % (msgType))
  275. def handleUpdateField(self, di):
  276. # The CMU update message starts with an additional field, not
  277. # present in the Disney update message: the doIdBase of the
  278. # original sender. Extract that and call up to the parent.
  279. self.currentSenderId = di.getUint32()
  280. ClientRepositoryBase.handleUpdateField(self, di)
  281. def handleDisable(self, di):
  282. # Receives a list of doIds.
  283. while di.getRemainingSize() > 0:
  284. doId = di.getUint32()
  285. # We should never get a disable message for our own object.
  286. assert not self.isLocalId(doId)
  287. self.disableDoId(doId)
  288. def handleDelete(self, di):
  289. # Receives a single doId.
  290. doId = di.getUint32()
  291. self.deleteObject(doId)
  292. def deleteObject(self, doId):
  293. """
  294. Removes the object from the client's view of the world. This
  295. should normally not be called directly except in the case of
  296. error recovery, since the server will normally be responsible
  297. for deleting and disabling objects as they go out of scope.
  298. After this is called, future updates by server on this object
  299. will be ignored (with a warning message). The object will
  300. become valid again the next time the server sends a generate
  301. message for this doId.
  302. This is not a distributed message and does not delete the
  303. object on the server or on any other client.
  304. """
  305. if self.doId2do.has_key(doId):
  306. # If it is in the dictionary, remove it.
  307. obj = self.doId2do[doId]
  308. # Remove it from the dictionary
  309. del self.doId2do[doId]
  310. # Disable, announce, and delete the object itself...
  311. # unless delayDelete is on...
  312. obj.deleteOrDelay()
  313. if self.isLocalId(doId):
  314. self.freeDoId(doId)
  315. elif self.cache.contains(doId):
  316. # If it is in the cache, remove it.
  317. self.cache.delete(doId)
  318. if self.isLocalId(doId):
  319. self.freeDoId(doId)
  320. else:
  321. # Otherwise, ignore it
  322. self.notify.warning(
  323. "Asked to delete non-existent DistObj " + str(doId))
  324. def stopTrackRequestDeletedDO(self, *args):
  325. # No-op. Not entirely sure what this does on the VR Studio side.
  326. pass
  327. def sendUpdate(self, distObj, fieldName, args):
  328. """ Sends a normal update for a single field. """
  329. dg = distObj.dclass.clientFormatUpdate(
  330. fieldName, distObj.doId, args)
  331. self.send(dg)
  332. def sendUpdateToChannel(self, distObj, channelId, fieldName, args):
  333. """ Sends a targeted update of a single field to a particular
  334. client. The top 32 bits of channelId is ignored; the lower 32
  335. bits should be the client Id of the recipient (i.e. the
  336. client's doIdbase). The field update will be sent to the
  337. indicated client only. The field must be marked clsend or
  338. p2p, and may not be marked broadcast. """
  339. datagram = distObj.dclass.clientFormatUpdate(
  340. fieldName, distObj.doId, args)
  341. dgi = PyDatagramIterator(datagram)
  342. # Reformat the packed datagram to change the message type and
  343. # add the target id.
  344. dgi.getUint16()
  345. dg = PyDatagram()
  346. dg.addUint16(CLIENT_OBJECT_UPDATE_FIELD_TARGETED_CMU)
  347. dg.addUint32(channelId & 0xffffffff)
  348. dg.appendData(dgi.getRemainingBytes())
  349. self.send(dg)