def save_to_packet(self): """ Create a "pickup" packet representing this entity. """ x, y, z = self.location.pos packets = make_packet('object', eid=self.eid, type='item_stack', x=x, y=y, z=z, yaw=0, pitch=0, data=1, speed=Speed(0, 0, 0)) packets += make_packet( 'metadata', eid=self.eid, # See http://www.wiki.vg/Entities#Objects metadata={ 0: ('byte', 0), # Flags 1: ('short', 300), # Drowning counter 10: ('slot', Slot.fromItem(self.item, self.quantity)) }) return packets
def position_changed(self): x, chaff, z, chaff = split_coords(self.location.x, self.location.z) # Inform everybody of our new location. packet = make_packet("teleport", eid=self.player.eid, x=self.location.x * 32, y=self.location.y * 32, z=self.location.z * 32, yaw=int(self.location.theta * 255 / (2 * pi)) % 256, pitch=int(self.location.phi * 255 / (2 * pi)) % 256, ) self.factory.broadcast_for_others(packet, self) self.update_chunks() for entity in self.entities_near(2): if entity.name != "Item": continue left = self.player.inventory.add(entity.item, entity.quantity) if left != entity.quantity: if left != 0: # partial collect entity.quantity = left else: packet = make_packet("collect", eid=entity.eid, destination=self.player.eid) packet += make_packet("destroy", eid=entity.eid) self.factory.broadcast(packet) self.factory.destroy_entity(entity) packet = self.inventory.save_to_packet() self.transport.write(packet)
def position_changed(self): x, y, z = self.location.pos yaw, pitch = self.location.ori.to_fracs() # Inform everybody of our new location. packet = make_packet("teleport", eid=self.player.eid, x=x, y=y, z=z, yaw=yaw, pitch=pitch) self.factory.broadcast_for_others(packet, self) self.update_chunks() for entity in self.entities_near(2): if entity.name != "Item": continue left = self.player.inventory.add(entity.item, entity.quantity) if left != entity.quantity: if left != 0: # partial collect entity.quantity = left else: packet = make_packet("collect", eid=entity.eid, destination=self.player.eid) packet += make_packet("destroy", eid=entity.eid) self.factory.broadcast(packet) self.factory.destroy_entity(entity) packet = self.inventory.save_to_packet() self.transport.write(packet)
def make_packet(self): if self.weather == "rainy": return make_packet("state", state="start_rain", creative=False) elif self.weather == "sunny": return make_packet("state", state="stop_rain", creative=False) else: return ""
def connectionLost(self, reason): if self.time_loop: self.time_loop.stop() if self.chunk_tasks: for task in self.chunk_tasks: try: task.stop() except (TaskDone, TaskFailed): pass if self.player: self.factory.world.save_player(self.username, self.player) self.factory.destroy_entity(self.player) packet = make_packet("destroy", eid=self.player.eid) packet += make_packet("players", name=self.username, online=False, ping=0) self.factory.broadcast(packet) self.factory.chat("%s has left the game." % self.username) if self.username in self.factory.protocols: del self.factory.protocols[self.username] self.factory.connectedIPs[self.host] -= 1 if self.factory.connectedIPs[self.host] <= 0: del self.factory.connectedIPs[self.host]
def make_packet(self): # XXX this probably should use the factory's mode rather than # hardcoding creative mode. Probably. if self.weather == "rainy": return make_packet("state", state="start_rain", mode="creative") elif self.weather == "sunny": return make_packet("state", state="stop_rain", mode="creative") else: return ""
def get_damage_packet(self): """ Make a packet representing the current damage on this chunk. This method is not private, but some care should be taken with it, since it wraps some fairly cryptic internal data structures. If this chunk is currently undamaged, this method will return an empty string, which should be safe to treat as a packet. Please check with `is_damaged()` before doing this if you need to optimize this case. To avoid extra overhead, this method should really be used in conjunction with `Factory.broadcast_for_chunk()`. Do not forget to clear this chunk's damage! Callers are responsible for doing this. >>> packet = chunk.get_damage_packet() >>> factory.broadcast_for_chunk(packet, chunk.x, chunk.z) >>> chunk.clear_damage() :rtype: str :returns: String representation of the packet. """ if self.all_damaged: # Resend the entire chunk! return self.save_to_packet() elif not self.damaged.any(): return "" elif self.damaged.sum() == 1: # Use a single block update packet. x, z, y = [int(i) for i in zip(*self.damaged.nonzero())[0]] return make_packet("block", x=x + self.x * 16, y=y, z=z + self.z * 16, type=int(self.blocks[x, z, y]), meta=int(self.metadata[x, z, y])) else: # Use a batch update. damaged = self.damaged.nonzero() # Coordinates are not quite packed in the same system as the # indices for chunk data structures. # Chunk data structures are ((x * 16) + z) * 128) + y, or in # bit-twiddler's parlance, x << 11 | z << 7 | y. However, for # this, we need x << 12 | z << 8 | y, so repack accordingly. coords = [int(x << 12 | z << 8 | y) for x, z, y in zip(*damaged)] types = [int(i) for i in self.blocks[damaged]] metadata = [int(i) for i in self.metadata[damaged]] return make_packet("batch", x=self.x, z=self.z, length=len(coords), coords=coords, types=types, metadata=metadata)
def authenticated(self): BetaServerProtocol.authenticated(self) # Init player, and copy data into it. self.player = yield self.factory.world.load_player(self.username) self.player.eid = self.eid self.location = self.player.location # Init players' inventory window. self.inventory = InventoryWindow(self.player.inventory) # *Now* we are in our factory's list of protocols. Be aware. self.factory.protocols[self.username] = self # Announce our presence. self.factory.chat("%s is joining the game..." % self.username) packet = make_packet("players", name=self.username, online=True, ping=0) self.factory.broadcast(packet) # Craft our avatar and send it to already-connected other players. packet = make_packet("create", eid=self.player.eid) packet += self.player.save_to_packet() self.factory.broadcast_for_others(packet, self) # And of course spawn all of those players' avatars in our client as # well. for protocol in self.factory.protocols.itervalues(): # Skip over ourselves; otherwise, the client tweaks out and # usually either dies or locks up. if protocol is self: continue self.write_packet("create", eid=protocol.player.eid) packet = protocol.player.save_to_packet() packet += protocol.player.save_equipment_to_packet() self.transport.write(packet) # Send spawn and inventory. spawn = self.factory.world.level.spawn packet = make_packet("spawn", x=spawn[0], y=spawn[1], z=spawn[2]) packet += self.inventory.save_to_packet() self.transport.write(packet) # TODO: Send Abilities (0xca) # TODO: Update Health (0x08) # TODO: Update Experience (0x2b) # Send weather. self.transport.write(self.factory.vane.make_packet()) self.send_initial_chunk_and_location() self.time_loop = LoopingCall(self.update_time) self.time_loop.start(10)
def chat_command(self, username, parameters): from bravo.beta.packets import make_packet arg = "".join(parameters) if arg == "start": self.factory.broadcast( make_packet("state", state="start_rain", creative=False)) elif arg == "stop": self.factory.broadcast( make_packet("state", state="stop_rain", creative=False)) else: return ("Couldn't understand you!", ) return ("*%s did the rain dance*" % (username), )
def chat_command(self, username, parameters): from bravo.beta.packets import make_packet arg = "".join(parameters) if arg == "start": self.factory.broadcast(make_packet("state", state="start_rain", creative=False)) elif arg == "stop": self.factory.broadcast(make_packet("state", state="stop_rain", creative=False)) else: return ("Couldn't understand you!",) return ("*%s did the rain dance*" % (username),)
def packets_for_dirty(self, dirty_slots): """ Generate update packets for dirty usually privided by another window (sic!) """ packets = "" for slot, item in dirty_slots.iteritems(): if item is None: packets += make_packet("window-slot", wid=self.wid, slot=slot, primary=-1) else: packets += make_packet("window-slot", wid=self.wid, slot=slot, primary=item.primary, secondary=item.secondary, count=item.quantity) return packets
def authenticated(self): BetaServerProtocol.authenticated(self) # Init player, and copy data into it. self.player = yield self.factory.world.load_player(self.username) self.player.eid = self.eid self.location = self.player.location # Init players' inventory window. self.inventory = InventoryWindow(self.player.inventory) # Announce our presence. packet = make_packet("chat", message="%s is joining the game..." % self.username) packet += make_packet("players", name=self.username, online=True, ping=0) self.factory.broadcast(packet) # Craft our avatar and send it to already-connected other players. packet = self.player.save_to_packet() packet += make_packet("create", eid=self.player.eid) self.factory.broadcast_for_others(packet, self) # And of course spawn all of those players' avatars in our client as # well. Note that, at this point, we are not listed in the factory's # list of protocols, so we won't accidentally send one of these to # ourselves. for protocol in self.factory.protocols.itervalues(): packet = protocol.player.save_to_packet() packet += protocol.player.save_equipment_to_packet() self.transport.write(packet) self.write_packet("create", eid=protocol.player.eid) # *Now* we are in our factory's list of protocols. Be aware. self.factory.protocols[self.username] = self # Send spawn and inventory. spawn = self.factory.world.spawn packet = make_packet("spawn", x=spawn[0], y=spawn[1], z=spawn[2]) packet += self.inventory.save_to_packet() self.transport.write(packet) # Send weather. self.transport.write(self.factory.vane.make_packet()) self.send_initial_chunk_and_location() self.time_loop = LoopingCall(self.update_time) self.time_loop.start(10)
def authenticated(self): BetaServerProtocol.authenticated(self) # Init player, and copy data into it. self.player = yield self.factory.world.load_player(self.username) self.player.eid = self.eid self.location = self.player.location # Init players' inventory window. self.inventory = InventoryWindow(self.player.inventory) # Announce our presence. packet = make_packet("chat", message="%s is joining the game..." % self.username) packet += make_packet("players", name=self.username, online=True, ping=0) self.factory.broadcast(packet) # Craft our avatar and send it to already-connected other players. packet = self.player.save_to_packet() packet += make_packet("create", eid=self.player.eid) self.factory.broadcast_for_others(packet, self) # And of course spawn all of those players' avatars in our client as # well. Note that, at this point, we are not listed in the factory's # list of protocols, so we won't accidentally send one of these to # ourselves. for protocol in self.factory.protocols.itervalues(): packet = protocol.player.save_to_packet() packet += protocol.player.save_equipment_to_packet() self.transport.write(packet) self.write_packet("create", eid=protocol.player.eid) # *Now* we are in our factory's list of protocols. Be aware. self.factory.protocols[self.username] = self # Send spawn and inventory. spawn = self.factory.world.level.spawn packet = make_packet("spawn", x=spawn[0], y=spawn[1], z=spawn[2]) packet += self.inventory.save_to_packet() self.transport.write(packet) # Send weather. self.transport.write(self.factory.vane.make_packet()) self.send_initial_chunk_and_location() self.time_loop = LoopingCall(self.update_time) self.time_loop.start(10)
def update_location(self): """ Send this client's location to the client. Also let other clients know where this client is. """ # Don't bother trying to update things if the position's not yet # synchronized. We could end up jettisoning them into the void. if self.state != STATE_LOCATED: return x, y, z = self.location.pos yaw, pitch = self.location.ori.to_fracs() # Inform everybody of our new location. packet = make_packet("teleport", eid=self.player.eid, x=x, y=y, z=z, yaw=yaw, pitch=pitch) self.factory.broadcast_for_others(packet, self) # Inform ourselves of our new location. packet = self.location.save_to_packet() self.transport.write(packet)
def test_build_0x28(self): # Entity metadata self.check(0x28, make_packet('metadata', eid=8150, metadata={ 0: ('byte', 0), 1: ('short', 300), 10: ('slot', Slot(262, 2)) }))
def animate(self, container): # Broadcast the animation of the entity to everyone else. Only swing # arm is send by notchian clients. packet = make_packet("animate", eid=self.player.eid, animation=container.animation) self.factory.broadcast_for_others(packet, self)
def sign(self, container): bigx, smallx, bigz, smallz = split_coords(container.x, container.z) try: chunk = self.chunks[bigx, bigz] except KeyError: self.error("Couldn't handle sign in chunk (%d, %d)!" % (bigx, bigz)) return if (smallx, container.y, smallz) in chunk.tiles: new = False s = chunk.tiles[smallx, container.y, smallz] else: new = True s = Sign(smallx, container.y, smallz) chunk.tiles[smallx, container.y, smallz] = s s.text1 = container.line1 s.text2 = container.line2 s.text3 = container.line3 s.text4 = container.line4 chunk.dirty = True # The best part of a sign isn't making one, it's showing everybody # else on the server that you did. packet = make_packet("sign", container) self.factory.broadcast_for_chunk(packet, bigx, bigz) # Run sign hooks. for hook in self.sign_hooks: hook.sign_hook(self.factory, chunk, container.x, container.y, container.z, [s.text1, s.text2, s.text3, s.text4], new)
def save_to_packet(self): """ Create a "player" packet representing this entity. """ yaw, pitch = self.location.ori.to_fracs() x, y, z = self.location.pos item = self.inventory.holdables[self.equipped] if item is None: item = 0 else: item = item[0] packet = make_packet( "player", eid=self.eid, username=self.username, x=x, y=y, z=z, yaw=yaw, pitch=pitch, item=item, # http://www.wiki.vg/Entities#Objects metadata={ 0: ('byte', 0), # Flags 1: ('short', 300), # Drowning counter 8: ('int', 0), # Color of the bubbling effects }) return packet
def give(self, coords, block, quantity): """ Spawn a pickup at the specified coordinates. The coordinates need to be in pixels, not blocks. If the size of the stack is too big, multiple stacks will be dropped. :param tuple coords: coordinates, in pixels :param tuple block: key of block or item to drop :param int quantity: number of blocks to drop in the stack """ x, y, z = coords while quantity > 0: entity = self.create_entity(x // 32, y // 32, z // 32, "Item", item=block, quantity=min(quantity, 64)) packet = entity.save_to_packet() packet += make_packet("create", eid=entity.eid) self.broadcast(packet) quantity -= 64
def save_to_packet(self): """ Generate a chunk packet. """ mask = 0 packed = [] ls = segment_array(self.blocklight) for i, section in enumerate(self.sections): if any(section.blocks): mask |= 1 << i packed.append(section.blocks.tostring()) for i, section in enumerate(self.sections): if mask & 1 << i: packed.append(pack_nibbles(section.metadata)) for i, l in enumerate(ls): if mask & 1 << i: packed.append(pack_nibbles(l)) for i, section in enumerate(self.sections): if mask & 1 << i: packed.append(pack_nibbles(section.skylight)) # Fake the biome data. packed.append("\x00" * 256) packet = make_packet("chunk", x=self.x, z=self.z, continuous=True, primary=mask, add=0x0, data="".join(packed)) return packet
def animate(self, container): # Broadcast the animation of the entity to everyone else. Only swing # arm is send by notchian clients. packet = make_packet("animate", eid=self.player.eid, animation=container.animation ) self.factory.broadcast_for_others(packet, self)
def orientation_changed(self): # Bang your head! packet = make_packet("entity-orientation", eid=self.player.eid, yaw=int(self.location.theta * 255 / (2 * pi)) % 256, pitch=int(self.location.phi * 255 / (2 * pi)) % 256, ) self.factory.broadcast_for_others(packet, self)
def orientation_changed(self): # Bang your head! yaw, pitch = self.location.ori.to_fracs() packet = make_packet("entity-orientation", eid=self.player.eid, yaw=yaw, pitch=pitch) self.factory.broadcast_for_others(packet, self)
def save_location_to_packet(self): return make_packet("teleport", eid=self.eid, x=self.location.x * 32 + 16, y=self.location.y * 32, z=self.location.z * 32 + 16, yaw=int(self.location.yaw), pitch=int(self.location.pitch), )
def save_to_packet(self): """ Create a "painting" packet representing this entity. """ x, y, z = self.location.pos return make_packet("painting", eid=self.eid, title=self.motive, x=x, y=y, z=z, direction=self.direction)
def save_to_packet(self): """ Create a "pickup" packet representing this entity. """ x, y, z = self.location.pos packets = make_packet('object', eid=self.eid, type='item_stack', x=x, y=y, z=z, yaw=0, pitch=0, data=1, speed=Speed(0, 0, 0)) packets += make_packet('metadata', eid=self.eid, # See http://www.wiki.vg/Entities#Objects metadata={ 0: ('byte', 0), # Flags 1: ('short', 300), # Drowning counter 10: ('slot', Slot.fromItem(self.item, self.quantity)) }) return packets
def connectionLost(self, reason): """ Cleanup after a lost connection. Most of the time, these connections are lost cleanly; we don't have any cleanup to do in the unclean case since clients don't have any kind of pending state which must be recovered. Remember, the connection can be lost before identification and authentication, so ``self.username`` and ``self.player`` can be None. """ if self.username and self.player: self.factory.world.save_player(self.username, self.player) if self.player: self.factory.destroy_entity(self.player) packet = make_packet("destroy", eid=self.player.eid) self.factory.broadcast(packet) if self.username: packet = make_packet("players", name=self.username, online=False, ping=0) self.factory.broadcast(packet) self.factory.chat("%s has left the game." % self.username) self.factory.teardown_protocol(self) # We are now torn down. After this point, there will be no more # factory stuff, just our own personal stuff. del self.factory if self.time_loop: self.time_loop.stop() if self.chunk_tasks: for task in self.chunk_tasks: try: task.stop() except (TaskDone, TaskFailed): pass
def test_build_0x28(self): # Entity metadata self.check( 0x28, make_packet('metadata', eid=8150, metadata={ 0: ('byte', 0), 1: ('short', 300), 10: ('slot', Slot(262, 2)) }))
def dispatch(self, parameters): player = parse_player(self.factory, parameters[0]) if len(parameters) == 1: msg = "%s has been kicked." % parameters[0] elif len(parameters) > 1: reason = " ".join(parameters[1:]) msg = "%s has been kicked for %s" % (parameters[0], reason) packet = make_packet("error", message=msg) player.transport.write(packet) yield msg
def save_to_packet(self): """ Create a "pickup" packet representing this entity. """ x, y, z = self.location.pos return make_packet("pickup", eid=self.eid, primary=self.item[0], secondary=self.item[1], count=self.quantity, x=x, y=y, z=z, yaw=0, pitch=0, roll=0)
def save_to_packet(self): packet = make_packet("sign", x=self.x, y=self.y, z=self.z, line1=self.text1, line2=self.text2, line3=self.text3, line4=self.text4) return packet
def dispatch(self, parameters): player = parse_player(self.factory, parameters[0]) if len(parameters) == 1: msg = "%s has been kicked." % parameters[0] elif len(parameters) > 1: reason = " ".join(parameters[1:]) msg = "%s has been kicked for %s" % (parameters[0],reason) packet = make_packet("error", message=msg) player.transport.write(packet) yield msg
def login(self, protocol, container): protocol.username = container.username packet = make_packet("login", protocol=protocol.eid, username="", seed=protocol.factory.world.seed, mode=protocol.factory.mode, dimension=protocol.factory.world.dimension, unknown=1, height=128, players=0) protocol.transport.write(packet) return succeed(None)
def save_to_packet(self): l = [] for item in chain(*self.metalist): if item is None: l.append(Container(primary=-1)) else: l.append(Container(primary=item.primary, secondary=item.secondary, count=item.quantity)) packet = make_packet("inventory", wid=self.wid, length=len(l), items=l) return packet
def save_location_to_packet(self): x, y, z = self.location.pos yaw, pitch = self.location.ori.to_fracs() return make_packet("teleport", eid=self.eid, x=x, y=y, z=z, yaw=yaw, pitch=pitch)
def success(self, response, protocol, container): if response != "YES": protocol.error("Authentication server didn't like you.") return packet = make_packet("login", protocol=protocol.eid, username="", seed=protocol.factory.world.seed, mode=protocol.factory.mode, dimension=protocol.factory.world.dimension, unknown=1, height=128, players=0) protocol.transport.write(packet)
def latency(self, value): # Clamp the value to not exceed the boundaries of the packet. This is # necessary even though, in theory, a ping this high is bad news. value = clamp(value, 0, 65535) # Check to see if this is a new value, and if so, alert everybody. if self._latency != value: packet = make_packet("players", name=self.username, online=True, ping=value) self.factory.broadcast(packet) self._latency = value
def save_to_packet(self): """ Generate a chunk packet. """ array = self.blocks.tostring() array += pack_nibbles(self.metadata) array += pack_nibbles(self.blocklight) array += pack_nibbles(self.skylight) packet = make_packet("chunk", x=self.x * 16, y=0, z=self.z * 16, x_size=15, y_size=127, z_size=15, data=array) return packet
def login(self, protocol, container): protocol.username = container.username players = min(protocol.factory.limitConnections, 60) packet = make_packet("login", protocol=protocol.eid, username="", seed=protocol.factory.world.seed, mode=protocol.factory.mode, dimension=protocol.factory.world.dimension, difficulty=1, height=128, players=players) protocol.transport.write(packet) return succeed(None)
def test_build_0x17(self): # Add vehicle/object self.check( 0x17, make_packet('object', eid=8150, type='item_stack', x=-4801, y=2180, z=-1468, pitch=0, yaw=237, data=1, speed=Speed(0, 0, 0)))
def save_to_packet(self): """ Returns a position/look/grounded packet. """ position = Container(x=self.x, y=self.stance, z=self.z, stance=self.y) orientation = Container(rotation=self.yaw, pitch=self.pitch) grounded = Container(grounded=self.grounded) packet = make_packet("location", position=position, orientation=orientation, grounded=grounded) return packet
def position_changed(self): # Send chunks. self.update_chunks() for entity in self.entities_near(2): if entity.name != "Item": continue left = self.player.inventory.add(entity.item, entity.quantity) if left != entity.quantity: if left != 0: # partial collect entity.quantity = left else: packet = make_packet("collect", eid=entity.eid, destination=self.player.eid) packet += make_packet("destroy", count=1, eid=[entity.eid]) self.factory.broadcast(packet) self.factory.destroy_entity(entity) packet = self.inventory.save_to_packet() self.transport.write(packet)
def save_to_packet(self): """ Create a "mob" packet representing this entity. """ x, y, z = self.location.pos yaw, pitch = self.location.ori.to_fracs() # Update metadata from instance variables. self.update_metadata() return make_packet("mob", eid=self.eid, type=self.name, x=x, y=y, z=z, yaw=yaw, pitch=pitch, metadata=self.metadata)
def handshake(self, protocol, container): """ Handle a handshake with an online challenge. """ challenge = "%x" % random.randint(0, sys.maxint) self.challenges[protocol] = challenge packet = make_packet("handshake", username=challenge) d = deferLater(reactor, 0, protocol.challenged) d.addCallback(lambda none: protocol.transport.write(packet)) return True
def console_command(self, parameters): # Let's shutdown! message = "Server shutting down." yield message # Use an error packet to kick clients cleanly. packet = make_packet("error", message=message) self.factory.broadcast(packet) yield "Saving all chunks to disk..." for chunk in self.factory.world.dirty_chunk_cache.itervalues(): self.factory.world.save_chunk(chunk) yield "Halting." reactor.stop()
def handshake(self, protocol, container): """ Handle a handshake with an offline challenge. This will authenticate just about anybody. """ packet = make_packet("handshake", username="******") # Order is important here; the challenged callback *must* fire before # we send anything back to the client, because otherwise we won't have # a valid entity ready to use. d = deferLater(reactor, 0, protocol.challenged) d.addCallback(lambda none: protocol.transport.write(packet)) return True
def equip(self, container): self.player.equipped = container.item # Inform everyone about the item the player is holding now. item = self.player.inventory.holdables[self.player.equipped] if item is None: # Empty slot. Use signed short -1 == unsigned 65535. primary, secondary = 65535, 0 else: primary, secondary, count = item packet = make_packet("entity-equipment", eid=self.player.eid, slot=0, primary=primary, secondary=secondary) self.factory.broadcast_for_others(packet, self)