package client.renderer;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Collection;
import java.util.EnumSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.function.Predicate;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL13;
import org.lwjgl.opengl.GL15;

import client.Client;
import client.renderer.blockmodel.BakedModel;
import client.renderer.blockmodel.BakedQuad;
import client.renderer.blockmodel.IBakedModel;
import client.renderer.blockmodel.ModelManager;
import client.renderer.chunk.BlockLayer;
import client.renderer.chunk.ChunkRenderDispatcher;
import client.renderer.chunk.CompiledChunk;
import client.renderer.chunk.RenderChunk;
import client.renderer.chunk.VisGraph;
import client.renderer.entity.RenderManager;
import client.renderer.texture.DynamicTexture;
import client.renderer.texture.Sprite;
import client.renderer.texture.TextureManager;
import client.renderer.texture.TextureMap;
import client.renderer.tileentity.SpecialRenderer;
import client.world.ChunkClient;
import common.block.Block;
import common.block.Material;
import common.block.artificial.BlockSlab;
import common.block.liquid.BlockDynamicLiquid;
import common.block.liquid.BlockLiquid;
import common.block.liquid.BlockStaticLiquid;
import common.collect.Lists;
import common.collect.Maps;
import common.collect.Sets;
import common.dimension.DimType;
import common.effect.Effect;
import common.entity.Entity;
import common.entity.npc.EntityCameraHolder;
import common.entity.npc.EntityNPC;
import common.entity.types.EntityAnimal;
import common.entity.types.EntityLiving;
import common.init.BlockRegistry;
import common.init.Blocks;
import common.init.Items;
import common.init.SoundEvent;
import common.rng.Random;
import common.sound.PositionedSound;
import common.sound.Sound;
import common.tileentity.TileEntity;
import common.util.BlockPos;
import common.util.BoundingBox;
import common.util.ExtMath;
import common.util.Facing;
import common.util.HitPosition;
import common.util.InheritanceMultiMap;
import common.util.Pair;
import common.util.HitPosition.ObjectType;
import common.util.ParticleType;
import common.util.Vec3;
import common.util.Vec3i;
import common.util.Vector3f;
import common.world.IBlockAccess;
import common.world.IWorldAccess;
import common.world.State;
import common.world.World;

public class Renderer {
	private class RenderInfo {
		final RenderChunk chunk;
		final Facing facing;
		final Set<Facing> faces;
		final int counter;

		private RenderInfo(RenderChunk chunk, Facing dir, int counter) {
			this.faces = EnumSet.<Facing>noneOf(Facing.class);
			this.chunk = chunk;
			this.facing = dir;
			this.counter = counter;
		}
	}
	
	private static class DestroyProgress {
		private final int id;
		private final BlockPos pos;

		private int damage;
		private int time;

		public DestroyProgress(int id, BlockPos pos) {
			this.id = id;
			this.pos = pos;
		}

		public BlockPos getPosition() {
			return this.pos;
		}

		public void setDamage(int damage) {
			this.damage = damage > 10 ? 10 : damage;
		}

		public int getDamage() {
			return this.damage;
		}

		public void setTime(int time) {
			this.time = time;
		}

		public int getTime() {
			return this.time;
		}
	}
	
	private static final String TEX_MOLTEN = "textures/world/molten.png";
	private static final String TEX_RAIN = "textures/world/rain.png";
	private static final String TEX_HAIL = "textures/world/hail.png";
    private static final String TEX_SNOW = "textures/world/snow.png";
    private static final String MOON_TEX = "textures/world/moon_phases.png";
    private static final String PLANET_TEX = "textures/world/planet_phases.png";
    private static final String SUN_TEX = "textures/world/sun.png";
    private static final String EXTERMINATED_TEX = "textures/world/destroyed.png";
    private static final String TEX_LIGHTMAP = "dynamic/lightmap";
    private static final float FOG_DENSITY = 0.05f;
    private static final float FOG_DISTANCE = 0.4f;
    private static final float SQRT_2 = ExtMath.sqrtf(2.0F);
	private static final float[] SUN_COLOR = new float[4];
    
    private final Client gm;
    private final Random rng = new Random();
    private final Random seededRng = new Random();
    private final ItemRenderer itemRenderer;
    private final DynamicTexture lightmapTexture;
    private final int[] lightmapColors;
    private final TextureManager renderEngine;
    private final RenderManager renderManager;
    private final ModelManager manager;
    private final Set<TileEntity> setTileEntities = Sets.<TileEntity>newHashSet();
    private final Map<Integer, DestroyProgress> damagedBlocks = Maps.<Integer, DestroyProgress>newHashMap();
    private final Map<BlockPos, Sound> mapSoundPositions = Maps.<BlockPos, Sound>newHashMap();
	private final Map<BlockLiquid, Sprite[]> fluids = Maps.newHashMap();
    private final Sprite[] destroyBlockIcons = new Sprite[10];
    
    private float farPlaneDistance;
    private int rendererUpdateCount;
    private Entity pointedEntity;
    private float thirdPersonDistance = 4.0F;
    private float thirdPersonDistanceTemp = 4.0F;
    private float fovModifierHand;
    private float fovModifierHandPrev;
    private boolean lightmapUpdateNeeded;
    private float torchFlickerX;
    private float torchFlickerDX;
    private int rainSoundCounter;
    private float[] rainXCoords = new float[32*32];
    private float[] rainZCoords = new float[32*32];
    private FloatBuffer fogColorBuffer = ByteBuffer.allocateDirect(16 << 2).order(ByteOrder.nativeOrder()).asFloatBuffer();
    private float fogColorRed;
    private float fogColorGreen;
    private float fogColorBlue;
    private float lastFogMult;
    private float fogMult;
    private double cameraYaw;
    private double cameraPitch;
    private int frameCount;
	private int lastLightning;
	private Vec3 lightColor = new Vec3(0xffffff);
    private World theWorld;
    private Set<RenderChunk> chunksToUpdate = new LinkedHashSet<RenderChunk>();
    private List<RenderInfo> renderInfos = new ArrayList<RenderInfo>(69696);
    private ViewFrustum viewFrustum;
    private VertexFormat vertexBufferFormat = new VertexFormat().addElement(new VertexFormatElement(0, VertexFormatElement.EnumType.FLOAT, VertexFormatElement.EnumUsage.POSITION, 3));
    private VertexBuffer starVBO;
    private VertexBuffer dstarVBO;
    private VertexBuffer skyVBO;
    private VertexBuffer sky2VBO;
    private int cloudTickCounter;
    private double frustumUpdatePosX = Double.MIN_VALUE;
    private double frustumUpdatePosY = Double.MIN_VALUE;
    private double frustumUpdatePosZ = Double.MIN_VALUE;
    private int frustumUpdatePosChunkX = Integer.MIN_VALUE;
    private int frustumUpdatePosChunkY = Integer.MIN_VALUE;
    private int frustumUpdatePosChunkZ = Integer.MIN_VALUE;
    private double lastViewEntityX = Double.MIN_VALUE;
    private double lastViewEntityY = Double.MIN_VALUE;
    private double lastViewEntityZ = Double.MIN_VALUE;
    private double lastViewEntityPitch = Double.MIN_VALUE;
    private double lastViewEntityYaw = Double.MIN_VALUE;
    private final ChunkRenderDispatcher renderDispatcher = new ChunkRenderDispatcher();
    private double viewEntityX;
    private double viewEntityY;
    private double viewEntityZ;
    private List<RenderChunk> renderChunks = new ArrayList<RenderChunk>(17424);
    private boolean initialized;
    private int renderDistanceChunks = -1;
    private int renderEntitiesStartupCounter = 2;
    private int countEntitiesTotal;
    private int countEntitiesRendered;
    private int countEntitiesHidden;
    private double prevRenderSortX;
    private double prevRenderSortY;
    private double prevRenderSortZ;
    private boolean displayListEntitiesDirty = true;

    public Renderer(Client gm, ModelManager manager)
    {
        this.gm = gm;
        this.manager = manager;
        this.itemRenderer = gm.getItemRenderer();
        this.renderManager = gm.getRenderManager();
        this.renderEngine = gm.getTextureManager();
        this.lightmapTexture = new DynamicTexture(16, 16);
        gm.getTextureManager().loadTexture(TEX_LIGHTMAP, this.lightmapTexture);
        this.lightmapColors = this.lightmapTexture.getData();

        for (int x = 0; x < 32; ++x)
        {
            for (int z = 0; z < 32; ++z)
            {
                float dz = (float)(z - 16);
                float dx = (float)(x - 16);
                float dist = ExtMath.sqrtf(dz * dz + dx * dx);
                this.rainXCoords[x << 5 | z] = -dx / dist;
                this.rainZCoords[x << 5 | z] = dz / dist;
            }
        }
        
        GlState.bindTexture(0);
        this.generateStars();
        this.generateDeepStars();
        this.generateSky();
        this.generateSky2();
    }

    public ModelManager getModelManager()
    {
        return this.manager;
    }

    public void update()
    {
        this.updateFovModifierHand();
        this.updateTorchFlicker();
        this.lastFogMult = this.fogMult;
        this.thirdPersonDistanceTemp = this.thirdPersonDistance;

        if (this.gm.getRenderViewEntity() == null)
        {
            this.gm.setRenderViewEntity(this.gm.player);
        }

        float light = this.gm.world.getLightBrightness(new BlockPos(this.gm.getRenderViewEntity()));
        float dist = (float)this.gm.renderDistance / 32.0F;
        float shift = light * (1.0F - dist) + dist;
        this.fogMult += (shift - this.fogMult) * 0.1F;
        ++this.rendererUpdateCount;
        this.itemRenderer.update();
        this.addRainParticles();
		if(this.lastLightning > 0)
			this.lastLightning -= 1;
        ++this.cloudTickCounter;
        if (this.cloudTickCounter % 20 == 0)
            this.cleanupDamagedBlocks(this.damagedBlocks.values().iterator());
    }

    public void getMouseOver(float partialTicks)
    {
        Entity entity = this.gm.getRenderViewEntity();

        if (entity != null)
        {
            if (this.gm.world != null)
            {
                this.gm.setPointedEntity(null);
                double max = this.gm.player != null ? this.gm.player.getReachDistance() : 5.0;
                this.gm.pointed = entity.rayTrace(max, partialTicks, false);
                double dist = max;
                Vec3 eye = entity.getPositionEyes(partialTicks);
//                boolean far = false;
                int i = 3;

//                if (this.gm.controller.extendedReach())
//                {
                max += 1.0D;
                dist += 1.0D;
//                }
//                else
//                {
//                    if (max > 3.0D)
//                    {
//                        far = true;
//                    }
//                }

                if (this.gm.pointed != null)
                {
                    dist = this.gm.pointed.vec.distanceTo(eye);
                }

                Vec3 look = entity.getLook(partialTicks);
                Vec3 eyelook = eye.addVector(look.xCoord * max, look.yCoord * max, look.zCoord * max);
                this.pointedEntity = null;
                Vec3 hit = null;
                float exp = 1.0F;
                List<Entity> list = this.gm.world.getEntitiesInAABBexcluding(entity, entity.getEntityBoundingBox().addCoord(look.xCoord * max, look.yCoord * max, look.zCoord * max).expand((double)exp, (double)exp, (double)exp), new Predicate<Entity>()
                {
                    public boolean test(Entity p_apply_1_)
                    {
                        return p_apply_1_.canBeCollidedWith();
                    }
                });
                double edist = dist;

                for (int j = 0; j < list.size(); ++j)
                {
                    Entity entity1 = (Entity)list.get(j);
                    float f1 = entity1.getCollisionBorderSize();
                    BoundingBox axisalignedbb = entity1.getEntityBoundingBox().expand((double)f1, (double)f1, (double)f1);
                    HitPosition objpos = axisalignedbb.calculateIntercept(eye, eyelook);

                    if (axisalignedbb.isVecInside(eye))
                    {
                        if (edist >= 0.0D)
                        {
                            this.pointedEntity = entity1;
                            hit = objpos == null ? eye : objpos.vec;
                            edist = 0.0D;
                        }
                    }
                    else if (objpos != null)
                    {
                        double eyehit = eye.distanceTo(objpos.vec);

                        if (eyehit < edist || edist == 0.0D)
                        {
                            if (entity1 == entity.vehicle)
                            {
                                if (edist == 0.0D)
                                {
                                    this.pointedEntity = entity1;
                                    hit = objpos.vec;
                                }
                            }
                            else
                            {
                                this.pointedEntity = entity1;
                                hit = objpos.vec;
                                edist = eyehit;
                            }
                        }
                    }
                }

//                if (this.pointedEntity != null && far && eye.distanceTo(hit) > 3.0D)
//                {
//                    this.pointedEntity = null;
//                    this.gm.pointed = new MovingObjectPosition(MovingObjectPosition.MovingObjectType.MISS, hit, (EnumFacing)null, new BlockPos(hit));
//                }

                if (this.pointedEntity != null && (edist < dist || this.gm.pointed == null))
                {
                    this.gm.pointed = new HitPosition(this.pointedEntity, hit);

                    if (this.pointedEntity instanceof EntityLiving) // || this.pointedEntity instanceof EntityFrame)
                    {
                        this.gm.setPointedEntity(this.pointedEntity);
                    }
                }

            	this.gm.pointedLiquid = null;
                if(this.gm.pointed == null || this.gm.pointed.type != ObjectType.ENTITY) {
                    HitPosition liquid = entity.rayTrace(max, partialTicks, true);
                    if(liquid != null && liquid.type == ObjectType.BLOCK && liquid.block != null && this.gm.world.getState(liquid.block).getBlock().getMaterial().isLiquid())
                    	this.gm.pointedLiquid = liquid.block;
                }
            }
        }
    }

    private void updateFovModifierHand()
    {
        float f = 1.0F;

        if (this.gm.getRenderViewEntity() != null && this.gm.getRenderViewEntity().isPlayer())
        {
            EntityNPC player = (EntityNPC)this.gm.getRenderViewEntity();
            f = getFovModifier(player);
        }

        this.fovModifierHandPrev = this.fovModifierHand;
        this.fovModifierHand += (f - this.fovModifierHand) * 0.5F;

        if (this.fovModifierHand > 1.5F)
        {
            this.fovModifierHand = 1.5F;
        }

        if (this.fovModifierHand < 0.1F)
        {
            this.fovModifierHand = 0.1F;
        }
    }
    
    private static float getFovModifier(EntityNPC player)
    {
        float f = 1.0F;

        if (player.isUsingItem() && player.getItemInUse().getItem() == Items.bow)
        {
            int i = player.getItemInUseDuration();
            float f1 = (float)i / 20.0F;

            if (f1 > 1.0F)
            {
                f1 = 1.0F;
            }
            else
            {
                f1 = f1 * f1;
            }

            f *= 1.0F - f1 * 0.15F;
        }

        return f;
    }
	
    private static int hsvToRGB(float hue, float saturation, float value)
    {
        int i = (int)(hue * 6.0F) % 6;
        float f = hue * 6.0F - (float)i;
        float f1 = value * (1.0F - saturation);
        float f2 = value * (1.0F - f * saturation);
        float f3 = value * (1.0F - (1.0F - f) * saturation);
        float f4;
        float f5;
        float f6;

        switch (i)
        {
            case 0:
                f4 = value;
                f5 = f3;
                f6 = f1;
                break;

            case 1:
                f4 = f2;
                f5 = value;
                f6 = f1;
                break;

            case 2:
                f4 = f1;
                f5 = value;
                f6 = f3;
                break;

            case 3:
                f4 = f1;
                f5 = f2;
                f6 = value;
                break;

            case 4:
                f4 = f3;
                f5 = f1;
                f6 = value;
                break;

            case 5:
                f4 = value;
                f5 = f1;
                f6 = f2;
                break;

            default:
                throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + hue + ", " + saturation + ", " + value);
        }

