PageRenderTime 538ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/modLoader/release/sources/ModLoader.java

https://code.google.com/p/minecraft-smp-mocreatures/
Java | 1202 lines | 1112 code | 90 blank | 0 comment | 223 complexity | effc2afcfa473def864cc5f7eb6d627d MD5 | raw file
  1. import java.awt.image.BufferedImage;
  2. import java.io.BufferedInputStream;
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileOutputStream;
  7. import java.io.IOException;
  8. import java.io.InputStream;
  9. import java.io.OutputStream;
  10. import java.lang.reflect.Field;
  11. import java.lang.reflect.InvocationTargetException;
  12. import java.lang.reflect.Method;
  13. import java.net.URL;
  14. import java.net.URLClassLoader;
  15. import java.util.ArrayList;
  16. import java.util.Arrays;
  17. import java.util.Collections;
  18. import java.util.HashMap;
  19. import java.util.HashSet;
  20. import java.util.LinkedList;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Properties;
  24. import java.util.logging.FileHandler;
  25. import java.util.logging.Level;
  26. import java.util.logging.Logger;
  27. import java.util.logging.SimpleFormatter;
  28. import java.util.zip.ZipEntry;
  29. import java.util.zip.ZipInputStream;
  30. import javax.imageio.ImageIO;
  31. import net.minecraft.client.Minecraft;
  32. import org.lwjgl.input.Keyboard;
  33. public final class ModLoader
  34. {
  35. private static final List<av> animList = new LinkedList<av>();
  36. private static final Map<Integer, BaseMod> blockModels = new HashMap<Integer, BaseMod>();
  37. private static final Map<Integer, Boolean> blockSpecialInv = new HashMap<Integer, Boolean>();
  38. private static final File cfgdir = new File(Minecraft.b(), "/config/");
  39. private static final File cfgfile = new File(cfgdir, "ModLoader.cfg");
  40. public static Level cfgLoggingLevel = Level.FINER;
  41. private static Map<String, Class<? extends si>> classMap = null;
  42. private static long clock = 0L;
  43. public static final boolean DEBUG = false;
  44. private static Field field_animList = null;
  45. private static Field field_armorList = null;
  46. private static Field field_blockList = null;
  47. private static Field field_modifiers = null;
  48. private static Field field_TileEntityRenderers = null;
  49. private static boolean hasInit = false;
  50. private static int highestEntityId = 3000;
  51. private static final Map<BaseMod, Boolean> inGameHooks = new HashMap<BaseMod, Boolean>();
  52. private static final Map<BaseMod, Boolean> inGUIHooks = new HashMap<BaseMod, Boolean>();
  53. private static Minecraft instance = null;
  54. private static int itemSpriteIndex = 0;
  55. private static int itemSpritesLeft = 0;
  56. private static final Map<BaseMod, Map<px, boolean[]>> keyList = new HashMap<BaseMod, Map<px, boolean[]>>();
  57. private static final File logfile = new File(Minecraft.b(), "ModLoader.txt");
  58. private static final File modDir = new File(Minecraft.b(), "/mods/");
  59. private static final Logger logger = Logger.getLogger("ModLoader");
  60. private static FileHandler logHandler = null;
  61. private static Method method_RegisterEntityID = null;
  62. private static Method method_RegisterTileEntity = null;
  63. private static final Map<String, BaseMod> modList = new HashMap<String, BaseMod>();
  64. private static int nextBlockModelID = 1000;
  65. private static final Map<Integer, Map<String, Integer>> overrides = new HashMap<Integer, Map<String, Integer>>();
  66. public static final Properties props = new Properties();
  67. private static jz[] standardBiomes;
  68. private static int terrainSpriteIndex = 0;
  69. private static int terrainSpritesLeft = 0;
  70. private static String texPack = null;
  71. private static boolean texturesAdded = false;
  72. private static final boolean[] usedItemSprites = new boolean[256];
  73. private static final boolean[] usedTerrainSprites = new boolean[256];
  74. public static final String VERSION = "ModLoader Beta 1.6.6";
  75. public static void AddAchievementDesc(nu achievement, String name, String description)
  76. {
  77. try
  78. {
  79. if (achievement.f.contains(".")) {
  80. String key = achievement.f.split("\\.")[1];
  81. AddLocalization("achievement." + key, name);
  82. AddLocalization("achievement." + key + ".desc", description);
  83. setPrivateValue(vj.class, achievement, 1, dm.a("achievement." + key));
  84. setPrivateValue(nu.class, achievement, 3, dm.a("achievement." + key + ".desc"));
  85. } else {
  86. setPrivateValue(vj.class, achievement, 1, name);
  87. setPrivateValue(nu.class, achievement, 3, description);
  88. }
  89. } catch (IllegalArgumentException e) {
  90. logger.throwing("ModLoader", "AddAchievementDesc", e);
  91. ThrowException(e);
  92. } catch (SecurityException e) {
  93. logger.throwing("ModLoader", "AddAchievementDesc", e);
  94. ThrowException(e);
  95. } catch (NoSuchFieldException e) {
  96. logger.throwing("ModLoader", "AddAchievementDesc", e);
  97. ThrowException(e);
  98. }
  99. }
  100. public static int AddAllFuel(int id)
  101. {
  102. logger.finest("Finding fuel for " + id);
  103. int result = 0;
  104. for (BaseMod mod : modList.values())
  105. {
  106. if ((result = mod.AddFuel(id)) == 0)
  107. {
  108. logger.finest("Returned " + result);
  109. break;
  110. }
  111. }
  112. return result;
  113. }
  114. public static void AddAllRenderers(Map<Class<? extends si>, bu> o)
  115. {
  116. if (!hasInit) {
  117. init();
  118. logger.fine("Initialized");
  119. }
  120. for (BaseMod mod : modList.values())
  121. mod.AddRenderer(o);
  122. }
  123. public static void addAnimation(av anim)
  124. {
  125. logger.finest("Adding animation " + anim.toString());
  126. for (av oldAnim : animList)
  127. {
  128. if (oldAnim.b != anim.b)
  129. continue;
  130. animList.remove(anim);
  131. break;
  132. }
  133. animList.add(anim);
  134. }
  135. public static int AddArmor(String armor)
  136. {
  137. try
  138. {
  139. String[] existingArmor = (String[])field_armorList.get(null);
  140. List<String> existingArmorList = Arrays.asList(existingArmor);
  141. List<String> combinedList = new ArrayList<String>();
  142. combinedList.addAll(existingArmorList);
  143. if (!combinedList.contains(armor))
  144. combinedList.add(armor);
  145. int index = combinedList.indexOf(armor);
  146. field_armorList.set(null, combinedList.toArray(new String[0]));
  147. return index;
  148. } catch (IllegalArgumentException e) {
  149. logger.throwing("ModLoader", "AddArmor", e);
  150. ThrowException("An impossible error has occured!", e);
  151. } catch (IllegalAccessException e) {
  152. logger.throwing("ModLoader", "AddArmor", e);
  153. ThrowException("An impossible error has occured!", e);
  154. }
  155. return -1;
  156. }
  157. public static void AddLocalization(String key, String value)
  158. {
  159. Properties props = null;
  160. try {
  161. props = (Properties)getPrivateValue(nd.class, nd.a(), 1);
  162. } catch (SecurityException e) {
  163. logger.throwing("ModLoader", "AddLocalization", e);
  164. ThrowException(e);
  165. } catch (NoSuchFieldException e) {
  166. logger.throwing("ModLoader", "AddLocalization", e);
  167. ThrowException(e);
  168. }
  169. if (props != null)
  170. props.put(key, value);
  171. }
  172. private static void addMod(ClassLoader classLoader, String className, String classFullName)
  173. {
  174. try
  175. {
  176. classFullName = classFullName.substring(0, classFullName.lastIndexOf('.'));
  177. if(!classFullName.contains("$") && (!props.containsKey(className) || (!props.getProperty(className).equalsIgnoreCase("no") && !props.getProperty(className).equalsIgnoreCase("off"))))
  178. {
  179. Class modClass = classLoader.loadClass(classFullName);
  180. if(BaseMod.class.isAssignableFrom(modClass))
  181. {
  182. setupProperties(modClass);
  183. BaseMod mod = (BaseMod)modClass.newInstance();
  184. String modName = mod.toString();
  185. if(mod != null && !modList.containsKey(modName))
  186. {
  187. modList.put(modName, mod);
  188. logger.fine((new StringBuilder("Mod Loaded: \"")).append(modName).append("\" from ").append(className).toString());
  189. System.out.println("Mod Loaded: " + modName);
  190. }
  191. }
  192. }
  193. }
  194. catch(Throwable e)
  195. {
  196. logger.fine((new StringBuilder("Failed to load mod from \"")).append(className).append("\"").toString());
  197. System.out.println((new StringBuilder("Failed to load mod from \"")).append(className).append("\"").toString());
  198. logger.throwing("ModLoader", "addMod", e);
  199. ThrowException(e);
  200. }
  201. }
  202. private static void setupProperties(Class<? extends BaseMod> mod) throws IllegalArgumentException, IllegalAccessException, IOException, SecurityException, NoSuchFieldException
  203. {
  204. Properties modprops = new Properties();
  205. File modcfgfile = new File(cfgdir, mod.getName() + ".cfg");
  206. if ((modcfgfile.exists()) && (modcfgfile.canRead())) {
  207. modprops.load(new FileInputStream(modcfgfile));
  208. }
  209. StringBuilder helptext = new StringBuilder();
  210. for (Field field : mod.getFields()) {
  211. if (((field.getModifiers() & 0x8) != 0) && (field.isAnnotationPresent(MLProp.class))) {
  212. Class type = field.getType();
  213. MLProp annotation = field.getAnnotation(MLProp.class);
  214. String key = annotation.name().length() == 0 ? field.getName() : annotation.name();
  215. Object currentvalue = field.get(null);
  216. StringBuilder range = new StringBuilder();
  217. if (annotation.min() != (-1.0D / 0.0D))
  218. range.append(String.format(",>=%.1f", new Object[] { Double.valueOf(annotation.min()) }));
  219. if (annotation.max() != (1.0D / 0.0D)) {
  220. range.append(String.format(",<=%.1f", new Object[] { Double.valueOf(annotation.max()) }));
  221. }
  222. StringBuilder info = new StringBuilder();
  223. if (annotation.info().length() > 0) {
  224. info.append(" -- ");
  225. info.append(annotation.info());
  226. }
  227. helptext.append(String.format("%s (%s:%s%s)%s\n", new Object[] { key, type.getName(), currentvalue, range, info }));
  228. if (modprops.containsKey(key)) {
  229. String strvalue = modprops.getProperty(key);
  230. Object value = null;
  231. if (type.isAssignableFrom(String.class)) value = strvalue;
  232. else if (type.isAssignableFrom(Integer.TYPE)) value = Integer.valueOf(Integer.parseInt(strvalue));
  233. else if (type.isAssignableFrom(Short.TYPE)) value = Short.valueOf(Short.parseShort(strvalue));
  234. else if (type.isAssignableFrom(Byte.TYPE)) value = Byte.valueOf(Byte.parseByte(strvalue));
  235. else if (type.isAssignableFrom(Boolean.TYPE)) value = Boolean.valueOf(Boolean.parseBoolean(strvalue));
  236. else if (type.isAssignableFrom(Float.TYPE)) value = Float.valueOf(Float.parseFloat(strvalue));
  237. else if (type.isAssignableFrom(Double.TYPE)) {
  238. value = Double.valueOf(Double.parseDouble(strvalue));
  239. }
  240. if (value != null) {
  241. if ((value instanceof Number)) {
  242. double num = ((Number)value).doubleValue();
  243. if ((annotation.min() != (-1.0D / 0.0D)) && (num < annotation.min()))
  244. continue;
  245. if ((annotation.max() != (1.0D / 0.0D)) && (num > annotation.max())) {
  246. continue;
  247. }
  248. }
  249. logger.finer(key + " set to " + value);
  250. if (!value.equals(currentvalue))
  251. field.set(null, value);
  252. }
  253. } else {
  254. logger.finer(key + " not in config, using default: " + currentvalue);
  255. modprops.setProperty(key, currentvalue.toString());
  256. }
  257. }
  258. }
  259. if ((!modprops.isEmpty()) && ((modcfgfile.exists()) || (modcfgfile.createNewFile())) && (modcfgfile.canWrite()))
  260. modprops.store(new FileOutputStream(modcfgfile), helptext.toString());
  261. }
  262. public static void AddName(Object instance, String name)
  263. {
  264. String tag = null;
  265. if ((instance instanceof gk)) {
  266. gk item = (gk)instance;
  267. if (item.a() != null)
  268. tag = item.a() + ".name";
  269. } else if ((instance instanceof un)) {
  270. un block = (un)instance;
  271. if (block.k() != null)
  272. tag = block.k() + ".name";
  273. } else if ((instance instanceof iw)) {
  274. iw stack = (iw)instance;
  275. if (stack.l() != null)
  276. tag = stack.l() + ".name";
  277. } else {
  278. Exception e = new Exception(instance.getClass().getName() + " cannot have name attached to it!");
  279. logger.throwing("ModLoader", "AddName", e);
  280. ThrowException(e);
  281. }
  282. if (tag != null) {
  283. AddLocalization(tag, name);
  284. } else {
  285. Exception e = new Exception(instance + " is missing name tag!");
  286. logger.throwing("ModLoader", "AddName", e);
  287. ThrowException(e);
  288. }
  289. }
  290. public static int addOverride(String fileToOverride, String fileToAdd)
  291. {
  292. try
  293. {
  294. int i = getUniqueSpriteIndex(fileToOverride);
  295. addOverride(fileToOverride, fileToAdd, i);
  296. return i;
  297. } catch (Throwable e) {
  298. logger.throwing("ModLoader", "addOverride", e);
  299. ThrowException(e);
  300. throw new RuntimeException(e);
  301. }
  302. }
  303. public static void addOverride(String path, String overlayPath, int index)
  304. {
  305. int dst = -1;
  306. int left = 0;
  307. if (path.equals("/terrain.png")) {
  308. dst = 0;
  309. left = terrainSpritesLeft;
  310. } else if (path.equals("/gui/items.png")) {
  311. dst = 1;
  312. left = itemSpritesLeft; } else {
  313. return;
  314. }System.out.println("Overriding " + path + " with " + overlayPath + " @ " + index + ". " + left + " left.");
  315. logger.finer("addOverride(" + path + "," + overlayPath + "," + index + "). " + left + " left.");
  316. Map<String, Integer> overlays = overrides.get(Integer.valueOf(dst));
  317. if (overlays == null) {
  318. overlays = new HashMap<String, Integer>();
  319. overrides.put(Integer.valueOf(dst), overlays);
  320. }
  321. overlays.put(overlayPath, Integer.valueOf(index));
  322. }
  323. public static void AddRecipe(iw output, Object[] params)
  324. {
  325. hi.a().a(output, params);
  326. }
  327. public static void AddShapelessRecipe(iw output, Object[] params)
  328. {
  329. hi.a().b(output, params);
  330. }
  331. public static void AddSmelting(int input, iw output)
  332. {
  333. ew.a().a(input, output);
  334. }
  335. public static void AddSpawn(Class<? extends lo> entityClass, int weightedProb, lg spawnList)
  336. {
  337. AddSpawn(entityClass, weightedProb, spawnList, null);
  338. }
  339. public static void AddSpawn(Class<? extends lo> entityClass, int weightedProb, lg spawnList, jz[] biomes)
  340. {
  341. if (entityClass == null) {
  342. throw new IllegalArgumentException("entityClass cannot be null");
  343. }
  344. if (spawnList == null) {
  345. throw new IllegalArgumentException("spawnList cannot be null");
  346. }
  347. if (biomes == null) {
  348. biomes = standardBiomes;
  349. }
  350. for (int i = 0; i < biomes.length; i++)
  351. {
  352. List<bi> list = biomes[i].a(spawnList);
  353. if (list != null) {
  354. boolean exists = false;
  355. for (bi entry : list) {
  356. if (entry.a == entityClass) {
  357. entry.b = weightedProb;
  358. exists = true;
  359. break;
  360. }
  361. }
  362. if (!exists)
  363. list.add(new bi(entityClass, weightedProb));
  364. }
  365. }
  366. }
  367. public static void AddSpawn(String entityName, int weightedProb, lg spawnList)
  368. {
  369. AddSpawn(entityName, weightedProb, spawnList, null);
  370. }
  371. public static void AddSpawn(String entityName, int weightedProb, lg spawnList, jz[] biomes)
  372. {
  373. Class entityClass = classMap.get(entityName);
  374. if ((entityClass != null) && (lo.class.isAssignableFrom(entityClass)))
  375. AddSpawn(entityClass, weightedProb, spawnList, biomes);
  376. }
  377. public static boolean DispenseEntity(fb world, double x, double y, double z, int xVel, int zVel, iw item)
  378. {
  379. for (BaseMod mod : modList.values())
  380. if (mod.DispenseEntity(world, x, y, z, xVel, zVel, item))
  381. return true;
  382. return false;
  383. }
  384. public static List<BaseMod> getLoadedMods()
  385. {
  386. return Collections.unmodifiableList(new LinkedList<BaseMod>(modList.values()));
  387. }
  388. public static Logger getLogger()
  389. {
  390. return logger;
  391. }
  392. public static Minecraft getMinecraftInstance()
  393. {
  394. if (instance == null) {
  395. try {
  396. ThreadGroup group = Thread.currentThread().getThreadGroup();
  397. int count = group.activeCount();
  398. Thread[] threads = new Thread[count];
  399. group.enumerate(threads);
  400. for (Thread thread : threads)
  401. if (thread.getName().equals("Minecraft main thread")) {
  402. instance = (Minecraft)getPrivateValue(Thread.class, thread, "target");
  403. break;
  404. }
  405. }
  406. catch (SecurityException e) {
  407. logger.throwing("ModLoader", "getMinecraftInstance", e);
  408. throw new RuntimeException(e);
  409. } catch (NoSuchFieldException e) {
  410. logger.throwing("ModLoader", "getMinecraftInstance", e);
  411. throw new RuntimeException(e);
  412. }
  413. }
  414. return instance;
  415. }
  416. public static <T, E> T getPrivateValue(Class<? super E> instanceclass, E instance, int fieldindex)
  417. throws IllegalArgumentException, SecurityException, NoSuchFieldException
  418. {
  419. try
  420. {
  421. Field f = instanceclass.getDeclaredFields()[fieldindex];
  422. f.setAccessible(true);
  423. return (T)f.get(instance);
  424. } catch (IllegalAccessException e) {
  425. logger.throwing("ModLoader", "getPrivateValue", e);
  426. ThrowException("An impossible error has occured!", e);
  427. }
  428. return null;
  429. }
  430. public static <T, E> T getPrivateValue(Class<? super E> instanceclass, E instance, String field)
  431. throws IllegalArgumentException, SecurityException, NoSuchFieldException
  432. {
  433. try
  434. {
  435. Field f = instanceclass.getDeclaredField(field);
  436. f.setAccessible(true);
  437. return (T)f.get(instance);
  438. } catch (IllegalAccessException e) {
  439. logger.throwing("ModLoader", "getPrivateValue", e);
  440. ThrowException("An impossible error has occured!", e);
  441. }
  442. return null;
  443. }
  444. public static int getUniqueBlockModelID(BaseMod mod, boolean full3DItem)
  445. {
  446. int id = nextBlockModelID++;
  447. blockModels.put(Integer.valueOf(id), mod);
  448. blockSpecialInv.put(Integer.valueOf(id), Boolean.valueOf(full3DItem));
  449. return id;
  450. }
  451. public static int getUniqueEntityId()
  452. {
  453. return highestEntityId++;
  454. }
  455. private static int getUniqueItemSpriteIndex()
  456. {
  457. for (; itemSpriteIndex < usedItemSprites.length; itemSpriteIndex += 1)
  458. if (!usedItemSprites[itemSpriteIndex]) {
  459. usedItemSprites[itemSpriteIndex] = true;
  460. itemSpritesLeft -= 1;
  461. return itemSpriteIndex++;
  462. }
  463. Exception e = new Exception("No more empty item sprite indices left!");
  464. logger.throwing("ModLoader", "getUniqueItemSpriteIndex", e);
  465. ThrowException(e);
  466. return 0;
  467. }
  468. public static int getUniqueSpriteIndex(String path)
  469. {
  470. if (path.equals("/gui/items.png")) return getUniqueItemSpriteIndex();
  471. if (path.equals("/terrain.png"))
  472. return getUniqueTerrainSpriteIndex();
  473. Exception e = new Exception("No registry for this texture: " + path);
  474. logger.throwing("ModLoader", "getUniqueItemSpriteIndex", e);
  475. ThrowException(e);
  476. return 0;
  477. }
  478. private static int getUniqueTerrainSpriteIndex()
  479. {
  480. for (; terrainSpriteIndex < usedTerrainSprites.length; terrainSpriteIndex += 1)
  481. if (!usedTerrainSprites[terrainSpriteIndex]) {
  482. usedTerrainSprites[terrainSpriteIndex] = true;
  483. terrainSpritesLeft -= 1;
  484. return terrainSpriteIndex++;
  485. }
  486. Exception e = new Exception("No more empty terrain sprite indices left!");
  487. logger.throwing("ModLoader", "getUniqueItemSpriteIndex", e);
  488. ThrowException(e);
  489. return 0;
  490. }
  491. private static void init()
  492. {
  493. hasInit = true;
  494. String usedItemSpritesString =
  495. "1111111111111111111111111111111111111101111111011111111111111001111111111111111111111111111010111111100110000011111110000000001111111001100000110000000100000011000000010000001100000000000000110000000000000000000000000000000000000000000000001100000000000000";
  496. String usedTerrainSpritesString =
  497. "1111111111111111111111111111110111111111111111111111110111111111111111111111000111111011111111111111001111000000111111111111100011111111000010001111011110000000111111000000000011111100000000001111000000000111111000000000001101000000000001111111111111000011";
  498. for (int i = 0; i < 256; i++) {
  499. usedItemSprites[i] = usedItemSpritesString.charAt(i) == '1';
  500. if (!usedItemSprites[i])
  501. itemSpritesLeft += 1;
  502. usedTerrainSprites[i] = usedTerrainSpritesString.charAt(i) == '1';
  503. if (!usedTerrainSprites[i]) {
  504. terrainSpritesLeft += 1;
  505. }
  506. }
  507. try
  508. {
  509. instance = (Minecraft)getPrivateValue(Minecraft.class, null, 1);
  510. instance.t = new EntityRendererProxy(instance);
  511. classMap = (Map<String, Class<? extends si>>)getPrivateValue(iz.class, null, 0);
  512. field_modifiers = Field.class.getDeclaredField("modifiers");
  513. field_modifiers.setAccessible(true);
  514. field_blockList = gp.class.getDeclaredFields()[0];
  515. field_blockList.setAccessible(true);
  516. field_TileEntityRenderers = lh.class.getDeclaredFields()[0];
  517. field_TileEntityRenderers.setAccessible(true);
  518. field_armorList = dq.class.getDeclaredFields()[3];
  519. field_modifiers.setInt(field_armorList, field_armorList.getModifiers() & 0xFFFFFFEF);
  520. field_armorList.setAccessible(true);
  521. field_animList = jf.class.getDeclaredFields()[5];
  522. field_animList.setAccessible(true);
  523. Field[] fieldArray = jz.class.getDeclaredFields();
  524. List<jz> biomes = new LinkedList<jz>();
  525. for (int i = 0; i < fieldArray.length; i++) {
  526. Class fieldType = fieldArray[i].getType();
  527. if (((fieldArray[i].getModifiers() & 0x8) != 0) && (fieldType.isAssignableFrom(jz.class))) {
  528. jz biome = (jz)fieldArray[i].get(null);
  529. if ((biome instanceof s))
  530. continue;
  531. biomes.add(biome);
  532. }
  533. }
  534. standardBiomes = biomes.toArray(new jz[0]);
  535. try
  536. {
  537. method_RegisterTileEntity = os.class.getDeclaredMethod("a", new Class[] { Class.class, String.class });
  538. } catch (NoSuchMethodException e) {
  539. method_RegisterTileEntity = os.class.getDeclaredMethod("addMapping", new Class[] { Class.class, String.class });
  540. }
  541. method_RegisterTileEntity.setAccessible(true);
  542. try
  543. {
  544. method_RegisterEntityID = iz.class.getDeclaredMethod("a", new Class[] { Class.class, String.class, Integer.TYPE });
  545. } catch (NoSuchMethodException e) {
  546. method_RegisterEntityID = iz.class.getDeclaredMethod("addMapping", new Class[] { Class.class, String.class, Integer.TYPE });
  547. }
  548. method_RegisterEntityID.setAccessible(true);
  549. }
  550. catch (SecurityException e) {
  551. logger.throwing("ModLoader", "init", e);
  552. ThrowException(e);
  553. throw new RuntimeException(e);
  554. } catch (NoSuchFieldException e) {
  555. logger.throwing("ModLoader", "init", e);
  556. ThrowException(e);
  557. throw new RuntimeException(e);
  558. } catch (NoSuchMethodException e) {
  559. logger.throwing("ModLoader", "init", e);
  560. ThrowException(e);
  561. throw new RuntimeException(e);
  562. } catch (IllegalArgumentException e) {
  563. logger.throwing("ModLoader", "init", e);
  564. ThrowException(e);
  565. throw new RuntimeException(e);
  566. } catch (IllegalAccessException e) {
  567. logger.throwing("ModLoader", "init", e);
  568. ThrowException(e);
  569. throw new RuntimeException(e);
  570. }
  571. try
  572. {
  573. loadConfig();
  574. if (props.containsKey("loggingLevel"))
  575. cfgLoggingLevel = Level.parse(props.getProperty("loggingLevel"));
  576. if (props.containsKey("grassFix")) {
  577. ct.cfgGrassFix = Boolean.parseBoolean(props.getProperty("grassFix"));
  578. }
  579. logger.setLevel(cfgLoggingLevel);
  580. if (((logfile.exists()) || (logfile.createNewFile())) && (logfile.canWrite()) && (logHandler == null)) {
  581. logHandler = new FileHandler(logfile.getPath());
  582. logHandler.setFormatter(new SimpleFormatter());
  583. logger.addHandler(logHandler);
  584. }
  585. logger.fine("ModLoader Beta 1.6.6 Initializing...");
  586. System.out.println("ModLoader Beta 1.6.6 Initializing...");
  587. File source = new File(ModLoader.class.getProtectionDomain().getCodeSource().getLocation().toURI());
  588. modDir.mkdirs();
  589. readFromModFolder(modDir);
  590. readFromClassPath(source);
  591. System.out.println("Done.");
  592. props.setProperty("loggingLevel", cfgLoggingLevel.getName());
  593. props.setProperty("grassFix", Boolean.toString(ct.cfgGrassFix));
  594. for (BaseMod mod : modList.values()) {
  595. mod.ModsLoaded();
  596. if (!props.containsKey(mod.getClass().getName())) {
  597. props.setProperty(mod.getClass().getName(), "on");
  598. }
  599. }
  600. initStats();
  601. saveConfig();
  602. }
  603. catch (Throwable e) {
  604. logger.throwing("ModLoader", "init", e);
  605. ThrowException("ModLoader has failed to initialize.", e);
  606. if (logHandler != null)
  607. logHandler.close();
  608. throw new RuntimeException(e);
  609. }
  610. }
  611. private static void initStats() {
  612. for (int id = 0; id < un.m.length; id++) {
  613. if ((!ji.a.containsKey(Integer.valueOf(16777216 + id))) && (un.m[id] != null) && (un.m[id].l())) {
  614. String str = dm.a("stat.mineBlock", new Object[] { un.m[id].j() });
  615. ji.C[id] = new tr(16777216 + id, str, id).g();
  616. ji.e.add(ji.C[id]);
  617. }
  618. }
  619. for (int id = 0; id < gk.c.length; id++) {
  620. if ((!ji.a.containsKey(Integer.valueOf(16908288 + id))) && (gk.c[id] != null)) {
  621. String str = dm.a("stat.useItem", new Object[] { gk.c[id].k() });
  622. ji.E[id] = new tr(16908288 + id, str, id).g();
  623. if (id >= un.m.length) {
  624. ji.d.add(ji.E[id]);
  625. }
  626. }
  627. if ((!ji.a.containsKey(Integer.valueOf(16973824 + id))) && (gk.c[id] != null) && (gk.c[id].g())) {
  628. String str = dm.a("stat.breakItem", new Object[] { gk.c[id].k() });
  629. ji.F[id] = new tr(16973824 + id, str, id).g();
  630. }
  631. }
  632. HashSet<Integer> idHashSet = new HashSet<Integer>();
  633. for (Object result : hi.a().b())
  634. idHashSet.add(Integer.valueOf(((dr)result).b().c));
  635. for (Object result : ew.a().b().values())
  636. idHashSet.add(Integer.valueOf(((iw)result).c));
  637. for (int id : idHashSet) {
  638. if ((!ji.a.containsKey(Integer.valueOf(16842752 + id))) && (gk.c[id] != null)) {
  639. String str = dm.a("stat.craftItem", new Object[] { gk.c[id].k() });
  640. ji.D[id] = new tr(16842752 + id, str, id).g();
  641. }
  642. }
  643. }
  644. public static boolean isGUIOpen(Class<? extends cy> gui)
  645. {
  646. Minecraft game = getMinecraftInstance();
  647. if (gui == null) {
  648. return game.r == null;
  649. }
  650. if ((game.r == null) && (gui != null)) {
  651. return false;
  652. }
  653. return gui.isInstance(game.r);
  654. }
  655. public static boolean isModLoaded(String modname)
  656. {
  657. Class chk = null;
  658. try {
  659. chk = Class.forName(modname);
  660. } catch (ClassNotFoundException e) {
  661. return false;
  662. }
  663. if (chk != null) {
  664. for (BaseMod mod : modList.values()) {
  665. if (chk.isInstance(mod))
  666. return true;
  667. }
  668. }
  669. return false;
  670. }
  671. public static void loadConfig()
  672. throws IOException
  673. {
  674. cfgdir.mkdir();
  675. if ((!cfgfile.exists()) && (!cfgfile.createNewFile())) {
  676. return;
  677. }
  678. if (cfgfile.canRead()) {
  679. InputStream in = new FileInputStream(cfgfile);
  680. props.load(in);
  681. in.close();
  682. }
  683. }
  684. public static BufferedImage loadImage(jf texCache, String path)
  685. throws Exception
  686. {
  687. ih pack = (ih)getPrivateValue(jf.class, texCache, 11);
  688. InputStream input = pack.a.a(path);
  689. if (input == null)
  690. throw new Exception("Image not found: " + path);
  691. BufferedImage image = ImageIO.read(input);
  692. if (image == null)
  693. throw new Exception("Image not found: " + path);
  694. return image;
  695. }
  696. public static void OnTick(Minecraft game)
  697. {
  698. if (!hasInit) {
  699. init();
  700. logger.fine("Initialized");
  701. }
  702. if ((texPack == null) || (game.z.l != texPack)) {
  703. texturesAdded = false;
  704. texPack = game.z.l;
  705. }
  706. if ((!texturesAdded) && (game.p != null))
  707. {
  708. RegisterAllTextureOverrides(game.p);
  709. texturesAdded = true;
  710. }
  711. long newclock = 0L;
  712. if (game.f != null)
  713. {
  714. newclock = game.f.t();
  715. for (Map.Entry<BaseMod, Boolean> modSet : inGameHooks.entrySet()) {
  716. if ((clock == newclock) && (modSet.getValue().booleanValue()))
  717. continue;
  718. modSet.getKey().OnTickInGame(game);
  719. }
  720. }
  721. if (game.r != null) {
  722. for (Map.Entry<BaseMod, Boolean> modSet : inGUIHooks.entrySet()) {
  723. if (clock == newclock) if ((modSet.getValue().booleanValue() & game.f != null))
  724. continue;
  725. modSet.getKey().OnTickInGUI(game, game.r);
  726. }
  727. }
  728. if (clock != newclock) {
  729. for (Map.Entry<BaseMod, Map<px, boolean[]>> modSet : keyList.entrySet()) {
  730. for (Map.Entry<px, boolean[]> keySet : modSet.getValue().entrySet()) {
  731. boolean state = Keyboard.isKeyDown(keySet.getKey().b);
  732. boolean[] keyInfo = keySet.getValue();
  733. boolean oldState = keyInfo[1];
  734. keyInfo[1] = state;
  735. if ((!state) || ((oldState) && (!keyInfo[0])))
  736. continue;
  737. modSet.getKey().KeyboardEvent(keySet.getKey());
  738. }
  739. }
  740. }
  741. clock = newclock;
  742. }
  743. public static void OpenGUI(gq player, cy gui)
  744. {
  745. if (!hasInit) {
  746. init();
  747. logger.fine("Initialized");
  748. }
  749. Minecraft game = getMinecraftInstance();
  750. if (game.h != player)
  751. return;
  752. if (gui != null)
  753. game.a(gui);
  754. }
  755. public static void PopulateChunk(cj generator, int chunkX, int chunkZ, fb world)
  756. {
  757. if (!hasInit) {
  758. init();
  759. logger.fine("Initialized");
  760. }
  761. for (BaseMod mod : modList.values())
  762. {
  763. if (generator.c().equals("RandomLevelSource")) mod.GenerateSurface(world, world.r, chunkX, chunkZ);
  764. else if (generator.c().equals("HellRandomLevelSource"))
  765. mod.GenerateNether(world, world.r, chunkX, chunkZ);
  766. }
  767. }
  768. private static void readFromModFolder(File folder) throws IOException, IllegalArgumentException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException
  769. {
  770. if (!folder.isDirectory()) {
  771. throw new IllegalArgumentException("folder must be a Directory.");
  772. }
  773. logger.finer((new StringBuilder("Adding mods from ")).append(folder.getCanonicalPath()).toString());
  774. System.out.println((new StringBuilder("Adding mods from ")).append(folder.getCanonicalPath()).toString());
  775. readFromFileRecursive(folder, folder);
  776. }
  777. private static void readFromClassPath(File file) throws FileNotFoundException, IOException
  778. {
  779. logger.finer((new StringBuilder("Adding mods from ")).append(file.getCanonicalPath()).toString());
  780. System.out.println((new StringBuilder("Adding mods from ")).append(file.getCanonicalPath()).toString());
  781. readFromFileRecursive(file, file.isDirectory() ? file : file.getParentFile());
  782. }
  783. private static void readFromFileRecursive(File file, File folder) throws FileNotFoundException, IOException
  784. {
  785. if(file.isDirectory())
  786. for (File subfFile : file.listFiles())
  787. readFromFileRecursive(subfFile, folder);
  788. else if(file.isFile())
  789. {
  790. String fileName = file.getName();
  791. if (fileName.endsWith(".jar") || fileName.endsWith(".zip"))
  792. {
  793. logger.finer("Archive found : " + fileName);
  794. ZipInputStream zipinputstream = new ZipInputStream(new BufferedInputStream(new FileInputStream(file)));
  795. try
  796. {
  797. for (ZipEntry entry = zipinputstream.getNextEntry(); entry != null; entry = zipinputstream.getNextEntry())
  798. {
  799. String entryName = entry.getName();
  800. String className = entryName.substring(entryName.lastIndexOf('/') + 1, entryName.length());
  801. if(!entry.isDirectory() && className.startsWith("mod_") && className.endsWith(".class"))
  802. addMod(new URLClassLoader(new URL[] { folder.toURI().toURL() }), className, entryName.replace('/', '.'));
  803. }
  804. }
  805. finally
  806. {
  807. zipinputstream.close();
  808. }
  809. }
  810. else if(fileName.startsWith("mod_") && fileName.endsWith(".class"))
  811. addMod(new URLClassLoader(new URL[] { folder.toURI().toURL() }), fileName, file.getAbsolutePath().replace(folder.getAbsolutePath() + "\\", "").replace('\\', '.'));
  812. }
  813. }
  814. public static px[] RegisterAllKeys(px[] w)
  815. {
  816. List<px> existingKeyList = Arrays.asList(w);
  817. List<px> combinedList = new ArrayList<px>();
  818. combinedList.addAll(existingKeyList);
  819. for (Map<px, boolean[]> keyMap : keyList.values())
  820. combinedList.addAll(keyMap.keySet());
  821. return combinedList.toArray(new px[0]);
  822. }
  823. public static void RegisterAllTextureOverrides(jf texCache)
  824. {
  825. animList.clear();
  826. Minecraft game = getMinecraftInstance();
  827. for (BaseMod mod : modList.values()) {
  828. mod.RegisterAnimation(game);
  829. }
  830. for (av anim : animList)
  831. {
  832. texCache.a(anim);
  833. }
  834. for (Map.Entry<Integer, Map<String, Integer>> overlay : overrides.entrySet())
  835. for (Map.Entry<String, Integer> overlayEntry : overlay.getValue().entrySet()) {
  836. String overlayPath = overlayEntry.getKey();
  837. int index = overlayEntry.getValue().intValue();
  838. int dst = overlay.getKey().intValue();
  839. String dstPath = null;
  840. if (dst == 0) dstPath = "/terrain.png";
  841. else if (dst == 1) dstPath = "/gui/items.png"; else
  842. throw new ArrayIndexOutOfBoundsException(dst);
  843. try {
  844. BufferedImage im = loadImage(texCache, overlayPath);
  845. av anim = new ModTextureStatic(index, dst, im);
  846. texCache.a(anim);
  847. } catch (Exception e) {
  848. logger.throwing("ModLoader", "RegisterAllTextureOverrides", e);
  849. ThrowException(e);
  850. throw new RuntimeException(e);
  851. }
  852. }
  853. }
  854. public static void RegisterBlock(un block)
  855. {
  856. RegisterBlock(block, null);
  857. }
  858. public static void RegisterBlock(un block, Class<? extends ci> itemclass)
  859. {
  860. try
  861. {
  862. if (block == null) {
  863. throw new IllegalArgumentException("block parameter cannot be null.");
  864. }
  865. List<un> list = (List<un>)field_blockList.get(null);
  866. list.add(block);
  867. int id = block.bn;
  868. ci item = null;
  869. if (itemclass != null) item = itemclass.getConstructor(new Class[] { Integer.TYPE }).newInstance(new Object[] { Integer.valueOf(id - 256) }); else {
  870. item = new ci(id - 256);
  871. }
  872. if ((un.m[id] != null) && (gk.c[id] == null))
  873. gk.c[id] = item;
  874. } catch (IllegalArgumentException e) {
  875. logger.throwing("ModLoader", "RegisterBlock", e);
  876. ThrowException(e);
  877. } catch (IllegalAccessException e) {
  878. logger.throwing("ModLoader", "RegisterBlock", e);
  879. ThrowException(e);
  880. } catch (SecurityException e) {
  881. logger.throwing("ModLoader", "RegisterBlock", e);
  882. ThrowException(e);
  883. } catch (InstantiationException e) {
  884. logger.throwing("ModLoader", "RegisterBlock", e);
  885. ThrowException(e);
  886. } catch (InvocationTargetException e) {
  887. logger.throwing("ModLoader", "RegisterBlock", e);
  888. ThrowException(e);
  889. } catch (NoSuchMethodException e) {
  890. logger.throwing("ModLoader", "RegisterBlock", e);
  891. ThrowException(e);
  892. }
  893. }
  894. public static void RegisterEntityID(Class<? extends si> entityClass, String entityName, int id)
  895. {
  896. try
  897. {
  898. method_RegisterEntityID.invoke(null, new Object[] { entityClass, entityName, Integer.valueOf(id) });
  899. } catch (IllegalArgumentException e) {
  900. logger.throwing("ModLoader", "RegisterEntityID", e);
  901. ThrowException(e);
  902. } catch (IllegalAccessException e) {
  903. logger.throwing("ModLoader", "RegisterEntityID", e);
  904. ThrowException(e);
  905. } catch (InvocationTargetException e) {
  906. logger.throwing("ModLoader", "RegisterEntityID", e);
  907. ThrowException(e);
  908. }
  909. }
  910. public static void RegisterKey(BaseMod mod, px keyHandler, boolean allowRepeat)
  911. {
  912. Map<px, boolean[]> keyMap = keyList.get(mod);
  913. if (keyMap == null)
  914. keyMap = new HashMap<px, boolean[]>();
  915. keyMap.put(keyHandler, new boolean[] { allowRepeat });
  916. keyList.put(mod, keyMap);
  917. }
  918. public static void RegisterTileEntity(Class<? extends os> tileEntityClass, String id)
  919. {
  920. RegisterTileEntity(tileEntityClass, id, null);
  921. }
  922. public static void RegisterTileEntity(Class<? extends os> tileEntityClass, String id, jb renderer)
  923. {
  924. try
  925. {
  926. method_RegisterTileEntity.invoke(null, new Object[] { tileEntityClass, id });
  927. if (renderer != null) {
  928. lh ref = lh.a;
  929. Map<Class<? extends os>, jb> renderers = (Map<Class<? extends os>, jb>)field_TileEntityRenderers.get(ref);
  930. renderers.put(tileEntityClass, renderer);
  931. renderer.a(ref);
  932. }
  933. } catch (IllegalArgumentException e) {
  934. logger.throwing("ModLoader", "RegisterTileEntity", e);
  935. ThrowException(e);
  936. } catch (IllegalAccessException e) {
  937. logger.throwing("ModLoader", "RegisterTileEntity", e);
  938. ThrowException(e);
  939. } catch (InvocationTargetException e) {
  940. logger.throwing("ModLoader", "RegisterTileEntity", e);
  941. ThrowException(e);
  942. }
  943. }
  944. public static void RemoveSpawn(Class<? extends lo> entityClass, lg spawnList)
  945. {
  946. RemoveSpawn(entityClass, spawnList, null);
  947. }
  948. public static void RemoveSpawn(Class<? extends lo> entityClass, lg spawnList, jz[] biomes)
  949. {
  950. if (entityClass == null) {
  951. throw new IllegalArgumentException("entityClass cannot be null");
  952. }
  953. if (spawnList == null) {
  954. throw new IllegalArgumentException("spawnList cannot be null");
  955. }
  956. if (biomes == null) {
  957. biomes = standardBiomes;
  958. }
  959. for (int i = 0; i < biomes.length; i++) {
  960. List<bi> list = biomes[i].a(spawnList);
  961. if (list != null)
  962. for (bi entry : list)
  963. if (entry.a == entityClass) {
  964. list.remove(entry);
  965. break;
  966. }
  967. }
  968. }
  969. public static void RemoveSpawn(String entityName, lg spawnList)
  970. {
  971. RemoveSpawn(entityName, spawnList, null);
  972. }
  973. public static void RemoveSpawn(String entityName, lg spawnList, jz[] biomes)
  974. {
  975. Class entityClass = classMap.get(entityName);
  976. if ((entityClass != null) && (lo.class.isAssignableFrom(entityClass)))
  977. RemoveSpawn(entityClass, spawnList, biomes);
  978. }
  979. public static boolean RenderBlockIsItemFull3D(int modelID)
  980. {
  981. if (!blockSpecialInv.containsKey(Integer.valueOf(modelID)))
  982. return modelID == 11;
  983. return blockSpecialInv.get(Integer.valueOf(modelID)).booleanValue();
  984. }
  985. public static void RenderInvBlock(ct renderer, un block, int metadata, int modelID)
  986. {
  987. BaseMod mod = blockModels.get(Integer.valueOf(modelID));
  988. if (mod == null)
  989. return;
  990. mod.RenderInvBlock(renderer, block, metadata, modelID);
  991. }
  992. public static boolean RenderWorldBlock(ct renderer, xg world, int x, int y, int z, un block, int modelID)
  993. {
  994. BaseMod mod = blockModels.get(Integer.valueOf(modelID));
  995. if (mod == null)
  996. return false;
  997. return mod.RenderWorldBlock(renderer, world, x, y, z, block, modelID);
  998. }
  999. public static void saveConfig()
  1000. throws IOException
  1001. {
  1002. cfgdir.mkdir();
  1003. if ((!cfgfile.exists()) && (!cfgfile.createNewFile())) {
  1004. return;
  1005. }
  1006. if (cfgfile.canWrite()) {
  1007. OutputStream out = new FileOutputStream(cfgfile);
  1008. props.store(out, "ModLoader Config");
  1009. out.close();
  1010. }
  1011. }
  1012. public static void SetInGameHook(BaseMod mod, boolean enable, boolean useClock)
  1013. {
  1014. if (enable) inGameHooks.put(mod, Boolean.valueOf(useClock)); else
  1015. inGameHooks.remove(mod);
  1016. }
  1017. public static void SetInGUIHook(BaseMod mod, boolean enable, boolean useClock)
  1018. {
  1019. if (enable) inGUIHooks.put(mod, Boolean.valueOf(useClock)); else
  1020. inGUIHooks.remove(mod);
  1021. }
  1022. public static <T, E> void setPrivateValue(Class<? super T> instanceclass, T instance, int fieldindex, E value)
  1023. throws IllegalArgumentException, SecurityException, NoSuchFieldException
  1024. {
  1025. try
  1026. {
  1027. Field f = instanceclass.getDeclaredFields()[fieldindex];
  1028. f.setAccessible(true);
  1029. int modifiers = field_modifiers.getInt(f);
  1030. if ((modifiers & 0x10) != 0)
  1031. field_modifiers.setInt(f, modifiers & 0xFFFFFFEF);
  1032. f.set(instance, value);
  1033. } catch (IllegalAccessException e) {
  1034. logger.throwing("ModLoader", "setPrivateValue", e);
  1035. ThrowException("An impossible error has occured!", e);
  1036. }
  1037. }
  1038. public static <T, E> void setPrivateValue(Class<? super T> instanceclass, T instance, String field, E value)
  1039. throws IllegalArgumentException, SecurityException, NoSuchFieldException
  1040. {
  1041. try
  1042. {
  1043. Field f = instanceclass.getDeclaredField(field);
  1044. int modifiers = field_modifiers.getInt(f);
  1045. if ((modifiers & 0x10) != 0)
  1046. field_modifiers.setInt(f, modifiers & 0xFFFFFFEF);
  1047. f.setAccessible(true);
  1048. f.set(instance, value);
  1049. } catch (IllegalAccessException e) {
  1050. logger.throwing("ModLoader", "setPrivateValue", e);
  1051. ThrowException("An impossible error has occured!", e);
  1052. }
  1053. }
  1054. public static void TakenFromCrafting(gq player, iw item)
  1055. {
  1056. for (BaseMod mod : modList.values())
  1057. mod.TakenFromCrafting(player, item);
  1058. }
  1059. public static void TakenFromFurnace(gq player, iw item)
  1060. {
  1061. for (BaseMod mod : modList.values())
  1062. mod.TakenFromFurnace(player, item);
  1063. }
  1064. public static void OnItemPickup(gq player, iw item)
  1065. {
  1066. for (BaseMod mod : modList.values())
  1067. mod.OnItemPickup(player, item);
  1068. }
  1069. public static void ThrowException(String message, Throwable e)
  1070. {
  1071. Minecraft game = getMinecraftInstance();
  1072. if (game != null) game.a(new mc(message, e)); else
  1073. throw new RuntimeException(e);
  1074. }
  1075. private static void ThrowException(Throwable e)
  1076. {
  1077. ThrowException("Exception occured in ModLoader", e);
  1078. }
  1079. }