LoadingBar.java 14.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
/*
 * This file is part of LiteLoader.
 * Copyright (C) 2012-16 Adam Mummery-Smith
 * All Rights Reserved.
 */
package com.mumfrey.liteloader.client.gui.startup;

import static com.mumfrey.liteloader.gl.GL.*;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.imageio.ImageIO;

import org.lwjgl.opengl.Display;

import com.mumfrey.liteloader.common.LoadingProgress;
import com.mumfrey.liteloader.util.log.LiteLoaderLogger;

import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.VertexBuffer;
import net.minecraft.client.renderer.texture.DynamicTexture;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.IResource;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.shader.Framebuffer;
import net.minecraft.util.ResourceLocation;

/**
 * Crappy implementation of a "Mojang Screen" loading bar
 *
 * @author Adam Mummery-Smith
 */
public class LoadingBar extends LoadingProgress
{
    private static LoadingBar instance;

    private static final int MAX_MINECRAFT_PROGRESS = 90;
    private static final int LITELOADER_PROGRESS_SCALE = 2;

    private static final String LOADING_MESSAGE_1 = "Starting Game...";
    private static final String LOADING_MESSAGE_2 = "Initialising...";

    private int minecraftProgress = 0;
    private int totalMinecraftProgress = LoadingBar.MAX_MINECRAFT_PROGRESS;

    private int liteLoaderProgress = 0;
    private int totalLiteLoaderProgress = 0;

    private ResourceLocation textureLocation = new ResourceLocation("textures/gui/title/mojang.png");

    private String minecraftMessage = LoadingBar.LOADING_MESSAGE_1;
    private String message = "";

    private Minecraft minecraft;
    private TextureManager textureManager;
    private FontRenderer fontRenderer;

    private Framebuffer fbo;

    private boolean enabled = true;
    private boolean errored;

    private boolean calculatedColour = false;
    private int barLuma = 0, r2 = 246, g2 = 136, b2 = 62;

    private int logIndex = 0;
    private List<String> logTail = new ArrayList<String>();

    public LoadingBar()
    {
        LoadingBar.instance = this;
    }

    @Override
    protected void _setEnabled(boolean enabled)
    {
        this.enabled = enabled;
    }

    @Override
    protected void _dispose()
    {
        this.minecraft = null;
        this.textureManager = null;
        this.fontRenderer = null;

        this.disposeFbo();
    }

    private void disposeFbo()
    {
        if (this.fbo != null)
        {
            this.fbo.deleteFramebuffer();
            this.fbo = null;
        }
    }

    public static void incrementProgress()
    {
        if (LoadingBar.instance != null) LoadingBar.instance._incrementProgress();
    }

    protected void _incrementProgress()
    {
        this.message = this.minecraftMessage;

        this.minecraftProgress++;
        this.render();
    }

    public static void initTextures()
    {
        if (LoadingBar.instance != null) LoadingBar.instance._initTextures();
    }

    protected void _initTextures()
    {
        this.minecraftMessage = LoadingBar.LOADING_MESSAGE_2;
    }

    @Override
    protected void _incLiteLoaderProgress()
    {
        this.liteLoaderProgress += LoadingBar.LITELOADER_PROGRESS_SCALE;
        this.render();
    }

    @Override
    protected void _setMessage(String message)
    {
        this.message = message;
        this.render();
    }

    @Override
    protected void _incLiteLoaderProgress(String message)
    {
        this.message = message;
        this.liteLoaderProgress += LoadingBar.LITELOADER_PROGRESS_SCALE ;
        this.render();
    }

    @Override
    protected void _incTotalLiteLoaderProgress(int by)
    {
        this.totalLiteLoaderProgress += (by * LoadingBar.LITELOADER_PROGRESS_SCALE);
        this.render();
    }

    /**
     * 
     */
    private void render()
    {
        if (!this.enabled || this.errored) return;

        try
        {
            if (this.minecraft == null) this.minecraft = Minecraft.getMinecraft();
            if (this.textureManager == null) this.textureManager = this.minecraft.getTextureManager();

            if (Display.isCreated() && this.textureManager != null)
            {
                if (this.fontRenderer == null)
                {
                    this.fontRenderer = new FontRenderer(this.minecraft.gameSettings, new ResourceLocation("textures/font/ascii.png"),
                            this.textureManager, false);
                    this.fontRenderer.onResourceManagerReload(this.minecraft.getResourceManager());
                }

                double totalProgress = this.totalMinecraftProgress + this.totalLiteLoaderProgress;
                double progress = (this.minecraftProgress + this.liteLoaderProgress) / totalProgress;

//                if (progress >= 1.0) LoadingBar.message = "Preparing...";

                this.render(progress);
            }
        }
        catch (Exception ex)
        {
            // Disable the loading bar if ANY errors occur
            this.errored = true;
        }
    }