        int j = ExtMath.clampi((int)(f4 * 255.0F), 0, 255);
        int k = ExtMath.clampi((int)(f5 * 255.0F), 0, 255);
        int l = ExtMath.clampi((int)(f6 * 255.0F), 0, 255);
        return j << 16 | k << 8 | l;
    }

    private float getFOVModifier(float partialTicks, boolean useFOVSetting)
    {
//        if (this.debugView)
//        {
//            return 90.0F;
//        }
//        else
//        {
        Entity entity = this.gm.getRenderViewEntity();
        float f = 70.0F;

        if (useFOVSetting)
        {
            f = this.gm.fov;
            if(this.gm.zooming) {
            	f /= this.gm.zoomLevel;
            }
            f = f * (this.fovModifierHandPrev + (this.fovModifierHand - this.fovModifierHandPrev) * partialTicks);
        }

        if (entity instanceof EntityLiving && ((EntityLiving)entity).getHealth() <= 0)
        {
            float f1 = (float)((EntityLiving)entity).deathTime + partialTicks;
            f /= (1.0F - 500.0F / (f1 + 500.0F)) * 2.0F + 1.0F;
        }

//            Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.gm.theWorld, entity, partialTicks);
//
//            if (block.getMaterial().isColdLiquid())
//            {
//                f = f * 60.0F / 70.0F;
//            }

        return f;
//        }
    }

    private void hurtCameraEffect(float partialTicks)
    {
        if (this.gm.getRenderViewEntity() instanceof EntityLiving)
        {
            EntityLiving entitylivingbase = (EntityLiving)this.gm.getRenderViewEntity();
            float f = (float)entitylivingbase.hurtTime - partialTicks;

            if (entitylivingbase.getHealth() <= 0)
            {
                float f1 = (float)entitylivingbase.deathTime + partialTicks;
                GL11.glRotatef(40.0F - 8000.0F / (f1 + 200.0F), 0.0F, 0.0F, 1.0F);
            }

            if (f < 0.0F || entitylivingbase.hasEffect(Effect.STABILITY))
            {
                return;
            }

            f = f / (float)entitylivingbase.maxHurtTime;
            f = ExtMath.sin(f * f * f * f * (float)Math.PI);
            float f2 = entitylivingbase.attackedYaw;
            GL11.glRotatef(-f2, 0.0F, 1.0F, 0.0F);
            GL11.glRotatef(-f * 14.0F, 0.0F, 0.0F, 1.0F);
            GL11.glRotatef(f2, 0.0F, 1.0F, 0.0F);
        }
    }

    private void setupViewBobbing(float partialTicks)
    {
        if (this.gm.getRenderViewEntity() != null && this.gm.getRenderViewEntity().isPlayer())
        {
            EntityNPC entityplayer = (EntityNPC)this.gm.getRenderViewEntity();
            float f = entityplayer.walkDistMod - entityplayer.prevWalkDistMod;
            float f1 = -(entityplayer.walkDistMod + f * partialTicks);
            float f2 = entityplayer.prevCameraYaw + (entityplayer.cameraYaw - entityplayer.prevCameraYaw) * partialTicks;
            float f3 = entityplayer.prevCamPitch + (entityplayer.camPitch - entityplayer.prevCamPitch) * partialTicks;
            GL11.glTranslatef(ExtMath.sin(f1 * (float)Math.PI) * f2 * 0.5F, -Math.abs(ExtMath.cos(f1 * (float)Math.PI) * f2), 0.0F);
            GL11.glRotatef(ExtMath.sin(f1 * (float)Math.PI) * f2 * 3.0F, 0.0F, 0.0F, 1.0F);
            GL11.glRotatef(Math.abs(ExtMath.cos(f1 * (float)Math.PI - 0.2F) * f2) * 5.0F, 1.0F, 0.0F, 0.0F);
            GL11.glRotatef(f3, 1.0F, 0.0F, 0.0F);
        }
    }

    private void orientCamera(float partialTicks)
    {
        Entity entity = this.gm.getRenderViewEntity();
        float f = entity.getEyeHeight();
        double d0 = entity.prevX + (entity.posX - entity.prevX) * (double)partialTicks;
        double d1 = entity.prevY + (entity.posY - entity.prevY) * (double)partialTicks + (double)f;
        double d2 = entity.prevZ + (entity.posZ - entity.prevZ) * (double)partialTicks;

//        if (entity instanceof EntityLivingBase && ((EntityLivingBase)entity).isPlayerSleeping())
//        {
//            f = (float)((double)f + 1.0D);
//            SKC.glTranslatef(0.0F, 0.3F, 0.0F);
//
//            if (!this.gm.debugCamEnable)
//            {
//                BlockPos blockpos = new BlockPos(entity);
//                IBlockState iblockstate = this.gm.theWorld.getBlockState(blockpos);
//                Block block = iblockstate.getBlock();
//
//                if (block instanceof BlockBed)
//                {
//                    int j = ((EnumFacing)iblockstate.getValue(BlockBed.FACING)).getHorizontalIndex();
//                    SKC.glRotatef((float)(j * 90), 0.0F, 1.0F, 0.0F);
//                }
//
//                SKC.glRotatef(entity.prevYaw + (entity.rotYaw - entity.prevYaw) * partialTicks + 180.0F, 0.0F, -1.0F, 0.0F);
//                SKC.glRotatef(entity.prevPitch + (entity.rotPitch - entity.prevPitch) * partialTicks, -1.0F, 0.0F, 0.0F);
//            }
//        }
//        else
        if (this.gm.thirdPersonView > 0)
        {
            double d3 = (double)(this.thirdPersonDistanceTemp + (this.thirdPersonDistance - this.thirdPersonDistanceTemp) * partialTicks);

            if (this.gm.debugCamEnable)
            {
                GL11.glTranslatef(0.0F, 0.0F, (float)(-d3));
            }
            else
            {
                float f1 = entity.rotYaw;
                float f2 = entity.rotPitch;

                if (this.gm.thirdPersonView == 2)
                {
                    f2 += 180.0F;
                }

                double d4 = (double)(-ExtMath.sin(f1 / 180.0F * (float)Math.PI) * ExtMath.cos(f2 / 180.0F * (float)Math.PI)) * d3;
                double d5 = (double)(ExtMath.cos(f1 / 180.0F * (float)Math.PI) * ExtMath.cos(f2 / 180.0F * (float)Math.PI)) * d3;
                double d6 = (double)(-ExtMath.sin(f2 / 180.0F * (float)Math.PI)) * d3;

                for (int i = 0; i < 8; ++i)
                {
                    float f3 = (float)((i & 1) * 2 - 1);
                    float f4 = (float)((i >> 1 & 1) * 2 - 1);
                    float f5 = (float)((i >> 2 & 1) * 2 - 1);
                    f3 = f3 * 0.1F;
                    f4 = f4 * 0.1F;
                    f5 = f5 * 0.1F;
                    HitPosition movingobjectposition = this.gm.world.rayTraceBlocks(new Vec3(d0 + (double)f3, d1 + (double)f4, d2 + (double)f5), new Vec3(d0 - d4 + (double)f3 + (double)f5, d1 - d6 + (double)f4, d2 - d5 + (double)f5));

                    if (movingobjectposition != null)
                    {
                        double d7 = movingobjectposition.vec.distanceTo(new Vec3(d0, d1, d2));

                        if (d7 < d3)
                        {
                            d3 = d7;
                        }
                    }
                }

                if (this.gm.thirdPersonView == 2)
                {
                    GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
                }

                GL11.glRotatef(entity.rotPitch - f2, 1.0F, 0.0F, 0.0F);
                GL11.glRotatef(entity.rotYaw - f1, 0.0F, 1.0F, 0.0F);
                GL11.glTranslatef(0.0F, 0.0F, (float)(-d3));
                GL11.glRotatef(f1 - entity.rotYaw, 0.0F, 1.0F, 0.0F);
                GL11.glRotatef(f2 - entity.rotPitch, 1.0F, 0.0F, 0.0F);
            }
        }
        else
        {
            GL11.glTranslatef(0.0F, 0.0F, -0.1F);
        }

        if (!this.gm.debugCamEnable || this.gm.thirdPersonView == 0)
        {
        	this.rotateCamera(entity, partialTicks, false);
        }

        GL11.glTranslatef(0.0F, -f, 0.0F);
    }

	public void rotateCamera(Entity entity, float partialTicks, boolean invert) {
		if(invert)
			GL11.glRotatef(360.0f - (entity.prevPitch + (entity.rotPitch - entity.prevPitch) * partialTicks), 1.0F, 0.0F, 0.0F);
		else
			GL11.glRotatef(entity.prevPitch + (entity.rotPitch - entity.prevPitch) * partialTicks, 1.0F, 0.0F, 0.0F);

		if(entity instanceof EntityAnimal) {
			EntityAnimal entityanimal = (EntityAnimal)entity;
			GL11.glRotatef(entityanimal.prevHeadYaw + (entityanimal.headYaw - entityanimal.prevHeadYaw) * partialTicks + 180.0F, 0.0F, 1.0F, 0.0F);
		}
		else {
			GL11.glRotatef(entity.prevYaw + (entity.rotYaw - entity.prevYaw) * partialTicks + 180.0F, 0.0F, 1.0F, 0.0F);
		}
	}

    private void setupCameraTransform(float partialTicks)
    {
        this.farPlaneDistance = (float)(this.gm.renderDistance * 16);
        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        float f = 0.07F;

//        if (this.cameraZoom != 1.0D)
//        {
//            SKC.glTranslatef((float)this.cameraYaw, (float)(-this.cameraPitch), 0.0F);
//            SKC.glScaled(this.cameraZoom, this.cameraZoom, 1.0D);
//        }

        Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fbRawX / (float)this.gm.fbRawY, 0.05F, this.farPlaneDistance * SQRT_2);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glLoadIdentity();

        this.hurtCameraEffect(partialTicks);

//        if (this.gm.viewBobbing)
//        {
        this.setupViewBobbing(partialTicks);
//        }

//        float f1 = this.gm.thePlayer.prevNausea + (this.gm.thePlayer.nausea - this.gm.thePlayer.prevNausea) * partialTicks;
//
//        if (f1 > 0.0F)
//        {
//            int i = 7;
//
////            if (this.gm.thePlayer.hasEffect(Potion.confusion))
////            {
////                i = 7;
////            }
//
//            float f2 = 5.0F / (f1 * f1 + 5.0F) - f1 * 0.04F;
//            f2 = f2 * f2;
//            SKC.glRotatef(((float)this.rendererUpdateCount + partialTicks) * (float)i, 0.0F, 1.0F, 1.0F);
//            SKC.glScalef(1.0F / f2, 1.0F, 1.0F);
//            SKC.glRotatef(-((float)this.rendererUpdateCount + partialTicks) * (float)i, 0.0F, 1.0F, 1.0F);
//        }

        this.orientCamera(partialTicks);

//        if (this.debugView)
//        {
//            switch (this.debugViewDirection)
//            {
//                case 0:
//				SKC.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);
//                    break;
//
//                case 1:
//				SKC.glRotatef(180.0F, 0.0F, 1.0F, 0.0F);
//                    break;
//
//                case 2:
//				SKC.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
//                    break;
//
//                case 3:
//				SKC.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
//                    break;
//
//                case 4:
//				SKC.glRotatef(-90.0F, 1.0F, 0.0F, 0.0F);
//            }
//        }
    }

    private void renderHand(float partialTicks)
    {
//        if (!this.debugView)
//        {
        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        float f = 0.07F;

        Project.gluPerspective(this.getFOVModifier(partialTicks, false), (float)this.gm.fbRawX / (float)this.gm.fbRawY, 0.05F, this.farPlaneDistance * 2.0F);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glLoadIdentity();

        GL11.glPushMatrix();
        this.hurtCameraEffect(partialTicks);

//            if (this.gm.viewBobbing)
//            {
        this.setupViewBobbing(partialTicks);
//            }

//            boolean flag = this.gm.getRenderViewEntity() instanceof EntityLivingBase && ((EntityLivingBase)this.gm.getRenderViewEntity()).isPlayerSleeping();

        if (this.gm.thirdPersonView == 0 && !this.gm.showPlayerFirstPerson) // && /* !flag && */ !this.gm.hideGUI) // && !this.gm.controller.isSpectator())
        {
            this.enableLightmap();
            this.itemRenderer.renderItemInFirstPerson(partialTicks);
            this.disableLightmap();
        }

        GL11.glPopMatrix();

        if (this.gm.thirdPersonView == 0) // && !flag)
        {
            this.itemRenderer.renderOverlays(partialTicks);
            this.hurtCameraEffect(partialTicks);
        }

//            if (this.gm.viewBobbing)
//            {
        this.setupViewBobbing(partialTicks);
//            }
//        }
    }

    private void disableLightmap()
    {
        GlState.setActiveTexture(GL13.GL_TEXTURE1);
        GlState.disableTexture2D();
        GlState.setActiveTexture(GL13.GL_TEXTURE0);
    }

    private void enableLightmap()
    {
        GlState.setActiveTexture(GL13.GL_TEXTURE1);
        GL11.glMatrixMode(GL11.GL_TEXTURE);
        GL11.glLoadIdentity();
        float f = 0.00390625F;
        GL11.glScalef(f, f, f);
        GL11.glTranslatef(8.0F, 8.0F, 8.0F);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        this.gm.getTextureManager().bindTexture(TEX_LIGHTMAP);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP);
        GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP);
        GlState.color(1.0F, 1.0F, 1.0F, 1.0F);
        GlState.enableTexture2D();
        GlState.setActiveTexture(GL13.GL_TEXTURE0);
    }

    private void updateTorchFlicker()
    {
        this.torchFlickerDX = (float)((double)this.torchFlickerDX + (Math.random() - Math.random()) * Math.random() * Math.random());
        this.torchFlickerDX = (float)((double)this.torchFlickerDX * 0.9D);
        this.torchFlickerX += (this.torchFlickerDX - this.torchFlickerX) * 1.0F;
        this.lightmapUpdateNeeded = true;
    }
    
    public void resetLightning() {
    	this.lastLightning = 0;
    	this.lightColor = new Vec3(0xffffff);
    }

	public void setLastLightning(int last, int color) {
		this.lastLightning = last;
		this.lightColor = new Vec3(color);
	}

	public float getSunBrightness(float partial) {
		float f = this.gm.world.getDayPhase(partial);
		float f1 = 1.0F - (ExtMath.cos(f) * 2.0F + 0.2F);
		f1 = ExtMath.clampf(f1, 0.0F, 1.0F);
		f1 = 1.0F - f1;
		f1 = (float)((double)f1 * (1.0D - (double)(this.gm.world.getRainStrength() * 5.0F) / 16.0D));
		f1 = (float)((double)f1 * (1.0D - (double)(this.gm.world.getDarkness() * 5.0F) / 16.0D));
		return Math.max(f1 * 0.8F + 0.2F, this.getSpaceFactor());
	}

	private Vec3 getSkyColor(Entity entity, float partial) {
		BlockPos pos = new BlockPos(ExtMath.floord(entity.posX), ExtMath.floord(entity.posY), 
				ExtMath.floord(entity.posZ));
		Vec3 vec;
		if(this.gm.world.dimension.isExterminated())
			vec = new Vec3(0x101010);
		else
			vec = new Vec3(this.gm.world.dimension.getSkyColor());
		if(this.gm.world.dimension.hasDaylight()) {
	    	float mult = ExtMath.clampf(ExtMath.cos(this.gm.world.getDayPhase(partial)) * 2.0F + 0.5F, 0.0F, 1.0F);
			vec = new Vec3(vec.xCoord * mult, vec.yCoord * mult, vec.zCoord * mult);
		}
		float r = (float)vec.xCoord;
		float g = (float)vec.yCoord;
		float b = (float)vec.zCoord;
		
		float rain = this.gm.world.getRainStrength();
		if(rain > 0.0F) {
			float mul = (r * 0.3F + g * 0.59F + b * 0.11F) * 0.6F;
			float shift = 1.0F - rain * 0.75F;
			r = r * shift + mul * (1.0F - shift);
			g = g * shift + mul * (1.0F - shift);
			b = b * shift + mul * (1.0F - shift);
		}

		float dark = this.gm.world.getDarkness();
		if(dark > 0.0F) {
			float mul = (r * 0.3F + g * 0.59F + b * 0.11F) * 0.2F;
			float shift = 1.0F - dark * 0.75F;
			r = r * shift + mul * (1.0F - shift);
			g = g * shift + mul * (1.0F - shift);
			b = b * shift + mul * (1.0F - shift);
		}

		if(this.lastLightning > 0) {
			float light = (float)this.lastLightning - partial;
			if(light > 1.0F)
				light = 1.0F;
//			light = light * 0.45F;
			r = r * (1.0F - light) + (float)this.lightColor.xCoord * light;
			g = g * (1.0F - light) + (float)this.lightColor.yCoord * light;
			b = b * (1.0F - light) + (float)this.lightColor.zCoord * light;
		}
		
		float space = this.getSpaceFactor();
		if(space > 0.0f) {
			r = r * (1.0F - space);
			g = g * (1.0F - space);
			b = b * (1.0F - space);
		}

		return new Vec3((double)r, (double)g, (double)b);
	}

	private Vec3 getCloudColor(Entity entity, float partialTicks) {
		Vec3 color = new Vec3(this.gm.world.dimension.getCloudColor());
		if(this.gm.world.dimension.isExterminated())
			color = new Vec3(0x000000);
		float r = (float)color.xCoord;
		float g = (float)color.yCoord;
		float b = (float)color.zCoord;
		
		float rain = this.gm.world.getRainStrength();
		if(rain > 0.0F) {
			float mul = (r * 0.3F + g * 0.59F + b * 0.11F) * 0.6F;
			float shift = 1.0F - rain * 0.95F;
			r = r * shift + mul * (1.0F - shift);
			g = g * shift + mul * (1.0F - shift);
			b = b * shift + mul * (1.0F - shift);
		}

		if(this.gm.world.dimension.hasDaylight()) {
			float sun = ExtMath.clampf(ExtMath.cos(this.gm.world.getDayPhase(partialTicks)) * 2.0F + 0.5F, 
					0.0F, 1.0F);
			r = r * (sun * 0.9F + 0.1F);
			g = g * (sun * 0.9F + 0.1F);
			b = b * (sun * 0.85F + 0.15F);
		}
		
		float dark = this.gm.world.getDarkness();
		if(dark > 0.0F) {
			float mul = (r * 0.3F + g * 0.59F + b * 0.11F) * 0.2F;
			float shift = 1.0F - dark * 0.95F;
			r = r * shift + mul * (1.0F - shift);
			g = g * shift + mul * (1.0F - shift);
			b = b * shift + mul * (1.0F - shift);
		}
		
		float space = this.getSpaceFactor();
		if(space > 0.0f) {
			r = r * (1.0F - space);
			g = g * (1.0F - space);
			b = b * (1.0F - space);
		}

		return new Vec3((double)r, (double)g, (double)b);
	}

	private float getStarBrightness(float partialTicks) {
		float f = this.gm.world.getDayPhase(partialTicks);
		float f1 = 1.0F - (ExtMath.cos(f) * 2.0F + 0.25F);
		f1 = ExtMath.clampf(f1, 0.0F, 1.0F);
		return Math.max(f1 * f1 * this.gm.world.dimension.getStarBrightness(), this.getSpaceFactor());
	}

	private float getDeepStarBrightness(float partialTicks) {
		float f = this.gm.world.getDayPhase(partialTicks);
		float f1 = 1.0F - (ExtMath.cos(f) * 2.0F + 0.25F);
		f1 = ExtMath.clampf(f1, 0.0F, 1.0F);
		return Math.max(f1 * f1 * this.gm.world.dimension.getDeepStarBrightness(), this.getSpaceFactor());
	}
	
	private float getSpaceFactor() {
		Entity entity = this.gm.getRenderViewEntity();
		return entity == null ? 0.0f : (float)this.gm.world.getSpaceFactor(entity.posX, entity.posY, entity.posZ);
	}

    private void updateLightmap(float partialTicks)
    {
        if (this.lightmapUpdateNeeded)
        {
            World world = this.gm.world;

            if (world != null)
            {
                float sun = this.getSunBrightness(1.0F);
                float msun = sun * 0.95F + 0.05F;
        		float space = this.getSpaceFactor();
        		float brightness = (float)world.dimension.getBrightness() / 15.0f;

                for (int n = 0; n < 256; ++n)
                {
                    float rsky = World.BRIGHTNESS[n / 16];
                    float rblock = World.BRIGHTNESS[n % 16];
                    float sky = rsky * msun;
                    float block = rblock * (this.torchFlickerX * 0.1F + 1.5F);

                    float sred = Math.max(sky * (sun * 0.65F + 0.35F), brightness);
                    float sgreen = Math.max(sky * (sun * 0.65F + 0.35F), brightness);
                    float sblue = Math.max(sky, brightness);
                    if (world.dimension.getLightColor() != 0xffffffff)
                    {
                    	Vec3 lightColor = new Vec3(world.dimension.getLightColor());
                    	float light = world.dimension.hasSkyLight() ? Math.max(sky, brightness) : 1.0f;
                    	sred = (float)lightColor.xCoord * light;
                        sgreen = (float)lightColor.yCoord * light;
                        sblue = (float)lightColor.zCoord * light;
                    }
            		if(space > 0.0f) {
            			sred = sred * (1.0F - space) + space;
            			sgreen = sgreen * (1.0F - space) + space;
            			sblue = sblue * (1.0F - space) + space;
            		}
                    if (this.lastLightning > 0)
                    {
            			float intens = (float)this.lastLightning - partialTicks;
            			if(intens > 1.0F)
            				intens = 1.0F;
            			float light = world.dimension.hasSkyLight() ? rsky : 1.0f;
            			sred = sred * (1.0F - intens) + (float)this.lightColor.xCoord * light * intens;
            			sgreen = sgreen * (1.0F - intens) + (float)this.lightColor.yCoord * light * intens;
            			sblue = sblue * (1.0F - intens) + (float)this.lightColor.zCoord * light * intens;
                    }
                    
                    float bred = block;
                    float bgreen = block * ((block * 0.6F + 0.4F) * 0.6F + 0.4F);
                    float bblue = block * (block * block * 0.6F + 0.4F);
                    if (world.dimension.getBlockColor() != 0xffffffff)
                    {
                    	Vec3 lightColor = new Vec3(world.dimension.getBlockColor());
                    	float light = block;
            			if(light > 1.0F)
            				light = 1.0F;
                    	bred = (float)lightColor.xCoord * light;
                        bgreen = (float)lightColor.yCoord * light;
                        bblue = (float)lightColor.zCoord * light;
                        if(world.dimension.isBlockLightSubtracted()) {
                        	sred *= 1.0f - rblock;
                        	sgreen *= 1.0f - rblock;
                        	sblue *= 1.0f - rblock;
                        }
                    }
                    
                    float red = sred + bred;
                    float green = sgreen + bgreen;
                    float blue = sblue + bblue;
                    
                    red = red * 0.96F + 0.03F;
                    green = green * 0.96F + 0.03F;
                    blue = blue * 0.96F + 0.03F;

                    if (this.gm.player.hasEffect(Effect.NIGHT_VISION))
                    {
                        float vis = this.getNightVisionBrightness(this.gm.player, partialTicks);
                        float mult = 1.0F / red;

                        if (mult > 1.0F / green)
                        {
                            mult = 1.0F / green;
                        }

                        if (mult > 1.0F / blue)
                        {
                            mult = 1.0F / blue;
                        }

                        red = red * (1.0F - vis) + red * mult * vis;
                        green = green * (1.0F - vis) + green * mult * vis;
                        blue = blue * (1.0F - vis) + blue * mult * vis;
                    }

                    if (red > 1.0F)
                    {
                        red = 1.0F;
                    }

                    if (green > 1.0F)
                    {
                        green = 1.0F;
                    }

                    if (blue > 1.0F)
                    {
                        blue = 1.0F;
                    }

                    float bright = this.gm.setGamma || this.gm.xrayActive ? 100.0f : this.gm.player.getVisionBrightness();
                    float ri = 1.0F - red;
                    float gi = 1.0F - green;
                    float bi = 1.0F - blue;
                    ri = 1.0F - ri * ri * ri * ri;
                    gi = 1.0F - gi * gi * gi * gi;
                    bi = 1.0F - bi * bi * bi * bi;
                    red = red * (1.0F - bright) + ri * bright;
                    green = green * (1.0F - bright) + gi * bright;
                    blue = blue * (1.0F - bright) + bi * bright;
                    red = red * 0.96F + 0.03F;
                    green = green * 0.96F + 0.03F;
                    blue = blue * 0.96F + 0.03F;

                    if (red > 1.0F)
                    {
                        red = 1.0F;
                    }

                    if (green > 1.0F)
                    {
                        green = 1.0F;
                    }

                    if (blue > 1.0F)
                    {
                        blue = 1.0F;
                    }

                    if (red < 0.0F)
                    {
                        red = 0.0F;
                    }

                    if (green < 0.0F)
                    {
                        green = 0.0F;
                    }

                    if (blue < 0.0F)
                    {
                        blue = 0.0F;
                    }

                    int a = 255;
                    int r = (int)(red * 255.0F);
                    int g = (int)(green * 255.0F);
                    int b = (int)(blue * 255.0F);
                    this.lightmapColors[n] = a << 24 | r << 16 | g << 8 | b;
                }

                this.lightmapTexture.updateTexture();
                this.lightmapUpdateNeeded = false;
            }
        }
    }

    private float getNightVisionBrightness(EntityLiving entitylivingbaseIn, float partialTicks)
    {
        int i = entitylivingbaseIn.getEffect(Effect.NIGHT_VISION).getRemaining();
        return i > 200 ? 1.0F : 0.7F + ExtMath.sin(((float)i - partialTicks) * (float)Math.PI * 0.2F) * 0.3F;
    }

    public void renderWorld(float partialTicks, long finishTimeNano)
    {
    	finishTimeNano = System.nanoTime() + Math.max((long)this.gm.maxBuildTime * 1000000L - finishTimeNano, 0L);
        this.updateLightmap(partialTicks);

        if (this.gm.getRenderViewEntity() == null)
        {
            this.gm.setRenderViewEntity(this.gm.player);
        }

        this.getMouseOver(partialTicks);
        GlState.enableDepth();
        GlState.enableAlpha();
        GlState.alphaFunc(GL11.GL_GREATER, 0.5F);

        boolean flag = this.gm.getRenderViewEntity() != null && this.gm.getRenderViewEntity().isPlayer();
        GlState.enableCull();
        this.updateFogColor(partialTicks);
        GL11.glClear(16640);
        this.setupCameraTransform(partialTicks);
        MatrixState.update(this.gm.player, this.gm.thirdPersonView == 2);
        Entity entity = this.gm.getRenderViewEntity();
        double d0 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double)partialTicks;
        double d1 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double)partialTicks;
        double d2 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double)partialTicks;
        Frustum.setPosition(d0, d1, d2);
        if (this.gm.renderDistance >= 4)
        {
            this.setupFog(-1, partialTicks);
            GL11.glMatrixMode(GL11.GL_PROJECTION);
            GL11.glLoadIdentity();
            Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fbRawX / (float)this.gm.fbRawY, 0.05F, this.farPlaneDistance * 2.0F);
            GL11.glMatrixMode(GL11.GL_MODELVIEW);
            this.renderSky(partialTicks);
            GL11.glMatrixMode(GL11.GL_PROJECTION);
            GL11.glLoadIdentity();
            Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fbRawX / (float)this.gm.fbRawY, 0.05F, this.farPlaneDistance * SQRT_2);
            GL11.glMatrixMode(GL11.GL_MODELVIEW);
        }

        this.setupFog(0, partialTicks);
        GlState.shadeModel(GL11.GL_SMOOTH);

        if (entity.posY + (double)entity.getEyeHeight() < (double)this.gm.world.dimension.getCloudHeight())
        {
            this.renderCloudsCheck(partialTicks);
        }
        this.setupFog(0, partialTicks);
        this.gm.getTextureManager().bindTexture(TextureMap.BLOCKS);
        ItemRenderer.disableStandardItemLighting();
        this.setupTerrain(entity, (double)partialTicks, this.frameCount++, entity != this.gm.player || this.gm.player.noclip);
        this.updateChunks(finishTimeNano);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glPushMatrix();
        GlState.disableAlpha();
        this.renderBlockLayer(BlockLayer.SOLID, (double)partialTicks, entity);
        GlState.enableAlpha();
        this.renderBlockLayer(BlockLayer.CUTOUT, (double)partialTicks, entity);
        GlState.shadeModel(GL11.GL_FLAT);
        GlState.alphaFunc(GL11.GL_GREATER, 0.1F);

