Search in sources :

Example 1 with CubicChunk

use of io.xol.chunkstories.world.chunk.CubicChunk in project chunkstories by Hugobros3.

the class MultithreadedOfflineWorldConverter method stepThreeSpreadLightning.

protected void stepThreeSpreadLightning(WorldTool csWorld) {
    verbose("Entering step three: spreading light");
    csWorld.setLightning(true);
    WorldSize size = csWorld.getWorldInfo().getSize();
    int maxHeightPossible = 256;
    int done = 0;
    int todo = (size.sizeInChunks) * (size.sizeInChunks);
    double completion = 0.0;
    long lastPercentageShow = System.currentTimeMillis();
    Set<ChunkHolder> registeredCS_Holders = new HashSet<ChunkHolder>();
    Set<Heightmap> registeredCS_Summaries = new HashSet<Heightmap>();
    int chunksAquired = 0;
    WorldUser worldUser = this;
    int waveSize = this.threadsCount * 32;
    int wave = 0;
    CompoundFence waveFence = new CompoundFence();
    for (int chunkX = 0; chunkX < size.sizeInChunks; chunkX++) {
        for (int chunkZ = 0; chunkZ < size.sizeInChunks; chunkZ++) {
            wave++;
            CompoundFence loadRelevantData = new CompoundFence();
            Heightmap sum = csWorld.getRegionsSummariesHolder().aquireHeightmapChunkCoordinates(worldUser, chunkX, chunkZ);
            registeredCS_Summaries.add(sum);
            loadRelevantData.add(sum.waitForLoading());
            // Loads 3x3 arround relevant chunks
            for (int i = -1; i < 2; i++) {
                for (int j = -1; j < 2; j++) {
                    for (int chunkY = 0; chunkY <= maxHeightPossible / 32; chunkY++) {
                        ChunkHolder chunkHolder = csWorld.aquireChunkHolder(worldUser, chunkX + i, chunkY, chunkZ + j);
                        if (chunkHolder != null) {
                            loadRelevantData.add(chunkHolder.waitForLoading());
                            if (registeredCS_Holders.add(chunkHolder))
                                chunksAquired++;
                        }
                    }
                }
            }
            assert chunksAquired == registeredCS_Holders.size();
            // Wait for everything to actually load
            loadRelevantData.traverse();
            // Spreads lightning, from top to botton
            for (int chunkY = maxHeightPossible / 32; chunkY >= 0; chunkY--) {
                CubicChunk chunk = csWorld.getChunk(chunkX, chunkY, chunkZ);
                Fence fence = chunk.lightBaker.requestLightningUpdate();
                // TaskLightChunk task = new TaskLightChunk(chunk, true);
                // workers.scheduleTask(task);
                waveFence.add(fence);
            }
            if (wave >= waveSize) {
                waveFence.traverse();
                waveFence.clear();
                while (true) {
                    if (workers.size() > 0) {
                        // endless tasks
                        try {
                            Thread.sleep(50L);
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else
                        break;
                }
                wave = 0;
                // Show progress
                done += waveSize;
                if (Math.floor(((double) done / (double) todo) * 100) > completion) {
                    completion = Math.floor(((double) done / (double) todo) * 100);
                    if (completion >= 100.0 || (System.currentTimeMillis() - lastPercentageShow > 5000)) {
                        verbose(completion + "% ... using " + Runtime.getRuntime().freeMemory() / 1024 / 1024 + "/" + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "Mb ");
                        lastPercentageShow = System.currentTimeMillis();
                    }
                }
                if (registeredCS_Holders.size() > targetChunksToKeepInRam) {
                    for (ChunkHolder holder : registeredCS_Holders) {
                        holder.unregisterUser(worldUser);
                        chunksAquired--;
                    }
                    for (Heightmap summary : registeredCS_Summaries) summary.unregisterUser(worldUser);
                    registeredCS_Summaries.clear();
                    registeredCS_Holders.clear();
                    csWorld.unloadUselessData().traverse();
                // verbose("Done.");
                }
            }
        }
    }
    waveFence.traverse();
    wave = 0;
    // Terminate
    for (ChunkHolder holder : registeredCS_Holders) {
        holder.unregisterUser(worldUser);
        chunksAquired--;
    }
    for (Heightmap summary : registeredCS_Summaries) summary.unregisterUser(worldUser);
    registeredCS_Summaries.clear();
    registeredCS_Holders.clear();
    csWorld.unloadUselessData().traverse();
/*csWorld.saveEverything();
		for (ChunkHolder holder : registeredCS_Holders)
			holder.unregisterUser(worldUser);

		csWorld.unloadUselessData().traverse();*/
}
Also used : Heightmap(io.xol.chunkstories.api.world.heightmap.Heightmap) WorldUser(io.xol.chunkstories.api.world.WorldUser) CompoundFence(io.xol.chunkstories.util.concurrency.CompoundFence) ChunkHolder(io.xol.chunkstories.api.world.chunk.ChunkHolder) WorldSize(io.xol.chunkstories.api.world.WorldInfo.WorldSize) CubicChunk(io.xol.chunkstories.world.chunk.CubicChunk) CompoundFence(io.xol.chunkstories.util.concurrency.CompoundFence) Fence(io.xol.chunkstories.api.util.concurrency.Fence) HashSet(java.util.HashSet)

Example 2 with CubicChunk

use of io.xol.chunkstories.world.chunk.CubicChunk in project chunkstories by Hugobros3.

the class TaskBakeChunk method task.

@Override
protected boolean task(TaskExecutor taskExecutor) {
    if (!(taskExecutor instanceof BakeChunkTaskExecutor))
        throw new UnexecutableTaskException(this, "This class requires to be executed by a BakeChunkTaskExecutor");
    this.cmd = ((BakeChunkTaskExecutor) taskExecutor).getBuffers();
    if (chunk == null) {
        throw new RuntimeException("Fuck off no");
    }
    Vector3dc camera = ((WorldClient) chunk.getWorld()).getWorldRenderer().getRenderingInterface().getCamera().getCameraPosition();
    // Check we aren't too far from the camera, and thus that our request hasn't been yet cancelled
    int vx = Math2.floor(camera.x() / 32);
    int vy = Math2.floor(camera.y() / 32);
    int vz = Math2.floor(camera.z() / 32);
    int dx = LoopingMathHelper.moduloDistance(chunk.getChunkX(), vx, chunk.getWorld().getSizeInChunks());
    int dz = LoopingMathHelper.moduloDistance(chunk.getChunkZ(), vz, chunk.getWorld().getSizeInChunks());
    int dy = Math.abs(chunk.getChunkY() - vy);
    int chunksViewDistance = (int) (world.getClient().getConfiguration().getIntOption("client.rendering.viewDistance") / 32);
    if (dx > chunksViewDistance || dz > chunksViewDistance || dy > 2) {
        // logger.info("unscheduled chunk mesh render task for it being too far to be rendered anyway");
        return true;
    }
    // Require the chunk and nearby ones to be already loaded in the world
    ChunkRenderable chunkWithinWorld = (ChunkRenderable) world.getChunk(chunk.getChunkX(), chunk.getChunkY(), chunk.getChunkZ());
    if (chunkWithinWorld != null) {
        // Require the chunks ARROUND it to be already loaded in the world
        int nearChunks = 0;
        if (world.isChunkLoaded(chunk.getChunkX() + 1, chunk.getChunkY(), chunk.getChunkZ()))
            nearChunks++;
        if (world.isChunkLoaded(chunk.getChunkX() - 1, chunk.getChunkY(), chunk.getChunkZ()))
            nearChunks++;
        if (world.isChunkLoaded(chunk.getChunkX(), chunk.getChunkY(), chunk.getChunkZ() + 1))
            nearChunks++;
        if (world.isChunkLoaded(chunk.getChunkX(), chunk.getChunkY(), chunk.getChunkZ() - 1))
            nearChunks++;
        if (world.isChunkLoaded(chunk.getChunkX(), chunk.getChunkY() + 1, chunk.getChunkZ()) || chunk.getChunkY() == world.getWorldInfo().getSize().heightInChunks - 1)
            nearChunks++;
        if (world.isChunkLoaded(chunk.getChunkX(), chunk.getChunkY() - 1, chunk.getChunkZ()) || chunk.getChunkY() == 0)
            nearChunks++;
        if (nearChunks != 6) {
            // We wait until that's the case
            return false;
        }
    } else {
        // We wait until the chunk is loaded in the world ( or destroyed, then the task is cancelled )
        return false;
    }
    // If the chunk has pending light updates, wait until THOSE are done
    if (chunk.lightBaker.pendingUpdates() > 0) {
        chunk.lightBaker.spawnUpdateTaskIfNeeded();
        return false;
    }
    int updatesToConsider = chunk.chunkRenderData.unbakedUpdates.get();
    // Don't waste time rendering void chunks m8
    if (chunk.isAirChunk())
        i = 32;
    int cx = chunk.getChunkX();
    int cy = chunk.getChunkY();
    int cz = chunk.getChunkZ();
    // Fill chunk caches ( saves much time avoiding slow-ass world->regions hashmap->chunk holder access for each vert )
    for (int relx = -1; relx <= 1; relx++) for (int rely = -1; rely <= 1; rely++) for (int relz = -1; relz <= 1; relz++) {
        CubicChunk chunk2 = (CubicChunk) world.getChunk(cx + relx, cy + rely, cz + relz);
        if (chunk2 != null)
            cmd.cache[((relx + 1) * 3 + (rely + 1)) * 3 + (relz + 1)] = chunk2.chunkVoxelData;
        else
            cmd.cache[((relx + 1) * 3 + (rely + 1)) * 3 + (relz + 1)] = null;
    }
    // Make sure we clear each sub-buffer type.
    for (int i = 0; i < ChunkMeshDataSubtypes.VertexLayout.values().length; i++) {
        for (int j = 0; j < ChunkMeshDataSubtypes.LodLevel.values().length; j++) {
            for (int k = 0; k < ChunkMeshDataSubtypes.ShadingType.values().length; k++) {
                cmd.byteBuffers[i][j][k].clear();
            }
        }
    }
    // Creates wrapper/interfaces for all the elements
    ChunkRenderer chunkRendererOutput = new ChunkRenderer() {

        @Override
        public VoxelBakerHighPoly getHighpolyBakerFor(LodLevel lodLevel, ShadingType renderPass) {
            return (VoxelBakerHighPoly) cmd.byteBuffersWrappers[VertexLayout.INTRICATE.ordinal()][lodLevel.ordinal()][renderPass.ordinal()];
        }

        @Override
        public VoxelBakerCubic getLowpolyBakerFor(LodLevel lodLevel, ShadingType renderPass) {
            return (VoxelBakerCubic) cmd.byteBuffersWrappers[VertexLayout.WHOLE_BLOCKS.ordinal()][lodLevel.ordinal()][renderPass.ordinal()];
        }
    };
    ChunkBakerRenderContext chunkRenderingContext = new ChunkBakerRenderContext(chunk, cx, cy, cz);
    bakedBlockId = -1;
    Map<Voxel, DynamicallyRenderedVoxelType> dynamicVoxels = new HashMap<>();
    BakeChunkScratchCell cell = new BakeChunkScratchCell(world);
    // Render the fucking thing!
    for (i = 0; i < 32; i++) {
        for (j = 0; j < 32; j++) {
            for (k = 0; k < 32; k++) {
                peek(i, k, j, cell);
                if (cell.voxel.isAir())
                    continue;
                // Fill near-blocks info
                // chunkRenderingContext.prepareVoxelLight(); // lol nope
                VoxelRenderer voxelRenderer = cell.getVoxelRenderer();
                if (voxelRenderer == null)
                    voxelRenderer = world.getContent().voxels().getDefaultVoxelRenderer();
                // Run the VoxelRenderer
                voxelRenderer.bakeInto(chunkRendererOutput, chunkRenderingContext, chunk, cell);
                // We handle voxels with a dynamic renderer here too - we just add them to a list !
                if (voxelRenderer instanceof VoxelDynamicRenderer) {
                    DynamicallyRenderedVoxelType drvt = dynamicVoxels.get(cell.voxel);
                    if (drvt == null) {
                        drvt = new DynamicallyRenderedVoxelType((VoxelDynamicRenderer) voxelRenderer, cell.voxel);
                        dynamicVoxels.put(cell.voxel, drvt);
                    }
                    drvt.indexes.add(i * 1024 + k * 32 + j);
                }
                bakedBlockId++;
            }
        }
    }
    // Parse output neatly
    int[][][] sizes = new int[ChunkMeshDataSubtypes.VertexLayout.values().length][ChunkMeshDataSubtypes.LodLevel.values().length][ChunkMeshDataSubtypes.ShadingType.values().length];
    ;
    int[][][] offsets = new int[ChunkMeshDataSubtypes.VertexLayout.values().length][ChunkMeshDataSubtypes.LodLevel.values().length][ChunkMeshDataSubtypes.ShadingType.values().length];
    ;
    int currentOffset = 0;
    // Compute total size to create final bytebuffer
    int sizeInBytes = 0;
    for (VertexLayout vertexLayout : VertexLayout.values()) for (LodLevel lodLevel : LodLevel.values()) for (ShadingType renderPass : ShadingType.values()) {
        int vertexLayoutIndex = vertexLayout.ordinal();
        int lodLevelIndex = lodLevel.ordinal();
        int renderPassIndex = renderPass.ordinal();
        final ByteBuffer relevantByteBuffer = cmd.byteBuffers[vertexLayoutIndex][lodLevelIndex][renderPassIndex];
        // / vertexLayout.bytesPerVertex;
        sizeInBytes += relevantByteBuffer.position();
    }
    ByteBuffer finalData = MemoryUtil.memAlloc(sizeInBytes);
    MemFreeByteBuffer wrappedBuffer = new MemFreeByteBuffer(finalData);
    // For EACH section, make offset and shite
    for (VertexLayout vertexLayout : VertexLayout.values()) for (LodLevel lodLevel : LodLevel.values()) for (ShadingType renderPass : ShadingType.values()) {
        int vertexLayoutIndex = vertexLayout.ordinal();
        int lodLevelIndex = lodLevel.ordinal();
        int renderPassIndex = renderPass.ordinal();
        // Else it gets really long for no reason
        final ByteBuffer relevantByteBuffer = cmd.byteBuffers[vertexLayoutIndex][lodLevelIndex][renderPassIndex];
        offsets[vertexLayoutIndex][lodLevelIndex][renderPassIndex] = currentOffset;
        sizes[vertexLayoutIndex][lodLevelIndex][renderPassIndex] = relevantByteBuffer.position() / vertexLayout.bytesPerVertex;
        // Move the offset accordingly
        currentOffset += relevantByteBuffer.position();
        // Limit the temporary byte buffer and fill the main buffer with it
        relevantByteBuffer.limit(relevantByteBuffer.position());
        relevantByteBuffer.position(0);
        finalData.put(relevantByteBuffer);
    }
    finalData.flip();
    ChunkMeshDataSections newRenderData = new ChunkMeshDataSections(wrappedBuffer, sizes, offsets);
    DynamicallyRenderedVoxelType[] bakedDrvt = new DynamicallyRenderedVoxelType[dynamicVoxels.size()];
    Iterator<DynamicallyRenderedVoxelType> i = dynamicVoxels.values().iterator();
    for (int j = 0; j < dynamicVoxels.size(); j++) {
        if (i.hasNext())
            bakedDrvt[j] = i.next();
        else {
            logger.error("while baking dynamicVoxelTypes array the iterator returned less than dynamicVoxels.size() elements");
            logger.error("cancelling");
            bakedDrvt = null;
            break;
        }
    }
    newRenderData.dynamicVoxelTypes = bakedDrvt;
    chunk.getChunkRenderData().setData(newRenderData);
    chunk.chunkRenderData.unbakedUpdates.addAndGet(-updatesToConsider);
    return true;
}
Also used : ChunkRenderable(io.xol.chunkstories.api.rendering.world.chunk.ChunkRenderable) HashMap(java.util.HashMap) VoxelBakerCubic(io.xol.chunkstories.api.rendering.voxel.VoxelBakerCubic) MemFreeByteBuffer(io.xol.chunkstories.client.util.MemFreeByteBuffer) VoxelBakerHighPoly(io.xol.chunkstories.api.rendering.voxel.VoxelBakerHighPoly) CubicChunk(io.xol.chunkstories.world.chunk.CubicChunk) LodLevel(io.xol.chunkstories.api.rendering.world.chunk.ChunkMeshDataSubtypes.LodLevel) Voxel(io.xol.chunkstories.api.voxel.Voxel) VoxelDynamicRenderer(io.xol.chunkstories.api.rendering.voxel.VoxelDynamicRenderer) UnexecutableTaskException(io.xol.chunkstories.api.exceptions.tasks.UnexecutableTaskException) ByteBuffer(java.nio.ByteBuffer) MemFreeByteBuffer(io.xol.chunkstories.client.util.MemFreeByteBuffer) VertexLayout(io.xol.chunkstories.api.rendering.world.chunk.ChunkMeshDataSubtypes.VertexLayout) Vector3dc(org.joml.Vector3dc) ChunkRenderer(io.xol.chunkstories.api.rendering.world.chunk.ChunkRenderer) ShadingType(io.xol.chunkstories.api.rendering.world.chunk.ChunkMeshDataSubtypes.ShadingType) DynamicallyRenderedVoxelType(io.xol.chunkstories.renderer.chunks.ChunkMeshDataSections.DynamicallyRenderedVoxelType) VoxelRenderer(io.xol.chunkstories.api.rendering.voxel.VoxelRenderer)

Aggregations

CubicChunk (io.xol.chunkstories.world.chunk.CubicChunk)2 UnexecutableTaskException (io.xol.chunkstories.api.exceptions.tasks.UnexecutableTaskException)1 VoxelBakerCubic (io.xol.chunkstories.api.rendering.voxel.VoxelBakerCubic)1 VoxelBakerHighPoly (io.xol.chunkstories.api.rendering.voxel.VoxelBakerHighPoly)1 VoxelDynamicRenderer (io.xol.chunkstories.api.rendering.voxel.VoxelDynamicRenderer)1 VoxelRenderer (io.xol.chunkstories.api.rendering.voxel.VoxelRenderer)1 LodLevel (io.xol.chunkstories.api.rendering.world.chunk.ChunkMeshDataSubtypes.LodLevel)1 ShadingType (io.xol.chunkstories.api.rendering.world.chunk.ChunkMeshDataSubtypes.ShadingType)1 VertexLayout (io.xol.chunkstories.api.rendering.world.chunk.ChunkMeshDataSubtypes.VertexLayout)1 ChunkRenderable (io.xol.chunkstories.api.rendering.world.chunk.ChunkRenderable)1 ChunkRenderer (io.xol.chunkstories.api.rendering.world.chunk.ChunkRenderer)1 Fence (io.xol.chunkstories.api.util.concurrency.Fence)1 Voxel (io.xol.chunkstories.api.voxel.Voxel)1 WorldSize (io.xol.chunkstories.api.world.WorldInfo.WorldSize)1 WorldUser (io.xol.chunkstories.api.world.WorldUser)1 ChunkHolder (io.xol.chunkstories.api.world.chunk.ChunkHolder)1 Heightmap (io.xol.chunkstories.api.world.heightmap.Heightmap)1 MemFreeByteBuffer (io.xol.chunkstories.client.util.MemFreeByteBuffer)1 DynamicallyRenderedVoxelType (io.xol.chunkstories.renderer.chunks.ChunkMeshDataSections.DynamicallyRenderedVoxelType)1 CompoundFence (io.xol.chunkstories.util.concurrency.CompoundFence)1