    /**
     * @param progress
     */
    private void render(double progress)
    {
        if (this.totalMinecraftProgress == -1)
        {
            this.totalMinecraftProgress = LoadingBar.MAX_MINECRAFT_PROGRESS - this.minecraftProgress;
            this.minecraftProgress = 0;
        }

        // Calculate the bar colour if we haven't already done that
        if (!this.calculatedColour)
        {
            this.calculatedColour = true;
            ITextureObject texture = this.textureManager.getTexture(this.textureLocation);
            if (texture == null)
            {
                try
                {
                    DynamicTexture textureData = this.loadTexture(this.minecraft.getResourceManager(), this.textureLocation);
                    this.textureLocation = this.minecraft.getTextureManager().getDynamicTextureLocation("loadingScreen", textureData);
                    this.findMostCommonColour(textureData.getTextureData());
                    textureData.updateDynamicTexture();
                }
                catch (IOException ex)
                {
                    ex.printStackTrace();
                }
            }
        }

        ScaledResolution scaledResolution = new ScaledResolution(this.minecraft);
        int scaleFactor = scaledResolution.getScaleFactor();
        int scaledWidth = scaledResolution.getScaledWidth();
        int scaledHeight = scaledResolution.getScaledHeight();

        int fboWidth = scaledWidth * scaleFactor;
        int fboHeight = scaledHeight * scaleFactor;

        if (this.fbo == null)
        {
            this.fbo = new Framebuffer(fboWidth, fboHeight, true);
        }
        else if (this.fbo.framebufferWidth != fboWidth || this.fbo.framebufferHeight != fboHeight)
        {
            this.fbo.createBindFramebuffer(fboWidth, fboHeight);
        }

        this.fbo.bindFramebuffer(false);

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        glOrtho(0.0D, scaledWidth, scaledHeight, 0.0D, 1000.0D, 3000.0D);

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glTranslatef(0.0F, 0.0F, -2000.0F);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glDisableLighting();
        glDisableFog();
        glDisableDepthTest();
        glEnableTexture2D();

        this.textureManager.bindTexture(this.textureLocation);
        Tessellator tessellator = Tessellator.getInstance();
        VertexBuffer vertexBuffer = tessellator.getBuffer();
        vertexBuffer.begin(GL_QUADS, VF_POSITION_TEX_COLOR);
        glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
        vertexBuffer.pos(0.0D,        scaledHeight, 0.0D).tex(0.0D, 0.0D).color(255, 255, 255, 255).endVertex();
        vertexBuffer.pos(scaledWidth, scaledHeight, 0.0D).tex(0.0D, 0.0D).color(255, 255, 255, 255).endVertex();
        vertexBuffer.pos(scaledWidth, 0.0D,         0.0D).tex(0.0D, 0.0D).color(255, 255, 255, 255).endVertex();
        vertexBuffer.pos(0.0D,        0.0D,         0.0D).tex(0.0D, 0.0D).color(255, 255, 255, 255).endVertex();
        tessellator.draw();

        glColor4f(1.0F, 1.0F, 1.0F, 1.0F);

        int left = (scaledWidth - 256) / 2;
        int top = (scaledHeight - 256) / 2;
        int u1 = 0;
        int v1 = 0;
        int u2 = 256;
        int v2 = 256;

        float texMapScale = 0.00390625F;
        vertexBuffer.begin(GL_QUADS, VF_POSITION_TEX_COLOR);
        vertexBuffer.pos(left + 0,  top + v2, 0.0D).tex((u1 + 0)  * texMapScale, (v1 + v2) * texMapScale).color(255, 255, 255, 255).endVertex();
        vertexBuffer.pos(left + u2, top + v2, 0.0D).tex((u1 + u2) * texMapScale, (v1 + v2) * texMapScale).color(255, 255, 255, 255).endVertex();
        vertexBuffer.pos(left + u2, top + 0,  0.0D).tex((u1 + u2) * texMapScale, (v1 + 0)  * texMapScale).color(255, 255, 255, 255).endVertex();
        vertexBuffer.pos(left + 0,  top + 0,  0.0D).tex((u1 + 0)  * texMapScale, (v1 + 0)  * texMapScale).color(255, 255, 255, 255).endVertex();
        tessellator.draw();

        glEnableTexture2D();
        glEnableColorLogic();
        glLogicOp(GL_OR_REVERSE);
        this.fontRenderer.drawString(this.message, 1, scaledHeight - 19, 0xFF000000);

        if (LiteLoaderLogger.DEBUG)
        {
            int logBottom = this.minecraft.displayHeight - (20 * scaleFactor) - 2;

            glPushMatrix();
            glScalef(1.0F / scaleFactor, 1.0F / scaleFactor, 1.0F);
            this.renderLogTail(logBottom);
            glPopMatrix();
        }

        glDisableColorLogic();
        glEnableTexture2D();

        double barHeight = 10.0D;

        double barWidth = scaledResolution.getScaledWidth_double() - 2.0D;

        glDisableTexture2D();
        glEnableBlend();
        glEnableAlphaTest();
        glAlphaFunc(GL_GREATER, 0.0F);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

//        tessellator.startDrawingQuads();
//        tessellator.setColorRGBA(0, 0, 0, 32);
//        tessellator.addVertex(0.0D,               scaledHeight,                      0.0D);
//        tessellator.setColorRGBA(0, 0, 0, 180);
//        tessellator.addVertex(0.0D + scaledWidth, scaledHeight,                      0.0D);
//        tessellator.setColorRGBA(0, 0, 0, 0);
//        tessellator.addVertex(0.0D + scaledWidth, (scaledHeight / 10),               0.0D);
//        tessellator.addVertex(0.0D,               scaledHeight - (scaledHeight / 3), 0.0D);
//        tessellator.draw();

        vertexBuffer.begin(GL_QUADS, VF_POSITION);
        float luma = this.barLuma / 255.0F;
        glColor4f(luma, luma, luma, 0.5F);
        vertexBuffer.pos(0.0D,               scaledHeight,             0.0D).endVertex();
        vertexBuffer.pos(0.0D + scaledWidth, scaledHeight,             0.0D).endVertex();
        vertexBuffer.pos(0.0D + scaledWidth, scaledHeight - barHeight, 0.0D).endVertex();
        vertexBuffer.pos(0.0D,               scaledHeight - barHeight, 0.0D).endVertex();
        tessellator.draw();

        barHeight -= 1;

        vertexBuffer.begin(GL_QUADS, VF_POSITION_COLOR);
        float r2 = this.r2 / 255.0F;
        float g2 = this.g2 / 255.0F;
        float b2 = this.b2 / 255.0F;
        vertexBuffer.pos(1.0D + barWidth * progress, scaledHeight - 1,         1.0D).color(r2, g2, b2, 1.0F).endVertex();
        vertexBuffer.pos(1.0D + barWidth * progress, scaledHeight - barHeight, 1.0D).color(r2, g2, b2, 1.0F).endVertex();
        vertexBuffer.pos(1.0D,                       scaledHeight - barHeight, 1.0D).color(0.0F, 0.0F, 0.0F, 1.0F).endVertex();
        vertexBuffer.pos(1.0D,                       scaledHeight - 1,         1.0D).color(0.0F, 0.0F, 0.0F, 1.0F).endVertex();
        tessellator.draw();

        glAlphaFunc(GL_GREATER, 0.1F);
        glDisableLighting();
        glDisableFog();
        this.fbo.unbindFramebuffer();

        this.fbo.framebufferRender(fboWidth, fboHeight);

        glEnableAlphaTest();
        glAlphaFunc(GL_GREATER, 0.1F);
//        glFlush();

        this.minecraft.updateDisplay();
    }