//        if (!this.debugView)
//        {
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glPopMatrix();
        GL11.glPushMatrix();
        ItemRenderer.enableStandardItemLighting();
        this.renderEntities(entity, partialTicks);
        ItemRenderer.disableStandardItemLighting();
        this.disableLightmap();
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glPopMatrix();
        GL11.glPushMatrix();

        if (this.gm.pointed != null && entity.isInsideOfLiquid() && flag)
        {
            EntityNPC entityplayer = (EntityNPC)entity;
            GlState.disableAlpha();
            this.drawSelectionBox(entityplayer, this.gm.pointed, partialTicks);
            GlState.enableAlpha();
        }
//        }

        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glPopMatrix();

        if (flag && this.gm.pointed != null && !entity.isInsideOfLiquid())
        {
            EntityNPC entityplayer1 = (EntityNPC)entity;
            GlState.disableAlpha();
            this.drawSelectionBox(entityplayer1, this.gm.pointed, partialTicks);
            GlState.enableAlpha();
        }
        GlState.enableBlend();
        GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ZERO);
        this.drawBlockDamageTexture(Tessellator.getBuffer(), entity, partialTicks);
        GlState.disableBlend();

//        if (!this.debugView)
//        {
        this.enableLightmap();
        this.gm.effectRenderer.renderTextured(entity, partialTicks);
        ItemRenderer.disableStandardItemLighting();
        this.setupFog(0, partialTicks);
        this.gm.effectRenderer.render(entity, partialTicks);
        this.disableLightmap();
//        }

        GlState.depthMask(false);
        GlState.enableCull();
        this.renderRainSnow(partialTicks);
        GlState.depthMask(true);
//        renderglobal.renderWorldBorder(entity, partialTicks);
        GlState.disableBlend();
        GlState.enableCull();
        GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
        GlState.alphaFunc(GL11.GL_GREATER, 0.1F);
//        this.setupFog(0, partialTicks);
//        GlState.enableBlend();
//        GlState.depthMask(false);
//        this.gm.getTextureManager().bindTexture(TextureMap.BLOCKS);
//        GlState.shadeModel(GL11.GL_SMOOTH);
//        this.renderBlockLayer(BlockLayer.TRANSLUCENT, (double)partialTicks, entity);
//        GlState.shadeModel(GL11.GL_FLAT);
//        GlState.depthMask(true);
//        GlState.enableCull();
//        GlState.disableBlend();
        GlState.disableFog();

        if (entity.posY + (double)entity.getEyeHeight() >= (double)this.gm.world.dimension.getCloudHeight())
        {
            this.renderCloudsCheck(partialTicks);
        }

        if (entity == this.gm.player && !(this.gm.player instanceof EntityCameraHolder))
        {
	        GL11.glClear(256);
	        this.renderHand(partialTicks);
        }
    }

    private void renderCloudsCheck(float partialTicks)
    {
		if (this.gm.renderDistance >= 4)
        {
            GL11.glMatrixMode(GL11.GL_PROJECTION);
            GL11.glLoadIdentity();
            Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fbRawX / (float)this.gm.fbRawY, 0.05F, this.farPlaneDistance * 4.0F);
            GL11.glMatrixMode(GL11.GL_MODELVIEW);
            GL11.glPushMatrix();
            this.setupFog(0, partialTicks);
            float alpha = 0.8F * (1.0f - this.getSpaceFactor());
            if(this.gm.world.dimension.hasWeather() && alpha > 0.5f)
            	this.renderClouds(alpha, partialTicks);
            GlState.disableFog();
            GL11.glPopMatrix();
            GL11.glMatrixMode(GL11.GL_PROJECTION);
            GL11.glLoadIdentity();
            Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fbRawX / (float)this.gm.fbRawY, 0.05F, this.farPlaneDistance * SQRT_2);
            GL11.glMatrixMode(GL11.GL_MODELVIEW);
        }
    }

    private void addRainParticles()
    {
        float f = this.gm.world.getRainStrength();

//        if (this.gm.downfallSetting != 0)
//        {
//            f /= 2.0F;
//        }

        if (f != 0.0F) // && this.gm.downfallSetting < 2)
        {
            this.rng.setSeed((long)this.rendererUpdateCount * 312987231L);
            Entity entity = this.gm.getRenderViewEntity();
            World world = this.gm.world;
            BlockPos blockpos = new BlockPos(entity);
            int i = this.gm.rainParticleRange;
            if(i <= 0)
            	return;
            double d0 = 0.0D;
            double d1 = 0.0D;
            double d2 = 0.0D;
            int j = 0;
            int n = 0;
            int k = (int)(10.0F * (float)i * f * f);

//            if (this.gm.particleSetting == 1)
//            {
//                k >>= 1;
//            }
//            else if (this.gm.particleSetting == 2)
//            {
//                k = 0;
//            }

//            boolean hail = !world.getWeather().isWet() && world.getWeather().hasDownfall();

            for (int l = 0; l < k; ++l)
            {
                BlockPos blockpos1 = world.getPrecipitationHeight(blockpos.add(this.rng.zrange(i) - this.rng.zrange(i), 0, this.rng.zrange(i) - this.rng.zrange(i)));
                BlockPos blockpos2 = blockpos1.down();
                Block block = world.getState(blockpos2).getBlock();
                float temp = world.getTemperatureC(blockpos1);

                if (blockpos1.getY() <= blockpos.getY() + i && blockpos1.getY() >= blockpos.getY() - i && /* biomegenbase.canRain() && */ temp > 0.0F)
                {
                    double d3 = this.rng.doublev();
                    double d4 = this.rng.doublev();

                    if (temp >= 194.0f || block.getMaterial() == Material.LAVA)
                    {
                    	if(temp >= 194.0f) {
                    		++n;
                            if (this.rng.zrange(n) == 0)
                            {
                                d0 = (double)blockpos2.getX() + d3;
                                d1 = (double)((float)blockpos2.getY() + 0.1F) + block.getBlockBoundsMaxY() - 1.0D;
                                d2 = (double)blockpos2.getZ() + d4;
                            }
                    	}
                    	if(temp < 194.0f || this.rng.chance(8))
                    		this.gm.world.clientParticle(temp >= 194.0f && this.rng.chance(20) ? ParticleType.LAVA : ParticleType.SMOKE, (double)blockpos1.getX() + d3, (double)((float)blockpos1.getY() + 0.1F) - block.getBlockBoundsMinY(), (double)blockpos1.getZ() + d4);
                    }
                    else if (block != Blocks.air)
                    {
                        block.setBlockBounds(world, blockpos2);
                        ++j;

                        if (this.rng.zrange(j) == 0)
                        {
                            d0 = (double)blockpos2.getX() + d3;
                            d1 = (double)((float)blockpos2.getY() + 0.1F) + block.getBlockBoundsMaxY() - 1.0D;
                            d2 = (double)blockpos2.getZ() + d4;
                        }

                        this.gm.world.clientParticle(temp <= 5.0f ? ParticleType.HAIL_CORN : ParticleType.WATER_DROP, (double)blockpos2.getX() + d3, (double)((float)blockpos2.getY() + 0.1F) + block.getBlockBoundsMaxY(), (double)blockpos2.getZ() + d4);
                    }
                }
            }

            if ((j > 0 || n > 0) && this.rng.zrange(3) < this.rainSoundCounter++)
            {
                this.rainSoundCounter = 0;

                if (d1 > (double)(blockpos.getY() + 1) && world.getPrecipitationHeight(blockpos).getY() > ExtMath.floorf((float)blockpos.getY()))
                {
                	this.gm.getSoundManager().playSound(new PositionedSound(n >= j ? this.pickMoltenSound() : SoundEvent.RAIN, n >= j ? 0.2f : 0.1F, (float)d0, (float)d1, (float)d2));
                }
                else
                {
                	this.gm.getSoundManager().playSound(new PositionedSound(n >= j ? this.pickMoltenSound() : SoundEvent.RAIN, n >= j ? 0.4f : 0.2F, (float)d0, (float)d1, (float)d2));
                }
            }
        }
    }
    
    private SoundEvent pickMoltenSound() {
    	return this.rng.chance(28) ? this.rng.pick(SoundEvent.MOLTEN, SoundEvent.MOLTEN_POP) : SoundEvent.FIRE;
    }

	private void renderRainSnow(float partial) {
		float rain = this.gm.world.getRainStrength();
		if(rain <= 0.0F)
			return;
		this.enableLightmap();
		Entity entity = this.gm.getRenderViewEntity();
		World world = this.gm.world;
		int ex = ExtMath.floord(entity.posX);
		int ey = ExtMath.floord(entity.posY);
		int ez = ExtMath.floord(entity.posZ);
		RenderBuffer buf = Tessellator.getBuffer();
		GlState.disableCull();
		GL11.glNormal3f(0.0F, 1.0F, 0.0F);
		GlState.enableBlend();
		GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
		GlState.alphaFunc(GL11.GL_GREATER, 0.1F);
		double ax = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double)partial;
		double ay = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double)partial;
		double az = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double)partial;
		int height = ExtMath.floord(ay);
		int range = this.gm.downfallRange;
		int hrange = 10;
		int mode = -1;
		float tic = (float)this.rendererUpdateCount + partial;
		buf.setTranslation(-ax, -ay, -az);
		GlState.color(1.0F, 1.0F, 1.0F, 1.0F);
		BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();

		for(int z = ez - range; z <= ez + range; z++) {
			for(int x = ex - range; x <= ex + range; x++) {
				int idx = (z - ez + 16) * 32 + x - ex + 16;
				double rx = (double)this.rainXCoords[idx] * 0.5D;
				double rz = (double)this.rainZCoords[idx] * 0.5D;
				pos.set(x, 0, z);

				int prec = world.getPrecipitationHeight(pos).getY();
				int miny = ey - hrange;
				int maxy = ey + hrange;

				if(miny < prec) {
					miny = prec;
				}

				if(maxy < prec) {
					maxy = prec;
				}

				int lpos = prec;

				if(prec < height) {
					lpos = height;
				}

				if(miny != maxy) {
					this.rng.setSeed((long)(x * x * 3121 + x * 45238971 ^ z * z * 418711 + z * 13761));
					pos.set(x, miny, z);
					float temp = world.getTemperatureC(pos);

					if(temp > 0.0F) {
						if(mode != (temp >= 194.0f ? 2 : (temp <= 5.0f ? 3 : 0))) {
							if(mode >= 0)
								Tessellator.draw();
							mode = temp >= 194.0f ? 2 : (temp <= 5.0f ? 3 : 0);
							this.gm.getTextureManager()
									.bindTexture(temp >= 194.0f ? TEX_MOLTEN : (temp <= 5.0f ? TEX_HAIL : TEX_RAIN));
							buf.begin(GL11.GL_QUADS, DefaultVertexFormats.PARTICLE_POSITION_TEX_COLOR_LMAP);
						}

						double offset = ((double)(this.rendererUpdateCount + x * x * 3121 + x * 45238971 + z * z * 418711 + z * 13761 & 31)
								+ (double)partial) / (temp >= 194.0f ? 64.0 : 32.0) * (3.0 + this.rng.doublev());
						double dx = (double)((float)x + 0.5F) - entity.posX;
						double dz = (double)((float)z + 0.5F) - entity.posZ;
						float dist = ExtMath.sqrtd(dx * dx + dz * dz) / (float)range;
						float alpha = ((1.0F - dist * dist) * 0.5F + 0.5F) * rain;
						pos.set(x, lpos, z);
						int light = world.getCombinedLight(pos, 0);
						int sky = light >> 16 & 65535;
						int blk = light & 65535;
						buf.pos((double)x - rx + 0.5D, (double)miny, (double)z - rz + 0.5D).tex(0.0D, (double)miny * 0.25D + offset)
								.color(1.0F, 1.0F, 1.0F, alpha).lightmap(sky, blk).endVertex();
						buf.pos((double)x + rx + 0.5D, (double)miny, (double)z + rz + 0.5D).tex(1.0D, (double)miny * 0.25D + offset)
								.color(1.0F, 1.0F, 1.0F, alpha).lightmap(sky, blk).endVertex();
						buf.pos((double)x + rx + 0.5D, (double)maxy, (double)z + rz + 0.5D).tex(1.0D, (double)maxy * 0.25D + offset)
								.color(1.0F, 1.0F, 1.0F, alpha).lightmap(sky, blk).endVertex();
						buf.pos((double)x - rx + 0.5D, (double)maxy, (double)z - rz + 0.5D).tex(0.0D, (double)maxy * 0.25D + offset)
								.color(1.0F, 1.0F, 1.0F, alpha).lightmap(sky, blk).endVertex();
					}
					else {
						if(mode != 1) {
							if(mode >= 0)
								Tessellator.draw();
							mode = 1;
							this.gm.getTextureManager().bindTexture(TEX_SNOW);
							buf.begin(GL11.GL_QUADS, DefaultVertexFormats.PARTICLE_POSITION_TEX_COLOR_LMAP);
						}

						double offset = (double)(((float)(this.rendererUpdateCount & 511) + partial) / 512.0F);
						double tx = this.rng.doublev() + (double)tic * 0.01D * (double)((float)this.rng.gaussian());
						double ty = this.rng.doublev() + (double)(tic * (float)this.rng.gaussian()) * 0.001D;
						double dx = (double)((float)x + 0.5F) - entity.posX;
						double dz = (double)((float)z + 0.5F) - entity.posZ;
						float dist = ExtMath.sqrtd(dx * dx + dz * dz) / (float)range;
						float alpha = ((1.0F - dist * dist) * 0.3F + 0.5F) * rain;
						pos.set(x, lpos, z);
						int light = (world.getCombinedLight(pos, 0) * 3 + 15728880) / 4;
						int sky = light >> 16 & 65535;
						int blk = light & 65535;
						buf.pos((double)x - rx + 0.5D, (double)miny, (double)z - rz + 0.5D).tex(0.0D + tx, (double)miny * 0.25D + offset + ty)
								.color(1.0F, 1.0F, 1.0F, alpha).lightmap(sky, blk).endVertex();
						buf.pos((double)x + rx + 0.5D, (double)miny, (double)z + rz + 0.5D).tex(1.0D + tx, (double)miny * 0.25D + offset + ty)
								.color(1.0F, 1.0F, 1.0F, alpha).lightmap(sky, blk).endVertex();
						buf.pos((double)x + rx + 0.5D, (double)maxy, (double)z + rz + 0.5D).tex(1.0D + tx, (double)maxy * 0.25D + offset + ty)
								.color(1.0F, 1.0F, 1.0F, alpha).lightmap(sky, blk).endVertex();
						buf.pos((double)x - rx + 0.5D, (double)maxy, (double)z - rz + 0.5D).tex(0.0D + tx, (double)maxy * 0.25D + offset + ty)
								.color(1.0F, 1.0F, 1.0F, alpha).lightmap(sky, blk).endVertex();
					}
				}
			}
		}

		if(mode >= 0)
			Tessellator.draw();
		buf.setTranslation(0.0D, 0.0D, 0.0D);
		GlState.enableCull();
		GlState.disableBlend();
		GlState.alphaFunc(GL11.GL_GREATER, 0.1F);
		this.disableLightmap();
	}

    private void updateFogColor(float partial)
    {
        World world = this.gm.world;
        Entity entity = this.gm.getRenderViewEntity();
        
		Vec3 fog = new Vec3(world.dimension.getFogColor());
        this.fogColorRed = (float)fog.xCoord;
        this.fogColorGreen = (float)fog.yCoord;
        this.fogColorBlue = (float)fog.zCoord;
        
		if(world.dimension.isExterminated()) {
			this.fogColorRed = 0.188f;
	        this.fogColorGreen = 0.188f;
	        this.fogColorBlue = 0.188f;
		}
		
		if(world.dimension.hasDaylight()) {
			float sun = ExtMath.clampf(ExtMath.cos(world.getDayPhase(partial)) * 2.0F + 0.5F, 0.0F, 1.0F);
			this.fogColorRed = this.fogColorRed * (sun * 0.94F + 0.06F);
			this.fogColorGreen = this.fogColorGreen * (sun * 0.94F + 0.06F);
			this.fogColorBlue = this.fogColorBlue * (sun * 0.91F + 0.09F);
		}

		float space = this.getSpaceFactor();
		if(space > 0.0f) {
			this.fogColorRed = this.fogColorRed * (1.0F - space);
			this.fogColorGreen = this.fogColorGreen * (1.0F - space);
			this.fogColorBlue = this.fogColorBlue * (1.0F - space);
		}
		
        if (this.gm.renderDistance >= 4 && world.dimension.hasDaylight() && !world.dimension.isBaseDestroyed())
        {
            double neg = -1.0D;
            Vec3 pos = ExtMath.sin(world.getDayPhase(partial)) > 0.0F ? new Vec3(neg, 0.0D, 0.0D) : new Vec3(1.0D, 0.0D, 0.0D);
            float shift = (float)entity.getLook(partial).dotProduct(pos);
            if (shift > 0.0F)
            {
                float[] sun = calcSunriseSunsetColors(world.getDayPhase(partial), partial);
                if (sun != null)
                {
                    shift = shift * sun[3];
                    this.fogColorRed = this.fogColorRed * (1.0F - shift) + sun[0] * shift;
                    this.fogColorGreen = this.fogColorGreen * (1.0F - shift) + sun[1] * shift;
                    this.fogColorBlue = this.fogColorBlue * (1.0F - shift) + sun[2] * shift;
                }
            }
        }

        float dist = 0.25F + 0.75F * (float)this.gm.renderDistance / 32.0F;
        dist = 1.0F - (float)Math.pow((double)dist, 0.25D);
        Vec3 sky = this.getSkyColor(this.gm.getRenderViewEntity(), partial);
        this.fogColorRed += ((float)sky.xCoord - this.fogColorRed) * dist;
        this.fogColorGreen += ((float)sky.yCoord - this.fogColorGreen) * dist;
        this.fogColorBlue += ((float)sky.zCoord - this.fogColorBlue) * dist;
        
        float rain = world.getRainStrength();
        if (rain > 0.0F)
        {
            float rg = 1.0F - rain * 0.5F;
            float b = 1.0F - rain * 0.4F;
            this.fogColorRed *= rg;
            this.fogColorGreen *= rg;
            this.fogColorBlue *= b;
        }

        float dark = world.getDarkness();
        if (dark > 0.0F)
        {
            float mul = 1.0F - dark * 0.5F;
            this.fogColorRed *= mul;
            this.fogColorGreen *= mul;
            this.fogColorBlue *= mul;
        }

        Block block = MatrixState.getLookedBlock(this.gm.world, entity, partial);
        if (block.getMaterial().isColdLiquid())
        {
            this.fogColorRed = 0.42F;
            this.fogColorGreen = 0.42F;
            this.fogColorBlue = 0.6F;
        }
        else if (block.getMaterial().isHotLiquid())
        {
            this.fogColorRed = 0.6F;
            this.fogColorGreen = 0.1F;
            this.fogColorBlue = 0.0F;
        }

        float mult = this.lastFogMult + (this.fogMult - this.lastFogMult) * partial;
        this.fogColorRed *= mult;
        this.fogColorGreen *= mult;
        this.fogColorBlue *= mult;
        
        double vision = 1.0;
        if(world.dimension.hasVoidFog() && this.gm.voidFog) {
        	double y = (entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double)partial);
        	if(y < 0.0)
        		vision += y / 64.0;
        }
        if (entity instanceof EntityLiving living && living.hasEffect(Effect.BLINDNESS))
        {
            int blind = living.getEffect(Effect.BLINDNESS).getRemaining();

            if (blind < 20)
                vision *= (double)(1.0F - (float)blind / 20.0F);
            else
                vision = 0.0D;
        }
        if (vision < 1.0D)
        {
            if (vision < 0.0D)
                vision = 0.0D;
            vision = vision * vision;
            this.fogColorRed = (float)((double)this.fogColorRed * vision);
            this.fogColorGreen = (float)((double)this.fogColorGreen * vision);
            this.fogColorBlue = (float)((double)this.fogColorBlue * vision);
        }

        if (entity instanceof EntityLiving living && living.hasEffect(Effect.NIGHT_VISION))
        {
            float vis = this.getNightVisionBrightness(living, partial);
            float mul = 1.0F / this.fogColorRed;
            if (mul > 1.0F / this.fogColorGreen)
                mul = 1.0F / this.fogColorGreen;
            if (mul > 1.0F / this.fogColorBlue)
                mul = 1.0F / this.fogColorBlue;
            this.fogColorRed = this.fogColorRed * (1.0F - vis) + this.fogColorRed * mul * vis;
            this.fogColorGreen = this.fogColorGreen * (1.0F - vis) + this.fogColorGreen * mul * vis;
            this.fogColorBlue = this.fogColorBlue * (1.0F - vis) + this.fogColorBlue * mul * vis;
        }

        GlState.clearColor(this.fogColorRed, this.fogColorGreen, this.fogColorBlue, 0.0F);
    }

    /**
     * Sets up the fog to be rendered. If the arg passed in is -1 the fog starts at 0 and goes to 80% of far plane
     * distance and is used for sky rendering.
     *  
     * @param start If is -1 the fog start at 0.0
     */
    private void setupFog(int start, float partial)
    {
        Entity entity = this.gm.getRenderViewEntity();
        float fog = this.gm.world.getFogStrength();
        float distance = Math.min(0.995f, Math.max(0.005f, FOG_DISTANCE - (0.3f * fog)));
        float density = 1.0f - Math.min(1.0f, FOG_DENSITY * (1.0f - fog * 0.1f));

        GL11.glFogfv(GL11.GL_FOG_COLOR, (FloatBuffer)this.setFogColorBuffer(this.fogColorRed, this.fogColorGreen, this.fogColorBlue, 1.0F));
        GL11.glNormal3f(0.0F, -1.0F, 0.0F);
        GlState.color(1.0F, 1.0F, 1.0F, 1.0F);
        Block block = MatrixState.getLookedBlock(this.gm.world, entity, partial);

        if(distance >= 1.0f) {
        	;
        }
        else if (entity instanceof EntityLiving && ((EntityLiving)entity).hasEffect(Effect.BLINDNESS))
        {
            float far = 5.0F;
            int effect = ((EntityLiving)entity).getEffect(Effect.BLINDNESS).getRemaining();

            if (effect < 20)
            {
                far = 5.0F + (this.farPlaneDistance - 5.0F) * (1.0F - (float)effect / 20.0F);
            }

            GlState.setFog(GL11.GL_LINEAR);

            if (start == -1)
            {
                GlState.setFogStart(0.0F);
                GlState.setFogEnd(far * 0.8F);
            }
            else
            {
                GlState.setFogStart(far * 0.25F);
                GlState.setFogEnd(far);
            }

//            if (GLContext.getCapabilities().GL_NV_fog_distance)
//            {
//                SKC.glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, NVFogDistance.GL_EYE_RADIAL_NV);
//            }
        }
//        else if (this.cloudFog)
//        {
//            GlState.setFog(SKC.GL_EXP);
//            GlState.setFogDensity(0.1F);
//        }
        else if (block.getMaterial().isColdLiquid())
        {
            GlState.setFog(GL11.GL_EXP);

//            if (entity instanceof EntityLivingBase && ((EntityLivingBase)entity).hasEffect(Potion.waterBreathing))
//            {
//                GlState.setFogDensity(0.01F);
//            }
//            else
//            {
            GlState.setFogDensity(0.04F); // - (float)EnchantmentHelper.getRespiration(entity) * 0.03F);
//            }
        }
        else if (block.getMaterial().isHotLiquid())
        {
            GlState.setFog(GL11.GL_EXP);
            GlState.setFogDensity(2.0F);
        }
        else
        {
            float far = this.farPlaneDistance;
            GlState.setFog(GL11.GL_LINEAR);

            if (start == -1)
            {
                GlState.setFogStart(0.0F);
                GlState.setFogEnd(far * Math.max(density * 2.0f, 0.01f));
            }
            else
            {
                GlState.setFogStart(far * distance);
                GlState.setFogEnd(far * Math.max(density * (distance / 0.75f) * 2.0f, distance + 0.01f));
            }

//            if (GLContext.getCapabilities().GL_NV_fog_distance)
//            {
//                SKC.glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, NVFogDistance.GL_EYE_RADIAL_NV);
//            }

            if (this.gm.world.dimension.hasDenseFog())
            {
                GlState.setFogStart(far * ((distance / 0.75f) * 0.05F));
                GlState.setFogEnd(Math.min(far, 192.0F) * Math.max(density * (distance / 0.75f), (distance / 0.75f) * 0.05F + 0.01f));
            }
        }

        GlState.enableColorMaterial();
        GlState.setFogEnabled(distance < 1.0f);
        GlState.colorMaterial(GL11.GL_FRONT, GL11.GL_AMBIENT);
    }

    private FloatBuffer setFogColorBuffer(float red, float green, float blue, float alpha)
    {
        this.fogColorBuffer.clear();
        this.fogColorBuffer.put(red).put(green).put(blue).put(alpha);
        this.fogColorBuffer.flip();
        return this.fogColorBuffer;
    }

	public void cacheSprites() {
		TextureMap texturemap = this.gm.getTextureMapBlocks();
		for(Pair<BlockStaticLiquid, BlockDynamicLiquid> liquid : BlockLiquid.LIQUIDS) {
			String name = BlockRegistry.getName(liquid.first());
			Sprite[] sprites = new Sprite[] {texturemap.getAtlasSprite("blocks/" + name + "_still"), texturemap.getAtlasSprite("blocks/" + name + "_flow")};
			this.fluids.put(liquid.second(), sprites);
			this.fluids.put(liquid.first(), sprites);
		}
		for(int i = 0; i < this.destroyBlockIcons.length; ++i) {
			this.destroyBlockIcons[i] = texturemap.getAtlasSprite("blocks/destroy_stage_" + i);
		}
	}

    private void generateSky2()
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        if (this.sky2VBO != null)
        {
            this.sky2VBO.deleteGlBuffers();
        }

