public static void onClick(long x, short y, long z, boolean mouseButton, boolean shift) { for (Chunk chunk : chunks) { if (chunk.isInBounds(x, z)) { chunk.onClick(x, y, z, mouseButton, shift); } } }
@Test public void testAfterWrite() throws Exception { Chunk<String> chunk = new Chunk<String>(Arrays.asList("foo", "fail", "bar")); processor.setListeners( Arrays.asList( new ItemListenerSupport<String, String>() { @Override public void afterWrite(List<? extends String> item) { after.addAll(item); } })); processor.setWriteSkipPolicy(new AlwaysSkipItemSkipPolicy()); processAndExpectPlannedRuntimeException(chunk); processor.process(contribution, chunk); assertEquals(2, chunk.getItems().size()); processAndExpectPlannedRuntimeException(chunk); assertEquals(1, chunk.getItems().size()); processor.process(contribution, chunk); assertEquals(0, chunk.getItems().size()); // foo is written once because it the failure is detected before it is // committed the first time assertEquals("[foo, bar]", list.toString()); // the after listener is called once per successful item, which is // important assertEquals("[foo, bar]", after.toString()); }
// When a chunk unloads, remove its monsters, excluding Withers // EnderDragon is NOT a monster, it is a ComplexLivingEntity (LEAVE ENDER ALONE) // Hoping this cuts down on lag? @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onChunkUnload(ChunkUnloadEvent event) { Chunk chunk = event.getChunk(); for (Entity entity : chunk.getEntities()) { if (!entity.isDead() && entity instanceof Monster) { Monster monster = (Monster) entity; Boolean remove = true; if (monster.getCustomName() != null) { remove = false; } if (monster.getType() == EntityType.WITHER) { remove = false; } for (ItemStack item : monster.getEquipment().getArmorContents()) { if (item != null) { remove = false; break; } } if ((monster.getEquipment().getItemInHand() != null) || (monster.getType() == EntityType.SKELETON && monster.getEquipment().getItemInHand().getType() != Material.BOW)) { remove = false; } if (remove) { if (monster.getVehicle() instanceof Chicken) { monster.getVehicle().remove(); } monster.remove(); } } } }
public void save(Chunk chunk) { ChunkPosition pos = chunk.getPosition(); CompressedChunk c = chunks.get(pos); if (c == null) { c = new CompressedChunk(pos); chunks.put(pos, c); c.setVersion(~chunk.getVersion()); } if (c.getVersion() != chunk.getVersion()) { if (c.getData() != null) { approxSize.addAndGet(-c.getData().length); } long start = TimeStatistics.TIME_STATISTICS.start(); // ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); // DataOutputStream dataOut = new DataOutputStream(byteOut); // compressor.compress(dataOut, chunk.getDataXZY()); try { c.setData(DeflaterWrapper.compress(chunk.getDataXZY())); // c.setData(DeflaterWrapper.compress(byteOut.toByteArray())); } catch (IOException ex) { throw new RuntimeException(ex); } c.setVersion(chunk.getVersion()); TimeStatistics.TIME_STATISTICS.end(start, "save"); approxSize.addAndGet(-c.getData().length); if (chunks.size() % 1000 == 0) { System.out.println( Util.humanReadableByteCount(approxSize.get()) + ", " + Util.humanReadableByteCount(approxSize.get() / chunks.size()) + "/chunk"); } } }
@Override public void onLoadCompleted(Loadable loadable) { long now = SystemClock.elapsedRealtime(); long loadDurationMs = now - currentLoadStartTimeMs; Chunk currentLoadable = currentLoadableHolder.chunk; chunkSource.onChunkLoadCompleted(currentLoadable); if (isMediaChunk(currentLoadable)) { BaseMediaChunk mediaChunk = (BaseMediaChunk) currentLoadable; notifyLoadCompleted( currentLoadable.bytesLoaded(), mediaChunk.type, mediaChunk.trigger, mediaChunk.format, mediaChunk.startTimeUs, mediaChunk.endTimeUs, now, loadDurationMs); } else { notifyLoadCompleted( currentLoadable.bytesLoaded(), currentLoadable.type, currentLoadable.trigger, currentLoadable.format, -1, -1, now, loadDurationMs); } clearCurrentLoadable(); updateLoadControl(); }
/** * Render overlay icons * * @param world * @param chunky * @param g * @param renderBuffer */ public void renderHUD(World world, Chunky chunky, Graphics g, RenderBuffer renderBuffer) { boolean loadIndicator = chunky.isLoading(); Chunk.Renderer renderer = chunky.getChunkRenderer(); ChunkView view = renderBuffer.getView(); if (loadIndicator) { g.drawImage(MiscImages.clock, view.width - 32, 0, 32, 32, null); } if (world.havePlayerPos()) { renderPlayer( world, g, view, renderer == Chunk.surfaceRenderer || world.playerLocY() == world.currentLayer()); } if (world.haveSpawnPos()) { renderSpawn( world, g, view, renderer == Chunk.surfaceRenderer || world.spawnPosY() == world.currentLayer()); } Chunk hoveredChunk = chunky.getHoveredChunk(); if (!hoveredChunk.isEmpty()) { g.setFont(font); g.setColor(Color.white); g.drawString("Chunk: " + hoveredChunk.getPosition(), 5, view.height - 5); } }
public static void main(String[] args) { String host = (args.length < 1) ? null : args[0]; int[] big_array = new int[100000]; for (int i = 0; i < big_array.length; i++) big_array[i] = i; try { int[] first_arr = new int[big_array.length / 2]; for (int i = 0; i < first_arr.length; i++) first_arr[i] = big_array[i]; int[] second_arr = new int[big_array.length / 2]; for (int i = 0; i < second_arr.length; i++) second_arr[i] = big_array[i + big_array.length / 2]; Registry registry = LocateRegistry.getRegistry(host, 4242); Chunk stub = (Chunk) registry.lookup("Chunk1"); int a = stub.sum(first_arr); System.out.println("sub sub:" + a); Registry registry2 = LocateRegistry.getRegistry(host, 4242); Chunk stub2 = (Chunk) registry.lookup("Chunk2"); int b = stub.sum(second_arr); System.out.println("sub sub:" + b); System.out.println("Total: " + (a + b)); } catch (Exception e) { System.err.println("Client exception: " + e.toString()); e.printStackTrace(); } }
@NonNull protected static Map<String, Chunk> readChunks(@NonNull File file) throws IOException { Map<String, Chunk> chunks = Maps.newHashMap(); byte[] fileBuffer = Files.toByteArray(file); ByteBuffer buffer = ByteBuffer.wrap(fileBuffer); byte[] sig = new byte[8]; buffer.get(sig); assertTrue(Arrays.equals(sig, SIGNATURE)); byte[] data, type; int len; int crc32; while (buffer.hasRemaining()) { len = buffer.getInt(); type = new byte[4]; buffer.get(type); data = new byte[len]; buffer.get(data); // crc crc32 = buffer.getInt(); Chunk chunk = new Chunk(type, data, crc32); chunks.put(chunk.getTypeAsString(), chunk); } return chunks; }
public boolean unloadChunks() { if (!this.world.savingDisabled) { // CraftBukkit start Server server = this.world.getServer(); for (int i = 0; i < 50 && !this.unloadQueue.isEmpty(); i++) { long chunkcoordinates = this.unloadQueue.popFirst(); Chunk chunk = this.chunks.get(chunkcoordinates); if (chunk == null) continue; ChunkUnloadEvent event = new ChunkUnloadEvent(chunk.bukkitChunk); server.getPluginManager().callEvent(event); if (!event.isCancelled()) { chunk.removeEntities(); this.saveChunk(chunk); this.saveChunkNOP(chunk); // this.unloadQueue.remove(integer); this.chunks.remove(chunkcoordinates); // CraftBukkit this.chunkList.remove(chunk); } } // CraftBukkit end if (this.e != null) { this.e.a(); } } return this.chunkProvider.unloadChunks(); }
public boolean saveChunks(boolean flag, IProgressUpdate iprogressupdate) { int i = 0; for (int j = 0; j < this.chunkList.size(); ++j) { Chunk chunk = (Chunk) this.chunkList.get(j); if (flag) { this.saveChunkNOP(chunk); } if (chunk.a(flag)) { this.saveChunk(chunk); chunk.l = false; ++i; if (i == 24 && !flag) { return false; } } } if (flag) { if (this.e == null) { return true; } this.e.b(); } return true; }
public void getChunkAt(IChunkProvider ichunkprovider, int i, int j) { Chunk chunk = this.getOrCreateChunk(i, j); if (!chunk.done) { chunk.done = true; if (this.chunkProvider != null) { this.chunkProvider.getChunkAt(ichunkprovider, i, j); // CraftBukkit start BlockSand.instaFall = true; Random random = new Random(); random.setSeed(world.getSeed()); long xRand = random.nextLong() / 2L * 2L + 1L; long zRand = random.nextLong() / 2L * 2L + 1L; random.setSeed((long) i * xRand + (long) j * zRand ^ world.getSeed()); org.bukkit.World world = this.world.getWorld(); if (world != null) { for (org.bukkit.generator.BlockPopulator populator : world.getPopulators()) { populator.populate(world, random, chunk.bukkitChunk); } } BlockSand.instaFall = false; this.world .getServer() .getPluginManager() .callEvent(new org.bukkit.event.world.ChunkPopulateEvent(chunk.bukkitChunk)); // CraftBukkit end chunk.e(); } } }
/** * Adds an <CODE>Object</CODE> to the <CODE>List</CODE>. * * @param o the object to add. * @return true if adding the object succeeded */ public boolean add(Object o) { if (o instanceof ListItem) { ListItem item = (ListItem) o; if (numbered || lettered) { Chunk chunk; if (lettered) chunk = new Chunk(nextLetter(), symbol.font()); else chunk = new Chunk(String.valueOf(first + list.size()), symbol.font()); chunk.append("."); item.setListSymbol(chunk); } else { item.setListSymbol(symbol); } item.setIndentationLeft(symbolIndent); item.setIndentationRight(0); list.add(item); } else if (o instanceof List) { List nested = (List) o; nested.setIndentationLeft(nested.indentationLeft() + symbolIndent); first--; return list.add(nested); } else if (o instanceof String) { return this.add(new ListItem((String) o)); } return false; }
/** * Adds a <CODE>Chunk</CODE>, an <CODE>Anchor</CODE> or another <CODE>Phrase</CODE> to this <CODE> * Phrase</CODE>. * * @param index index at which the specified element is to be inserted * @param o an object of type <CODE>Chunk</CODE>, <CODE>Anchor</CODE> or <CODE>Phrase</CODE> * @throws ClassCastException when you try to add something that isn't a <CODE>Chunk</CODE>, * <CODE>Anchor</CODE> or <CODE>Phrase</CODE> */ public void add(int index, Object o) { if (o == null) return; try { Element element = (Element) o; if (element.type() == Element.CHUNK) { Chunk chunk = (Chunk) element; if (!font.isStandardFont()) { chunk.setFont(font.difference(chunk.getFont())); } if (hyphenation != null) { chunk.setHyphenation(hyphenation); } super.add(index, chunk); } else if (element.type() == Element.PHRASE || element.type() == Element.ANCHOR || element.type() == Element.ANNOTATION || element.type() == Element.TABLE || // line added by David Freels element.type() == Element.YMARK || element.type() == Element.MARKED) { super.add(index, element); } else { throw new ClassCastException(String.valueOf(element.type())); } } catch (ClassCastException cce) { throw new ClassCastException("Insertion of illegal Element: " + cce.getMessage()); } }
public boolean canSpawn() { Chunk chunk = this.world.getChunkAtWorldCoords(MathHelper.floor(this.locX), MathHelper.floor(this.locZ)); if (this.world.getWorldData().getType() == WorldType.FLAT && this.random.nextInt(4) != 1) { return false; } else { if (this.getSize() == 1 || this.world.difficulty > 0) { BiomeBase biomebase = this.world.getBiome(MathHelper.floor(this.locX), MathHelper.floor(this.locZ)); if (biomebase == BiomeBase.SWAMPLAND && this.locY > 50.0D && this.locY < 70.0D && this.random.nextFloat() < 0.5F && this.random.nextFloat() < e[this.world.w()] && this.world.getLightLevel( MathHelper.floor(this.locX), MathHelper.floor(this.locY), MathHelper.floor(this.locZ)) <= this.random.nextInt(8)) { return super.canSpawn(); } if (this.random.nextInt(10) == 0 && chunk.a(987234911L).nextInt(10) == 0 && this.locY < 40.0D) { return super.canSpawn(); } } return false; } }
public void addStr(Chunk c, int row) { if (c.isNA(row)) addNA(); else { addStr(c.atStr(new BufferedString(), row)); _isAllASCII &= ((CStrChunk) c)._isAllASCII; } }
@Override public byte[] generate(World world, Random random, int chunkX, int chunkZ) { Chunk chunk = new Chunk(); // what type of road? boolean northsouth = chunkX % cityblocksize == 0; boolean eastwest = chunkZ % cityblocksize == 0; // underlayment chunk.setLayer(random, 0, Material.BEDROCK); // TODO Need to do something MUCH smarter // TODO Multiple width buildings // roads? if (northsouth || eastwest) { chunk.setStreet(world, random, citystreetat, northsouth, eastwest); // park? (about one per city block, on average) } else if (random.nextInt((cityblocksize - 1) * (cityblocksize - 1)) == 0) { chunk.setPark(world, random, citystreetat); // building... } else { chunk.setBuilding(world, random, citystreetat); } return chunk.blocks; }
@Override public void unloadChunks() { for (Chunk chunk : this.chunks.values()) { this.unloadChunk(chunk.getX(), chunk.getZ(), false); } this.chunks = new HashMap<>(); }
/** * Handles post-mortem of writes that have failed. * * @param cause the cause of the failure. * @param propagateErrorIfRequired if {@code true} and {@code cause} is not an instance of {@link * Exception}, the error is propagated through the netty pipeline. */ private void handleChannelWriteFailure(Throwable cause, boolean propagateErrorIfRequired) { long writeFailureProcessingStartTime = System.currentTimeMillis(); try { nettyMetrics.channelWriteError.inc(); Exception exception; if (!(cause instanceof Exception)) { logger.warn("Encountered a throwable on channel write failure", cause); exception = new IllegalStateException("Encountered a Throwable - " + cause.getMessage()); if (propagateErrorIfRequired) { // we can't ignore throwables - so we let Netty deal with it. ctx.fireExceptionCaught(cause); nettyMetrics.throwableCount.inc(); } } else { exception = (Exception) cause; } onResponseComplete(exception); logger.trace("Cleaning up remaining chunks on write failure"); Chunk chunk = chunksAwaitingCallback.poll(); while (chunk != null) { chunk.resolveChunk(exception); chunk = chunksAwaitingCallback.poll(); } chunk = chunksToWrite.poll(); while (chunk != null) { chunksToWriteCount.decrementAndGet(); chunk.resolveChunk(exception); chunk = chunksToWrite.poll(); } } finally { nettyMetrics.channelWriteFailureProcessingTimeInMs.update( System.currentTimeMillis() - writeFailureProcessingStartTime); } }
public StringBuilder toString(StringBuilder sb, String[] fs, long idx) { Vec vecs[] = vecs(); for (int c = 0; c < fs.length; c++) { Vec vec = vecs[c]; if (vec.isEnum()) { String s = "----------"; if (!vec.isNA(idx)) { int x = (int) vec.at8(idx); if (x >= 0 && x < vec._domain.length) s = vec._domain[x]; } sb.append(String.format(fs[c], s)); } else if (vec.isInt()) { if (vec.isNA(idx)) { Chunk C = vec.elem2BV(0); // 1st Chunk int len = C.pformat_len0(); // Printable width for (int i = 0; i < len; i++) sb.append('-'); } else { try { sb.append(String.format(fs[c], vec.at8(idx))); } catch (IllegalFormatException ife) { System.out.println("Format: " + fs[c] + " col=" + c + " not for ints"); ife.printStackTrace(); } } } else { sb.append(String.format(fs[c], vec.at(idx))); if (vec.isNA(idx)) sb.append(' '); } sb.append(' '); // Column seperator } sb.append('\n'); return sb; }
public Chunk getOrCreateChunk(int i, int j) { // CraftBukkit start Chunk chunk = this.chunks.get(i, j); chunk = chunk == null ? (!this.world.isLoading && !this.forceChunkLoad ? this.emptyChunk : this.getChunkAt(i, j)) : chunk; if (chunk == this.emptyChunk) return chunk; if (i != chunk.x || j != chunk.z) { MinecraftServer.log.severe( "Chunk (" + chunk.x + ", " + chunk.z + ") stored at (" + i + ", " + j + ") in world '" + world.getWorld().getName() + "'"); MinecraftServer.log.severe(chunk.getClass().getName()); Throwable ex = new Throwable(); ex.fillInStackTrace(); ex.printStackTrace(); } return chunk; // CraftBukkit end }
@Override public void map(Chunk chks[], NewChunk nchks[]) { long rstart = chks[0]._start; int rlen = chks[0]._len; // Total row count int rx = 0; // Which row to in/ex-clude int rlo = 0; // Lo/Hi for this block of rows int rhi = rlen; while (true) { // Still got rows to include? if (_rows != null) { // Got a row selector? if (rx >= _rows.length) break; // All done with row selections long r = _rows[rx++] - 1; // Next row selector if (r < 0) { // Row exclusion if (rx > 0 && _rows[rx - 1] < _rows[rx]) throw H2O.unimpl(); long er = Math.abs(r) - 2; if (er < rstart) continue; // scoop up all of the rows before the first exclusion if (rx == 1 && ((int) (er + 1 - rstart)) > 0 && _ex) { rlo = (int) rstart; rhi = (int) (er - rstart); _ex = false; rx--; } else { rlo = (int) (er + 1 - rstart); // TODO: handle jumbled row indices ( e.g. -c(1,5,3) ) while (rx < _rows.length && (_rows[rx] + 1 == _rows[rx - 1] && rlo < rlen)) { if (rx < _rows.length - 1 && _rows[rx] < _rows[rx + 1]) throw H2O.unimpl(); rx++; rlo++; // Exclude consecutive rows } rhi = rx >= _rows.length ? rlen : (int) Math.abs(_rows[rx] - 1) - 2; if (rx < _rows.length - 1 && _rows[rx] < _rows[rx + 1]) throw H2O.unimpl(); } } else { // Positive row list? if (r < rstart) continue; rlo = (int) (r - rstart); rhi = rlo + 1; // Stop at the next row while (rx < _rows.length && (_rows[rx] - 1 - rstart) == rhi && rhi < rlen) { rx++; rhi++; // Grab sequential rows } } } // Process this next set of rows // For all cols in the new set for (int i = 0; i < _cols.length; i++) { Chunk oc = chks[_cols[i]]; NewChunk nc = nchks[i]; if (oc._vec.isInt()) { // Slice on integer columns for (int j = rlo; j < rhi; j++) if (oc.isNA0(j)) nc.addNA(); else nc.addNum(oc.at80(j), 0); } else { // Slice on double columns for (int j = rlo; j < rhi; j++) nc.addNum(oc.at0(j)); } } rlo = rhi; if (_rows == null) break; } }
/** * @param decodedChunk * @return */ public PNGChunk encode(Chunk decodedChunk) { String chunkTypeString = decodedChunk.getChunkType(); byte[] chunkType = chunkTypeString.getBytes(); byte[] data = decodedChunk.toByteArray(); int length = data.length; PNGChunk encodedChunk = new PNGChunk(length, chunkType, data, 0, 0); return encodedChunk; }
public void write(Chunk chunk) throws IOException { SeekableByteChannel input = getInput(chunk); input.position(chunk.getOffset()); long pos = out.position(); out.write(NIOUtils.fetchFrom(input, (int) chunk.getSize())); offsets[curChunk++] = pos; }
@Override public void map(Chunk chks[], NewChunk nchks[]) { Chunk pred = chks[chks.length - 1]; for (int i = 0; i < pred._len; ++i) { if (pred.at0(i) != 0) for (int j = 0; j < chks.length - 1; ++j) nchks[j].addNum(chks[j].at0(i)); } }
@Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((original == null) ? 0 : original.hashCode()); result = prime * result + ((revised == null) ? 0 : revised.hashCode()); return result; }
private static void validate(Chunk chunk) { if (chunk == null) throw new IllegalArgumentException("Input chunk is null"); if (chunk.getChunkType() != ChunkType.TEXT && chunk.getChunkType() != ChunkType.ZTXT && chunk.getChunkType() != ChunkType.ITXT) { throw new IllegalArgumentException("Not a valid textual chunk."); } }
@Override public boolean unloadChunk(int X, int Z, boolean safe) { String index = Level.chunkHash(X, Z); Chunk chunk = this.chunks.containsKey(index) ? this.chunks.get(index) : null; if (chunk != null && chunk.unload(false, safe)) { this.chunks.remove(index); return true; } return false; }
public void setMeta(int x, int y, int m) { Chunk chunk = getChunkI(x, y); if (chunk == null) return; TileInstance t = chunk.getTileInstance(x, y); if (t != null) { int m0 = t.metadata; t.metadata = (byte) m; if (m0 != m) chunk.markDirty(); } }
public boolean g() { Chunk chunk = this.world.getChunkAtWorldCoords(MathHelper.floor(this.locX), MathHelper.floor(this.locZ)); return (this.getSize() == 1 || this.world.difficulty > 0) && this.random.nextInt(10) == 0 && chunk.a(987234911L).nextInt(10) == 0 && this.locY < 40.0D ? super.g() : false; }
public Location getSurfaceAt(Location origin) { Chunk chunky = origin.getChunk(); int x = origin.getBlockX(), z = origin.getBlockZ(), surface = 0, envid = origin.getWorld().getEnvironment().getId(); Set dimmap = Sets.newHashSet(envid == 0 ? new int[] {1, 2, 3, 7, 15, 16} : envid == -1 ? 87 : 121); for (int y = 0; y != 256; y++) if (dimmap.contains(chunky.getBlock(x, y, z).getTypeId())) surface = y; return chunky.getBlock(x, surface, z).getLocation(); }