    private void renderLogTail(int yPos)
    {
        if (this.logIndex != LiteLoaderLogger.getLogIndex())
        {
            this.logTail = LiteLoaderLogger.getLogTail();
        }

        for (int logIndex = this.logTail.size() - 1; yPos > 10 && logIndex >= 0; logIndex--)
        {
            this.fontRenderer.drawString(this.logTail.get(logIndex), 10, yPos -= 10, 0xFF000000);
        }
    }

    /**
     * Find the most common (approx) colour in the image and assign it to the
     * bar, reduces the palette to 9-bit by stripping the the 5 LSB from each
     * byte to create a 9-bit palette index in the form RRRGGGBBB
     * 
     * @param textureData
     */
    private void findMostCommonColour(int[] textureData)
    {
        // Array of frequency values, indexed by palette index
        int[] freq = new int[512];

        for (int pos = 0; pos < textureData.length; pos++)
        {
            int paletteIndex = ((textureData[pos] >> 21 & 0x7) << 6) + ((textureData[pos] >> 13 & 0x7) << 3) + (textureData[pos] >> 5 & 0x7);
            freq[paletteIndex]++;
        }

        int peak = 0;

        // Black, white and 0x200000 excluded on purpose
        for (int paletteIndex = 2; paletteIndex < 511; paletteIndex++)
        {
            if (freq[paletteIndex] > peak)
            {
                peak = freq[paletteIndex];
                this.setBarColour(paletteIndex);
            }
        }
    }

    /**
     * @param paletteIndex
     */
    private void setBarColour(int paletteIndex)
    {
        this.r2 = this.padComponent((paletteIndex & 0x1C0) >> 1);
        this.g2 = this.padComponent((paletteIndex & 0x38) << 2);
        this.b2 = this.padComponent((paletteIndex & 0x7) << 5);

        this.barLuma = (Math.max(this.r2, Math.max(this.g2, this.b2)) < 64) ? 255 : 0;
    }

    /**
     * Pad LSB with 1's if any MSB are 1 (effectively a bitwise ceil() function)
     * 
     * @param component
     */
    private int padComponent(int component)
    {
        return (component > 0x1F) ? component | 0x1F : component;
    }

    private DynamicTexture loadTexture(IResourceManager resourceManager, ResourceLocation textureLocation) throws IOException
    {
        InputStream inputStream = null;

        try
        {
            IResource resource = resourceManager.getResource(textureLocation);
            inputStream = resource.getInputStream();
            BufferedImage image = ImageIO.read(inputStream);
            return new DynamicTexture(image);
        }
        finally
        {
            if (inputStream != null)
            {
                inputStream.close();
            }
        }
    }
}