//        if (this.glSkyList2 >= 0)
//        {
//            GLAllocation.deleteDisplayLists(this.glSkyList2);
//            this.glSkyList2 = -1;
//        }

//        if (this.vboEnabled)
//        {
            this.sky2VBO = new VertexBuffer(this.vertexBufferFormat);
            this.renderSky(worldrenderer, -16.0F, true);
            worldrenderer.finishDrawing();
            worldrenderer.reset();
            this.sky2VBO.bufferData(worldrenderer.getByteBuffer());
//        }
//        else
//        {
//            this.glSkyList2 = GLAllocation.generateDisplayLists(1);
//            SKC.glNewList(this.glSkyList2, SKC.GL_COMPILE);
//            this.renderSky(worldrenderer, -16.0F, true);
//            tessellator.draw();
//            SKC.glEndList();
//        }
    }

    private void generateSky()
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        if (this.skyVBO != null)
        {
            this.skyVBO.deleteGlBuffers();
        }

//        if (this.glSkyList >= 0)
//        {
//            GLAllocation.deleteDisplayLists(this.glSkyList);
//            this.glSkyList = -1;
//        }

//        if (this.vboEnabled)
//        {
            this.skyVBO = new VertexBuffer(this.vertexBufferFormat);
            this.renderSky(worldrenderer, 16.0F, false);
            worldrenderer.finishDrawing();
            worldrenderer.reset();
            this.skyVBO.bufferData(worldrenderer.getByteBuffer());
//        }
//        else
//        {
//            this.glSkyList = GLAllocation.generateDisplayLists(1);
//            SKC.glNewList(this.glSkyList, SKC.GL_COMPILE);
//            this.renderSky(worldrenderer, 16.0F, false);
//            tessellator.draw();
//            SKC.glEndList();
//        }
    }

    private void renderSky(RenderBuffer worldRendererIn, float posY, boolean reverseX)
    {
        int i = 64;
        int j = 6;
        worldRendererIn.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION);

        for (int k = -384; k <= 384; k += 64)
        {
            for (int l = -384; l <= 384; l += 64)
            {
                float f = (float)k;
                float f1 = (float)(k + 64);

                if (reverseX)
                {
                    f1 = (float)k;
                    f = (float)(k + 64);
                }

                worldRendererIn.pos((double)f, (double)posY, (double)l).endVertex();
                worldRendererIn.pos((double)f1, (double)posY, (double)l).endVertex();
                worldRendererIn.pos((double)f1, (double)posY, (double)(l + 64)).endVertex();
                worldRendererIn.pos((double)f, (double)posY, (double)(l + 64)).endVertex();
            }
        }
    }

    private void generateStars()
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        if (this.starVBO != null)
        {
            this.starVBO.deleteGlBuffers();
        }

//        if (this.starGLCallList >= 0)
//        {
//            GLAllocation.deleteDisplayLists(this.starGLCallList);
//            this.starGLCallList = -1;
//        }

//        if (this.vboEnabled)
//        {
            this.starVBO = new VertexBuffer(this.vertexBufferFormat);
            this.renderStars(worldrenderer, 10842L, 1500, 0.15f, 0.25f);
            worldrenderer.finishDrawing();
            worldrenderer.reset();
            this.starVBO.bufferData(worldrenderer.getByteBuffer());
//        }
//        else
//        {
//            this.starGLCallList = GLAllocation.generateDisplayLists(1);
//            GlState.pushMatrix();
//            SKC.glNewList(this.starGLCallList, SKC.GL_COMPILE);
//            this.renderStars(worldrenderer, 10842L, 1500, 0.15f, 0.25f);
//            tessellator.draw();
//            SKC.glEndList();
//            GlState.popMatrix();
//        }
    }

    private void generateDeepStars()
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        if (this.dstarVBO != null)
        {
            this.dstarVBO.deleteGlBuffers();
        }

//        if (this.dstarGLCallList >= 0)
//        {
//            GLAllocation.deleteDisplayLists(this.dstarGLCallList);
//            this.dstarGLCallList = -1;
//        }

//        if (this.vboEnabled)
//        {
            this.dstarVBO = new VertexBuffer(this.vertexBufferFormat);
            this.renderStars(worldrenderer, 0x59616f69L, 5000, 0.025f, 0.15f);
            worldrenderer.finishDrawing();
            worldrenderer.reset();
            this.dstarVBO.bufferData(worldrenderer.getByteBuffer());
