Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ME] Fix mipmap calculation in WebP #268

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 19 additions & 11 deletions src/Shared.TextureContainer/WebP/Texture2DExt.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
//https://github.com/octo-code/webp-unity3d
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;

using UnityEngine;

using WebP.Extern;

namespace WebP
Expand Down Expand Up @@ -112,13 +108,8 @@ public static unsafe byte[] LoadRGBAFromWebP(byte[] lData, ref int lWidth, ref i
{
scalingFunction(ref lWidth, ref lHeight);
}

// If mipmaps are requested we need to create 1/3 more memory for the mipmaps to be generated in.
int numBytesRequired = lWidth * lHeight * 4;
if (lMipmaps)
{
numBytesRequired = Mathf.CeilToInt((numBytesRequired * 4.0f) / 3.0f);
}

int numBytesRequired = CalculateTextureBytes(lWidth, lHeight, lMipmaps);

lRawData = new byte[numBytesRequired];
fixed (byte* lRawDataPtr = lRawData)
Expand Down Expand Up @@ -276,5 +267,22 @@ public static unsafe byte[] EncodeToWebP(this Texture2D lTexture2D, float lQuali

return lOutputBuffer;
}

internal static int CalculateTextureBytes(int width, int height, bool mipmap)
{
int bytes = width * height * 4;

if (!mipmap)
return bytes;

while (width > 1 || height > 1)
{
width = (width + 1) >> 1;
height = (height + 1) >> 1;
bytes += width * height * 4;
}

return bytes;
}
}
}