This commit is contained in:
Alexander Xia committed 2016-02-05 13:11:12 +08:00
1 parent d8518588f2
commit 09010f7fe5
5 files changed
+881

No files matched your search

@@ -0,0 +1,361 @@
package idv.jlchntoz;
import net.minecraft.client.Minecraft;
import java.io.*;
import java.math.BigInteger;
import java.net.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.logging.*;
import java.util.regex.*;
/**
* Custom skin loader mod for Minecraft.
*
* @version 12th Revision 8th Subversion 2016.2.3
*
* @author (C) Jeremy Lam [JLChnToZ] 2013 & Alexander Xia [xfl03] 2014-2016
*/
public class CustomSkinLoader {
public final static String VERSION="12.8";
public final static String DefaultSkinURL = "http://skins.minecraft.net/MinecraftSkins/*.png";
public final static String DefaultCloakURL = "http://skins.minecraft.net/MinecraftCloaks/*.png";
private final static Pattern newResPattern = Pattern.compile("^http://textures.minecraft.net/texture/(.*?)?(Skin|Cloak)=(.*?)$"),
newURLPattern = Pattern.compile("^http://skins.minecraft.net/Minecraft(Skin|Cloak)s/(.*?).png$"),
oldURLPattern = Pattern.compile("^http://s3.amazonaws.com/Minecraft(Skin|Cloak)s/(.*?).png$"),
optifineCapeURLPattern = Pattern.compile("^http://s.optifine.net/capes/(.*?).png$");
public final static File DATA_DIR=new File(Minecraft.getMinecraft().mcDataDir,"CustomSkinLoader"),
CACHE_DIR=new File(DATA_DIR,"caches"),
LOG_FILE=new File(DATA_DIR,"CustomSkinLoader.log"),
SKIN_URL_FILE=new File(DATA_DIR,"skinurls.txt"),
CAPE_URL_FILE=new File(DATA_DIR,"capeurls.txt");
public final static MainLogger logger = getLogger(LOG_FILE);
public final static String[] DEFAULT_SKIN_URLS={
"http://skins.minecraft.net/MinecraftSkins/*.png",
"http://minecrack.fr.nf/mc/skinsminecrackd/*.png",
"http://www.skinme.cc/MinecraftSkins/*.png"};
public final static String[] DEFAULT_CAPE_URLS={
"http://skins.minecraft.net/MinecraftCloaks/*.png",
"http://s.optifine.net/capes/*.png",
"http://minecrack.fr.nf/mc/cloaksminecrackd/*.png",
"http://www.skinme.cc/MinecraftCloaks/*.png"};
private static String[] cloakURLs = null, skinURLs = null;
private HttpURLConnection C = null;
//Entrance
public InputStream getPlayerSkinStream(String path) {
if(!DATA_DIR.exists())
DATA_DIR.mkdir();
if(!CACHE_DIR.exists())
CACHE_DIR.mkdir();
logger.info("Get a request: "+path);
if(path.contains("NOCSL"))//Not to use CSL to load, prepared for json api
return getStream(path, false);
Matcher m = newURLPattern.matcher(path);
if (!m.matches())//Is not new url
{
m = oldURLPattern.matcher(path);//May be old url
}
if (m.matches()) {
if (m.group(1).contains("Skin")) // Skin
return getPlayerSkinStream(false, m.group(2));
else if (m.group(1).contains("Cloak")) // Cloak
return getPlayerSkinStream(true, m.group(2));
}else{
m = newResPattern.matcher(path);
if(m.matches()){
if (m.group(2).contains("Skin")) // Skin
return getPlayerSkinStream(false, m.group(3));
else if (m.group(2).contains("Cloak")) // Cloak
return getPlayerSkinStream(true, m.group(3));
}else{
m = optifineCapeURLPattern.matcher(path);
if(m.matches()){//Optifine Cape
logger.info("Ignore Optifine Cape.");
return null;//Not Load This
}
}
}
return getStream(path, false); // Neither skin nor cloak...
}
public InputStream getPlayerSkinStream(Boolean isCloak, String playerName) {
if (skinURLs == null || cloakURLs == null || skinURLs.length <= 0
|| cloakURLs.length <= 0)
refreshSkinURL(); // If the list is blank or null, try to load again.
InputStream S=null;
for (String l : isCloak ? cloakURLs : skinURLs) {
if(l==null||l.equalsIgnoreCase(""))
continue;
String loc = str_replace("*", playerName, l);
logger.log(Level.INFO, "Try to load " + (isCloak ? "cloak" : "skin") + " in " + loc);
S = getStream(loc, true);
if (S == null){
logger.log(Level.INFO, "No " + (isCloak ? "cloak" : "skin") + " found in " + loc);
}else{
logger.info("Succeessfully load " + (isCloak ? "cloak" : "skin") + " in " + loc);
return S;
}
}
logger.log(Level.INFO, "Try to load skin in default URL instead.");
return getStream(str_replace("*", playerName, isCloak ? DefaultCloakURL : DefaultSkinURL), true);
}
private InputStream getStream(String URL, Boolean CheckPNG) {
boolean success=false;
File cacheFile=new File(CACHE_DIR,MD5(URL));
boolean alreadyCached=false;
if(cacheFile.exists()&&cacheFile.length()>1){
alreadyCached=true;
logger.info("Cache File Found (LastModified: "+cacheFile.lastModified()+")");
}
try {
URL U = new URL(URL);
C = (HttpURLConnection) U.openConnection();
C.setReadTimeout(15000);
C.setDoInput(true);
C.setDoOutput(false);
C.connect();
logger.info("Response Code: "+C.getResponseCode());
int respcode = C.getResponseCode() / 100;
if (respcode != 4 && respcode != 5) { // Successful to get skin.
logger.info("Successfully Get Resource (LastModified: "+cacheFile.lastModified()+")");
if(alreadyCached && C.getLastModified()==cacheFile.lastModified()){
logger.info("Not Modified!");
return getStreamFromCache(cacheFile);
}
if(C.getContentLength()<=0){//Nothing to get
return null;
}
InputStream IS=new BufferedInputStream(C.getInputStream());
if (!CheckPNG){ // If no need to check PNG header, just skip it.
success=true;
saveToCache(IS,cacheFile);
return IS;
}
//logger.info(C.getContentLength()+" "+IS.available());
IS.mark(C.getContentLength()+10);
byte[] ib = new byte[4];
IS.read(ib);
if (ib[1] == (byte) 'P' && ib[2] == (byte) 'N' && ib[3] == (byte) 'G') { // Check PNG Header if needed
IS.reset();
success=true;
saveToCache(IS,cacheFile);
return IS;
}
}
} catch (Exception ex) {
success=false;
logger.log(Level.WARNING, ex.getMessage());
if(alreadyCached)
return getStreamFromCache(cacheFile);
}finally{
if(!success)
disconnect();
}
return null;
}
private InputStream getStreamFromCache(File cacheFile) {
try{
logger.info("Try load local cache in " + cacheFile.getAbsolutePath());
InputStream in = new FileInputStream(cacheFile);
BufferedInputStream bis=new BufferedInputStream(in);
if(bis.available()<=0){
logger.info("Cannot load local cache in " + cacheFile.getAbsolutePath());
return null;
}else{
logger.info("Successfully load cache in " + cacheFile.getAbsolutePath());
return bis;
}
}catch(Exception e){
logger.log(Level.WARNING, e.getMessage());
return null;
}
}
private void saveToCache(InputStream is,File to){
logger.info("Try save local cache to " + to.getAbsolutePath());
FileOutputStream fs=null;
int times=0;
try{//Save to Local Skin File
if(to.exists()){
to.delete();
}
fs = new FileOutputStream(to);
int byteRead = 0;
byte[] buffer = new byte[1024];
while (( byteRead = is.read(buffer)) != -1) {
times+=byteRead;
fs.write(buffer, 0, byteRead);
if(times>=C.getContentLength()){
//logger.info(times+" "+C.getContentLength());
break;
}
}
if(to.length()>1){
logger.info("Successfully save cache to " + to.getAbsolutePath());
}else{
to.delete();
logger.info("Cannot save local cache to " + to.getAbsolutePath());
}
}catch(Exception e){
logger.warning(e.getMessage());
}finally{
try {
if(fs!=null)
fs.close();
is.reset();
logger.info("Cache size : "+is.available());
if(to.exists()){
to.setLastModified(C.getLastModified());
logger.info("LastModified : "+to.lastModified());
}
} catch (IOException e) {
logger.warning(e.getMessage());
}
}
}
public void disconnect() {
if (C != null)
C.disconnect();
}
private static void refreshSkinURL() {
try {
if(!SKIN_URL_FILE.exists()){
logger.log(Level.INFO, "SKIN config not found, create a new one.");
SKIN_URL_FILE.createNewFile();
}
if(!CAPE_URL_FILE.exists()){
logger.log(Level.INFO, "CAPE config not found, create a new one.");
CAPE_URL_FILE.createNewFile();
}
skinURLs = readAllLines(SKIN_URL_FILE);
cloakURLs = readAllLines(CAPE_URL_FILE);
} catch (Exception ex) {
logger.log(Level.WARNING, ex.getMessage());
} finally {
if(skinURLs.length==0&&cloakURLs.length==0){
logger.info("No skinURLs and cloak URLS found, try to init and use default settings.");
initSkinURL();
refreshSkinURL();
}else{
logger.log(Level.INFO, "Skin URLs Refreshed. Skin count = "
+ skinURLs.length + ", Cloak count = " + cloakURLs.length);
}
}
}
private static void initSkinURL(){
//TODO Init URL List
skinURLs=DEFAULT_SKIN_URLS;
writeToFile(new File(DATA_DIR,"skinurls.txt"),parseArrayToText(skinURLs));
cloakURLs=DEFAULT_CAPE_URLS;
writeToFile(new File(DATA_DIR,"capeurls.txt"),parseArrayToText(cloakURLs));
}
private static String[] readAllLines(File F) {
try {
logger.log(Level.INFO, "Config file: " + F.getAbsolutePath());
if (F.length() <= 0) {
logger.log(Level.INFO, "Config file is blank, skipped.");
return new String[0];
} else {
byte[] b = new byte[(int) F.length()];
BufferedInputStream S = new BufferedInputStream(
new FileInputStream(F));
S.read(b);
S.close();
logger.log(Level.INFO, "Config file loaded.");
String[] re= str_replace("\r", "\n",
str_replace("\r\n", "\n", new String(b))).split("\n");
for(int i=0;i<re.length;i++){
if(re[i].startsWith("#"))//Remove note
re[i]=null;
else{//Remove same URL
for(int g=0;g<re.length;g++){
if(i==g)
continue;
if(re[i].equalsIgnoreCase(re[g])){
re[i]=null;
break;
}
}
}
}
return re;
}
} catch (Exception ex) {
logger.log(Level.WARNING, ex.getMessage());
return new String[0];
}
}
private static String str_replace(String search, String replace,
String subject) {
StringBuffer result = new StringBuffer(subject);
int pos;
while ((pos = result.indexOf(search)) != -1)
result.replace(pos, pos + search.length(), replace);
return result.toString();
}
private static String parseArrayToText(String[] data){
StringBuilder temp=new StringBuilder();
for(int i=0;i<data.length-1;i++)
temp.append(data[i]).append("\r\n");
temp.append(data[data.length-1]);
return temp.toString();
}
private static boolean writeToFile(File file,String Data){
System.out.print("Write to "+file.getAbsolutePath()+" ");
FileWriter fw=null;
try{
fw = new FileWriter(file);
fw.write(Data,0,Data.length());
fw.flush();
fw.close();
}catch(Exception ex){
ex.printStackTrace();
System.out.println("failed.");
return false;
}
System.out.println("succeed.");
return true;
}
public String MD5(String str){
byte [] buf = str.getBytes();
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
md5.update(buf);
byte [] tmp = md5.digest();
StringBuilder sb = new StringBuilder();
for (byte b:tmp) {
sb.append(Integer.toHexString(b&0xff));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
logger.warning(e.getMessage());
}
return "Fail";
}
private static MainLogger getLogger(File logFile){
MainLogger mainLogger = new MainLogger(logFile);
mainLogger.info("CustomSkinLoader " + VERSION);
return mainLogger;
}
}
@@ -0,0 +1,71 @@
package idv.jlchntoz;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
public class MainLogger {
private static final int LOWEST_DISPLAY_LEVEL=Level.INFO.intValue();
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private BufferedWriter writer;
public MainLogger(File logFile){
try {
if(!logFile.getParentFile().exists()){
logFile.getParentFile().mkdirs();
}
if(!logFile.exists())
logFile.createNewFile();
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(logFile), "UTF-8"));
} catch (Exception e) {
e.printStackTrace();
}
}
public void close(){
if(writer!=null){
try {
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void log(Level level,String msg){
if(level.intValue()>=LOWEST_DISPLAY_LEVEL)
System.out.println(msg);
try {
writer.write("[");
writer.write(DATE_FORMAT.format(new Date()));
writer.write(" ");
writer.write(Thread.currentThread().getName());
writer.write(" ");
writer.write(level.getName());
writer.write("] ");
writer.write(msg);
writer.write("\r\n");
writer.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public void info(String msg){
log(Level.INFO,msg);
}
public void warning(String msg){
log(Level.WARNING,msg);
}
public void warning(Exception e){
log(Level.WARNING,"Exception occurs while running: "+e.getMessage());
StackTraceElement[] stes=e.getStackTrace();
for(StackTraceElement ste : stes){
log(Level.WARNING,ste.toString());
}
log(Level.WARNING,"");
}
}
@@ -0,0 +1,117 @@
package net.minecraft.client.renderer;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
import java.awt.image.ImageObserver;
public class ImageBufferDownload implements IImageBuffer
{
private int[] imageData;
private int imageWidth;
private int imageHeight;
public BufferedImage parseUserSkin(BufferedImage image)
{
if (image == null)
{
return null;
}
else
{
int ratio=image.getWidth()/64;
this.imageWidth = 64 * ratio;
this.imageHeight = 64 * ratio;
BufferedImage var2 = new BufferedImage(this.imageWidth, this.imageHeight, 2);
Graphics var3 = var2.getGraphics();
var3.drawImage(image, 0, 0, (ImageObserver)null);
if (image.getHeight() == 32 * ratio)
{
var3.drawImage(var2, 24 * ratio, 48 * ratio, 20 * ratio, 52 * ratio, 4 * ratio, 16 * ratio, 8 * ratio, 20 * ratio, (ImageObserver)null);
var3.drawImage(var2, 28 * ratio, 48 * ratio, 24 * ratio, 52 * ratio, 8 * ratio, 16 * ratio, 12 * ratio, 20 * ratio, (ImageObserver)null);
var3.drawImage(var2, 20 * ratio, 52 * ratio, 16 * ratio, 64 * ratio, 8 * ratio, 20 * ratio, 12 * ratio, 32 * ratio, (ImageObserver)null);
var3.drawImage(var2, 24 * ratio, 52 * ratio, 20 * ratio, 64 * ratio, 4 * ratio, 20 * ratio, 8 * ratio, 32 * ratio, (ImageObserver)null);
var3.drawImage(var2, 28 * ratio, 52 * ratio, 24 * ratio, 64 * ratio, 0 * ratio, 20 * ratio, 4 * ratio, 32 * ratio, (ImageObserver)null);
var3.drawImage(var2, 32 * ratio, 52 * ratio, 28 * ratio, 64 * ratio, 12 * ratio, 20 * ratio, 16 * ratio, 32 * ratio, (ImageObserver)null);
var3.drawImage(var2, 40 * ratio, 48 * ratio, 36 * ratio, 52 * ratio, 44 * ratio, 16 * ratio, 48 * ratio, 20 * ratio, (ImageObserver)null);
var3.drawImage(var2, 44 * ratio, 48 * ratio, 40 * ratio, 52 * ratio, 48 * ratio, 16 * ratio, 52 * ratio, 20 * ratio, (ImageObserver)null);
var3.drawImage(var2, 36 * ratio, 52 * ratio, 32 * ratio, 64 * ratio, 48 * ratio, 20 * ratio, 52 * ratio, 32 * ratio, (ImageObserver)null);
var3.drawImage(var2, 40 * ratio, 52 * ratio, 36 * ratio, 64 * ratio, 44 * ratio, 20 * ratio, 48 * ratio, 32 * ratio, (ImageObserver)null);
var3.drawImage(var2, 44 * ratio, 52 * ratio, 40 * ratio, 64 * ratio, 40 * ratio, 20 * ratio, 44 * ratio, 32 * ratio, (ImageObserver)null);
var3.drawImage(var2, 48 * ratio, 52 * ratio, 44 * ratio, 64 * ratio, 52 * ratio, 20 * ratio, 56 * ratio, 32 * ratio, (ImageObserver)null);
}
var3.dispose();
this.imageData = ((DataBufferInt)var2.getRaster().getDataBuffer()).getData();
this.setAreaOpaque(0, 0, 32 * ratio, 16 * ratio);
this.setAreaTransparent(32 * ratio, 0, 64 * ratio, 32 * ratio);
this.setAreaOpaque(0, 16 * ratio, 64 * ratio, 32 * ratio);
this.setAreaTransparent(0, 32 * ratio, 16 * ratio, 48 * ratio);
this.setAreaTransparent(16 * ratio, 32 * ratio, 40 * ratio, 48 * ratio);
this.setAreaTransparent(40 * ratio, 32 * ratio, 56 * ratio, 48 * ratio);
this.setAreaTransparent(0, 48 * ratio, 16 * ratio, 64 * ratio);
this.setAreaOpaque(16 * ratio, 48 * ratio, 48 * ratio, 64 * ratio);
this.setAreaTransparent(48 * ratio, 48 * ratio, 64 * ratio, 64 * ratio);
return var2;
}
}
public void skinAvailable()
{
}
/**
* Makes the given area of the image transparent if it was previously completely opaque (used to remove the outer
* layer of a skin around the head if it was saved all opaque; this would be redundant so it's assumed that the skin
* maker is just using an image editor without an alpha channel)
*/
private void setAreaTransparent(int p_78434_1_, int p_78434_2_, int p_78434_3_, int p_78434_4_)
{
if (!this.hasTransparency(p_78434_1_, p_78434_2_, p_78434_3_, p_78434_4_))
{
for (int i = p_78434_1_; i < p_78434_3_; ++i)
{
for (int j = p_78434_2_; j < p_78434_4_; ++j)
{
this.imageData[i + j * this.imageWidth] &= 16777215;
}
}
}
}
/**
* Makes the given area of the image opaque
*/
private void setAreaOpaque(int p_78433_1_, int p_78433_2_, int p_78433_3_, int p_78433_4_)
{
for (int i = p_78433_1_; i < p_78433_3_; ++i)
{
for (int j = p_78433_2_; j < p_78433_4_; ++j)
{
this.imageData[i + j * this.imageWidth] |= -16777216;
}
}
}
/**
* Returns true if the given area of the image contains transparent pixels
*/
private boolean hasTransparency(int p_78435_1_, int p_78435_2_, int p_78435_3_, int p_78435_4_)
{
for (int i = p_78435_1_; i < p_78435_3_; ++i)
{
for (int j = p_78435_2_; j < p_78435_4_; ++j)
{
int k = this.imageData[i + j * this.imageWidth];
if ((k >> 24 & 255) < 128)
{
return true;
}
}
}
return false;
}
}
@@ -0,0 +1,148 @@
package net.minecraft.client.renderer;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.atomic.AtomicInteger;
import javax.imageio.ImageIO;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.texture.SimpleTexture;
import net.minecraft.client.renderer.texture.TextureUtil;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import idv.jlchntoz.CustomSkinLoader;
public class ThreadDownloadImageData extends SimpleTexture
{
private static final Logger logger = LogManager.getLogger();
private static final AtomicInteger threadDownloadCounter = new AtomicInteger(0);
private final File cacheFile;
private final String imageUrl;
private final IImageBuffer imageBuffer;
private BufferedImage bufferedImage;
private Thread imageThread;
private boolean textureUploaded;
//For Optifine
public Boolean imageFound = null;
public boolean pipeline = false;
public ThreadDownloadImageData(File cacheFileIn, String imageUrlIn, ResourceLocation textureResourceLocation, IImageBuffer imageBufferIn)
{
super(textureResourceLocation);
this.cacheFile = cacheFileIn;
this.imageUrl = imageUrlIn;
this.imageBuffer = imageBufferIn;
}
private void checkTextureUploaded()
{
if (!this.textureUploaded)
{
if (this.bufferedImage != null)
{
if (this.textureLocation != null)
{
this.deleteGlTexture();
}
TextureUtil.uploadTextureImage(super.getGlTextureId(), this.bufferedImage);
this.textureUploaded = true;
}
}
}
public int getGlTextureId()
{
this.checkTextureUploaded();
return super.getGlTextureId();
}
public void setBufferedImage(BufferedImage bufferedImageIn)
{
this.bufferedImage = bufferedImageIn;
if (this.imageBuffer != null)
{
this.imageBuffer.skinAvailable();
}
}
public void loadTexture(IResourceManager resourceManager) throws IOException
{
if (this.bufferedImage == null && this.textureLocation != null)
{
super.loadTexture(resourceManager);
}
if (this.imageThread == null)
{
if (this.cacheFile != null && this.cacheFile.isFile())
{
logger.info("Loading http texture from local cache ({})", new Object[] {this.cacheFile});
try
{
this.bufferedImage = ImageIO.read(this.cacheFile);
if (this.imageBuffer != null)
{
this.setBufferedImage(this.imageBuffer.parseUserSkin(this.bufferedImage));
}
}
catch (IOException ioexception)
{
logger.error((String)("Couldn\'t load skin " + this.cacheFile), (Throwable)ioexception);
this.loadTextureFromServer();
}
}
else
{
this.loadTextureFromServer();
}
}
}
protected void loadTextureFromServer()
{
this.imageThread = new Thread("Texture Downloader #" + threadDownloadCounter.incrementAndGet())
{
public void run()
{
CustomSkinLoader loader=new CustomSkinLoader();
ThreadDownloadImageData.logger.info("Downloading http texture from {} to {}", new Object[] {ThreadDownloadImageData.this.imageUrl, ThreadDownloadImageData.this.cacheFile});
try
{
BufferedImage bufferedimage;
bufferedimage = TextureUtil.readBufferedImage(loader.getPlayerSkinStream(ThreadDownloadImageData.this.imageUrl));
if (ThreadDownloadImageData.this.imageBuffer != null)
{
bufferedimage = ThreadDownloadImageData.this.imageBuffer.parseUserSkin(bufferedimage);
}
ThreadDownloadImageData.this.setBufferedImage(bufferedimage);
return;
}
catch (Exception exception)
{
ThreadDownloadImageData.logger.error((String)"Couldn\'t download http texture", (Throwable)exception);
return;
}
finally
{
loader.disconnect();
}
}
};
this.imageThread.setDaemon(true);
this.imageThread.start();
}
}
@@ -0,0 +1,184 @@
package net.minecraft.client.resources;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Maps;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.minecraft.InsecureTextureException;
import com.mojang.authlib.minecraft.MinecraftProfileTexture;
import com.mojang.authlib.minecraft.MinecraftSessionService;
import com.mojang.authlib.minecraft.MinecraftProfileTexture.Type;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.IImageBuffer;
import net.minecraft.client.renderer.ImageBufferDownload;
import net.minecraft.client.renderer.ThreadDownloadImageData;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.util.ResourceLocation;
public class SkinManager
{
private static final ExecutorService THREAD_POOL = new ThreadPoolExecutor(0, 2, 1L, TimeUnit.MINUTES, new LinkedBlockingQueue());
private final TextureManager textureManager;
private final File skinCacheDir;
private final MinecraftSessionService sessionService;
private final LoadingCache<GameProfile, Map<Type, MinecraftProfileTexture>> skinCacheLoader;
public SkinManager(TextureManager textureManagerInstance, File skinCacheDirectory, MinecraftSessionService sessionService)
{
this.textureManager = textureManagerInstance;
this.skinCacheDir = skinCacheDirectory;
this.sessionService = sessionService;
this.skinCacheLoader = CacheBuilder.newBuilder().expireAfterAccess(15L, TimeUnit.SECONDS).<GameProfile, Map<Type, MinecraftProfileTexture>>build(new CacheLoader<GameProfile, Map<Type, MinecraftProfileTexture>>()
{
public Map<Type, MinecraftProfileTexture> load(GameProfile p_load_1_) throws Exception
{
return Minecraft.getMinecraft().getSessionService().getTextures(p_load_1_, false);
}
});
}
/**
* Used in the Skull renderer to fetch a skin. May download the skin if it's not in the cache
*/
public ResourceLocation loadSkin(MinecraftProfileTexture profileTexture, Type p_152792_2_)
{
return this.loadSkin(profileTexture, p_152792_2_, (SkinManager.SkinAvailableCallback)null);
}
/**
* May download the skin if its not in the cache, can be passed a SkinManager#SkinAvailableCallback for handling
*/
public ResourceLocation loadSkin(final MinecraftProfileTexture profileTexture, final Type p_152789_2_, final SkinManager.SkinAvailableCallback skinAvailableCallback)
{
final ResourceLocation resourcelocation = new ResourceLocation(p_152789_2_.name() + "/" + profileTexture.getHash());
/*Remove cache
ITextureObject itextureobject = this.textureManager.getTexture(resourcelocation);
if (itextureobject != null)
{
if (skinAvailableCallback != null)
{
skinAvailableCallback.skinAvailable(p_152789_2_, resourcelocation, profileTexture);
}
}
else
{*/
File file1 = new File(this.skinCacheDir, profileTexture.getHash().length() > 2 ? profileTexture.getHash().substring(0, 2) : "xx");
File file2 = new File(file1, profileTexture.getHash());
final IImageBuffer iimagebuffer = p_152789_2_ == Type.SKIN ? new ImageBufferDownload() : null;
ThreadDownloadImageData threaddownloadimagedata = new ThreadDownloadImageData(file2, profileTexture.getUrl(), DefaultPlayerSkin.getDefaultSkinLegacy(), new IImageBuffer()
{
public BufferedImage parseUserSkin(BufferedImage image)
{
if (iimagebuffer != null)
{
image = iimagebuffer.parseUserSkin(image);
}
return image;
}
public void skinAvailable()
{
if (iimagebuffer != null)
{
iimagebuffer.skinAvailable();
}
if (skinAvailableCallback != null)
{
skinAvailableCallback.skinAvailable(p_152789_2_, resourcelocation, profileTexture);
}
}
});
this.textureManager.loadTexture(resourcelocation, threaddownloadimagedata);
//}
return resourcelocation;
}
public void loadProfileTextures(final GameProfile profile, final SkinManager.SkinAvailableCallback skinAvailableCallback, final boolean requireSecure)
{
THREAD_POOL.submit(new Runnable()
{
public void run()
{
final Map<Type, MinecraftProfileTexture> map = Maps.<Type, MinecraftProfileTexture>newHashMap();
try
{
map.putAll(SkinManager.this.sessionService.getTextures(profile, requireSecure));
}
catch (InsecureTextureException var3)
{
;
}
if (map.isEmpty() && profile.getId().equals(Minecraft.getMinecraft().getSession().getProfile().getId()))
{
profile.getProperties().clear();
profile.getProperties().putAll(Minecraft.getMinecraft().func_181037_M());
map.putAll(SkinManager.this.sessionService.getTextures(profile, false));
}
//CustomSkinLoader Begin
Map<Type, MinecraftProfileTexture> var2 = Maps.<Type, MinecraftProfileTexture>newHashMap();
if (map.containsKey(Type.SKIN)){
MinecraftProfileTexture var3=((MinecraftProfileTexture)map.get(Type.SKIN));
String var4=var3.getMetadata("model");
Map var5 = null;
if(var4!=null){
var5 = Maps.newHashMap();
var5.put("model", var4);
}
var2.put(Type.SKIN, new MinecraftProfileTexture(var3.getUrl()+"?Skin="+profile.getName(),var5));
}else{
Map var5 = Maps.newHashMap();
//var5.put("model", "slim");
var2.put(Type.SKIN,new MinecraftProfileTexture( "http://skins.minecraft.net/MinecraftSkins/"+profile.getName()+".png",var5));
}
if (map.containsKey(Type.CAPE)){
var2.put(Type.CAPE, new MinecraftProfileTexture(((MinecraftProfileTexture)map.get(Type.CAPE)).getUrl()+"?Cloak="+profile.getName(),null));
}else{
var2.put(Type.CAPE,new MinecraftProfileTexture( "http://skins.minecraft.net/MinecraftCloaks/"+profile.getName()+".png",null));
}
map.clear();
map.putAll(var2);
//CustomSkinLoader End
Minecraft.getMinecraft().addScheduledTask(new Runnable()
{
public void run()
{
if (map.containsKey(Type.SKIN))
{
SkinManager.this.loadSkin((MinecraftProfileTexture)map.get(Type.SKIN), Type.SKIN, skinAvailableCallback);
}
if (map.containsKey(Type.CAPE))
{
SkinManager.this.loadSkin((MinecraftProfileTexture)map.get(Type.CAPE), Type.CAPE, skinAvailableCallback);
}
}
});
}
});
}
public Map<Type, MinecraftProfileTexture> loadSkinFromCache(GameProfile profile)
{
return (Map)this.skinCacheLoader.getUnchecked(profile);
}
public interface SkinAvailableCallback
{
void skinAvailable(Type p_180521_1_, ResourceLocation location, MinecraftProfileTexture profileTexture);
}
}