//        }
//        else
//        {
//            this.dstarGLCallList = GLAllocation.generateDisplayLists(1);
//            GlState.pushMatrix();
//            SKC.glNewList(this.dstarGLCallList, SKC.GL_COMPILE);
//            this.renderStars(worldrenderer, 0x59616f69L, 5000, 0.025f, 0.15f);
//            tessellator.draw();
//            SKC.glEndList();
//            GlState.popMatrix();
//        }
    }

    private void renderStars(RenderBuffer rend, long seed, int nstars, float min, float max)
    {
    	max -= min;
        Random rand = new Random(seed);
        rend.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION);

        for (int n = 0; n < nstars; ++n)
        {
            double x = (double)(rand.floatv() * 2.0F - 1.0F);
            double y = (double)(rand.floatv() * 2.0F - 1.0F);
            double z = (double)(rand.floatv() * 2.0F - 1.0F);
            double size = (double)(min + rand.floatv() * max);
            double dist = x * x + y * y + z * z;

            if (dist < 1.0D && dist > 0.01D)
            {
                dist = 1.0D / Math.sqrt(dist);
                x = x * dist;
                y = y * dist;
                z = z * dist;
                double xm = x * 100.0D;
                double ym = y * 100.0D;
                double zm = z * 100.0D;
                double axz = Math.atan2(x, z);
                double sxz = Math.sin(axz);
                double cxz = Math.cos(axz);
                double ahz = Math.atan2(Math.sqrt(x * x + z * z), y);
                double shz = Math.sin(ahz);
                double chz = Math.cos(ahz);
                double arn = rand.doublev() * Math.PI * 2.0D;
                double shn = Math.sin(arn);
                double chn = Math.cos(arn);

                for (int v = 0; v < 4; ++v)
                {
//                    double d17 = 0.0D;
                    double sa = (double)((v & 2) - 1) * size;
                    double sb = (double)((v + 1 & 2) - 1) * size;
//                    double d20 = 0.0D;
                    double ra = sa * chn - sb * shn;
                    double rb = sb * chn + sa * shn;
                    double yo = ra * shz + 0.0D * chz;
                    double rot = 0.0D * shz - ra * chz;
                    double xo = rot * sxz - rb * cxz;
                    double zo = rb * sxz + rot * cxz;
                    rend.pos(xm + xo, ym + yo, zm + zo).endVertex();
                }
            }
        }
    }

    /**
     * set null to clear
     */
    public void setWorldAndLoadRenderers(World worldClientIn)
    {
//        if (this.theWorld != null)
//        {
//            this.theWorld.setWorldAccess(null);
//        }

        this.frustumUpdatePosX = Double.MIN_VALUE;
        this.frustumUpdatePosY = Double.MIN_VALUE;
        this.frustumUpdatePosZ = Double.MIN_VALUE;
        this.frustumUpdatePosChunkX = Integer.MIN_VALUE;
        this.frustumUpdatePosChunkY = Integer.MIN_VALUE;
        this.frustumUpdatePosChunkZ = Integer.MIN_VALUE;
        this.renderManager.set(worldClientIn);
        this.theWorld = worldClientIn;

        if (worldClientIn != null)
        {
//            worldClientIn.setWorldAccess(this);
            this.loadRenderers();
        }
    }

    /**
     * Loads all the renderers and sets up the basic settings usage
     */
    public void loadRenderers()
    {
        if (this.theWorld != null)
        {
            this.displayListEntitiesDirty = true;
            
            this.renderDistanceChunks = this.gm.renderDistance;

            if (this.viewFrustum != null)
            {
                this.viewFrustum.deleteGlResources();
            }

            this.stopChunkUpdates();

            synchronized (this.setTileEntities)
            {
                this.setTileEntities.clear();
            }

            this.viewFrustum = new ViewFrustum(this.gm, this.gm.renderDistance, this);

            if (this.theWorld != null)
            {
                Entity entity = this.gm.getRenderViewEntity();

                if (entity != null)
                {
                    this.viewFrustum.updateChunkPositions(entity.posX, entity.posY, entity.posZ);
                }
            }

            this.renderEntitiesStartupCounter = 2;
        }
    }
    
    public void stopChunkBuilders() {
    	this.renderDispatcher.kill();
    }

    private void stopChunkUpdates()
    {
        this.chunksToUpdate.clear();
        this.renderDispatcher.stopChunkUpdates();
    }

    private void renderEntities(Entity renderViewEntity, float partialTicks)
    {
        if (this.renderEntitiesStartupCounter > 0)
        {
            --this.renderEntitiesStartupCounter;
        }
        else
        {
            double d0 = renderViewEntity.prevX + (renderViewEntity.posX - renderViewEntity.prevX) * (double)partialTicks;
            double d1 = renderViewEntity.prevY + (renderViewEntity.posY - renderViewEntity.prevY) * (double)partialTicks;
            double d2 = renderViewEntity.prevZ + (renderViewEntity.posZ - renderViewEntity.prevZ) * (double)partialTicks;
            SpecialRenderer.instance.setPosition(this.theWorld, this.gm.getRenderViewEntity(), partialTicks);
            this.renderManager.cacheActiveRenderInfo(this.theWorld, this.gm.getRenderViewEntity(), this.gm.getPointedEntity(), this.gm, partialTicks);
            this.countEntitiesTotal = 0;
            this.countEntitiesRendered = 0;
            this.countEntitiesHidden = 0;
            Entity entity = this.gm.getRenderViewEntity();
            double d3 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double)partialTicks;
            double d4 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double)partialTicks;
            double d5 = entity.lastTickPosZ + (entity.posZ - entity.lastTickPosZ) * (double)partialTicks;
            SpecialRenderer.entityX = d3;
            SpecialRenderer.entityY = d4;
            SpecialRenderer.entityZ = d5;
            this.renderManager.setRenderPosition(d3, d4, d5);
            this.gm.renderer.enableLightmap();
            List<Entity> list = this.gm.getEntities();
            this.countEntitiesTotal = list.size();

            for (int i = 0; i < this.theWorld.effects.size(); ++i)
            {
                Entity entity1 = (Entity)this.theWorld.effects.get(i);
                ++this.countEntitiesRendered;

                if (entity1.isInRangeToRender3d(d0, d1, d2))
                {
                    this.renderManager.renderEntity(entity1, partialTicks);
                }
            }

            if (this.gm.tileOverlay)
            {
                GlState.depthFunc(GL11.GL_ALWAYS);
                GlState.disableFog();
                ItemRenderer.disableStandardItemLighting();
                GlState.enableBlend();
                GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
                GL11.glLineWidth(2.0F);
                GlState.disableTexture2D();
                GlState.depthMask(false);

                List<TileEntity> tiles = this.gm.getTiles();
                
                for (int j = 0; j < tiles.size(); ++j)
                {
                	TileEntity te = tiles.get(j);
                	BoundingBox bb = new BoundingBox(te.getPos(), te.getPos().add(1, 1, 1));
                    if(Frustum.isInFrustum(bb))
                    {
                    	int c = te.getColor();
                    	float r = (float)(c >> 16 & 255) / 255.0F;
                    	float g = (float)(c >> 8 & 255) / 255.0F;
                    	float b = (float)(c & 255) / 255.0F;
                        GlState.color(r, g, b, 0.8F);
                        drawSelectionBoundingBox(bb.offset(-d0, -d1, -d2));
                    }
                }
                
                ItemRenderer.enableStandardItemLighting();
                GlState.enableTexture2D();
//                GlState.depthMask(false);
                GlState.enableLighting();
                GlState.depthMask(true);
                GlState.enableFog();
                GlState.enableColorMaterial();
                GlState.depthFunc(GL11.GL_LEQUAL);
                GlState.enableDepth();
                GlState.enableAlpha();
            }

            if (this.gm.renderOutlines && this.gm.player != null)
            {
                GlState.depthFunc(GL11.GL_ALWAYS);
                GlState.disableFog();
                ItemRenderer.disableStandardItemLighting();
                GlState.enableBlend();
                GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
                GL11.glLineWidth(2.0F);
                GlState.disableTexture2D();
                GlState.depthMask(false);

                for (int j = 0; j < list.size(); ++j)
                {
                    Entity entity3 = list.get(j);
                    if ((entity3 != this.gm.getRenderViewEntity() || this.gm.thirdPersonView != 0 || this.gm.showPlayerFirstPerson) && 
                    		entity3 instanceof EntityLiving && entity3.isInRangeToRender3d(d0, d1, d2) && (entity3.noFrustumCheck || Frustum.isInFrustum(entity3.getEntityBoundingBox()) || entity3.passenger == this.gm.player))
                    {
//                        this.renderManager.renderEntity(entity3, partialTicks);
                    	int c = ((EntityLiving)entity3).getColor();
                    	float r = (float)(c >> 16 & 255) / 255.0F;
                    	float g = (float)(c >> 8 & 255) / 255.0F;
                    	float b = (float)(c & 255) / 255.0F;
                        GlState.color(r, g, b, 0.8F);
                        drawSelectionBoundingBox(entity3.getEntityBoundingBox().offset(-d0, -d1, -d2));
                    }
                }
                
                ItemRenderer.enableStandardItemLighting();
                GlState.enableTexture2D();
//                GlState.depthMask(false);
                GlState.enableLighting();
                GlState.depthMask(true);
                GlState.enableFog();
                GlState.enableColorMaterial();
                GlState.depthFunc(GL11.GL_LEQUAL);
                GlState.enableDepth();
                GlState.enableAlpha();
            }
            
            label738:

            for (RenderInfo render : this.renderInfos)
            {
            	ChunkClient chunk = this.gm.getChunk(render.chunk.getPosition().getX() >> 4, render.chunk.getPosition().getZ() >> 4);
                InheritanceMultiMap<Entity> classinheritancemultimap = chunk.getEntities()[ExtMath.clampi(render.chunk.getPosition().getY() / 16, 0, 31)];

                if (!classinheritancemultimap.isEmpty())
                {
                    Iterator iterator = classinheritancemultimap.iterator();

                    while (true)
                    {
                        Entity entity2;
                        boolean flag2;

                        while (true)
                        {
                            if (!iterator.hasNext())
                            {
                                continue label738;
                            }

                            entity2 = (Entity)iterator.next();
                            flag2 = this.renderManager.shouldRender(entity2, d0, d1, d2) || entity2.passenger == this.gm.player;

                            if (!flag2)
                            {
                                break;
                            }

//                            boolean flag3 = this.gm.getRenderViewEntity() instanceof EntityLivingBase ? ((EntityLivingBase)this.gm.getRenderViewEntity()).isPlayerSleeping() : false;

                            if (entity2.posY < (double)(-World.MAX_SIZE_Y) || entity2.posY >= (double)World.MAX_SIZE_Y || this.theWorld.isBlockLoaded(new BlockPos(entity2)))
                            {
                            	if((entity2 != this.gm.getRenderViewEntity() || this.gm.thirdPersonView != 0 || this.gm.showPlayerFirstPerson)) {
	                                ++this.countEntitiesRendered;
	                                this.renderManager.renderEntity(entity2, partialTicks);
                            	}
                            	else {
                            		this.renderManager.renderBox(entity2, partialTicks);
                            	}
                                break;
                            }
                        }
                    }
                }
            }
            
            ItemRenderer.enableStandardItemLighting();

            for (RenderInfo renderglobal$containerlocalrenderinformation1 : this.renderInfos)
            {
                List<TileEntity> list1 = renderglobal$containerlocalrenderinformation1.chunk.getCompiledChunk().getTileEntities();

                if (!list1.isEmpty())
                {
                    for (TileEntity tileentity2 : list1)
                    {
                        SpecialRenderer.instance.renderTile(tileentity2, partialTicks);
                    }
                }
            }

            synchronized (this.setTileEntities)
            {
                for (TileEntity tileentity : this.setTileEntities)
                {
                    SpecialRenderer.instance.renderTile(tileentity, partialTicks);
                }
            }

            this.gm.renderer.disableLightmap();
        }
    }

    /**
     * Gets the render info for use on the Debug screen
     */
    public String getDebugInfoRenders()
    {
        int i = this.viewFrustum.renderChunks.length;
        int j = 0;

        for (RenderInfo renderglobal$containerlocalrenderinformation : this.renderInfos)
        {
            CompiledChunk compiledchunk = renderglobal$containerlocalrenderinformation.chunk.compiledChunk;

            if (compiledchunk != CompiledChunk.DUMMY && !compiledchunk.isEmpty())
            {
                ++j;
            }
        }

        return String.format("Chunks: %d/%d (%d Chunk-Update%s) D: %d, %s", j, i, this.gm.chunksUpdated, this.gm.chunksUpdated != 1 ? "s" : "", 
        		/* this.gm.renderChunksMany ? "(s) " : "", */ this.renderDistanceChunks, this.renderDispatcher.getDebugInfo());
    }

    /**
     * Gets the entities info for use on the Debug screen
     */
    public String getDebugInfoEntities()
    {
        return "Objekte: " + this.countEntitiesRendered + "/" + this.countEntitiesTotal + ", V: " + this.countEntitiesHidden + ", I: " + (this.countEntitiesTotal - this.countEntitiesHidden - this.countEntitiesRendered);
    }

    private void setupTerrain(Entity viewEntity, double partialTicks, int frameCount, boolean playerSpectator)
    {
        if (this.gm.renderDistance != this.renderDistanceChunks)
        {
            this.loadRenderers();
        }
        double d0 = viewEntity.posX - this.frustumUpdatePosX;
        double d1 = viewEntity.posY - this.frustumUpdatePosY;
        double d2 = viewEntity.posZ - this.frustumUpdatePosZ;
        int prev = this.frustumUpdatePosChunkY;

        if (this.frustumUpdatePosChunkX != viewEntity.chunkCoordX || this.frustumUpdatePosChunkY != viewEntity.chunkCoordY || this.frustumUpdatePosChunkZ != viewEntity.chunkCoordZ || d0 * d0 + d1 * d1 + d2 * d2 > 16.0D)
        {
            this.frustumUpdatePosX = viewEntity.posX;
            this.frustumUpdatePosY = viewEntity.posY;
            this.frustumUpdatePosZ = viewEntity.posZ;
            this.frustumUpdatePosChunkX = viewEntity.chunkCoordX;
            this.frustumUpdatePosChunkY = viewEntity.chunkCoordY;
            this.frustumUpdatePosChunkZ = viewEntity.chunkCoordZ;
            this.viewFrustum.updateChunkPositions(viewEntity.posX, viewEntity.posY, viewEntity.posZ);
        }
        double d3 = viewEntity.lastTickPosX + (viewEntity.posX - viewEntity.lastTickPosX) * partialTicks;
        double d4 = viewEntity.lastTickPosY + (viewEntity.posY - viewEntity.lastTickPosY) * partialTicks;
        double d5 = viewEntity.lastTickPosZ + (viewEntity.posZ - viewEntity.lastTickPosZ) * partialTicks;
        this.initialize(d3, d4, d5);
        BlockPos blockpos1 = new BlockPos(d3, d4 + (double)viewEntity.getEyeHeight(), d5);
        RenderChunk renderchunk = this.viewFrustum.getRenderChunk(blockpos1);
        BlockPos blockpos = new BlockPos(ExtMath.floord(d3 / 16.0D) * 16, ExtMath.floord(d4 / 16.0D) * 16, ExtMath.floord(d5 / 16.0D) * 16);
        this.displayListEntitiesDirty = this.displayListEntitiesDirty || !this.chunksToUpdate.isEmpty() || viewEntity.posX != this.lastViewEntityX || viewEntity.posY != this.lastViewEntityY || viewEntity.posZ != this.lastViewEntityZ || (double)viewEntity.rotPitch != this.lastViewEntityPitch || (double)viewEntity.rotYaw != this.lastViewEntityYaw;
        this.lastViewEntityX = viewEntity.posX;
        this.lastViewEntityY = viewEntity.posY;
        this.lastViewEntityZ = viewEntity.posZ;
        this.lastViewEntityPitch = (double)viewEntity.rotPitch;
        this.lastViewEntityYaw = (double)viewEntity.rotYaw;
//        boolean flag = this.debugFixedClippingHelper != null;

        if (/* !flag && */ this.displayListEntitiesDirty)
        {
            this.displayListEntitiesDirty = false;
            this.renderInfos = Lists.<RenderInfo>newArrayList();
            Queue<RenderInfo> queue = new LinkedList<RenderInfo>();
            boolean vision = true; // this.gm.renderChunksMany;

            if (renderchunk != null)
            {
                boolean flag2 = false;
                RenderInfo renderglobal$containerlocalrenderinformation3 = new RenderInfo(renderchunk, (Facing)null, 0);
                Set<Facing> set1 = this.getVisibleFacings(blockpos1);

                if (set1.size() == 1)
                {
                    Vector3f vector3f = this.getViewVector(viewEntity, partialTicks);
                    Facing enumfacing = Facing.getFacingFromVector(vector3f.x, vector3f.y, vector3f.z).getOpposite();
                    set1.remove(enumfacing);
                }

                if (set1.isEmpty())
                {
                    flag2 = true;
                }

                if (flag2 && !playerSpectator)
                {
                    this.renderInfos.add(renderglobal$containerlocalrenderinformation3);
                }
                else
                {
                    if (playerSpectator && this.theWorld.getState(blockpos1).getBlock().isOpaqueCube())
                    {
                        vision = false;
                    }

                    renderchunk.setFrameIndex(frameCount);
                    queue.add(renderglobal$containerlocalrenderinformation3);
                }
            }
            else
            {
//                int i = blockpos1.getY() > 0 ? 248 : 8;
//                int i = blockpos1.getY() > 0 ? 504 : 8;

                for (int j = -this.renderDistanceChunks; j <= this.renderDistanceChunks; ++j)
                {
                    for (int k = -this.renderDistanceChunks; k <= this.renderDistanceChunks; ++k)
                    {
                        for (int i = -this.renderDistanceChunks; i <= this.renderDistanceChunks; ++i)
                        {
	                        RenderChunk renderchunk1 = this.viewFrustum.getRenderChunk(new BlockPos((j << 4) + 8, (i << 4) + 8, (k << 4) + 8));
	
	                        if (renderchunk1 != null && Frustum.isInFrustum(renderchunk1.boundingBox))
	                        {
	                            renderchunk1.setFrameIndex(frameCount);
	                            queue.add(new RenderInfo(renderchunk1, (Facing)null, 0));
	                        }
                        }
                    }
                }
            }
            
//            int n = queue.size();
//            Log.RENDER.info("** " + n + " render");

            while (!((Queue)queue).isEmpty())
            {
                RenderInfo render1 = (RenderInfo)queue.poll();
                RenderChunk chunk1 = render1.chunk;
                Facing face1 = this.gm.xrayActive ? null : render1.facing;
                BlockPos pos1 = chunk1.getPosition();
                this.renderInfos.add(render1);

                for (Facing face2 : Facing.values())
                {
                    RenderChunk chunk2 = this.getRenderChunkOffset(blockpos, chunk1, face2);

                    if ((!vision || !render1.faces.contains(face2.getOpposite())) 
                    		&& (!vision || face1 == null || chunk1.getCompiledChunk().isVisible(face1.getOpposite(), face2)) 
                    		&& chunk2 != null && chunk2.setFrameIndex(frameCount) && Frustum.isInFrustum(chunk2.boundingBox))
                    {
                        RenderInfo render2 = 
                        		new RenderInfo(chunk2, face2, render1.counter + 1);
                        render2.faces.addAll(render1.faces);
                        render2.faces.add(face2);
                        queue.add(render2);
//                        n++;
                    }
                }
            }
            
//            Log.RENDER.info("+ " + n + " render");
        }

//        if (this.debugFixTerrainFrustum)
//        {
//            this.fixTerrainFrustum(d3, d4, d5);
//            this.debugFixTerrainFrustum = false;
//        }

        this.renderDispatcher.clearChunkUpdates();
        Set<RenderChunk> set = this.chunksToUpdate;
        this.chunksToUpdate = new LinkedHashSet<RenderChunk>();

        for (RenderInfo renderglobal$containerlocalrenderinformation2 : this.renderInfos)
        {
            RenderChunk renderchunk4 = renderglobal$containerlocalrenderinformation2.chunk;

            if (renderchunk4.isNeedsUpdate() || set.contains(renderchunk4))
            {
                this.displayListEntitiesDirty = true;

                if (this.isPositionInRenderChunk(blockpos, renderglobal$containerlocalrenderinformation2.chunk))
                {
                    this.renderDispatcher.updateChunkNow(renderchunk4);
                    renderchunk4.setNeedsUpdate(false);
                }
                else
                {
                    this.chunksToUpdate.add(renderchunk4);
                }
            }
        }

        this.chunksToUpdate.addAll(set);
        
    	if(prev != Integer.MIN_VALUE && viewEntity.chunkCoordY != prev) {
    		for (int j = -this.renderDistanceChunks; j <= this.renderDistanceChunks; ++j)
            {
                for (int k = -this.renderDistanceChunks; k <= this.renderDistanceChunks; ++k)
                {
                    for (int i = -this.renderDistanceChunks; i <= this.renderDistanceChunks; ++i)
                    {
                        RenderChunk renderchunk1 = this.viewFrustum.getRenderChunk(new BlockPos((j << 4) + 8, (i << 4) + 8, (k << 4) + 8));

                        if (renderchunk1 != null)
                        {
                            renderchunk1.setNeedsUpdate(true);
                        }
                    }
                }
            }
    	}
    }

    private boolean isPositionInRenderChunk(BlockPos pos, RenderChunk renderChunkIn)
    {
        BlockPos blockpos = renderChunkIn.getPosition();
        return ExtMath.absi(pos.getX() - blockpos.getX()) > 16 ? false : (ExtMath.absi(pos.getY() - blockpos.getY()) > 16 ? false : ExtMath.absi(pos.getZ() - blockpos.getZ()) <= 16);
    }

    private Set<Facing> getVisibleFacings(BlockPos pos)
    {
        VisGraph visgraph = new VisGraph();
        BlockPos blockpos = new BlockPos(pos.getX() >> 4 << 4, pos.getY() >> 4 << 4, pos.getZ() >> 4 << 4);
        ChunkClient chunk = this.gm.getChunk(blockpos.getX() >> 4, blockpos.getZ() >> 4);

        for (BlockPos.MutableBlockPos blockpos$mutableblockpos : BlockPos.getAllInBoxMutable(blockpos, blockpos.add(15, 15, 15)))
        {
            if (chunk.getBlock(blockpos$mutableblockpos).isOpaqueCube())
            {
                visgraph.func_178606_a(blockpos$mutableblockpos);
            }
        }
        return visgraph.func_178609_b(pos);
    }

    /**
     * Returns RenderChunk offset from given RenderChunk in given direction, or null if it can't be seen by player at
     * given BlockPos.
     */
    private RenderChunk getRenderChunkOffset(BlockPos playerPos, RenderChunk renderChunkBase, Facing facing)
    {
        BlockPos blockpos = renderChunkBase.getBlockPosOffset16(facing);
        return ExtMath.absi(playerPos.getX() - blockpos.getX()) > this.renderDistanceChunks * 16 ? null : (ExtMath.absi(playerPos.getY() - blockpos.getY()) <= this.renderDistanceChunks * 16 ? (ExtMath.absi(playerPos.getZ() - blockpos.getZ()) > this.renderDistanceChunks * 16 ? null : this.viewFrustum.getRenderChunk(blockpos)) : null);
    }

    private Vector3f getViewVector(Entity entityIn, double partialTicks)
    {
        float f = (float)((double)entityIn.prevPitch + (double)(entityIn.rotPitch - entityIn.prevPitch) * partialTicks);
        float f1 = (float)((double)entityIn.prevYaw + (double)(entityIn.rotYaw - entityIn.prevYaw) * partialTicks);

        if (Client.CLIENT.thirdPersonView == 2)
        {
            f += 180.0F;
        }

        float f2 = ExtMath.cos(-f1 * 0.017453292F - (float)Math.PI);
        float f3 = ExtMath.sin(-f1 * 0.017453292F - (float)Math.PI);
        float f4 = -ExtMath.cos(-f * 0.017453292F);
        float f5 = ExtMath.sin(-f * 0.017453292F);
        return new Vector3f(f3 * f4, f5, f2 * f4);
    }

    private int renderBlockLayer(BlockLayer blockLayerIn, double partialTicks, Entity entityIn)
    {
        ItemRenderer.disableStandardItemLighting();

        int l = 0;
        int i = this.renderInfos.size();

        for (int j = 0; j < i; j++)
        {
            RenderChunk renderchunk = ((RenderInfo)this.renderInfos.get(j)).chunk;

            if (!renderchunk.getCompiledChunk().isLayerEmpty(blockLayerIn))
            {
                ++l;
                this.addRenderChunk(renderchunk, blockLayerIn);
            }
        }
        this.renderBlockLayer(blockLayerIn);
        return l;
    }

    
    private void renderBlockLayer(BlockLayer blockLayerIn)
    {
        this.gm.renderer.enableLightmap();

//        if (OpenGl.useVbo())
//        {
            GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
            GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
            GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
            GL13.glClientActiveTexture(GL13.GL_TEXTURE1);
            GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
            GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
            GL11.glEnableClientState(GL11.GL_COLOR_ARRAY);
//        }

        this.renderChunkLayer(blockLayerIn);

//        if (OpenGl.useVbo())
//        {
            for (VertexFormatElement vertexformatelement : DefaultVertexFormats.BLOCK.getElements())
            {
                VertexFormatElement.EnumUsage vertexformatelement$enumusage = vertexformatelement.usage();
                int i = vertexformatelement.index();

                switch (vertexformatelement$enumusage)
                {
                    case POSITION:
					GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
                        break;

                    case UV:
					GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + i);
					GL11.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
					GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
                        break;

                    case COLOR:
					GL11.glDisableClientState(GL11.GL_COLOR_ARRAY);
                        GlState.resetColor();
                }
            }
//        }

        this.gm.renderer.disableLightmap();
    }

    private void cleanupDamagedBlocks(Iterator<DestroyProgress> iteratorIn)
    {
        while (iteratorIn.hasNext())
        {
            DestroyProgress destroyblockprogress = (DestroyProgress)iteratorIn.next();
            int i = destroyblockprogress.getTime();

            if (this.cloudTickCounter - i > 400)
            {
                iteratorIn.remove();
            }
        }
    }

    private void renderSkyBox(String texture)
    {
        GlState.disableFog();
        GlState.disableAlpha();
        GlState.enableBlend();
        GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
        ItemRenderer.disableStandardItemLighting();
        GlState.depthMask(false);
        this.renderEngine.bindTexture(texture);
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        for (int i = 0; i < 6; ++i)
        {
            GL11.glPushMatrix();

            if (i == 1)
            {
                GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
            }

            if (i == 2)
            {
                GL11.glRotatef(-90.0F, 1.0F, 0.0F, 0.0F);
            }

            if (i == 3)
            {
                GL11.glRotatef(180.0F, 1.0F, 0.0F, 0.0F);
            }

            if (i == 4)
            {
                GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F);
            }

            if (i == 5)
            {
                GL11.glRotatef(-90.0F, 0.0F, 0.0F, 1.0F);
            }

            worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR);
            worldrenderer.pos(-100.0D, -100.0D, -100.0D).tex(0.0D, 0.0D).color(40, 40, 40, 255).endVertex();
            worldrenderer.pos(-100.0D, -100.0D, 100.0D).tex(0.0D, 16.0D).color(40, 40, 40, 255).endVertex();
            worldrenderer.pos(100.0D, -100.0D, 100.0D).tex(16.0D, 16.0D).color(40, 40, 40, 255).endVertex();
            worldrenderer.pos(100.0D, -100.0D, -100.0D).tex(16.0D, 0.0D).color(40, 40, 40, 255).endVertex();
            Tessellator.draw();
            GL11.glPopMatrix();
        }

        GlState.depthMask(true);
        GlState.enableTexture2D();
        GlState.enableAlpha();
    }

    private void renderSky(float partialTicks)
    {
        if (this.gm.world.dimension.getSkyBoxTexture() != null)
        {
            this.renderSkyBox(this.gm.world.dimension.getSkyBoxTexture());
        }
        else if (this.gm.world.dimension.hasSky())
        {
            GlState.disableTexture2D();
            Vec3 vec3 = this.gm.renderer.getSkyColor(this.gm.getRenderViewEntity(), partialTicks);
            float f = (float)vec3.xCoord;
            float f1 = (float)vec3.yCoord;
            float f2 = (float)vec3.zCoord;

//            if (pass != 2)
//            {
//                float f3 = (f * 30.0F + f1 * 59.0F + f2 * 11.0F) / 100.0F;
//                float f4 = (f * 30.0F + f1 * 70.0F) / 100.0F;
//                float f5 = (f * 30.0F + f2 * 70.0F) / 100.0F;
//                f = f3;
//                f1 = f4;
//                f2 = f5;
//            }

            float fog = 1.0f - this.theWorld.getFogStrength();
            GlState.color(f, f1, f2, fog);
//            Tessellator tessellator = Tessellator.getInstance();
            RenderBuffer worldrenderer = Tessellator.getBuffer();
            GlState.depthMask(false);
            GlState.enableFog();
            GlState.color(f, f1, f2, fog);

//            if (this.vboEnabled)
//            {
                this.skyVBO.bindBuffer();
                GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
                GL11.nglVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
                this.skyVBO.drawArrays(GL11.GL_QUADS);
                this.skyVBO.unbindBuffer();
                GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
//            }
//            else
//            {
//                GlState.callList(this.glSkyList);
//            }

            GlState.disableFog();
            GlState.disableAlpha();
            GlState.enableBlend();
            GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
            ItemRenderer.disableStandardItemLighting();

            float[] afloat = this.theWorld.dimension.hasDaylight() && !this.theWorld.dimension.isBaseDestroyed() ? 
            		calcSunriseSunsetColors(this.theWorld.getDayPhase(partialTicks), partialTicks) : null;
            if (afloat != null)
            {
                GlState.disableTexture2D();
                GlState.shadeModel(GL11.GL_SMOOTH);
                GL11.glPushMatrix();
                GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F);
                GL11.glRotatef(ExtMath.sin(this.theWorld.getDayPhase(partialTicks)) < 0.0F ? 180.0F : 0.0F, 0.0F, 0.0F, 1.0F);
                GL11.glRotatef(90.0F, 0.0F, 0.0F, 1.0F);
                float f6 = afloat[0];
                float f7 = afloat[1];
                float f8 = afloat[2];

//                if (pass != 2)
//                {
//                    float f9 = (f6 * 30.0F + f7 * 59.0F + f8 * 11.0F) / 100.0F;
//                    float f10 = (f6 * 30.0F + f7 * 70.0F) / 100.0F;
//                    float f11 = (f6 * 30.0F + f8 * 70.0F) / 100.0F;
//                    f6 = f9;
//                    f7 = f10;
//                    f8 = f11;
//                }

                worldrenderer.begin(GL11.GL_TRIANGLE_FAN, DefaultVertexFormats.POSITION_COLOR);
                worldrenderer.pos(0.0D, 100.0D, 0.0D).color(f6, f7, f8, afloat[3]).endVertex();
                int j = 16;

                for (int l = 0; l <= 16; ++l)
                {
                    float f21 = (float)l * (float)Math.PI * 2.0F / 16.0F;
                    float f12 = ExtMath.sin(f21);
                    float f13 = ExtMath.cos(f21);
                    worldrenderer.pos((double)(f12 * 120.0F), (double)(f13 * 120.0F), (double)(-f13 * 40.0F * afloat[3])).color(afloat[0], afloat[1], afloat[2], 0.0F).endVertex();
                }

                Tessellator.draw();
                GL11.glPopMatrix();
                GlState.shadeModel(GL11.GL_FLAT);
            }

            GlState.enableTexture2D();
            GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ZERO);
            GL11.glPushMatrix();
            float f16 = 1.0F - Math.max(this.theWorld.getRainStrength(), this.theWorld.getFogStrength());
            GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F);
            GL11.glRotatef(this.theWorld.getCelestialAngle(partialTicks), 1.0F, 0.0F, 0.0F);
            if(this.gm.world.dimension.getType() == DimType.PLANET || this.gm.world.dimension.getType() == DimType.MOON) {
	            float size = 30.0F;
	            int color = this.gm.world.dimension.getSunColor();
	            if(color != 0xffffffff) {
		            this.renderEngine.bindTexture((color & 0xff000000) != 0 ? EXTERMINATED_TEX : SUN_TEX);
	            	Vec3 ncolor = new Vec3(color);
	            	float mul = Math.min(1.0f / (float)ncolor.xCoord, Math.min(1.0f / (float)ncolor.yCoord, 1.0f / (float)ncolor.zCoord));
	                GlState.color((float)ncolor.xCoord * mul, (float)ncolor.yCoord * mul, (float)ncolor.zCoord * mul, f16);
		            worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
		            worldrenderer.pos((double)(-size), 100.0D, (double)(-size)).tex(0.0D, 0.0D).endVertex();
		            worldrenderer.pos((double)size, 100.0D, (double)(-size)).tex(1.0D, 0.0D).endVertex();
		            worldrenderer.pos((double)size, 100.0D, (double)size).tex(1.0D, 1.0D).endVertex();
		            worldrenderer.pos((double)(-size), 100.0D, (double)size).tex(0.0D, 1.0D).endVertex();
		            Tessellator.draw();
	            }
            	size = 20.0F;
	            int[] colors = this.gm.world.dimension.getMoonColors();
	            this.seededRng.setSeed(this.gm.world.dimension.getSeed());
	            int mx = 0;
	            int mz = 0;
	            for(int z = 0; z < colors.length; z++) {
	            	boolean destroyed = (colors[z] & 0xff000000) != 0;
		            this.renderEngine.bindTexture(destroyed ? EXTERMINATED_TEX : (this.gm.world.dimension.getType() == DimType.MOON ? PLANET_TEX : MOON_TEX));
	            	Vec3 ncolor = new Vec3(colors[z]);
	            	float mul = Math.min(1.0f / (float)ncolor.xCoord, Math.min(1.0f / (float)ncolor.yCoord, 1.0f / (float)ncolor.zCoord));
	                GlState.color((float)ncolor.xCoord * mul, (float)ncolor.yCoord * mul, (float)ncolor.zCoord * mul, f16);
		            int phase = this.theWorld.getMoonPhase(z);
		            int tx = phase % 4;
		            int ty = phase / 4 % 2;
		            float u1 = destroyed ? 0.0f : (float)(tx + 0) / 4.0F;
		            float v1 = destroyed ? 0.0f : (float)(ty + 0) / 2.0F;
		            float u2 = destroyed ? 1.0f : (float)(tx + 1) / 4.0F;
		            float v2 = destroyed ? 1.0f : (float)(ty + 1) / 2.0F;
		            worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX);
		            worldrenderer.pos((double)(-size + mx), -100.0D, (double)(size + mz)).tex((double)u2, (double)v2).endVertex();
		            worldrenderer.pos((double)(size + mx), -100.0D, (double)(size + mz)).tex((double)u1, (double)v2).endVertex();
		            worldrenderer.pos((double)(size + mx), -100.0D, (double)(-size + mz)).tex((double)u1, (double)v1).endVertex();
		            worldrenderer.pos((double)(-size + mx), -100.0D, (double)(-size + mz)).tex((double)u2, (double)v1).endVertex();
		            Tessellator.draw();
		            mx = this.seededRng.range(-60, 60);
		            mz = this.seededRng.range(-80, 80);
	            }
            }
            GlState.disableTexture2D();
            
            float f15 = this.gm.renderer.getStarBrightness(partialTicks) * f16;
            if (f15 > 0.0F)
            {
            	int stars = this.theWorld.dimension.getStarColor(this.theWorld.getRotation());
            	if(stars == 0xffffffff) {
            		GlState.color(f15, f15, f15, f15);
            	}
            	else {
                	Vec3 color = new Vec3(stars);
            		GlState.color((float)color.xCoord, (float)color.yCoord, (float)color.zCoord, f15);
            	}

//                if (this.vboEnabled)
//                {
                    this.starVBO.bindBuffer();
                    GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
                    GL11.nglVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
                    this.starVBO.drawArrays(GL11.GL_QUADS);
                    this.starVBO.unbindBuffer();
                    GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
//                }
//                else
//                {
//                    GlState.callList(this.starGLCallList);
//                }
            }
            
            f15 = this.gm.renderer.getDeepStarBrightness(partialTicks) * f16;
            if (f15 > 0.0F)
            {
            	int stars = this.theWorld.dimension.getDeepStarColor(this.theWorld.getRotation());
            	if(stars == 0xffffffff) {
            		GlState.color(f15, f15, f15, f15);
            	}
            	else {
                	Vec3 color = new Vec3(stars);
            		GlState.color((float)color.xCoord, (float)color.yCoord, (float)color.zCoord, f15);
            	}

//                if (this.vboEnabled)
//                {
                    this.dstarVBO.bindBuffer();
                    GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
                    GL11.nglVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
                    this.dstarVBO.drawArrays(GL11.GL_QUADS);
                    this.dstarVBO.unbindBuffer();
                    GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
//                }
//                else
//                {
//                    GlState.callList(this.dstarGLCallList);
//                }
            }

            GlState.color(1.0F, 1.0F, 1.0F, 1.0F);
            GlState.disableBlend();
            GlState.enableAlpha();
            GlState.enableFog();
            GL11.glPopMatrix();
            GlState.enableTexture2D();
            GlState.depthMask(true);
        }
    }

    private void renderClouds(float alpha, float partialTicks)
    {
        GlState.disableCull();
        float f = (float)(this.gm.getRenderViewEntity().lastTickPosY + (this.gm.getRenderViewEntity().posY - this.gm.getRenderViewEntity().lastTickPosY) * (double)partialTicks);
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();
        float f1 = 12.0F;
        float f2 = 4.0F;
        double d0 = (double)((float)this.cloudTickCounter + partialTicks);
        double d1 = (this.gm.getRenderViewEntity().prevX + (this.gm.getRenderViewEntity().posX - this.gm.getRenderViewEntity().prevX) * (double)partialTicks + d0 * 0.029999999329447746D) / 12.0D;
        double d2 = (this.gm.getRenderViewEntity().prevZ + (this.gm.getRenderViewEntity().posZ - this.gm.getRenderViewEntity().prevZ) * (double)partialTicks) / 12.0D + 0.33000001311302185D;
        float f3 = this.theWorld.dimension.getCloudHeight() - f + 0.33F;
        int i = ExtMath.floord(d1 / 2048.0D);
        int j = ExtMath.floord(d2 / 2048.0D);
        d1 = d1 - (double)(i * 2048);
        d2 = d2 - (double)(j * 2048);
        this.renderEngine.bindTexture(this.gm.world.dimension.getCloudTexture());
        GlState.enableBlend();
        GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
        Vec3 vec3 = this.gm.renderer.getCloudColor(this.gm.getRenderViewEntity(), partialTicks);
        float f4 = (float)vec3.xCoord;
        float f5 = (float)vec3.yCoord;
        float f6 = (float)vec3.zCoord;

//        if (pass != 2)
//        {
//            float f7 = (f4 * 30.0F + f5 * 59.0F + f6 * 11.0F) / 100.0F;
//            float f8 = (f4 * 30.0F + f5 * 70.0F) / 100.0F;
//            float f9 = (f4 * 30.0F + f6 * 70.0F) / 100.0F;
//            f4 = f7;
//            f5 = f8;
//            f6 = f9;
//        }

        float f26 = f4 * 0.9F;
        float f27 = f5 * 0.9F;
        float f28 = f6 * 0.9F;
        float f10 = f4 * 0.7F;
        float f11 = f5 * 0.7F;
        float f12 = f6 * 0.7F;
        float f13 = f4 * 0.8F;
        float f14 = f5 * 0.8F;
        float f15 = f6 * 0.8F;
        float f16 = 0.00390625F;
        float f17 = (float)ExtMath.floord(d1) * 0.00390625F;
        float f18 = (float)ExtMath.floord(d2) * 0.00390625F;
        float f19 = (float)(d1 - (double)ExtMath.floord(d1));
        float f20 = (float)(d2 - (double)ExtMath.floord(d2));
        int k = 8;
        int l = 4;
        float f21 = 9.765625E-4F;
        GL11.glScalef(12.0F, 1.0F, 12.0F);

        for (int i1 = 0; i1 < 2; ++i1)
        {
            if (i1 == 0)
            {
                GlState.colorMask(false, false, false, false);
            }
            else
            {
//                switch (pass)
//                {
//                    case 0:
//                        GlState.colorMask(false, true, true, true);
//                        break;
//
//                    case 1:
//                        GlState.colorMask(true, false, false, true);
//                        break;
//
//                    case 2:
                 GlState.colorMask(true, true, true, true);
//                }
            }

            for (int j1 = -3; j1 <= 4; ++j1)
            {
                for (int k1 = -3; k1 <= 4; ++k1)
                {
                    worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR_NORMAL);
                    float f22 = (float)(j1 * 8);
                    float f23 = (float)(k1 * 8);
                    float f24 = f22 - f19;
                    float f25 = f23 - f20;

                    if (f3 > -5.0F)
                    {
                        worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + 8.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f10, f11, f12, alpha).normal(0.0F, -1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 0.0F), (double)(f25 + 8.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f10, f11, f12, alpha).normal(0.0F, -1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 0.0F), (double)(f25 + 0.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f10, f11, f12, alpha).normal(0.0F, -1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + 0.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f10, f11, f12, alpha).normal(0.0F, -1.0F, 0.0F).endVertex();
                    }

                    if (f3 <= 5.0F)
                    {
                        worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 4.0F - 9.765625E-4F), (double)(f25 + 8.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f4, f5, f6, alpha).normal(0.0F, 1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 4.0F - 9.765625E-4F), (double)(f25 + 8.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f4, f5, f6, alpha).normal(0.0F, 1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 4.0F - 9.765625E-4F), (double)(f25 + 0.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f4, f5, f6, alpha).normal(0.0F, 1.0F, 0.0F).endVertex();
                        worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 4.0F - 9.765625E-4F), (double)(f25 + 0.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f4, f5, f6, alpha).normal(0.0F, 1.0F, 0.0F).endVertex();
                    }

                    if (j1 > -1)
                    {
                        for (int l1 = 0; l1 < 8; ++l1)
                        {
                            worldrenderer.pos((double)(f24 + (float)l1 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + 8.0F)).tex((double)((f22 + (float)l1 + 0.5F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f26, f27, f28, alpha).normal(-1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)l1 + 0.0F), (double)(f3 + 4.0F), (double)(f25 + 8.0F)).tex((double)((f22 + (float)l1 + 0.5F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f26, f27, f28, alpha).normal(-1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)l1 + 0.0F), (double)(f3 + 4.0F), (double)(f25 + 0.0F)).tex((double)((f22 + (float)l1 + 0.5F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f26, f27, f28, alpha).normal(-1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)l1 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + 0.0F)).tex((double)((f22 + (float)l1 + 0.5F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f26, f27, f28, alpha).normal(-1.0F, 0.0F, 0.0F).endVertex();
                        }
                    }

                    if (j1 <= 1)
                    {
                        for (int i2 = 0; i2 < 8; ++i2)
                        {
                            worldrenderer.pos((double)(f24 + (float)i2 + 1.0F - 9.765625E-4F), (double)(f3 + 0.0F), (double)(f25 + 8.0F)).tex((double)((f22 + (float)i2 + 0.5F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f26, f27, f28, alpha).normal(1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)i2 + 1.0F - 9.765625E-4F), (double)(f3 + 4.0F), (double)(f25 + 8.0F)).tex((double)((f22 + (float)i2 + 0.5F) * 0.00390625F + f17), (double)((f23 + 8.0F) * 0.00390625F + f18)).color(f26, f27, f28, alpha).normal(1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)i2 + 1.0F - 9.765625E-4F), (double)(f3 + 4.0F), (double)(f25 + 0.0F)).tex((double)((f22 + (float)i2 + 0.5F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f26, f27, f28, alpha).normal(1.0F, 0.0F, 0.0F).endVertex();
                            worldrenderer.pos((double)(f24 + (float)i2 + 1.0F - 9.765625E-4F), (double)(f3 + 0.0F), (double)(f25 + 0.0F)).tex((double)((f22 + (float)i2 + 0.5F) * 0.00390625F + f17), (double)((f23 + 0.0F) * 0.00390625F + f18)).color(f26, f27, f28, alpha).normal(1.0F, 0.0F, 0.0F).endVertex();
                        }
                    }

                    if (k1 > -1)
                    {
                        for (int j2 = 0; j2 < 8; ++j2)
                        {
                            worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 4.0F), (double)(f25 + (float)j2 + 0.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + (float)j2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, alpha).normal(0.0F, 0.0F, -1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 4.0F), (double)(f25 + (float)j2 + 0.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + (float)j2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, alpha).normal(0.0F, 0.0F, -1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 0.0F), (double)(f25 + (float)j2 + 0.0F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + (float)j2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, alpha).normal(0.0F, 0.0F, -1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + (float)j2 + 0.0F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + (float)j2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, alpha).normal(0.0F, 0.0F, -1.0F).endVertex();
                        }
                    }

                    if (k1 <= 1)
                    {
                        for (int k2 = 0; k2 < 8; ++k2)
                        {
                            worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 4.0F), (double)(f25 + (float)k2 + 1.0F - 9.765625E-4F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + (float)k2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, alpha).normal(0.0F, 0.0F, 1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 4.0F), (double)(f25 + (float)k2 + 1.0F - 9.765625E-4F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + (float)k2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, alpha).normal(0.0F, 0.0F, 1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 8.0F), (double)(f3 + 0.0F), (double)(f25 + (float)k2 + 1.0F - 9.765625E-4F)).tex((double)((f22 + 8.0F) * 0.00390625F + f17), (double)((f23 + (float)k2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, alpha).normal(0.0F, 0.0F, 1.0F).endVertex();
                            worldrenderer.pos((double)(f24 + 0.0F), (double)(f3 + 0.0F), (double)(f25 + (float)k2 + 1.0F - 9.765625E-4F)).tex((double)((f22 + 0.0F) * 0.00390625F + f17), (double)((f23 + (float)k2 + 0.5F) * 0.00390625F + f18)).color(f13, f14, f15, alpha).normal(0.0F, 0.0F, 1.0F).endVertex();
                        }
                    }

                    Tessellator.draw();
                }
            }
        }

        GlState.color(1.0F, 1.0F, 1.0F, 1.0F);
        GlState.disableBlend();
        GlState.enableCull();
    }

    private void updateChunks(long finishTimeNano)
    {
        this.displayListEntitiesDirty |= this.renderDispatcher.runChunkUploads(finishTimeNano);

        if (!this.chunksToUpdate.isEmpty())
        {
            Iterator<RenderChunk> iterator = this.chunksToUpdate.iterator();

            while (iterator.hasNext())
            {
                RenderChunk renderchunk = (RenderChunk)iterator.next();

                if (!this.renderDispatcher.updateChunkLater(renderchunk))
                {
                    break;
                }

                renderchunk.setNeedsUpdate(false);
                iterator.remove();
                long i = finishTimeNano - System.nanoTime();

                if (i < 0L)
                {
                    break;
                }
            }
        }
    }

    private void preRenderDamagedBlocks()
    {
        GlState.tryBlendFuncSeparate(GL11.GL_DST_COLOR, GL11.GL_SRC_COLOR, GL11.GL_ONE, GL11.GL_ZERO);
        GlState.enableBlend();
        GlState.color(1.0F, 1.0F, 1.0F, 0.5F);
        GlState.doPolygonOffset(-3.0F, -3.0F);
        GlState.enablePolygonOffset();
        GlState.alphaFunc(GL11.GL_GREATER, 0.1F);
        GlState.enableAlpha();
        GL11.glPushMatrix();
    }

    private void postRenderDamagedBlocks()
    {
        GlState.disableAlpha();
        GlState.doPolygonOffset(0.0F, 0.0F);
        GlState.disablePolygonOffset();
        GlState.enableAlpha();
        GlState.depthMask(true);
        GL11.glPopMatrix();
    }

    private void drawBlockDamageTexture(RenderBuffer worldRendererIn, Entity entityIn, float partialTicks)
    {
        double d0 = entityIn.lastTickPosX + (entityIn.posX - entityIn.lastTickPosX) * (double)partialTicks;
        double d1 = entityIn.lastTickPosY + (entityIn.posY - entityIn.lastTickPosY) * (double)partialTicks;
        double d2 = entityIn.lastTickPosZ + (entityIn.posZ - entityIn.lastTickPosZ) * (double)partialTicks;

        if (!this.damagedBlocks.isEmpty())
        {
            this.renderEngine.bindTexture(TextureMap.BLOCKS);
            this.preRenderDamagedBlocks();
            worldRendererIn.begin(GL11.GL_QUADS, DefaultVertexFormats.BLOCK);
            worldRendererIn.setTranslation(-d0, -d1, -d2);
            worldRendererIn.noColor();
            Iterator<DestroyProgress> iterator = this.damagedBlocks.values().iterator();

            while (iterator.hasNext())
            {
                DestroyProgress destroyblockprogress = (DestroyProgress)iterator.next();
                BlockPos blockpos = destroyblockprogress.getPosition();
                double d3 = (double)blockpos.getX() - d0;
                double d4 = (double)blockpos.getY() - d1;
                double d5 = (double)blockpos.getZ() - d2;
                Block block = this.theWorld.getState(blockpos).getBlock();

                if (d3 * d3 + d4 * d4 + d5 * d5 > 1024.0D)
                {
                    iterator.remove();
                }
                else
                {
                    State iblockstate = this.theWorld.getState(blockpos);

                    if (iblockstate.getBlock() != Blocks.air)
                    {
                        int i = destroyblockprogress.getDamage();
                        Sprite textureatlassprite = this.destroyBlockIcons[i];
                        this.renderBlockDamage(iblockstate, blockpos, textureatlassprite, this.theWorld);
                    }
                }
            }

            Tessellator.draw();
            worldRendererIn.setTranslation(0.0D, 0.0D, 0.0D);
            this.postRenderDamagedBlocks();
        }
    }

    /**
     * Draws the selection box for the player. Args: entityPlayer, rayTraceHit, i, itemStack, partialTickTime
     *  
     * @param execute If equals to 0 the method is executed
     */
    private void drawSelectionBox(EntityNPC player, HitPosition movingObjectPositionIn, float partialTicks)
    {
        if (movingObjectPositionIn.type == HitPosition.ObjectType.BLOCK)
        {
            GlState.enableBlend();
            GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO);
            GlState.color(0.0F, 0.0F, 0.0F, 0.4F);
            GL11.glLineWidth(2.0F);
            GlState.disableTexture2D();
            GlState.depthMask(false);
            float f = 0.002F;
            BlockPos blockpos = movingObjectPositionIn.block;
            Block block = this.theWorld.getState(blockpos).getBlock();

            if (block != Blocks.air) // && this.theWorld.getWorldBorder().contains(blockpos))
            {
                block.setBlockBounds(this.theWorld, blockpos);
                double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double)partialTicks;
                double d1 = player.lastTickPosY + (player.posY - player.lastTickPosY) * (double)partialTicks;
                double d2 = player.lastTickPosZ + (player.posZ - player.lastTickPosZ) * (double)partialTicks;
                drawSelectionBoundingBox(block.getSelectionBox(this.theWorld, blockpos).expand(0.0020000000949949026D, 0.0020000000949949026D, 0.0020000000949949026D).offset(-d0, -d1, -d2));
            }

            GlState.depthMask(true);
            GlState.enableTexture2D();
            GlState.disableBlend();
        }
    }

    public static void drawSelectionBoundingBox(BoundingBox boundingBox)
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();
        worldrenderer.begin(GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION);
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();
        Tessellator.draw();
        worldrenderer.begin(GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION);
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();
        Tessellator.draw();
        worldrenderer.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION);
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).endVertex();
        Tessellator.draw();
    }

    public static void drawOutlinedBoundingBox(BoundingBox boundingBox, int red, int green, int blue, int alpha)
    {
//        Tessellator tessellator = Tessellator.getInstance();
        RenderBuffer worldrenderer = Tessellator.getBuffer();
        worldrenderer.begin(GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION_COLOR);
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        Tessellator.draw();
        worldrenderer.begin(GL11.GL_LINE_STRIP, DefaultVertexFormats.POSITION_COLOR);
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        Tessellator.draw();
        worldrenderer.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR);
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.minZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.minY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.maxX, boundingBox.maxY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.minY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        worldrenderer.pos(boundingBox.minX, boundingBox.maxY, boundingBox.maxZ).color(red, green, blue, alpha).endVertex();
        Tessellator.draw();
    }

    public void markUpdate(int x1, int y1, int z1, int x2, int y2, int z2)
    {
        this.viewFrustum.markBlocksForUpdate(x1, y1, z1, x2, y2, z2);
    }

    public void setBreakProgress(int breakerId, BlockPos pos, int progress)
    {
        if (progress >= 0 && progress < 10)
        {
            DestroyProgress destroyblockprogress = (DestroyProgress)this.damagedBlocks.get(Integer.valueOf(breakerId));

            if (destroyblockprogress == null || destroyblockprogress.getPosition().getX() != pos.getX() || destroyblockprogress.getPosition().getY() != pos.getY() || destroyblockprogress.getPosition().getZ() != pos.getZ())
            {
                destroyblockprogress = new DestroyProgress(breakerId, pos);
                this.damagedBlocks.put(Integer.valueOf(breakerId), destroyblockprogress);
            }

            destroyblockprogress.setDamage(progress);
            destroyblockprogress.setTime(this.cloudTickCounter);
        }
        else
        {
            this.damagedBlocks.remove(Integer.valueOf(breakerId));
        }
    }

    public void setDisplayListEntitiesDirty()
    {
        this.displayListEntitiesDirty = true;
    }

    public void updateTileEntities(Collection<TileEntity> tileEntitiesToRemove, Collection<TileEntity> tileEntitiesToAdd)
    {
        synchronized (this.setTileEntities)
        {
            this.setTileEntities.removeAll(tileEntitiesToRemove);
            this.setTileEntities.addAll(tileEntitiesToAdd);
        }
    }
    
    private void initialize(double viewEntityXIn, double viewEntityYIn, double viewEntityZIn)
    {
        this.initialized = true;
        this.renderChunks.clear();
        this.viewEntityX = viewEntityXIn;
        this.viewEntityY = viewEntityYIn;
        this.viewEntityZ = viewEntityZIn;
    }

    private void preRenderChunk(RenderChunk renderChunkIn)
    {
        BlockPos blockpos = renderChunkIn.getPosition();
        GL11.glTranslatef((float)((double)blockpos.getX() - this.viewEntityX), (float)((double)blockpos.getY() - this.viewEntityY), (float)((double)blockpos.getZ() - this.viewEntityZ));
    }

    private void addRenderChunk(RenderChunk renderChunkIn, BlockLayer layer)
    {
        this.renderChunks.add(renderChunkIn);
    }
    
    private void renderChunkLayer(BlockLayer layer)
    {
        if (this.initialized)
        {
            for (RenderChunk renderchunk : this.renderChunks)
            {
                VertexBuffer vertexbuffer = renderchunk.getVertexBufferByLayer(layer.ordinal());
                GL11.glPushMatrix();
                this.preRenderChunk(renderchunk);
                renderchunk.multModelviewMatrix();
                vertexbuffer.bindBuffer();
                this.setupArrayPointers();
                vertexbuffer.drawArrays(GL11.GL_QUADS);
                GL11.glPopMatrix();
            }

            GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
            GlState.resetColor();
            this.renderChunks.clear();
        }
    }

    private void setupArrayPointers()
    {
        GL11.nglVertexPointer(3, GL11.GL_FLOAT, 28, 0L);
        GL11.nglColorPointer(4, GL11.GL_UNSIGNED_BYTE, 28, 12L);
        GL11.glTexCoordPointer(2, GL11.GL_FLOAT, 28, 16L);
        GL13.glClientActiveTexture(GL13.GL_TEXTURE1);
        GL11.glTexCoordPointer(2, GL11.GL_SHORT, 28, 24L);
        GL13.glClientActiveTexture(GL13.GL_TEXTURE0);
    }

    public void renderStarField(int w, int h, int bg, int color, float ticks, Random rand) {
    	long seed = rand.getSeed();
        Vec3 stars = new Vec3(color);
    	ticks *= 5.0f;
        GlState.disableCull();
		GlState.disableLighting();
        GlState.disableDepth();
        Drawing.drawRect(0, 0, w, h, bg | 0xff000000);
//    	Gui.drawRect(0, 0, w, h, bg | 0xff000000);
    	for(int z = 0; z < 6; z++) {
	        GL11.glMatrixMode(GL11.GL_MODELVIEW);
	        GL11.glLoadIdentity();
	        float shift = ticks % 30.0f - (float)z * 30.0f;
	        int n = z + (int)(ticks / 30.0f);
//	        WCF.glTranslatef(0.0f, 0.0f, (float)n * -30.0f);
	        rand.setSeed((long)n * 8436723957L);
	        GL11.glRotatef(rand.floatv() * 360.0f, 0.0f, 0.0f, 1.0f);
	        float timer = (float)((double)(System.nanoTime() / 1000L) / 1000000.0) * 0.12f;
	//    	Project.gluLookAt(0.0f, 0.0f, shift, ExtMath.sin(timer), ExtMath.cos(timer * 2.0f), shift + ExtMath.cos(timer * 0.33f), 0.0f, ExtMath.sin(timer), ExtMath.cos(timer));
	    	Project.gluLookAt(0.0f, 0.0f, shift, 0.0f, 0.0f, shift + 1.0f, 0.0f, 1.0f, 0.0f);
	        GL11.glMatrixMode(GL11.GL_PROJECTION);
	        GL11.glLoadIdentity();
	        Project.gluPerspective(90.0f, (float)w / (float)h, 0.05f, 1024.0f);
	//        WCF.glTranslatef(w / 2.0f, h / 2.0f, 0.0f);
	//        GlState.disableDepth();
	        GlState.disableTexture2D();
	        GlState.depthMask(false);
	//        this.skyVBO.bindBuffer();
	//        WCF.glEnableClientState(WCF.GL_VERTEX_ARRAY);
	//        WCF.glVertexPointer(3, WCF.GL_FLOAT, 12, 0L);
	//        this.skyVBO.drawArrays(GL11.GL_QUADS);
	//        this.skyVBO.unbindBuffer();
	//        WCF.glDisableClientState(WCF.GL_VERTEX_ARRAY);
	        GlState.disableAlpha();
	        GlState.enableBlend();
	        GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ONE, GL11.GL_ZERO);
	        ItemRenderer.disableStandardItemLighting();
	    	GlState.color((float)stars.xCoord, (float)stars.yCoord, (float)stars.zCoord, 1.0f);
	    	this.starVBO.bindBuffer();
	        GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
	        GL11.nglVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
	        this.starVBO.drawArrays(GL11.GL_QUADS);
	        this.starVBO.unbindBuffer();
	        GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
	        this.dstarVBO.bindBuffer();
	        GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY);
	        GL11.nglVertexPointer(3, GL11.GL_FLOAT, 12, 0L);
	        this.dstarVBO.drawArrays(GL11.GL_QUADS);
	        this.dstarVBO.unbindBuffer();
	        GL11.glDisableClientState(GL11.GL_VERTEX_ARRAY);
	        GlState.enableTexture2D();
	        GL11.glMatrixMode(GL11.GL_PROJECTION);
	        GL11.glLoadIdentity();
	        GL11.glMatrixMode(GL11.GL_MODELVIEW);
	        GL11.glLoadIdentity();
    	}
        GlState.enableCull();
        this.gm.setupOverlay();
        rand.setSeed(seed);
    }

    private static float[] calcSunriseSunsetColors(float radians, float partial) {
		float f = 0.4F;
		float f1 = ExtMath.cos(radians) - 0.0F;
		float f2 = -0.0F;
	
		if(f1 >= f2 - f && f1 <= f2 + f) {
			float f3 = (f1 - f2) / f * 0.5F + 0.5F;
			float f4 = 1.0F - (1.0F - ExtMath.sin(f3 * (float)Math.PI)) * 0.99F;
			f4 = f4 * f4;
			SUN_COLOR[0] = f3 * 0.3F + 0.7F;
			SUN_COLOR[1] = f3 * f3 * 0.7F + 0.2F;
			SUN_COLOR[2] = f3 * f3 * 0.0F + 0.2F;
			SUN_COLOR[3] = f4;
			return SUN_COLOR;
		}
		else {
			return null;
		}
	}

    private void renderBlockDamage(State state, BlockPos pos, Sprite texture, IWorldAccess world)
    {
        Block block = state.getBlock();
        if (block != Blocks.air && !block.getMaterial().isLiquid())
        {
            state = block.getState(state, world, pos);
            IBakedModel model = new BakedModel.Builder(this.manager.getModelForState(state), texture).makeBakedModel();
            block.setBlockBounds(world, pos);
            this.renderModel(world, model, state, pos, Tessellator.getBuffer(), true);
        }
    }

	public boolean renderBlock(State state, BlockPos pos, IWorldAccess world, RenderBuffer rb) {
		Block block = state.getBlock();
		if(this.gm.xrayActive && !block.isXrayVisible())
			return false;
		if(block == Blocks.air)
			return false;
		else if(block.getMaterial().isLiquid())
			return this.renderFluid(world, state, pos, rb);
		IBakedModel model = this.getBlockModel(state, world, pos);
        block.setBlockBounds(world, pos);
        return this.renderModel(world, model, state, pos, rb, !this.gm.xrayActive);
	}

	public IBakedModel getBlockModel(State state, IWorldAccess world, BlockPos pos) {
		Block block = state.getBlock();
		if(!this.gm.debugWorld) {
			try {
				state = block.getState(state, world, pos);
			}
			catch(Exception e) {
			}
		}
		return this.manager.getModelForState(state);
	}

    public void renderBlockEntity(State state, float brightness)
    {
        if (state.getBlock() != Blocks.air && !state.getBlock().getMaterial().isLiquid())
        {
            IBakedModel model = this.manager.getModelForState(state);
            Block block = state.getBlock();
            GL11.glRotatef(90.0F, 0.0F, 1.0F, 0.0F);

            for (Facing enumfacing : Facing.values())
            {
                this.renderSimple(brightness, model.getFace(enumfacing));
            }

            this.renderSimple(brightness, model.getQuads());
        }
    }

    private void renderSimple(float brightness, List<BakedQuad> listQuads)
    {
        RenderBuffer worldrenderer = Tessellator.getBuffer();

        for (BakedQuad bakedquad : listQuads)
        {
            worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.ITEM);
            worldrenderer.addVertexData(bakedquad.getVertexData());
            worldrenderer.putColorRGB_F4(brightness, brightness, brightness);
            Vec3i vec3i = bakedquad.getFace().getDirectionVec();
            worldrenderer.putNormal((float)vec3i.getX(), (float)vec3i.getY(), (float)vec3i.getZ());
            Tessellator.draw();
        }
    }
    
	private static final int getLightmapValue(IWorldAccess world, BlockPos pos) {
		Block block = world.getState(pos).getBlock();
		int light = world.getCombinedLight(pos, block.getLight());
		if(light == 0 && block instanceof BlockSlab) {
			pos = pos.down();
			block = world.getState(pos).getBlock();
			return world.getCombinedLight(pos, block.getLight());
		}
		return light;
	}
    
	private static final int getLightmapValueLiquid(IWorldAccess world, BlockPos pos) {
        int i = world.getCombinedLight(pos, 0);
        int j = world.getCombinedLight(pos.up(), 0);
        int k = i & 255;
        int l = j & 255;
        int i1 = i >> 16 & 255;
        int j1 = j >> 16 & 255;
        return (k > l ? k : l) | (i1 > j1 ? i1 : j1) << 16;
	}

    public boolean renderModel(IWorldAccess blockAccessIn, IBakedModel modelIn, State blockStateIn, BlockPos blockPosIn, RenderBuffer worldRendererIn, boolean checkSides)
    {
    	Block blockIn = blockStateIn.getBlock();
        boolean flag = false;
        BitSet bitset = new BitSet(3);

        for (Facing enumfacing : Facing.values())
        {
            List<BakedQuad> list = modelIn.getFace(enumfacing);

            if (!list.isEmpty())
            {
                BlockPos blockpos = blockPosIn.offset(enumfacing);

                if (!checkSides || blockIn.canRender(blockAccessIn, blockpos, enumfacing))
                {
                    int i = getLightmapValue(blockAccessIn, blockpos);
                    this.renderModelStandardQuads(blockAccessIn, blockIn, blockPosIn, enumfacing, i, false, worldRendererIn, list, bitset);
                    flag = true;
                }
            }
        }

        List<BakedQuad> list1 = modelIn.getQuads();

        if (list1.size() > 0)
        {
            this.renderModelStandardQuads(blockAccessIn, blockIn, blockPosIn, (Facing)null, -1, true, worldRendererIn, list1, bitset);
            flag = true;
        }

        return flag;
    }

    private void renderModelStandardQuads(IWorldAccess blockAccessIn, Block blockIn, BlockPos blockPosIn, Facing faceIn, int brightnessIn, boolean ownBrightness, RenderBuffer worldRendererIn, List<BakedQuad> listQuadsIn, BitSet boundsFlags)
    {
        double d0 = (double)blockPosIn.getX();
        double d1 = (double)blockPosIn.getY();
        double d2 = (double)blockPosIn.getZ();

        for (BakedQuad bakedquad : listQuadsIn)
        {
            if (ownBrightness)
            {
                this.fillQuadBounds(blockIn, bakedquad.getVertexData(), bakedquad.getFace(), (float[])null, boundsFlags);
                brightnessIn = boundsFlags.get(0) ? getLightmapValue(blockAccessIn, blockPosIn.offset(bakedquad.getFace())) : getLightmapValue(blockAccessIn, blockPosIn);
            }

            worldRendererIn.addVertexData(bakedquad.getVertexData());
            worldRendererIn.putBrightness4(brightnessIn, brightnessIn, brightnessIn, brightnessIn);
            worldRendererIn.putPosition(d0, d1, d2);
        }
    }

    private void fillQuadBounds(Block blockIn, int[] vertexData, Facing facingIn, float[] quadBounds, BitSet boundsFlags)
    {
        float f = 32.0F;
        float f1 = 32.0F;
        float f2 = 32.0F;
        float f3 = -32.0F;
        float f4 = -32.0F;
        float f5 = -32.0F;

        for (int i = 0; i < 4; ++i)
        {
            float f6 = Float.intBitsToFloat(vertexData[i * 7]);
            float f7 = Float.intBitsToFloat(vertexData[i * 7 + 1]);
            float f8 = Float.intBitsToFloat(vertexData[i * 7 + 2]);
            f = Math.min(f, f6);
            f1 = Math.min(f1, f7);
            f2 = Math.min(f2, f8);
            f3 = Math.max(f3, f6);
            f4 = Math.max(f4, f7);
            f5 = Math.max(f5, f8);
        }

        if (quadBounds != null)
        {
            quadBounds[Facing.WEST.getIndex()] = f;
            quadBounds[Facing.EAST.getIndex()] = f3;
            quadBounds[Facing.DOWN.getIndex()] = f1;
            quadBounds[Facing.UP.getIndex()] = f4;
            quadBounds[Facing.NORTH.getIndex()] = f2;
            quadBounds[Facing.SOUTH.getIndex()] = f5;
            quadBounds[Facing.WEST.getIndex() + Facing.values().length] = 1.0F - f;
            quadBounds[Facing.EAST.getIndex() + Facing.values().length] = 1.0F - f3;
            quadBounds[Facing.DOWN.getIndex() + Facing.values().length] = 1.0F - f1;
            quadBounds[Facing.UP.getIndex() + Facing.values().length] = 1.0F - f4;
            quadBounds[Facing.NORTH.getIndex() + Facing.values().length] = 1.0F - f2;
            quadBounds[Facing.SOUTH.getIndex() + Facing.values().length] = 1.0F - f5;
        }

        float f9 = 1.0E-4F;
        float f10 = 0.9999F;

        switch (facingIn)
        {
            case DOWN:
                boundsFlags.set(1, f >= 1.0E-4F || f2 >= 1.0E-4F || f3 <= 0.9999F || f5 <= 0.9999F);
                boundsFlags.set(0, (f1 < 1.0E-4F || blockIn.isFullCube()) && f1 == f4);
                break;

            case UP:
                boundsFlags.set(1, f >= 1.0E-4F || f2 >= 1.0E-4F || f3 <= 0.9999F || f5 <= 0.9999F);
                boundsFlags.set(0, (f4 > 0.9999F || blockIn.isFullCube()) && f1 == f4);
                break;

            case NORTH:
                boundsFlags.set(1, f >= 1.0E-4F || f1 >= 1.0E-4F || f3 <= 0.9999F || f4 <= 0.9999F);
                boundsFlags.set(0, (f2 < 1.0E-4F || blockIn.isFullCube()) && f2 == f5);
                break;

            case SOUTH:
                boundsFlags.set(1, f >= 1.0E-4F || f1 >= 1.0E-4F || f3 <= 0.9999F || f4 <= 0.9999F);
                boundsFlags.set(0, (f5 > 0.9999F || blockIn.isFullCube()) && f2 == f5);
                break;

            case WEST:
                boundsFlags.set(1, f1 >= 1.0E-4F || f2 >= 1.0E-4F || f4 <= 0.9999F || f5 <= 0.9999F);
                boundsFlags.set(0, (f < 1.0E-4F || blockIn.isFullCube()) && f == f3);
                break;

            case EAST:
                boundsFlags.set(1, f1 >= 1.0E-4F || f2 >= 1.0E-4F || f4 <= 0.9999F || f5 <= 0.9999F);
                boundsFlags.set(0, (f3 > 0.9999F || blockIn.isFullCube()) && f == f3);
        }
    }

    private boolean renderFluid(IWorldAccess blockAccess, State blockStateIn, BlockPos blockPosIn, RenderBuffer worldRendererIn)
    {
        BlockLiquid blockliquid = (BlockLiquid)blockStateIn.getBlock();
        blockliquid.setBlockBounds(blockAccess, blockPosIn);
        Sprite[] atextureatlassprite = this.fluids.get(blockliquid);
        boolean flag = blockliquid.canRender(blockAccess, blockPosIn.up(), Facing.UP);
        boolean flag1 = blockliquid.canRender(blockAccess, blockPosIn.down(), Facing.DOWN);
        boolean[] aboolean = new boolean[] {blockliquid.canRender(blockAccess, blockPosIn.north(), Facing.NORTH), blockliquid.canRender(blockAccess, blockPosIn.south(), Facing.SOUTH), blockliquid.canRender(blockAccess, blockPosIn.west(), Facing.WEST), blockliquid.canRender(blockAccess, blockPosIn.east(), Facing.EAST)};

        if (!flag && !flag1 && !aboolean[0] && !aboolean[1] && !aboolean[2] && !aboolean[3])
        {
            return false;
        }
        else
        {
            boolean flag2 = false;
            float f3 = 0.5F;
            float f4 = 1.0F;
            float f5 = 0.8F;
            float f6 = 0.6F;
            float f7 = this.getFluidHeight(blockAccess, blockPosIn);
            float f8 = this.getFluidHeight(blockAccess, blockPosIn.south());
            float f9 = this.getFluidHeight(blockAccess, blockPosIn.east().south());
            float f10 = this.getFluidHeight(blockAccess, blockPosIn.east());
            double d0 = (double)blockPosIn.getX();
            double d1 = (double)blockPosIn.getY();
            double d2 = (double)blockPosIn.getZ();
            float f11 = 0.001F;

            if (flag)
            {
                flag2 = true;
                Sprite textureatlassprite = atextureatlassprite[0];
                float f12 = (float)BlockLiquid.getFlowDirection(blockAccess, blockPosIn, blockliquid);

                if (f12 > -999.0F)
                {
                    textureatlassprite = atextureatlassprite[1];
                }

                f7 -= f11;
                f8 -= f11;
                f9 -= f11;
                f10 -= f11;
                float f13;
                float f14;
                float f15;
                float f16;
                float f17;
                float f18;
                float f19;
                float f20;

                if (f12 < -999.0F)
                {
                    f13 = textureatlassprite.getInterpolatedU(0.0D);
                    f17 = textureatlassprite.getInterpolatedV(0.0D);
                    f14 = f13;
                    f18 = textureatlassprite.getInterpolatedV(16.0D);
                    f15 = textureatlassprite.getInterpolatedU(16.0D);
                    f19 = f18;
                    f16 = f15;
                    f20 = f17;
                }
                else
                {
                    float f21 = ExtMath.sin(f12) * 0.25F;
                    float f22 = ExtMath.cos(f12) * 0.25F;
                    float f23 = 8.0F;
                    f13 = textureatlassprite.getInterpolatedU((double)(8.0F + (-f22 - f21) * 16.0F));
                    f17 = textureatlassprite.getInterpolatedV((double)(8.0F + (-f22 + f21) * 16.0F));
                    f14 = textureatlassprite.getInterpolatedU((double)(8.0F + (-f22 + f21) * 16.0F));
                    f18 = textureatlassprite.getInterpolatedV((double)(8.0F + (f22 + f21) * 16.0F));
                    f15 = textureatlassprite.getInterpolatedU((double)(8.0F + (f22 + f21) * 16.0F));
                    f19 = textureatlassprite.getInterpolatedV((double)(8.0F + (f22 - f21) * 16.0F));
                    f16 = textureatlassprite.getInterpolatedU((double)(8.0F + (f22 - f21) * 16.0F));
                    f20 = textureatlassprite.getInterpolatedV((double)(8.0F + (-f22 - f21) * 16.0F));
                }

                int k2 = getLightmapValueLiquid(blockAccess, blockPosIn);
                int l2 = k2 >> 16 & 65535;
                int i3 = k2 & 65535;
                float f24 = f4;
                float f25 = f4;
                float f26 = f4;
                worldRendererIn.pos(d0 + 0.0D, d1 + (double)f7, d2 + 0.0D).color(f24, f25, f26, 1.0F).tex((double)f13, (double)f17).lightmap(l2, i3).endVertex();
                worldRendererIn.pos(d0 + 0.0D, d1 + (double)f8, d2 + 1.0D).color(f24, f25, f26, 1.0F).tex((double)f14, (double)f18).lightmap(l2, i3).endVertex();
                worldRendererIn.pos(d0 + 1.0D, d1 + (double)f9, d2 + 1.0D).color(f24, f25, f26, 1.0F).tex((double)f15, (double)f19).lightmap(l2, i3).endVertex();
                worldRendererIn.pos(d0 + 1.0D, d1 + (double)f10, d2 + 0.0D).color(f24, f25, f26, 1.0F).tex((double)f16, (double)f20).lightmap(l2, i3).endVertex();

                if (blockliquid.shouldRenderSides(blockAccess, blockPosIn.up()))
                {
                    worldRendererIn.pos(d0 + 0.0D, d1 + (double)f7, d2 + 0.0D).color(f24, f25, f26, 1.0F).tex((double)f13, (double)f17).lightmap(l2, i3).endVertex();
                    worldRendererIn.pos(d0 + 1.0D, d1 + (double)f10, d2 + 0.0D).color(f24, f25, f26, 1.0F).tex((double)f16, (double)f20).lightmap(l2, i3).endVertex();
                    worldRendererIn.pos(d0 + 1.0D, d1 + (double)f9, d2 + 1.0D).color(f24, f25, f26, 1.0F).tex((double)f15, (double)f19).lightmap(l2, i3).endVertex();
                    worldRendererIn.pos(d0 + 0.0D, d1 + (double)f8, d2 + 1.0D).color(f24, f25, f26, 1.0F).tex((double)f14, (double)f18).lightmap(l2, i3).endVertex();
                }
            }

            if (flag1)
            {
                float f35 = atextureatlassprite[0].getMinU();
                float f36 = atextureatlassprite[0].getMaxU();
                float f37 = atextureatlassprite[0].getMinV();
                float f38 = atextureatlassprite[0].getMaxV();
                int l1 = getLightmapValueLiquid(blockAccess, blockPosIn.down());
                int i2 = l1 >> 16 & 65535;
                int j2 = l1 & 65535;
                worldRendererIn.pos(d0, d1, d2 + 1.0D).color(f3, f3, f3, 1.0F).tex((double)f35, (double)f38).lightmap(i2, j2).endVertex();
                worldRendererIn.pos(d0, d1, d2).color(f3, f3, f3, 1.0F).tex((double)f35, (double)f37).lightmap(i2, j2).endVertex();
                worldRendererIn.pos(d0 + 1.0D, d1, d2).color(f3, f3, f3, 1.0F).tex((double)f36, (double)f37).lightmap(i2, j2).endVertex();
                worldRendererIn.pos(d0 + 1.0D, d1, d2 + 1.0D).color(f3, f3, f3, 1.0F).tex((double)f36, (double)f38).lightmap(i2, j2).endVertex();
                flag2 = true;
            }

            for (int i1 = 0; i1 < 4; ++i1)
            {
                int j1 = 0;
                int k1 = 0;

                if (i1 == 0)
                {
                    --k1;
                }

                if (i1 == 1)
                {
                    ++k1;
                }

                if (i1 == 2)
                {
                    --j1;
                }

                if (i1 == 3)
                {
                    ++j1;
                }

                BlockPos blockpos = blockPosIn.add(j1, 0, k1);
                Sprite textureatlassprite1 = atextureatlassprite[1];

                if (aboolean[i1])
                {
                    float f39;
                    float f40;
                    double d3;
                    double d4;
                    double d5;
                    double d6;

                    if (i1 == 0)
                    {
                        f39 = f7;
                        f40 = f10;
                        d3 = d0;
                        d5 = d0 + 1.0D;
                        d4 = d2 + (double)f11;
                        d6 = d2 + (double)f11;
                    }
                    else if (i1 == 1)
                    {
                        f39 = f9;
                        f40 = f8;
                        d3 = d0 + 1.0D;
                        d5 = d0;
                        d4 = d2 + 1.0D - (double)f11;
                        d6 = d2 + 1.0D - (double)f11;
                    }
                    else if (i1 == 2)
                    {
                        f39 = f8;
                        f40 = f7;
                        d3 = d0 + (double)f11;
                        d5 = d0 + (double)f11;
                        d4 = d2 + 1.0D;
                        d6 = d2;
                    }
                    else
                    {
                        f39 = f10;
                        f40 = f9;
                        d3 = d0 + 1.0D - (double)f11;
                        d5 = d0 + 1.0D - (double)f11;
                        d4 = d2;
                        d6 = d2 + 1.0D;
                    }

                    flag2 = true;
                    float f41 = textureatlassprite1.getInterpolatedU(0.0D);
                    float f27 = textureatlassprite1.getInterpolatedU(8.0D);
                    float f28 = textureatlassprite1.getInterpolatedV((double)((1.0F - f39) * 16.0F * 0.5F));
                    float f29 = textureatlassprite1.getInterpolatedV((double)((1.0F - f40) * 16.0F * 0.5F));
                    float f30 = textureatlassprite1.getInterpolatedV(8.0D);
                    int j = getLightmapValueLiquid(blockAccess, blockpos);
                    int k = j >> 16 & 65535;
                    int l = j & 65535;
                    float f31 = i1 < 2 ? f5 : f6;
                    float f32 = f4 * f31;
                    float f33 = f4 * f31;
                    float f34 = f4 * f31;
                    worldRendererIn.pos(d3, d1 + (double)f39, d4).color(f32, f33, f34, 1.0F).tex((double)f41, (double)f28).lightmap(k, l).endVertex();
                    worldRendererIn.pos(d5, d1 + (double)f40, d6).color(f32, f33, f34, 1.0F).tex((double)f27, (double)f29).lightmap(k, l).endVertex();
                    worldRendererIn.pos(d5, d1 + 0.0D, d6).color(f32, f33, f34, 1.0F).tex((double)f27, (double)f30).lightmap(k, l).endVertex();
                    worldRendererIn.pos(d3, d1 + 0.0D, d4).color(f32, f33, f34, 1.0F).tex((double)f41, (double)f30).lightmap(k, l).endVertex();
                    worldRendererIn.pos(d3, d1 + 0.0D, d4).color(f32, f33, f34, 1.0F).tex((double)f41, (double)f30).lightmap(k, l).endVertex();
                    worldRendererIn.pos(d5, d1 + 0.0D, d6).color(f32, f33, f34, 1.0F).tex((double)f27, (double)f30).lightmap(k, l).endVertex();
                    worldRendererIn.pos(d5, d1 + (double)f40, d6).color(f32, f33, f34, 1.0F).tex((double)f27, (double)f29).lightmap(k, l).endVertex();
                    worldRendererIn.pos(d3, d1 + (double)f39, d4).color(f32, f33, f34, 1.0F).tex((double)f41, (double)f28).lightmap(k, l).endVertex();
                }
            }

            return flag2;
        }
    }

    private float getFluidHeight(IBlockAccess blockAccess, BlockPos blockPosIn)
    {
        int i = 0;
        float f = 0.0F;

        for (int j = 0; j < 4; ++j)
        {
            BlockPos blockpos = blockPosIn.add(-(j & 1), 0, -(j >> 1 & 1));

            if (blockAccess.getState(blockpos.up()).getBlock().getMaterial().isLiquid())
            {
                return 1.0F;
            }

            State iblockstate = blockAccess.getState(blockpos);
            Material material = iblockstate.getBlock().getMaterial();

            if (!material.isLiquid())
            {
                if (!material.isSolid())
                {
                    ++f;
                    ++i;
                }
            }
            else
            {
                int k = ((Integer)iblockstate.getValue(BlockLiquid.LEVEL)).intValue();

                if (k >= 8 || k == 0)
                {
                    f += BlockLiquid.getLiquidHeightPercent(k) * 10.0F;
                    i += 10;
                }

                f += BlockLiquid.getLiquidHeightPercent(k);
                ++i;
            }
        }

        return 1.0F - f / (float)i;
    }
}
